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

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