psionic 0.3.1 → 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.
Files changed (84) hide show
  1. package/README.md +321 -0
  2. package/__tests__/async-functions.ts +43 -0
  3. package/__tests__/async-generator-functions.ts +137 -0
  4. package/__tests__/convert-from-wire-format.ts +65 -0
  5. package/__tests__/convert-to-wire-format.ts +66 -0
  6. package/__tests__/describe.ts +26 -0
  7. package/__tests__/lib/adapter.ts +47 -0
  8. package/docs/extending.md +19 -0
  9. package/docs/protocol.md +154 -0
  10. package/examples/cli-chat/client.mjs +21 -0
  11. package/examples/cli-chat/package.json +17 -0
  12. package/examples/cli-chat/server.mjs +48 -0
  13. package/examples/cloudflare/README.md +37 -0
  14. package/examples/cloudflare/eslint.config.js +19 -0
  15. package/examples/cloudflare/index.html +13 -0
  16. package/examples/cloudflare/package.json +29 -0
  17. package/examples/cloudflare/public/vite.svg +1 -0
  18. package/examples/cloudflare/src/App.svelte +450 -0
  19. package/examples/cloudflare/src/api.ts +33 -0
  20. package/examples/cloudflare/src/main.ts +4 -0
  21. package/examples/cloudflare/tsconfig.app.json +27 -0
  22. package/examples/cloudflare/tsconfig.json +14 -0
  23. package/examples/cloudflare/tsconfig.node.json +26 -0
  24. package/examples/cloudflare/tsconfig.worker.json +8 -0
  25. package/examples/cloudflare/vite.config.ts +8 -0
  26. package/examples/cloudflare/worker/cloudflare.ts +115 -0
  27. package/examples/cloudflare/worker/index.ts +17 -0
  28. package/examples/cloudflare/worker/peer.ts +47 -0
  29. package/examples/cloudflare/worker-configuration.d.ts +10922 -0
  30. package/examples/cloudflare/wrangler.jsonc +58 -0
  31. package/examples/nodestreams/adapter.mjs +36 -0
  32. package/examples/nodestreams/child.mjs +20 -0
  33. package/examples/nodestreams/package.json +14 -0
  34. package/examples/nodestreams/parent.mjs +20 -0
  35. package/examples/reconnect/client.mjs +22 -0
  36. package/examples/reconnect/package.json +15 -0
  37. package/examples/reconnect/server.mjs +30 -0
  38. package/examples/tokens/client.mjs +26 -0
  39. package/examples/tokens/package.json +20 -0
  40. package/examples/tokens/server.mjs +46 -0
  41. package/make-package.js +23 -0
  42. package/package.json +24 -42
  43. package/src/adapters/reconnect.ts +54 -0
  44. package/src/adapters/resend.ts +34 -0
  45. package/src/adapters/socket.ts +183 -0
  46. package/src/adapters/websocket.ts +157 -0
  47. package/src/adapters/webworker.ts +48 -0
  48. package/src/codecs/cbor.ts +239 -0
  49. package/src/codecs/psionic.ts +75 -0
  50. package/src/psionic.ts +876 -0
  51. package/src/session.ts +164 -0
  52. package/src/utils/react-hooks.ts +48 -0
  53. package/tests +8 -0
  54. package/tsdown.config.ts +19 -0
  55. package/adapters/reconnect.d.mts +0 -10
  56. package/adapters/reconnect.mjs +0 -42
  57. package/adapters/reconnect.mjs.map +0 -1
  58. package/adapters/resend.d.mts +0 -13
  59. package/adapters/resend.mjs +0 -29
  60. package/adapters/resend.mjs.map +0 -1
  61. package/adapters/socket.d.mts +0 -14
  62. package/adapters/socket.mjs +0 -160
  63. package/adapters/socket.mjs.map +0 -1
  64. package/adapters/websocket.d.mts +0 -20
  65. package/adapters/websocket.mjs +0 -134
  66. package/adapters/websocket.mjs.map +0 -1
  67. package/adapters/webworker.d.mts +0 -8
  68. package/adapters/webworker.mjs +0 -42
  69. package/adapters/webworker.mjs.map +0 -1
  70. package/codecs/cbor.d.mts +0 -12
  71. package/codecs/cbor.mjs +0 -198
  72. package/codecs/cbor.mjs.map +0 -1
  73. package/codecs/psionic.d.mts +0 -12
  74. package/codecs/psionic.mjs +0 -57
  75. package/codecs/psionic.mjs.map +0 -1
  76. package/psionic.d.mts +0 -203
  77. package/psionic.mjs +0 -671
  78. package/psionic.mjs.map +0 -1
  79. package/session.d.mts +0 -63
  80. package/session.mjs +0 -92
  81. package/session.mjs.map +0 -1
  82. package/utils/react-hooks.d.mts +0 -24
  83. package/utils/react-hooks.mjs +0 -37
  84. package/utils/react-hooks.mjs.map +0 -1
