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

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.
@@ -0,0 +1,1439 @@
1
+ const require_shutdown = require("./shutdown-BMJmAhSt.cjs");
2
+ const require_construct_interface = require("./construct-interface.cjs");
3
+ const require_surfaceEnv = require("./surfaceEnv-CNimK76p.cjs");
4
+ let _geekmidas_manifest = require("@geekmidas/manifest");
5
+ let _geekmidas_logger_console = require("@geekmidas/logger/console");
6
+ let node_crypto = require("node:crypto");
7
+ let _geekmidas_services = require("@geekmidas/services");
8
+ let _geekmidas_errors = require("@geekmidas/errors");
9
+ let _geekmidas_schema_conversion = require("@geekmidas/schema/conversion");
10
+ //#region src/websocket/frame.ts
11
+ /**
12
+ * The shape a surface's frames take on the wire.
13
+ *
14
+ * By default a frame is `{ "action": …, "id"?: …, "data": … }` — API
15
+ * Gateway's shape. A surface that names a discriminator — `frame: {
16
+ * discriminator: 'type' }` — sends and reads flat frames instead: the action
17
+ * under that key, and the data's own fields beside it.
18
+ *
19
+ * ```json
20
+ * {"type":"chat.message.created","chatId":"c1","message":{…}}
21
+ * ```
22
+ *
23
+ * A flat frame has no `id` of its own: every field but the discriminator is
24
+ * the data, so a reply is paired by its action, not an echoed id.
25
+ */
26
+ /** A declared message whose schema does not describe an object. */
27
+ var WebSocketMessageNotAnObject = class extends Error {
28
+ surface;
29
+ action;
30
+ discriminator;
31
+ constructor(surface, action, discriminator) {
32
+ super(`${surface} sends flat frames, keyed by '${discriminator}', so each message's fields sit beside it — but '${action}' is not an object schema. Declare it as an object (z.object({ … })), or drop \`frame\` to send { action, data }.`);
33
+ this.surface = surface;
34
+ this.action = action;
35
+ this.discriminator = discriminator;
36
+ this.name = "WebSocketMessageNotAnObject";
37
+ }
38
+ };
39
+ /** A declared message whose schema has a field named the discriminator. */
40
+ var WebSocketMessageDeclaresDiscriminator = class extends Error {
41
+ surface;
42
+ action;
43
+ discriminator;
44
+ constructor(surface, action, discriminator) {
45
+ super(`${surface}'s '${action}' message declares a '${discriminator}' field, which is where its flat frames keep the action. Rename the field, or give \`frame.discriminator\` a key no message uses.`);
46
+ this.surface = surface;
47
+ this.action = action;
48
+ this.discriminator = discriminator;
49
+ this.name = "WebSocketMessageDeclaresDiscriminator";
50
+ }
51
+ };
52
+ /** Data sent in a flat frame that is not an object. */
53
+ var WebSocketDataNotAnObject = class extends Error {
54
+ surface;
55
+ action;
56
+ discriminator;
57
+ constructor(surface, action, discriminator) {
58
+ super(`${surface} sends flat frames, keyed by '${discriminator}', and '${action}''s data is not an object, so it has no fields to put beside it. Send an object. Nothing was sent.`);
59
+ this.surface = surface;
60
+ this.action = action;
61
+ this.discriminator = discriminator;
62
+ this.name = "WebSocketDataNotAnObject";
63
+ }
64
+ };
65
+ /** Data sent in a flat frame that carries the discriminator itself. */
66
+ var WebSocketDataHasDiscriminator = class extends Error {
67
+ surface;
68
+ action;
69
+ discriminator;
70
+ constructor(surface, action, discriminator) {
71
+ super(`'${action}''s data on ${surface} has a '${discriminator}' field, which is where its flat frames keep the action. Rename the field. Nothing was sent.`);
72
+ this.surface = surface;
73
+ this.action = action;
74
+ this.discriminator = discriminator;
75
+ this.name = "WebSocketDataHasDiscriminator";
76
+ }
77
+ };
78
+ /** How one surface writes and reads its frames. */
79
+ var FrameShape = class {
80
+ surface;
81
+ discriminator;
82
+ constructor(surface, discriminator) {
83
+ this.surface = surface;
84
+ this.discriminator = discriminator;
85
+ }
86
+ /** The key an inbound frame names its action under. */
87
+ get key() {
88
+ return this.discriminator ?? "action";
89
+ }
90
+ /**
91
+ * The frame for `action`'s `data`, serialised.
92
+ *
93
+ * @throws {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator} for
94
+ * a flat frame whose data cannot sit beside the discriminator.
95
+ */
96
+ encode(action, data, id) {
97
+ const { discriminator } = this;
98
+ if (discriminator === void 0) return JSON.stringify({
99
+ action,
100
+ ...id !== void 0 ? { id } : {},
101
+ data
102
+ });
103
+ if (!isRecord(data)) throw new WebSocketDataNotAnObject(this.surface, action, discriminator);
104
+ if (Object.hasOwn(data, discriminator)) throw new WebSocketDataHasDiscriminator(this.surface, action, discriminator);
105
+ return JSON.stringify({
106
+ [discriminator]: action,
107
+ ...data
108
+ });
109
+ }
110
+ /** A parsed frame's action, id and data — `undefined` when it names none. */
111
+ decode(frame) {
112
+ if (!isRecord(frame)) return void 0;
113
+ const { discriminator } = this;
114
+ if (discriminator === void 0) {
115
+ if (typeof frame.action !== "string") return void 0;
116
+ return {
117
+ action: frame.action,
118
+ ...isId(frame.id) ? { id: frame.id } : {},
119
+ data: frame.data
120
+ };
121
+ }
122
+ const { [discriminator]: action, ...data } = frame;
123
+ if (typeof action !== "string") return void 0;
124
+ return {
125
+ action,
126
+ data
127
+ };
128
+ }
129
+ /** The id a frame that names no action carried, to echo on its error. */
130
+ idOf(frame) {
131
+ if (this.discriminator !== void 0 || !isRecord(frame)) return void 0;
132
+ return isId(frame.id) ? frame.id : void 0;
133
+ }
134
+ /**
135
+ * Refuse a declared message a flat frame cannot carry: one that is not an
136
+ * object, or that has a field named the discriminator.
137
+ *
138
+ * @throws {WebSocketMessageNotAnObject}, {WebSocketMessageDeclaresDiscriminator}
139
+ */
140
+ check(messages) {
141
+ const { discriminator } = this;
142
+ if (discriminator === void 0) return;
143
+ for (const [action, schema] of Object.entries(messages)) {
144
+ const shape = objectShape((0, _geekmidas_schema_conversion.toJsonSchema)(schema));
145
+ if (!shape) throw new WebSocketMessageNotAnObject(this.surface, action, discriminator);
146
+ if (shape.has(discriminator)) throw new WebSocketMessageDeclaresDiscriminator(this.surface, action, discriminator);
147
+ }
148
+ }
149
+ };
150
+ /**
151
+ * The fields a JSON Schema's object declares, or `undefined` when it is not
152
+ * an object. A union or intersection is one when each of its members is.
153
+ */
154
+ function objectShape(schema) {
155
+ if (!isRecord(schema)) return void 0;
156
+ const members = schema.anyOf ?? schema.oneOf ?? schema.allOf;
157
+ if (Array.isArray(members) && members.length > 0) {
158
+ const fields = /* @__PURE__ */ new Set();
159
+ for (const member of members) {
160
+ const shape = objectShape(member);
161
+ if (!shape) return void 0;
162
+ for (const field of shape) fields.add(field);
163
+ }
164
+ return fields;
165
+ }
166
+ if (schema.type !== "object") return void 0;
167
+ return new Set(isRecord(schema.properties) ? Object.keys(schema.properties) : []);
168
+ }
169
+ function isRecord(value) {
170
+ return typeof value === "object" && value !== null && !Array.isArray(value);
171
+ }
172
+ function isId(value) {
173
+ return typeof value === "string" || typeof value === "number";
174
+ }
175
+ //#endregion
176
+ //#region src/websocket/publisher.ts
177
+ /** A message sent on an action the surface does not declare. */
178
+ var UnknownWebSocketMessage = class extends Error {
179
+ surface;
180
+ action;
181
+ declared;
182
+ constructor(surface, action, declared) {
183
+ super(`${surface} sends no '${action}' message. It declares ${declared.map((a) => `'${a}'`).join(", ")} — send one of them, or add '${action}' to its messages.`);
184
+ this.surface = surface;
185
+ this.action = action;
186
+ this.declared = declared;
187
+ this.name = "UnknownWebSocketMessage";
188
+ }
189
+ };
190
+ /** A message whose data its action's schema refused. */
191
+ var InvalidWebSocketMessage = class extends Error {
192
+ surface;
193
+ action;
194
+ issues;
195
+ constructor(surface, action, issues) {
196
+ super(`${surface}'s '${action}' message was refused by its schema: ${issues.map((issue) => issue.message).join("; ")}. Nothing was sent.`);
197
+ this.surface = surface;
198
+ this.action = action;
199
+ this.issues = issues;
200
+ this.name = "InvalidWebSocketMessage";
201
+ }
202
+ };
203
+ /**
204
+ * How anything reaches a socket — `services.realtime` in an endpoint, and
205
+ * `sockets` in a route of the surface itself.
206
+ *
207
+ * A message is `{ action, data }`, the shape a client's frames arrive in —
208
+ * or, where the surface names a `frame.discriminator`, flat: `{ [key]: action,
209
+ * ...data }`.
210
+ * Where the surface declares its messages, `action` is one of them and
211
+ * `data` is typed and checked by its schema before anything is sent; where it
212
+ * declares none, any action and any JSON value go. A message is serialised
213
+ * once, whatever the number of sockets it goes to. An id whose process has
214
+ * gone is dropped silently, as API Gateway's `postToConnection` to a closed
215
+ * connection is a no-op the sender rarely wants to handle.
216
+ */
217
+ var WebSocketPublisher = class {
218
+ sink;
219
+ declared;
220
+ frame;
221
+ constructor(sink, declared, frame = new FrameShape(declared?.surface ?? "")) {
222
+ this.sink = sink;
223
+ this.declared = declared;
224
+ this.frame = frame;
225
+ }
226
+ /** Send `action`'s message to each connection. */
227
+ async send(ids, action, data) {
228
+ const payload = await this.payload(action, data);
229
+ await this.sink.send(listOf(ids), payload);
230
+ }
231
+ /** Send `action`'s message to every open connection, on every process. */
232
+ async broadcast(action, data, options = {}) {
233
+ const payload = await this.payload(action, data);
234
+ await this.sink.broadcast(payload, options.except?.length ? options.except : void 0);
235
+ }
236
+ /** Close each connection, with a close code and reason its client sees. */
237
+ async close(ids, code = 1e3, reason = "") {
238
+ await this.sink.close(listOf(ids), code, reason);
239
+ }
240
+ /**
241
+ * The frame, checked by the action's schema where the surface declares
242
+ * its messages.
243
+ *
244
+ * @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}, and for a
245
+ * flat frame {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator}
246
+ */
247
+ async payload(action, data) {
248
+ if (!this.declared) return this.frame.encode(action, data);
249
+ const { surface, messages } = this.declared;
250
+ const schema = messages[action];
251
+ if (!schema) throw new UnknownWebSocketMessage(surface, action, Object.keys(messages));
252
+ const result = await schema["~standard"].validate(data);
253
+ if (result.issues) throw new InvalidWebSocketMessage(surface, action, result.issues);
254
+ return this.frame.encode(action, result.value);
255
+ }
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 _geekmidas_errors.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 _geekmidas_errors.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 (0, _geekmidas_services.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 _geekmidas_services.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/testing.ts
493
+ /**
494
+ * A sink that keeps what it is handed, decoded by the surface's frame shape,
495
+ * and sends it nowhere.
496
+ */
497
+ var RecordingSink = class {
498
+ frame;
499
+ sent = [];
500
+ broadcasts = [];
501
+ closed = [];
502
+ constructor(frame) {
503
+ this.frame = frame;
504
+ }
505
+ async send(ids, payload) {
506
+ this.sent.push({
507
+ ids: [...ids],
508
+ ...this.decode(payload)
509
+ });
510
+ }
511
+ async broadcast(payload, except) {
512
+ this.broadcasts.push({
513
+ except: [...except ?? []],
514
+ ...this.decode(payload)
515
+ });
516
+ }
517
+ async close(ids, code, reason) {
518
+ this.closed.push({
519
+ ids: [...ids],
520
+ code,
521
+ reason
522
+ });
523
+ }
524
+ clear() {
525
+ this.sent.length = 0;
526
+ this.broadcasts.length = 0;
527
+ this.closed.length = 0;
528
+ }
529
+ decode(payload) {
530
+ const frame = JSON.parse(payload);
531
+ const { action, data } = this.frame.decode(frame);
532
+ return {
533
+ action,
534
+ data,
535
+ frame
536
+ };
537
+ }
538
+ };
539
+ /**
540
+ * A surface's publisher that records rather than sends — what
541
+ * `surface.testPublisher()` returns, of the type `services.<surface>` is.
542
+ *
543
+ * Every send is still checked by the declared `messages` and encoded by the
544
+ * surface's `frame`, so an invalid push fails the spec as it would fail
545
+ * deployed, and `frame` on each record is what the client would parse.
546
+ */
547
+ var TestWebSocketPublisher = class extends WebSocketPublisher {
548
+ /** Where the records are kept — what `route.request()` builds its core on. */
549
+ recording;
550
+ constructor(frame, declared) {
551
+ const recording = new RecordingSink(frame);
552
+ super(recording, declared, frame);
553
+ this.recording = recording;
554
+ }
555
+ /** Each `send(ids, action, data)`, in order. */
556
+ get sent() {
557
+ return this.recording.sent;
558
+ }
559
+ /** Each `broadcast(action, data, { except })`, in order. */
560
+ get broadcasts() {
561
+ return this.recording.broadcasts;
562
+ }
563
+ /** Each `close(ids, code, reason)`, in order. */
564
+ get closed() {
565
+ return this.recording.closed;
566
+ }
567
+ /** Forget everything recorded so far. */
568
+ clear() {
569
+ this.recording.clear();
570
+ }
571
+ };
572
+ /** A frame `route.request()` sent was refused before its handler ran. */
573
+ var InvalidWebSocketRequest = class extends Error {
574
+ surface;
575
+ action;
576
+ reason;
577
+ issues;
578
+ constructor(surface, action, reason, issues) {
579
+ super(`${surface}'s '${action}' route refused the request: ${reason}${issues?.length ? ` ${issues.map((issue) => issue.message).join("; ")}.` : ""} Send a body its schema accepts.`);
580
+ this.surface = surface;
581
+ this.action = action;
582
+ this.reason = reason;
583
+ this.issues = issues;
584
+ this.name = "InvalidWebSocketRequest";
585
+ }
586
+ };
587
+ let issued = 0;
588
+ /** A connection id no other test call is using. */
589
+ function nextConnectionId() {
590
+ issued += 1;
591
+ return `test.${issued}`;
592
+ }
593
+ function connectionOf(given) {
594
+ return {
595
+ id: given?.id ?? nextConnectionId(),
596
+ data: given?.data ?? {}
597
+ };
598
+ }
599
+ function coreFor(route, surface, sockets) {
600
+ return surface.core({
601
+ envParser: surface.envParser,
602
+ sink: (sockets ?? surface.testPublisher()).recording,
603
+ modules: [{ route }]
604
+ });
605
+ }
606
+ /** `connect.request()`: the connection's `data`, or what refused it. */
607
+ async function requestConnect(route, surface, request = {}) {
608
+ const outcome = await coreFor(route, surface, request.sockets).connect({
609
+ connectionId: request.connectionId ?? nextConnectionId(),
610
+ headers: new Headers(request.headers),
611
+ query: new URLSearchParams(request.query),
612
+ ..."session" in request ? { session: request.session } : {}
613
+ }, request.services ? { services: request.services } : {});
614
+ if (!outcome.accepted) throw outcome.error;
615
+ return outcome.connection.data;
616
+ }
617
+ /** A message route's `fullRequest()`: what it returned and wrote. */
618
+ async function requestMessage(route, surface, request) {
619
+ const core = coreFor(route, surface, request.sockets);
620
+ const frames = [];
621
+ const outcome = await core.message(connectionOf(request.connection), core.frame.encode(route.action, request.body, request.id), (payload) => frames.push(JSON.parse(payload)), request.services ? { services: request.services } : {});
622
+ if (outcome.ok) return {
623
+ returned: outcome.returned,
624
+ frames
625
+ };
626
+ if ("error" in outcome) throw outcome.error;
627
+ throw new InvalidWebSocketRequest(surface.id, route.action, outcome.message, outcome.issues);
628
+ }
629
+ /** `disconnect.request()`: resolves once the handler has run. */
630
+ async function requestDisconnect(route, surface, request = {}) {
631
+ const outcome = await coreFor(route, surface, request.sockets).disconnect(connectionOf(request.connection), {
632
+ code: request.code ?? 1e3,
633
+ reason: request.reason ?? ""
634
+ }, request.services ? { services: request.services } : {});
635
+ if (!outcome.ok) throw outcome.error;
636
+ }
637
+ //#endregion
638
+ //#region src/websocket/route.ts
639
+ /**
640
+ * A handler bound to a WebSocket surface — what `realtime.route('chat.send')
641
+ * …handle()` returns, and what a file exports.
642
+ *
643
+ * Carries `surface` and `constructs` the way an endpoint does, so discovery
644
+ * records what its process reaches without knowing what a route is.
645
+ */
646
+ var WebSocketRoute = class {
647
+ kind;
648
+ action;
649
+ surface;
650
+ services;
651
+ constructs;
652
+ handler;
653
+ schema;
654
+ __IS_WEBSOCKET_ROUTE__ = true;
655
+ static isRoute(value) {
656
+ return Boolean(value && value.__IS_WEBSOCKET_ROUTE__ === true);
657
+ }
658
+ constructor(kind, action, surface, services, constructs, handler, schema) {
659
+ this.kind = kind;
660
+ this.action = action;
661
+ this.surface = surface;
662
+ this.services = services;
663
+ this.constructs = constructs;
664
+ this.handler = handler;
665
+ this.schema = schema;
666
+ }
667
+ /**
668
+ * Run the handler as its surface would, with no server and no socket —
669
+ * as `endpoint.request()` runs an endpoint.
670
+ *
671
+ * - `connect`: resolves with the connection's `data`, or rejects with what
672
+ * refused it (an `UnauthorizedError` stays a 401).
673
+ * - a message route: `body` is encoded as a frame and checked by the
674
+ * route's schema; resolves with the handler's return, or rejects with
675
+ * what it threw or an `InvalidWebSocketRequest`.
676
+ * - `disconnect`: resolves once the handler has run, or rejects with what
677
+ * it threw.
678
+ */
679
+ request(...[request]) {
680
+ const route = this;
681
+ const given = request ?? {};
682
+ if (this.kind === "connect") return requestConnect(route, this.surface, given);
683
+ if (this.kind === "disconnect") return requestDisconnect(route, this.surface, given);
684
+ return requestMessage(route, this.surface, given).then(({ returned }) => returned);
685
+ }
686
+ /**
687
+ * A message route's `request()`, with every frame it wrote back to the
688
+ * connection — each `reply()` and the reply itself — beside its return.
689
+ */
690
+ fullRequest(request) {
691
+ return requestMessage(this, this.surface, request);
692
+ }
693
+ };
694
+ /** The builder `connect()`, `disconnect()` and `route()` start. */
695
+ var WebSocketRouteBuilder = class WebSocketRouteBuilder {
696
+ kind;
697
+ action;
698
+ surface;
699
+ _services;
700
+ _constructs;
701
+ schema;
702
+ constructor(kind, action, surface, _services = [], _constructs = [], schema) {
703
+ this.kind = kind;
704
+ this.action = action;
705
+ this.surface = surface;
706
+ this._services = _services;
707
+ this._constructs = _constructs;
708
+ this.schema = schema;
709
+ }
710
+ /** The schema a frame's `data` must satisfy before the handler runs. */
711
+ body(schema) {
712
+ return new WebSocketRouteBuilder(this.kind, this.action, this.surface, this._services, this._constructs, schema);
713
+ }
714
+ /** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */
715
+ dependsOn(constructs) {
716
+ 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);
717
+ }
718
+ /**
719
+ * The handler. A message handler's return value, when there is one, is
720
+ * sent back to the connection as the reply to that frame; a connect
721
+ * handler's is kept as the connection's `data`.
722
+ */
723
+ handle(handler) {
724
+ return new WebSocketRoute(this.kind, this.action, this.surface, this._services, this._constructs, handler, this.schema);
725
+ }
726
+ };
727
+ /** The instance a connection id was issued by: everything before its dot. */
728
+ function instanceOf(connectionId) {
729
+ const dot = connectionId.indexOf(".");
730
+ return dot > 0 ? connectionId.slice(0, dot) : void 0;
731
+ }
732
+ /**
733
+ * A publisher's sink over a transport: a send goes to the instance each
734
+ * connection id names, a broadcast to every instance. What `services.<id>`
735
+ * sends through, and what the Node adaptor's own `sockets` do.
736
+ */
737
+ var TransportSink = class {
738
+ transport;
739
+ local;
740
+ constructor(transport, local) {
741
+ this.transport = transport;
742
+ this.local = local;
743
+ }
744
+ send(ids, payload) {
745
+ return this.each(ids, (group) => ({
746
+ kind: "send",
747
+ ids: group,
748
+ payload
749
+ }));
750
+ }
751
+ async broadcast(payload, except) {
752
+ await this.transport.publish("*", {
753
+ kind: "broadcast",
754
+ payload,
755
+ ...except?.length ? { except } : {}
756
+ });
757
+ }
758
+ close(ids, code, reason) {
759
+ return this.each(ids, (group) => ({
760
+ kind: "close",
761
+ ids: group,
762
+ code,
763
+ reason
764
+ }));
765
+ }
766
+ /** One delivery per process that holds any of `ids`. */
767
+ async each(ids, delivery) {
768
+ const byInstance = /* @__PURE__ */ new Map();
769
+ for (const id of ids) {
770
+ const instance = instanceOf(id);
771
+ if (!instance) continue;
772
+ const group = byInstance.get(instance) ?? [];
773
+ group.push(id);
774
+ byInstance.set(instance, group);
775
+ }
776
+ await Promise.all([...byInstance].map(([instance, group]) => this.local?.instance === instance ? this.local.deliver(delivery(group)) : this.transport.publish(instance, delivery(group))));
777
+ }
778
+ };
779
+ /** A connection string names no transport this package knows. */
780
+ var UnsupportedWebSocketTransport = class extends Error {
781
+ connectionString;
782
+ constructor(connectionString) {
783
+ super(`'${redact(connectionString)}' is not a WebSocket publisher connection string. Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.`);
784
+ this.connectionString = connectionString;
785
+ this.name = "UnsupportedWebSocketTransport";
786
+ }
787
+ };
788
+ /** The scheme alone, so an error never prints a password. */
789
+ function redact(connectionString) {
790
+ const scheme = connectionString.split("://")[0];
791
+ return scheme && scheme !== connectionString ? `${scheme}://…` : connectionString.slice(0, 12);
792
+ }
793
+ const key = Symbol.for("@geekmidas/constructs/websocket/memory");
794
+ const registry = globalThis;
795
+ registry[key] ??= /* @__PURE__ */ new Map();
796
+ const channels = registry[key];
797
+ /**
798
+ * In one process: the server and whoever sends meet in a map, keyed by the
799
+ * channel the connection string names.
800
+ */
801
+ var MemoryTransport = class {
802
+ channel;
803
+ subscribed = /* @__PURE__ */ new Set();
804
+ constructor(channel) {
805
+ this.channel = channel;
806
+ }
807
+ async publish(instance, delivery) {
808
+ const instances = channels.get(this.channel);
809
+ if (!instances) return;
810
+ if (instance === "*") {
811
+ for (const receive of instances.values()) receive(delivery);
812
+ return;
813
+ }
814
+ instances.get(instance)?.(delivery);
815
+ }
816
+ async subscribe(instance, receive) {
817
+ let instances = channels.get(this.channel);
818
+ if (!instances) {
819
+ instances = /* @__PURE__ */ new Map();
820
+ channels.set(this.channel, instances);
821
+ }
822
+ instances.set(instance, receive);
823
+ this.subscribed.add(instance);
824
+ }
825
+ async close() {
826
+ const instances = channels.get(this.channel);
827
+ for (const instance of this.subscribed) instances?.delete(instance);
828
+ this.subscribed.clear();
829
+ }
830
+ };
831
+ /**
832
+ * Over Redis pub/sub: one channel per instance and one for broadcasts, under
833
+ * a prefix that keeps two surfaces — or two projects on one Redis — apart.
834
+ * Channels are not scoped by database index, so the prefix is what does it.
835
+ *
836
+ * Publishing and subscribing take separate connections, because a connection
837
+ * that has subscribed can do nothing else.
838
+ */
839
+ var RedisTransport = class {
840
+ client;
841
+ prefix;
842
+ subscriber;
843
+ closed;
844
+ constructor(client, prefix) {
845
+ this.client = client;
846
+ this.prefix = prefix;
847
+ }
848
+ channel(instance) {
849
+ return `${this.prefix}:${instance}`;
850
+ }
851
+ async publish(instance, delivery) {
852
+ await this.client.publish(this.channel(instance), JSON.stringify(delivery));
853
+ }
854
+ async subscribe(instance, receive) {
855
+ const subscriber = this.client.duplicate();
856
+ this.subscriber = subscriber;
857
+ const own = this.channel(instance);
858
+ const every = this.channel("*");
859
+ subscriber.on("message", (channel, message) => {
860
+ if (channel !== own && channel !== every) return;
861
+ receive(JSON.parse(message));
862
+ });
863
+ await subscriber.subscribe(own, every);
864
+ }
865
+ /** Idempotent: the server and a shutdown hook may both close it. */
866
+ close() {
867
+ this.closed ??= Promise.all([this.subscriber?.quit(), this.client.quit()]).then(() => void 0);
868
+ return this.closed;
869
+ }
870
+ };
871
+ /**
872
+ * The transport a connection string names.
873
+ *
874
+ * `redis://` and `rediss://` take an optional `channel` query parameter, the
875
+ * prefix every channel is named under; `memory://<channel>` is in-process.
876
+ * Absent, the channel is `fallback` — the surface's own.
877
+ */
878
+ async function transportFromConnectionString(connectionString, fallback) {
879
+ if (connectionString.startsWith("memory://")) return new MemoryTransport(connectionString.slice(9) || fallback);
880
+ const url = URL.canParse(connectionString) ? new URL(connectionString) : void 0;
881
+ if (!url) throw new UnsupportedWebSocketTransport(connectionString);
882
+ if (url.protocol === "redis:" || url.protocol === "rediss:") {
883
+ const channel = url.searchParams.get("channel") || fallback;
884
+ url.searchParams.delete("channel");
885
+ const { Redis } = await import("ioredis");
886
+ return new RedisTransport(new Redis(url.toString(), {
887
+ maxRetriesPerRequest: null,
888
+ lazyConnect: false
889
+ }), channel);
890
+ }
891
+ throw new UnsupportedWebSocketTransport(connectionString);
892
+ }
893
+ //#endregion
894
+ //#region src/websocket/server.ts
895
+ /**
896
+ * The Node adaptor: the process that holds a WebSocket surface's sockets.
897
+ *
898
+ * Node's own `http` server and `ws`, nothing between them. This owns what
899
+ * only a real socket has — the upgrade, the Origin check, connection ids,
900
+ * the heartbeat, backpressure — and hands the rest to the surface's
901
+ * `WebSocketCore`: a handshake to `connect()`, each frame to `message()`, a
902
+ * close to `disconnect()`. The HTTP server is whatever the entry started —
903
+ * the generated one serves `/health` on the same port — and this attaches to
904
+ * its `upgrade` event.
905
+ */
906
+ /** Close codes a client sees. */
907
+ const CLOSE = {
908
+ normal: 1e3,
909
+ /** The process is stopping; reconnect and land on another. */
910
+ serviceRestart: 1012,
911
+ /** It stopped reading, and what was queued for it passed the limit. */
912
+ tooSlow: 1013
913
+ };
914
+ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
915
+ wss;
916
+ options;
917
+ /** This process, as connection ids name it. */
918
+ instance = (0, node_crypto.randomBytes)(6).toString("hex");
919
+ /** Where each handshake, frame and close is handed. */
920
+ core;
921
+ held = /* @__PURE__ */ new Map();
922
+ heartbeat;
923
+ trusted;
924
+ next = 0;
925
+ closing = false;
926
+ constructor(wss, options) {
927
+ this.wss = wss;
928
+ this.options = options;
929
+ this.core = options.core(new TransportSink(options.transport, {
930
+ instance: this.instance,
931
+ deliver: (delivery) => this.deliver(delivery)
932
+ }));
933
+ this.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];
934
+ this.heartbeat = setInterval(() => this.beat(), options.heartbeatMs ?? 3e4);
935
+ this.heartbeat.unref();
936
+ }
937
+ static async start(options) {
938
+ const { WebSocketServer } = await import("ws");
939
+ const wss = new WebSocketServer({
940
+ noServer: true,
941
+ maxPayload: options.maxPayload ?? 1048576,
942
+ perMessageDeflate: false,
943
+ clientTracking: false
944
+ });
945
+ const server = new WebSocketSurfaceServer(wss, options);
946
+ await options.transport.subscribe(server.instance, (delivery) => server.deliver(delivery));
947
+ return server;
948
+ }
949
+ /** `sockets` in a route: local sends skip the transport. */
950
+ get publisher() {
951
+ return this.core.sockets;
952
+ }
953
+ /** How many sockets this process holds. */
954
+ get size() {
955
+ return this.held.size;
956
+ }
957
+ /** Take over `server`'s upgrades. */
958
+ attach(server) {
959
+ server.on("upgrade", (request, socket, head) => {
960
+ this.upgrade(request, socket, head);
961
+ });
962
+ }
963
+ /** Upgrade one request, or refuse it with a status line. */
964
+ async upgrade(request, socket, head) {
965
+ if (this.closing) return refuse(socket, 503, "Service Unavailable");
966
+ const origin = request.headers.origin;
967
+ if (origin && !(0, _geekmidas_manifest.trustsOrigin)(origin, this.trusted)) return refuse(socket, 403, "Forbidden");
968
+ const outcome = await this.core.connect({
969
+ connectionId: `${this.instance}.${(this.next++).toString(36)}`,
970
+ headers: headersOf(request),
971
+ query: new URL(request.url ?? "/", "http://localhost").searchParams
972
+ });
973
+ if (!outcome.accepted) return refuse(socket, outcome.status, outcome.statusText);
974
+ if (socket.destroyed) return;
975
+ this.wss.handleUpgrade(request, socket, head, (ws) => this.open(ws, outcome.connection));
976
+ }
977
+ open(socket, connection) {
978
+ const held = {
979
+ socket,
980
+ connection,
981
+ alive: true
982
+ };
983
+ this.held.set(connection.id, held);
984
+ const write = (payload) => this.write(held, payload);
985
+ socket.on("pong", () => {
986
+ held.alive = true;
987
+ });
988
+ socket.on("message", (raw, isBinary) => {
989
+ held.alive = true;
990
+ this.core.message(connection, isBinary ? bytesOf(raw) : raw.toString(), write);
991
+ });
992
+ socket.on("error", () => socket.terminate());
993
+ socket.on("close", (code, reason) => {
994
+ this.held.delete(connection.id);
995
+ this.core.disconnect(connection, {
996
+ code,
997
+ reason: reason.toString()
998
+ });
999
+ });
1000
+ }
1001
+ /** Write, unless the socket has stopped reading and its queue is full. */
1002
+ write(held, payload) {
1003
+ const { socket } = held;
1004
+ if (socket.readyState !== socket.OPEN) return;
1005
+ if (socket.bufferedAmount > (this.options.maxBufferedBytes ?? 4194304)) {
1006
+ socket.close(CLOSE.tooSlow, "Too slow");
1007
+ return;
1008
+ }
1009
+ socket.send(payload);
1010
+ }
1011
+ /** What the transport, or a local publisher, asked of this process. */
1012
+ deliver(delivery) {
1013
+ switch (delivery.kind) {
1014
+ case "send":
1015
+ for (const id of delivery.ids) {
1016
+ const held = this.held.get(id);
1017
+ if (held) this.write(held, delivery.payload);
1018
+ }
1019
+ return;
1020
+ case "broadcast": {
1021
+ const except = delivery.except ? new Set(delivery.except) : void 0;
1022
+ for (const [id, held] of this.held) if (!except?.has(id)) this.write(held, delivery.payload);
1023
+ return;
1024
+ }
1025
+ case "close":
1026
+ for (const id of delivery.ids) this.held.get(id)?.socket.close(delivery.code, delivery.reason);
1027
+ return;
1028
+ }
1029
+ }
1030
+ /** Drop every socket that missed the last ping, and ping the rest. */
1031
+ beat() {
1032
+ for (const [id, held] of this.held) {
1033
+ if (!held.alive) {
1034
+ held.socket.terminate();
1035
+ this.held.delete(id);
1036
+ continue;
1037
+ }
1038
+ held.alive = false;
1039
+ held.socket.ping();
1040
+ }
1041
+ }
1042
+ /**
1043
+ * Stop: refuse new upgrades, close every socket with `code` — 1012 tells
1044
+ * a client to reconnect, and it lands on a process that is still up — and
1045
+ * leave the transport.
1046
+ */
1047
+ async close(code = CLOSE.serviceRestart, reason = "Restarting") {
1048
+ if (this.closing) return;
1049
+ this.closing = true;
1050
+ clearInterval(this.heartbeat);
1051
+ const closed = [...this.held.values()].map(({ socket }) => new Promise((resolve) => {
1052
+ if (socket.readyState === socket.CLOSED) return resolve();
1053
+ socket.once("close", () => resolve());
1054
+ socket.close(code, reason);
1055
+ setTimeout(() => {
1056
+ socket.terminate();
1057
+ resolve();
1058
+ }, 2e3).unref();
1059
+ }));
1060
+ await Promise.all(closed);
1061
+ await this.options.transport.close();
1062
+ this.wss.close();
1063
+ }
1064
+ };
1065
+ /**
1066
+ * The origins a client of the surface's own address sends: the `https://`
1067
+ * one a native socket derives from `wss://`, and the address's own.
1068
+ */
1069
+ function ownOrigins(url) {
1070
+ if (!url || !URL.canParse(url)) return [];
1071
+ const own = new URL(url);
1072
+ const web = new URL(url.replace(/^ws(s?):/i, "http$1:"));
1073
+ return [.../* @__PURE__ */ new Set([`${own.protocol}//${own.host}`, web.origin])];
1074
+ }
1075
+ /** A binary frame's bytes, however `ws` delivered them. */
1076
+ function bytesOf(raw) {
1077
+ if (Array.isArray(raw)) return Buffer.concat(raw);
1078
+ return raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw;
1079
+ }
1080
+ function headersOf(request) {
1081
+ const headers = new Headers();
1082
+ for (const [name, value] of Object.entries(request.headers)) {
1083
+ if (value === void 0) continue;
1084
+ for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one);
1085
+ }
1086
+ return headers;
1087
+ }
1088
+ function refuse(socket, status, message) {
1089
+ if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${message}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
1090
+ }
1091
+ //#endregion
1092
+ //#region src/websocket-api.ts
1093
+ /** A replica count that is not a whole number of at least one. */
1094
+ var InvalidReplicaCount = class extends Error {
1095
+ id;
1096
+ replicas;
1097
+ constructor(id, replicas) {
1098
+ super(`${id} asks for ${replicas} replicas. A surface runs on at least one process — give a whole number of 1 or more.`);
1099
+ this.id = id;
1100
+ this.replicas = replicas;
1101
+ this.name = "InvalidReplicaCount";
1102
+ }
1103
+ };
1104
+ var WebSocketApi = class WebSocketApi {
1105
+ config;
1106
+ authenticator;
1107
+ id;
1108
+ keys;
1109
+ logger;
1110
+ envParser;
1111
+ telemetry;
1112
+ /**
1113
+ * The shape its frames take — `{ action, data }`, or flat under
1114
+ * `discriminator`. What a client of the surface decodes by.
1115
+ */
1116
+ frame;
1117
+ /**
1118
+ * The surface as a dependency: `services.<id>` is its publisher, so an
1119
+ * endpoint sends to a socket the way a route beside it does.
1120
+ */
1121
+ service;
1122
+ constructor(id, config, authenticator) {
1123
+ this.config = config;
1124
+ this.authenticator = authenticator;
1125
+ const canonical = (0, _geekmidas_manifest.canonicalId)(id);
1126
+ this.id = canonical;
1127
+ const replicas = config.replicas ?? 1;
1128
+ if (!Number.isInteger(replicas) || replicas < 1) throw new InvalidReplicaCount(canonical, replicas);
1129
+ const frame = new FrameShape(canonical, config.frame?.discriminator);
1130
+ if (config.messages) frame.check(config.messages);
1131
+ this.frame = config.frame ? { discriminator: config.frame.discriminator } : {};
1132
+ this.keys = {
1133
+ url: (0, _geekmidas_manifest.provideKey)(canonical, "url"),
1134
+ trustedOrigins: (0, _geekmidas_manifest.provideKey)(canonical, "trustedOrigins"),
1135
+ publisherConnectionString: (0, _geekmidas_manifest.provideKey)(canonical, "publisherConnectionString")
1136
+ };
1137
+ this.logger = config.logger ?? _geekmidas_logger_console.DEFAULT_LOGGER;
1138
+ this.telemetry = config.telemetry;
1139
+ this.envParser = require_surfaceEnv.envParserFor(config.envParser ? {
1140
+ id: canonical,
1141
+ envParser: config.envParser
1142
+ } : void 0);
1143
+ const envVar = this.keys.publisherConnectionString;
1144
+ const channel = channelOf(canonical);
1145
+ const declared = this.declared;
1146
+ this.service = {
1147
+ serviceName: (0, _geekmidas_manifest.serviceKey)(canonical),
1148
+ async register({ envParser }) {
1149
+ const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
1150
+ const transport = await transportFromConnectionString(connectionString, channel);
1151
+ require_shutdown.onShutdown(() => transport.close());
1152
+ return new WebSocketPublisher(new TransportSink(transport), declared, frame);
1153
+ }
1154
+ };
1155
+ }
1156
+ /** The handler a connection's upgrade runs: refuse it, or say who it is. */
1157
+ connect() {
1158
+ return new WebSocketRouteBuilder("connect", "$connect", this);
1159
+ }
1160
+ /** The handler a closed connection runs. */
1161
+ disconnect() {
1162
+ return new WebSocketRouteBuilder("disconnect", "$disconnect", this);
1163
+ }
1164
+ /**
1165
+ * The handler for frames whose `action` — or, for flat frames, whose
1166
+ * discriminator — is `action`. `$default` answers
1167
+ * any action nothing else does.
1168
+ */
1169
+ route(action) {
1170
+ return new WebSocketRouteBuilder("message", action, this);
1171
+ }
1172
+ /** What authenticates a connection — its session reaches `connect()`. */
1173
+ auth(construct) {
1174
+ return new WebSocketApi(this.id, this.config, construct);
1175
+ }
1176
+ /**
1177
+ * Serve it: the routes exported by `modules` that were built from this
1178
+ * surface, on whatever HTTP server `attach` is handed.
1179
+ *
1180
+ * `app` answers plain HTTP — the generated entry puts `/health` in front
1181
+ * of it — and `attach` takes over the server's upgrades. The sockets are
1182
+ * closed with 1012 when the server shuts down.
1183
+ */
1184
+ async server(options) {
1185
+ const { Hono } = await import("hono");
1186
+ const { connectionString, origins, url } = options.envParser.create((get) => ({
1187
+ connectionString: get(this.keys.publisherConnectionString).string().default(`memory://${channelOf(this.id)}`),
1188
+ origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean)),
1189
+ url: get(this.keys.url).string().optional()
1190
+ })).parse();
1191
+ const server = await WebSocketSurfaceServer.start({
1192
+ core: (sink) => this.core({
1193
+ envParser: options.envParser,
1194
+ sink,
1195
+ ...options.modules ? { modules: options.modules } : {}
1196
+ }),
1197
+ transport: await transportFromConnectionString(connectionString, channelOf(this.id)),
1198
+ trustedOrigins: origins,
1199
+ ...url ? { url } : {},
1200
+ ...this.config.heartbeat ? { heartbeatMs: this.config.heartbeat * 1e3 } : {},
1201
+ ...this.config.maxPayload ? { maxPayload: this.config.maxPayload } : {}
1202
+ });
1203
+ require_shutdown.onShutdown(() => server.close());
1204
+ const app = new Hono();
1205
+ app.get("/health", (c) => c.json({
1206
+ status: "ok",
1207
+ connections: server.size
1208
+ }));
1209
+ app.get("/", (c) => c.json({
1210
+ surface: this.id,
1211
+ connections: server.size
1212
+ }, 426, { Upgrade: "websocket" }));
1213
+ return {
1214
+ app,
1215
+ attach: (http) => server.attach(http),
1216
+ release: () => server.close(),
1217
+ server
1218
+ };
1219
+ }
1220
+ /**
1221
+ * The surface with no socket in it — what every runtime serves. The
1222
+ * routes exported by `modules` that were built from this surface answer
1223
+ * its frames; `sink` is where its handlers' `sockets` send.
1224
+ *
1225
+ * `server()` is the Node adaptor over it. Another runtime (a Lambda
1226
+ * behind API Gateway, a test) builds one with a sink of its own and
1227
+ * calls `connect()`, `message()` and `disconnect()` per connection id.
1228
+ *
1229
+ * @throws {DuplicateWebSocketRoute} when two routes answer one action.
1230
+ */
1231
+ core(options) {
1232
+ return new WebSocketCore({
1233
+ surface: this.id,
1234
+ routes: (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute)),
1235
+ sink: options.sink,
1236
+ envParser: options.envParser,
1237
+ logger: this.logger,
1238
+ ...this.config.frame ? { frame: this.config.frame } : {},
1239
+ ...this.declared ? { messages: this.declared.messages } : {},
1240
+ ...this.authenticator ? { authenticator: this.authenticator } : {}
1241
+ });
1242
+ }
1243
+ /**
1244
+ * The surface's publisher over `sink` — typed, checked and encoded as
1245
+ * `services.<id>` is. What an adaptor with a sink of its own (MSW, a
1246
+ * Lambda) hands the code that sends to its connections.
1247
+ */
1248
+ publisher(sink) {
1249
+ return new WebSocketPublisher(sink, this.declared, new FrameShape(this.id, this.config.frame?.discriminator));
1250
+ }
1251
+ /**
1252
+ * A publisher of the type `services.<id>` is, that records rather than
1253
+ * sends — hand it to an endpoint's spec, or to a route's `request()` as
1254
+ * `sockets`, and assert on `sent`, `broadcasts` and `closed`.
1255
+ *
1256
+ * Every send is checked by the declared `messages` and encoded by `frame`,
1257
+ * as deployed: an invalid push rejects, and each record carries the
1258
+ * frame a client would parse.
1259
+ *
1260
+ * ```ts
1261
+ * const realtime = surface.testPublisher();
1262
+ * await sendMessage.request({ services: { realtime }, … });
1263
+ * expect(realtime.sent).toEqual([
1264
+ * { ids: ['a.1'], action: 'chat.sent', data: { text: 'hi' }, frame: … },
1265
+ * ]);
1266
+ * ```
1267
+ */
1268
+ testPublisher() {
1269
+ return new TestWebSocketPublisher(new FrameShape(this.id, this.config.frame?.discriminator), this.declared);
1270
+ }
1271
+ /** The declared messages, with the surface they are checked for. */
1272
+ get declared() {
1273
+ return this.config.messages ? {
1274
+ surface: this.id,
1275
+ messages: this.config.messages
1276
+ } : void 0;
1277
+ }
1278
+ declare() {
1279
+ return [{
1280
+ kind: "websocket-api",
1281
+ id: this.id,
1282
+ path: this.config.path,
1283
+ ...this.config.subdomain ? { subdomain: this.config.subdomain } : {},
1284
+ ...this.authenticator ? { auth: require_construct_interface.edgeTo(this.authenticator) } : {},
1285
+ ...this.config.telemetry ? { telemetry: this.config.telemetry.id } : {},
1286
+ ...this.config.replicas && this.config.replicas > 1 ? { replicas: this.config.replicas } : {},
1287
+ provides: [
1288
+ this.keys.url,
1289
+ this.keys.trustedOrigins,
1290
+ this.keys.publisherConnectionString
1291
+ ]
1292
+ }];
1293
+ }
1294
+ };
1295
+ /** The prefix a surface's channels are named under. */
1296
+ function channelOf(id) {
1297
+ return `gkm:ws:${id}`;
1298
+ }
1299
+ //#endregion
1300
+ Object.defineProperty(exports, "CLOSE", {
1301
+ enumerable: true,
1302
+ get: function() {
1303
+ return CLOSE;
1304
+ }
1305
+ });
1306
+ Object.defineProperty(exports, "DuplicateWebSocketRoute", {
1307
+ enumerable: true,
1308
+ get: function() {
1309
+ return DuplicateWebSocketRoute;
1310
+ }
1311
+ });
1312
+ Object.defineProperty(exports, "InvalidReplicaCount", {
1313
+ enumerable: true,
1314
+ get: function() {
1315
+ return InvalidReplicaCount;
1316
+ }
1317
+ });
1318
+ Object.defineProperty(exports, "InvalidWebSocketMessage", {
1319
+ enumerable: true,
1320
+ get: function() {
1321
+ return InvalidWebSocketMessage;
1322
+ }
1323
+ });
1324
+ Object.defineProperty(exports, "InvalidWebSocketRequest", {
1325
+ enumerable: true,
1326
+ get: function() {
1327
+ return InvalidWebSocketRequest;
1328
+ }
1329
+ });
1330
+ Object.defineProperty(exports, "MemoryTransport", {
1331
+ enumerable: true,
1332
+ get: function() {
1333
+ return MemoryTransport;
1334
+ }
1335
+ });
1336
+ Object.defineProperty(exports, "RecordingSink", {
1337
+ enumerable: true,
1338
+ get: function() {
1339
+ return RecordingSink;
1340
+ }
1341
+ });
1342
+ Object.defineProperty(exports, "RedisTransport", {
1343
+ enumerable: true,
1344
+ get: function() {
1345
+ return RedisTransport;
1346
+ }
1347
+ });
1348
+ Object.defineProperty(exports, "TestWebSocketPublisher", {
1349
+ enumerable: true,
1350
+ get: function() {
1351
+ return TestWebSocketPublisher;
1352
+ }
1353
+ });
1354
+ Object.defineProperty(exports, "TransportSink", {
1355
+ enumerable: true,
1356
+ get: function() {
1357
+ return TransportSink;
1358
+ }
1359
+ });
1360
+ Object.defineProperty(exports, "UnknownWebSocketMessage", {
1361
+ enumerable: true,
1362
+ get: function() {
1363
+ return UnknownWebSocketMessage;
1364
+ }
1365
+ });
1366
+ Object.defineProperty(exports, "UnsupportedWebSocketTransport", {
1367
+ enumerable: true,
1368
+ get: function() {
1369
+ return UnsupportedWebSocketTransport;
1370
+ }
1371
+ });
1372
+ Object.defineProperty(exports, "WebSocketApi", {
1373
+ enumerable: true,
1374
+ get: function() {
1375
+ return WebSocketApi;
1376
+ }
1377
+ });
1378
+ Object.defineProperty(exports, "WebSocketCore", {
1379
+ enumerable: true,
1380
+ get: function() {
1381
+ return WebSocketCore;
1382
+ }
1383
+ });
1384
+ Object.defineProperty(exports, "WebSocketDataHasDiscriminator", {
1385
+ enumerable: true,
1386
+ get: function() {
1387
+ return WebSocketDataHasDiscriminator;
1388
+ }
1389
+ });
1390
+ Object.defineProperty(exports, "WebSocketDataNotAnObject", {
1391
+ enumerable: true,
1392
+ get: function() {
1393
+ return WebSocketDataNotAnObject;
1394
+ }
1395
+ });
1396
+ Object.defineProperty(exports, "WebSocketMessageDeclaresDiscriminator", {
1397
+ enumerable: true,
1398
+ get: function() {
1399
+ return WebSocketMessageDeclaresDiscriminator;
1400
+ }
1401
+ });
1402
+ Object.defineProperty(exports, "WebSocketMessageNotAnObject", {
1403
+ enumerable: true,
1404
+ get: function() {
1405
+ return WebSocketMessageNotAnObject;
1406
+ }
1407
+ });
1408
+ Object.defineProperty(exports, "WebSocketPublisher", {
1409
+ enumerable: true,
1410
+ get: function() {
1411
+ return WebSocketPublisher;
1412
+ }
1413
+ });
1414
+ Object.defineProperty(exports, "WebSocketRoute", {
1415
+ enumerable: true,
1416
+ get: function() {
1417
+ return WebSocketRoute;
1418
+ }
1419
+ });
1420
+ Object.defineProperty(exports, "WebSocketRouteBuilder", {
1421
+ enumerable: true,
1422
+ get: function() {
1423
+ return WebSocketRouteBuilder;
1424
+ }
1425
+ });
1426
+ Object.defineProperty(exports, "WebSocketSurfaceServer", {
1427
+ enumerable: true,
1428
+ get: function() {
1429
+ return WebSocketSurfaceServer;
1430
+ }
1431
+ });
1432
+ Object.defineProperty(exports, "transportFromConnectionString", {
1433
+ enumerable: true,
1434
+ get: function() {
1435
+ return transportFromConnectionString;
1436
+ }
1437
+ });
1438
+
1439
+ //# sourceMappingURL=websocket-api-9bXfgrqd.cjs.map