@geekmidas/constructs 10.0.0-alpha.152 → 10.0.0-alpha.154

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.
@@ -172,127 +172,8 @@ function isRecord(value) {
172
172
  function isId(value) {
173
173
  return typeof value === "string" || typeof value === "number";
174
174
  }
175
- /** A connection string names no transport this package knows. */
176
- var UnsupportedWebSocketTransport = class extends Error {
177
- connectionString;
178
- constructor(connectionString) {
179
- super(`'${redact(connectionString)}' is not a WebSocket publisher connection string. Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.`);
180
- this.connectionString = connectionString;
181
- this.name = "UnsupportedWebSocketTransport";
182
- }
183
- };
184
- /** The scheme alone, so an error never prints a password. */
185
- function redact(connectionString) {
186
- const scheme = connectionString.split("://")[0];
187
- return scheme && scheme !== connectionString ? `${scheme}://…` : connectionString.slice(0, 12);
188
- }
189
- const key = Symbol.for("@geekmidas/constructs/websocket/memory");
190
- const registry = globalThis;
191
- registry[key] ??= /* @__PURE__ */ new Map();
192
- const channels = registry[key];
193
- /**
194
- * In one process: the server and whoever sends meet in a map, keyed by the
195
- * channel the connection string names.
196
- */
197
- var MemoryTransport = class {
198
- channel;
199
- subscribed = /* @__PURE__ */ new Set();
200
- constructor(channel) {
201
- this.channel = channel;
202
- }
203
- async publish(instance, delivery) {
204
- const instances = channels.get(this.channel);
205
- if (!instances) return;
206
- if (instance === "*") {
207
- for (const receive of instances.values()) receive(delivery);
208
- return;
209
- }
210
- instances.get(instance)?.(delivery);
211
- }
212
- async subscribe(instance, receive) {
213
- let instances = channels.get(this.channel);
214
- if (!instances) {
215
- instances = /* @__PURE__ */ new Map();
216
- channels.set(this.channel, instances);
217
- }
218
- instances.set(instance, receive);
219
- this.subscribed.add(instance);
220
- }
221
- async close() {
222
- const instances = channels.get(this.channel);
223
- for (const instance of this.subscribed) instances?.delete(instance);
224
- this.subscribed.clear();
225
- }
226
- };
227
- /**
228
- * Over Redis pub/sub: one channel per instance and one for broadcasts, under
229
- * a prefix that keeps two surfaces — or two projects on one Redis — apart.
230
- * Channels are not scoped by database index, so the prefix is what does it.
231
- *
232
- * Publishing and subscribing take separate connections, because a connection
233
- * that has subscribed can do nothing else.
234
- */
235
- var RedisTransport = class {
236
- client;
237
- prefix;
238
- subscriber;
239
- closed;
240
- constructor(client, prefix) {
241
- this.client = client;
242
- this.prefix = prefix;
243
- }
244
- channel(instance) {
245
- return `${this.prefix}:${instance}`;
246
- }
247
- async publish(instance, delivery) {
248
- await this.client.publish(this.channel(instance), JSON.stringify(delivery));
249
- }
250
- async subscribe(instance, receive) {
251
- const subscriber = this.client.duplicate();
252
- this.subscriber = subscriber;
253
- const own = this.channel(instance);
254
- const every = this.channel("*");
255
- subscriber.on("message", (channel, message) => {
256
- if (channel !== own && channel !== every) return;
257
- receive(JSON.parse(message));
258
- });
259
- await subscriber.subscribe(own, every);
260
- }
261
- /** Idempotent: the server and a shutdown hook may both close it. */
262
- close() {
263
- this.closed ??= Promise.all([this.subscriber?.quit(), this.client.quit()]).then(() => void 0);
264
- return this.closed;
265
- }
266
- };
267
- /**
268
- * The transport a connection string names.
269
- *
270
- * `redis://` and `rediss://` take an optional `channel` query parameter, the
271
- * prefix every channel is named under; `memory://<channel>` is in-process.
272
- * Absent, the channel is `fallback` — the surface's own.
273
- */
274
- async function transportFromConnectionString(connectionString, fallback) {
275
- if (connectionString.startsWith("memory://")) return new MemoryTransport(connectionString.slice(9) || fallback);
276
- const url = URL.canParse(connectionString) ? new URL(connectionString) : void 0;
277
- if (!url) throw new UnsupportedWebSocketTransport(connectionString);
278
- if (url.protocol === "redis:" || url.protocol === "rediss:") {
279
- const channel = url.searchParams.get("channel") || fallback;
280
- url.searchParams.delete("channel");
281
- const { Redis } = await import("ioredis");
282
- return new RedisTransport(new Redis(url.toString(), {
283
- maxRetriesPerRequest: null,
284
- lazyConnect: false
285
- }), channel);
286
- }
287
- throw new UnsupportedWebSocketTransport(connectionString);
288
- }
289
175
  //#endregion
290
176
  //#region src/websocket/publisher.ts
291
- /** The instance a connection id was issued by: everything before its dot. */
292
- function instanceOf(connectionId) {
293
- const dot = connectionId.indexOf(".");
294
- return dot > 0 ? connectionId.slice(0, dot) : void 0;
295
- }
296
177
  /** A message sent on an action the surface does not declare. */
297
178
  var UnknownWebSocketMessage = class extends Error {
298
179
  surface;
@@ -334,42 +215,27 @@ var InvalidWebSocketMessage = class extends Error {
334
215
  * connection is a no-op the sender rarely wants to handle.
335
216
  */
336
217
  var WebSocketPublisher = class {
337
- transport;
338
- local;
218
+ sink;
339
219
  declared;
340
220
  frame;
341
- constructor(transport, local, declared, frame = new FrameShape(declared?.surface ?? "")) {
342
- this.transport = transport;
343
- this.local = local;
221
+ constructor(sink, declared, frame = new FrameShape(declared?.surface ?? "")) {
222
+ this.sink = sink;
344
223
  this.declared = declared;
345
224
  this.frame = frame;
346
225
  }
347
226
  /** Send `action`'s message to each connection. */
348
227
  async send(ids, action, data) {
349
228
  const payload = await this.payload(action, data);
350
- await this.each(ids, (group) => ({
351
- kind: "send",
352
- ids: group,
353
- payload
354
- }));
229
+ await this.sink.send(listOf(ids), payload);
355
230
  }
356
231
  /** Send `action`'s message to every open connection, on every process. */
357
232
  async broadcast(action, data, options = {}) {
358
233
  const payload = await this.payload(action, data);
359
- await this.transport.publish("*", {
360
- kind: "broadcast",
361
- payload,
362
- ...options.except?.length ? { except: options.except } : {}
363
- });
234
+ await this.sink.broadcast(payload, options.except?.length ? options.except : void 0);
364
235
  }
365
236
  /** Close each connection, with a close code and reason its client sees. */
366
237
  async close(ids, code = 1e3, reason = "") {
367
- await this.each(ids, (group) => ({
368
- kind: "close",
369
- ids: group,
370
- code,
371
- reason
372
- }));
238
+ await this.sink.close(listOf(ids), code, reason);
373
239
  }
374
240
  /**
375
241
  * The frame, checked by the action's schema where the surface declares
@@ -387,92 +253,483 @@ var WebSocketPublisher = class {
387
253
  if (result.issues) throw new InvalidWebSocketMessage(surface, action, result.issues);
388
254
  return this.frame.encode(action, result.value);
389
255
  }
390
- /** One delivery per process that holds any of `ids`. */
391
- async each(ids, delivery) {
392
- const byInstance = /* @__PURE__ */ new Map();
393
- for (const id of typeof ids === "string" ? [ids] : ids) {
394
- const instance = instanceOf(id);
395
- if (!instance) continue;
396
- const group = byInstance.get(instance) ?? [];
397
- group.push(id);
398
- byInstance.set(instance, group);
256
+ };
257
+ function listOf(ids) {
258
+ return typeof ids === "string" ? [ids] : ids;
259
+ }
260
+ //#endregion
261
+ //#region src/websocket/core.ts
262
+ /** Two routes answer one action. */
263
+ var DuplicateWebSocketRoute = class extends Error {
264
+ surface;
265
+ action;
266
+ constructor(surface, action) {
267
+ super(`Two routes on ${surface} answer '${action}'. Each action has one handler — rename one of them.`);
268
+ this.surface = surface;
269
+ this.action = action;
270
+ this.name = "DuplicateWebSocketRoute";
271
+ }
272
+ };
273
+ var WebSocketCore = class {
274
+ options;
275
+ surface;
276
+ /** How frames are read and written — what an adaptor decodes replies by. */
277
+ frame;
278
+ /** `sockets` in every handler. */
279
+ sockets;
280
+ routes = /* @__PURE__ */ new Map();
281
+ lifecycle = {};
282
+ /**
283
+ * @throws {DuplicateWebSocketRoute} when two routes answer one action, and
284
+ * the frame checks of `FrameShape.check` for declared messages.
285
+ */
286
+ constructor(options) {
287
+ this.options = options;
288
+ this.surface = options.surface;
289
+ for (const route of options.routes) {
290
+ if (route.surface.id !== options.surface) continue;
291
+ if (route.kind === "message") {
292
+ if (this.routes.has(route.action)) throw new DuplicateWebSocketRoute(options.surface, route.action);
293
+ this.routes.set(route.action, route);
294
+ } else {
295
+ if (this.lifecycle[route.kind]) throw new DuplicateWebSocketRoute(options.surface, route.action);
296
+ this.lifecycle[route.kind] = route;
297
+ }
298
+ }
299
+ this.frame = new FrameShape(options.surface, options.frame?.discriminator);
300
+ if (options.messages) this.frame.check(options.messages);
301
+ this.sockets = new WebSocketPublisher(options.sink, options.messages ? {
302
+ surface: options.surface,
303
+ messages: options.messages
304
+ } : void 0, this.frame);
305
+ }
306
+ /**
307
+ * Run the connect handler for a handshake: accepted with the connection's
308
+ * `data` (what the handler returned, `{}` for nothing), or refused with
309
+ * the status of the `HttpError` it threw — 500 for anything else. A surface
310
+ * with no connect handler accepts every handshake, and verifies no session.
311
+ */
312
+ async connect(request, options = {}) {
313
+ const { connectionId, headers, query } = request;
314
+ const route = this.lifecycle.connect;
315
+ if (!route) return {
316
+ accepted: true,
317
+ connection: {
318
+ id: connectionId,
319
+ data: {}
320
+ }
321
+ };
322
+ try {
323
+ const session = "session" in request ? request.session : this.options.authenticator ? await this.options.authenticator.verify(headers, this.options.envParser) : null;
324
+ const returned = await this.run(route, connectionId, (base) => ({
325
+ ...base,
326
+ connectionId,
327
+ headers,
328
+ query,
329
+ session
330
+ }), options);
331
+ return {
332
+ accepted: true,
333
+ connection: {
334
+ id: connectionId,
335
+ data: returned && typeof returned === "object" ? returned : {}
336
+ }
337
+ };
338
+ } catch (error) {
339
+ if (error instanceof HttpError) return {
340
+ accepted: false,
341
+ status: error.statusCode,
342
+ statusText: error.statusMessage,
343
+ error
344
+ };
345
+ this.options.logger.error({
346
+ err: error,
347
+ connectionId
348
+ }, "WebSocket connect handler failed");
349
+ return {
350
+ accepted: false,
351
+ status: 500,
352
+ statusText: "Internal Server Error",
353
+ error
354
+ };
355
+ }
356
+ }
357
+ /**
358
+ * Parse, validate and run one inbound frame. The reply — the handler's
359
+ * return, encoded — and every `$error` are written with `write`; an error
360
+ * is a frame, never a close. A binary frame is refused: frames are text.
361
+ */
362
+ async message(connection, raw, write, options = {}) {
363
+ if (typeof raw !== "string") return this.error(write, {}, "Frames are JSON text.");
364
+ let parsed;
365
+ try {
366
+ parsed = JSON.parse(raw);
367
+ } catch {
368
+ return this.error(write, {}, "Frames are JSON.");
369
+ }
370
+ const frame = this.frame.decode(parsed);
371
+ if (!frame) return this.error(write, { id: this.frame.idOf(parsed) }, `A frame names its \`${this.frame.key}\`.`);
372
+ const { action, id } = frame;
373
+ const route = this.routes.get(action) ?? this.routes.get("$default");
374
+ if (!route) return this.error(write, {
375
+ action,
376
+ id
377
+ }, `No route answers '${action}'.`);
378
+ let body = frame.data;
379
+ if (route.schema) {
380
+ const result = await route.schema["~standard"].validate(frame.data);
381
+ if (result.issues) return this.error(write, {
382
+ action,
383
+ id
384
+ }, "The frame was invalid.", result.issues);
385
+ body = result.value;
386
+ }
387
+ try {
388
+ const returned = await this.run(route, connection.id, (base) => ({
389
+ ...base,
390
+ connection,
391
+ body,
392
+ reply: (message) => write(JSON.stringify(message))
393
+ }), options);
394
+ if (returned !== void 0) write(this.frame.encode(action, returned, id));
395
+ return {
396
+ ok: true,
397
+ action,
398
+ ...id !== void 0 ? { id } : {},
399
+ returned
400
+ };
401
+ } catch (error) {
402
+ if (error instanceof HttpError) return this.error(write, {
403
+ action,
404
+ id
405
+ }, error.message, void 0, error);
406
+ this.options.logger.error({
407
+ err: error,
408
+ connectionId: connection.id,
409
+ action
410
+ }, "WebSocket route failed");
411
+ return this.error(write, {
412
+ action,
413
+ id
414
+ }, "The route failed.", void 0, error);
415
+ }
416
+ }
417
+ /**
418
+ * Run the disconnect handler for a connection that has closed. What it
419
+ * throws is logged and returned, never thrown: the socket is gone either
420
+ * way.
421
+ */
422
+ async disconnect(connection, close, options = {}) {
423
+ const route = this.lifecycle.disconnect;
424
+ if (!route) return { ok: true };
425
+ try {
426
+ await this.run(route, connection.id, (base) => ({
427
+ ...base,
428
+ connection,
429
+ ...close
430
+ }), options);
431
+ return { ok: true };
432
+ } catch (error) {
433
+ this.options.logger.error({
434
+ err: error,
435
+ connectionId: connection.id
436
+ }, "WebSocket disconnect handler failed");
437
+ return {
438
+ ok: false,
439
+ error
440
+ };
441
+ }
442
+ }
443
+ /** Run a handler with its services, inside a request context of its own. */
444
+ async run(route, connectionId, context, options) {
445
+ const logger = this.options.logger.child({
446
+ connectionId,
447
+ action: route.action
448
+ });
449
+ return runWithRequestContext({
450
+ logger,
451
+ requestId: connectionId,
452
+ startTime: Date.now(),
453
+ operation: `ws ${route.action}`
454
+ }, async () => {
455
+ const services = await this.services(route, options.services);
456
+ return route.handler(context({
457
+ services,
458
+ logger,
459
+ sockets: this.sockets
460
+ }));
461
+ });
462
+ }
463
+ /** The route's services: the overrides it names, the rest registered. */
464
+ async services(route, overrides = {}) {
465
+ const given = {};
466
+ const wanted = route.services.filter((service) => {
467
+ if (!Object.hasOwn(overrides, service.serviceName)) return true;
468
+ given[service.serviceName] = overrides[service.serviceName];
469
+ return false;
470
+ });
471
+ return {
472
+ ...wanted.length ? await ServiceDiscovery.getInstance(this.options.envParser).register([...wanted]) : {},
473
+ ...given
474
+ };
475
+ }
476
+ error(write, at, message, issues, error) {
477
+ write(this.frame.encode("$error", {
478
+ message,
479
+ ...issues ? { issues } : {}
480
+ }, at.id));
481
+ return {
482
+ ok: false,
483
+ ...at.action !== void 0 ? { action: at.action } : {},
484
+ ...at.id !== void 0 ? { id: at.id } : {},
485
+ message,
486
+ ...issues ? { issues } : {},
487
+ ...error !== void 0 ? { error } : {}
488
+ };
489
+ }
490
+ };
491
+ //#endregion
492
+ //#region src/websocket/route.ts
493
+ /**
494
+ * A handler bound to a WebSocket surface — what `realtime.route('chat.send')
495
+ * …handle()` returns, and what a file exports.
496
+ *
497
+ * Carries `surface` and `constructs` the way an endpoint does, so discovery
498
+ * records what its process reaches without knowing what a route is.
499
+ */
500
+ var WebSocketRoute = class {
501
+ kind;
502
+ action;
503
+ surface;
504
+ services;
505
+ constructs;
506
+ handler;
507
+ schema;
508
+ __IS_WEBSOCKET_ROUTE__ = true;
509
+ static isRoute(value) {
510
+ return Boolean(value && value.__IS_WEBSOCKET_ROUTE__ === true);
511
+ }
512
+ constructor(kind, action, surface, services, constructs, handler, schema) {
513
+ this.kind = kind;
514
+ this.action = action;
515
+ this.surface = surface;
516
+ this.services = services;
517
+ this.constructs = constructs;
518
+ this.handler = handler;
519
+ this.schema = schema;
520
+ }
521
+ };
522
+ /** The builder `connect()`, `disconnect()` and `route()` start. */
523
+ var WebSocketRouteBuilder = class WebSocketRouteBuilder {
524
+ kind;
525
+ action;
526
+ surface;
527
+ _services;
528
+ _constructs;
529
+ schema;
530
+ constructor(kind, action, surface, _services = [], _constructs = [], schema) {
531
+ this.kind = kind;
532
+ this.action = action;
533
+ this.surface = surface;
534
+ this._services = _services;
535
+ this._constructs = _constructs;
536
+ this.schema = schema;
537
+ }
538
+ /** The schema a frame's `data` must satisfy before the handler runs. */
539
+ body(schema) {
540
+ return new WebSocketRouteBuilder(this.kind, this.action, this.surface, this._services, this._constructs, schema);
541
+ }
542
+ /** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */
543
+ dependsOn(constructs) {
544
+ return new WebSocketRouteBuilder(this.kind, this.action, this.surface, [...this._services, ...servicesOf(constructs)], idsOf(constructs, this._constructs), this.schema);
545
+ }
546
+ /**
547
+ * The handler. A message handler's return value, when there is one, is
548
+ * sent back to the connection as the reply to that frame; a connect
549
+ * handler's is kept as the connection's `data`.
550
+ */
551
+ handle(handler) {
552
+ return new WebSocketRoute(this.kind, this.action, this.surface, this._services, this._constructs, handler, this.schema);
553
+ }
554
+ };
555
+ /** The instance a connection id was issued by: everything before its dot. */
556
+ function instanceOf(connectionId) {
557
+ const dot = connectionId.indexOf(".");
558
+ return dot > 0 ? connectionId.slice(0, dot) : void 0;
559
+ }
560
+ /**
561
+ * A publisher's sink over a transport: a send goes to the instance each
562
+ * connection id names, a broadcast to every instance. What `services.<id>`
563
+ * sends through, and what the Node adaptor's own `sockets` do.
564
+ */
565
+ var TransportSink = class {
566
+ transport;
567
+ local;
568
+ constructor(transport, local) {
569
+ this.transport = transport;
570
+ this.local = local;
571
+ }
572
+ send(ids, payload) {
573
+ return this.each(ids, (group) => ({
574
+ kind: "send",
575
+ ids: group,
576
+ payload
577
+ }));
578
+ }
579
+ async broadcast(payload, except) {
580
+ await this.transport.publish("*", {
581
+ kind: "broadcast",
582
+ payload,
583
+ ...except?.length ? { except } : {}
584
+ });
585
+ }
586
+ close(ids, code, reason) {
587
+ return this.each(ids, (group) => ({
588
+ kind: "close",
589
+ ids: group,
590
+ code,
591
+ reason
592
+ }));
593
+ }
594
+ /** One delivery per process that holds any of `ids`. */
595
+ async each(ids, delivery) {
596
+ const byInstance = /* @__PURE__ */ new Map();
597
+ for (const id of ids) {
598
+ const instance = instanceOf(id);
599
+ if (!instance) continue;
600
+ const group = byInstance.get(instance) ?? [];
601
+ group.push(id);
602
+ byInstance.set(instance, group);
603
+ }
604
+ await Promise.all([...byInstance].map(([instance, group]) => this.local?.instance === instance ? this.local.deliver(delivery(group)) : this.transport.publish(instance, delivery(group))));
605
+ }
606
+ };
607
+ /** A connection string names no transport this package knows. */
608
+ var UnsupportedWebSocketTransport = class extends Error {
609
+ connectionString;
610
+ constructor(connectionString) {
611
+ super(`'${redact(connectionString)}' is not a WebSocket publisher connection string. Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.`);
612
+ this.connectionString = connectionString;
613
+ this.name = "UnsupportedWebSocketTransport";
614
+ }
615
+ };
616
+ /** The scheme alone, so an error never prints a password. */
617
+ function redact(connectionString) {
618
+ const scheme = connectionString.split("://")[0];
619
+ return scheme && scheme !== connectionString ? `${scheme}://…` : connectionString.slice(0, 12);
620
+ }
621
+ const key = Symbol.for("@geekmidas/constructs/websocket/memory");
622
+ const registry = globalThis;
623
+ registry[key] ??= /* @__PURE__ */ new Map();
624
+ const channels = registry[key];
625
+ /**
626
+ * In one process: the server and whoever sends meet in a map, keyed by the
627
+ * channel the connection string names.
628
+ */
629
+ var MemoryTransport = class {
630
+ channel;
631
+ subscribed = /* @__PURE__ */ new Set();
632
+ constructor(channel) {
633
+ this.channel = channel;
634
+ }
635
+ async publish(instance, delivery) {
636
+ const instances = channels.get(this.channel);
637
+ if (!instances) return;
638
+ if (instance === "*") {
639
+ for (const receive of instances.values()) receive(delivery);
640
+ return;
399
641
  }
400
- await Promise.all([...byInstance].map(([instance, group]) => this.local?.instance === instance ? this.local.deliver(delivery(group)) : this.transport.publish(instance, delivery(group))));
642
+ instances.get(instance)?.(delivery);
643
+ }
644
+ async subscribe(instance, receive) {
645
+ let instances = channels.get(this.channel);
646
+ if (!instances) {
647
+ instances = /* @__PURE__ */ new Map();
648
+ channels.set(this.channel, instances);
649
+ }
650
+ instances.set(instance, receive);
651
+ this.subscribed.add(instance);
652
+ }
653
+ async close() {
654
+ const instances = channels.get(this.channel);
655
+ for (const instance of this.subscribed) instances?.delete(instance);
656
+ this.subscribed.clear();
401
657
  }
402
658
  };
403
- //#endregion
404
- //#region src/websocket/route.ts
405
659
  /**
406
- * A handler bound to a WebSocket surface — what `realtime.route('chat.send')
407
- * …handle()` returns, and what a file exports.
660
+ * Over Redis pub/sub: one channel per instance and one for broadcasts, under
661
+ * a prefix that keeps two surfaces — or two projects on one Redis — apart.
662
+ * Channels are not scoped by database index, so the prefix is what does it.
408
663
  *
409
- * Carries `surface` and `constructs` the way an endpoint does, so discovery
410
- * records what its process reaches without knowing what a route is.
664
+ * Publishing and subscribing take separate connections, because a connection
665
+ * that has subscribed can do nothing else.
411
666
  */
412
- var WebSocketRoute = class {
413
- kind;
414
- action;
415
- surface;
416
- services;
417
- constructs;
418
- handler;
419
- schema;
420
- __IS_WEBSOCKET_ROUTE__ = true;
421
- static isRoute(value) {
422
- return Boolean(value && value.__IS_WEBSOCKET_ROUTE__ === true);
423
- }
424
- constructor(kind, action, surface, services, constructs, handler, schema) {
425
- this.kind = kind;
426
- this.action = action;
427
- this.surface = surface;
428
- this.services = services;
429
- this.constructs = constructs;
430
- this.handler = handler;
431
- this.schema = schema;
667
+ var RedisTransport = class {
668
+ client;
669
+ prefix;
670
+ subscriber;
671
+ closed;
672
+ constructor(client, prefix) {
673
+ this.client = client;
674
+ this.prefix = prefix;
432
675
  }
433
- };
434
- /** The builder `connect()`, `disconnect()` and `route()` start. */
435
- var WebSocketRouteBuilder = class WebSocketRouteBuilder {
436
- kind;
437
- action;
438
- surface;
439
- _services;
440
- _constructs;
441
- schema;
442
- constructor(kind, action, surface, _services = [], _constructs = [], schema) {
443
- this.kind = kind;
444
- this.action = action;
445
- this.surface = surface;
446
- this._services = _services;
447
- this._constructs = _constructs;
448
- this.schema = schema;
676
+ channel(instance) {
677
+ return `${this.prefix}:${instance}`;
449
678
  }
450
- /** The schema a frame's `data` must satisfy before the handler runs. */
451
- body(schema) {
452
- return new WebSocketRouteBuilder(this.kind, this.action, this.surface, this._services, this._constructs, schema);
679
+ async publish(instance, delivery) {
680
+ await this.client.publish(this.channel(instance), JSON.stringify(delivery));
453
681
  }
454
- /** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */
455
- dependsOn(constructs) {
456
- return new WebSocketRouteBuilder(this.kind, this.action, this.surface, [...this._services, ...servicesOf(constructs)], idsOf(constructs, this._constructs), this.schema);
682
+ async subscribe(instance, receive) {
683
+ const subscriber = this.client.duplicate();
684
+ this.subscriber = subscriber;
685
+ const own = this.channel(instance);
686
+ const every = this.channel("*");
687
+ subscriber.on("message", (channel, message) => {
688
+ if (channel !== own && channel !== every) return;
689
+ receive(JSON.parse(message));
690
+ });
691
+ await subscriber.subscribe(own, every);
457
692
  }
458
- /**
459
- * The handler. A message handler's return value, when there is one, is
460
- * sent back to the connection as the reply to that frame; a connect
461
- * handler's is kept as the connection's `data`.
462
- */
463
- handle(handler) {
464
- return new WebSocketRoute(this.kind, this.action, this.surface, this._services, this._constructs, handler, this.schema);
693
+ /** Idempotent: the server and a shutdown hook may both close it. */
694
+ close() {
695
+ this.closed ??= Promise.all([this.subscriber?.quit(), this.client.quit()]).then(() => void 0);
696
+ return this.closed;
465
697
  }
466
698
  };
699
+ /**
700
+ * The transport a connection string names.
701
+ *
702
+ * `redis://` and `rediss://` take an optional `channel` query parameter, the
703
+ * prefix every channel is named under; `memory://<channel>` is in-process.
704
+ * Absent, the channel is `fallback` — the surface's own.
705
+ */
706
+ async function transportFromConnectionString(connectionString, fallback) {
707
+ if (connectionString.startsWith("memory://")) return new MemoryTransport(connectionString.slice(9) || fallback);
708
+ const url = URL.canParse(connectionString) ? new URL(connectionString) : void 0;
709
+ if (!url) throw new UnsupportedWebSocketTransport(connectionString);
710
+ if (url.protocol === "redis:" || url.protocol === "rediss:") {
711
+ const channel = url.searchParams.get("channel") || fallback;
712
+ url.searchParams.delete("channel");
713
+ const { Redis } = await import("ioredis");
714
+ return new RedisTransport(new Redis(url.toString(), {
715
+ maxRetriesPerRequest: null,
716
+ lazyConnect: false
717
+ }), channel);
718
+ }
719
+ throw new UnsupportedWebSocketTransport(connectionString);
720
+ }
467
721
  //#endregion
468
722
  //#region src/websocket/server.ts
469
723
  /**
470
- * The process that holds a WebSocket surface's sockets.
724
+ * The Node adaptor: the process that holds a WebSocket surface's sockets.
471
725
  *
472
- * Node's own `http` server and `ws`, nothing between them: a frame is parsed,
473
- * validated and handed to its route, and that is the whole hot path. The HTTP
474
- * server is whatever the entry started — the generated one serves `/health`
475
- * on the same port — and this attaches to its `upgrade` event.
726
+ * Node's own `http` server and `ws`, nothing between them. This owns what
727
+ * only a real socket has — the upgrade, the Origin check, connection ids,
728
+ * the heartbeat, backpressure — and hands the rest to the surface's
729
+ * `WebSocketCore`: a handshake to `connect()`, each frame to `message()`, a
730
+ * close to `disconnect()`. The HTTP server is whatever the entry started —
731
+ * the generated one serves `/health` on the same port — and this attaches to
732
+ * its `upgrade` event.
476
733
  */
477
734
  /** Close codes a client sees. */
478
735
  const CLOSE = {
@@ -482,55 +739,26 @@ const CLOSE = {
482
739
  /** It stopped reading, and what was queued for it passed the limit. */
483
740
  tooSlow: 1013
484
741
  };
485
- /** Two routes answer one action. */
486
- var DuplicateWebSocketRoute = class extends Error {
487
- surface;
488
- action;
489
- constructor(surface, action) {
490
- super(`Two routes on ${surface} answer '${action}'. Each action has one handler — rename one of them.`);
491
- this.surface = surface;
492
- this.action = action;
493
- this.name = "DuplicateWebSocketRoute";
494
- }
495
- };
496
742
  var WebSocketSurfaceServer = class WebSocketSurfaceServer {
497
743
  wss;
498
744
  options;
499
745
  /** This process, as connection ids name it. */
500
746
  instance = randomBytes(6).toString("hex");
501
- /** `sockets` in a route: local sends skip the transport. */
502
- publisher;
747
+ /** Where each handshake, frame and close is handed. */
748
+ core;
503
749
  held = /* @__PURE__ */ new Map();
504
- routes = /* @__PURE__ */ new Map();
505
- lifecycle = {};
506
750
  heartbeat;
507
- frame;
508
751
  trusted;
509
752
  next = 0;
510
753
  closing = false;
511
754
  constructor(wss, options) {
512
755
  this.wss = wss;
513
756
  this.options = options;
514
- for (const route of options.routes) {
515
- if (route.surface.id !== options.surface) continue;
516
- if (route.kind === "message") {
517
- if (this.routes.has(route.action)) throw new DuplicateWebSocketRoute(options.surface, route.action);
518
- this.routes.set(route.action, route);
519
- } else {
520
- if (this.lifecycle[route.kind]) throw new DuplicateWebSocketRoute(options.surface, route.action);
521
- this.lifecycle[route.kind] = route;
522
- }
523
- }
524
- this.frame = new FrameShape(options.surface, options.frame?.discriminator);
525
- if (options.messages) this.frame.check(options.messages);
526
- this.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];
527
- this.publisher = new WebSocketPublisher(options.transport, {
757
+ this.core = options.core(new TransportSink(options.transport, {
528
758
  instance: this.instance,
529
759
  deliver: (delivery) => this.deliver(delivery)
530
- }, options.messages ? {
531
- surface: options.surface,
532
- messages: options.messages
533
- } : void 0, this.frame);
760
+ }));
761
+ this.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];
534
762
  this.heartbeat = setInterval(() => this.beat(), options.heartbeatMs ?? 3e4);
535
763
  this.heartbeat.unref();
536
764
  }
@@ -546,6 +774,10 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
546
774
  await options.transport.subscribe(server.instance, (delivery) => server.deliver(delivery));
547
775
  return server;
548
776
  }
777
+ /** `sockets` in a route: local sends skip the transport. */
778
+ get publisher() {
779
+ return this.core.sockets;
780
+ }
549
781
  /** How many sockets this process holds. */
550
782
  get size() {
551
783
  return this.held.size;
@@ -561,33 +793,14 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
561
793
  if (this.closing) return refuse(socket, 503, "Service Unavailable");
562
794
  const origin = request.headers.origin;
563
795
  if (origin && !trustsOrigin(origin, this.trusted)) return refuse(socket, 403, "Forbidden");
564
- const connectionId = `${this.instance}.${(this.next++).toString(36)}`;
565
- const headers = headersOf(request);
566
- let data = {};
567
- const connect = this.lifecycle.connect;
568
- if (connect) try {
569
- const session = this.options.authenticator ? await this.options.authenticator.verify(headers, this.options.envParser) : null;
570
- const returned = await this.run(connect, connectionId, (base) => ({
571
- ...base,
572
- connectionId,
573
- headers,
574
- query: new URL(request.url ?? "/", "http://localhost").searchParams,
575
- session
576
- }));
577
- if (returned && typeof returned === "object") data = returned;
578
- } catch (error) {
579
- if (error instanceof HttpError) return refuse(socket, error.statusCode, error.statusMessage);
580
- this.options.logger.error({
581
- err: error,
582
- connectionId
583
- }, "WebSocket connect handler failed");
584
- return refuse(socket, 500, "Internal Server Error");
585
- }
796
+ const outcome = await this.core.connect({
797
+ connectionId: `${this.instance}.${(this.next++).toString(36)}`,
798
+ headers: headersOf(request),
799
+ query: new URL(request.url ?? "/", "http://localhost").searchParams
800
+ });
801
+ if (!outcome.accepted) return refuse(socket, outcome.status, outcome.statusText);
586
802
  if (socket.destroyed) return;
587
- this.wss.handleUpgrade(request, socket, head, (ws) => this.open(ws, {
588
- id: connectionId,
589
- data
590
- }));
803
+ this.wss.handleUpgrade(request, socket, head, (ws) => this.open(ws, outcome.connection));
591
804
  }
592
805
  open(socket, connection) {
593
806
  const held = {
@@ -596,92 +809,23 @@ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
596
809
  alive: true
597
810
  };
598
811
  this.held.set(connection.id, held);
812
+ const write = (payload) => this.write(held, payload);
599
813
  socket.on("pong", () => {
600
814
  held.alive = true;
601
815
  });
602
816
  socket.on("message", (raw, isBinary) => {
603
817
  held.alive = true;
604
- if (isBinary) return this.error(held, void 0, "Frames are JSON text.");
605
- this.dispatch(held, raw.toString());
818
+ this.core.message(connection, isBinary ? bytesOf(raw) : raw.toString(), write);
606
819
  });
607
820
  socket.on("error", () => socket.terminate());
608
821
  socket.on("close", (code, reason) => {
609
822
  this.held.delete(connection.id);
610
- const disconnect = this.lifecycle.disconnect;
611
- if (!disconnect) return;
612
- this.run(disconnect, connection.id, (base) => ({
613
- ...base,
614
- connection,
823
+ this.core.disconnect(connection, {
615
824
  code,
616
825
  reason: reason.toString()
617
- })).catch((error) => this.options.logger.error({
618
- err: error,
619
- connectionId: connection.id
620
- }, "WebSocket disconnect handler failed"));
621
- });
622
- }
623
- /** Parse, validate and run one frame. Errors go back as frames, not closes. */
624
- async dispatch(held, text) {
625
- let parsed;
626
- try {
627
- parsed = JSON.parse(text);
628
- } catch {
629
- return this.error(held, void 0, "Frames are JSON.");
630
- }
631
- const frame = this.frame.decode(parsed);
632
- if (!frame) return this.error(held, this.frame.idOf(parsed), `A frame names its \`${this.frame.key}\`.`);
633
- const route = this.routes.get(frame.action) ?? this.routes.get("$default");
634
- if (!route) return this.error(held, frame.id, `No route answers '${frame.action}'.`);
635
- let body = frame.data;
636
- if (route.schema) {
637
- const result = await route.schema["~standard"].validate(frame.data);
638
- if (result.issues) return this.error(held, frame.id, "The frame was invalid.", result.issues);
639
- body = result.value;
640
- }
641
- try {
642
- const returned = await this.run(route, held.connection.id, (base) => ({
643
- ...base,
644
- connection: held.connection,
645
- body,
646
- reply: (message) => this.write(held, JSON.stringify(message))
647
- }));
648
- if (returned !== void 0) this.write(held, this.frame.encode(frame.action, returned, frame.id));
649
- } catch (error) {
650
- if (error instanceof HttpError) return this.error(held, frame.id, error.message);
651
- this.options.logger.error({
652
- err: error,
653
- connectionId: held.connection.id,
654
- action: frame.action
655
- }, "WebSocket route failed");
656
- this.error(held, frame.id, "The route failed.");
657
- }
658
- }
659
- /** Run a handler with its services, inside a request context of its own. */
660
- async run(route, connectionId, context) {
661
- const logger = this.options.logger.child({
662
- connectionId,
663
- action: route.action
664
- });
665
- return runWithRequestContext({
666
- logger,
667
- requestId: connectionId,
668
- startTime: Date.now(),
669
- operation: `ws ${route.action}`
670
- }, async () => {
671
- const services = route.services.length ? await ServiceDiscovery.getInstance(this.options.envParser).register([...route.services]) : {};
672
- return route.handler(context({
673
- services,
674
- logger,
675
- sockets: this.publisher
676
- }));
826
+ });
677
827
  });
678
828
  }
679
- error(held, id, message, issues) {
680
- this.write(held, this.frame.encode("$error", {
681
- message,
682
- ...issues ? { issues } : {}
683
- }, id));
684
- }
685
829
  /** Write, unless the socket has stopped reading and its queue is full. */
686
830
  write(held, payload) {
687
831
  const { socket } = held;
@@ -756,6 +900,11 @@ function ownOrigins(url) {
756
900
  const web = new URL(url.replace(/^ws(s?):/i, "http$1:"));
757
901
  return [.../* @__PURE__ */ new Set([`${own.protocol}//${own.host}`, web.origin])];
758
902
  }
903
+ /** A binary frame's bytes, however `ws` delivered them. */
904
+ function bytesOf(raw) {
905
+ if (Array.isArray(raw)) return Buffer.concat(raw);
906
+ return raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw;
907
+ }
759
908
  function headersOf(request) {
760
909
  const headers = new Headers();
761
910
  for (const [name, value] of Object.entries(request.headers)) {
@@ -828,7 +977,7 @@ var WebSocketApi = class WebSocketApi {
828
977
  const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
829
978
  const transport = await transportFromConnectionString(connectionString, channel);
830
979
  onShutdown(() => transport.close());
831
- return new WebSocketPublisher(transport, void 0, declared, frame);
980
+ return new WebSocketPublisher(new TransportSink(transport), declared, frame);
832
981
  }
833
982
  };
834
983
  }
@@ -862,23 +1011,20 @@ var WebSocketApi = class WebSocketApi {
862
1011
  */
863
1012
  async server(options) {
864
1013
  const { Hono } = await import("hono");
865
- const routes = (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute));
866
1014
  const { connectionString, origins, url } = options.envParser.create((get) => ({
867
1015
  connectionString: get(this.keys.publisherConnectionString).string().default(`memory://${channelOf(this.id)}`),
868
1016
  origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean)),
869
1017
  url: get(this.keys.url).string().optional()
870
1018
  })).parse();
871
1019
  const server = await WebSocketSurfaceServer.start({
872
- surface: this.id,
873
- routes,
1020
+ core: (sink) => this.core({
1021
+ envParser: options.envParser,
1022
+ sink,
1023
+ ...options.modules ? { modules: options.modules } : {}
1024
+ }),
874
1025
  transport: await transportFromConnectionString(connectionString, channelOf(this.id)),
875
- envParser: options.envParser,
876
- logger: this.logger,
877
1026
  trustedOrigins: origins,
878
1027
  ...url ? { url } : {},
879
- ...this.config.frame ? { frame: this.config.frame } : {},
880
- ...this.declared ? { messages: this.declared.messages } : {},
881
- ...this.authenticator ? { authenticator: this.authenticator } : {},
882
1028
  ...this.config.heartbeat ? { heartbeatMs: this.config.heartbeat * 1e3 } : {},
883
1029
  ...this.config.maxPayload ? { maxPayload: this.config.maxPayload } : {}
884
1030
  });
@@ -899,6 +1045,29 @@ var WebSocketApi = class WebSocketApi {
899
1045
  server
900
1046
  };
901
1047
  }
1048
+ /**
1049
+ * The surface with no socket in it — what every runtime serves. The
1050
+ * routes exported by `modules` that were built from this surface answer
1051
+ * its frames; `sink` is where its handlers' `sockets` send.
1052
+ *
1053
+ * `server()` is the Node adaptor over it. Another runtime (a Lambda
1054
+ * behind API Gateway, a test) builds one with a sink of its own and
1055
+ * calls `connect()`, `message()` and `disconnect()` per connection id.
1056
+ *
1057
+ * @throws {DuplicateWebSocketRoute} when two routes answer one action.
1058
+ */
1059
+ core(options) {
1060
+ return new WebSocketCore({
1061
+ surface: this.id,
1062
+ routes: (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute)),
1063
+ sink: options.sink,
1064
+ envParser: options.envParser,
1065
+ logger: this.logger,
1066
+ ...this.config.frame ? { frame: this.config.frame } : {},
1067
+ ...this.declared ? { messages: this.declared.messages } : {},
1068
+ ...this.authenticator ? { authenticator: this.authenticator } : {}
1069
+ });
1070
+ }
902
1071
  /** The declared messages, with the surface they are checked for. */
903
1072
  get declared() {
904
1073
  return this.config.messages ? {
@@ -928,6 +1097,6 @@ function channelOf(id) {
928
1097
  return `gkm:ws:${id}`;
929
1098
  }
930
1099
  //#endregion
931
- export { CLOSE, DuplicateWebSocketRoute, InvalidReplicaCount, InvalidWebSocketMessage, MemoryTransport, RedisTransport, UnknownWebSocketMessage, UnsupportedWebSocketTransport, WebSocketApi, WebSocketDataHasDiscriminator, WebSocketDataNotAnObject, WebSocketMessageDeclaresDiscriminator, WebSocketMessageNotAnObject, WebSocketPublisher, WebSocketRoute, WebSocketRouteBuilder, WebSocketSurfaceServer, transportFromConnectionString };
1100
+ export { CLOSE, DuplicateWebSocketRoute, InvalidReplicaCount, InvalidWebSocketMessage, MemoryTransport, RedisTransport, TransportSink, UnknownWebSocketMessage, UnsupportedWebSocketTransport, WebSocketApi, WebSocketCore, WebSocketDataHasDiscriminator, WebSocketDataNotAnObject, WebSocketMessageDeclaresDiscriminator, WebSocketMessageNotAnObject, WebSocketPublisher, WebSocketRoute, WebSocketRouteBuilder, WebSocketSurfaceServer, transportFromConnectionString };
932
1101
 
933
1102
  //# sourceMappingURL=websocket-api.mjs.map