Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

surrealdb.js

Package Overview
Dependencies
Maintainers
1
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

surrealdb.js - npm Package Compare versions

Comparing version 0.8.4 to 0.9.0

11

esm/library/SurrealSocket.d.ts

@@ -11,6 +11,5 @@ import { type LiveQueryResponse, type RawSocketLiveQueryNotification, type Result, WebsocketStatus } from "../types.js";

private unprocessedLiveResponses;
ready: Promise<void>;
private resolveReady;
closed: Promise<void>;
private resolveClosed;
ready?: Promise<void>;
closed?: Promise<void>;
private resolveClosed?;
socketClosureReason: Record<number, string>;

@@ -22,3 +21,3 @@ constructor({ url, onOpen, onClose, }: {

});
open(): void;
open(): Promise<void>;
send(method: string, params: unknown[], callback: (data: Result) => unknown): Promise<void>;

@@ -30,5 +29,3 @@ listenLive(queryUuid: string, callback: (data: LiveQueryResponse) => unknown): Promise<void>;

get connectionStatus(): WebsocketStatus;
private resetReady;
private resetClosed;
static isLiveNotification(message: Record<string, unknown>): message is RawSocketLiveQueryNotification;
}

@@ -61,8 +61,2 @@ import { WebsocketStatus, } from "../types.js";

});
Object.defineProperty(this, "resolveReady", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "closed", {

@@ -88,6 +82,2 @@ enumerable: true,

});
this.resolveReady = () => { }; // Purely for typescript typing :)
this.ready = new Promise((r) => (this.resolveReady = r));
this.resolveClosed = () => { }; // Purely for typescript typing :)
this.closed = new Promise((r) => (this.resolveClosed = r));
this.onOpen = onOpen;

@@ -103,13 +93,26 @@ this.onClose = onClose;

