@thomas57/rennari-client-js 0.1.0 → 0.2.0

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 CHANGED
@@ -1,224 +1,78 @@
1
- Rennari Client JS
2
- =================
1
+ # rennari-client-js
3
2
 
4
- JavaScript client for the Rennari protocol. Wire-compatible with
5
- Mojo::Rennari::Server (Perl) and rennari-server-js (Node).
3
+ A JavaScript client for Rennari servers: events, namespaces, acknowledgements, automatic reconnection with session recovery, MessagePack or JSON. Runs in Node.js and browsers.
6
4
 
7
- Small, secure, MessagePack- or JSON-framed WebSocket event layer with
8
- custom events, namespaces, acknowledgements, automatic reconnection, and
9
- connection state recovery.
5
+ ## Quick start
10
6
 
11
- Works in Node 18+ and any modern browser. No build step. No bundler.
7
+ npx rennari-client new my-client # single-file client
8
+ npx rennari-client new my-client --app # one file per event handler
12
9
 
13
- STATUS
10
+ cd my-client
11
+ npm install
12
+ # edit config.js: set url and token
13
+ npm start
14
14
 
15
- Working. Tested against both server implementations.
15
+ ## Install
16
16
 
17
- INSTALL
17
+ npm install @thomas57/rennari-client-js ws
18
18
 
19
- npm install @thomas/rennari-client-js
19
+ `ws` is only needed in Node.js.
20
20
 
21
- Or import directly from src if you clone the repo.
21
+ ## Connect (Node.js)
22
22
 
23
- QUICK START
24
-
25
- import { Rennari } from '@thomas/rennari-client-js';
23
+ import { WebSocket } from 'ws';
24
+ import { Rennari, setWebSocket } from '@thomas57/rennari-client-js';
26
25
 
27
- const client = new Rennari('wss://example.com/ws?token=secret');
26
+ setWebSocket(WebSocket);
28
27
 
