surrealdb.js
Advanced tools
Comparing version 0.9.0 to 0.9.1
@@ -104,8 +104,6 @@ import { WebsocketStatus, } from "../types.js"; | ||
ws.addEventListener("error", (e) => { | ||
if (e instanceof ErrorEvent) { | ||
this.status = WebsocketStatus.CLOSED; | ||
if (!resolved) { | ||
resolved = true; | ||
reject(e.error); | ||
} | ||
this.status = WebsocketStatus.CLOSED; | ||
if (!resolved) { | ||
resolved = true; | ||
reject("error" in e ? e.error : e.toString()); | ||
} | ||
@@ -112,0 +110,0 @@ }); |
@@ -166,3 +166,3 @@ import { NoConnectionDetails } from "../errors.js"; | ||
k, | ||
typeof v == "object" ? JSON.stringify(v) : `${v}`, | ||
JSON.stringify(v), | ||
]))), | ||
@@ -169,0 +169,0 @@ }); |
@@ -142,3 +142,15 @@ export type ConnectionStrategy = "websocket" | "experimental_http"; | ||
}; | ||
export type Patch = AddPatch | RemovePatch | ReplacePatch | ChangePatch; | ||
export type CopyPatch<T = string, U = string> = BasePatch<T> & { | ||
op: "copy"; | ||
from: U; | ||
}; | ||
export type MovePatch<T = string, U = string> = BasePatch<T> & { | ||
op: "move"; | ||
from: U; | ||
}; | ||
export type TestPatch<T = string, U = unknown> = BasePatch<T> & { | ||
op: "test"; | ||
value: U; | ||
}; | ||
export type Patch = AddPatch | RemovePatch | ReplacePatch | ChangePatch | CopyPatch | MovePatch | TestPatch; | ||
export declare enum WebsocketStatus { | ||
@@ -145,0 +157,0 @@ OPEN = 0, |
@@ -5,3 +5,3 @@ { | ||
"name": "surrealdb.js", | ||
"version": "0.9.0", | ||
"version": "0.9.1", | ||
"description": "Javascript driver for SurrealDB", | ||
@@ -8,0 +8,0 @@ "license": "Apache 2.0", |
@@ -5,9 +5,9 @@ # surrealdb.js | ||
[![npm version](https://badge.fury.io/js/surrealdb.js.svg)](https://badge.fury.io/js/surrealdb.js) | ||
[![deno module](https://shield.deno.dev/x/surrealdb)](https://deno.land/x/surrealdb) | ||
[![](https://img.shields.io/badge/status-beta-ff00bb.svg?style=flat-square)](https://github.com/surrealdb/surrealdb.js) | ||
[![](https://img.shields.io/badge/docs-view-44cc11.svg?style=flat-square)](https://surrealdb.com/docs/integration/libraries/javascript) | ||
[![](https://img.shields.io/badge/license-Apache_License_2.0-00bfff.svg?style=flat-square)](https://github.com/surrealdb/surrealdb.js) | ||
[![](https://img.shields.io/npm/v/surrealdb.js?style=flat-square)](https://www.npmjs.com/package/surrealdb.js) | ||
[![](https://img.shields.io/npm/v/surrealdb.js?style=flat-square&label=deno)](https://deno.land/x/surrealdb) | ||
## Quickstart-Guide | ||
@@ -102,3 +102,3 @@ | ||
// Update a person record with a specific id | ||
let updated = await db.change("person:jaime", { | ||
let updated = await db.merge("person:jaime", { | ||
marketing: true, | ||
@@ -105,0 +105,0 @@ }); |
@@ -110,8 +110,6 @@ "use strict"; | ||
ws.addEventListener("error", (e) => { | ||
if (e instanceof ErrorEvent) { | ||
this.status = types_js_1.WebsocketStatus.CLOSED; | ||
if (!resolved) { | ||
resolved = true; | ||
reject(e.error); | ||
} | ||
this.status = types_js_1.WebsocketStatus.CLOSED; | ||
if (!resolved) { | ||
resolved = true; | ||
reject("error" in e ? e.error : e.toString()); | ||
} | ||
@@ -118,0 +116,0 @@ }); |
@@ -169,3 +169,3 @@ "use strict"; | ||
k, | ||
typeof v == "object" ? JSON.stringify(v) : `${v}`, | ||
JSON.stringify(v), | ||
]))), | ||
@@ -172,0 +172,0 @@ }); |
@@ -142,3 +142,15 @@ export type ConnectionStrategy = "websocket" | "experimental_http"; | ||
}; | ||
export type Patch = AddPatch | RemovePatch | ReplacePatch | ChangePatch; | ||
export type CopyPatch<T = string, U = string> = BasePatch<T> & { | ||
op: "copy"; | ||
from: U; | ||
}; | ||
export type MovePatch<T = string, U = string> = BasePatch<T> & { | ||
op: "move"; | ||
from: U; | ||
}; | ||
export type TestPatch<T = string, U = unknown> = BasePatch<T> & { | ||
op: "test"; | ||
value: U; | ||
}; | ||
export type Patch = AddPatch | RemovePatch | ReplacePatch | ChangePatch | CopyPatch | MovePatch | TestPatch; | ||
export declare enum WebsocketStatus { | ||
@@ -145,0 +157,0 @@ OPEN = 0, |
@@ -71,8 +71,6 @@ import { | ||
ws.addEventListener("error", (e) => { | ||
if (e instanceof ErrorEvent) { | ||
this.status = WebsocketStatus.CLOSED; | ||
if (!resolved) { | ||
resolved = true; | ||
reject(e.error); | ||
} | ||
this.status = WebsocketStatus.CLOSED; | ||
if (!resolved) { | ||
resolved = true; | ||
reject("error" in e ? e.error : e.toString()); | ||
} | ||
@@ -79,0 +77,0 @@ }); |
@@ -184,3 +184,3 @@ import { NoConnectionDetails } from "../errors.js"; | ||
k, | ||
typeof v == "object" ? JSON.stringify(v) : `${v}`, | ||
JSON.stringify(v), | ||
]), | ||
@@ -187,0 +187,0 @@ ), |
@@ -253,4 +253,26 @@ export type ConnectionStrategy = "websocket" | "experimental_http"; | ||
export type Patch = AddPatch | RemovePatch | ReplacePatch | ChangePatch; | ||
export type CopyPatch<T = string, U = string> = BasePatch<T> & { | ||
op: "copy"; | ||
from: U; | ||
}; | ||
export type MovePatch<T = string, U = string> = BasePatch<T> & { | ||
op: "move"; | ||
from: U; | ||
}; | ||
export type TestPatch<T = string, U = unknown> = BasePatch<T> & { | ||
op: "test"; | ||
value: U; | ||
}; | ||
export type Patch = | ||
| AddPatch | ||
| RemovePatch | ||
| ReplacePatch | ||
| ChangePatch | ||
| CopyPatch | ||
| MovePatch | ||
| TestPatch; | ||
/////////////////////////////////// | ||
@@ -257,0 +279,0 @@ ////////// WEBSOCKET ////////// |
@@ -1,2 +0,2 @@ | ||
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}; | ||
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 p=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 f(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=f(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=>{this.status=a.CLOSED,e||(e=!0,i("error"in n?n.error:n.toString()))})}),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 p(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=f(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,JSON.stringify(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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Unpopular package
QualityThis package is not very popular.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
254881
4705
1
656
1