package/README.md ADDED
@@ -0,0 +1,321 @@
1
+ # Psionic
2
+
3
+ ```bash
4
+ bun add psionic # or npm install psionic
5
+ ```
6
+
7
+ Psionic is a lightweight bidirectional communication protocol designed for dynamic APIs and streaming data.
8
+
9
+ Each connection consists of two symmetrical peers. Either side may expose functions, invoke calls, and stream data from the other end.
10
+
11
+ ## Quick start - Streaming RPC data
12
+
13
+ We'll start with a simple streaming chat example using the OpenAI API.
14
+
15
+ ```bash
16
+ mkdir cli-chat && cd cli-chat
17
+ bun init -y
18
+ bun add openai psionic
19
+ ```
20
+
21
+ #### server.mjs
22
+ ```javascript
23
+ import { createPeer } from "psionic";
24
+ import OpenAI from "openai";
25
+
26
+ // listen for incoming socket connections and create a new peer for each one
27
+ import { createServer } from "net";
28
+ import { createNodeSocketAdapter } from "psionic/adapters/socket";
29
+ createServer(socket => handlePeer(createNodeSocketAdapter(socket))).listen(1234);
30
+
31
+ // global conversation_id for demo purposes.
32
+ let conversation_id = undefined;
33
+
34
+ async function handlePeer(adapter) {
35
+ const peer = createPeer();
36
+ await peer.connect(adapter);
37
+
38
+ const openAI = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
39
+ // send a list of functions and properties to the client.
40
+ // they can access this under peer.remote from their end, and we can update it at any time.
41
+ await peer.describe(desc => ({ ...desc, prompt }));
42
+
43
+ // this is a function that can be called by the client.
44
+ // it returns an async generator, which allows us to stream data back to the client in chunks.
45
+ async function* prompt(input) {
46
+ try {
47
+ const data = await openAI.responses.create({
48
+ // peer.remote is a live-updating view of the client's described state.
49
+ model: peer.remote?.model || 'gpt-5.2',
50
+ store: true,
51
+ stream: true,
52
+ previous_response_id: conversation_id,
53
+ tools: [{ type: "web_search" }],
54
+ instructions: `Send really terse responses.`,
55
+ input: String(input)
56
+ });
57
+ for await (const part of data) {
58
+ console.log(part.type, part.sequence_number);
59
+ if (part.type === 'response.completed')
60
+ conversation_id = part.response.id;
61
+ // yield one chunk to the client at a time
62
+ // this waits until they ask for the next one before continuing.
63
+ yield part;
64
+ }
65
+ } finally {
66
+ // this will run if the peer disconnects, times out, or if the function completes!
67
+ console.log('prompt ended!');
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ #### client.mjs
74
+ ```javascript
75
+
76
+ import { createPeer } from "psionic";
77
+
78
+ // create a peer, with the description we want to send when we connect.
79
+ // could be anything, in this case, just the model we want the server to use.
80
+ const peer = createPeer({ description: { model: process.argv[3] || 'gpt-5.2' } });
81
+
82
+ // connect to the local socket
83
+ import { createConnection } from "net";
84
+ import { createNodeSocketAdapter } from "psionic/adapters/socket";
85
+ await peer.connect(createNodeSocketAdapter(createConnection({ port: 1234 })));
86
+
87
+ // pass the argument from the command line to the server's prompt function
88
+ for await (const chunk of peer.remote.prompt(process.argv[2])) {
89
+ // and stream the response back to the console as it comes in!
90
+ if (chunk.type === 'response.output_text.delta')
91
+ process.stdout.write(String(chunk.delta));
92
+ }
93
+
94
+ // close the connection so that the process exits
95
+ peer.close();
96
+ console.log('');
97
+ ```
98
+
99
+ Then start the server and client in separate terminal windows:
100
+ ```bash
101
+ bun server.mjs
102
+ ```
103
+
104
+ ```bash
105
+ bun client.mjs "How many people live in New York City?" "gpt-5.1"
106
+ # New York City has roughly **8.5–8.8 million** residents.
107
+
108
+ bun client.mjs "When was it founded?"
109
+ # Founded in 1624 as New Amsterdam by the Dutch West India Company; it was renamed New York in 1664 after the English seized the colony.
110
+ ```
111
+
112
+ The server will stream the response from OpenAI to the client, which will print it to the console as it arrives.
113
+
114
+ You can abort the response at any time by pressing Ctrl-C in the client terminal, which will also trigger cleanup on the server.
115
+
116
+ ## Why Psionic Exists
117
+
118
+ Most RPC systems assume relatively static APIs and short-lived request/response interactions.
119
+
120
+ Psionic was designed for environments where APIs are inherently dynamic, where functions and permissions can change at any point during runtime. Instead of treating an API as a fixed contract, Psionic models it as a live capability graph that peers synchronize with each other.
121
+
122
+ ## Bundle size
123
+
124
+ Psionic has no dependencies. Total size depends on which modules you include:
125
+
126
+ ```
127
+ psionic 9.93 kB │ gzip: 3.73 kB
128
+ adapters/socket 2.61 kB │ gzip: 1.17 kB
129
+ adapters/websocket 1.61 kB │ gzip: 0.74 kB
130
+ adapters/webworker 1.09 kB │ gzip: 0.48 kB
131
+ codecs/default 1.24 kB │ gzip: 0.68 kB
132
+ codecs/cbor 3.26 kB │ gzip: 1.41 kB
133
+ session 0.83 kB │ gzip: 0.51 kB
134
+ ```
135
+
136
+ ## Dynamic capabilities and Error handling
137
+
138
+ The remote state can be changed at any time by calling `peer.describe()`, this example uses dynamic descriptions to limit the amount of work a single peer can do.
139
+
140
+ #### server.mjs
141
+ ```javascript
142
+ import { createPeer } from "psionic";
143
+ import { WebSocketServer } from "ws";
144
+ import { createWebSocketAdapter } from "psionic/adapters/websocket";
145
+ const wss = new WebSocketServer({ port: 1234 });
146
+ wss.on('connection', socket => handlePeer(createWebSocketAdapter(socket)));
147
+
148
+ async function handlePeer(adapter) {
149
+ let tokens = 5;
150
+ const peer = createPeer({
151
+ description: describe(),
152
+ // if this is not true, any errors will have their text replaced by a generic message.
153
+ sendErrorMessages: true
154
+ });
155
+ await peer.connect(adapter);
156
+ peer.on('error', ex => {
157
+ console.log('Something went wrong:', ex.message);
158
+ });
159
+
160
+ async function dowork() {
161
+ await new Promise(r => setTimeout(r, Math.random() * 4_000));
162
+
163
+ const workResult = Math.random();
164
+
165
+ if (workResult > 0.5) {
166
+ // this will propagate as a remote error to the client.
167
+ throw new Error('Work failed!');
168
+ }
169
+
170
+ tokens -= 1;
171
+
172
+ // Send a new description to the client, which will cause their peer.remote to update.
173
+ await peer.describe(describe);
174
+
175
+ return workResult;
176
+ }
177
+
178
+ function describe() {
179
+ return {
180
+ tokens,
181
+ // dowork can only be called if we have tokens.
182
+ // so if we don't, we don't even include it, making it uncallable.
183
+ dowork: tokens > 0 ? dowork : undefined
184
+ };
185
+ }
186
+ }
187
+ ```
188
+
189
+ #### client.mjs
190
+ ```javascript
191
+ import { createPeer } from "psionic";
192
+
193
+ const peer = createPeer({
194
+ description: {},
195
+ // this allows us to receive error details from the server, otherwise all errors are generic.
196
+ receiveErrorMessages: true
197
+ });
198
+
199
+ // connect to the local websocket
200
+ import { createWebSocketAdapter } from "psionic/adapters/websocket";
201
+ await peer.connect(createWebSocketAdapter(new WebSocket('ws://localhost:1234')));
202
+
203
+ while (peer.remote.dowork) {
204
+ try {
205
+ const result = await peer.remote.dowork();
206
+
207
+ console.log(`Work result: ${result}`);
208
+ console.log(`Tokens remaining: ${peer.remote.tokens}`);
209
+ } catch(ex) {
210
+ console.log('Something went wrong while working:', ex.message);
211
+ }
212
+ }
213
+
214
+ console.log('No more tokens!');
215
+ peer.close();
216
+ ```
217
+
218
+ ## Key Concepts
219
+
220
+ ### Peer
221
+
222
+ A `Peer` represents one side of a Psionic connection.
223
+
224
+ Peers are symmetrical: either side may describe state, expose functions, invoke remote functions, or stream data.
225
+ There is no client/server distinction at the protocol level.
226
+
227
+ ### Description
228
+
229
+ A `Description` represents the capability surface exposed by a `Peer`.
230
+
231
+ It defines which functions and properties are available to the remote `Peer`. Only values present in the `Description` may be accessed or invoked remotely.
232
+
233
+ Descriptions may be updated at runtime. Removing a function from a description immediately revokes the remote peer’s ability to invoke it.
234
+
235
+ ```javascript
236
+ peer.describe(newState) // swap the entire state with a new description object
237
+ peer.describe(current => ({ ...current, ...changes })) // apply a partial update to the state
238
+ ```
239
+
240
+ A description update is transactional. The call completes only after the remote peer acknowledges the new capability state, but the state is immediately updated on the local peer. If the call cannot complete for any reason, the connection is closed to prevent desynchronization.
241
+
242
+ When using the function form, only the structural differences are sent, if any. This allows you to keep a larger description up-to-date with less overhead.
243
+
244
+ Descriptions define the authority boundary of a peer.
245
+ A peer may only access or invoke values explicitly described by the remote side.
246
+
247
+ This simplifies reasoning about security and capabilities in a dynamic system.
248
+
249
+ ### Adapter
250
+
251
+ An `Adapter` binds a `Peer` to a transport layer.
252
+
253
+ Adapters are transport-agnostic and may be implemented for any bidirectional communication channel.
254
+
255
+ There are built-in adapters for node.js sockets, web sockets and web workers, but you can implement your own for any transport that supports bidirectional communication.
256
+
257
+ The adapter is responsible for:
258
+
259
+ - Delivering frames between peers
260
+ - Managing connection lifecycle
261
+ - Providing an `Session` for operation lifecycle management
262
+
263
+ The `Session` manages pending calls, generators, and cleanup semantics.
264
+
265
+ ## Events
266
+
267
+ Peers emit events for connection lifecycle and state changes, most applications will use `ready` and `describe` events to manage connection state and react to description updates, and `error` to catch unhandled exceptions.
268
+
269
+ - **`connect`** - Transport connection established.
270
+
271
+ - **`ready`** - Both peers have exchanged descriptions and remote capabilities are available.
272
+
273
+ - **`disconnect`** - Transport connection lost.
274
+
275
+ - **`describe`** - Remote description has been updated.
276
+
277
+ - **`send`** - A frame is being sent to the remote peer.
278
+
279
+ - **`message`** - A frame has been received from the remote peer.
280
+
281
+ - **`error`** - An unhandled error was thrown during operation.
282
+
283
+ The events can be registered and unregistered:
284
+
285
+ ```javascript
286
+ const unsubscribe = peer.on('error', logErrorToMonitoringService);
287
+ peer.off('error', logErrorToMonitoringService);
288
+ unsubscribe(); // alternative way to unregister the listener
289
+ ```
290
+
291
+ There is a utility for subscribing to the `describe` events
292
+
293
+
294
+ ## Call context
295
+
296
+ In some situations you may need to find the ID of the current RPC call, for tracing for example. There is a wrapping function that adds a context object to the start of the arguments list, which contains this information. You can access it like this:
297
+
298
+ ```javascript
299
+ import { withContext } from "psionic";
300
+
301
+ function myFunction(context, arg1, arg2) {
302
+ console.log(context.id); // the id that the peer sent to start the call.
303
+ console.log(context.operation.id); // the id of the operation operation associated with this call.
304
+ }
305
+
306
+ peer.describe(desc => ({ ...desc, myFunction: withContext(myFunction) }));
307
+ ```
308
+
309
+ ## Examples & Documentation
310
+
311
+ There are examples in the `examples` folder:
312
+
313
+ - [Cloudflare Pages / Workers Example](./examples/cloudflare)
314
+ - [Node.js Child process streams](./examples/nodestreams)
315
+ - [OpenAI chat](./examples/cli-chat)
316
+ - [Work tokens example](./examples/tokens)
317
+
318
+ And further documentation is in the `docs` folder:
319
+
320
+ - [Protocol documentation](./docs/protocol.md)
321
+ - [Extending Psionic](./docs/extending.md)
@@ -0,0 +1,43 @@
1
+ import assert from 'assert'
2
+ import { createAsyncFunction, createPeer, ErrorFunctionNotFound, ErrorGeneric } from '../src/psionic';
3
+ import { createPair } from './lib/adapter';
4
+
5
+ const description = {
6
+ ok: async (msg: string) => { return msg },
7
+ fail: async () => { throw new Error('fail') }
8
+ };
9
+
10
+ const left = createPeer({ description, sendErrorMessages: true });
11
+ const right = createPeer({ description, receiveErrorMessages: true });
12
+ const pair = await createPair(left, right);
13
+
14
+ const asyncOkInvoker = createAsyncFunction(left, ["ok"], false);
15
+ const asyncFailInvoker = createAsyncFunction(left, ["fail"], false);
16
+ const asyncFailInvokerRight = createAsyncFunction(right, ["fail"], false);
17
+ const asyncMissingInvoker = createAsyncFunction(left, ["missing"], false);
18
+
19
+ console.log('- Testing basic async function call');
20
+ await asyncOkInvoker("hello")
21
+ .then(result => {
22
+ assert.strictEqual(result, 'hello', 'The caller should receive the correct result from the async function call')
23
+ });
24
+
25
+ console.log('- Testing async function call that throws an error - the caller should receive a generic error message because debugErrors is not enabled on the callee peer');
26
+ await asyncFailInvoker()
27
+ .catch(err => {
28
+ assert.strictEqual(err.message, ErrorGeneric.error, 'The caller should receive a generic error message when debugErrors is not enabled on the callee peer');
29
+ });
30
+
31
+ console.log('- Testing async function call that throws an error - the caller should receive the original error message because debugErrors is enabled on the callee peer');
32
+ await asyncFailInvokerRight()
33
+ .catch(err => {
34
+ assert.strictEqual(err.message, 'fail', 'The caller should receive the original error message when debugErrors is enabled on the callee peer');
35
+ });
36
+
37
+ console.log('- Testing async function call to a non-existent function - the caller should receive a function not found error');
38
+ await asyncMissingInvoker()
39
+ .catch(err => {
40
+ assert.strictEqual(err.message, ErrorFunctionNotFound.error, 'The caller should receive a function not found error when calling a non-existent function');
41
+ });
42
+
43
+ console.log('- All async function tests passed successfully');
@@ -0,0 +1,137 @@
1
+ import assert from 'assert'
2
+ import { createAsyncGeneratorFunction, createPeer, ErrorExpiredOrInvalid, ErrorGeneric } from '../src/psionic';
3
+ import { createPair } from './lib/adapter';
4
+
5
+ const description = {
6
+ ok: async function *() {
7
+ yield 'yield1';
8
+ yield 'yield2';
9
+ return 'ok';
10
+ },
11
+ fail: async function *() { throw new Error('fail') }
12
+ };
13
+
14
+ const left = createPeer({ description, sendErrorMessages: true });
15
+ const right = createPeer({ description, receiveErrorMessages: true });
16
+ await createPair(left, right);
17
+
18
+ const asyncFailInvoker = createAsyncGeneratorFunction(left, ["fail"]);
19
+ const asyncOkInvoker = createAsyncGeneratorFunction(left, ["ok"]);
20
+
21
+ console.log('- Testing basic async generator function call');
22
+ const okresult = asyncOkInvoker("hello");
23
+ assert.deepStrictEqual(
24
+ await okresult.next(),
25
+ { value: 'yield1', done: false },
26
+ 'The caller should receive the correct yielded value from the async generator'
27
+ );
28
+
29
+ await okresult.next();
30
+
31
+ assert.deepStrictEqual(
32
+ await okresult.next(),
33
+ { value: 'ok', done: true },
34
+ 'The caller should receive the correct return value from the async generator'
35
+ );
36
+
37
+ console.log('- Testing closing an async generator from the caller');
38
+ const breakresult = asyncOkInvoker("hello");
39
+ assert.deepStrictEqual(
40
+ await breakresult.next(),
41
+ { value: 'yield1', done: false },
42
+ 'The caller should receive the correct yielded value from the async generator'
43
+ );
44
+
45
+ assert.deepStrictEqual(
46
+ await breakresult.return('return'),
47
+ { value: 'return', done: true },
48
+ 'The caller should be able to close the async generator and receive the provided value'
49
+ );
50
+
51
+ assert.deepStrictEqual(
52
+ await breakresult.next(),
53
+ { value: undefined, done: true },
54
+ 'After an async generator is closed, it should be completed and not yield any further values'
55
+ );
56
+
57
+ console.log('- Testing throwing an error into an async generator from the caller');
58
+ const throwsresult = asyncOkInvoker("hello");
59
+ assert.deepStrictEqual(
60
+ await throwsresult.next(),
61
+ { value: 'yield1', done: false },
62
+ 'The caller should receive the correct yielded value from the async generator'
63
+ );
64
+
65
+ await throwsresult.throw('crash')
66
+ .then(() => {
67
+ assert.fail('The caller should not resolve successfully when an error is thrown into the async generator');
68
+ })
69
+ .catch(err => {
70
+ assert.strictEqual(
71
+ err.message,
72
+ ErrorGeneric.error,
73
+ 'The caller should receive a generic error message when an error is thrown into the async generator'
74
+ );
75
+ });
76
+
77
+ assert.deepStrictEqual(
78
+ await throwsresult.next(),
79
+ { value: undefined, done: true },
80
+ 'After an error is thrown into the async generator and caught, it should be completed'
81
+ );
82
+
83
+ console.log('- Testing async generator function that throws an error');
84
+ const failresult = asyncFailInvoker("hello");
85
+ await failresult.next()
86
+ .then(() => {
87
+ assert.fail('The caller should not resolve successfully when the async generator throws an error');
88
+ })
89
+ .catch(err => {
90
+ assert.strictEqual(
91
+ err.message,
92
+ ErrorGeneric.error,
93
+ 'The caller should receive a generic error message when an async generator throws an error'
94
+ );
95
+ });
96
+
97
+ assert.deepStrictEqual(
98
+ await failresult.next(),
99
+ { value: undefined, done: true },
100
+ 'After an async generator throws an error, it should be completed and not yield any further values'
101
+ );
102
+
103
+ console.log('- Testing concurrent async generator calls');
104
+ {
105
+ const g1 = asyncOkInvoker();
106
+ const g2 = asyncOkInvoker();
107
+
108
+ assert.deepStrictEqual(await g1.next(), { value: 'yield1', done: false }, 'concurrent g1 should receive the first yield');
109
+ assert.deepStrictEqual(await g2.next(), { value: 'yield1', done: false }, 'concurrent g2 should receive the first yield');
110
+ assert.deepStrictEqual(await g1.next(), { value: 'yield2', done: false }, 'concurrent g1 should receive the second yield');
111
+ await g2.return(undefined);
112
+ assert.deepStrictEqual(await g1.next(), { value: 'ok', done: true }, 'concurrent g1 should receive the return value and be completed');
113
+ assert.deepStrictEqual(await g2.next(), { value: undefined, done: true }, 'concurrent g2 should be completed after being returned');
114
+ }
115
+
116
+ console.log('- Testing async generator expiration');
117
+ {
118
+ const g1 = asyncOkInvoker();
119
+ assert.deepStrictEqual(await g1.next(),{ value: 'yield1', done: false },'The async generator should yield the first value correctly');
120
+ right.session.clear();
121
+ await g1.next()
122
+ .then(() => { assert.fail('Expired generators should be cleaned up'); })
123
+ .catch(err => {
124
+ assert.strictEqual(
125
+ err.message,
126
+ ErrorExpiredOrInvalid.error,
127
+ 'The caller should receive a generic error message when interacting with an expired async generator'
128
+ );
129
+ });
130
+ assert.deepStrictEqual(
131
+ await g1.next(),
132
+ { value: undefined, done: true },
133
+ 'After an async generator has expired, it should be completed and not yield any further values'
134
+ );
135
+ }
136
+
137
+ console.log('- All async generator function tests passed successfully');
@@ -0,0 +1,65 @@
1
+ import assert from 'assert'
2
+ import { fromCodecDescription, createPeer, AsyncGenKey, AsyncFnKey, isAsyncGeneratorLike, Keyword } from '../src/psionic';
3
+
4
+ const peer = createPeer();
5
+
6
+ const allSimpleValues = () => ({
7
+ 'hello': 'world',
8
+ number: 9,
9
+ nested: {
10
+ arrayValue: [1,2,3],
11
+ isThisATest: true
12
+ }
13
+ });
14
+
15
+ console.log('- Testing converting a description from the wire format');
16
+ assert.deepStrictEqual(
17
+ fromCodecDescription(peer, allSimpleValues()),
18
+ allSimpleValues(),
19
+ 'Plain values should be unchanged'
20
+ );
21
+
22
+ console.log('- Testing that functions are not allowed in the wire format');
23
+ assert.throws(
24
+ () => fromCodecDescription(peer, { hello: () => 'world' } as any),
25
+ 'Functions should throw an error, as they are not supported in the wire format'
26
+ );
27
+
28
+ console.log('- Testing that async function keywords are converted to actual async functions');
29
+ assert.ok(
30
+ fromCodecDescription(peer, { hello: { [Keyword]: AsyncFnKey } }).hello() instanceof Promise,
31
+ 'Async functions keywords should be converted to actual async functions'
32
+ );
33
+
34
+ console.log('- Testing that async generator function keywords are converted to actual async generator functions');
35
+ assert.ok(
36
+ isAsyncGeneratorLike(fromCodecDescription(peer, { hello: { [Keyword]: AsyncGenKey } }).hello),
37
+ 'Async generator functions keywords should be converted to actual async generator functions'
38
+ );
39
+
40
+ console.log('- Testing that Date instances are not allowed in the wire format');
41
+ assert.throws(
42
+ () => fromCodecDescription(peer, { hello: new Date() }),
43
+ 'Date instances are not allowed in the wire format.'
44
+ );
45
+
46
+ console.log('- Testing that class instances are not allowed in the wire format');
47
+ assert.throws(
48
+ () => fromCodecDescription(peer, { hello: new (class X {})() }),
49
+ 'Class instances are not allowed in the wire format.'
50
+ );
51
+
52
+ console.log('- Testing that objects without a prototype are not allowed in the wire format');
53
+ assert.throws(
54
+ () => fromCodecDescription(peer, { hello: Object.create(null) }),
55
+ 'Objects without a prototype are not allowed in the wire format.'
56
+ );
57
+
58
+ console.log('- Testing that circular references are not allowed in the wire format');
59
+ let nest: any = {}; nest.nest = nest;
60
+ assert.throws(
61
+ () => fromCodecDescription(peer, nest),
62
+ 'Circular references are not allowed in the wire format.'
63
+ );
64
+
65
+ console.log('- All convert from wire format tests passed successfully');
@@ -0,0 +1,66 @@
1
+ import assert from 'assert'
2
+ import { AsyncFnKey, AsyncGenKey, Keyword, toCodecDescription } from '../src/psionic';
3
+
4
+ const allSimpleValues = () => ({
5
+ 'hello': 'world',
6
+ number: 9,
7
+ nested: {
8
+ arrayValue: [1,2,3],
9
+ isThisATest: true
10
+ }
11
+ });
12
+
13
+ console.log('- Testing converting a description to the wire format');
14
+ assert.deepStrictEqual(
15
+ toCodecDescription(allSimpleValues()),
16
+ allSimpleValues(),
17
+ 'Plain values should be unchanged'
18
+ );
19
+
20
+ console.log('- Testing that functions are not allowed in the wire format');
21
+ assert.deepStrictEqual(
22
+ toCodecDescription({ hello: async () => 'world' }),
23
+ { hello: { [Keyword]: AsyncFnKey } },
24
+ 'Async functions should be replaced with transport keyword'
25
+ );
26
+
27
+ console.log('- Testing that async generator functions are not allowed in the wire format');
28
+ assert.deepStrictEqual(
29
+ toCodecDescription({ hello: async function* () { yield 'world' } }),
30
+ { hello: { [Keyword]: AsyncGenKey } },
31
+ 'Async generator functions should be replaced with transport keyword'
32
+ );
33
+
34
+ console.log('- Testing that functions are replaced with transport keywords even when nested in arrays');
35
+ assert.deepStrictEqual(
36
+ toCodecDescription([{ hello: async () => 'world' }]),
37
+ [{ hello: { [Keyword]: AsyncFnKey } }],
38
+ 'Function should be replaced with transport keyword even when nested in arrays'
39
+ );
40
+
41
+ console.log('- Testing that class instances are not allowed in descriptions');
42
+ assert.throws(
43
+ () => toCodecDescription({ hello: new Date() }),
44
+ 'Date instances are not allowed in descriptions.'
45
+ );
46
+
47
+ console.log('- Testing that class instances are not allowed in descriptions');
48
+ assert.throws(
49
+ () => toCodecDescription({ hello: new (class X {})() }),
50
+ 'Class instances are not allowed in descriptions.'
51
+ );
52
+
53
+ console.log('- Testing that objects without a prototype are not allowed in descriptions');
54
+ assert.throws(
55
+ () => toCodecDescription({ hello: Object.create(null) }),
56
+ 'Objects without a prototype are not allowed in descriptions.'
57
+ );
58
+
59
+ console.log('- Testing that circular references are not allowed in descriptions');
60
+ let nest: any = {}; nest.nest = nest;
61
+ assert.throws(
62
+ () => toCodecDescription(nest),
63
+ 'Circular references are not allowed in descriptions.'
64
+ );
65
+
66
+ console.log('- All convert to wire format tests passed successfully');
@@ -0,0 +1,26 @@
1
+ import assert from 'assert'
2
+ import { createPeer } from '../src/psionic';
3
+ import { createPair } from './lib/adapter';
4
+
5
+ type Description ={ initial: boolean; hello?: string; third?: { value: string }; };
6
+
7
+ const left = createPeer({ description: { initial: true, hello: 'there' } as Description });
8
+ const right = createPeer({ });
9
+
10
+ console.log('- Testing that peers receive the initial descriptions');
11
+ await createPair(left, right);
12
+
13
+ assert.deepStrictEqual(right.remote, { initial: true, hello: 'there' });
14
+ assert.deepStrictEqual(left.remote, undefined);
15
+
16
+ console.log('- Testing that peers can update their descriptions and the other peer receives the updated description');
17
+ await left.describe({ initial: false, third: { value: 'key' } });
18
+
19
+ assert.deepStrictEqual(right.remote, { initial: false, third: { value: 'key' } });
20
+
21
+ console.log('- Testing that peers can merge updates to their descriptions and the other peer receives the merged description');
22
+ await left.describe(d => ({ ...d, third: { value: 'merged' } }));
23
+
24
+ assert.deepStrictEqual(right.remote, { initial: false, third: { value: 'merged' } });
25
+
26
+ console.log('- All describe tests passed successfully');