29
- client.on('connect', () => {
30
- console.log('connected', client.sessionId);
31
- client.emit('chat', { room: 'lobby', text: 'hi' });
28
+ const client = new Rennari('ws://localhost:3000/ws', {
29
+ serializer: 'msgpack',
30
+ headers: { 'X-Rennari-App-Token': token },
32
31
  });
33
32
 
34
- client.on('chat', (p) => console.log(p.from, ':', p.text));
35
- client.on('disconnect', ({ code, reason }) => console.log(code, reason));
33
+ client.on('connect', () => client.emit('ping', { n: 1 }));
34
+ client.on('pong', (payload) => console.log(payload.got.n));
36
35
 
37
36
  await client.connect();
38
37
 
39
- CORE CONCEPTS
40
-
41
- Frames
42
-
43
- Every message is a map:
44
-
45
- { e, d, id?, o?, n? }
46
-
47
- - e - event name, [A-Za-z0-9_.:-]{1,64}
48
- - d - payload
49
- - id - optional acknowledgement id
50
- - o - optional offset, present when the server has recovery enabled
51
- - n - optional namespace, omitted for /
52
-
53
- The wire format is identical on both server implementations. If the
54
- server is configured with serializer: 'json', the client must be too:
55
-
56
- new Rennari(url, { serializer: 'json' });
57
-
58
- Events
59
-
60
- client.on(event, handler);
61
- client.off(event, handler);
62
- client.emit(event, payload);
63
-
64
- The client-level methods operate on the default / namespace. Local
65
- lifecycle events also fire there:
66
-
67
- client.on('connect', () => {});
68
- client.on('disconnect', ({ code, reason }) => {});
69
- client.on('error', (err) => {});
70
- client.on('ack_timeout', ({ event, payload }) => {});
71
- client.on('reconnect_attempt', ({ attempt, delay }) => {});
72
- client.on('reconnect_failed', () => {});
73
- client.on('recovered', ({ offset }) => {});
74
-
75
- Namespaces
76
-
77
- const chat = client.of('/chat');
78
-
79
- chat.on('message', (p) => {});
80
- chat.emit('message', { text: 'hi' });
81
-
82
- Every non-default namespace is declared to the server on connect and on
83
- reconnect. Incoming frames are dispatched by their n field. A frame for
84
- a namespace the client has not joined on the server causes a close with
85
- code 4005.
86
-
87
- Acknowledgements
88
-
89
- const ack = await client.emitWithAck('chat', { text: 'hi' }, {
90
- timeout: 3000,
91
- retries: 2,
92
- });
93
-
94
- The client assigns an id, sends the frame, and waits for rennari_ack.
95
- If no ack arrives within timeout milliseconds, the frame is resent up to
96
- retries times. When retries are exhausted, the promise rejects and the
97
- ack_timeout local event fires.
98
-
99
- Duplicate delivery is possible by design. Handlers on the server should
100
- be idempotent if the application uses retries.
101
-
102
- Reconnection
103
-
104
- On by default:
105
-
106
- new Rennari(url, {
107
- reconnection: true,
108
- reconnectionDelay: 1000,
109
- reconnectionDelayMax: 5000,
110
- reconnectionAttempts: Infinity,
111
- reconnectionJitter: 0.5,
112
- });
113
-
114
- When the WebSocket closes unexpectedly, the client reconnects with
115
- exponential backoff plus jitter. Before each attempt, reconnect_attempt
116
- fires. When attempts are exhausted, reconnect_failed fires. On
117
- successful reconnect, connect fires again.
118
-
119
- While disconnected, emit() queues the frame in an outbox. The queue is
120
- flushed on the next connect. If reconnection is off, emit() throws when
121
- not connected.
122
-
123
- Recovery
124
-
125
- When the server has recovery enabled, it issues a session id at
126
- handshake. The client stores it as client.sessionId and tracks the
127
- server's offset as client.lastOffset.
128
-
129
- If the connection drops and reconnects within the server's recovery
130
- window, the client sends rennari_resume with the session id and last
131
- offset. The server replays missed frames, re-attaches namespaces and
132
- rooms, and replies rennari_resumed with the transferred session id. The
133
- client then fires recovered.
134
-
135
- new Rennari(url, {
136
- recovery: true,
137
- recoveryWindow: 120000,
138
- });
139
-
140
- Both recovery and reconnection must be enabled for session recovery to
141
- work. Without reconnection, the client never tries to resume.
142
-
143
- DISCONNECT
144
-
145
- client.disconnect();
146
- client.disconnect(4000, 'user_exit');
147
-
148
- Intentional disconnect does not trigger reconnection.
149
-
150
- CONFIGURATION
151
-
152
- new Rennari(url, {
153
- serializer: 'msgpack', // or 'json'
154
- maxBytes: 64 * 1024, // max incoming frame size
155
- ackTimeout: 5000, // ms, default per emitWithAck
156
- retries: 3, // default per emitWithAck
157
- reconnection: true,
158
- reconnectionDelay: 1000,
159
- reconnectionDelayMax: 5000,
160
- reconnectionAttempts: Infinity,
161
- reconnectionJitter: 0.5,
162
- recovery: true,
163
- recoveryWindow: 120000,
164
- });
165
-
166
- NODE VERSUS BROWSER
167
-
168
- In the browser, globalThis.WebSocket exists. In Node 18 and 20, it
169
- does not, so the ws package must be provided:
170
-
171
- import { WebSocket } from 'ws';
172
- import { setWebSocket, Rennari } from '@thomas/rennari-client-js';
173
-
174
- setWebSocket(WebSocket);
175
-
176
- Node 22+ has a built-in WebSocket and does not need the ws package.
177
-
178
- In both environments, binary WebSocket frames are used. binaryType is
179
- set to 'arraybuffer' by the transport.
38
+ Load `token` from a private config file. Never put it in the URL, an environment variable or a command-line argument.
180
39
 
181
- CLOSE CODES
40
+ ## Authentication
182
41
 
183
- The server closes with:
42
+ - **Node.js:** the `headers` option sends `X-Rennari-App-Token: <raw token>` during the handshake. It is not a Bearer token.
43
+ - **Browsers and Node.js:** the `auth` option sends a first-message frame instead. Browsers cannot set custom headers.
184
44
 
185
- - 4002 - bad frame
186
- - 4003 - unknown event
187
- - 4004 - handler error
188
- - 4005 - unknown namespace
189
- - 4006 - recovery disabled but client sent rennari_resume
45
+ See [docs/authentication.md](docs/authentication.md).
190
46
 
191
- These arrive in the disconnect local event as { code, reason }.
47
+ ## Features
192
48
 
193
- SECURITY NOTES
49
+ - Namespaces: `client.of('/chat')`
50
+ - Acknowledgements: `await client.emitWithAck(event, payload)`
51
+ - Reconnection with exponential backoff and jitter
52
+ - Session recovery after a dropped connection
53
+ - Offline outbox while reconnecting
194
54
 
195
- The token is passed in the URL query string in the examples. That is
196
- for demonstration only. In production, use one of:
55
+ ## Documentation
197
56
 
198
- - HttpOnly cookies with an Origin check on the server.
199
- - First-message auth: connect without credentials, then emit an 'auth'
200
- event with the token as the first message. The server enforces a
201
- timeout and closes the connection if no valid auth arrives.
57
+ - [Getting started](docs/getting-started.md)
58
+ - [Concepts](docs/concepts.md)
59
+ - [API reference](docs/api.md)
60
+ - [Authentication](docs/authentication.md)
61
+ - [Troubleshooting](docs/troubleshooting.md)
62
+ - [Testing and compatibility](docs/testing.md)
202
63
 
203
- The framework does not store tokens. It does not log frame payloads. It
204
- rejects frames larger than maxBytes before decoding. It rejects event
205
- names, ids, offsets, and namespaces that do not match the protocol
206
- grammar.
64
+ ## Project generator
207
65
 
208
- EXAMPLES
66
+ rennari-client new <name> [--lite | --app] [--client-path <dir>]
209
67
 
210
- A Node smoke test is in examples/node.mjs. It connects to a running
211
- Rennari server, exercises custom events, namespaces, acks, and recovery
212
- across a forced disconnect.
68
+ The generator refuses a non-empty folder and never accepts a token on the command line.
213
69
 
214
- node examples/node.mjs <port>
70
+ ## Testing
215
71
 
216
- Integration tests in tests/integration.test.js run the same client
217
- against a server spawned from the Perl repo. Skipped if
218
- RENNARI_PERL_DIR is unset.
72
+ npm test
219
73
 
220
- RENNARI_PERL_DIR=/path/to/mojo-rennari npm test
74
+ Integration tests need the Perl implementation: `RENNARI_PERL_DIR=/path/to/perl npm test`. See [docs/testing.md](docs/testing.md).
221
75
 
222
- LICENSE
76
+ ## License
223
77
 
224
- MIT.
78
+ TODO: add your license.
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ mkdirSync, readdirSync, readFileSync, writeFileSync, existsSync,
4
+ } from 'node:fs';
5
+ import { join, resolve, dirname, basename, relative, sep } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
9
+ const TEMPLATES = fileURLToPath(new URL('../templates/', import.meta.url));
10
+ const RENAMES = { _gitignore: '.gitignore' }; // npm strips real .gitignore files
11
+
12
+ function usage() {
13
+ return [
14
+ 'Usage: rennari-client new <name> [--lite | --app] [--client-path <dir>]',
15
+ '',
16
+ ' --lite single-file client (default)',
17
+ ' --app larger app with one file per event handler',
18
+ ' --client-path use a local copy of the client package (file: dependency)',
19
+ ' --help show this help',
20
+ '',
21
+ 'Tokens are never accepted here. Put the token in config.js after generating.',
22
+ ].join('\n');
23
+ }
24
+
25
+ function fail(message) {
26
+ console.error(`rennari-client: ${message}\n\n${usage()}`);
27
+ process.exit(2);
28
+ }
29
+
30
+ function parseArgs(argv) {
31
+ const opts = { kind: 'lite', clientPath: null, name: null, help: false };
32
+ for (let i = 0; i < argv.length; i++) {
33
+ const a = argv[i];
34
+ if (a === '--help' || a === '-h') opts.help = true;
35
+ else if (a === '--lite') opts.kind = 'lite';
36
+ else if (a === '--app') opts.kind = 'app';
37
+ else if (a === '--client-path') {
38
+ opts.clientPath = argv[++i];
39
+ if (!opts.clientPath) fail('--client-path needs a value');
40
+ } else if (a.startsWith('-')) fail(`unknown option ${a}`);
41
+ else if (opts.name === null) opts.name = a;
42
+ else fail('too many arguments');
43
+ }
44
+ return opts;
45
+ }
46
+
47
+ function* walk(dir, rel = '') {
48
+ for (const entry of readdirSync(join(dir, rel), { withFileTypes: true })) {
49
+ const r = join(rel, entry.name);
50
+ if (entry.isDirectory()) yield* walk(dir, r);
51
+ else yield r;
52
+ }
53
+ }
54
+
55
+ function main() {
56
+ const argv = process.argv.slice(2);
57
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {
58
+ console.log(usage());
59
+ return;
60
+ }
61
+ if (argv[0] !== 'new') fail(`unknown command '${argv[0]}'`);
62
+
63
+ const opts = parseArgs(argv.slice(1));
64
+ if (opts.help) { console.log(usage()); return; }
65
+ if (!opts.name) fail('project name is required');
66
+ if (!NAME_RE.test(opts.name)) {
67
+ fail('name must be lowercase letters, numbers, dot, dash or underscore (max 64)');
68
+ }
69
+
70
+ const source = join(TEMPLATES, opts.kind);
71
+ if (!existsSync(source)) fail(`the '${opts.kind}' template is not available yet`);
72
+
73
+ const target = resolve(opts.name);
74
+ if (existsSync(target) && readdirSync(target).length > 0) {
75
+ fail(`'${opts.name}' already exists and is not empty`);
76
+ }
77
+
78
+ let clientDep = '^0.1.0';
79
+ if (opts.clientPath) {
80
+ const clientDir = resolve(opts.clientPath);
81
+ if (!existsSync(join(clientDir, 'package.json'))) {
82
+ fail(`no package.json in ${clientDir}`);
83
+ }
84
+ const rel = relative(target, clientDir).split(sep).join('/');
85
+ clientDep = `file:${rel}`;
86
+ }
87
+
88
+ mkdirSync(target, { recursive: true });
89
+
90
+ for (const rel of walk(source)) {
91
+ const text = readFileSync(join(source, rel), 'utf8')
92
+ .replace(/\{\{name\}\}/g, opts.name)
93
+ .replace(/\{\{clientDep\}\}/g, clientDep);
94
+ const base = basename(rel);
95
+ const destRel = join(dirname(rel), RENAMES[base] ?? base);
96
+ const dest = join(target, destRel);
97
+ mkdirSync(dirname(dest), { recursive: true });
98
+ writeFileSync(dest, text, { flag: 'wx' });
99
+ }
100
+
101
+ // Private config with a placeholder token that fails validation until edited.
102
+ const example = readFileSync(join(target, 'config.example.js'), 'utf8');
103
+ writeFileSync(join(target, 'config.js'), example, { flag: 'wx', mode: 0o600 });
104
+
105
+ console.log([
106
+ `Created ${opts.kind} client in ${target}`,
107
+ '',
108
+ 'Next steps:',
109
+ ` cd ${opts.name}`,
110
+ ' npm install',
111
+ ' edit config.js (url and token)',
112
+ ' npm start',
113
+ ].join('\n'));
114
+ }
115
+
116
+ main();
package/package.json CHANGED
@@ -1,11 +1,22 @@
1
1
  {
2
2
  "name": "@thomas57/rennari-client-js",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "src/index.js",
6
- "files": ["src"],
6
+ "bin": {
7
+ "rennari-client": "./bin/rennari-client.mjs"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "bin",
12
+ "templates",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test \"tests/*.test.js\""
17
+ },
7
18
  "dependencies": {
8
19
  "@msgpack/msgpack": "^3.0.0",
9
- "ws": "^8.18.0"
20
+ "ws": "^8.23.0"
10
21
  }
11
22
  }
package/src/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export const VERSION = '0.1.0';
2
+ export { Rennari, Rennari as default, setWebSocket } from './rennari.js';
package/src/rennari.js CHANGED
@@ -18,6 +18,9 @@ const LOCAL_EVENTS = new Set([
18
18
  'recovered',
19
19
  ]);
20
20
 
21
+ // Close code the server uses for "unauthorized". The client does not retry on it.
22
+ const CLOSE_UNAUTHORIZED = 4001;
23
+
21
24
  export class Rennari {
22
25
  constructor(url, opts = {}) {
23
26
  this.url = url;
@@ -27,6 +30,13 @@ export class Rennari {
27
30
  this.defaultRetries = opts.retries ?? 3;
28
31
  this.defaultNamespace = '/';
29
32
 
33
+ // Auth. `headers` works in Node (ws) only. `auth` works everywhere.
34
+ this.headers = opts.headers ?? null;
35
+ this.auth = opts.auth ?? null;
36
+ this.authEvent = opts.authEvent ?? 'auth';
37
+
38
+ this.maxOutbox = opts.maxOutbox ?? 1000;
39
+
30
40
  this.reconnection = opts.reconnection ?? true;
31
41
  this.reconnectionDelay = opts.reconnectionDelay ?? 1000;
32
42
  this.reconnectionDelayMax = opts.reconnectionDelayMax ?? 5000;
@@ -87,12 +97,18 @@ export class Rennari {
87
97
  clearTimeout(this._reconnectTimer);
88
98
  this._reconnectTimer = null;
89
99
  }
100
+ for (const [id, entry] of this._pending) {
101
+ clearTimeout(entry.timer);
102
+ this._pending.delete(id);
103
+ entry.reject(new Error('rennari: disconnected'));
104
+ }
105
+ this._outbox = [];
90
106
  if (this._transport) this._transport.close(code, reason);
91
107
  this._connected = false;
92
108
  }
93
109
 
94
110
  _newTransport() {
95
- return new Transport(this.url);
111
+ return new Transport(this.url, { headers: this.headers });
96
112
  }
97
113
 
98
114
  _open() {
@@ -108,6 +124,23 @@ export class Rennari {
108
124
  this._connected = true;
109
125
  this._reconnectAttempts = 0;
110
126
 
127
+ // First-message auth must be the very first frame on the socket.
128
+ if (this.auth) {
129
+ try {
130
+ const payload = typeof this.auth === 'function'
131
+ ? this.auth()
132
+ : this.auth;
133
+ transport.send(encodeFrame(this.authEvent, payload, {
134
+ serializer: this.serializer.name,
135
+ }));
136
+ } catch (e) {
137
+ this._fireLocal('/', 'error', e);
138
+ transport.close(CLOSE_UNAUTHORIZED, 'auth_failed');
139
+ reject(e);
140
+ return;
141
+ }
142
+ }
143
+
111
144
  const useResume = this.recovery
112
145
  && this._sessionId
113
146
  && Date.now() <= this._sessionExpiresAt;
@@ -157,7 +190,11 @@ export class Rennari {
157
190
  reject(new Error(`rennari: connection closed before open (${code})`));
158
191
  }
159
192
 
160
- if (!this._intentionalDisconnect && this.reconnection) {
193
+ if (
194
+ !this._intentionalDisconnect
195
+ && this.reconnection
196
+ && code !== CLOSE_UNAUTHORIZED
197
+ ) {
161
198
  this._scheduleReconnect();
162
199
  }
163
200
  });
@@ -173,6 +210,7 @@ export class Rennari {
173
210
  }
174
211
 
175
212
  _scheduleReconnect() {
213
+ if (this._reconnectTimer) return;
176
214
  if (this._reconnectAttempts >= this.reconnectionAttempts) {
177
215
  this._fireLocal('/', 'reconnect_failed');
178
216
  return;
@@ -195,7 +233,7 @@ export class Rennari {
195
233
 
196
234
  this._reconnectTimer = setTimeout(() => {
197
235
  this._reconnectTimer = null;
198
- this._open().catch((e) => this._fireLocal('/', 'error', e));
236
+ this._open().catch(() => { /* errors already reported via 'error' */ });
199
237
  }, delay);
200
238
  }
201
239
 
@@ -242,11 +280,8 @@ export class Rennari {
242
280
  }
243
281
  }
244
282
 
245
- _emit(nsp, event, payload, id) {
246
- if (!validEventName(event)) {
247
- throw new Error(`invalid event name '${event}'`);
248
- }
249
- const writer = (transport) => {
283
+ _makeWriter(nsp, event, payload, id) {
284
+ return (transport) => {
250
285
  const bytes = encodeFrame(event, payload, {
251
286
  serializer: this.serializer.name,
252
287
  id,
@@ -254,6 +289,11 @@ export class Rennari {
254
289
  });
255
290
  transport.send(bytes);
256
291
  };
292
+ }
293
+
294
+ // Sends now if open, otherwise queues. `entry` (optional) limits an ack
295
+ // retry to one queued copy.
296
+ _dispatch(writer, entry = null) {
257
297
  if (this._transport && this._transport.isOpen()) {
258
298
  writer(this._transport);
259
299
  return;
@@ -261,17 +301,37 @@ export class Rennari {
261
301
  if (!this.reconnection) {
262
302
  throw new Error('rennari: not connected');
263
303
  }
304
+ if (entry) {
305
+ if (entry.queued) return;
306
+ entry.queued = true;
307
+ const inner = writer;
308
+ writer = (t) => { entry.queued = false; inner(t); };
309
+ }
310
+ if (this._outbox.length >= this.maxOutbox) {
311
+ if (entry) entry.queued = false;
312
+ throw new Error('rennari: outbox full');
313
+ }
264
314
  this._outbox.push(writer);
265
315
  }
266
316
 
317
+ _emit(nsp, event, payload, id) {
318
+ if (!validEventName(event)) {
319
+ throw new Error(`invalid event name '${event}'`);
320
+ }
321
+ this._dispatch(this._makeWriter(nsp, event, payload, id));
322
+ }
323
+
267
324
  _emitWithAck(nsp, event, payload, opts = {}) {
325
+ if (!validEventName(event)) {
326
+ return Promise.reject(new Error(`invalid event name '${event}'`));
327
+ }
268
328
  return new Promise((resolve, reject) => {
269
329
  const timeout = opts.timeout ?? this.defaultAckTimeout;
270
330
  const retries = opts.retries ?? this.defaultRetries;
271
331
  const id = ++this._nextId;
272
332
  const entry = {
273
333
  nsp, event, payload, id, timeout, retries,
274
- attempt: 0, resolve, reject, timer: null,
334
+ attempt: 0, queued: false, resolve, reject, timer: null,
275
335
  };
276
336
  this._pending.set(id, entry);
277
337
  this._sendPending(id);
@@ -292,7 +352,10 @@ export class Rennari {
292
352
  }
293
353
  entry.attempt++;
294
354
  try {
295
- this._emit(entry.nsp, entry.event, entry.payload, entry.id);
355
+ this._dispatch(
356
+ this._makeWriter(entry.nsp, entry.event, entry.payload, entry.id),
357
+ entry
358
+ );
296
359
  } catch (e) {
297
360
  this._pending.delete(id);
298
361
  entry.reject(e);
@@ -316,17 +379,21 @@ export class Rennari {
316
379
  this._lastOffset = frame.o;
317
380
  }
318
381
 
382
+ const d = frame.d && typeof frame.d === 'object' ? frame.d : {};
383
+
319
384
  if (frame.e === 'rennari_session') {
320
- this._sessionId = frame.d.id;
321
- this._sessionExpiresAt = Date.now() + this.recoveryWindow;
385
+ if (d.id !== undefined) {
386
+ this._sessionId = d.id;
387
+ this._sessionExpiresAt = Date.now() + this.recoveryWindow;
388
+ }
322
389
  return;
323
390
  }
324
391
  if (frame.e === 'rennari_resumed') {
325
- if (frame.d.session_id) {
326
- this._sessionId = frame.d.session_id;
392
+ if (d.session_id) {
393
+ this._sessionId = d.session_id;
327
394
  this._sessionExpiresAt = Date.now() + this.recoveryWindow;
328
395
  }
329
- this._fireLocal('/', 'recovered', { offset: frame.d.offset });
396
+ this._fireLocal('/', 'recovered', { offset: d.offset });
330
397
  return;
331
398
  }
332
399
  if (frame.e === 'rennari_resume_failed') {
@@ -339,10 +406,10 @@ export class Rennari {
339
406
  return;
340
407
  }
341
408
  if (frame.e === 'rennari_ack') {
342
- const entry = this._pending.get(frame.d.id);
409
+ const entry = this._pending.get(d.id);
343
410
  if (entry) {
344
411
  clearTimeout(entry.timer);
345
- this._pending.delete(frame.d.id);
412
+ this._pending.delete(d.id);
346
413
  entry.resolve(frame.d);
347
414
  }
348
415
  return;
package/src/transport.js CHANGED
@@ -1,13 +1,9 @@
1
1
  export class Transport {
2
- constructor(url) {
2
+ constructor(url, opts = {}) {
3
3
  this.url = url;
4
+ this.headers = opts.headers ?? null;
4
5
  this.socket = null;
5
- this.listeners = {
6
- open: [],
7
- message: [],
8
- close: [],
9
- error: [],
10
- };
6
+ this.listeners = { open: [], message: [], close: [], error: [] };
11
7
  }
12
8
 
13
9
  on(event, cb) {
@@ -18,17 +14,31 @@ export class Transport {
18
14
 
19
15
  emit(event, ...args) {
20
16
  for (const cb of this.listeners[event] || []) {
21
- try { cb(...args) } catch (_e) { /* listener errors do not break transport */ }
17
+ try { cb(...args); } catch (_e) { /* listener errors do not break transport */ }
22
18
  }
23
19
  }
24
20
 
25
21
  connect() {
26
22
  const Ctor = pickWebSocketCtor();
27
- const socket = new Ctor(this.url);
23
+ if (this.headers && typeof document !== 'undefined') {
24
+ throw new Error('rennari: headers are not supported in browsers; use the auth option');
25
+ }
26
+ const socket = this.headers
27
+ ? new Ctor(this.url, { headers: this.headers })
28
+ : new Ctor(this.url);
28
29
  if ('binaryType' in socket) socket.binaryType = 'arraybuffer';
29
30
 
30
31
  socket.addEventListener('open', () => this.emit('open'));
31
- socket.addEventListener('message', (e) => this.emit('message', toBytes(e.data)));
32
+ socket.addEventListener('message', (e) => {
33
+ try {
34
+ const bytes = toBytes(e.data);
35
+ if (bytes instanceof Promise) {
36
+ bytes.then((b) => this.emit('message', b), (err) => this.emit('error', err));
37
+ } else {
38
+ this.emit('message', bytes);
39
+ }
40
+ } catch (err) { this.emit('error', err); }
41
+ });
32
42
  socket.addEventListener('close', (e) => this.emit('close', e.code, e.reason));
33
43
  socket.addEventListener('error', (e) => this.emit('error', e));
34
44
 
@@ -42,16 +52,22 @@ export class Transport {
42
52
  }
43
53
 
44
54
  close(code, reason) {
45
- if (!this.socket) return;
46
- try { this.socket.close(code, reason) } catch (_e) { /* already closed */ }
55
+ const s = this.socket;
56
+ if (!s) return;
47
57
  this.socket = null;
58
+ try { s.close(safeCloseCode(code), reason); } catch (_e) { /* already closed */ }
48
59
  }
49
60
 
50
61
  isOpen() {
51
- return !!(this.socket && this.socket.readyState === 1);
62
+ return !!(this.socket && this.socket.readyState === 1);
52
63
  }
53
64
  }
54
65
 
66
+ function safeCloseCode(code) {
67
+ if (code === undefined) return 1000;
68
+ return code === 1000 || (code >= 3000 && code <= 4999) ? code : 1000;
69
+ }
70
+
55
71
  function toBytes(data) {
56
72
  if (data instanceof Uint8Array) return data;
57
73
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
@@ -0,0 +1,33 @@
1
+ # {{name}}
2
+
3
+ A Rennari client with one file per event handler.
4
+
5
+ 1. npm install
6
+ 2. Edit config.js: set url and token. The token must match the server.
7
+ 3. npm start
8
+
9
+ ## Adding an event handler
10
+
11
+ 1. Create handlers/my_event.mjs:
12
+
13
+ export default {
14
+ event: 'my_event',
15
+ handle(payload, client) {
16
+ console.log('got', payload);
17
+ },
18
+ };
19
+
20
+ 2. Add it to the list in handlers/index.mjs.
21
+
22
+ Handlers receive (payload, client, frame). To send something, call
23
+ client.emit('event_name', { ... }).
24
+
25
+ ## Layout
26
+
27
+ - client.mjs starts the client and handles shutdown
28
+ - lib/config.mjs checks config.js
29
+ - lib/connect.mjs creates the client and sends the token header
30
+ - handlers/ one file per event
31
+
32
+ Never put the token in the URL, in an environment variable, or on the command line.
33
+ The token header only works in Node. Browsers cannot set it.
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ config.js
@@ -0,0 +1,42 @@
1
+ import config from './config.js';
2
+ import { validateConfig } from './lib/config.mjs';
3
+ import { createClient } from './lib/connect.mjs';
4
+ import handlers from './handlers/index.mjs';
5
+
6
+ let settings;
7
+ try {
8
+ settings = validateConfig(config);
9
+ } catch (e) {
10
+ console.error(e.message);
11
+ process.exit(2);
12
+ }
13
+
14
+ const client = createClient(settings);
15
+
16
+ for (const h of handlers) {
17
+ client.on(h.event, (payload, frame) => h.handle(payload, client, frame));
18
+ }
19
+
20
+ let stopped = false;
21
+ let status = 0;
22
+
23
+ function stop(error) {
24
+ if (stopped) return;
25
+ stopped = true;
26
+ if (error) { console.error(error); status = 1; }
27
+ client.disconnect();
28
+ process.exitCode = status;
29
+ setTimeout(() => process.exit(status), 500);
30
+ }
31
+
32
+ client.on('error', (error) => stop(error?.message ?? error?.error?.message ?? 'connection failed'));
33
+ client.on('disconnect', () => { console.log('Disconnected'); stop(); });
34
+
35
+ process.once('SIGINT', () => stop());
36
+ process.once('SIGTERM', () => stop());
37
+
38
+ try {
39
+ await client.connect();
40
+ } catch {
41
+ stop();
42
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ url: 'ws://127.0.0.1:3000/ws',
3
+ token: 'CHANGE_ME', // private token, 32-256 chars of A-Za-z0-9._~-; must match the server
4
+ serializer: 'msgpack', // must match the server: 'msgpack' or 'json'
5
+ // headers: { Authorization: `Bearer ${userToken}` }, // optional user auth
6
+ };
@@ -0,0 +1,9 @@
1
+ export default {
2
+ event: 'connect',
3
+ handle(_payload, client) {
4
+ console.log('Connected');
5
+ client.emit('ping', { n: 1 });
6
+ client.emit('whoami', {});
7
+ // client.emit('join_room', { room: 'lobby' });
8
+ },
9
+ };
@@ -0,0 +1,6 @@
1
+ import connect from './connect.mjs';
2
+ import pong from './pong.mjs';
3
+ import reply from './reply.mjs';
4
+
5
+ // Add your handlers to this list.
6
+ export default [connect, pong, reply];
@@ -0,0 +1,8 @@
1
+ export default {
2
+ event: 'pong',
3
+ handle(payload) {
4
+ if (!payload || typeof payload !== 'object') return;
5
+ if (!payload.got || typeof payload.got !== 'object') return;
6
+ console.log(`pong: ${payload.got.n ?? '?'}`);
7
+ },
8
+ };
@@ -0,0 +1,10 @@
1
+ export default {
2
+ event: 'reply',
3
+ handle(payload) {
4
+ if (!payload || typeof payload !== 'object') return;
5
+ if ('error' in payload) { console.log(`server error: ${payload.error ?? 'unknown'}`); return; }
6
+ if ('name' in payload) { console.log(`reply: user_id=${payload.user_id ?? '-'} name=${payload.name ?? '-'}`); return; }
7
+ if ('joined' in payload) { console.log(`joined room: ${payload.joined}`); return; }
8
+ console.log('Reply received');
9
+ },
10
+ };
@@ -0,0 +1,16 @@
1
+ const TOKEN_RE = /^[A-Za-z0-9._~-]{32,256}$/;
2
+
3
+ export function validateConfig(c) {
4
+ const token = c?.token ?? c?.TOKEN_APP;
5
+ if (typeof token !== 'string' || !TOKEN_RE.test(token) || token === 'CHANGE_ME') {
6
+ throw new Error('config.js: set token to a private token (32-256 letters/numbers/._~-)');
7
+ }
8
+ if (typeof c.url !== 'string' || !/^wss?:\/\//.test(c.url)) {
9
+ throw new Error('config.js: url must start with ws:// or wss://');
10
+ }
11
+ const serializer = c.serializer ?? 'msgpack';
12
+ if (serializer !== 'msgpack' && serializer !== 'json') {
13
+ throw new Error('config.js: serializer must be msgpack or json');
14
+ }
15
+ return { url: c.url, token, serializer, headers: c.headers ?? {} };
16
+ }
@@ -0,0 +1,12 @@
1
+ import { WebSocket } from 'ws';
2
+ import { Rennari, setWebSocket } from '@thomas57/rennari-client-js';
3
+
4
+ export function createClient(settings) {
5
+ setWebSocket(WebSocket);
6
+ return new Rennari(settings.url, {
7
+ serializer: settings.serializer,
8
+ headers: { ...settings.headers, 'X-Rennari-App-Token': settings.token },
9
+ reconnection: false,
10
+ recovery: false,
11
+ });
12
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": { "start": "node client.mjs" },
7
+ "dependencies": {
8
+ "@thomas57/rennari-client-js": "{{clientDep}}",
9
+ "ws": "^8.0.0"
10
+ }
11
+ }
@@ -0,0 +1,13 @@
1
+ # {{name}}
2
+
3
+ A small Rennari client.
4
+
5
+ 1. npm install
6
+ 2. Edit config.js: set url and token. The token must match the server.
7
+ 3. npm start
8
+
9
+ Edit client.mjs to change what happens on connect and to add event handlers.
10
+
11
+ Never put the token in the URL, in an environment variable, or on the command line.
12
+ This client sends it in the X-Rennari-App-Token header, which only works in Node.
13
+ Browsers cannot set that header.
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ config.js
@@ -0,0 +1,94 @@
1
+ import { WebSocket } from 'ws';
2
+ import { Rennari, setWebSocket } from '@thomas57/rennari-client-js';
3
+ import config from './config.js';
4
+
5
+ const TOKEN_RE = /^[A-Za-z0-9._~-]{32,256}$/;
6
+
7
+ function validateConfig(c) {
8
+ const token = c?.token ?? c?.TOKEN_APP;
9
+ if (typeof token !== 'string' || !TOKEN_RE.test(token) || token === 'CHANGE_ME') {
10
+ throw new Error('config.js: set token to a private token (32-256 letters/numbers/._~-)');
11
+ }
12
+ if (typeof c.url !== 'string' || !/^wss?:\/\//.test(c.url)) {
13
+ throw new Error('config.js: url must start with ws:// or wss://');
14
+ }
15
+ const serializer = c.serializer ?? 'msgpack';
16
+ if (serializer !== 'msgpack' && serializer !== 'json') {
17
+ throw new Error('config.js: serializer must be msgpack or json');
18
+ }
19
+ return { url: c.url, token, serializer, headers: c.headers ?? {} };
20
+ }
21
+
22
+ let settings;
23
+ try {
24
+ settings = validateConfig(config);
25
+ } catch (e) {
26
+ console.error(e.message);
27
+ process.exit(2);
28
+ }
29
+
30
+ class RennariWebSocket extends WebSocket {
31
+ constructor(url) {
32
+ super(url, {
33
+ headers: {
34
+ ...settings.headers,
35
+ 'X-Rennari-App-Token': settings.token,
36
+ },
37
+ handshakeTimeout: 5000,
38
+ });
39
+ }
40
+ }
41
+
42
+ setWebSocket(RennariWebSocket);
43
+
44
+ const client = new Rennari(settings.url, {
45
+ serializer: settings.serializer,
46
+ reconnection: false,
47
+ recovery: false,
48
+ });
49
+
50
+ let stopped = false;
51
+ let status = 0;
52
+
53
+ function stop(error) {
54
+ if (stopped) return;
55
+ stopped = true;
56
+ if (error) { console.error(error); status = 1; }
57
+ client.disconnect();
58
+ process.exitCode = status;
59
+ setTimeout(() => process.exit(status), 500);
60
+ }
61
+
62
+ // ---- What happens when connected: edit this ----
63
+ client.on('connect', () => {
64
+ console.log('Connected');
65
+ client.emit('ping', { n: 1 });
66
+ client.emit('whoami', {});
67
+ });
68
+
69
+ // ---- Incoming events: add your own here ----
70
+ client.on('pong', (payload) => {
71
+ if (!payload || typeof payload !== 'object') return;
72
+ if (!payload.got || typeof payload.got !== 'object') return;
73
+ console.log(`pong: ${payload.got.n ?? '?'}`);
74
+ });
75
+
76
+ client.on('reply', (payload) => {
77
+ if (!payload || typeof payload !== 'object') return;
78
+ if ('error' in payload) { console.log(`server error: ${payload.error ?? 'unknown'}`); return; }
79
+ if ('name' in payload) { console.log(`reply: user_id=${payload.user_id ?? '-'} name=${payload.name ?? '-'}`); return; }
80
+ if ('joined' in payload) { console.log(`joined room: ${payload.joined}`); return; }
81
+ console.log('Reply received');
82
+ });
83
+
84
+ client.on('error', (error) => stop(error?.message ?? error?.error?.message ?? 'connection failed'));
85
+ client.on('disconnect', () => { console.log('Disconnected'); stop(); });
86
+
87
+ process.once('SIGINT', () => stop());
88
+ process.once('SIGTERM', () => stop());
89
+
90
+ try {
91
+ await client.connect();
92
+ } catch {
93
+ stop();
94
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ url: 'ws://127.0.0.1:3000/ws',
3
+ token: 'CHANGE_ME', // private token, 32-256 chars of A-Za-z0-9._~-; must match the server
4
+ serializer: 'msgpack', // must match the server: 'msgpack' or 'json'
5
+ // headers: { Authorization: `Bearer ${userToken}` }, // optional user auth
6
+ };
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": { "start": "node client.mjs" },
7
+ "dependencies": {
8
+ "@thomas57/rennari-client-js": "{{clientDep}}",
9
+ "ws": "^8.0.0"
10
+ }
11
+ }