psionic 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/adapters/reconnect.d.mts +10 -0
- package/adapters/reconnect.mjs +2 -0
- package/adapters/reconnect.mjs.map +1 -0
- package/adapters/resend.d.mts +13 -0
- package/adapters/resend.mjs +2 -0
- package/adapters/resend.mjs.map +1 -0
- package/adapters/socket.d.mts +14 -0
- package/adapters/socket.mjs +3 -0
- package/adapters/socket.mjs.map +1 -0
- package/adapters/websocket.d.mts +21 -0
- package/adapters/websocket.mjs +2 -0
- package/adapters/websocket.mjs.map +1 -0
- package/adapters/webworker.d.mts +8 -0
- package/adapters/webworker.mjs +2 -0
- package/adapters/webworker.mjs.map +1 -0
- package/codecs/cbor.d.mts +12 -0
- package/codecs/cbor.mjs +2 -0
- package/codecs/cbor.mjs.map +1 -0
- package/codecs/psionic.d.mts +12 -0
- package/codecs/psionic.mjs +2 -0
- package/codecs/psionic.mjs.map +1 -0
- package/package.json +42 -24
- package/psionic.d.mts +203 -0
- package/psionic.mjs +2 -0
- package/psionic.mjs.map +1 -0
- package/session.d.mts +63 -0
- package/session.mjs +2 -0
- package/session.mjs.map +1 -0
- package/utils/react-hooks.d.mts +24 -0
- package/utils/react-hooks.mjs +2 -0
- package/utils/react-hooks.mjs.map +1 -0
- package/README.md +0 -321
- package/__tests__/async-functions.ts +0 -43
- package/__tests__/async-generator-functions.ts +0 -137
- package/__tests__/convert-from-wire-format.ts +0 -65
- package/__tests__/convert-to-wire-format.ts +0 -66
- package/__tests__/describe.ts +0 -26
- package/__tests__/lib/adapter.ts +0 -47
- package/docs/extending.md +0 -19
- package/docs/protocol.md +0 -154
- package/examples/cli-chat/client.mjs +0 -21
- package/examples/cli-chat/package.json +0 -17
- package/examples/cli-chat/server.mjs +0 -48
- package/examples/cloudflare/README.md +0 -37
- package/examples/cloudflare/eslint.config.js +0 -19
- package/examples/cloudflare/index.html +0 -13
- package/examples/cloudflare/package.json +0 -29
- package/examples/cloudflare/public/vite.svg +0 -1
- package/examples/cloudflare/src/App.svelte +0 -450
- package/examples/cloudflare/src/api.ts +0 -33
- package/examples/cloudflare/src/main.ts +0 -4
- package/examples/cloudflare/tsconfig.app.json +0 -27
- package/examples/cloudflare/tsconfig.json +0 -14
- package/examples/cloudflare/tsconfig.node.json +0 -26
- package/examples/cloudflare/tsconfig.worker.json +0 -8
- package/examples/cloudflare/vite.config.ts +0 -8
- package/examples/cloudflare/worker/cloudflare.ts +0 -115
- package/examples/cloudflare/worker/index.ts +0 -17
- package/examples/cloudflare/worker/peer.ts +0 -47
- package/examples/cloudflare/worker-configuration.d.ts +0 -10922
- package/examples/cloudflare/wrangler.jsonc +0 -58
- package/examples/nodestreams/adapter.mjs +0 -36
- package/examples/nodestreams/child.mjs +0 -20
- package/examples/nodestreams/package.json +0 -14
- package/examples/nodestreams/parent.mjs +0 -20
- package/examples/reconnect/client.mjs +0 -22
- package/examples/reconnect/package.json +0 -15
- package/examples/reconnect/server.mjs +0 -30
- package/examples/tokens/client.mjs +0 -26
- package/examples/tokens/package.json +0 -20
- package/examples/tokens/server.mjs +0 -46
- package/make-package.js +0 -23
- package/src/adapters/reconnect.ts +0 -54
- package/src/adapters/resend.ts +0 -34
- package/src/adapters/socket.ts +0 -183
- package/src/adapters/websocket.ts +0 -157
- package/src/adapters/webworker.ts +0 -48
- package/src/codecs/cbor.ts +0 -239
- package/src/codecs/psionic.ts +0 -75
- package/src/psionic.ts +0 -876
- package/src/session.ts +0 -164
- package/src/utils/react-hooks.ts +0 -48
- package/tests +0 -8
- package/tsdown.config.ts +0 -19
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { AdapterNext, Connection, Peer } from "../psionic.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/adapters/reconnect.d.ts
|
|
4
|
+
type ReconnectAdapterOptions = {
|
|
5
|
+
/** Maximum number of reconnection attempts before giving up. Default: Infinity. */maxAttempts?: number;
|
|
6
|
+
};
|
|
7
|
+
declare function reconnect(inner: () => (peer: AdapterNext) => Promise<Connection>, opts?: ReconnectAdapterOptions): (peer: Peer) => Promise<Connection>;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { reconnect };
|
|
10
|
+
//# sourceMappingURL=reconnect.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e,t){let n=null,r=0,i=t?.maxAttempts??1/0;return async function t(a){let o=await e()({session:a.session,close:e=>{if(!e){a.close();return}if(n&&clearTimeout(n),r>=i){console.warn(`Max reconnection attempts reached. Closing peer.`),a.close();return}n=setTimeout(()=>{r+=1,a.connect(()=>t(a)).then(()=>{r=0}).catch(()=>{})},Math.min(300*2**r,3e4)+Math.random()*1e3)},handleMessage:e=>a.handleMessage(e)});return r=0,queueMicrotask(()=>{a.local&&a.describe(a.local)}),o}}export{e as reconnect};
|
|
2
|
+
//# sourceMappingURL=reconnect.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconnect.mjs","names":[],"sources":["../../src/adapters/reconnect.ts"],"sourcesContent":["import type { AdapterNext, Connection, Peer } from \"../psionic\";\nimport type { Session } from \"../session\";\n\ntype ReconnectAdapterOptions = {\n /** Maximum number of reconnection attempts before giving up. Default: Infinity. */\n maxAttempts?: number;\n};\n\ntype ReconnectAdaptable = {\n session: Session;\n connect: (adapter: () => Promise<Connection>) => Promise<void>;\n handleMessage: (frame: any) => void;\n close: (ex?: any) => void;\n describe: (desc: any) => void;\n local?: any;\n};\n\nexport function reconnect(inner: () => (peer: AdapterNext) => Promise<Connection>, opts?: ReconnectAdapterOptions): (peer: Peer) => Promise<Connection> {\n let timer: ReturnType<typeof setTimeout> | null = null;\n let attempt = 0;\n const maxAttempts = opts?.maxAttempts ?? Infinity;\n return async function connectPeer(peer: ReconnectAdaptable) {\n const newAdapter = inner();\n const connection = await newAdapter({\n session: peer.session,\n close: (ex?: any) => {\n if (!ex) {\n // allow intentional closes.\n peer.close();\n return;\n }\n if (timer) clearTimeout(timer);\n if (attempt >= maxAttempts) {\n console.warn('Max reconnection attempts reached. Closing peer.');\n peer.close();\n return;\n }\n timer = setTimeout(() => {\n attempt += 1;\n peer.connect(() => connectPeer(peer)).then(() => { attempt = 0; }).catch(() => {});\n }, Math.min(300 * 2 ** attempt, 30000) + Math.random() * 1000);\n },\n handleMessage: (frame) => {\n return peer.handleMessage(frame);\n }\n });\n attempt = 0;\n queueMicrotask(() => {\n if (!peer.local) return;\n peer.describe(peer.local);\n });\n return connection;\n };\n}"],"mappings":"AAiBA,SAAgB,EAAU,EAAyD,EAAqE,CACpJ,IAAI,EAA8C,KAC9C,EAAU,EACR,EAAc,GAAM,aAAe,IACzC,OAAO,eAAe,EAAY,EAA0B,CAExD,IAAM,EAAa,MADA,GAAO,CACU,CAChC,QAAS,EAAK,QACd,MAAQ,GAAa,CACjB,GAAI,CAAC,EAAI,CAEL,EAAK,OAAO,CACZ,OAGJ,GADI,GAAO,aAAa,EAAM,CAC1B,GAAW,EAAa,CACxB,QAAQ,KAAK,mDAAmD,CAChE,EAAK,OAAO,CACZ,OAEJ,EAAQ,eAAiB,CACrB,GAAW,EACX,EAAK,YAAc,EAAY,EAAK,CAAC,CAAC,SAAW,CAAE,EAAU,GAAK,CAAC,UAAY,GAAG,EACnF,KAAK,IAAI,IAAM,GAAK,EAAS,IAAM,CAAG,KAAK,QAAQ,CAAG,IAAK,EAElE,cAAgB,GACL,EAAK,cAAc,EAAM,CAEvC,CAAC,CAMF,MALA,GAAU,EACV,mBAAqB,CACZ,EAAK,OACV,EAAK,SAAS,EAAK,MAAM,EAC3B,CACK"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Session } from "../session.mjs";
|
|
2
|
+
import { AdapterNext, Connection } from "../psionic.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/adapters/resend.d.ts
|
|
5
|
+
type ResendAdaptable = {
|
|
6
|
+
session: Session;
|
|
7
|
+
handleMessage: (frame: any) => void;
|
|
8
|
+
close: (ex?: any) => void;
|
|
9
|
+
};
|
|
10
|
+
declare function resend(inner: (peer: AdapterNext) => Promise<Connection>): (peer: ResendAdaptable) => Promise<Connection>;
|
|
11
|
+
//#endregion
|
|
12
|
+
export { resend };
|
|
13
|
+
//# sourceMappingURL=resend.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){return async function(t){let n=t.session.meta.frames??=[],r=await e({close:t.close,session:t.session,handleMessage:e=>{n.length=0,t.handleMessage(e)}});for(let e of n)r.send(e);return{close:r.close,send:async e=>{(e[0]===`K`||e[0]===`E`)&&n.push(e),r.send(e)}}}}export{e as resend};
|
|
2
|
+
//# sourceMappingURL=resend.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resend.mjs","names":[],"sources":["../../src/adapters/resend.ts"],"sourcesContent":["import type { AdapterNext, Connection } from \"../psionic\";\nimport type { Session } from \"../session\";\n\ntype ResendAdaptable = {\n session: Session;\n handleMessage: (frame: any) => void;\n close: (ex?: any) => void;\n};\n\nexport function resend(inner: (peer: AdapterNext) => Promise<Connection>): (peer: ResendAdaptable) => Promise<Connection> {\n return async function connectPeer(peer: ResendAdaptable) {\n const frames = (peer.session.meta.frames ??= []);\n const newAdapter = await inner({\n close: peer.close,\n session: peer.session,\n handleMessage: (frame) => {\n frames.length = 0;\n peer.handleMessage(frame);\n }\n });\n for (const frame of frames) {\n newAdapter.send(frame);\n }\n return {\n close: newAdapter.close,\n send: async (frame) => {\n if (frame[0] === 'K' || frame[0] === 'E') {\n frames.push(frame);\n }\n newAdapter.send(frame);\n }\n };\n }\n};\n"],"mappings":"AASA,SAAgB,EAAO,EAAmG,CACtH,OAAO,eAA2B,EAAuB,CACrD,IAAM,EAAU,EAAK,QAAQ,KAAK,SAAW,EAAE,CACzC,EAAa,MAAM,EAAM,CAC3B,MAAO,EAAK,MACZ,QAAS,EAAK,QACd,cAAgB,GAAU,CACtB,EAAO,OAAS,EAChB,EAAK,cAAc,EAAM,EAEhC,CAAC,CACF,IAAK,IAAM,KAAS,EAChB,EAAW,KAAK,EAAM,CAE1B,MAAO,CACH,MAAO,EAAW,MAClB,KAAM,KAAO,IAAU,EACf,EAAM,KAAO,KAAO,EAAM,KAAO,MACjC,EAAO,KAAK,EAAM,CAEtB,EAAW,KAAK,EAAM,EAE7B"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Adapter, WireCodec } from "../psionic.mjs";
|
|
2
|
+
import { Socket } from "net";
|
|
3
|
+
|
|
4
|
+
//#region src/adapters/socket.d.ts
|
|
5
|
+
declare const ErrorFrameTooLarge = "Frame size exceeds maximum allowed";
|
|
6
|
+
type NodeSocketAdapterOptions = {
|
|
7
|
+
/** Optional codec to use for encoding/decoding messages. Default: `defaultCodec`. */codec?: WireCodec; /** Max frame size in bytes. Default: 1MB. */
|
|
8
|
+
maxFrameSize?: number;
|
|
9
|
+
};
|
|
10
|
+
/** Adapter for Node.js TCP sockets. */
|
|
11
|
+
declare function createNodeSocketAdapter(socket: Socket, opts?: NodeSocketAdapterOptions): Adapter;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { ErrorFrameTooLarge, NodeSocketAdapterOptions, createNodeSocketAdapter };
|
|
14
|
+
//# sourceMappingURL=socket.d.mts.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{psionicCodec as e}from"../codecs/psionic.mjs";const t=`Frame size exceeds maximum allowed`,n=Uint8Array.prototype.slice;function r(r,s){return async function(c){let l=s?.maxFrameSize??1048576,u=s?.codec??e(),d=Buffer.alloc(4096),f=0,p=!1;if(r.readyState===`closed`)throw Error(`Socket is already closed`);function m(e){try{let t=u.messageToWire(e);if(u.type===`binary`){let e=i(t.length);r.write(Buffer.concat([e,t]))}else r.write(t+`
|
|
2
|
+
`)}catch(e){g(e instanceof Error?e:Error(String(e)))}}function h(e){if(e.byteLength+d.byteLength>l){g(Error(t));return}if(e.byteLength>d.length-f){let e=Buffer.alloc(Math.min(l,d.length)*2);d.copy(e,0,0,f),d=e}e.copy(d,f),f+=e.byteLength;let r=0;for(;r<f;){let e,i=new DataView(d.buffer,r,f-r);if(u.type===`binary`){if(i.byteLength<4)break;let n=a(i),s=o(i,n);if(s===-1)break;if(s>l){g(Error(t));return}if(i.byteLength<n+s)break;let d=i.buffer.slice(n+i.byteOffset,n+i.byteOffset+s);r+=n+s,e=u.messageFromWire(new Uint8Array(d));try{c.handleMessage(e)}catch(e){g(e instanceof Error?e:Error(String(e)));return}}else{let e=d.indexOf(10,r);if(e===-1&&f>l){g(Error(t));return}if(e===-1)break;let i=n.call(d,r,e);r=e+1;try{let e=u.messageFromWire(i);c.handleMessage(e)}catch(e){g(e instanceof Error?e:Error(String(e)));return}}}d.copy(d,0,r,f),f-=r}function g(e){throw _(e),e}function _(e){p||(p=!0,r.off(`data`,h),r.off(`close`,_),r.destroy(e),c.close(e))}r.on(`data`,h),r.on(`close`,e=>_(e??Error(`Socket closed`)));async function v(){return await new Promise((e,t)=>{if(r.readyState===`open`)return e();r.once(`open`,n),r.once(`connect`,n),r.once(`close`,i);function n(){r.off(`open`,n),r.off(`connect`,n),r.off(`close`,i),e()}function i(){r.off(`open`,n),r.off(`close`,i),t(Error(`Socket closed before connection could be established`))}})}return await v(),{send:m,close:_}}}function i(e){if(e<64){let t=new DataView(new ArrayBuffer(1));return t.setUint8(0,e),new Uint8Array(t.buffer)}if(e<16384){let t=new DataView(new ArrayBuffer(2));return t.setUint16(0,16384|e),new Uint8Array(t.buffer)}if(e<1<<30){let t=new DataView(new ArrayBuffer(4));return t.setUint32(0,2<<30|e),new Uint8Array(t.buffer)}throw Error(`Value too large for variable byte length encoding`)}function a(e){switch(e.getUint8(0)>>6){case 0:return 1;case 1:return 2;case 2:return 4}return 2**53-1}function o(e,t){return t>e.byteLength-t-1?-1:t===1?e.getUint8(0)&63:t===2?e.getUint16(0)&16383:t===4?e.getUint32(0)&1073741823:2**53-1}export{t as ErrorFrameTooLarge,r as createNodeSocketAdapter};
|
|
3
|
+
//# sourceMappingURL=socket.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.mjs","names":[],"sources":["../../src/adapters/socket.ts"],"sourcesContent":["import type { WireCodec, Frame, AdapterNext, Adapter } from \"../psionic\";\nimport { Socket } from \"net\";\nimport { psionicCodec } from \"../codecs/psionic\";\n\nexport const ErrorFrameTooLarge = 'Frame size exceeds maximum allowed';\n\nexport type NodeSocketAdapterOptions = {\n /** Optional codec to use for encoding/decoding messages. Default: `defaultCodec`. */\n codec?: WireCodec;\n /** Max frame size in bytes. Default: 1MB. */\n maxFrameSize?: number;\n};\n\nconst slice = Uint8Array.prototype.slice;\n\n/** Adapter for Node.js TCP sockets. */\nexport function createNodeSocketAdapter(socket: Socket, opts?: NodeSocketAdapterOptions): Adapter {\n return async function connectPeer(next: AdapterNext) {\n const maxFrameSize = opts?.maxFrameSize ?? 1_048_576;\n const codec: WireCodec = opts?.codec ?? psionicCodec();\n const newline = '\\n';\n let readdata = Buffer.alloc(0x1000);\n let readlen = 0;\n let dead = false;\n \n if (socket.readyState === 'closed') {\n throw new Error('Socket is already closed');\n }\n\n function onSend(message: Frame) {\n try {\n const bytes = codec.messageToWire(message);\n if (codec.type === 'binary') {\n const len = toVariableByteLength(bytes.length);\n socket.write(Buffer.concat([len, bytes as Uint8Array]));\n } else {\n socket.write(bytes + newline);\n }\n } catch (ex) {\n teardown(ex instanceof Error ? ex : new Error(String(ex)));\n }\n }\n\n function onMessage(chunk: Buffer) {\n if (chunk.byteLength + readdata.byteLength > maxFrameSize) {\n teardown(new Error(ErrorFrameTooLarge));\n return;\n }\n if (chunk.byteLength > readdata.length - readlen) {\n const newBuffer = Buffer.alloc(Math.min(maxFrameSize, readdata.length) * 2);\n readdata.copy(newBuffer, 0, 0, readlen);\n readdata = newBuffer;\n }\n chunk.copy(readdata, readlen);\n readlen += chunk.byteLength;\n let i = 0;\n while (i < readlen) {\n let messageData: any;\n let view = new DataView(readdata.buffer, i, readlen - i);\n if (codec.type === 'binary') {\n if (view.byteLength < 4) break;\n const nlength = checkNumberLength(view);\n const length = readNumber(view, nlength);\n if (length === -1) break;\n if (length > maxFrameSize) {\n teardown(new Error(ErrorFrameTooLarge));\n return;\n }\n if (view.byteLength < nlength + length) break;\n\n const data = view.buffer.slice(nlength + view.byteOffset, nlength + view.byteOffset + length);\n i += nlength + length;\n messageData = codec.messageFromWire(new Uint8Array(data));\n try {\n next.handleMessage(messageData as Frame);\n } catch (ex) {\n teardown(ex instanceof Error ? ex : new Error(String(ex)));\n return;\n }\n } else {\n const lineIndex = readdata.indexOf(0x0A, i);\n if (lineIndex === -1 && readlen > maxFrameSize) {\n teardown(new Error(ErrorFrameTooLarge));\n return;\n }\n if (lineIndex === -1) break;\n const data = slice.call(readdata, i, lineIndex);\n i = lineIndex + 1;\n try {\n const messageData = codec.messageFromWire(data);\n next.handleMessage(messageData as Frame);\n } catch (ex) {\n teardown(ex instanceof Error ? ex : new Error(String(ex)));\n return;\n }\n }\n }\n\n readdata.copy(readdata, 0, i, readlen);\n readlen -= i;\n }\n\n function teardown(ex: any) {\n onClose(ex);\n throw ex;\n }\n\n function onClose(ex: any) {\n if (dead) return;\n dead = true;\n socket.off('data', onMessage);\n socket.off('close', onClose);\n socket.destroy(ex);\n next.close(ex);\n }\n\n socket.on('data', onMessage);\n socket.on('close', ex => onClose(ex ?? new Error('Socket closed')));\n\n async function waitUntilOpen(): Promise<void> {\n return await new Promise((resolve, reject) => {\n if (socket.readyState === 'open') return resolve();\n socket.once('open', opener);\n socket.once('connect', opener);\n socket.once('close', closer);\n function opener() {\n socket.off('open', opener);\n socket.off('connect', opener);\n socket.off('close', closer);\n resolve();\n }\n function closer() {\n socket.off('open', opener);\n socket.off('close', closer);\n reject(new Error('Socket closed before connection could be established'));\n }\n });\n }\n\n await waitUntilOpen();\n return {\n send: onSend,\n close: onClose\n }\n }\n}\n\n/** Encodes a length as a 1/2/4-byte variable-length integer (2-bit length prefix). */\nfunction toVariableByteLength(value: number): Uint8Array {\n if (value < 64) {\n const view = new DataView(new ArrayBuffer(1));\n view.setUint8(0, value);\n return new Uint8Array(view.buffer);\n }\n if (value < (0b01 << 14)) {\n const view = new DataView(new ArrayBuffer(2));\n view.setUint16(0, (0b01 << 14) | value);\n return new Uint8Array(view.buffer);\n }\n if (value < (0b01 << 30)) {\n const view = new DataView(new ArrayBuffer(4));\n view.setUint32(0, (0b10 << 30) | value);\n return new Uint8Array(view.buffer);\n }\n throw new Error('Value too large for variable byte length encoding');\n}\n\nfunction checkNumberLength(value: DataView) {\n switch (value.getUint8(0) >> 6) {\n case 0b00: return 1;\n case 0b01: return 2;\n case 0b10: return 4;\n }\n return Number.MAX_SAFE_INTEGER;\n}\n\nfunction readNumber(value: DataView, bytes: number) {\n if (bytes > value.byteLength - bytes - 1) return -1;\n if (bytes === 1) return value.getUint8(0) & 0b0011_1111;\n if (bytes === 2) return value.getUint16(0) & 0b0011_1111_1111_1111;\n if (bytes === 4) return value.getUint32(0) & 0b0011_1111_1111_1111_1111_1111_1111_1111;\n return Number.MAX_SAFE_INTEGER;\n}\n"],"mappings":"qDAIA,MAAa,EAAqB,qCAS5B,EAAQ,WAAW,UAAU,MAGnC,SAAgB,EAAwB,EAAgB,EAA0C,CAC9F,OAAO,eAA2B,EAAmB,CACjD,IAAM,EAAe,GAAM,cAAgB,QACrC,EAAmB,GAAM,OAAS,GAAc,CAElD,EAAW,OAAO,MAAM,KAAO,CAC/B,EAAU,EACV,EAAO,GAEX,GAAI,EAAO,aAAe,SACtB,MAAU,MAAM,2BAA2B,CAG/C,SAAS,EAAO,EAAgB,CAC5B,GAAI,CACA,IAAM,EAAQ,EAAM,cAAc,EAAQ,CAC1C,GAAI,EAAM,OAAS,SAAU,CACzB,IAAM,EAAM,EAAqB,EAAM,OAAO,CAC9C,EAAO,MAAM,OAAO,OAAO,CAAC,EAAK,EAAoB,CAAC,CAAC,MAEvD,EAAO,MAAM,EAAQ;EAAQ,OAE5B,EAAI,CAC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AI,SAAS,IAAI,YAAY,EAAE,CAAC,CAE7C,OADA,EAAK,UAAU,EAAI,MAAc,EAAM,CAChC,IAAI,WAAW,EAAK,OAAO,CAEtC,GAAI,EAAS,GAAQ,GAAK,CACtB,IAAM,EAAO,IAAI,SAAS,IAAI,YAAY,EAAE,CAAC,CAE7C,OADA,EAAK,UAAU,EAAI,GAAQ,GAAM,EAAM,CAChC,IAAI,WAAW,EAAK,OAAO,CAEtC,MAAU,MAAM,oDAAoD,CAGxE,SAAS,EAAkB,EAAiB,CACxC,OAAQ,EAAM,SAAS,EAAE,EAAI,EAA7B,CACI,IAAK,GAAM,MAAO,GAClB,IAAK,GAAM,MAAO,GAClB,IAAK,GAAM,MAAO,GAEtB,eAGJ,SAAS,EAAW,EAAiB,EAAe,CAKhD,OAJI,EAAQ,EAAM,WAAa,EAAQ,EAAU,GAC7C,IAAU,EAAU,EAAM,SAAS,EAAE,CAAG,GACxC,IAAU,EAAU,EAAM,UAAU,EAAE,CAAG,MACzC,IAAU,EAAU,EAAM,UAAU,EAAE,CAAG"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { AdapterNext, Connection, WireCodec } from "../psionic.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/adapters/websocket.d.ts
|
|
4
|
+
type WebSocketAdapterOptions = {
|
|
5
|
+
/** Optional codec to use for encoding/decoding messages. */codec?: WireCodec; /** Max frame size in bytes. Default: 1MB. */
|
|
6
|
+
maxFrameSize?: number; /** Interval in milliseconds for sending ping messages. Default: 10000 (10 seconds). */
|
|
7
|
+
pingInterval?: number;
|
|
8
|
+
};
|
|
9
|
+
type AdaptableWebSocket = {
|
|
10
|
+
binaryType?: string;
|
|
11
|
+
readyState: number;
|
|
12
|
+
addEventListener: (type: any, listener: (event: any) => void) => void;
|
|
13
|
+
removeEventListener: (type: any, listener: (event: any) => void) => void;
|
|
14
|
+
send: (message: any) => void;
|
|
15
|
+
close: (code?: number, reason?: string) => void;
|
|
16
|
+
};
|
|
17
|
+
/** Adapter for browser and standards-compatible WebSockets. */
|
|
18
|
+
declare function createWebSocketAdapter(socket: AdaptableWebSocket, opts?: WebSocketAdapterOptions): (peer: AdapterNext) => Promise<Connection>;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { AdaptableWebSocket, WebSocketAdapterOptions, createWebSocketAdapter };
|
|
21
|
+
//# sourceMappingURL=websocket.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{psionicCodec as e}from"../codecs/psionic.mjs";const t=new Uint8Array([112,105,110,103]),n=new Uint8Array([112,111,110,103]);function r(r,a){if(r.binaryType===`blob`)throw Error(`websocket blob binary type not supported, set ws.binaryType to 'arrayBuffer'.`);let o=a?.pingInterval??1e4;return async function(s){let c=Date.now(),l=a?.codec??e(),u=a?.maxFrameSize??1*1048576,d=!1;if(r.readyState===2||r.readyState===3)throw Error(`WebSocket is already closed or closing`);r.addEventListener(`close`,v);let f;function p(){f&&=(clearInterval(f),void 0),d||(f=setInterval(m,o))}function m(){if(d){clearInterval(f);return}let e=Date.now()-c;if(!(e<o)){if(e>o*2){clearInterval(f),_(Error(`No response to ping, assuming connection is dead`));return}try{r.send(t)}catch(e){_(e instanceof Error?e:Error(String(e)))}}}function h(e){if(c=Date.now(),e.data instanceof Uint8Array&&e.data.every((e,t)=>e===n[t]))return;if(e.data instanceof Uint8Array&&e.data.every((e,n)=>e===t[n])){r.send(n);return}let a=i(e);if(a.byteLength>u){_(Error(`Frame size exceeds maximum allowed`));return}try{let e=l.messageFromWire(a);s.handleMessage(e)}catch(e){_(e instanceof Error?e:Error(String(e)))}}function g(e){if(!d)try{let t=l.messageToWire(e);r.send(t)}catch(e){throw _(e instanceof Error?e:Error(String(e))),e}}function _(e){d||v(e)}function v(e){d||(d=!0,clearInterval(f),r.removeEventListener(`message`,h),r.removeEventListener(`close`,v),(r.readyState===1||r.readyState===0)&&r.close(e instanceof Error?3e3:1e3,e instanceof Error?e.message:`Normal Closure`),s.close(e))}async function y(){r.readyState!==1&&await new Promise((e,t)=>{if(d)return i();r.addEventListener(`open`,n),r.addEventListener(`close`,i);function n(){r.removeEventListener(`open`,n),r.removeEventListener(`close`,i),e(void 0)}function i(){r.removeEventListener(`open`,n),r.removeEventListener(`close`,i),t(Error(`WebSocket closed before connection could be established`))}})}return await y(),p(),r.addEventListener(`message`,h),{send:g,close:v}}}function i(e){if(typeof e.data==`string`)return new TextEncoder().encode(e.data);if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Uint8Array)return e.data;throw Error(`Unsupported message data type`)}export{r as createWebSocketAdapter};
|
|
2
|
+
//# sourceMappingURL=websocket.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket.mjs","names":[],"sources":["../../src/adapters/websocket.ts"],"sourcesContent":["import type { WireCodec, Frame, Connection, AdapterNext } from \"../psionic\";\nimport { psionicCodec } from \"../codecs/psionic\";\n\nexport type WebSocketAdapterOptions = {\n /** Optional codec to use for encoding/decoding messages. */\n codec?: WireCodec;\n /** Max frame size in bytes. Default: 1MB. */\n maxFrameSize?: number;\n /** Interval in milliseconds for sending ping messages. Default: 10000 (10 seconds). */\n pingInterval?: number;\n};\n\nexport type AdaptableWebSocket = {\n binaryType?: string;\n readyState: number;\n addEventListener: (type: any, listener: (event: any) => void) => void;\n removeEventListener: (type: any, listener: (event: any) => void) => void;\n send: (message: any) => void;\n close: (code?: number, reason?: string) => void;\n};\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\nconst pingText = new Uint8Array([112, 105, 110, 103]); // \"ping\";\nconst pongText = new Uint8Array([112, 111, 110, 103]); // \"pong\";\n\n/** Adapter for browser and standards-compatible WebSockets. */\nexport function createWebSocketAdapter(socket: AdaptableWebSocket, opts?: WebSocketAdapterOptions): (peer: AdapterNext) => Promise<Connection> {\n if (socket.binaryType === 'blob') throw new Error(\"websocket blob binary type not supported, set ws.binaryType to 'arrayBuffer'.\");\n const pingInterval = opts?.pingInterval ?? 10000;\n return async function connectPeer(peer: AdapterNext) {\n let latestMessage = Date.now();\n const codec = opts?.codec ?? psionicCodec();\n const maxFrameSize = opts?.maxFrameSize ?? (1 * 1_048_576);\n\n let dead = false;\n\n if (socket.readyState === CLOSING || socket.readyState === CLOSED) {\n throw new Error('WebSocket is already closed or closing');\n }\n\n socket.addEventListener('close', onClose);\n\n let pingTimer: ReturnType<typeof setInterval> | undefined = undefined;\n function startPing() {\n if (pingTimer) {\n clearInterval(pingTimer);\n pingTimer = undefined;\n }\n if (!dead) {\n pingTimer = setInterval(onPingTimer, pingInterval);\n }\n }\n\n function onPingTimer() {\n if (dead) {\n clearInterval(pingTimer!);\n return;\n }\n const elapsed = Date.now() - latestMessage;\n if (elapsed < pingInterval) return; // no need, we heard from them recently\n if (elapsed > pingInterval * 2) {\n clearInterval(pingTimer!);\n onError(new Error('No response to ping, assuming connection is dead'));\n return;\n }\n try {\n socket.send(pingText);\n } catch (ex) {\n onError(ex instanceof Error ? ex : new Error(String(ex)));\n }\n }\n\n function onMessage(message: MessageEvent) {\n latestMessage = Date.now();\n if (message.data instanceof Uint8Array && message.data.every((v, i) => v === pongText[i])) return; // Ignore pong responses\n if (message.data instanceof Uint8Array && message.data.every((v, i) => v === pingText[i])) { socket.send(pongText); return; } // Respond to pings\n const msg = getMessageBytes(message);\n if (msg.byteLength > maxFrameSize) {\n onError(new Error('Frame size exceeds maximum allowed'));\n return;\n }\n try {\n const messageData = codec.messageFromWire(msg);\n peer.handleMessage(messageData);\n } catch (ex) {\n onError(ex instanceof Error ? ex : new Error(String(ex)));\n }\n }\n\n function onSend(message: Frame) {\n if (dead) return;\n try {\n const messageData = codec.messageToWire(message);\n socket.send(messageData);\n } catch (ex) {\n onError(ex instanceof Error ? ex : new Error(String(ex)));\n throw ex;\n }\n }\n\n function onError(error: Error) {\n if (dead) return;\n onClose(error);\n }\n\n function onClose(error?: any) {\n if (dead) return;\n dead = true;\n clearInterval(pingTimer!);\n socket.removeEventListener('message', onMessage);\n socket.removeEventListener('close', onClose);\n if (socket.readyState === OPEN || socket.readyState === CONNECTING) {\n socket.close(error instanceof Error ? 3000 : 1000, error instanceof Error ? error.message : 'Normal Closure');\n }\n peer.close(error);\n }\n\n async function waitUntilOpen() {\n if (socket.readyState === OPEN) return;\n await new Promise((resolve, reject) => {\n if (dead) return closer();\n socket.addEventListener('open', opener);\n socket.addEventListener('close', closer);\n function opener() {\n socket.removeEventListener('open', opener);\n socket.removeEventListener('close', closer);\n resolve(undefined);\n }\n function closer() {\n socket.removeEventListener('open', opener);\n socket.removeEventListener('close', closer);\n reject(new Error('WebSocket closed before connection could be established'));\n }\n });\n }\n\n await waitUntilOpen();\n startPing();\n socket.addEventListener('message', onMessage);\n return {\n send: onSend,\n close: onClose\n };\n }\n}\n\nfunction getMessageBytes(message: MessageEvent): Uint8Array {\n if (typeof message.data === 'string') return new TextEncoder().encode(message.data);\n if (message.data instanceof ArrayBuffer) return new Uint8Array(message.data);\n if (message.data instanceof Uint8Array) return message.data;\n // no support for blobs, too much async overhead for something that can be easily handled at the application level if needed\n throw new Error('Unsupported message data type');\n}\n"],"mappings":"qDAqBA,MAKM,EAAW,IAAI,WAAW,CAAC,IAAK,IAAK,IAAK,IAAI,CAAC,CAC/C,EAAW,IAAI,WAAW,CAAC,IAAK,IAAK,IAAK,IAAI,CAAC,CAGrD,SAAgB,EAAuB,EAA4B,EAA4E,CAC3I,GAAI,EAAO,aAAe,OAAQ,MAAU,MAAM,gFAAgF,CAClI,IAAM,EAAe,GAAM,cAAgB,IAC3C,OAAO,eAA2B,EAAmB,CACjD,IAAI,EAAgB,KAAK,KAAK,CACxB,EAAQ,GAAM,OAAS,GAAc,CACrC,EAAe,GAAM,cAAiB,EAAI,QAE5C,EAAO,GAEX,GAAI,EAAO,aAAe,GAAW,EAAO,aAAe,EACvD,MAAU,MAAM,yCAAyC,CAG7D,EAAO,iBAAiB,QAAS,EAAQ,CAEzC,IAAI,EACJ,SAA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AU,CAChD,EAAO,oBAAoB,QAAS,EAAQ,EACxC,EAAO,aAAe,GAAQ,EAAO,aAAe,IACpD,EAAO,MAAM,aAAiB,MAAQ,IAAO,IAAM,aAAiB,MAAQ,EAAM,QAAU,iBAAiB,CAEjH,EAAK,MAAM,EAAM,EAGrB,eAAe,GAAgB,CACvB,EAAO,aAAe,GAC1B,MAAM,IAAI,SAAS,EAAS,IAAW,CACnC,GAAI,EAAM,OAAO,GAAQ,CACzB,EAAO,iBAAiB,OAAQ,EAAO,CACvC,EAAO,iBAAiB,QAAS,EAAO,CACxC,SAAS,GAAS,CACd,EAAO,oBAAoB,OAAQ,EAAO,CAC1C,EAAO,oBAAoB,QAAS,EAAO,CAC3C,EAAQ,IAAA,GAAU,CAEtB,SAAS,GAAS,CACd,EAAO,oBAAoB,OAAQ,EAAO,CAC1C,EAAO,oBAAoB,QAAS,EAAO,CAC3C,EAAW,MAAM,0DAA0D,CAAC,GAElF,CAMN,OAHA,MAAM,GAAe,CACrB,GAAW,CACX,EAAO,iBAAiB,UAAW,EAAU,CACtC,CACH,KAAM,EACN,MAAO,EACV,EAIT,SAAS,EAAgB,EAAmC,CACxD,GAAI,OAAO,EAAQ,MAAS,SAAU,OAAO,IAAI,aAAa,CAAC,OAAO,EAAQ,KAAK,CACnF,GAAI,EAAQ,gBAAgB,YAAa,OAAO,IAAI,WAAW,EAAQ,KAAK,CAC5E,GAAI,EAAQ,gBAAgB,WAAY,OAAO,EAAQ,KAEvD,MAAU,MAAM,gCAAgC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Adapter } from "../psionic.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/adapters/webworker.d.ts
|
|
4
|
+
type WorkerAdapterOptions = {};
|
|
5
|
+
declare function createWorkerAdapter(port: MessagePort, options?: WorkerAdapterOptions): Adapter;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { WorkerAdapterOptions, createWorkerAdapter };
|
|
8
|
+
//# sourceMappingURL=webworker.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{psionicCodec as e}from"../codecs/psionic.mjs";const t=e({maxEntities:0xffffffffffff});function n(e,n){return async function(n){let r=!1;function i(n){r||e.postMessage(t.messageToWire(n))}function a(e){e.data!==`STARTUP`&&n.handleMessage(t.messageFromWire(e.data))}function o(t){r||(r=!0,e.removeEventListener(`message`,a),e.close())}return await new Promise(t=>{e.addEventListener(`message`,n),e.postMessage(`STARTUP`),e.start();function n(r){r.data===`STARTUP`&&(e.addEventListener(`message`,a),e.removeEventListener(`message`,n),t(null))}}),{send:i,close:o}}}export{n as createWorkerAdapter};
|
|
2
|
+
//# sourceMappingURL=webworker.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webworker.mjs","names":[],"sources":["../../src/adapters/webworker.ts"],"sourcesContent":["import type { Frame, Adapter, AdapterNext } from \"../psionic\";\nimport { psionicCodec } from \"../codecs/psionic\";\n\nconst codec = psionicCodec({ maxEntities: 0xFFFFFFFFFFFF });\n\nexport type WorkerAdapterOptions = {\n};\n\nexport function createWorkerAdapter(port: MessagePort, options?: WorkerAdapterOptions): Adapter{\n return async function connectPeer(peer: AdapterNext) {\n let dead = false;\n\n function onSend(message: Frame) {\n if (dead) return;\n port.postMessage(codec.messageToWire(message));\n }\n\n function onMessage(event: MessageEvent) {\n if (event.data === 'STARTUP') return;\n peer.handleMessage(codec.messageFromWire(event.data));\n }\n\n function onClose(_err?: any) {\n if (dead) return;\n dead = true;\n port.removeEventListener('message', onMessage);\n port.close();\n }\n\n // Handshake: wait for worker to echo STARTUP before exchanging frames.\n await new Promise((resolve) => {\n port.addEventListener('message', onReadyMessage);\n port.postMessage('STARTUP');\n port.start();\n function onReadyMessage(d: MessageEvent) {\n if (d.data !== 'STARTUP') return;\n port.addEventListener('message', onMessage);\n port.removeEventListener('message', onReadyMessage);\n resolve(null);\n }\n });\n\n return {\n send: onSend,\n close: onClose\n };\n }\n};\n"],"mappings":"qDAGA,MAAM,EAAQ,EAAa,CAAE,YAAa,eAAgB,CAAC,CAK3D,SAAgB,EAAoB,EAAmB,EAAwC,CAC3F,OAAO,eAA2B,EAAmB,CACjD,IAAI,EAAO,GAEX,SAAS,EAAO,EAAgB,CACxB,GACJ,EAAK,YAAY,EAAM,cAAc,EAAQ,CAAC,CAGlD,SAAS,EAAU,EAAqB,CAChC,EAAM,OAAS,WACnB,EAAK,cAAc,EAAM,gBAAgB,EAAM,KAAK,CAAC,CAGzD,SAAS,EAAQ,EAAY,CACrB,IACJ,EAAO,GACP,EAAK,oBAAoB,UAAW,EAAU,CAC9C,EAAK,OAAO,EAgBhB,OAZA,MAAM,IAAI,QAAS,GAAY,CAC3B,EAAK,iBAAiB,UAAW,EAAe,CAChD,EAAK,YAAY,UAAU,CAC3B,EAAK,OAAO,CACZ,SAAS,EAAe,EAAiB,CACjC,EAAE,OAAS,YACf,EAAK,iBAAiB,UAAW,EAAU,CAC3C,EAAK,oBAAoB,UAAW,EAAe,CACnD,EAAQ,KAAK,IAEnB,CAEK,CACH,KAAM,EACN,MAAO,EACV"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/codecs/cbor.d.ts
|
|
2
|
+
type CborCodecOptions = {
|
|
3
|
+
/** Max entities per message. Default: 4096. */maxEntities?: number;
|
|
4
|
+
};
|
|
5
|
+
declare const cborCodec: (options?: CborCodecOptions) => {
|
|
6
|
+
type: "binary";
|
|
7
|
+
messageFromWire: (data: string | Uint8Array) => any;
|
|
8
|
+
messageToWire: (message: any[]) => Uint8Array;
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { CborCodecOptions, cborCodec };
|
|
12
|
+
//# sourceMappingURL=cbor.d.mts.map
|
package/codecs/cbor.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{AsyncFnKey as e,AsyncGenKey as t}from"../psionic.mjs";const n=32768,r=32769,i=function(i){let a=i?.maxEntities??4096;function o(i){let a=new Uint8Array(16),o=new DataView(a.buffer),s=new Uint8Array(512),c=0;function l(e){if(c+e<=s.length)return;let t=s.length*2;for(;t<c+e;)t*=2;if(t>=50331648)throw Error(`Message too large to encode`);let n=new Uint8Array(t);n.set(s),s=n}function u(e){l(e.length),s.set(e,c),c+=e.length}let d=new TextEncoder;function f(i){if(typeof i==`number`&&Number.isInteger(i)&&i>=0)p(0,i);else if(typeof i==`number`&&Number.isInteger(i)&&i<0)p(1,-1-i);else if(typeof i==`string`){let e=d.encode(i);p(3,e.length),l(e.length),s.set(e,c),c+=e.length}else if(Array.isArray(i)){p(4,i.length);for(let e of i)f(e)}else if(i===e)p(6,n),u([246]);else if(i===t)p(6,r),u([246]);else if(i&&typeof i==`object`){let e=Object.entries(i);p(5,e.length);for(let[t,n]of e){let e=d.encode(t);p(3,e.length),l(e.length),s.set(e,c),c+=e.length,f(n)}}else if(i===!1)u([244]);else if(i===!0)u([245]);else if(i===null)u([246]);else if(i===void 0)u([247]);else if(typeof i==`number`){let e=Math.fround(i),t=8;Number.isFinite(e)&&e===i&&(t=4),l(t+1),t===4?o.setFloat32(0,i,!1):o.setFloat64(0,i,!1),s[c++]=224|(t===4?26:27);for(let e=0;e<t;e++)s[c++]=a[e]}else throw Error(`Unsupported type`)}return f(i),s.subarray(0,c);function p(e,t){let n=e<<5;if(t<24){u([n|t]);return}let r=0;t>4294967295?r=3:t>65535?r=2:t>255&&(r=1);let i=[1,2,4,8][r];if(i===1)o.setUint8(0,t);else if(i===2)o.setUint16(0,t,!1);else if(i===4)o.setUint32(0,t,!1);else if(i===8)o.setBigUint64(0,BigInt(t),!1);else throw Error(`Number too large for encoding`);l(i+1),s[c++]=n|r+24;for(let e=0;e<i;e++)s[c++]=a[e]}}function s(i){function o(e){if(u+e>s.length)throw Error(`CBOR - Unexpected end of data`)}let s=typeof i==`string`?new TextEncoder().encode(i):i,c=new DataView(s.buffer,s.byteOffset,s.byteLength),l=new TextDecoder,u=0,d=0;return f();function f(){if(d>a)throw Error(`CBOR - Maximum entities exceeded`);d+=1,o(1);let i=null,m=(s[u]&224)>>5,h=s[u]&31;if(m===0)i=p(h);else if(m===1)i=-1-p(h);else if(m===3){let e=p(h);o(e),i=l.decode(s.subarray(u,u+e)),u+=e}else if(m===4){let e=p(h);i=[];for(let t=0;t<e;t++){let e=f();i.push(e)}}else if(m===5){let e=p(h);i={};for(let t=0;t<e;t++){let e=String(f()),t=f();i[e]=t}}else if(m===6){let i=p(h),a=f();return i===n?e:i===r?t:a}else if(m===7)if(h===20)i=!1;else if(h===21)i=!0;else if(h===22)i=null;else if(h===23)i=void 0;else if(h===26)o(5),u+=1,i=c.getFloat32(u,!1),u+=4;else if(h===27)o(9),u+=1,i=c.getFloat64(u,!1),u+=8;else throw Error(`CBOR - Unsupported simple value`);else throw Error(`CBOR - Unsupported major type `+m.toString(2).padStart(3,`0`));return i}function p(e){if(e<24)return u+=1,e;let t=[1,2,4,8][e-24];if(t===void 0)throw Error(`CBOR - Integer too large to decode`);o(t+1);let n;if(u+=1,t===1)n=c.getUint8(u);else if(t===2)n=c.getUint16(u,!1);else if(t===4)n=c.getUint32(u,!1);else if(t===8){let e=c.getBigUint64(u,!1);if(e>BigInt(2**53-1))throw Error(`CBOR - Number too large to safely represent in JavaScript`);n=Number(e)}else throw Error(`CBOR - Unsupported integer byte length`);return u+=t,n}}return{type:`binary`,messageFromWire:s,messageToWire:o}};export{i as cborCodec};
|
|
2
|
+
//# sourceMappingURL=cbor.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cbor.mjs","names":[],"sources":["../../src/codecs/cbor.ts"],"sourcesContent":["import { AsyncFnKey, AsyncGenKey } from \"../../src/psionic\";\n\nconst TAG_ASYNC_FN = 32768;\nconst TAG_ASYNC_GEN = 32769;\n\nexport type CborCodecOptions = {\n /** Max entities per message. Default: 4096. */\n maxEntities?: number;\n}\n\nexport const cborCodec = function (options?: CborCodecOptions) {\n const maxEntities = options?.maxEntities ?? 0x1000;\n\n function messageToWire(message: any[]): Uint8Array {\n const scratch = new Uint8Array(0x10);\n const scratchView = new DataView(scratch.buffer);\n let output = new Uint8Array(0x200);\n let at = 0;\n function ensureSpace(bytes: number) {\n if (at + bytes <= output.length) return;\n let newsize = output.length * 2;\n while (newsize < at + bytes) newsize *= 2;\n if (newsize >= 0x3000000) {\n throw new Error('Message too large to encode');\n }\n const newBuffer = new Uint8Array(newsize);\n newBuffer.set(output);\n output = newBuffer;\n }\n function append(bytes: number[]) {\n ensureSpace(bytes.length);\n output.set(bytes, at);\n at += bytes.length;\n }\n const encoder = new TextEncoder();\n function writeItem(item: any) {\n if (typeof item === 'number' && Number.isInteger(item) && item >= 0) {\n writeUInt(0b000, item);\n } else if (typeof item === 'number' && Number.isInteger(item) && item < 0) {\n writeUInt(0b001, -1 - item);\n } else if (typeof item === 'string') {\n const bytes = encoder.encode(item);\n writeUInt(0b011, bytes.length);\n ensureSpace(bytes.length);\n output.set(bytes, at);\n at += bytes.length;\n } else if (Array.isArray(item)) {\n writeUInt(0b100, item.length);\n for (const subitem of item) {\n writeItem(subitem);\n }\n } else if (item === AsyncFnKey) {\n writeUInt(0b110, TAG_ASYNC_FN);\n append([(0b111 << 5) | 22]); // null payload — only the tag matters\n } else if (item === AsyncGenKey) {\n writeUInt(0b110, TAG_ASYNC_GEN);\n append([(0b111 << 5) | 22]); // null payload — only the tag matters\n } else if (item && typeof item === 'object') {\n const entries = Object.entries(item);\n writeUInt(0b101, entries.length);\n for (const [key, value] of entries) {\n const keyBytes = encoder.encode(key);\n writeUInt(0b011, keyBytes.length);\n ensureSpace(keyBytes.length);\n output.set(keyBytes, at);\n at += keyBytes.length;\n writeItem(value);\n }\n } else if (item === false) {\n append([0b111 << 5 | 20]);\n } else if (item === true) {\n append([0b111 << 5 | 21]);\n } else if (item === null) {\n append([0b111 << 5 | 22]);\n } else if (item === undefined) {\n append([0b111 << 5 | 23]);\n } else if (typeof item === 'number') {\n const f32 = Math.fround(item);\n let bytes = 8;\n if (Number.isFinite(f32) && f32 === item) {\n bytes = 4;\n }\n ensureSpace(bytes + 1);\n if (bytes === 4) scratchView.setFloat32(0, item, false);\n else scratchView.setFloat64(0, item, false);\n output[at++] = (0b111 << 5) | (bytes === 4 ? 26 : 27);\n for (let i = 0; i < bytes; i++) output[at++] = scratch[i];\n } else {\n throw new Error('Unsupported type');\n }\n }\n writeItem(message);\n return output.subarray(0, at);\n\n function writeUInt(majorTypeValue: number, num: number) {\n const majorType = majorTypeValue << 5;\n if (num < 24) {\n append([majorType | num]);\n return;\n }\n\n let length = 0;\n if (num > 0xFFFFFFFF) {\n length = 3;\n } else if (num > 0xFFFF) {\n length = 2;\n } else if (num > 0xFF) {\n length = 1;\n }\n const bytesNeeded = [1,2,4,8][length];\n if (bytesNeeded === 1) {\n scratchView.setUint8(0, num);\n } else if (bytesNeeded === 2) {\n scratchView.setUint16(0, num, false);\n } else if (bytesNeeded === 4) {\n scratchView.setUint32(0, num, false);\n } else if (bytesNeeded === 8) {\n scratchView.setBigUint64(0, BigInt(num), false);\n } else {\n throw new Error('Number too large for encoding');\n }\n ensureSpace(bytesNeeded + 1);\n output[at++] = majorType | (length + 24);\n for (let i = 0; i < bytesNeeded; i++) output[at++] = scratch[i];\n }\n };\n\n function messageFromWire(data: string | Uint8Array): any {\n function ensureBytes(bytes: number) {\n if (i + bytes > wire.length) {\n throw new Error('CBOR - Unexpected end of data');\n }\n }\n const wire = typeof data === 'string' ? new TextEncoder().encode(data) : data;\n const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);\n const decoder = new TextDecoder();\n let i = 0, entities = 0;\n const result = takeNextValue();\n return result;\n\n function takeNextValue(): any {\n if (entities > maxEntities) throw new Error('CBOR - Maximum entities exceeded');\n entities += 1;\n ensureBytes(1);\n let value: any = null;\n const majorType = (wire[i] & 0b11100000) >> 5;\n const minorType = (wire[i] & 0b00011111);\n if (majorType === 0b000) {\n value = takeUInt(minorType);\n } else if (majorType === 0b001) {\n value = -1 - takeUInt(minorType);\n } else if (majorType === 0b011) {\n let length = takeUInt(minorType);\n ensureBytes(length);\n value = decoder.decode(wire.subarray(i, i + length));\n i += length;\n } else if (majorType === 0b100) {\n const length = takeUInt(minorType);\n value = [];\n for (let j = 0; j < length; j++) {\n const item = takeNextValue();\n value.push(item);\n }\n } else if (majorType === 0b101) {\n const length = takeUInt(minorType);\n value = {};\n for (let j = 0; j < length; j++) {\n const key = String(takeNextValue());\n const val = takeNextValue();\n value[key] = val;\n }\n } else if (majorType === 0b110) {\n const tag = takeUInt(minorType);\n const taggedvalue = takeNextValue();\n if (tag === TAG_ASYNC_FN) return AsyncFnKey;\n if (tag === TAG_ASYNC_GEN) return AsyncGenKey;\n return taggedvalue;\n } else if (majorType === 0b111) {\n if (minorType === 20) value = false;\n else if (minorType === 21) value = true;\n else if (minorType === 22) value = null;\n else if (minorType === 23) value = undefined;\n else if (minorType === 26) {\n ensureBytes(5);\n i += 1;\n value = view.getFloat32(i, false);\n i += 4;\n } else if (minorType === 27) {\n ensureBytes(9);\n i += 1;\n value = view.getFloat64(i, false);\n i += 8;\n } else {\n throw new Error('CBOR - Unsupported simple value');\n }\n } else {\n throw new Error('CBOR - Unsupported major type ' + majorType.toString(2).padStart(3, '0'));\n }\n return value;\n }\n\n function takeUInt(minorType: number): number {\n if (minorType < 24) {\n i += 1;\n return minorType;\n }\n\n const addl = minorType - 24;\n const bytes = [1,2,4,8][addl];\n if (bytes === undefined) throw new Error('CBOR - Integer too large to decode');\n ensureBytes(bytes + 1);\n let num: number;\n i += 1;\n if (bytes === 1) {\n num = view.getUint8(i);\n } else if (bytes === 2) {\n num = view.getUint16(i, false);\n } else if (bytes === 4) {\n num = view.getUint32(i, false);\n } else if (bytes === 8) {\n const bigNum = view.getBigUint64(i, false);\n if (bigNum > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error('CBOR - Number too large to safely represent in JavaScript');\n }\n num = Number(bigNum);\n } else {\n throw new Error('CBOR - Unsupported integer byte length');\n }\n i += bytes;\n return num;\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AAU,MAAM,yCAAyC,CAG7D,MADA,IAAK,EACE,GAIf,MAAO,CACH,KAAM,SACN,kBACA,gBACH"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/codecs/psionic.d.ts
|
|
2
|
+
type PsionicCodecOptions = {
|
|
3
|
+
/** Max entities per message. Default: 4096. */maxEntities?: number;
|
|
4
|
+
};
|
|
5
|
+
declare const psionicCodec: (options?: PsionicCodecOptions) => {
|
|
6
|
+
type: "text";
|
|
7
|
+
messageFromWire: (data: Uint8Array | string) => any;
|
|
8
|
+
messageToWire: (message: any[]) => Uint8Array | string;
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { PsionicCodecOptions, psionicCodec };
|
|
12
|
+
//# sourceMappingURL=psionic.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ErrorProtocolViolation as e,Keyword as t,OperationError as n}from"../psionic.mjs";const r=(r={})=>{let i=r.maxEntities??4096;function a(e){let t=String(e[0]),n;for(n=e.length-1;n>=0&&e[n]===void 0;--n);for(let r=1;r<=n;r++)t+=` `+JSON.stringify(e[r]);return t}function o(r){let a=typeof r==`string`?r:new TextDecoder().decode(r),o=0,s=0,c=0,l=0,u=[],d=0,f=!1;for(let e=0;e<=a.length;e++)if(a[e]===` `){let t=a.slice(0,e);u.push(t),d=e+1;break}for(let r=d;r<=a.length;r++){if(l>i)throw new n(`${t}: Maximum entity count exceeded`,e.code);if(a[r]===`{`&&!c)o++,l++;else if(a[r]===`}`&&!c)o--;else if(a[r]===`[`&&!c)s++,l++;else if(a[r]===`]`&&!c)s--;else if(a[r]===`\\`&&c)f=!f;else if(a[r]===`"`)f||(c=c?0:1),f=!1;else if(r===a.length&&d<r||a[r]===` `&&o===0&&s===0&&!c){l++;let e=a.slice(d,r);u.push(JSON.parse(e)),d=r+1}else f=!1}return u}return{type:`text`,messageFromWire:o,messageToWire:a}};export{r as psionicCodec};
|
|
2
|
+
//# sourceMappingURL=psionic.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"psionic.mjs","names":[],"sources":["../../src/codecs/psionic.ts"],"sourcesContent":["import { ErrorProtocolViolation, Keyword, OperationError} from \"../psionic\";\n\nexport type PsionicCodecOptions = {\n /** Max entities per message. Default: 4096. */\n maxEntities?: number;\n}\n\nexport const psionicCodec = (options: PsionicCodecOptions = {}) => {\n const maxEntities = options.maxEntities ?? 0x1000;\n\n function messageToWire(message: any[]): Uint8Array | string {\n let str = String(message[0]);\n let j: number;\n for (j = message.length - 1; j >= 0; --j) {\n if (message[j] !== undefined) break;\n }\n for (let i = 1; i <= j; i++) {\n str += ' ' + JSON.stringify(message[i]);\n }\n return str;\n };\n\n function messageFromWire(data: Uint8Array | string): any {\n const wire = typeof data === 'string' ? data : new TextDecoder().decode(data);\n let braceStack = 0, arrayStack = 0, inString = 0, entityCount = 0;\n let formatted = [];\n let start = 0;\n let escaping = false;\n // Extract the op code (first space-delimited token).\n for (let i = 0; i <= wire.length; i++) {\n if (wire[i] === ' ') {\n const value = wire.slice(0, i);\n formatted.push(value);\n start = i + 1;\n break;\n }\n }\n // Parse remaining space-delimited values, respecting JSON nesting.\n for (let i = start; i <= wire.length; i++) {\n if (entityCount > maxEntities) {\n throw new OperationError(`${Keyword}: Maximum entity count exceeded`, ErrorProtocolViolation.code);\n }\n if (wire[i] === '{' && !inString) {\n braceStack++;\n entityCount++;\n } else if (wire[i] === '}' && !inString) {\n braceStack--;\n } else if (wire[i] === '[' && !inString) {\n arrayStack++;\n entityCount++;\n } else if (wire[i] === ']' && !inString) {\n arrayStack--;\n } else if (wire[i] === '\\\\' && inString) {\n escaping = !escaping;\n } else if (wire[i] === '\"') {\n if (!escaping) inString = inString ? 0 : 1;\n escaping = false;\n } else if ((i === wire.length && start < i) || (wire[i] === ' ' && braceStack === 0 && arrayStack === 0 && !inString)) {\n entityCount++;\n const value = wire.slice(start, i);\n formatted.push(JSON.parse(value));\n start = i + 1;\n } else {\n escaping =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GAAK,CAAC,EAAW,CACnH,IACA,IAAM,EAAQ,EAAK,MAAM,EAAO,EAAE,CAClC,EAAU,KAAK,KAAK,MAAM,EAAM,CAAC,CACjC,EAAQ,EAAI,OAEZ,EAAW,GAGnB,OAAO,EAGX,MAAO,CACH,KAAM,OACN,kBACA,gBACH"}
|
package/package.json
CHANGED
|
@@ -1,30 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "psionic",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"description": "Light-weight streaming RPC library for JavaScript",
|
|
5
5
|
"license": "ISC",
|
|
6
|
-
"author": "JDP",
|
|
7
|
-
"type": "module",
|
|
8
|
-
"scripts": {
|
|
9
|
-
"test": "./tests",
|
|
10
|
-
"build": "tsdown && node make-package.js"
|
|
11
|
-
},
|
|
12
|
-
"devDependencies": {
|
|
13
|
-
"@types/node": "^25.2.3",
|
|
14
|
-
"@types/react": "^19.2.14",
|
|
15
|
-
"tsdown": "^0.20.3",
|
|
16
|
-
"typescript": "^5.9.3"
|
|
17
|
-
},
|
|
18
6
|
"exports": {
|
|
19
|
-
"./utils/react-hooks":
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
"./adapters/
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
"./
|
|
28
|
-
|
|
7
|
+
"./utils/react-hooks": {
|
|
8
|
+
"default": "./utils/react-hooks.mjs",
|
|
9
|
+
"types": "./utils/react-hooks.d.ts"
|
|
10
|
+
},
|
|
11
|
+
"./adapters/webworker": {
|
|
12
|
+
"default": "./adapters/webworker.mjs",
|
|
13
|
+
"types": "./adapters/webworker.d.ts"
|
|
14
|
+
},
|
|
15
|
+
"./adapters/reconnect": {
|
|
16
|
+
"default": "./adapters/reconnect.mjs",
|
|
17
|
+
"types": "./adapters/reconnect.d.ts"
|
|
18
|
+
},
|
|
19
|
+
"./adapters/resend": {
|
|
20
|
+
"default": "./adapters/resend.mjs",
|
|
21
|
+
"types": "./adapters/resend.d.ts"
|
|
22
|
+
},
|
|
23
|
+
"./adapters/socket": {
|
|
24
|
+
"default": "./adapters/socket.mjs",
|
|
25
|
+
"types": "./adapters/socket.d.ts"
|
|
26
|
+
},
|
|
27
|
+
"./adapters/websocket": {
|
|
28
|
+
"default": "./adapters/websocket.mjs",
|
|
29
|
+
"types": "./adapters/websocket.d.ts"
|
|
30
|
+
},
|
|
31
|
+
"./codecs/cbor": {
|
|
32
|
+
"default": "./codecs/cbor.mjs",
|
|
33
|
+
"types": "./codecs/cbor.d.ts"
|
|
34
|
+
},
|
|
35
|
+
"./codecs/psionic": {
|
|
36
|
+
"default": "./codecs/psionic.mjs",
|
|
37
|
+
"types": "./codecs/psionic.d.ts"
|
|
38
|
+
},
|
|
39
|
+
"./session": {
|
|
40
|
+
"default": "./session.mjs",
|
|
41
|
+
"types": "./session.d.ts"
|
|
42
|
+
},
|
|
43
|
+
".": {
|
|
44
|
+
"default": "./psionic.mjs",
|
|
45
|
+
"types": "./psionic.d.ts"
|
|
46
|
+
}
|
|
29
47
|
}
|
|
30
|
-
}
|
|
48
|
+
}
|
package/psionic.d.mts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { ID, OperationTypes, Session } from "./session.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/psionic.d.ts
|
|
4
|
+
declare const Keyword: "@@psion";
|
|
5
|
+
declare let CallContextSymbol: symbol;
|
|
6
|
+
declare const AsyncFnKey = "f";
|
|
7
|
+
declare const AsyncGenKey = "g";
|
|
8
|
+
declare const STATE_DISCONNECTED: 0;
|
|
9
|
+
declare const STATE_CONNECTING: 1;
|
|
10
|
+
declare const STATE_CONNECTED: 2;
|
|
11
|
+
declare const STATE_LOCAL_DESCRIBED: 3;
|
|
12
|
+
declare const STATE_REMOTE_DESCRIBED: 4;
|
|
13
|
+
declare const STATE_READY: 5;
|
|
14
|
+
type ReadyState = typeof STATE_DISCONNECTED | typeof STATE_CONNECTING | typeof STATE_CONNECTED | typeof STATE_LOCAL_DESCRIBED | typeof STATE_REMOTE_DESCRIBED | typeof STATE_READY;
|
|
15
|
+
declare const OpDescribe: "D";
|
|
16
|
+
declare const OpCall: "C";
|
|
17
|
+
declare const OpOK: "K";
|
|
18
|
+
declare const OpError: "E";
|
|
19
|
+
declare const OpIterNext: ".";
|
|
20
|
+
declare const OpIterReturn: "<";
|
|
21
|
+
declare const OpIterThrow: ">";
|
|
22
|
+
type CallFrame = [type: typeof OpCall, id: ID, name: string[], args: any[]];
|
|
23
|
+
type DescribeFrame = [type: typeof OpDescribe, id: ID, description: any, swap?: boolean];
|
|
24
|
+
type RespondFrame = [type: typeof OpOK, id: ID, result: any];
|
|
25
|
+
type ErrorFrame = [type: typeof OpError, id: ID, code: number, error?: string];
|
|
26
|
+
type IterNextFrame = [type: typeof OpIterNext, id: ID, operationId: ID, value: any];
|
|
27
|
+
type IterReturnFrame = [type: typeof OpIterReturn, id: ID, operationId: ID, value: any];
|
|
28
|
+
type IterThrowFrame = [type: typeof OpIterThrow, id: ID, operationId: ID, code: number, error?: string];
|
|
29
|
+
type Frame = DescribeFrame | CallFrame | RespondFrame | ErrorFrame | IterNextFrame | IterReturnFrame | IterThrowFrame;
|
|
30
|
+
type FrameOps = Frame[0];
|
|
31
|
+
declare const Errors: readonly [{
|
|
32
|
+
readonly code: 0;
|
|
33
|
+
readonly error: "@@psion: Remote error";
|
|
34
|
+
}, {
|
|
35
|
+
readonly code: 1;
|
|
36
|
+
readonly error: "@@psion: No remote assigned";
|
|
37
|
+
}, {
|
|
38
|
+
readonly code: 2;
|
|
39
|
+
readonly error: "@@psion: Disconnected";
|
|
40
|
+
}, {
|
|
41
|
+
readonly code: 3;
|
|
42
|
+
readonly error: "@@psion: Protocol violation";
|
|
43
|
+
}, {
|
|
44
|
+
readonly code: 4;
|
|
45
|
+
readonly error: "@@psion: Function not found";
|
|
46
|
+
}, {
|
|
47
|
+
readonly code: 5;
|
|
48
|
+
readonly error: "@@psion: Expired or invalid";
|
|
49
|
+
}, {
|
|
50
|
+
readonly code: 6;
|
|
51
|
+
readonly error: "@@psion: Rejected";
|
|
52
|
+
}];
|
|
53
|
+
declare const ErrorGeneric: {
|
|
54
|
+
readonly code: 0;
|
|
55
|
+
readonly error: "@@psion: Remote error";
|
|
56
|
+
};
|
|
57
|
+
declare const ErrorNoRemote: {
|
|
58
|
+
readonly code: 1;
|
|
59
|
+
readonly error: "@@psion: No remote assigned";
|
|
60
|
+
};
|
|
61
|
+
declare const ErrorDisconnected: {
|
|
62
|
+
readonly code: 2;
|
|
63
|
+
readonly error: "@@psion: Disconnected";
|
|
64
|
+
};
|
|
65
|
+
declare const ErrorProtocolViolation: {
|
|
66
|
+
readonly code: 3;
|
|
67
|
+
readonly error: "@@psion: Protocol violation";
|
|
68
|
+
};
|
|
69
|
+
declare const ErrorFunctionNotFound: {
|
|
70
|
+
readonly code: 4;
|
|
71
|
+
readonly error: "@@psion: Function not found";
|
|
72
|
+
};
|
|
73
|
+
declare const ErrorExpiredOrInvalid: {
|
|
74
|
+
readonly code: 5;
|
|
75
|
+
readonly error: "@@psion: Expired or invalid";
|
|
76
|
+
};
|
|
77
|
+
declare const ErrorRejected: {
|
|
78
|
+
readonly code: 6;
|
|
79
|
+
readonly error: "@@psion: Rejected";
|
|
80
|
+
};
|
|
81
|
+
type ErrorTypes = typeof Errors[number];
|
|
82
|
+
/** Codec for serializing frames to/from wire format. */
|
|
83
|
+
type WireCodec = {
|
|
84
|
+
type?: 'text' | 'binary';
|
|
85
|
+
messageToWire: (message: any[]) => string | Uint8Array;
|
|
86
|
+
messageFromWire: (wire: string | Uint8Array) => any[];
|
|
87
|
+
};
|
|
88
|
+
type BasicDescription = {
|
|
89
|
+
[key: string]: BasicValue;
|
|
90
|
+
};
|
|
91
|
+
type BasicValue = string | number | boolean | null | undefined | ((...args: any[]) => Promise<any>) | ((...args: any[]) => AsyncGenerator<any, any, any>) | BasicDescription | BasicValue[];
|
|
92
|
+
type DescriptionValue<T> = [T] extends [(string | number | boolean | null | undefined)] ? T : [T] extends [readonly (infer U)[]] ? DescriptionValue<U>[] : [T] extends [object] ? Description<T> : [T] extends [(...args: infer A extends any[]) => Promise<infer R>] ? (...args: A) => Promise<R> : [T] extends [(...args: infer A extends any[]) => AsyncGenerator<infer Y, infer R, infer N>] ? (...args: A) => AsyncGenerator<Y, R, N> : never;
|
|
93
|
+
/** Infers concrete types for functions within a description. */
|
|
94
|
+
type Description<T> = { [K in keyof T]: DescriptionValue<T[K]> };
|
|
95
|
+
type PeerEvents<RemoteAPI> = {
|
|
96
|
+
readyStateChange: (readyState: ReadyState) => void;
|
|
97
|
+
describe: (description: Description<RemoteAPI>) => void;
|
|
98
|
+
error: (err: Error) => void;
|
|
99
|
+
send: (frame: Frame) => void;
|
|
100
|
+
message: (frame: Frame) => void;
|
|
101
|
+
};
|
|
102
|
+
/** Transport-level connection to a remote peer. */
|
|
103
|
+
type Connection = {
|
|
104
|
+
/** Send a frame to the remote. */send: (frame: Frame) => void; /** Close the connection and clean up resources. */
|
|
105
|
+
close: (err?: any) => void;
|
|
106
|
+
};
|
|
107
|
+
/** Adapter interface for middleware or peers */
|
|
108
|
+
type AdapterNext = {
|
|
109
|
+
session: Session;
|
|
110
|
+
handleMessage: Peer["handleMessage"];
|
|
111
|
+
close: Peer["close"];
|
|
112
|
+
};
|
|
113
|
+
type Adapter = (peer: Peer) => Promise<Connection>;
|
|
114
|
+
type PeerOptions<LocalAPI extends BasicDescription> = {
|
|
115
|
+
/** Initial description sent to the remote on connect. */description?: LocalAPI; /** Send full error messages to remote. Default: false. */
|
|
116
|
+
sendErrorMessages?: boolean; /** Accept full error messages from remote. Default: false. */
|
|
117
|
+
receiveErrorMessages?: boolean;
|
|
118
|
+
session?: Session;
|
|
119
|
+
};
|
|
120
|
+
/** Represents a peer in the network. */
|
|
121
|
+
type Peer<RemoteAPI extends BasicDescription = any, LocalAPI extends BasicDescription = any> = {
|
|
122
|
+
session: Session; /** Send a frame to the remote peer. */
|
|
123
|
+
send(...frame: any[]): void; /** Emit an event to local listeners. */
|
|
124
|
+
emit(key: string, ...args: any[]): void; /** Handle an incoming message frame from the remote peer. */
|
|
125
|
+
handleMessage(frame: Frame): void; /** Whether to send full error messages to remote. */
|
|
126
|
+
sendErrorMessages?: boolean; /** Whether to accept full error messages from remote. */
|
|
127
|
+
receiveErrorMessages?: boolean; /** Register an event listener. */
|
|
128
|
+
on: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => () => void; /** Remove an event listener. */
|
|
129
|
+
off: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => void; /** Connect to remote, describe local state, optionally wait for remote description. */
|
|
130
|
+
connect(connect: Adapter, waitForRemoteDescribe?: boolean): Promise<void>; /** Remote's described state, with functions replaced by invokers. */
|
|
131
|
+
remote?: Description<RemoteAPI>; /** Describe local state to remote. Accepts an object or an updater function. */
|
|
132
|
+
describe: (stateChange: DescribeCallback<Description<LocalAPI>>) => Promise<void>; /** Close connection and clean up. Peer can reconnect after closing. */
|
|
133
|
+
close(ex?: any): void; /** Copy of the most recently described local state. */
|
|
134
|
+
local?: Description<LocalAPI>;
|
|
135
|
+
/**
|
|
136
|
+
* - `0` STATE_DISCONNECTED: The peer is not connected to any remote.
|
|
137
|
+
* - `1` STATE_CONNECTING: The peer is currently connecting to a new remote.
|
|
138
|
+
* - `2` STATE_CONNECTED: The peer is connected to a remote, but is not yet ready to use.
|
|
139
|
+
* - `3` STATE_LOCAL_DESCRIBED: The peer has described itself, but not received a description.
|
|
140
|
+
* - `4` STATE_REMOTE_DESCRIBED: The peer has received a description, but not described itself.
|
|
141
|
+
* - `5` STATE_READY: The peer is ready to both send and receive messages.
|
|
142
|
+
*/
|
|
143
|
+
readyState: ReadyState; /** Current remote connection, if any. */
|
|
144
|
+
connection?: Connection;
|
|
145
|
+
get ready(): boolean;
|
|
146
|
+
};
|
|
147
|
+
type EventEmitter<T> = {
|
|
148
|
+
on: <K extends keyof T>(key: K, listener: T[K]) => () => void;
|
|
149
|
+
off: <K extends keyof T>(key: K, listener: T[K]) => void;
|
|
150
|
+
};
|
|
151
|
+
/** Create a new event emitter instance. */
|
|
152
|
+
declare function createEventEmitter(): {
|
|
153
|
+
on: (key: string, listener: (...args: any[]) => void) => () => void;
|
|
154
|
+
emit: (key: string, ...args: any[]) => void;
|
|
155
|
+
off: (key: string, listener: (...args: any[]) => void) => void;
|
|
156
|
+
};
|
|
157
|
+
/** Either a full state object, or a state updater function. */
|
|
158
|
+
type DescribeCallback<T> = T | ((current: T) => T);
|
|
159
|
+
/** Events emitted by a Describer instance. */
|
|
160
|
+
type DescriberEvents<T> = {
|
|
161
|
+
/** Emitted when the state changes. */change: (description: Description<T>, previous: Description<T>, swap?: boolean) => void;
|
|
162
|
+
};
|
|
163
|
+
/** A Describer instance manages state and emits events when the state changes. */
|
|
164
|
+
type Describer<T> = EventEmitter<DescriberEvents<T>> & {
|
|
165
|
+
/** Get the complete current state. */currentState(): T; /** Describe a new state change. */
|
|
166
|
+
describe: (stateChange: DescribeCallback<T>) => [prevState: T, newState: T, swap: boolean];
|
|
167
|
+
};
|
|
168
|
+
/** Create a new Describer instance, which holds state and emits events when state changes. */
|
|
169
|
+
declare function createDescription<T>(initialState: T): Describer<T>;
|
|
170
|
+
/** Create a new disconnected peer instance. */
|
|
171
|
+
declare function createPeer<RemoteAPI extends BasicDescription = any, LocalAPI extends BasicDescription = any>(opts?: PeerOptions<LocalAPI>): Peer<RemoteAPI, LocalAPI>;
|
|
172
|
+
/** Resolves when remote has described itself. Rejects on disconnect. */
|
|
173
|
+
declare function waitUntilRemoteReady(peer: Peer): Promise<void>;
|
|
174
|
+
/** Converts a local description to wire-safe codec format (functions → sentinel symbols). */
|
|
175
|
+
declare function toCodecDescription(description: any): any;
|
|
176
|
+
/** Converts a wire-format description into a usable object (sentinel symbols → invoker functions). */
|
|
177
|
+
declare function fromCodecDescription(peer: Peer, description: any): any;
|
|
178
|
+
/** Creates a local async generator that proxies iteration to the remote. */
|
|
179
|
+
declare function createAsyncGeneratorFunction(peer: Peer, name: string[]): (...args: any[]) => AsyncGenerator<any, any, any>;
|
|
180
|
+
/** Marks a function as an async generator, setting the appropriate properties. */
|
|
181
|
+
declare function markAsAsyncGenerator<T>(wrappedAsyncGeneratorFunction: T): T;
|
|
182
|
+
/** Creates a local async function that proxies calls to the remote. */
|
|
183
|
+
declare function createAsyncFunction(peer: Peer, name: string[], waitForPeer?: boolean): (...args: any[]) => Promise<any>;
|
|
184
|
+
/** Context value that can be passed in to described functions */
|
|
185
|
+
type CallContext = {
|
|
186
|
+
peer: Peer;
|
|
187
|
+
id: ID;
|
|
188
|
+
operation: OperationTypes;
|
|
189
|
+
};
|
|
190
|
+
type HasContext<T> = {};
|
|
191
|
+
type RemoveFirstParameter<T> = T extends ((first: CallContext, ...args: infer U) => infer R) ? (...args: U) => R : never;
|
|
192
|
+
/** Wraps a function to automatically provide a call context. */
|
|
193
|
+
declare function withContext<T extends Function>(fn: T): RemoveFirstParameter<T> | HasContext<RemoveFirstParameter<T>>;
|
|
194
|
+
declare class OperationError extends Error {
|
|
195
|
+
code: number;
|
|
196
|
+
constructor(ex: ErrorTypes | string, code?: number);
|
|
197
|
+
}
|
|
198
|
+
declare function isAsyncGeneratorLike(value: any): boolean;
|
|
199
|
+
/** Deep-merges a patch into a description. Null values delete keys. */
|
|
200
|
+
declare function mergeDescriptions(original: any, patch: any): any;
|
|
201
|
+
//#endregion
|
|
202
|
+
export { Adapter, AdapterNext, AsyncFnKey, AsyncGenKey, BasicDescription, BasicValue, CallContext, CallContextSymbol, CallFrame, Connection, DescribeFrame, Description, DescriptionValue, ErrorDisconnected, ErrorExpiredOrInvalid, ErrorFrame, ErrorFunctionNotFound, ErrorGeneric, ErrorNoRemote, ErrorProtocolViolation, ErrorRejected, Errors, Frame, FrameOps, IterNextFrame, IterReturnFrame, IterThrowFrame, Keyword, OpCall, OpDescribe, OpError, OpIterNext, OpIterReturn, OpIterThrow, OpOK, OperationError, Peer, PeerEvents, PeerOptions, ReadyState, RespondFrame, STATE_CONNECTED, STATE_CONNECTING, STATE_DISCONNECTED, STATE_LOCAL_DESCRIBED, STATE_READY, STATE_REMOTE_DESCRIBED, WireCodec, createAsyncFunction, createAsyncGeneratorFunction, createDescription, createEventEmitter, createPeer, fromCodecDescription, isAsyncGeneratorLike, markAsAsyncGenerator, mergeDescriptions, toCodecDescription, waitUntilRemoteReady, withContext };
|
|
203
|
+
//# sourceMappingURL=psionic.d.mts.map
|
package/psionic.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createSession as e}from"./session.mjs";const t=`@@psion`;let n=Symbol(`call-context`);const r=`f`,i=`g`,a=0,o=1,s=2,c=3,l=4,u=5,d=`D`,f=`C`,p=`K`,m=`E`,h=`.`,g=`<`,_=`>`,v=[{code:0,error:`${t}: Remote error`},{code:1,error:`${t}: No remote assigned`},{code:2,error:`${t}: Disconnected`},{code:3,error:`${t}: Protocol violation`},{code:4,error:`${t}: Function not found`},{code:5,error:`${t}: Expired or invalid`},{code:6,error:`${t}: Rejected`}],y=v[0],b=v[1],x=v[2],S=v[3],C=v[4],w=v[5],T=v[6];function E(){let e={};function n(t,n){return e[t]||(e[t]=new Set),e[t].add(n),()=>i(t,n)}function r(n,...i){if(e[n]){let t=Array.from(e[n]);for(let e of t)try{e(...i)}catch(e){n!==`error`&&r(`error`,e instanceof Error?e:Error(String(e)))}return}n===`error`&&console.error(`${t} Unhandled error:`,...i)}function i(t,n){e[t]&&(e[t].delete(n),e[t].size===0&&delete e[t])}return{on:n,emit:r,off:i}}function D(e){let t=e,n=E();return{currentState(){return t},off:n.off,on:n.on,describe(e){let r=t,i=r,a=!0;return typeof e==`function`?(i=e(r),a=!1):i=e,t=i,i!==r&&n.emit(`change`,i,r,a),[r,i,a]}}}function O(t){let n=E(),r=t?.session??e(),i={readyState:0,session:r,emit:n.emit,on:n.on,off:n.off,send:l,get ready(){return i.readyState===5},close:c,describe:o,connect:s,sendErrorMessages:t?.sendErrorMessages??!1,receiveErrorMessages:t?.receiveErrorMessages??!1,connection:void 0,handleMessage:u};i.remote=r.remoteDescription?j(i,r.remoteDescription):i.remote,t?.description&&(i.local=t.description);let a=D(i.local);async function o(e){let[t,n,r]=a.describe(e);if(i.local=n,i.readyState<2)return;i.session.localDescription=A(n);let o=r?n??{}:J(t??{},n??{});if(o===null)return;let s=A(o);try{await R(i,`D`,s,r||void 0)}catch(e){throw c(new K(S)),e}i.readyState===4?i.readyState=5:i.readyState<3&&(i.readyState=3),i.emit(`readyStateChange`,i.readyState)}async function s(e,n=!0){c(null);let r=i.local;i.readyState=1;let a=i.connection,s=await e(i);if(i.connection!==a||i.readyState!==1){s.close();return}i.connection=s,i.local=r??t?.description,i.readyState=2,i.emit(`readyStateChange`,i.readyState),i.local&&await o(i.local),n!==!1&&await k(i)}function c(e){i.readyState!==0&&(i.readyState=0,i.emit(`readyStateChange`,i.readyState),i.connection&&i.connection.close(e))}function l(e,...t){if(!i.connection)throw new K(b);let n=[e,...t];i.connection.send(n),i.emit(`send`,n)}function u(e){i.emit(`message`,e),H(i,e).catch(e=>{i.emit(`error`,e instanceof Error?e:Error(String(e)))})}return i}function k(e){return new Promise(function(t,n){if(e.readyState>=4)return t();let r=e.on(`readyStateChange`,i);function i(e){e>=4&&(r(),t()),e===0&&(r(),n(new K(x)))}})}function A(e){let r=new WeakSet;function i(e){let a=e?.[n]??e;if(q(a))return{[t]:`g`};if(typeof a==`function`)return{[t]:`f`};if(a&&typeof a==`object`){if(!Array.isArray(a)&&Object.getPrototypeOf(a)!==Object.prototype)throw new K(S);let e=Array.isArray(a)?[]:{};if(r.has(a))throw new K(S);r.add(a);for(let n of Object.keys(a)){if(n===t)throw new K(S);e[n]=i(a[n])}return e}return a}return i(e??{})}function j(e,n){let r=new WeakSet;function i(n,a=[]){if(n?.[t]===`g`)return N(e,a);if(n?.[t]===`f`)return L(e,a);if(typeof n==`function`)throw new K(S);if(n&&typeof n==`object`){if(!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype||r.has(n))throw new K(S);r.add(n);let e=Array.isArray(n)?[]:{};for(let t of Object.keys(n))e[t]=i(n[t],[...a,t]);return e}return n}return i(n??{})}const M=(async function*(){});function N(e,t){function n(...n){let r=null,i=!1;function a(t){return e=>{if(i)return{value:void 0,done:!0};try{return t(e).catch(n)}catch(e){throw n(e),e}};function n(t){if(r&&!i){let n=F(e,t);R(e,`>`,r,n.code,n.error).catch(()=>{})}throw i=!0,t}}let o=a(async t=>{let[n,r]=await R(e,`.`,await u(),t);return r&&(i=!0),{value:n,done:!!r}}),s=a(async t=>{let n=F(e,t),[r,a]=await R(e,`>`,await u(),n.code,n.error);return a&&(i=!0),{value:r,done:!!a}}),c=a(async t=>(i=!0,await R(e,`<`,await u(),t).catch(()=>{}),{value:t,done:!0})),l={[Symbol.asyncIterator](){return this},next:o,throw:s,return:c};async function u(){if(r||i)return r;try{return r=await R(e,`C`,t,n)}catch(e){throw i=!0,e}}return l}return P(n)}function P(e){return Object.defineProperties(e,{[Symbol.toStringTag]:{value:M[Symbol.toStringTag],writable:!0},prototype:{value:M.prototype,writable:!0},constructor:{value:M.constructor,writable:!0}}),e}function F(e,t){let n=typeof t==`string`?y.code:t.code??y.code;return e.sendErrorMessages?typeof t==`object`?{code:t.code??0,error:t.message}:typeof t==`string`?{code:y.code,error:t}:y:{code:n,error:(v[n]??y).error}}function I(e,t){let n=typeof t==`string`?y.code:t.code??y.code;return e.receiveErrorMessages?new K(typeof t==`string`?t:t.message??v[n]?.error??y.error,n):new K((v[n]??y).error,n)}function L(e,t,n=!0){return async function(...r){return n&&await k(e),await R(e,`C`,t,r)}}function R(e,t,...n){return new Promise(function(r,i){if(!e.connection)return i(new K(b));let a;try{a=e.session.add(`outbound-call`,{resolve:r,reject:i},i),e.send(t,a.id,...n)}catch(e){a?.cleanup(),i(e)}})}const z={async D(e,t,n,r,i){if(typeof r!=`object`||!r||Array.isArray(r)||i!=null&&typeof i!=`boolean`)throw new K(S);let a=j(e,r);e.remote={...i?a:Y(e.remote,a)},e.session.remoteDescription=A(e.remote);let o=e.readyState;e.readyState===3?e.readyState=5:e.readyState<4&&(e.readyState=4),o!==e.readyState&&e.emit(`readyStateChange`,e.readyState),e.emit(`describe`,e.remote),e.send(`K`,n)},async C(e,t,n,r,i){if(!Array.isArray(r)||!Array.isArray(i))throw new K(S);await G(e,t,n,r,i)},K(e,t,n,r){let i=t.use(`outbound-call`,n);i&&(i.cleanup(),i.context.resolve(r))},E(e,t,n,r,i){if(typeof r!=`number`){e.close();return}let a=I(e,{code:r,message:i}),o=t.use(void 0,n);o&&o.reject(a)},async"."(e,t,n,r,i){return await B(e,t,n,r,async e=>{let t=await e.context.generator.next(i);return t.done&&e.cleanup(),[t.value,t.done?1:0]})},async"<"(e,t,n,r,i){return await B(e,t,n,r,async e=>{let t=e.context.generator;e.cleanup();let n=await t.return(i);return[n.value,n.done?1:0]},!1)},async">"(e,t,n,r,i,a){if(typeof i!=`number`||a!==void 0&&typeof a!=`string`)throw new K(S);return await B(e,t,n,r,async t=>{let n=I(e,{code:i,message:a}),r=await t.context.generator.throw(n);return r.done&&t.cleanup(),[r.value,r.done?1:0]})}};async function B(e,t,n,r,i,a=!0){if(!X(r))throw new K(S);let o=t.use(`generator`,r);if(!o)throw new K(w);if(!s()){let e=new K(C);throw o.reject(e),e}if(o.context.busy&&a)throw new K(S);try{o.context.busy=!0;let t=await i(o);if(s())e.send(`K`,n,t);else return o.reject(new K(C)),e.send(`K`,n,[void 0,1])}catch(t){throw o.cleanup(),V(e,n,t?.code,t),t}finally{o.context.busy=!1}function s(){return U(e.local,o.context.name)===o?.context.target}}function V(e,t,n,r){let i=r?.error??r?.message??r,a=(typeof r==`object`&&typeof r.code==`number`?r.code:n)??y.code;if(e.readyState>=2){let n=F(e,{code:a,message:i});e.send(`E`,t,n.code,n.error);return}a!==b.code&&e.emit(`error`,new K(String(i??v[a]?.error??y.error),a))}async function H(e,t){if(!Array.isArray(t)||typeof t[0]!=`string`||t[0].length!==1)return;if(!X(t[1]))throw new K(S);let n=z[t[0]];if(n)try{return await n(e,e.session,...t.slice(1))}catch(n){if(t[0]===`E`){e.emit(`error`,n);return}let r=F(e,n);try{e.send(`E`,t[1],r.code,r.error)}catch{}throw n}}function U(e,t){if(e==null)return null;let n=e;for(let e=0;n&&e<t.length;++e)if(Object.prototype.hasOwnProperty.call(n,t[e]))n=n[t[e]];else return null;return typeof n==`function`?n:null}function W(e){let t=()=>{throw Error(`withContext functions cannot be wrapped.`)};return t[n]=e,t}async function G(e,t,r,i,a){let o;try{let s=U(e.local,i);if(!s||typeof s!=`function`)throw new K(C);let c={peer:e,id:r},l=a;n in s&&(l=[c,...a],s=s[n]);let u=!1;if(q(s)){let n={target:s,name:i};if(o=t.add(`generator`,n,function(e){u||!n.generator||(u=!0,n.generator.return(void 0).catch(()=>{}))}),c.operation=o,!o)return e.send(`E`,r,T.code,T.error);n.generator=s(...l),e.send(`K`,r,o.id)}else{if(o=t.add(`inbound-call`,void 0,t=>{if(!u){u=!0;try{V(e,r,t?.code??y.code,t)}catch{}}}),c.operation=o,!o)return e.send(`E`,r,T.code,T.error);let n=await Promise.resolve().then(()=>s(...l));if(u)return;u=!0,o.cleanup(),r&&e.send(`K`,r,n)}}catch(t){throw o&&o.cleanup(),V(e,r,t?.code??y.code,t),t}}var K=class extends Error{code;constructor(e,t){typeof e==`string`?(super(e),this.code=t??y.code):(super(e.error),this.code=t??e.code)}};function q(e){return typeof e==`function`?!!(e.constructor?.name===`AsyncGeneratorFunction`||e.prototype?.[Symbol.asyncIterator]):!1}function J(e,t){let n=[{prev:e,next:t,path:[]}],r={},i=!1;for(;n.length>0;){let{prev:e,next:t,path:a}=n.pop();if(e===t||typeof e==`function`&&typeof t==`function`&&q(e)===q(t))continue;if(Array.isArray(e)&&Array.isArray(t))e.length===t.length?e.some((e,n)=>e!==t[n])&&(i=!0,o(t)):(i=!0,o(t));else if(typeof e==`object`&&typeof t==`object`&&e!==null&&t!==null){let r=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of r)n.push({prev:e[i],next:t[i],path:[...a,i]})}else i=!0,o(t);function o(e){let t=r;for(let e=0;e<a.length-1;++e)a[e]in t||(t[a[e]]={}),t=t[a[e]];t[a[a.length-1]]=e??null}}return i?r:null}function Y(e,t){let n={...e};for(let[e,r]of Object.entries(t))r==null?delete n[e]:Array.isArray(r)||Array.isArray(n[e])?n[e]=r:typeof r==`object`&&r&&typeof n[e]==`object`&&n[e]!==null?n[e]=Y(n[e],r):n[e]=r;return n}function X(e){return typeof e==`string`&&e.length>0&&e.length<64}export{r as AsyncFnKey,i as AsyncGenKey,n as CallContextSymbol,x as ErrorDisconnected,w as ErrorExpiredOrInvalid,C as ErrorFunctionNotFound,y as ErrorGeneric,b as ErrorNoRemote,S as ErrorProtocolViolation,T as ErrorRejected,v as Errors,t as Keyword,f as OpCall,d as OpDescribe,m as OpError,h as OpIterNext,g as OpIterReturn,_ as OpIterThrow,p as OpOK,K as OperationError,s as STATE_CONNECTED,o as STATE_CONNECTING,a as STATE_DISCONNECTED,c as STATE_LOCAL_DESCRIBED,u as STATE_READY,l as STATE_REMOTE_DESCRIBED,L as createAsyncFunction,N as createAsyncGeneratorFunction,D as createDescription,E as createEventEmitter,O as createPeer,j as fromCodecDescription,q as isAsyncGeneratorLike,P as markAsAsyncGenerator,Y as mergeDescriptions,A as toCodecDescription,k as waitUntilRemoteReady,W as withContext};
|
|
2
|
+
//# sourceMappingURL=psionic.mjs.map
|