this.close(1000);
this.resetReady();
// Connect to Surreal instance
this.ws = new WebSocket(this.url);
this.ws.addEventListener("open", (_e) => {
this.status = WebsocketStatus.OPEN;
this.resolveReady();
this.onOpen?.();
let resolved = false;
const ws = new WebSocket(this.url);
this.ready = new Promise((resolve, reject) => {
ws.addEventListener("open", (_e) => {
this.status = WebsocketStatus.OPEN;
if (!resolved) {
resolved = true;
resolve();
}
this.onOpen?.();
});
ws.addEventListener("error", (e) => {
if (e instanceof ErrorEvent) {
this.status = WebsocketStatus.CLOSED;
if (!resolved) {
resolved = true;
reject(e.error);
}
}
});
});
this.ws.addEventListener("close", (_e) => {
this.resolveClosed();
this.resetClosed();
ws.addEventListener("close", (_e) => {
this.resolveClosed?.();
Object.values(this.liveQueue).map((query) => {

@@ -133,3 +136,3 @@ query.map((cb) => cb({

});
this.ws.addEventListener("message", (e) => {
ws.addEventListener("message", (e) => {
const res = JSON.parse(e.data.toString());

@@ -144,2 +147,4 @@ if (SurrealSocket.isLiveNotification(res)) {

});
this.ws = ws;
return this.ready;
}

@@ -192,2 +197,3 @@ // Extracting the pure object to prevent any getters/setters that could break stuff

this.status = WebsocketStatus.CLOSED;
this.closed = new Promise((r) => this.resolveClosed = r);
this.ws?.close(reason, this.socketClosureReason[reason]);

@@ -200,8 +206,2 @@ this.onClose?.();

}
resetReady() {
this.ready = new Promise((r) => (this.resolveReady = r));
}
resetClosed() {
this.closed = new Promise((r) => (this.resetClosed = r));
}
static isLiveNotification(message) {

@@ -208,0 +208,0 @@ return !!(!("id" in message) &&

@@ -59,3 +59,3 @@ import { SurrealHTTP } from "../library/SurrealHTTP.js";

*/
authenticate(token: Token): void;
authenticate(token: Token): boolean;
/**

@@ -62,0 +62,0 @@ * Invalidates the authentication for the current connection.

@@ -144,2 +144,3 @@ import { NoConnectionDetails } from "../errors.js";

this.http?.setTokenAuth(token);
return true;
}

@@ -146,0 +147,0 @@ /**

@@ -7,4 +7,5 @@ import { SurrealSocket } from "../library/SurrealSocket.js";

private connection;
ready: Promise<void>;
private resolveReady;
ready?: Promise<void>;
private resolveReady?;
private rejectReady?;
strategy: "ws" | "http";

@@ -15,9 +16,4 @@ /**

*/
constructor(url?: string, options?: ConnectionOptions);
connect(url: string, { prepare, auth, ns, db }?: ConnectionOptions): Promise<void>;
/**
* Establish a socket connection to the database
* @param connection - Connection details
*/
connect(url: string, { prepare, auth, ns, db }?: ConnectionOptions): void;
/**
* Disconnect the socket to the database

@@ -72,3 +68,3 @@ */

*/
authenticate(token: Token): Promise<void>;
authenticate(token: Token): Promise<boolean>;
/**

@@ -171,6 +167,2 @@ * Invalidates the authentication for the current connection.

private outputHandler;
/**
* Reset the ready mechanism.
*/
private resetReady;
}

@@ -6,7 +6,3 @@ import { NoActiveSocket, UnexpectedResponse } from "../errors.js";

export class WebSocketStrategy {
/**
* Establish a socket connection to the database
* @param connection - Connection details
*/
constructor(url, options = {}) {
constructor() {
Object.defineProperty(this, "socket", {

@@ -42,2 +38,8 @@ enumerable: true,

});
Object.defineProperty(this, "rejectReady", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "strategy", {

@@ -49,6 +51,2 @@ enumerable: true,

});
this.resolveReady = () => { }; // Purely for typescript typing :)
this.ready = new Promise((r) => (this.resolveReady = r));
if (url)
this.connect(url, options);
}

@@ -59,3 +57,7 @@ /**

*/
connect(url, { prepare, auth, ns, db } = {}) {
async connect(url, { prepare, auth, ns, db } = {}) {
this.ready = new Promise((resolve, reject) => {
this.resolveReady = resolve;
this.rejectReady = reject;
});
this.connection = {

@@ -82,10 +84,10 @@ auth,

await prepare?.(this);
this.resolveReady();
this.resolveReady?.();
},
onClose: () => {
this.pinger?.stop();
this.resetReady();
},
});
this.socket.open();
await this.socket.open().catch(this.rejectReady);
return this.ready;
}

@@ -200,2 +202,3 @@ /**

this.connection.auth = token;
return !!token;
}

@@ -393,9 +396,3 @@ /**

}
/**
* Reset the ready mechanism.
*/
resetReady() {
this.ready = new Promise((r) => (this.resolveReady = r));
}
}
//# sourceMappingURL=websocket.js.map
export type ConnectionStrategy = "websocket" | "experimental_http";
export interface Connection {
constructor: Constructor<(url?: string, options?: ConnectionOptions) => void>;
constructor: Constructor<() => void>;
strategy: "ws" | "http";

@@ -14,3 +14,3 @@ connect: (url: string, options?: ConnectionOptions) => void;

signin: (vars: AnyAuth) => Promise<Token | void>;
authenticate: (token: Token) => MaybePromise<void>;
authenticate: (token: Token) => MaybePromise<boolean>;
invalidate: () => MaybePromise<void>;

@@ -17,0 +17,0 @@ let?: (variable: string, value: unknown) => Promise<void>;

@@ -5,3 +5,3 @@ {

"name": "surrealdb.js",
"version": "0.8.4",
"version": "0.9.0",
"description": "Javascript driver for SurrealDB",

@@ -8,0 +8,0 @@ "license": "Apache 2.0",

@@ -74,5 +74,8 @@ # surrealdb.js

```ts
const db = new Surreal("http://127.0.0.1:8000/rpc");
const db = new Surreal();
try {
// Connect to the database
await db.connect("http://127.0.0.1:8000/rpc");
// Signin as a namespace, database, or root user

@@ -79,0 +82,0 @@ await db.signin({

@@ -11,6 +11,5 @@ import { type LiveQueryResponse, type RawSocketLiveQueryNotification, type Result, WebsocketStatus } from "../types.js";

private unprocessedLiveResponses;
ready: Promise<void>;
private resolveReady;
closed: Promise<void>;
private resolveClosed;
ready?: Promise<void>;
closed?: Promise<void>;
private resolveClosed?;
socketClosureReason: Record<number, string>;

@@ -22,3 +21,3 @@ constructor({ url, onOpen, onClose, }: {

});
open(): void;
open(): Promise<void>;
send(method: string, params: unknown[], callback: (data: Result) => unknown): Promise<void>;

@@ -30,5 +29,3 @@ listenLive(queryUuid: string, callback: (data: LiveQueryResponse) => unknown): Promise<void>;

get connectionStatus(): WebsocketStatus;
private resetReady;
private resetClosed;
static isLiveNotification(message: Record<string, unknown>): message is RawSocketLiveQueryNotification;
}

@@ -67,8 +67,2 @@ "use strict";

});
Object.defineProperty(this, "resolveReady", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "closed", {

@@ -94,6 +88,2 @@ enumerable: true,

});
this.resolveReady = () => { }; // Purely for typescript typing :)
this.ready = new Promise((r) => (this.resolveReady = r));
this.resolveClosed = () => { }; // Purely for typescript typing :)
this.closed = new Promise((r) => (this.resolveClosed = r));
this.onOpen = onOpen;

@@ -109,13 +99,26 @@ this.onClose = onClose;

this.close(1000);
this.resetReady();
// Connect to Surreal instance
this.ws = new node_js_1.default(this.url);
this.ws.addEventListener("open", (_e) => {
this.status = types_js_1.WebsocketStatus.OPEN;
this.resolveReady();
this.onOpen?.();
let resolved = false;
const ws = new node_js_1.default(this.url);
this.ready = new Promise((resolve, reject) => {
ws.addEventListener("open", (_e) => {
this.status = types_js_1.WebsocketStatus.OPEN;
if (!resolved) {
resolved = true;
resolve();
}
this.onOpen?.();
});
ws.addEventListener("error", (e) => {
if (e instanceof ErrorEvent) {
this.status = types_js_1.WebsocketStatus.CLOSED;
if (!resolved) {
resolved = true;
reject(e.error);
}
}
});
});
this.ws.addEventListener("close", (_e) => {
this.resolveClosed();
this.resetClosed();
ws.addEventListener("close", (_e) => {
this.resolveClosed?.();
Object.values(this.liveQueue).map((query) => {

@@ -139,3 +142,3 @@ query.map((cb) => cb({

});
this.ws.addEventListener("message", (e) => {
ws.addEventListener("message", (e) => {
const res = JSON.parse(e.data.toString());

@@ -150,2 +153,4 @@ if (SurrealSocket.isLiveNotification(res)) {

});
this.ws = ws;
return this.ready;
}

@@ -198,2 +203,3 @@ // Extracting the pure object to prevent any getters/setters that could break stuff

this.status = types_js_1.WebsocketStatus.CLOSED;
this.closed = new Promise((r) => this.resolveClosed = r);
this.ws?.close(reason, this.socketClosureReason[reason]);

@@ -206,8 +212,2 @@ this.onClose?.();

}
resetReady() {
this.ready = new Promise((r) => (this.resolveReady = r));
}
resetClosed() {
this.closed = new Promise((r) => (this.resetClosed = r));
}
static isLiveNotification(message) {

@@ -214,0 +214,0 @@ return !!(!("id" in message) &&

@@ -59,3 +59,3 @@ import { SurrealHTTP } from "../library/SurrealHTTP.js";

*/
authenticate(token: Token): void;
authenticate(token: Token): boolean;
/**

@@ -62,0 +62,0 @@ * Invalidates the authentication for the current connection.

@@ -147,2 +147,3 @@ "use strict";

this.http?.setTokenAuth(token);
return true;
}

@@ -149,0 +150,0 @@ /**

@@ -7,4 +7,5 @@ import { SurrealSocket } from "../library/SurrealSocket.js";

private connection;
ready: Promise<void>;
private resolveReady;
ready?: Promise<void>;
private resolveReady?;
private rejectReady?;
strategy: "ws" | "http";

@@ -15,9 +16,4 @@ /**

*/
constructor(url?: string, options?: ConnectionOptions);
connect(url: string, { prepare, auth, ns, db }?: ConnectionOptions): Promise<void>;
/**
* Establish a socket connection to the database
* @param connection - Connection details
*/
connect(url: string, { prepare, auth, ns, db }?: ConnectionOptions): void;
/**
* Disconnect the socket to the database

@@ -72,3 +68,3 @@ */

*/
authenticate(token: Token): Promise<void>;
authenticate(token: Token): Promise<boolean>;
/**

@@ -171,6 +167,2 @@ * Invalidates the authentication for the current connection.

private outputHandler;
/**
* Reset the ready mechanism.
*/
private resetReady;
}

@@ -9,7 +9,3 @@ "use strict";

class WebSocketStrategy {
/**
* Establish a socket connection to the database
* @param connection - Connection details
*/
constructor(url, options = {}) {
constructor() {
Object.defineProperty(this, "socket", {

@@ -45,2 +41,8 @@ enumerable: true,

});
Object.defineProperty(this, "rejectReady", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "strategy", {

@@ -52,6 +54,2 @@ enumerable: true,

});
this.resolveReady = () => { }; // Purely for typescript typing :)
this.ready = new Promise((r) => (this.resolveReady = r));
if (url)
this.connect(url, options);
}

@@ -62,3 +60,7 @@ /**

*/
connect(url, { prepare, auth, ns, db } = {}) {
async connect(url, { prepare, auth, ns, db } = {}) {
this.ready = new Promise((resolve, reject) => {
this.resolveReady = resolve;
this.rejectReady = reject;
});
this.connection = {

@@ -85,10 +87,10 @@ auth,

await prepare?.(this);
this.resolveReady();
this.resolveReady?.();
},
onClose: () => {
this.pinger?.stop();
this.resetReady();
},
});
this.socket.open();
await this.socket.open().catch(this.rejectReady);
return this.ready;
}

@@ -203,2 +205,3 @@ /**

this.connection.auth = token;
return !!token;
}

@@ -396,10 +399,4 @@ /**

}
/**
* Reset the ready mechanism.
*/
resetReady() {
this.ready = new Promise((r) => (this.resolveReady = r));
}
}
exports.WebSocketStrategy = WebSocketStrategy;
//# sourceMappingURL=websocket.js.map
export type ConnectionStrategy = "websocket" | "experimental_http";
export interface Connection {
constructor: Constructor<(url?: string, options?: ConnectionOptions) => void>;
constructor: Constructor<() => void>;
strategy: "ws" | "http";

@@ -14,3 +14,3 @@ connect: (url: string, options?: ConnectionOptions) => void;

signin: (vars: AnyAuth) => Promise<Token | void>;
authenticate: (token: Token) => MaybePromise<void>;
authenticate: (token: Token) => MaybePromise<boolean>;
invalidate: () => MaybePromise<void>;

@@ -17,0 +17,0 @@ let?: (variable: string, value: unknown) => Promise<void>;

@@ -27,8 +27,6 @@ import {

public ready: Promise<void>;
private resolveReady: () => void;
public ready?: Promise<void>;
public closed?: Promise<void>;
private resolveClosed?: () => void;
public closed: Promise<void>;
private resolveClosed: () => void;
public socketClosureReason: Record<number, string> = {

@@ -47,6 +45,2 @@ 1000: "CLOSE_NORMAL",

}) {
this.resolveReady = () => {}; // Purely for typescript typing :)
this.ready = new Promise((r) => (this.resolveReady = r));
this.resolveClosed = () => {}; // Purely for typescript typing :)
this.closed = new Promise((r) => (this.resolveClosed = r));
this.onOpen = onOpen;

@@ -63,15 +57,30 @@ this.onClose = onClose;

this.close(1000);
this.resetReady();
// Connect to Surreal instance
this.ws = new WebSocket(this.url);
this.ws.addEventListener("open", (_e) => {
this.status = WebsocketStatus.OPEN;
this.resolveReady();
this.onOpen?.();
let resolved = false;
const ws = new WebSocket(this.url);
this.ready = new Promise((resolve, reject) => {
ws.addEventListener("open", (_e) => {
this.status = WebsocketStatus.OPEN;
if (!resolved) {
resolved = true;
resolve();
}
this.onOpen?.();
});
ws.addEventListener("error", (e) => {
if (e instanceof ErrorEvent) {
this.status = WebsocketStatus.CLOSED;
if (!resolved) {
resolved = true;
reject(e.error);
}
}
});
});
this.ws.addEventListener("close", (_e) => {
this.resolveClosed();
this.resetClosed();
ws.addEventListener("close", (_e) => {
this.resolveClosed?.();

@@ -103,3 +112,3 @@ Object.values(this.liveQueue).map((query) => {

this.ws.addEventListener("message", (e) => {
ws.addEventListener("message", (e) => {
const res = JSON.parse(

@@ -115,2 +124,5 @@ e.data.toString(),

});
this.ws = ws;
return this.ready;
}

@@ -186,2 +198,3 @@

this.status = WebsocketStatus.CLOSED;
this.closed = new Promise((r) => this.resolveClosed = r);
this.ws?.close(reason, this.socketClosureReason[reason]);

@@ -196,10 +209,2 @@ this.onClose?.();

private resetReady() {
this.ready = new Promise((r) => (this.resolveReady = r));
}
private resetClosed() {
this.closed = new Promise((r) => (this.resetClosed = r));
}
public static isLiveNotification(

@@ -206,0 +211,0 @@ message: Record<string, unknown>,

@@ -155,2 +155,3 @@ import { NoConnectionDetails } from "../errors.js";

this.http?.setTokenAuth(token);
return true;
}

@@ -157,0 +158,0 @@

@@ -28,4 +28,5 @@ import { NoActiveSocket, UnexpectedResponse } from "../errors.js";

public ready: Promise<void>;
private resolveReady: () => void;
public ready?: Promise<void>;
private resolveReady?: () => void;
private rejectReady?: (e: Error) => void;

@@ -38,13 +39,11 @@ public strategy: "ws" | "http" = "ws";

*/
constructor(url?: string, options: ConnectionOptions = {}) {
this.resolveReady = () => {}; // Purely for typescript typing :)
this.ready = new Promise((r) => (this.resolveReady = r));
if (url) this.connect(url, options);
}
async connect(
url: string,
{ prepare, auth, ns, db }: ConnectionOptions = {},
) {
this.ready = new Promise((resolve, reject) => {
this.resolveReady = resolve;
this.rejectReady = reject;
});
/**
* Establish a socket connection to the database
* @param connection - Connection details
*/
connect(url: string, { prepare, auth, ns, db }: ConnectionOptions = {}) {
this.connection = {

@@ -72,11 +71,11 @@ auth,

await prepare?.(this);
this.resolveReady();
this.resolveReady?.();
},
onClose: () => {
this.pinger?.stop();
this.resetReady();
},
});
this.socket.open();
await this.socket.open().catch(this.rejectReady);
return this.ready;
}

@@ -194,2 +193,3 @@

this.connection.auth = token;
return !!token;
}

@@ -421,9 +421,2 @@

}
/**
* Reset the ready mechanism.
*/
private resetReady() {
this.ready = new Promise((r) => (this.resolveReady = r));
}
}
export type ConnectionStrategy = "websocket" | "experimental_http";
export interface Connection {
constructor: Constructor<
(url?: string, options?: ConnectionOptions) => void
>;
constructor: Constructor<() => void>;

@@ -18,3 +16,3 @@ strategy: "ws" | "http";

signin: (vars: AnyAuth) => Promise<Token | void>;
authenticate: (token: Token) => MaybePromise<void>;
authenticate: (token: Token) => MaybePromise<boolean>;
invalidate: () => MaybePromise<void>;

@@ -21,0 +19,0 @@

@@ -1,2 +0,2 @@

var a=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"NoActiveSocket"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"No socket is currently connected to a SurrealDB instance. Please call the .connect() method first!"})}},o=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"NoConnectionDetails"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"No connection details for the HTTP api have been provided. Please call the .connect() method first!"})}},d=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnexpectedResponse"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"The returned response from the SurrealDB instance is in an unexpected format. Unable to process response!"})}},l=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidURLProvided"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"The provided string is either not a URL or is a URL but with an invalid protocol!"})}};var w=class{constructor(e=3e4){Object.defineProperty(this,"pinger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.interval=e}start(e){this.pinger=setInterval(e,this.interval)}stop(){clearInterval(this.pinger)}};var u;(function(i){i[i.OPEN=0]="OPEN",i[i.CLOSED=1]="CLOSED",i[i.RECONNECTING=2]="RECONNECTING"})(u||(u={}));var m=typeof WebSocket<"u"?WebSocket:null;var g=0;function O(){return(g=(g+1)%Number.MAX_SAFE_INTEGER).toString()}function p(i,e){let{protocol:t,host:r}=E(i);if(!Object.entries(e).flat().map(n=>n.toLowerCase()).includes(t))throw new l;return R(t,r,e)}function E(i){let e=/^([^/:]+):\/\/([^/]+)/,t=i.match(e);if(!t)throw new l;let[r,s]=[...t].slice(1,3).map(n=>n.toLowerCase());return{protocol:r,host:s}}function R(i,e,t){return i=i in t?t[i]:i,`${i}://${e}`}var h=class{constructor({url:e,onOpen:t,onClose:r}){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onOpen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onClose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:u.CLOSED}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"liveQueue",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"unprocessedLiveResponses",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"ready",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveClosed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"socketClosureReason",{enumerable:!0,configurable:!0,writable:!0,value:{1e3:"CLOSE_NORMAL"}}),this.resolveReady=()=>{},this.ready=new Promise(s=>this.resolveReady=s),this.resolveClosed=()=>{},this.closed=new Promise(s=>this.resolveClosed=s),this.onOpen=t,this.onClose=r,this.url=p(e,{http:"ws",https:"wss"})+"/rpc"}open(){this.close(1e3),this.resetReady(),this.ws=new m(this.url),this.ws.addEventListener("open",e=>{this.status=u.OPEN,this.resolveReady(),this.onOpen?.()}),this.ws.addEventListener("close",e=>{this.resolveClosed(),this.resetClosed(),Object.values(this.liveQueue).map(t=>{t.map(r=>r({action:"CLOSE",detail:"SOCKET_CLOSED"}))}),this.queue={},this.liveQueue={},this.unprocessedLiveResponses={},this.status!==u.CLOSED&&(this.status=u.RECONNECTING,setTimeout(()=>{this.open()},2500),this.onClose?.())}),this.ws.addEventListener("message",e=>{let t=JSON.parse(e.data.toString());h.isLiveNotification(t)?this.handleLiveBatch(t.result):t.id&&t.id in this.queue&&(this.queue[t.id](t),delete this.queue[t.id])})}async send(e,t,r){await this.ready;let s=O();this.queue[s]=r,this.ws?.send(JSON.stringify({id:s,method:e,params:t}))}async listenLive(e,t){e in this.liveQueue||(this.liveQueue[e]=[]),this.liveQueue[e].push(t),await Promise.all(this.unprocessedLiveResponses[e]?.map(t)??[]),delete this.unprocessedLiveResponses[e]}async kill(e){e in this.liveQueue&&(this.liveQueue[e].forEach(t=>t({action:"CLOSE",detail:"QUERY_KILLED"})),delete this.liveQueue[e]),await new Promise(t=>{this.send("kill",[e],r=>{e in this.unprocessedLiveResponses&&delete this.unprocessedLiveResponses[e],t()})})}async handleLiveBatch({id:e,...t}){this.liveQueue[e]?await Promise.all(this.liveQueue[e].map(async r=>await r(t))):(e in this.unprocessedLiveResponses||(this.unprocessedLiveResponses[e]=[]),this.unprocessedLiveResponses[e].push(t))}async close(e){this.status=u.CLOSED,this.ws?.close(e,this.socketClosureReason[e]),this.onClose?.(),await this.closed}get connectionStatus(){return this.status}resetReady(){this.ready=new Promise(e=>this.resolveReady=e)}resetClosed(){this.closed=new Promise(e=>this.resetClosed=e)}static isLiveNotification(e){return!("id"in e)&&"result"in e&&typeof e.result=="object"&&e.result!==null&&"action"in e.result&&"id"in e.result&&"result"in e.result}};function y(i){return i==null}function c(i,e){if("SC"in i){if(i.NS||(i.NS=e?.namespace),i.DB||(i.DB=e?.database),y(i.NS))throw new Error("No namespace was specified!");if(y(i.DB))throw new Error("No database was specified!")}return i}var f=class{constructor(e,t={}){Object.defineProperty(this,"socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pinger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connection",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"ready",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"strategy",{enumerable:!0,configurable:!0,writable:!0,value:"ws"}),this.resolveReady=()=>{},this.ready=new Promise(r=>this.resolveReady=r),e&&this.connect(e,t)}connect(e,{prepare:t,auth:r,ns:s,db:n}={}){this.connection={auth:r,ns:s,db:n},this.socket?.close(1e3),this.pinger=new w(3e4),this.socket=new h({url:e,onOpen:async()=>{this.pinger?.start(()=>this.ping()),this.connection.ns&&this.connection.db&&await this.use({}),typeof this.connection.auth=="string"?await this.authenticate(this.connection.auth):this.connection.auth&&await this.signin(this.connection.auth),await t?.(this),this.resolveReady()},onClose:()=>{this.pinger?.stop(),this.resetReady()}}),this.socket.open()}async close(){await this.socket?.close(1e3),this.socket=void 0}async wait(){if(!this.socket)throw new a;await this.ready}get status(){if(!this.socket)throw new a;return this.socket.connectionStatus}async ping(){let{error:e}=await this.send("ping");if(e)throw new Error(e.message)}async use({ns:e,db:t}){if(!e&&!this.connection.ns)throw new Error("Please specify a namespace to use.");if(!t&&!this.connection.db)throw new Error("Please specify a database to use.");this.connection.ns=e??this.connection.ns,this.connection.db=t??this.connection.db;let{error:r}=await this.send("use",[this.connection.ns,this.connection.db]);if(r)throw new Error(r.message)}async info(){await this.ready;let e=await this.send("info");if(e.error)throw new Error(e.error.message);return e.result??void 0}async signup(e){e=c(e,{namespace:this.connection.ns,database:this.connection.db});let t=await this.send("signup",[e]);if(t.error)throw new Error(t.error.message);return this.connection.auth=t.result,t.result}async signin(e){e=c(e,{namespace:this.connection.ns,database:this.connection.db});let t=await this.send("signin",[e]);if(t.error)throw new Error(t.error.message);return this.connection.auth=t.result??e,t.result}async authenticate(e){let t=await this.send("authenticate",[e]);if(t.error)throw new Error(t.error.message);this.connection.auth=e}async invalidate(){let e=await this.send("invalidate");if(e.error)throw new Error(e.error.message);this.connection.auth=void 0}async let(e,t){let r=await this.send("let",[e,t]);if(r.error)throw new Error(r.error.message)}async unset(e){let t=await this.send("unset",[e]);if(t.error)throw new Error(t.error.message)}async live(e,t,r){await this.ready;let s=await this.send("live",[e,r]);if(s.error)throw new Error(s.error.message);return t&&this.listenLive(s.result,t),s.result}async listenLive(e,t){if(await this.ready,!this.socket)throw new a;this.socket.listenLive(e,t)}async kill(e){if(await this.ready,!this.socket)throw new a;await this.socket.kill(e)}async query(e,t){await this.ready;let r=await this.send("query",[e,t]);if(r.error)throw new Error(r.error.message);return r.result}async select(e){await this.ready;let t=await this.send("select",[e]);return this.outputHandler(t)}async create(e,t){await this.ready;let r=await this.send("create",[e,t]);return this.outputHandler(r)}async insert(e,t){await this.ready;let r=await this.send("insert",[e,t]);return this.outputHandler(r)}async update(e,t){await this.ready;let r=await this.send("update",[e,t]);return this.outputHandler(r)}async merge(e,t){await this.ready;let r=await this.send("merge",[e,t]);return this.outputHandler(r)}async patch(e,t){await this.ready;let r=await this.send("patch",[e,t]);return this.outputHandler(r)}async delete(e){await this.ready;let t=await this.send("delete",[e]);return this.outputHandler(t)}send(e,t){return new Promise(r=>{if(!this.socket)throw new a;this.socket.send(e,t??[],s=>r(s))})}outputHandler(e){if(e.error)throw new Error(e.error.message);if(Array.isArray(e.result))return e.result;if("id"in(e.result??{}))return[e.result];if(e.result===null)return[];throw console.debug({res:e}),new d}resetReady(){this.ready=new Promise(e=>this.resolveReady=e)}};var b=class{constructor(e,{fetcher:t}={}){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"authorization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_namespace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_database",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.fetch=t??fetch,this.url=p(e,{ws:"http",wss:"https"})}ready(){return!!(this.url&&this._namespace&&this._database)}setTokenAuth(e){this.authorization=`Bearer ${e}`}createRootAuth(e,t){this.authorization=`Basic ${btoa(`${e}:${t}`)}`}clearAuth(){this.authorization=void 0}use({ns:e,db:t}){e&&(this._namespace=e),t&&(this._database=t)}get namespace(){return this._namespace}get database(){return this._database}async request(e,t){if(e=e.startsWith("/")?e.slice(1):e,!this.ready())throw new o;return(await this.fetch(`${this.url}/${e}${t?.searchParams?`?${t?.searchParams}`:""}`,{method:t?.method??"POST",headers:{"Content-Type":t?.plainBody?"text/plain":"application/json",Accept:"application/json",NS:this._namespace,DB:this._database,...this.authorization?{Authorization:this.authorization}:{}},body:typeof t?.body=="string"?t?.body:JSON.stringify(t?.body)})).json()}};var v=class{constructor(e,t={}){Object.defineProperty(this,"http",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ready",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"strategy",{enumerable:!0,configurable:!0,writable:!0,value:"http"}),this.resolveReady=()=>{},this.ready=new Promise(r=>this.resolveReady=r),e&&this.connect(e,t)}async connect(e,{fetch:t,prepare:r,auth:s,ns:n,db:P}={}){this.http=new b(e,{fetcher:t}),await this.use({ns:n,db:P}),typeof s=="string"?await this.authenticate(s):s&&await this.signin(s),await r?.(this),this.resolveReady(),await this.ready}close(){this.http=void 0,this.resetReady()}wait(){if(!this.http)throw new o;return this.ready}get status(){return this.request("/status")}async ping(){await this.request("/health")}use({ns:e,db:t}){if(!this.http)throw new o;return this.http.use({ns:e,db:t})}async signup(e){e=c(e,{namespace:this.http?.namespace,database:this.http?.database});let t=await this.request("/signup",{method:"POST",body:e});if(t.description)throw new Error(t.description);if(!t.token)throw new Error("Did not receive authentication token");return this.http?.setTokenAuth(t.token),t.token}async signin(e){e=c(e,{namespace:this.http?.namespace,database:this.http?.database});let t=await this.request("/signin",{method:"POST",body:e});if(t.description)throw new Error(t.description);if(!t.token)this.http?.createRootAuth(e.user,e.pass);else return this.http?.setTokenAuth(t.token),t.token}authenticate(e){this.http?.setTokenAuth(e)}invalidate(){this.http?.clearAuth()}async query(e,t){await this.ready;let r=await this.request("/sql",{body:e,plainBody:!0,method:"POST",searchParams:t&&new URLSearchParams(Object.fromEntries(Object.entries(t).map(([s,n])=>[s,typeof n=="object"?JSON.stringify(n):`${n}`])))});if("information"in r)throw new Error(r.information);return r}async select(e){await this.ready;let t=`/key/${this.modifyThing(e)}`,[r]=await this.request(t,{method:"GET"});if(r.status=="ERR")throw new Error(r.detail);return r.result}async create(e,t){await this.ready;let r=`/key/${this.modifyThing(e)}`,[s]=await this.request(r,{method:"POST",body:t});if(s.status=="ERR")throw new Error(s.detail);return s.result}async update(e,t){await this.ready;let r=`/key/${this.modifyThing(e)}`,[s]=await this.request(r,{method:"PUT",body:t});if(s.status=="ERR")throw new Error(s.detail);return s.result}async merge(e,t){await this.ready;let r=`/key/${this.modifyThing(e)}`,[s]=await this.request(r,{method:"PATCH",body:t});if(s.status=="ERR")throw new Error(s.detail);return s.result}async delete(e){await this.ready;let t=`/key/${this.modifyThing(e)}`,[r]=await this.request(t,{method:"DELETE"});if(r.status=="ERR")throw new Error(r.detail);return r.result}get request(){if(!this.http)throw new o;return this.http.request.bind(this.http)}resetReady(){this.ready=new Promise(e=>this.resolveReady=e)}modifyThing(e){let t=/([^`:⟨⟩]+|\`.+\`|⟨.+⟩):([^`:⟨⟩]+|\`.+\`|⟨.+⟩)/;return e=e.replace(t,"$1/$2"),e}};var re=f;export{v as ExperimentalSurrealHTTP,f as Surreal,f as SurrealWebSocket,re as default};
var o=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"NoActiveSocket"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"No socket is currently connected to a SurrealDB instance. Please call the .connect() method first!"})}},u=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"NoConnectionDetails"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"No connection details for the HTTP api have been provided. Please call the .connect() method first!"})}},d=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnexpectedResponse"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"The returned response from the SurrealDB instance is in an unexpected format. Unable to process response!"})}},l=class extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidURLProvided"}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:"The provided string is either not a URL or is a URL but with an invalid protocol!"})}};var f=class{constructor(e=3e4){Object.defineProperty(this,"pinger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.interval=e}start(e){this.pinger=setInterval(e,this.interval)}stop(){clearInterval(this.pinger)}};var a;(function(s){s[s.OPEN=0]="OPEN",s[s.CLOSED=1]="CLOSED",s[s.RECONNECTING=2]="RECONNECTING"})(a||(a={}));var y=typeof WebSocket<"u"?WebSocket:null;var O=0;function E(){return(O=(O+1)%Number.MAX_SAFE_INTEGER).toString()}function p(s,e){let{protocol:t,host:r}=j(s);if(!Object.entries(e).flat().map(n=>n.toLowerCase()).includes(t))throw new l;return R(t,r,e)}function j(s){let e=/^([^/:]+):\/\/([^/]+)/,t=s.match(e);if(!t)throw new l;let[r,i]=[...t].slice(1,3).map(n=>n.toLowerCase());return{protocol:r,host:i}}function R(s,e,t){return s=s in t?t[s]:s,`${s}://${e}`}var c=class{constructor({url:e,onOpen:t,onClose:r}){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onOpen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onClose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:a.CLOSED}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"liveQueue",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"unprocessedLiveResponses",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"ready",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"closed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveClosed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"socketClosureReason",{enumerable:!0,configurable:!0,writable:!0,value:{1e3:"CLOSE_NORMAL"}}),this.onOpen=t,this.onClose=r,this.url=p(e,{http:"ws",https:"wss"})+"/rpc"}open(){this.close(1e3);let e=!1,t=new y(this.url);return this.ready=new Promise((r,i)=>{t.addEventListener("open",n=>{this.status=a.OPEN,e||(e=!0,r()),this.onOpen?.()}),t.addEventListener("error",n=>{n instanceof ErrorEvent&&(this.status=a.CLOSED,e||(e=!0,i(n.error)))})}),t.addEventListener("close",r=>{this.resolveClosed?.(),Object.values(this.liveQueue).map(i=>{i.map(n=>n({action:"CLOSE",detail:"SOCKET_CLOSED"}))}),this.queue={},this.liveQueue={},this.unprocessedLiveResponses={},this.status!==a.CLOSED&&(this.status=a.RECONNECTING,setTimeout(()=>{this.open()},2500),this.onClose?.())}),t.addEventListener("message",r=>{let i=JSON.parse(r.data.toString());c.isLiveNotification(i)?this.handleLiveBatch(i.result):i.id&&i.id in this.queue&&(this.queue[i.id](i),delete this.queue[i.id])}),this.ws=t,this.ready}async send(e,t,r){await this.ready;let i=E();this.queue[i]=r,this.ws?.send(JSON.stringify({id:i,method:e,params:t}))}async listenLive(e,t){e in this.liveQueue||(this.liveQueue[e]=[]),this.liveQueue[e].push(t),await Promise.all(this.unprocessedLiveResponses[e]?.map(t)??[]),delete this.unprocessedLiveResponses[e]}async kill(e){e in this.liveQueue&&(this.liveQueue[e].forEach(t=>t({action:"CLOSE",detail:"QUERY_KILLED"})),delete this.liveQueue[e]),await new Promise(t=>{this.send("kill",[e],r=>{e in this.unprocessedLiveResponses&&delete this.unprocessedLiveResponses[e],t()})})}async handleLiveBatch({id:e,...t}){this.liveQueue[e]?await Promise.all(this.liveQueue[e].map(async r=>await r(t))):(e in this.unprocessedLiveResponses||(this.unprocessedLiveResponses[e]=[]),this.unprocessedLiveResponses[e].push(t))}async close(e){this.status=a.CLOSED,this.closed=new Promise(t=>this.resolveClosed=t),this.ws?.close(e,this.socketClosureReason[e]),this.onClose?.(),await this.closed}get connectionStatus(){return this.status}static isLiveNotification(e){return!("id"in e)&&"result"in e&&typeof e.result=="object"&&e.result!==null&&"action"in e.result&&"id"in e.result&&"result"in e.result}};function v(s){return s==null}function h(s,e){if("SC"in s){if(s.NS||(s.NS=e?.namespace),s.DB||(s.DB=e?.database),v(s.NS))throw new Error("No namespace was specified!");if(v(s.DB))throw new Error("No database was specified!")}return s}var w=class{constructor(){Object.defineProperty(this,"socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pinger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connection",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"ready",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rejectReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"strategy",{enumerable:!0,configurable:!0,writable:!0,value:"ws"})}async connect(e,{prepare:t,auth:r,ns:i,db:n}={}){return this.ready=new Promise((m,P)=>{this.resolveReady=m,this.rejectReady=P}),this.connection={auth:r,ns:i,db:n},this.socket?.close(1e3),this.pinger=new f(3e4),this.socket=new c({url:e,onOpen:async()=>{this.pinger?.start(()=>this.ping()),this.connection.ns&&this.connection.db&&await this.use({}),typeof this.connection.auth=="string"?await this.authenticate(this.connection.auth):this.connection.auth&&await this.signin(this.connection.auth),await t?.(this),this.resolveReady?.()},onClose:()=>{this.pinger?.stop()}}),await this.socket.open().catch(this.rejectReady),this.ready}async close(){await this.socket?.close(1e3),this.socket=void 0}async wait(){if(!this.socket)throw new o;await this.ready}get status(){if(!this.socket)throw new o;return this.socket.connectionStatus}async ping(){let{error:e}=await this.send("ping");if(e)throw new Error(e.message)}async use({ns:e,db:t}){if(!e&&!this.connection.ns)throw new Error("Please specify a namespace to use.");if(!t&&!this.connection.db)throw new Error("Please specify a database to use.");this.connection.ns=e??this.connection.ns,this.connection.db=t??this.connection.db;let{error:r}=await this.send("use",[this.connection.ns,this.connection.db]);if(r)throw new Error(r.message)}async info(){await this.ready;let e=await this.send("info");if(e.error)throw new Error(e.error.message);return e.result??void 0}async signup(e){e=h(e,{namespace:this.connection.ns,database:this.connection.db});let t=await this.send("signup",[e]);if(t.error)throw new Error(t.error.message);return this.connection.auth=t.result,t.result}async signin(e){e=h(e,{namespace:this.connection.ns,database:this.connection.db});let t=await this.send("signin",[e]);if(t.error)throw new Error(t.error.message);return this.connection.auth=t.result??e,t.result}async authenticate(e){let t=await this.send("authenticate",[e]);if(t.error)throw new Error(t.error.message);return this.connection.auth=e,!!e}async invalidate(){let e=await this.send("invalidate");if(e.error)throw new Error(e.error.message);this.connection.auth=void 0}async let(e,t){let r=await this.send("let",[e,t]);if(r.error)throw new Error(r.error.message)}async unset(e){let t=await this.send("unset",[e]);if(t.error)throw new Error(t.error.message)}async live(e,t,r){await this.ready;let i=await this.send("live",[e,r]);if(i.error)throw new Error(i.error.message);return t&&this.listenLive(i.result,t),i.result}async listenLive(e,t){if(await this.ready,!this.socket)throw new o;this.socket.listenLive(e,t)}async kill(e){if(await this.ready,!this.socket)throw new o;await this.socket.kill(e)}async query(e,t){await this.ready;let r=await this.send("query",[e,t]);if(r.error)throw new Error(r.error.message);return r.result}async select(e){await this.ready;let t=await this.send("select",[e]);return this.outputHandler(t)}async create(e,t){await this.ready;let r=await this.send("create",[e,t]);return this.outputHandler(r)}async insert(e,t){await this.ready;let r=await this.send("insert",[e,t]);return this.outputHandler(r)}async update(e,t){await this.ready;let r=await this.send("update",[e,t]);return this.outputHandler(r)}async merge(e,t){await this.ready;let r=await this.send("merge",[e,t]);return this.outputHandler(r)}async patch(e,t){await this.ready;let r=await this.send("patch",[e,t]);return this.outputHandler(r)}async delete(e){await this.ready;let t=await this.send("delete",[e]);return this.outputHandler(t)}send(e,t){return new Promise(r=>{if(!this.socket)throw new o;this.socket.send(e,t??[],i=>r(i))})}outputHandler(e){if(e.error)throw new Error(e.error.message);if(Array.isArray(e.result))return e.result;if("id"in(e.result??{}))return[e.result];if(e.result===null)return[];throw console.debug({res:e}),new d}};var b=class{constructor(e,{fetcher:t}={}){Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"authorization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_namespace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_database",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.fetch=t??fetch,this.url=p(e,{ws:"http",wss:"https"})}ready(){return!!(this.url&&this._namespace&&this._database)}setTokenAuth(e){this.authorization=`Bearer ${e}`}createRootAuth(e,t){this.authorization=`Basic ${btoa(`${e}:${t}`)}`}clearAuth(){this.authorization=void 0}use({ns:e,db:t}){e&&(this._namespace=e),t&&(this._database=t)}get namespace(){return this._namespace}get database(){return this._database}async request(e,t){if(e=e.startsWith("/")?e.slice(1):e,!this.ready())throw new u;return(await this.fetch(`${this.url}/${e}${t?.searchParams?`?${t?.searchParams}`:""}`,{method:t?.method??"POST",headers:{"Content-Type":t?.plainBody?"text/plain":"application/json",Accept:"application/json",NS:this._namespace,DB:this._database,...this.authorization?{Authorization:this.authorization}:{}},body:typeof t?.body=="string"?t?.body:JSON.stringify(t?.body)})).json()}};var g=class{constructor(e,t={}){Object.defineProperty(this,"http",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ready",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"strategy",{enumerable:!0,configurable:!0,writable:!0,value:"http"}),this.resolveReady=()=>{},this.ready=new Promise(r=>this.resolveReady=r),e&&this.connect(e,t)}async connect(e,{fetch:t,prepare:r,auth:i,ns:n,db:m}={}){this.http=new b(e,{fetcher:t}),await this.use({ns:n,db:m}),typeof i=="string"?await this.authenticate(i):i&&await this.signin(i),await r?.(this),this.resolveReady(),await this.ready}close(){this.http=void 0,this.resetReady()}wait(){if(!this.http)throw new u;return this.ready}get status(){return this.request("/status")}async ping(){await this.request("/health")}use({ns:e,db:t}){if(!this.http)throw new u;return this.http.use({ns:e,db:t})}async signup(e){e=h(e,{namespace:this.http?.namespace,database:this.http?.database});let t=await this.request("/signup",{method:"POST",body:e});if(t.description)throw new Error(t.description);if(!t.token)throw new Error("Did not receive authentication token");return this.http?.setTokenAuth(t.token),t.token}async signin(e){e=h(e,{namespace:this.http?.namespace,database:this.http?.database});let t=await this.request("/signin",{method:"POST",body:e});if(t.description)throw new Error(t.description);if(!t.token)this.http?.createRootAuth(e.user,e.pass);else return this.http?.setTokenAuth(t.token),t.token}authenticate(e){return this.http?.setTokenAuth(e),!0}invalidate(){this.http?.clearAuth()}async query(e,t){await this.ready;let r=await this.request("/sql",{body:e,plainBody:!0,method:"POST",searchParams:t&&new URLSearchParams(Object.fromEntries(Object.entries(t).map(([i,n])=>[i,typeof n=="object"?JSON.stringify(n):`${n}`])))});if("information"in r)throw new Error(r.information);return r}async select(e){await this.ready;let t=`/key/${this.modifyThing(e)}`,[r]=await this.request(t,{method:"GET"});if(r.status=="ERR")throw new Error(r.detail);return r.result}async create(e,t){await this.ready;let r=`/key/${this.modifyThing(e)}`,[i]=await this.request(r,{method:"POST",body:t});if(i.status=="ERR")throw new Error(i.detail);return i.result}async update(e,t){await this.ready;let r=`/key/${this.modifyThing(e)}`,[i]=await this.request(r,{method:"PUT",body:t});if(i.status=="ERR")throw new Error(i.detail);return i.result}async merge(e,t){await this.ready;let r=`/key/${this.modifyThing(e)}`,[i]=await this.request(r,{method:"PATCH",body:t});if(i.status=="ERR")throw new Error(i.detail);return i.result}async delete(e){await this.ready;let t=`/key/${this.modifyThing(e)}`,[r]=await this.request(t,{method:"DELETE"});if(r.status=="ERR")throw new Error(r.detail);return r.result}get request(){if(!this.http)throw new u;return this.http.request.bind(this.http)}resetReady(){this.ready=new Promise(e=>this.resolveReady=e)}modifyThing(e){let t=/([^`:⟨⟩]+|\`.+\`|⟨.+⟩):([^`:⟨⟩]+|\`.+\`|⟨.+⟩)/;return e=e.replace(t,"$1/$2"),e}};var ie=w;export{g as ExperimentalSurrealHTTP,w as Surreal,w as SurrealWebSocket,ie as default};
//# sourceMappingURL=index.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc