psionic 0.3.0 → 0.3.2
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/README.md +321 -0
- package/__tests__/async-functions.ts +43 -0
- package/__tests__/async-generator-functions.ts +137 -0
- package/__tests__/convert-from-wire-format.ts +65 -0
- package/__tests__/convert-to-wire-format.ts +66 -0
- package/__tests__/describe.ts +26 -0
- package/__tests__/lib/adapter.ts +47 -0
- package/docs/extending.md +19 -0
- package/docs/protocol.md +154 -0
- package/examples/cli-chat/client.mjs +21 -0
- package/examples/cli-chat/package.json +17 -0
- package/examples/cli-chat/server.mjs +48 -0
- package/examples/cloudflare/README.md +37 -0
- package/examples/cloudflare/eslint.config.js +19 -0
- package/examples/cloudflare/index.html +13 -0
- package/examples/cloudflare/package.json +29 -0
- package/examples/cloudflare/public/vite.svg +1 -0
- package/examples/cloudflare/src/App.svelte +450 -0
- package/examples/cloudflare/src/api.ts +33 -0
- package/examples/cloudflare/src/main.ts +4 -0
- package/examples/cloudflare/tsconfig.app.json +27 -0
- package/examples/cloudflare/tsconfig.json +14 -0
- package/examples/cloudflare/tsconfig.node.json +26 -0
- package/examples/cloudflare/tsconfig.worker.json +8 -0
- package/examples/cloudflare/vite.config.ts +8 -0
- package/examples/cloudflare/worker/cloudflare.ts +115 -0
- package/examples/cloudflare/worker/index.ts +17 -0
- package/examples/cloudflare/worker/peer.ts +47 -0
- package/examples/cloudflare/worker-configuration.d.ts +10922 -0
- package/examples/cloudflare/wrangler.jsonc +58 -0
- package/examples/nodestreams/adapter.mjs +36 -0
- package/examples/nodestreams/child.mjs +20 -0
- package/examples/nodestreams/package.json +14 -0
- package/examples/nodestreams/parent.mjs +20 -0
- package/examples/reconnect/client.mjs +22 -0
- package/examples/reconnect/package.json +15 -0
- package/examples/reconnect/server.mjs +30 -0
- package/examples/tokens/client.mjs +26 -0
- package/examples/tokens/package.json +20 -0
- package/examples/tokens/server.mjs +46 -0
- package/make-package.js +23 -0
- package/package.json +24 -42
- package/src/adapters/reconnect.ts +54 -0
- package/src/adapters/resend.ts +34 -0
- package/src/adapters/socket.ts +183 -0
- package/src/adapters/websocket.ts +157 -0
- package/src/adapters/webworker.ts +48 -0
- package/src/codecs/cbor.ts +239 -0
- package/src/codecs/psionic.ts +75 -0
- package/src/psionic.ts +876 -0
- package/src/session.ts +164 -0
- package/src/utils/react-hooks.ts +48 -0
- package/tests +8 -0
- package/tsdown.config.ts +19 -0
- package/adapters/reconnect.d.mts +0 -10
- package/adapters/reconnect.mjs +0 -42
- package/adapters/reconnect.mjs.map +0 -1
- package/adapters/resend.d.mts +0 -13
- package/adapters/resend.mjs +0 -29
- package/adapters/resend.mjs.map +0 -1
- package/adapters/socket.d.mts +0 -14
- package/adapters/socket.mjs +0 -160
- package/adapters/socket.mjs.map +0 -1
- package/adapters/websocket.d.mts +0 -20
- package/adapters/websocket.mjs +0 -124
- package/adapters/websocket.mjs.map +0 -1
- package/adapters/webworker.d.mts +0 -8
- package/adapters/webworker.mjs +0 -42
- package/adapters/webworker.mjs.map +0 -1
- package/codecs/cbor.d.mts +0 -12
- package/codecs/cbor.mjs +0 -198
- package/codecs/cbor.mjs.map +0 -1
- package/codecs/psionic.d.mts +0 -12
- package/codecs/psionic.mjs +0 -57
- package/codecs/psionic.mjs.map +0 -1
- package/psionic.d.mts +0 -203
- package/psionic.mjs +0 -671
- package/psionic.mjs.map +0 -1
- package/session.d.mts +0 -63
- package/session.mjs +0 -92
- package/session.mjs.map +0 -1
- package/utils/react-hooks.d.mts +0 -24
- package/utils/react-hooks.mjs +0 -37
- package/utils/react-hooks.mjs.map +0 -1
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import type { WireCodec, Frame, AdapterNext, Adapter } from "../psionic";
|
|
2
|
+
import { Socket } from "net";
|
|
3
|
+
import { psionicCodec } from "../codecs/psionic";
|
|
4
|
+
|
|
5
|
+
export const ErrorFrameTooLarge = 'Frame size exceeds maximum allowed';
|
|
6
|
+
|
|
7
|
+
export type NodeSocketAdapterOptions = {
|
|
8
|
+
/** Optional codec to use for encoding/decoding messages. Default: `defaultCodec`. */
|
|
9
|
+
codec?: WireCodec;
|
|
10
|
+
/** Max frame size in bytes. Default: 1MB. */
|
|
11
|
+
maxFrameSize?: number;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const slice = Uint8Array.prototype.slice;
|
|
15
|
+
|
|
16
|
+
/** Adapter for Node.js TCP sockets. */
|
|
17
|
+
export function createNodeSocketAdapter(socket: Socket, opts?: NodeSocketAdapterOptions): Adapter {
|
|
18
|
+
return async function connectPeer(next: AdapterNext) {
|
|
19
|
+
const maxFrameSize = opts?.maxFrameSize ?? 1_048_576;
|
|
20
|
+
const codec: WireCodec = opts?.codec ?? psionicCodec();
|
|
21
|
+
const newline = '\n';
|
|
22
|
+
let readdata = Buffer.alloc(0x1000);
|
|
23
|
+
let readlen = 0;
|
|
24
|
+
let dead = false;
|
|
25
|
+
|
|
26
|
+
if (socket.readyState === 'closed') {
|
|
27
|
+
throw new Error('Socket is already closed');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function onSend(message: Frame) {
|
|
31
|
+
try {
|
|
32
|
+
const bytes = codec.messageToWire(message);
|
|
33
|
+
if (codec.type === 'binary') {
|
|
34
|
+
const len = toVariableByteLength(bytes.length);
|
|
35
|
+
socket.write(Buffer.concat([len, bytes as Uint8Array]));
|
|
36
|
+
} else {
|
|
37
|
+
socket.write(bytes + newline);
|
|
38
|
+
}
|
|
39
|
+
} catch (ex) {
|
|
40
|
+
teardown(ex instanceof Error ? ex : new Error(String(ex)));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function onMessage(chunk: Buffer) {
|
|
45
|
+
if (chunk.byteLength + readdata.byteLength > maxFrameSize) {
|
|
46
|
+
teardown(new Error(ErrorFrameTooLarge));
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (chunk.byteLength > readdata.length - readlen) {
|
|
50
|
+
const newBuffer = Buffer.alloc(Math.min(maxFrameSize, readdata.length) * 2);
|
|
51
|
+
readdata.copy(newBuffer, 0, 0, readlen);
|
|
52
|
+
readdata = newBuffer;
|
|
53
|
+
}
|
|
54
|
+
chunk.copy(readdata, readlen);
|
|
55
|
+
readlen += chunk.byteLength;
|
|
56
|
+
let i = 0;
|
|
57
|
+
while (i < readlen) {
|
|
58
|
+
let messageData: any;
|
|
59
|
+
let view = new DataView(readdata.buffer, i, readlen - i);
|
|
60
|
+
if (codec.type === 'binary') {
|
|
61
|
+
if (view.byteLength < 4) break;
|
|
62
|
+
const nlength = checkNumberLength(view);
|
|
63
|
+
const length = readNumber(view, nlength);
|
|
64
|
+
if (length === -1) break;
|
|
65
|
+
if (length > maxFrameSize) {
|
|
66
|
+
teardown(new Error(ErrorFrameTooLarge));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (view.byteLength < nlength + length) break;
|
|
70
|
+
|
|
71
|
+
const data = view.buffer.slice(nlength + view.byteOffset, nlength + view.byteOffset + length);
|
|
72
|
+
i += nlength + length;
|
|
73
|
+
messageData = codec.messageFromWire(new Uint8Array(data));
|
|
74
|
+
try {
|
|
75
|
+
next.handleMessage(messageData as Frame);
|
|
76
|
+
} catch (ex) {
|
|
77
|
+
teardown(ex instanceof Error ? ex : new Error(String(ex)));
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
} else {
|
|
81
|
+
const lineIndex = readdata.indexOf(0x0A, i);
|
|
82
|
+
if (lineIndex === -1 && readlen > maxFrameSize) {
|
|
83
|
+
teardown(new Error(ErrorFrameTooLarge));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (lineIndex === -1) break;
|
|
87
|
+
const data = slice.call(readdata, i, lineIndex);
|
|
88
|
+
i = lineIndex + 1;
|
|
89
|
+
try {
|
|
90
|
+
const messageData = codec.messageFromWire(data);
|
|
91
|
+
next.handleMessage(messageData as Frame);
|
|
92
|
+
} catch (ex) {
|
|
93
|
+
teardown(ex instanceof Error ? ex : new Error(String(ex)));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
readdata.copy(readdata, 0, i, readlen);
|
|
100
|
+
readlen -= i;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function teardown(ex: any) {
|
|
104
|
+
onClose(ex);
|
|
105
|
+
throw ex;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function onClose(ex: any) {
|
|
109
|
+
if (dead) return;
|
|
110
|
+
dead = true;
|
|
111
|
+
socket.off('data', onMessage);
|
|
112
|
+
socket.off('close', onClose);
|
|
113
|
+
socket.destroy(ex);
|
|
114
|
+
next.close(ex);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
socket.on('data', onMessage);
|
|
118
|
+
socket.on('close', ex => onClose(ex ?? new Error('Socket closed')));
|
|
119
|
+
|
|
120
|
+
async function waitUntilOpen(): Promise<void> {
|
|
121
|
+
return await new Promise((resolve, reject) => {
|
|
122
|
+
if (socket.readyState === 'open') return resolve();
|
|
123
|
+
socket.once('open', opener);
|
|
124
|
+
socket.once('connect', opener);
|
|
125
|
+
socket.once('close', closer);
|
|
126
|
+
function opener() {
|
|
127
|
+
socket.off('open', opener);
|
|
128
|
+
socket.off('connect', opener);
|
|
129
|
+
socket.off('close', closer);
|
|
130
|
+
resolve();
|
|
131
|
+
}
|
|
132
|
+
function closer() {
|
|
133
|
+
socket.off('open', opener);
|
|
134
|
+
socket.off('close', closer);
|
|
135
|
+
reject(new Error('Socket closed before connection could be established'));
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
await waitUntilOpen();
|
|
141
|
+
return {
|
|
142
|
+
send: onSend,
|
|
143
|
+
close: onClose
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Encodes a length as a 1/2/4-byte variable-length integer (2-bit length prefix). */
|
|
149
|
+
function toVariableByteLength(value: number): Uint8Array {
|
|
150
|
+
if (value < 64) {
|
|
151
|
+
const view = new DataView(new ArrayBuffer(1));
|
|
152
|
+
view.setUint8(0, value);
|
|
153
|
+
return new Uint8Array(view.buffer);
|
|
154
|
+
}
|
|
155
|
+
if (value < (0b01 << 14)) {
|
|
156
|
+
const view = new DataView(new ArrayBuffer(2));
|
|
157
|
+
view.setUint16(0, (0b01 << 14) | value);
|
|
158
|
+
return new Uint8Array(view.buffer);
|
|
159
|
+
}
|
|
160
|
+
if (value < (0b01 << 30)) {
|
|
161
|
+
const view = new DataView(new ArrayBuffer(4));
|
|
162
|
+
view.setUint32(0, (0b10 << 30) | value);
|
|
163
|
+
return new Uint8Array(view.buffer);
|
|
164
|
+
}
|
|
165
|
+
throw new Error('Value too large for variable byte length encoding');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function checkNumberLength(value: DataView) {
|
|
169
|
+
switch (value.getUint8(0) >> 6) {
|
|
170
|
+
case 0b00: return 1;
|
|
171
|
+
case 0b01: return 2;
|
|
172
|
+
case 0b10: return 4;
|
|
173
|
+
}
|
|
174
|
+
return Number.MAX_SAFE_INTEGER;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function readNumber(value: DataView, bytes: number) {
|
|
178
|
+
if (bytes > value.byteLength - bytes - 1) return -1;
|
|
179
|
+
if (bytes === 1) return value.getUint8(0) & 0b0011_1111;
|
|
180
|
+
if (bytes === 2) return value.getUint16(0) & 0b0011_1111_1111_1111;
|
|
181
|
+
if (bytes === 4) return value.getUint32(0) & 0b0011_1111_1111_1111_1111_1111_1111_1111;
|
|
182
|
+
return Number.MAX_SAFE_INTEGER;
|
|
183
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import type { WireCodec, Frame, Connection, AdapterNext } from "../psionic";
|
|
2
|
+
import { psionicCodec } from "../codecs/psionic";
|
|
3
|
+
|
|
4
|
+
export type WebSocketAdapterOptions = {
|
|
5
|
+
/** Optional codec to use for encoding/decoding messages. */
|
|
6
|
+
codec?: WireCodec;
|
|
7
|
+
/** Max frame size in bytes. Default: 1MB. */
|
|
8
|
+
maxFrameSize?: number;
|
|
9
|
+
/** Interval in milliseconds for sending ping messages. Default: 10000 (10 seconds). */
|
|
10
|
+
pingInterval?: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type AdaptableWebSocket = {
|
|
14
|
+
binaryType?: string;
|
|
15
|
+
readyState: number;
|
|
16
|
+
addEventListener: (type: any, listener: (event: any) => void) => void;
|
|
17
|
+
removeEventListener: (type: any, listener: (event: any) => void) => void;
|
|
18
|
+
send: (message: any) => void;
|
|
19
|
+
close: (code?: number, reason?: string) => void;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const CONNECTING = 0;
|
|
23
|
+
const OPEN = 1;
|
|
24
|
+
const CLOSING = 2;
|
|
25
|
+
const CLOSED = 3;
|
|
26
|
+
|
|
27
|
+
const pingText = new Uint8Array([112, 105, 110, 103]); // "ping";
|
|
28
|
+
const pongText = new Uint8Array([112, 111, 110, 103]); // "pong";
|
|
29
|
+
|
|
30
|
+
/** Adapter for browser and standards-compatible WebSockets. */
|
|
31
|
+
export function createWebSocketAdapter(socket: AdaptableWebSocket, opts?: WebSocketAdapterOptions): (peer: AdapterNext) => Promise<Connection> {
|
|
32
|
+
if (socket.binaryType === 'blob') throw new Error("websocket blob binary type not supported, set ws.binaryType to 'arrayBuffer'.");
|
|
33
|
+
const pingInterval = opts?.pingInterval ?? 10000;
|
|
34
|
+
return async function connectPeer(peer: AdapterNext) {
|
|
35
|
+
let latestMessage = Date.now();
|
|
36
|
+
const codec = opts?.codec ?? psionicCodec();
|
|
37
|
+
const maxFrameSize = opts?.maxFrameSize ?? (1 * 1_048_576);
|
|
38
|
+
|
|
39
|
+
let dead = false;
|
|
40
|
+
|
|
41
|
+
if (socket.readyState === CLOSING || socket.readyState === CLOSED) {
|
|
42
|
+
throw new Error('WebSocket is already closed or closing');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
socket.addEventListener('close', onClose);
|
|
46
|
+
|
|
47
|
+
let pingTimer: ReturnType<typeof setInterval> | undefined = undefined;
|
|
48
|
+
function startPing() {
|
|
49
|
+
if (pingTimer) {
|
|
50
|
+
clearInterval(pingTimer);
|
|
51
|
+
pingTimer = undefined;
|
|
52
|
+
}
|
|
53
|
+
if (!dead) {
|
|
54
|
+
pingTimer = setInterval(onPingTimer, pingInterval);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function onPingTimer() {
|
|
59
|
+
if (dead) {
|
|
60
|
+
clearInterval(pingTimer!);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const elapsed = Date.now() - latestMessage;
|
|
64
|
+
if (elapsed < pingInterval) return; // no need, we heard from them recently
|
|
65
|
+
if (elapsed > pingInterval * 2) {
|
|
66
|
+
clearInterval(pingTimer!);
|
|
67
|
+
onError(new Error('No response to ping, assuming connection is dead'));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
socket.send(pingText);
|
|
72
|
+
} catch (ex) {
|
|
73
|
+
onError(ex instanceof Error ? ex : new Error(String(ex)));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function onMessage(message: MessageEvent) {
|
|
78
|
+
latestMessage = Date.now();
|
|
79
|
+
if (message.data instanceof Uint8Array && message.data.every((v, i) => v === pongText[i])) return; // Ignore pong responses
|
|
80
|
+
if (message.data instanceof Uint8Array && message.data.every((v, i) => v === pingText[i])) { socket.send(pongText); return; } // Respond to pings
|
|
81
|
+
const msg = getMessageBytes(message);
|
|
82
|
+
if (msg.byteLength > maxFrameSize) {
|
|
83
|
+
onError(new Error('Frame size exceeds maximum allowed'));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
const messageData = codec.messageFromWire(msg);
|
|
88
|
+
peer.handleMessage(messageData);
|
|
89
|
+
} catch (ex) {
|
|
90
|
+
onError(ex instanceof Error ? ex : new Error(String(ex)));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function onSend(message: Frame) {
|
|
95
|
+
if (dead) return;
|
|
96
|
+
try {
|
|
97
|
+
const messageData = codec.messageToWire(message);
|
|
98
|
+
socket.send(messageData);
|
|
99
|
+
} catch (ex) {
|
|
100
|
+
onError(ex instanceof Error ? ex : new Error(String(ex)));
|
|
101
|
+
throw ex;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function onError(error: Error) {
|
|
106
|
+
if (dead) return;
|
|
107
|
+
onClose(error);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function onClose(error?: any) {
|
|
111
|
+
if (dead) return;
|
|
112
|
+
dead = true;
|
|
113
|
+
clearInterval(pingTimer!);
|
|
114
|
+
socket.removeEventListener('message', onMessage);
|
|
115
|
+
socket.removeEventListener('close', onClose);
|
|
116
|
+
if (socket.readyState === OPEN || socket.readyState === CONNECTING) {
|
|
117
|
+
socket.close(error instanceof Error ? 3000 : 1000, error instanceof Error ? error.message : 'Normal Closure');
|
|
118
|
+
}
|
|
119
|
+
peer.close(error);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function waitUntilOpen() {
|
|
123
|
+
if (socket.readyState === OPEN) return;
|
|
124
|
+
await new Promise((resolve, reject) => {
|
|
125
|
+
if (dead) return closer();
|
|
126
|
+
socket.addEventListener('open', opener);
|
|
127
|
+
socket.addEventListener('close', closer);
|
|
128
|
+
function opener() {
|
|
129
|
+
socket.removeEventListener('open', opener);
|
|
130
|
+
socket.removeEventListener('close', closer);
|
|
131
|
+
resolve(undefined);
|
|
132
|
+
}
|
|
133
|
+
function closer() {
|
|
134
|
+
socket.removeEventListener('open', opener);
|
|
135
|
+
socket.removeEventListener('close', closer);
|
|
136
|
+
reject(new Error('WebSocket closed before connection could be established'));
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
await waitUntilOpen();
|
|
142
|
+
startPing();
|
|
143
|
+
socket.addEventListener('message', onMessage);
|
|
144
|
+
return {
|
|
145
|
+
send: onSend,
|
|
146
|
+
close: onClose
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function getMessageBytes(message: MessageEvent): Uint8Array {
|
|
152
|
+
if (typeof message.data === 'string') return new TextEncoder().encode(message.data);
|
|
153
|
+
if (message.data instanceof ArrayBuffer) return new Uint8Array(message.data);
|
|
154
|
+
if (message.data instanceof Uint8Array) return message.data;
|
|
155
|
+
// no support for blobs, too much async overhead for something that can be easily handled at the application level if needed
|
|
156
|
+
throw new Error('Unsupported message data type');
|
|
157
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Frame, Adapter, AdapterNext } from "../psionic";
|
|
2
|
+
import { psionicCodec } from "../codecs/psionic";
|
|
3
|
+
|
|
4
|
+
const codec = psionicCodec({ maxEntities: 0xFFFFFFFFFFFF });
|
|
5
|
+
|
|
6
|
+
export type WorkerAdapterOptions = {
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export function createWorkerAdapter(port: MessagePort, options?: WorkerAdapterOptions): Adapter{
|
|
10
|
+
return async function connectPeer(peer: AdapterNext) {
|
|
11
|
+
let dead = false;
|
|
12
|
+
|
|
13
|
+
function onSend(message: Frame) {
|
|
14
|
+
if (dead) return;
|
|
15
|
+
port.postMessage(codec.messageToWire(message));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function onMessage(event: MessageEvent) {
|
|
19
|
+
if (event.data === 'STARTUP') return;
|
|
20
|
+
peer.handleMessage(codec.messageFromWire(event.data));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function onClose(_err?: any) {
|
|
24
|
+
if (dead) return;
|
|
25
|
+
dead = true;
|
|
26
|
+
port.removeEventListener('message', onMessage);
|
|
27
|
+
port.close();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Handshake: wait for worker to echo STARTUP before exchanging frames.
|
|
31
|
+
await new Promise((resolve) => {
|
|
32
|
+
port.addEventListener('message', onReadyMessage);
|
|
33
|
+
port.postMessage('STARTUP');
|
|
34
|
+
port.start();
|
|
35
|
+
function onReadyMessage(d: MessageEvent) {
|
|
36
|
+
if (d.data !== 'STARTUP') return;
|
|
37
|
+
port.addEventListener('message', onMessage);
|
|
38
|
+
port.removeEventListener('message', onReadyMessage);
|
|
39
|
+
resolve(null);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
send: onSend,
|
|
45
|
+
close: onClose
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
};
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { AsyncFnKey, AsyncGenKey } from "../../src/psionic";
|
|
2
|
+
|
|
3
|
+
const TAG_ASYNC_FN = 32768;
|
|
4
|
+
const TAG_ASYNC_GEN = 32769;
|
|
5
|
+
|
|
6
|
+
export type CborCodecOptions = {
|
|
7
|
+
/** Max entities per message. Default: 4096. */
|
|
8
|
+
maxEntities?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const cborCodec = function (options?: CborCodecOptions) {
|
|
12
|
+
const maxEntities = options?.maxEntities ?? 0x1000;
|
|
13
|
+
|
|
14
|
+
function messageToWire(message: any[]): Uint8Array {
|
|
15
|
+
const scratch = new Uint8Array(0x10);
|
|
16
|
+
const scratchView = new DataView(scratch.buffer);
|
|
17
|
+
let output = new Uint8Array(0x200);
|
|
18
|
+
let at = 0;
|
|
19
|
+
function ensureSpace(bytes: number) {
|
|
20
|
+
if (at + bytes <= output.length) return;
|
|
21
|
+
let newsize = output.length * 2;
|
|
22
|
+
while (newsize < at + bytes) newsize *= 2;
|
|
23
|
+
if (newsize >= 0x3000000) {
|
|
24
|
+
throw new Error('Message too large to encode');
|
|
25
|
+
}
|
|
26
|
+
const newBuffer = new Uint8Array(newsize);
|
|
27
|
+
newBuffer.set(output);
|
|
28
|
+
output = newBuffer;
|
|
29
|
+
}
|
|
30
|
+
function append(bytes: number[]) {
|
|
31
|
+
ensureSpace(bytes.length);
|
|
32
|
+
output.set(bytes, at);
|
|
33
|
+
at += bytes.length;
|
|
34
|
+
}
|
|
35
|
+
const encoder = new TextEncoder();
|
|
36
|
+
function writeItem(item: any) {
|
|
37
|
+
if (typeof item === 'number' && Number.isInteger(item) && item >= 0) {
|
|
38
|
+
writeUInt(0b000, item);
|
|
39
|
+
} else if (typeof item === 'number' && Number.isInteger(item) && item < 0) {
|
|
40
|
+
writeUInt(0b001, -1 - item);
|
|
41
|
+
} else if (typeof item === 'string') {
|
|
42
|
+
const bytes = encoder.encode(item);
|
|
43
|
+
writeUInt(0b011, bytes.length);
|
|
44
|
+
ensureSpace(bytes.length);
|
|
45
|
+
output.set(bytes, at);
|
|
46
|
+
at += bytes.length;
|
|
47
|
+
} else if (Array.isArray(item)) {
|
|
48
|
+
writeUInt(0b100, item.length);
|
|
49
|
+
for (const subitem of item) {
|
|
50
|
+
writeItem(subitem);
|
|
51
|
+
}
|
|
52
|
+
} else if (item === AsyncFnKey) {
|
|
53
|
+
writeUInt(0b110, TAG_ASYNC_FN);
|
|
54
|
+
append([(0b111 << 5) | 22]); // null payload — only the tag matters
|
|
55
|
+
} else if (item === AsyncGenKey) {
|
|
56
|
+
writeUInt(0b110, TAG_ASYNC_GEN);
|
|
57
|
+
append([(0b111 << 5) | 22]); // null payload — only the tag matters
|
|
58
|
+
} else if (item && typeof item === 'object') {
|
|
59
|
+
const entries = Object.entries(item);
|
|
60
|
+
writeUInt(0b101, entries.length);
|
|
61
|
+
for (const [key, value] of entries) {
|
|
62
|
+
const keyBytes = encoder.encode(key);
|
|
63
|
+
writeUInt(0b011, keyBytes.length);
|
|
64
|
+
ensureSpace(keyBytes.length);
|
|
65
|
+
output.set(keyBytes, at);
|
|
66
|
+
at += keyBytes.length;
|
|
67
|
+
writeItem(value);
|
|
68
|
+
}
|
|
69
|
+
} else if (item === false) {
|
|
70
|
+
append([0b111 << 5 | 20]);
|
|
71
|
+
} else if (item === true) {
|
|
72
|
+
append([0b111 << 5 | 21]);
|
|
73
|
+
} else if (item === null) {
|
|
74
|
+
append([0b111 << 5 | 22]);
|
|
75
|
+
} else if (item === undefined) {
|
|
76
|
+
append([0b111 << 5 | 23]);
|
|
77
|
+
} else if (typeof item === 'number') {
|
|
78
|
+
const f32 = Math.fround(item);
|
|
79
|
+
let bytes = 8;
|
|
80
|
+
if (Number.isFinite(f32) && f32 === item) {
|
|
81
|
+
bytes = 4;
|
|
82
|
+
}
|
|
83
|
+
ensureSpace(bytes + 1);
|
|
84
|
+
if (bytes === 4) scratchView.setFloat32(0, item, false);
|
|
85
|
+
else scratchView.setFloat64(0, item, false);
|
|
86
|
+
output[at++] = (0b111 << 5) | (bytes === 4 ? 26 : 27);
|
|
87
|
+
for (let i = 0; i < bytes; i++) output[at++] = scratch[i];
|
|
88
|
+
} else {
|
|
89
|
+
throw new Error('Unsupported type');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
writeItem(message);
|
|
93
|
+
return output.subarray(0, at);
|
|
94
|
+
|
|
95
|
+
function writeUInt(majorTypeValue: number, num: number) {
|
|
96
|
+
const majorType = majorTypeValue << 5;
|
|
97
|
+
if (num < 24) {
|
|
98
|
+
append([majorType | num]);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let length = 0;
|
|
103
|
+
if (num > 0xFFFFFFFF) {
|
|
104
|
+
length = 3;
|
|
105
|
+
} else if (num > 0xFFFF) {
|
|
106
|
+
length = 2;
|
|
107
|
+
} else if (num > 0xFF) {
|
|
108
|
+
length = 1;
|
|
109
|
+
}
|
|
110
|
+
const bytesNeeded = [1,2,4,8][length];
|
|
111
|
+
if (bytesNeeded === 1) {
|
|
112
|
+
scratchView.setUint8(0, num);
|
|
113
|
+
} else if (bytesNeeded === 2) {
|
|
114
|
+
scratchView.setUint16(0, num, false);
|
|
115
|
+
} else if (bytesNeeded === 4) {
|
|
116
|
+
scratchView.setUint32(0, num, false);
|
|
117
|
+
} else if (bytesNeeded === 8) {
|
|
118
|
+
scratchView.setBigUint64(0, BigInt(num), false);
|
|
119
|
+
} else {
|
|
120
|
+
throw new Error('Number too large for encoding');
|
|
121
|
+
}
|
|
122
|
+
ensureSpace(bytesNeeded + 1);
|
|
123
|
+
output[at++] = majorType | (length + 24);
|
|
124
|
+
for (let i = 0; i < bytesNeeded; i++) output[at++] = scratch[i];
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
function messageFromWire(data: string | Uint8Array): any {
|
|
129
|
+
function ensureBytes(bytes: number) {
|
|
130
|
+
if (i + bytes > wire.length) {
|
|
131
|
+
throw new Error('CBOR - Unexpected end of data');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const wire = typeof data === 'string' ? new TextEncoder().encode(data) : data;
|
|
135
|
+
const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
|
|
136
|
+
const decoder = new TextDecoder();
|
|
137
|
+
let i = 0, entities = 0;
|
|
138
|
+
const result = takeNextValue();
|
|
139
|
+
return result;
|
|
140
|
+
|
|
141
|
+
function takeNextValue(): any {
|
|
142
|
+
if (entities > maxEntities) throw new Error('CBOR - Maximum entities exceeded');
|
|
143
|
+
entities += 1;
|
|
144
|
+
ensureBytes(1);
|
|
145
|
+
let value: any = null;
|
|
146
|
+
const majorType = (wire[i] & 0b11100000) >> 5;
|
|
147
|
+
const minorType = (wire[i] & 0b00011111);
|
|
148
|
+
if (majorType === 0b000) {
|
|
149
|
+
value = takeUInt(minorType);
|
|
150
|
+
} else if (majorType === 0b001) {
|
|
151
|
+
value = -1 - takeUInt(minorType);
|
|
152
|
+
} else if (majorType === 0b011) {
|
|
153
|
+
let length = takeUInt(minorType);
|
|
154
|
+
ensureBytes(length);
|
|
155
|
+
value = decoder.decode(wire.subarray(i, i + length));
|
|
156
|
+
i += length;
|
|
157
|
+
} else if (majorType === 0b100) {
|
|
158
|
+
const length = takeUInt(minorType);
|
|
159
|
+
value = [];
|
|
160
|
+
for (let j = 0; j < length; j++) {
|
|
161
|
+
const item = takeNextValue();
|
|
162
|
+
value.push(item);
|
|
163
|
+
}
|
|
164
|
+
} else if (majorType === 0b101) {
|
|
165
|
+
const length = takeUInt(minorType);
|
|
166
|
+
value = {};
|
|
167
|
+
for (let j = 0; j < length; j++) {
|
|
168
|
+
const key = String(takeNextValue());
|
|
169
|
+
const val = takeNextValue();
|
|
170
|
+
value[key] = val;
|
|
171
|
+
}
|
|
172
|
+
} else if (majorType === 0b110) {
|
|
173
|
+
const tag = takeUInt(minorType);
|
|
174
|
+
const taggedvalue = takeNextValue();
|
|
175
|
+
if (tag === TAG_ASYNC_FN) return AsyncFnKey;
|
|
176
|
+
if (tag === TAG_ASYNC_GEN) return AsyncGenKey;
|
|
177
|
+
return taggedvalue;
|
|
178
|
+
} else if (majorType === 0b111) {
|
|
179
|
+
if (minorType === 20) value = false;
|
|
180
|
+
else if (minorType === 21) value = true;
|
|
181
|
+
else if (minorType === 22) value = null;
|
|
182
|
+
else if (minorType === 23) value = undefined;
|
|
183
|
+
else if (minorType === 26) {
|
|
184
|
+
ensureBytes(5);
|
|
185
|
+
i += 1;
|
|
186
|
+
value = view.getFloat32(i, false);
|
|
187
|
+
i += 4;
|
|
188
|
+
} else if (minorType === 27) {
|
|
189
|
+
ensureBytes(9);
|
|
190
|
+
i += 1;
|
|
191
|
+
value = view.getFloat64(i, false);
|
|
192
|
+
i += 8;
|
|
193
|
+
} else {
|
|
194
|
+
throw new Error('CBOR - Unsupported simple value');
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
throw new Error('CBOR - Unsupported major type ' + majorType.toString(2).padStart(3, '0'));
|
|
198
|
+
}
|
|
199
|
+
return value;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function takeUInt(minorType: number): number {
|
|
203
|
+
if (minorType < 24) {
|
|
204
|
+
i += 1;
|
|
205
|
+
return minorType;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const addl = minorType - 24;
|
|
209
|
+
const bytes = [1,2,4,8][addl];
|
|
210
|
+
if (bytes === undefined) throw new Error('CBOR - Integer too large to decode');
|
|
211
|
+
ensureBytes(bytes + 1);
|
|
212
|
+
let num: number;
|
|
213
|
+
i += 1;
|
|
214
|
+
if (bytes === 1) {
|
|
215
|
+
num = view.getUint8(i);
|
|
216
|
+
} else if (bytes === 2) {
|
|
217
|
+
num = view.getUint16(i, false);
|
|
218
|
+
} else if (bytes === 4) {
|
|
219
|
+
num = view.getUint32(i, false);
|
|
220
|
+
} else if (bytes === 8) {
|
|
221
|
+
const bigNum = view.getBigUint64(i, false);
|
|
222
|
+
if (bigNum > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
223
|
+
throw new Error('CBOR - Number too large to safely represent in JavaScript');
|
|
224
|
+
}
|
|
225
|
+
num = Number(bigNum);
|
|
226
|
+
} else {
|
|
227
|
+
throw new Error('CBOR - Unsupported integer byte length');
|
|
228
|
+
}
|
|
229
|
+
i += bytes;
|
|
230
|
+
return num;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return {
|
|
235
|
+
type: 'binary' as const,
|
|
236
|
+
messageFromWire,
|
|
237
|
+
messageToWire
|
|
238
|
+
};
|
|
239
|
+
}
|