@nice-code/action 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +91 -59
  2. package/build/{ActionDevtoolsCore-baIHExfj.d.mts → ActionDevtoolsCore-CQ0vrvPD.d.cts} +2 -2
  3. package/build/{ActionDevtoolsCore-dApyYvTS.d.cts → ActionDevtoolsCore-CiLBYC3K.d.mts} +2 -2
  4. package/build/{ActionPayload.types-CQM1HRw_.d.cts → ActionPayload.types-Dx1JPyfs.d.mts} +133 -30
  5. package/build/{ActionPayload.types-DXGiw1SF.d.mts → ActionPayload.types-L9k0LyBd.d.cts} +133 -30
  6. package/build/devtools/browser/index.d.cts +1 -1
  7. package/build/devtools/browser/index.d.mts +1 -1
  8. package/build/devtools/server/index.d.cts +1 -1
  9. package/build/devtools/server/index.d.mts +1 -1
  10. package/build/httpAcceptorCarrier-DL8lf0xB.mjs +3906 -0
  11. package/build/httpAcceptorCarrier-DL8lf0xB.mjs.map +1 -0
  12. package/build/httpAcceptorCarrier-OnJxzsAD.cjs +4291 -0
  13. package/build/httpAcceptorCarrier-OnJxzsAD.cjs.map +1 -0
  14. package/build/index.cjs +368 -4139
  15. package/build/index.cjs.map +1 -1
  16. package/build/index.d.cts +2 -2
  17. package/build/index.d.mts +2 -2
  18. package/build/index.mjs +299 -4069
  19. package/build/index.mjs.map +1 -1
  20. package/build/platform/cloudflare/index.cjs +30 -2
  21. package/build/platform/cloudflare/index.cjs.map +1 -1
  22. package/build/platform/cloudflare/index.d.cts +55 -2
  23. package/build/platform/cloudflare/index.d.mts +55 -2
  24. package/build/platform/cloudflare/index.mjs +28 -2
  25. package/build/platform/cloudflare/index.mjs.map +1 -1
  26. package/build/react-query/index.d.cts +1 -1
  27. package/build/react-query/index.d.mts +1 -1
  28. package/package.json +4 -4
  29. package/build/wsAcceptorCarrier-BDJRIPfu.cjs +0 -103
  30. package/build/wsAcceptorCarrier-BDJRIPfu.cjs.map +0 -1
  31. package/build/wsAcceptorCarrier-CW2qX25W.mjs +0 -80
  32. package/build/wsAcceptorCarrier-CW2qX25W.mjs.map +0 -1
@@ -0,0 +1,3906 @@
1
+ import "./RunningAction.types-C176rqHG.mjs";
2
+ import { nanoid } from "nanoid";
3
+ import { NiceError, castNiceError, err, err_nice, isNiceErrorObject } from "@nice-code/error";
4
+ import { extractMessageFromStandardSchema } from "@nice-code/common-errors";
5
+ import { runtime } from "std-env";
6
+ import { ClientCryptoKeyLink, createTypedStorage } from "@nice-code/util";
7
+ import * as v from "valibot";
8
+ import { pack, unpack } from "msgpackr";
9
+ const UNSET_RUNTIME_ENV_ID = "_unset_";
10
+ //#endregion
11
+ //#region src/ActionRuntime/utils/runtimeCoordinateToStringIds.ts
12
+ function runtimeCoordinateToStringIds(coordinate) {
13
+ return [
14
+ `envId[${coordinate.envId}]perId[${coordinate.perId ?? "_"}]:insId[${coordinate.insId ?? "_"}]`,
15
+ `envId[${coordinate.envId}]perId[${coordinate.perId ?? "_"}]:insId[_]`,
16
+ `envId[${coordinate.envId}]perId[_]:insId[_]`
17
+ ];
18
+ }
19
+ //#endregion
20
+ //#region src/ActionRuntime/RuntimeCoordinate.ts
21
+ var RuntimeCoordinate = class RuntimeCoordinate {
22
+ envId;
23
+ perId;
24
+ insId;
25
+ static get unknown() {
26
+ return new RuntimeCoordinate({ envId: UNSET_RUNTIME_ENV_ID });
27
+ }
28
+ static env(envId) {
29
+ return new RuntimeCoordinate({ envId });
30
+ }
31
+ withPersistentId(perId) {
32
+ return this.specify({ perId });
33
+ }
34
+ constructor({ envId, perId, insId }) {
35
+ this.envId = envId;
36
+ this.perId = perId;
37
+ this.insId = insId;
38
+ }
39
+ specify(specifics) {
40
+ return new RuntimeCoordinate({
41
+ envId: this.envId,
42
+ perId: this.perId,
43
+ insId: this.insId,
44
+ ...specifics
45
+ });
46
+ }
47
+ specifyIfUnset(specifics) {
48
+ return new RuntimeCoordinate({
49
+ envId: this.envId,
50
+ perId: this.perId ?? specifics.perId,
51
+ insId: this.insId ?? specifics.insId
52
+ });
53
+ }
54
+ toJsonObject() {
55
+ return {
56
+ envId: this.envId,
57
+ perId: this.perId,
58
+ insId: this.insId
59
+ };
60
+ }
61
+ isExactlySame(other) {
62
+ return this.envId === other.envId && this.perId === other.perId && this.insId === other.insId;
63
+ }
64
+ isSameFor(other) {
65
+ return {
66
+ id: this.envId === other.envId,
67
+ perId: this.envId === other.envId && this.perId === other.perId,
68
+ insId: this.envId === other.envId && this.perId === other.perId && this.insId === other.insId
69
+ };
70
+ }
71
+ similarityLevel(other) {
72
+ const sameFor = this.isSameFor(other);
73
+ if (sameFor.insId) return 3;
74
+ if (sameFor.perId) return 2;
75
+ if (sameFor.id) return 1;
76
+ return 0;
77
+ }
78
+ get stringId() {
79
+ return `envId[${this.envId}]perId[${this.perId ?? "_"}]:insId[${this.insId ?? "_"}]`;
80
+ }
81
+ /**
82
+ * Takes the "Runtime Coordinate" and generates a list of full coordinate IDs representing the runtime
83
+ * with decreasing levels of specificity.
84
+ *
85
+ * The first full coordinate ID is the most specific (including instance ID), while the last ID is
86
+ * the least specific (only environment ID).
87
+ *
88
+ * Example output for a RuntimeCoordinate with envId "web_app", perId "user123", and insId "instance456":
89
+ * [
90
+ * "envId[web_app]perId[user123]:insId[instance456]",
91
+ * "envId[web_app]perId[user123]:insId[_]",
92
+ * "envId[web_app]perId[_]:insId[_]"
93
+ * ]
94
+ *
95
+ * @returns a list of "full" runtime coordinate IDs with decreasing accuracy for targeting a runtime.
96
+ */
97
+ toStringIds() {
98
+ return runtimeCoordinateToStringIds(this);
99
+ }
100
+ };
101
+ //#endregion
102
+ //#region src/ActionDefinition/Action/ActionBase.ts
103
+ var ActionBase = class {
104
+ form;
105
+ _domain;
106
+ id;
107
+ domain;
108
+ allDomains;
109
+ schema;
110
+ constructor(form, _domain, id) {
111
+ this.form = form;
112
+ this._domain = _domain;
113
+ this.id = id;
114
+ this.domain = _domain.domain;
115
+ this.allDomains = _domain.allDomains;
116
+ this.schema = _domain.actionSchema[id];
117
+ }
118
+ toJsonObject() {
119
+ return {
120
+ form: this.form,
121
+ domain: this.domain,
122
+ allDomains: this.allDomains,
123
+ id: this.id
124
+ };
125
+ }
126
+ toJsonString() {
127
+ return JSON.stringify(this.toJsonObject());
128
+ }
129
+ };
130
+ //#endregion
131
+ //#region src/ActionDefinition/Action/Payload/ActionPayload.ts
132
+ var ActionPayload = class extends ActionBase {
133
+ form = "data";
134
+ type;
135
+ context;
136
+ time;
137
+ constructor(context, type, data) {
138
+ super("data", context._domain, context.id);
139
+ this.context = context;
140
+ this.type = type;
141
+ this.time = data.time;
142
+ }
143
+ toBaseJsonObject() {
144
+ return {
145
+ ...super.toJsonObject(),
146
+ type: this.type,
147
+ context: this.context.toContextDataJsonObject(),
148
+ time: this.time
149
+ };
150
+ }
151
+ };
152
+ //#endregion
153
+ //#region src/utils/hashPayloadData.ts
154
+ function stableStringify(value) {
155
+ if (value === null || value === void 0) return String(value);
156
+ if (typeof value !== "object") return JSON.stringify(value) ?? "undefined";
157
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
158
+ return "{" + Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",") + "}";
159
+ }
160
+ function fnv1a32(str) {
161
+ let hash = 2166136261;
162
+ for (let i = 0; i < str.length; i++) hash = (hash ^ str.charCodeAt(i)) * 16777619 >>> 0;
163
+ return hash.toString(16).padStart(8, "0");
164
+ }
165
+ /**
166
+ * Produces a deterministic 8-char hex hash of any JSON-serializable value.
167
+ * Useful for grouping/comparing action inputs, outputs, and progress payloads.
168
+ */
169
+ function hashPayloadData(data) {
170
+ return fnv1a32(stableStringify(data));
171
+ }
172
+ //#endregion
173
+ //#region src/ActionDefinition/Action/Payload/ActionPayload.types.ts
174
+ let EActionPayloadType = /* @__PURE__ */ function(EActionPayloadType) {
175
+ EActionPayloadType["request"] = "request";
176
+ EActionPayloadType["progress"] = "progress";
177
+ EActionPayloadType["result"] = "result";
178
+ EActionPayloadType["stream"] = "stream";
179
+ EActionPayloadType["push"] = "push";
180
+ return EActionPayloadType;
181
+ }({});
182
+ /**
183
+ *
184
+ * [ PROGRESS ]
185
+ *
186
+ */
187
+ let EActionProgressType = /* @__PURE__ */ function(EActionProgressType) {
188
+ EActionProgressType["none"] = "none";
189
+ EActionProgressType["percentage"] = "percentage";
190
+ EActionProgressType["custom"] = "custom";
191
+ return EActionProgressType;
192
+ }({});
193
+ //#endregion
194
+ //#region src/ActionDefinition/Action/Payload/ActionPayload_Progress.ts
195
+ var ActionPayload_Progress = class extends ActionPayload {
196
+ progress;
197
+ constructor(params, progress, data) {
198
+ super(params.context, "progress", data);
199
+ this.progress = progress;
200
+ }
201
+ toJsonObject() {
202
+ return {
203
+ ...this.toBaseJsonObject(),
204
+ progress: this.progress
205
+ };
206
+ }
207
+ toJsonString() {
208
+ return JSON.stringify(this.toJsonObject());
209
+ }
210
+ toHttpResponse() {
211
+ return new Response(this.toJsonString(), {
212
+ status: 200,
213
+ headers: { "Content-Type": "application/json" }
214
+ });
215
+ }
216
+ };
217
+ //#endregion
218
+ //#region src/ActionDefinition/Action/Payload/ActionPayload_Result.ts
219
+ var ActionPayload_Result = class extends ActionPayload {
220
+ result;
221
+ outputHash;
222
+ constructor(params, result, data) {
223
+ super(params.context, "result", data);
224
+ this.result = result;
225
+ this.outputHash = result.ok ? hashPayloadData(this.context.schema.serializeOutput(result.output)) : hashPayloadData(result.error.message);
226
+ }
227
+ toJsonObject() {
228
+ const wireResult = this.result.ok ? {
229
+ ok: true,
230
+ output: this.context.schema.serializeOutput(this.result.output)
231
+ } : this.result;
232
+ return {
233
+ ...this.toBaseJsonObject(),
234
+ result: wireResult,
235
+ outputHash: this.outputHash
236
+ };
237
+ }
238
+ toJsonString() {
239
+ return JSON.stringify(this.toJsonObject());
240
+ }
241
+ toHttpResponse({ useErrorStatus = true } = {}) {
242
+ return new Response(this.toJsonString(), {
243
+ status: this.result.ok ? 200 : useErrorStatus ? this.result.error.httpStatusCode : 500,
244
+ headers: { "Content-Type": "application/json" }
245
+ });
246
+ }
247
+ };
248
+ //#endregion
249
+ //#region src/ActionDefinition/Action/Payload/ActionPayload_Request.ts
250
+ var ActionPayload_Request = class extends ActionPayload {
251
+ input;
252
+ inputHash;
253
+ _callSite;
254
+ constructor(params, input, data) {
255
+ super(params.context, "request", data);
256
+ this.input = input;
257
+ this.inputHash = hashPayloadData(this.context.schema.serializeInput(input));
258
+ }
259
+ successResult(...args) {
260
+ const output = args[0];
261
+ const finalOutput = this.context.schema.validateOutput(output, {
262
+ domain: this.domain,
263
+ actionId: this.id
264
+ });
265
+ return new ActionPayload_Result(this, {
266
+ ok: true,
267
+ output: finalOutput
268
+ }, { time: Date.now() });
269
+ }
270
+ errorResult(err) {
271
+ return new ActionPayload_Result(this, {
272
+ ok: false,
273
+ error: err
274
+ }, { time: Date.now() });
275
+ }
276
+ progress(progress) {
277
+ return new ActionPayload_Progress(this, progress, { time: Date.now() });
278
+ }
279
+ toJsonObject() {
280
+ return {
281
+ ...super.toBaseJsonObject(),
282
+ input: this.context.schema.serializeInput(this.input),
283
+ inputHash: this.inputHash
284
+ };
285
+ }
286
+ toJsonString() {
287
+ return JSON.stringify(this.toJsonObject());
288
+ }
289
+ async runToOutput(options) {
290
+ const result = await (await this.run(options)).waitForResultPayload();
291
+ if (result.result.ok) return result.result.output;
292
+ throw result.result.error;
293
+ }
294
+ async runToResultPayload(options) {
295
+ return (await this.run(options)).waitForResultPayload();
296
+ }
297
+ async run(options) {
298
+ if (this._callSite == null) this._callSite = (/* @__PURE__ */ new Error()).stack;
299
+ return this._domain.runAction(this, options);
300
+ }
301
+ };
302
+ //#endregion
303
+ //#region src/ActionDefinition/Action/RunningAction.ts
304
+ var RunningAction = class {
305
+ _state;
306
+ context;
307
+ cuid;
308
+ id;
309
+ _domain;
310
+ domain;
311
+ allDomains;
312
+ parentCuid;
313
+ callSite;
314
+ _resultPayloadPromise;
315
+ _resolveResult;
316
+ _rejectResult;
317
+ _isAborted = false;
318
+ _updates = [];
319
+ _updateListeners = [];
320
+ constructor(initialState) {
321
+ this.context = initialState.context;
322
+ this.cuid = initialState.context.cuid;
323
+ this.id = initialState.context.id;
324
+ this.domain = initialState.context.domain;
325
+ this.allDomains = initialState.context.allDomains;
326
+ this._domain = initialState.context._domain;
327
+ this.parentCuid = initialState.parentCuid;
328
+ this.callSite = initialState.callSite;
329
+ this._resultPayloadPromise = new Promise((resolve, reject) => {
330
+ this._resolveResult = resolve;
331
+ this._rejectResult = reject;
332
+ });
333
+ this._resultPayloadPromise.catch(() => {});
334
+ this._state = {
335
+ request: initialState.request,
336
+ progress: initialState.progress ?? [],
337
+ result: initialState.result
338
+ };
339
+ this._sendUpdate({
340
+ type: "started",
341
+ runningAction: this,
342
+ time: Date.now()
343
+ });
344
+ }
345
+ get state() {
346
+ return this._state;
347
+ }
348
+ abort(reason) {
349
+ this._abort(reason);
350
+ }
351
+ addUpdateListeners(listeners) {
352
+ this._updateListeners.push(...listeners);
353
+ for (const event of this._updates) for (const listener of listeners) listener(event);
354
+ return () => {
355
+ for (const listener of listeners) {
356
+ const i = this._updateListeners.indexOf(listener);
357
+ if (i !== -1) this._updateListeners.splice(i, 1);
358
+ }
359
+ };
360
+ }
361
+ async *iterateUpdates() {
362
+ const queue = [];
363
+ let resolveWaiter = null;
364
+ const unsubscribe = this.addUpdateListeners([(event) => {
365
+ queue.push(event);
366
+ if (resolveWaiter) {
367
+ resolveWaiter();
368
+ resolveWaiter = null;
369
+ }
370
+ }]);
371
+ try {
372
+ while (true) {
373
+ if (queue.length === 0) await new Promise((resolve) => {
374
+ resolveWaiter = resolve;
375
+ });
376
+ const event = queue.shift();
377
+ yield event;
378
+ if (event.type === "finished") break;
379
+ }
380
+ } finally {
381
+ unsubscribe();
382
+ }
383
+ }
384
+ _sendUpdate(update) {
385
+ this._updates.push(update);
386
+ for (const listener of this._updateListeners) listener(update);
387
+ }
388
+ _completeWithResult(result) {
389
+ if (this._state.result != null || this._isAborted) return false;
390
+ this._state = {
391
+ request: this._state.request,
392
+ progress: this._state.progress,
393
+ result
394
+ };
395
+ this._resolveResult(result);
396
+ this._sendUpdate({
397
+ type: "finished",
398
+ finishType: "success",
399
+ runningAction: this,
400
+ time: Date.now(),
401
+ response: result
402
+ });
403
+ return true;
404
+ }
405
+ _abort(reason) {
406
+ if (this._state.result != null || this._isAborted) return false;
407
+ this._isAborted = true;
408
+ this._rejectResult(reason);
409
+ this._sendUpdate({
410
+ type: "finished",
411
+ finishType: "aborted",
412
+ runningAction: this,
413
+ time: Date.now(),
414
+ reason
415
+ });
416
+ return true;
417
+ }
418
+ _failWithError(error) {
419
+ if (this._state.result != null || this._isAborted) return false;
420
+ this._isAborted = true;
421
+ this._rejectResult(error);
422
+ this._sendUpdate({
423
+ type: "finished",
424
+ finishType: "failed",
425
+ runningAction: this,
426
+ time: Date.now(),
427
+ error
428
+ });
429
+ return true;
430
+ }
431
+ _updateProgress(progress) {
432
+ if (this._state.result != null || this._isAborted) return;
433
+ this._state.progress.push(progress);
434
+ this._sendUpdate({
435
+ type: "progress",
436
+ runningAction: this,
437
+ time: Date.now(),
438
+ progress: progress.progress
439
+ });
440
+ }
441
+ waitForResultPayload() {
442
+ return this._resultPayloadPromise;
443
+ }
444
+ _resolveFromJson(resultJson) {
445
+ if (this._state.result != null || this._isAborted) return false;
446
+ const result = this._domain.hydrateResultPayload(resultJson);
447
+ return this._completeWithResult(result);
448
+ }
449
+ };
450
+ //#endregion
451
+ //#region src/errors/err_nice_action.ts
452
+ let EErrId_NiceAction = /* @__PURE__ */ function(EErrId_NiceAction) {
453
+ EErrId_NiceAction["not_implemented"] = "not_implemented";
454
+ EErrId_NiceAction["action_id_not_in_domain"] = "action_id_not_in_domain";
455
+ EErrId_NiceAction["domain_already_exists_in_hierarchy"] = "domain_already_exists_in_hierarchy";
456
+ EErrId_NiceAction["domain_no_handler"] = "domain_no_handler";
457
+ EErrId_NiceAction["hydration_domain_mismatch"] = "hydration_domain_mismatch";
458
+ EErrId_NiceAction["hydration_action_state_mismatch"] = "hydration_action_state_mismatch";
459
+ EErrId_NiceAction["hydration_action_id_not_found"] = "hydration_action_id_not_found";
460
+ EErrId_NiceAction["no_action_execution_handler"] = "no_action_execution_handler";
461
+ EErrId_NiceAction["wire_action_not_payload"] = "wire_action_not_payload";
462
+ EErrId_NiceAction["wire_not_action_data"] = "wire_not_action_data";
463
+ EErrId_NiceAction["client_runtime_already_registered"] = "client_runtime_already_registered";
464
+ EErrId_NiceAction["client_runtime_not_registered"] = "client_runtime_not_registered";
465
+ EErrId_NiceAction["runtime_reset"] = "runtime_reset";
466
+ EErrId_NiceAction["no_client_runtimes_registered"] = "no_client_runtimes_registered";
467
+ EErrId_NiceAction["action_input_validation_failed"] = "action_input_validation_failed";
468
+ EErrId_NiceAction["action_input_validation_promise"] = "action_input_validation_promise";
469
+ EErrId_NiceAction["action_output_validation_failed"] = "action_output_validation_failed";
470
+ EErrId_NiceAction["action_output_validation_promise"] = "action_output_validation_promise";
471
+ return EErrId_NiceAction;
472
+ }({});
473
+ const err_nice_action = err_nice.createChildDomain({
474
+ domain: "err_nice_action",
475
+ defaultHttpStatusCode: 500,
476
+ schema: {
477
+ ["not_implemented"]: err({ message: ({ label }) => `The "${label}" functionality is not implemented yet.` }),
478
+ ["action_id_not_in_domain"]: err({ message: ({ actionId, domain }) => `Action with id "${actionId}" does not exist in domain "${domain}".` }),
479
+ ["domain_already_exists_in_hierarchy"]: err({ message: ({ domain, allParentDomains, parentDomain }) => `Domain "${domain}" already exists in the hierarchy under the parent "${parentDomain}". All parent domains ["${allParentDomains.join(", ")}"]` }),
480
+ ["domain_no_handler"]: err({ message: ({ domain }) => `Domain "${domain}" has no action handler registered.` }),
481
+ ["hydration_domain_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: domain mismatch. Expected "${expected}", got "${received}".` }),
482
+ ["hydration_action_state_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: action state type mismatch. Expected "${expected}", got "${received}".` }),
483
+ ["hydration_action_id_not_found"]: err({ message: ({ domain, actionId }) => `Cannot hydrate action: id "${actionId}" does not exist in domain "${domain}".` }),
484
+ ["no_action_execution_handler"]: err({ message: ({ domain, actionId, specifiedClient }) => `${specifiedClient ? ` The targeted client runtime [${specifiedClient.stringId}] has no` : "No"} action handler registered for "${actionId}" in domain "${domain}".` }),
485
+ ["wire_action_not_payload"]: err({ message: ({ domain, actionId, actionState }) => `Cannot handle wire for action "${actionId}" in domain "${domain}": expected action form of "data" and type of "request", "progress" or "result", got "${actionState}".` }),
486
+ ["wire_not_action_data"]: err({ message: () => `Cannot handle wire for action: expected an object with a "domain" property of type string, a "form" property of "data" and a "type" property of "request", "progress" or "result".` }),
487
+ ["runtime_reset"]: err({ message: () => `Runtime has been reset.` }),
488
+ ["client_runtime_already_registered"]: err({ message: ({ context, client }) => `Environment is already registered${context?.domain ? ` on domain "${context.domain}"` : ""} for client [${client.stringId}]. Each client specifier (exact match on all properties) may only be registered once.` }),
489
+ ["client_runtime_not_registered"]: err({ message: ({ context, clientStringId }) => `No runtime registered${context?.domain ? ` on domain "${context.domain}"` : ""} for client [${clientStringId}].` }),
490
+ ["no_client_runtimes_registered"]: err({ message: ({ context }) => `No runtimes registered${context?.domain ? ` on domain "${context.domain}"` : ""}. Add handlers to a runtime via runtime.addHandlers([handler]) before executing actions.` }),
491
+ ["action_input_validation_failed"]: err({
492
+ message: ({ domain, actionId, validationMessage }) => `Input validation failed for action "${actionId}" in domain "${domain}":\n${validationMessage}`,
493
+ httpStatusCode: 400
494
+ }),
495
+ ["action_input_validation_promise"]: err({
496
+ message: ({ domain, actionId }) => `Input validation for action "${actionId}" in domain "${domain}" returned a promise, which is not supported.`,
497
+ httpStatusCode: 400
498
+ }),
499
+ ["action_output_validation_failed"]: err({
500
+ message: ({ domain, actionId, validationMessage }) => `Output validation failed for action "${actionId}" in domain "${domain}":\n${validationMessage}`,
501
+ httpStatusCode: 500
502
+ }),
503
+ ["action_output_validation_promise"]: err({
504
+ message: ({ domain, actionId }) => `Output validation for action "${actionId}" in domain "${domain}" returned a promise, which is not supported.`,
505
+ httpStatusCode: 500
506
+ })
507
+ }
508
+ });
509
+ //#endregion
510
+ //#region src/utils/isAction_Base_JsonObject.ts
511
+ const isAction_Base_JsonObject = (obj) => {
512
+ return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && typeof obj.form === "string";
513
+ };
514
+ //#endregion
515
+ //#region src/utils/isActionPayload_Result_JsonObject.ts
516
+ const isActionPayload_Result_JsonObject = (obj) => {
517
+ return isAction_Base_JsonObject(obj) && obj.result != null && obj.form === "data" && obj.type === "result";
518
+ };
519
+ //#endregion
520
+ //#region src/ActionDefinition/Schema/ActionSchema.ts
521
+ /**
522
+ * What a sender should expect back from an action — declared on its schema so both ends agree without
523
+ * any wire flag (each derives the mode from the shared `domain:id`).
524
+ *
525
+ * - `payload` — a typed output (the action has `.output(...)`); the sender awaits it.
526
+ * - `ack` — an empty success confirming receipt (no output); the sender may await it to know the
527
+ * receiver handled it (or to surface an error). This is the default for an action with no output.
528
+ * - `none` — fire-and-forget: the receiver sends no reply and the sender doesn't wait. The sender's
529
+ * running action completes as soon as the frame is on the wire (no pending reply, no timeout).
530
+ */
531
+ let EActionResponseMode = /* @__PURE__ */ function(EActionResponseMode) {
532
+ EActionResponseMode["payload"] = "payload";
533
+ EActionResponseMode["ack"] = "ack";
534
+ EActionResponseMode["none"] = "none";
535
+ return EActionResponseMode;
536
+ }({});
537
+ var ActionSchema = class {
538
+ _errorDeclarations = [];
539
+ inputOptions;
540
+ outputOptions;
541
+ _responseMode;
542
+ get inputSchema() {
543
+ return this.inputOptions?.schema;
544
+ }
545
+ get outputSchema() {
546
+ return this.outputOptions?.schema;
547
+ }
548
+ /**
549
+ * The response contract for this action. Defaults are inferred — `payload` when an output schema is
550
+ * declared, otherwise `ack` — and made explicit by {@link ack} / {@link fireAndForget}.
551
+ */
552
+ get responseMode() {
553
+ if (this._responseMode != null) return this._responseMode;
554
+ return this.outputOptions != null ? "payload" : "ack";
555
+ }
556
+ /**
557
+ * Mark this action as expecting only an acknowledgment (an empty success). Mostly for clarity — an
558
+ * output-less action already acks by default — but it documents intent and reads as the deliberate
559
+ * counterpart to {@link fireAndForget}.
560
+ */
561
+ ack() {
562
+ this._responseMode = "ack";
563
+ return this;
564
+ }
565
+ /**
566
+ * Mark this action as fire-and-forget: the receiver sends no reply, and the sender's running action
567
+ * completes the moment the frame is sent (no awaited reply, no timeout). Ideal for high-frequency
568
+ * server→client pushes (presence, ticks) where an ack would only add wire chatter.
569
+ */
570
+ fireAndForget() {
571
+ this._responseMode = "none";
572
+ return this;
573
+ }
574
+ /**
575
+ * Declare the input schema (JSON-native or with explicit SERDE type param).
576
+ * For non-JSON-native inputs, prefer the 3-argument form below to avoid
577
+ * needing explicit type parameters.
578
+ */
579
+ input(options) {
580
+ this.inputOptions = options;
581
+ return this;
582
+ }
583
+ /**
584
+ * Declare the output schema (JSON-native or with explicit SERDE type param).
585
+ * For non-JSON-native outputs, prefer the 3-argument form below to avoid
586
+ * needing explicit type parameters.
587
+ */
588
+ output(options) {
589
+ this.outputOptions = options;
590
+ return this;
591
+ }
592
+ throws(domain, ids) {
593
+ this._errorDeclarations.push({
594
+ _domain: domain,
595
+ _ids: ids
596
+ });
597
+ return this;
598
+ }
599
+ /**
600
+ * Serialize raw input to a JSON-serializable form.
601
+ * Uses the schema's serialization.serialize if defined; otherwise the input
602
+ * is already JSON-native and is returned as-is.
603
+ */
604
+ serializeInput(rawInput) {
605
+ if (this.inputOptions?.serialization) return this.inputOptions.serialization.serialize(rawInput);
606
+ return rawInput;
607
+ }
608
+ /**
609
+ * Deserialize a JSON value back into the raw input type.
610
+ * Uses serialization.deserialize if defined; otherwise the value is cast
611
+ * directly (it's already in the correct shape).
612
+ */
613
+ deserializeInput(serialized) {
614
+ if (this.inputOptions?.serialization) return this.inputOptions.serialization.deserialize(serialized);
615
+ return serialized;
616
+ }
617
+ /**
618
+ * Validate raw input against the schema defined via `.input({ schema })`.
619
+ * Throws `action_input_validation_failed` if validation fails.
620
+ * Returns the validated (and possibly coerced) value on success.
621
+ * If no input schema was declared, the value is passed through as-is.
622
+ */
623
+ validateInput(value, meta) {
624
+ if (this.inputOptions?.schema == null) return value;
625
+ const result = this.inputOptions.schema["~standard"].validate(value);
626
+ if (result instanceof Promise) throw err_nice_action.fromId("action_input_validation_promise", {
627
+ domain: meta.domain,
628
+ actionId: meta.actionId
629
+ });
630
+ if (result.issues != null) throw err_nice_action.fromId("action_input_validation_failed", {
631
+ domain: meta.domain,
632
+ actionId: meta.actionId,
633
+ validationMessage: extractMessageFromStandardSchema(result)
634
+ });
635
+ return result.value;
636
+ }
637
+ validateOutput(value, meta) {
638
+ if (this.outputOptions?.schema == null) return value;
639
+ const result = this.outputOptions.schema["~standard"].validate(value);
640
+ if (result instanceof Promise) throw err_nice_action.fromId("action_output_validation_promise", {
641
+ domain: meta.domain,
642
+ actionId: meta.actionId
643
+ });
644
+ if (result.issues != null) throw err_nice_action.fromId("action_output_validation_failed", {
645
+ domain: meta.domain,
646
+ actionId: meta.actionId,
647
+ validationMessage: extractMessageFromStandardSchema(result)
648
+ });
649
+ return result.value;
650
+ }
651
+ /**
652
+ * Serialize raw output to a JSON-serializable form.
653
+ */
654
+ serializeOutput(rawOutput) {
655
+ if (this.outputOptions?.serialization) return this.outputOptions.serialization.serialize(rawOutput);
656
+ return rawOutput;
657
+ }
658
+ /**
659
+ * Deserialize a JSON value back into the raw output type.
660
+ */
661
+ deserializeOutput(serialized) {
662
+ if (this.outputOptions?.serialization) return this.outputOptions.serialization.deserialize(serialized);
663
+ return serialized;
664
+ }
665
+ };
666
+ const actionSchema = () => {
667
+ return new ActionSchema();
668
+ };
669
+ //#endregion
670
+ //#region src/utils/getAssumedRuntimeEnvironment.ts
671
+ const getAssumedRuntimeInfo = () => {
672
+ return {
673
+ assumed: true,
674
+ runtimeName: runtime
675
+ };
676
+ };
677
+ //#endregion
678
+ //#region src/utils/isActionPayload_Progress_JsonObject.ts
679
+ const isActionPayload_Progress_JsonObject = (obj) => {
680
+ return isAction_Base_JsonObject(obj) && "progress" in obj && obj.form === "data" && obj.type === "progress";
681
+ };
682
+ //#endregion
683
+ //#region src/utils/isActionPayload_Request_JsonObject.ts
684
+ const isActionPayload_Request_JsonObject = (obj) => {
685
+ return isAction_Base_JsonObject(obj) && "input" in obj && obj.form === "data" && obj.type === "request";
686
+ };
687
+ //#endregion
688
+ //#region src/utils/isActionPayload_Any_JsonObject.ts
689
+ function isActionPayload_Any_JsonObject(obj) {
690
+ return isActionPayload_Request_JsonObject(obj) || isActionPayload_Result_JsonObject(obj) || isActionPayload_Progress_JsonObject(obj);
691
+ }
692
+ //#endregion
693
+ //#region src/ActionRuntime/HandlerCallStack.ts
694
+ const _stack = [];
695
+ function pushHandlerCuid(cuid) {
696
+ _stack.push(cuid);
697
+ }
698
+ function popHandlerCuid() {
699
+ _stack.pop();
700
+ }
701
+ function peekHandlerCuid() {
702
+ return _stack[_stack.length - 1];
703
+ }
704
+ //#endregion
705
+ //#region src/ActionRuntime/Handler/PeerLink/Connector/err_nice_external_client.ts
706
+ const err_nice_external_client = err_nice_action.createChildDomain({
707
+ domain: "err_nice_external_client",
708
+ schema: {}
709
+ });
710
+ //#endregion
711
+ //#region src/ActionRuntime/Transport/err_nice_transport.ts
712
+ let EErrId_NiceTransport = /* @__PURE__ */ function(EErrId_NiceTransport) {
713
+ EErrId_NiceTransport["timeout"] = "timeout";
714
+ EErrId_NiceTransport["not_found"] = "not_found";
715
+ EErrId_NiceTransport["unsupported"] = "unsupported";
716
+ EErrId_NiceTransport["initialization_failed"] = "initialization_failed";
717
+ EErrId_NiceTransport["send_failed"] = "send_failed";
718
+ EErrId_NiceTransport["invalid_action_response"] = "invalid_action_response";
719
+ return EErrId_NiceTransport;
720
+ }({});
721
+ const err_nice_transport = err_nice_external_client.createChildDomain({
722
+ domain: "err_nice_transport",
723
+ schema: {
724
+ ["timeout"]: err({ message: ({ timeout }) => `ActionConnect transport timed out after ${timeout}ms.` }),
725
+ ["not_found"]: err({ message: ({ actionId }) => `No connected transport found for action "${actionId}".` }),
726
+ ["unsupported"]: err({ message: ({ transportShapes }) => `${transportShapes.length} Transport(s) [${transportShapes.join(", ")}] found but returned "unsupported" status.` }),
727
+ ["initialization_failed"]: err({ message: ({ actionId }) => `Transports found for action "${actionId}", but none are ready.` }),
728
+ ["send_failed"]: err({
729
+ message: ({ actionId, httpStatusCode, message }) => `Failed to send action "${actionId}" [${httpStatusCode ?? "Unknown status"}]: ${message ?? "Unknown error"}.`,
730
+ httpStatusCode: ({ httpStatusCode }) => httpStatusCode ?? 500
731
+ }),
732
+ ["invalid_action_response"]: err({ message: ({ actionId }) => `Invalid action response JSON structure for action "${actionId}"` })
733
+ }
734
+ });
735
+ //#endregion
736
+ //#region src/ActionRuntime/Transport/Transport.types.ts
737
+ /**
738
+ * Carrier-shape class identity: the one carrier-invariant trait the selection layer reasons about —
739
+ * whether a carrier can push unsolicited frames (`duplex`: WS/WebRTC/BLE/in-memory) or only answers a
740
+ * request with a single correlated reply (`exchange`: HTTP). The concrete carrier kind ("ws", "webrtc",
741
+ * "http", …) is a free-form {@link ITransportRouteInfo.carrierLabel} for display, not a class tag.
742
+ */
743
+ let ETransportShape = /* @__PURE__ */ function(ETransportShape) {
744
+ ETransportShape["duplex"] = "duplex";
745
+ ETransportShape["exchange"] = "exchange";
746
+ return ETransportShape;
747
+ }({});
748
+ /**
749
+ *
750
+ * TRANSPORT READINESS RESPONSE
751
+ *
752
+ */
753
+ let ETransportStatus = /* @__PURE__ */ function(ETransportStatus) {
754
+ ETransportStatus["uninitialized"] = "uninitialized";
755
+ ETransportStatus["unsupported"] = "unsupported";
756
+ ETransportStatus["initializing"] = "initializing";
757
+ ETransportStatus["ready"] = "ready";
758
+ ETransportStatus["failed"] = "failed";
759
+ return ETransportStatus;
760
+ }({});
761
+ //#endregion
762
+ //#region src/ActionRuntime/Transport/ConnectionTransportManager.ts
763
+ var ConnectionTransportManager = class {
764
+ _cache;
765
+ _transports = [];
766
+ constructor(_cache) {
767
+ this._cache = _cache;
768
+ }
769
+ addTransport(transport) {
770
+ this._transports.push(transport);
771
+ }
772
+ /**
773
+ * The highest-priority transport (first declared). Used to label an action's route *before* the
774
+ * transport has finished connecting — so a still-connecting action shows its (expected) destination
775
+ * instead of an "unknown" hop. {@link getReadyTransport} still decides the real winner, and the
776
+ * caller corrects the hop if a lower-priority transport ends up serving the action.
777
+ */
778
+ getPreferredTransport() {
779
+ return this._transports[0];
780
+ }
781
+ async getReadyTransport(routeActionParams) {
782
+ const action = routeActionParams.action;
783
+ const candidates = [];
784
+ const unavailableTransports = [];
785
+ for (const transport of this._transports) {
786
+ if (!transport.isAvailable(routeActionParams)) {
787
+ unavailableTransports.push(transport);
788
+ continue;
789
+ }
790
+ const cacheKey = transport.getCacheKey(routeActionParams);
791
+ if (cacheKey != null) {
792
+ const cached = this._cache.get(cacheKey);
793
+ if (cached != null) {
794
+ if (cached instanceof Promise) {
795
+ candidates.push(cached);
796
+ continue;
797
+ }
798
+ candidates.push(Promise.resolve({
799
+ ...cached,
800
+ transport
801
+ }));
802
+ break;
803
+ }
804
+ }
805
+ const statusInfo = transport.getTransport(routeActionParams);
806
+ if (statusInfo.status === "ready") {
807
+ const readyData = statusInfo.readyData;
808
+ if (cacheKey != null) {
809
+ const entry = {
810
+ methods: readyData,
811
+ transport
812
+ };
813
+ this._cache.set(cacheKey, entry);
814
+ readyData.addOnDisconnectListener?.(() => {
815
+ if (this._cache.get(cacheKey) === entry) this._cache.delete(cacheKey);
816
+ });
817
+ }
818
+ candidates.push(Promise.resolve({
819
+ methods: readyData,
820
+ transport
821
+ }));
822
+ break;
823
+ }
824
+ if (statusInfo.status === "unsupported") {
825
+ unavailableTransports.push(transport);
826
+ continue;
827
+ }
828
+ if (statusInfo.status === "initializing") {
829
+ const promise = statusInfo.initializationPromise.then((info) => {
830
+ if (info.status === "failed") throw info.error;
831
+ if (info.status === "unsupported") throw err_nice_transport.fromId("unsupported", { transportShapes: [transport.type] });
832
+ const readyData = info.readyData;
833
+ const entry = {
834
+ methods: readyData,
835
+ transport
836
+ };
837
+ if (cacheKey != null) if (this._cache.get(cacheKey) === promise) {
838
+ this._cache.set(cacheKey, entry);
839
+ readyData.addOnDisconnectListener?.(() => {
840
+ if (this._cache.get(cacheKey) === entry) this._cache.delete(cacheKey);
841
+ });
842
+ } else readyData.disconnect?.();
843
+ return entry;
844
+ }).catch((e) => {
845
+ if (cacheKey != null && this._cache.get(cacheKey) === promise) this._cache.delete(cacheKey);
846
+ throw e;
847
+ });
848
+ if (cacheKey != null) this._cache.set(cacheKey, promise);
849
+ candidates.push(promise);
850
+ }
851
+ }
852
+ if (candidates.length === 0) {
853
+ if (unavailableTransports.length > 0) throw err_nice_transport.fromId("unsupported", { transportShapes: unavailableTransports.map((t) => t.type) });
854
+ throw err_nice_transport.fromId("not_found", { actionId: action.id });
855
+ }
856
+ let lastError;
857
+ for (const candidate of candidates) try {
858
+ return await candidate;
859
+ } catch (e) {
860
+ lastError = e;
861
+ }
862
+ throw err_nice_transport.fromId("initialization_failed", { actionId: action.id }).withOriginError(lastError);
863
+ }
864
+ };
865
+ //#endregion
866
+ //#region src/ActionRuntime/ActionDomainManager.ts
867
+ var ActionDomainManager = class {
868
+ _domains = /* @__PURE__ */ new Map();
869
+ addDomain(domain) {
870
+ this._domains.set(domain.domain, domain);
871
+ }
872
+ getDomains() {
873
+ return [...this._domains.values()];
874
+ }
875
+ verifyIsActionJson(action) {
876
+ if (typeof action.domain !== "string" || typeof action.id !== "string") throw err_nice_action.fromId("wire_not_action_data");
877
+ }
878
+ getActionDomain(action) {
879
+ this.verifyIsActionJson(action);
880
+ const domain = this._domains.get(action.domain);
881
+ if (!domain) return;
882
+ return domain;
883
+ }
884
+ getActionDomainOrThrow(action) {
885
+ this.verifyIsActionJson(action);
886
+ const domain = this._domains.get(action.domain);
887
+ if (!domain) throw err_nice_action.fromId("domain_no_handler", { domain: action.domain });
888
+ return domain;
889
+ }
890
+ hydrateActionPayload(actionJson) {
891
+ return this.getActionDomainOrThrow(actionJson).hydrateAnyAction(actionJson);
892
+ }
893
+ };
894
+ //#endregion
895
+ //#region src/ActionRuntime/Routing/ActionRouter.ts
896
+ var ActionRouter = class {
897
+ domainManager = new ActionDomainManager();
898
+ actionRouteData = /* @__PURE__ */ new Map();
899
+ _context;
900
+ constructor(context) {
901
+ this._context = context;
902
+ }
903
+ /** Copy all routes from another router into this one, replacing any overlapping keys. */
904
+ mergeRouter(actionRouter) {
905
+ for (const domain of actionRouter.getDomains()) this.domainManager.addDomain(domain);
906
+ for (const [matchKey, routeDataEntries] of actionRouter.actionRouteData.entries()) this.actionRouteData.set(matchKey, [...routeDataEntries]);
907
+ }
908
+ addDomainsFromOther(actionRouter) {
909
+ for (const domain of actionRouter.getDomains()) this.domainManager.addDomain(domain);
910
+ }
911
+ /** All FNs registered for an action, ID-specific entries first then domain wildcard. */
912
+ getRouteDataEntriesForAction(action) {
913
+ const idKey = `dom[${action.domain}]id[${action.id}]`;
914
+ const domKey = `dom[${action.domain}]id[_]`;
915
+ return [...this.actionRouteData.get(idKey) ?? [], ...this.actionRouteData.get(domKey) ?? []];
916
+ }
917
+ /** First FN registered for an action (ID-specific beats domain wildcard). */
918
+ getRouteDataForAction(action) {
919
+ return this.getRouteDataEntriesForAction(action)[0];
920
+ }
921
+ throwNoHandlerForAction(action, context) {
922
+ if (this._context.contextType === "handler_route") throw err_nice_action.fromId("no_action_execution_handler", {
923
+ domain: action.domain,
924
+ actionId: action.id,
925
+ specifiedClient: context.targetLocalRuntime?.coordinate
926
+ });
927
+ if (this._context.contextType === "runtime_to_handler") throw err_nice_action.fromId("no_action_execution_handler", {
928
+ domain: action.domain,
929
+ actionId: action.id,
930
+ specifiedClient: this._context.runtime.coordinate
931
+ });
932
+ throw err_nice_action.fromId("no_action_execution_handler", {
933
+ domain: action.domain,
934
+ actionId: action.id
935
+ });
936
+ }
937
+ getRouteDataEntriesForActionOrThrow(action, context) {
938
+ const entries = this.getRouteDataEntriesForAction(action);
939
+ if (entries.length === 0) this.throwNoHandlerForAction(action, context);
940
+ return entries;
941
+ }
942
+ getRouteDataForActionOrThrow(action, context) {
943
+ const routeData = this.getRouteDataForAction(action);
944
+ if (!routeData) this.throwNoHandlerForAction(action, context);
945
+ return routeData;
946
+ }
947
+ /** All FNs stored under an exact match key. */
948
+ getForKey(key) {
949
+ return this.actionRouteData.get(key) ?? [];
950
+ }
951
+ /** Every match key that has at least one registered FN. */
952
+ getRegisteredKeys() {
953
+ return [...this.actionRouteData.keys()];
954
+ }
955
+ getDomains() {
956
+ return this.domainManager.getDomains();
957
+ }
958
+ /** Register a handler for all actions in a domain, replacing any existing one. */
959
+ forDomain(domain, routeData) {
960
+ this.domainManager.addDomain(domain);
961
+ this.actionRouteData.set(`dom[${domain.domain}]id[_]`, [routeData]);
962
+ return this;
963
+ }
964
+ forAction(action, routeData) {
965
+ return this.forActionId(action._domain, action.id, routeData);
966
+ }
967
+ /** Register a handler for a specific action, replacing any existing one. */
968
+ forActionId(domain, id, routeData) {
969
+ this.domainManager.addDomain(domain);
970
+ this.actionRouteData.set(`dom[${domain.domain}]id[${id}]`, [routeData]);
971
+ return this;
972
+ }
973
+ /** Register one handler for several action IDs, replacing any existing ones. */
974
+ forActionIds(domain, ids, routeData) {
975
+ this.domainManager.addDomain(domain);
976
+ for (const id of ids) this.forActionId(domain, id, routeData);
977
+ return this;
978
+ }
979
+ /** Register per-action handlers from a cases map, replacing any existing ones. */
980
+ forDomainActionCases(domain, cases) {
981
+ this.domainManager.addDomain(domain);
982
+ for (const id of Object.keys(cases)) {
983
+ const routeData = cases[id];
984
+ if (routeData != null) this.actionRouteData.set(`dom[${domain.domain}]id[${id}]`, [routeData]);
985
+ }
986
+ return this;
987
+ }
988
+ /** Append a handler for all actions in a domain (accumulates alongside existing). */
989
+ addForDomain(domain, routeData) {
990
+ this.domainManager.addDomain(domain);
991
+ this._push(`dom[${domain.domain}]id[_]`, routeData);
992
+ return this;
993
+ }
994
+ /** Append a handler for a specific action (accumulates alongside existing). */
995
+ addForAction(domain, id, routeData) {
996
+ this.domainManager.addDomain(domain);
997
+ this._push(`dom[${domain.domain}]id[${id}]`, routeData);
998
+ return this;
999
+ }
1000
+ /** Append one handler for several action IDs (accumulates alongside existing). */
1001
+ addForActionIds(domain, ids, routeData) {
1002
+ this.domainManager.addDomain(domain);
1003
+ for (const id of ids) this.addForAction(domain, id, routeData);
1004
+ return this;
1005
+ }
1006
+ /** Append per-action handlers from a cases map (accumulates alongside existing). */
1007
+ addForDomainActionCases(domain, cases) {
1008
+ this.domainManager.addDomain(domain);
1009
+ for (const id of Object.keys(cases)) {
1010
+ const routeData = cases[id];
1011
+ if (routeData != null) this._push(`dom[${domain.domain}]id[${id}]`, routeData);
1012
+ }
1013
+ return this;
1014
+ }
1015
+ /** Append a handler directly by its raw match key (used when the key is known ahead of time). */
1016
+ addForKey(key, routeData) {
1017
+ this._push(key, routeData);
1018
+ return this;
1019
+ }
1020
+ _push(key, routeData) {
1021
+ const existing = this.actionRouteData.get(key);
1022
+ if (existing != null) existing.push(routeData);
1023
+ else this.actionRouteData.set(key, [routeData]);
1024
+ }
1025
+ };
1026
+ //#endregion
1027
+ //#region src/ActionRuntime/Handler/ActionHandler.ts
1028
+ var ActionHandler = class {
1029
+ cuid;
1030
+ constructor() {
1031
+ this.cuid = nanoid();
1032
+ }
1033
+ getActionRouter() {
1034
+ return this.actionRouter;
1035
+ }
1036
+ };
1037
+ //#endregion
1038
+ //#region src/ActionRuntime/Handler/PeerLink/PeerLinkHandler.ts
1039
+ /**
1040
+ * Shared base for every handler that routes a domain set to/from *another runtime* (a "peer") — the
1041
+ * unified peer-link concept. Both specializations extend this as siblings, differing only in *who
1042
+ * establishes the connection*, which is a transport trait, not a routing one:
1043
+ *
1044
+ * - {@link ConnectorHandler} — **dial-out**: this runtime opens connection(s) to one peer
1045
+ * over a transport stack (with caching + fallback). The classic "client → backend" link.
1046
+ * - {@link AcceptorHandler} — **accept-in**: connections are accepted from many peers and fed in
1047
+ * via `receive()`; it keeps a per-connection registry and can push to any of them.
1048
+ *
1049
+ * To the runtime there is no "client" vs "server" — both are peer-link handlers (`handlerType =
1050
+ * external`) keyed to a peer coordinate, chosen by the return-path dispatch via {@link sendReturnPayload}.
1051
+ */
1052
+ var PeerLinkHandler = class extends ActionHandler {
1053
+ /** The peer runtime this handler links to (an env-only coordinate for an accept-in handler). */
1054
+ peerClient;
1055
+ handlerType = "peer";
1056
+ actionRouter = new ActionRouter({
1057
+ contextType: "handler_route",
1058
+ handler: this
1059
+ });
1060
+ /** Listeners installed by the runtime (`resolveIncomingActionPayload`) for inbound peer frames. */
1061
+ _incomingActionDataListeners = [];
1062
+ constructor(peerCoordinate) {
1063
+ super();
1064
+ this.peerClient = peerCoordinate;
1065
+ }
1066
+ forDomain(domain) {
1067
+ this.actionRouter.forDomain(domain, true);
1068
+ return this;
1069
+ }
1070
+ forAction(action) {
1071
+ this.actionRouter.forAction(action, true);
1072
+ return this;
1073
+ }
1074
+ forActionIds(domain, ids) {
1075
+ this.actionRouter.forActionIds(domain, ids, true);
1076
+ return this;
1077
+ }
1078
+ _setIncomingActionDataListener(listener) {
1079
+ this._incomingActionDataListeners.push(listener);
1080
+ }
1081
+ /** Hand a decoded inbound frame to the runtime (called by each specialization's receive path). */
1082
+ _emitIncoming(json) {
1083
+ for (const listener of this._incomingActionDataListeners) listener(json);
1084
+ }
1085
+ /**
1086
+ * Whether this handler currently holds a *live* connection bound to `origin`. The runtime's return-path
1087
+ * dispatch ({@link ActionRuntime.getReturnHandlerForOrigin}) prefers a handler that owns the origin's
1088
+ * connection over a mere coordinate match, so with several duplex acceptors a result/push routes back
1089
+ * over the carrier the client connected on. Defaults to `false`; an acceptor overrides it from its
1090
+ * connection registry.
1091
+ */
1092
+ ownsLiveConnectionFor(_origin) {
1093
+ return false;
1094
+ }
1095
+ /** Release any long-lived connections this handler owns (a teardown). No-op by default. */
1096
+ clearTransportCache() {}
1097
+ };
1098
+ //#endregion
1099
+ //#region src/ActionRuntime/Handler/PeerLink/Connector/ConnectorHandler.ts
1100
+ /**
1101
+ * Dial-out peer link: this runtime opens connection(s) to one peer over a transport stack (cached, with
1102
+ * preference-ordered fallback). The classic "client → backend" handler — but to the runtime it's just a
1103
+ * {@link PeerLinkHandler} like the accept-in server one.
1104
+ */
1105
+ var ConnectorHandler = class extends PeerLinkHandler {
1106
+ /**
1107
+ * Dial-out can receive (and so return) an unsolicited push only over a duplex transport. With every
1108
+ * transport exchange-only (HTTP), the peer can never push to us — so this link can't deliver one back.
1109
+ */
1110
+ canPush;
1111
+ _defaultTimeout;
1112
+ _transportCache = /* @__PURE__ */ new Map();
1113
+ transportManager = new ConnectionTransportManager(this._transportCache);
1114
+ constructor({ runtimeCoordinate: peerSpecifier, transports, defaultTimeout }) {
1115
+ super(peerSpecifier);
1116
+ this._defaultTimeout = defaultTimeout ?? 1e4;
1117
+ this.canPush = transports.some((transport) => transport.type === "duplex");
1118
+ for (const transport of transports) {
1119
+ const connection = transport._createConnection({ resolvers: { onIncomingActionDataJson: (json) => this._emitIncoming(json) } });
1120
+ connection.definition = transport;
1121
+ this.transportManager.addTransport(connection);
1122
+ }
1123
+ }
1124
+ async handleActionRequest(action, config) {
1125
+ const localRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();
1126
+ const localClient = localRuntime.coordinate;
1127
+ const incomingTimeout = config?.timeout ?? this._defaultTimeout;
1128
+ const parentCuid = peekHandlerCuid();
1129
+ const callSite = action._callSite ?? (/* @__PURE__ */ new Error()).stack;
1130
+ const routeParams = {
1131
+ action,
1132
+ localClient,
1133
+ externalClient: this.peerClient
1134
+ };
1135
+ const preferredTransport = this.transportManager.getPreferredTransport();
1136
+ const routeItem = preferredTransport != null ? {
1137
+ runtime: localClient,
1138
+ handler: this.toHandlerRouteItem(preferredTransport, routeParams),
1139
+ time: Date.now()
1140
+ } : void 0;
1141
+ if (routeItem != null) action.context.addRouteItem(routeItem);
1142
+ const runningAction = new RunningAction({
1143
+ context: action.context,
1144
+ request: action,
1145
+ parentCuid,
1146
+ callSite
1147
+ });
1148
+ localRuntime.registerRunningAction(runningAction);
1149
+ this._dispatchWhenTransportReady(runningAction, routeParams, routeItem, incomingTimeout);
1150
+ return runningAction;
1151
+ }
1152
+ async _dispatchWhenTransportReady(runningAction, routeParams, routeItem, incomingTimeout) {
1153
+ const action = routeParams.action;
1154
+ try {
1155
+ const { methods, transport } = await this.transportManager.getReadyTransport(routeParams);
1156
+ const handlerRouteItem = this.toHandlerRouteItem(transport, routeParams);
1157
+ if (routeItem != null) {
1158
+ routeItem.handler = handlerRouteItem;
1159
+ routeItem.time = Date.now();
1160
+ } else action.context.addRouteItem({
1161
+ runtime: routeParams.localClient,
1162
+ handler: handlerRouteItem,
1163
+ time: Date.now()
1164
+ });
1165
+ const sendInput = {
1166
+ ...routeParams,
1167
+ runningAction,
1168
+ timeout: incomingTimeout
1169
+ };
1170
+ if (action.type === "request" && methods.updateRunConfig != null) sendInput.timeout = methods.updateRunConfig(sendInput)?.timeout ?? incomingTimeout;
1171
+ methods.sendActionData(sendInput);
1172
+ if (action.type === "request" && action.schema.responseMode === "none") runningAction._completeWithResult(action.successResult(void 0));
1173
+ } catch (err) {
1174
+ runningAction._abort(err);
1175
+ }
1176
+ }
1177
+ /**
1178
+ * Dispatch a result or progress payload directly back to the external client via the best
1179
+ * available bidirectional transport (WebSocket / Custom). Used for return-path routing when the
1180
+ * local runtime recognises that it has a direct channel to the action's originClient.
1181
+ *
1182
+ * Returns `true` if the payload was sent, `false` if no suitable transport was available.
1183
+ */
1184
+ async sendReturnPayload(payload, config) {
1185
+ const localClient = config.targetLocalRuntime.coordinate;
1186
+ try {
1187
+ const { methods } = await this.transportManager.getReadyTransport({
1188
+ action: payload,
1189
+ localClient,
1190
+ externalClient: this.peerClient
1191
+ });
1192
+ if (methods.sendReturnData == null) return false;
1193
+ methods.sendReturnData(payload, {
1194
+ localClient,
1195
+ externalClient: this.peerClient
1196
+ });
1197
+ return true;
1198
+ } catch {
1199
+ return false;
1200
+ }
1201
+ }
1202
+ toJsonObject() {
1203
+ return {
1204
+ type: this.handlerType,
1205
+ client: this.peerClient
1206
+ };
1207
+ }
1208
+ toHandlerRouteItem(transport, input) {
1209
+ return {
1210
+ type: this.handlerType,
1211
+ client: this.peerClient,
1212
+ transOrd: transport.transOrd,
1213
+ transShape: transport.type,
1214
+ transInfo: transport.getRouteInfo(input)
1215
+ };
1216
+ }
1217
+ clearTransportCache() {
1218
+ for (const entry of this._transportCache.values()) if (entry instanceof Promise) entry.then((ready) => ready.methods.disconnect?.()).catch(() => {});
1219
+ else entry.methods.disconnect?.();
1220
+ this._transportCache.clear();
1221
+ }
1222
+ };
1223
+ const createConnectorHandler = (config) => {
1224
+ return new ConnectorHandler(config);
1225
+ };
1226
+ //#endregion
1227
+ //#region src/ActionRuntime/ActionRuntime.ts
1228
+ var ActionRuntime = class {
1229
+ _coordinate;
1230
+ timeCreated;
1231
+ runtimeInfo = getAssumedRuntimeInfo();
1232
+ actionRouter;
1233
+ _pendingRunningActions = /* @__PURE__ */ new Map();
1234
+ _registeredPeerHandlers = [];
1235
+ _applied = false;
1236
+ static getDefault() {
1237
+ return getDefaultActionRuntime();
1238
+ }
1239
+ constructor(coordinate) {
1240
+ this._coordinate = coordinate.specifyIfUnset({ insId: nanoid(14) });
1241
+ this.timeCreated = Date.now();
1242
+ this.actionRouter = new ActionRouter({
1243
+ contextType: "runtime_to_handler",
1244
+ runtime: this
1245
+ });
1246
+ }
1247
+ get coordinate() {
1248
+ return this._coordinate;
1249
+ }
1250
+ specifyRuntimeCoordinate(specifics) {
1251
+ if (specifics.envId != null && this._coordinate.envId !== specifics.envId) throw err_nice_action.fromId("not_implemented", { label: `updating RuntimeCoordinate with a different "envId" ("${this._coordinate.envId}" → "${specifics.envId}")` });
1252
+ this._coordinate = this._coordinate.specify(specifics);
1253
+ this.apply();
1254
+ }
1255
+ registerRunningAction(ra) {
1256
+ this._pendingRunningActions.set(ra.cuid, ra);
1257
+ ra.addUpdateListeners([(update) => {
1258
+ if (update.type === "finished") this._pendingRunningActions.delete(ra.cuid);
1259
+ }]);
1260
+ }
1261
+ resolveIncomingActionPayload(json) {
1262
+ if (json.type === "request") {
1263
+ this.handleActionPayloadWire(json).catch((err) => {
1264
+ console.error(`[ActionRuntime] Incoming action [${json.domain}:${json.id}:${json.form}:${json.type}] unhandled:`, err);
1265
+ });
1266
+ return;
1267
+ }
1268
+ this._pendingRunningActions.get(json.context.cuid)?._resolveFromJson(json);
1269
+ }
1270
+ async handleActionPayloadWire(wire) {
1271
+ let action;
1272
+ if (isActionPayload_Any_JsonObject(wire)) action = this.actionRouter.domainManager.getActionDomainOrThrow(wire).hydrateAnyAction(wire);
1273
+ if (action == null) throw err_nice_action.fromId("wire_not_action_data");
1274
+ return this.handleActionPayload(action);
1275
+ }
1276
+ async handleActionPayload(action, options) {
1277
+ if (action.type === "request") {
1278
+ const observers = action.context._domain._collectActionObservers();
1279
+ let handlerForAction;
1280
+ try {
1281
+ handlerForAction = this.getHandlerForActionOrThrow(action, options);
1282
+ } catch (err) {
1283
+ const runningAction = new RunningAction({
1284
+ context: action.context,
1285
+ request: action
1286
+ });
1287
+ runningAction.addUpdateListeners(observers);
1288
+ runningAction._completeWithResult(action.errorResult(castNiceError(err)));
1289
+ return runningAction;
1290
+ }
1291
+ const runningAction = await handlerForAction.handleActionRequest(action, {
1292
+ ...options,
1293
+ targetLocalRuntime: this
1294
+ });
1295
+ runningAction.addUpdateListeners(observers);
1296
+ this._trySetupReturnDispatch(runningAction);
1297
+ return runningAction;
1298
+ }
1299
+ throw err_nice_action.fromId("not_implemented", { label: `Handling incoming action payloads of type "${action.type}"` });
1300
+ }
1301
+ /**
1302
+ * @internal
1303
+ *
1304
+ * Return the first handler registered for the given action, or `undefined`
1305
+ * if none has been registered (action-ID-specific beats domain-wildcard).
1306
+ */
1307
+ _getHandlerForAction(action, options) {
1308
+ const handlers = this.actionRouter.getRouteDataEntriesForAction(action);
1309
+ const targetPeer = options?.targetPeer;
1310
+ const possibleHandlers = handlers.filter((handler) => {
1311
+ if (handler.handlerType === "peer") {
1312
+ if (targetPeer && !targetPeer.isSameFor(handler.peerClient).id) return false;
1313
+ return true;
1314
+ }
1315
+ if (targetPeer != null) return false;
1316
+ if (action.type === "request") return true;
1317
+ return false;
1318
+ });
1319
+ if (possibleHandlers.length === 0) return;
1320
+ const scoringPeer = targetPeer ?? RuntimeCoordinate.unknown;
1321
+ let handlerScore = -1;
1322
+ let handler;
1323
+ for (const possibleHandler of possibleHandlers) {
1324
+ if (possibleHandler.handlerType === "local") return possibleHandler;
1325
+ if (possibleHandler.handlerType === "peer") {
1326
+ const score = scoringPeer.similarityLevel(possibleHandler.peerClient);
1327
+ if (score > handlerScore) {
1328
+ handlerScore = score;
1329
+ handler = possibleHandler;
1330
+ }
1331
+ }
1332
+ }
1333
+ return handler;
1334
+ }
1335
+ getHandlerForActionOrThrow(action, options) {
1336
+ const handler = this._getHandlerForAction(action, options);
1337
+ if (handler == null) throw err_nice_action.fromId("no_action_execution_handler", {
1338
+ actionId: action.id,
1339
+ domain: action.domain,
1340
+ specifiedClient: options?.targetPeer
1341
+ });
1342
+ return handler;
1343
+ }
1344
+ /**
1345
+ * Register one or more handlers. Each handler's own `actionRouter` defines
1346
+ * which domains/actions it handles — those routing keys are mirrored into
1347
+ * this runtime's router so the same action can be served by multiple handlers.
1348
+ * Duplicate registrations (same handler cuid for the same key) are skipped.
1349
+ */
1350
+ addHandlers(handlers) {
1351
+ for (const handler of handlers) {
1352
+ if (handler.handlerType === "peer") {
1353
+ handler._setIncomingActionDataListener((json) => this.resolveIncomingActionPayload(json));
1354
+ this._registeredPeerHandlers.push(handler);
1355
+ }
1356
+ const handlerRouter = handler.getActionRouter();
1357
+ this.actionRouter.addDomainsFromOther(handlerRouter);
1358
+ if (this._applied) this.apply();
1359
+ for (const key of handlerRouter.getRegisteredKeys()) if (!this.actionRouter.getForKey(key).some((h) => h.cuid === handler.cuid)) this.actionRouter.addForKey(key, handler);
1360
+ }
1361
+ return this;
1362
+ }
1363
+ /**
1364
+ * @internal Low-level primitive — the public way to open a connection is `connectChannel`, which
1365
+ * derives routing from a channel and binds the crypto identity for you. This stays as the raw building
1366
+ * block it sits on (it restates domain lists by hand) and is not part of the supported surface.
1367
+ *
1368
+ * Declare an external "backend client" in one call: build an
1369
+ * {@link ConnectorHandler} for `externalCoordinate` carrying the given
1370
+ * `transports`, route the listed `domains`/`actions` to it, register it (plus any
1371
+ * `localHandlers` — e.g. server→client push handlers that share the same channel)
1372
+ * on this runtime, and `apply()`. Returns the external handler so the caller can
1373
+ * later `clearTransportCache()` it.
1374
+ */
1375
+ connectTo(externalCoordinate, options) {
1376
+ const handler = new ConnectorHandler({
1377
+ runtimeCoordinate: externalCoordinate,
1378
+ transports: options.transports,
1379
+ defaultTimeout: options.defaultTimeout
1380
+ });
1381
+ for (const domain of options.domains ?? []) handler.forDomain(domain);
1382
+ for (const action of options.actions ?? []) handler.forAction(action);
1383
+ this.addHandlers([handler, ...options.localHandlers ?? []]);
1384
+ this.apply();
1385
+ return handler;
1386
+ }
1387
+ applyRuntimeForDomain(domain) {
1388
+ const rootDomain = domain.rootDomain;
1389
+ if (!rootDomain._hasRuntime(this)) rootDomain._registerRuntime(this);
1390
+ }
1391
+ /**
1392
+ * Register this runtime with all root domains covered by its currently-added handlers,
1393
+ * making it eligible to execute actions dispatched from those domains.
1394
+ * After apply() is called, any subsequent addHandlers() calls also auto-register.
1395
+ */
1396
+ apply() {
1397
+ this._applied = true;
1398
+ for (const domain of this.actionRouter.getDomains()) this.applyRuntimeForDomain(domain);
1399
+ return this;
1400
+ }
1401
+ /**
1402
+ * Find the best registered external handler that can reach `originClient` directly.
1403
+ * Used to locate the return-path channel for dispatching results back to the action origin.
1404
+ * Returns `undefined` if no handler matches (score > 0 required, i.e. at least id must match).
1405
+ *
1406
+ * A handler that currently holds the origin's *live* connection always wins over a mere coordinate
1407
+ * match — so with several duplex acceptors (e.g. WS + WebRTC) a result/push routes back over the carrier
1408
+ * the client actually connected on, never a same-coordinate sibling that lacks the socket. Only when no
1409
+ * handler owns a live connection do we fall back to the plain best-coordinate-score pick (the
1410
+ * single-acceptor and connector-only cases, unchanged).
1411
+ */
1412
+ getReturnHandlerForOrigin(originClient) {
1413
+ if (originClient.envId === "_unset_") return void 0;
1414
+ let bestScore = -1;
1415
+ let bestHandler;
1416
+ let bestOwnedScore = -1;
1417
+ let bestOwnedHandler;
1418
+ for (const handler of this._registeredPeerHandlers) {
1419
+ if (!handler.canPush) continue;
1420
+ const score = originClient.similarityLevel(handler.peerClient);
1421
+ if (score > bestScore) {
1422
+ bestScore = score;
1423
+ bestHandler = handler;
1424
+ }
1425
+ if (score > bestOwnedScore && handler.ownsLiveConnectionFor(originClient)) {
1426
+ bestOwnedScore = score;
1427
+ bestOwnedHandler = handler;
1428
+ }
1429
+ }
1430
+ if (bestOwnedHandler != null && bestOwnedScore > 0) return bestOwnedHandler;
1431
+ return bestScore > 0 ? bestHandler : void 0;
1432
+ }
1433
+ resetRuntime() {
1434
+ for (const ra of this._pendingRunningActions.values()) ra._abort(err_nice_action.fromId("runtime_reset"));
1435
+ for (const handler of this._registeredPeerHandlers) handler.clearTransportCache();
1436
+ }
1437
+ _trySetupReturnDispatch(runningAction) {
1438
+ if (runningAction.context.schema.responseMode === "none") return;
1439
+ const originClient = runningAction.context.originClient;
1440
+ if (originClient.envId === "_unset_" || originClient.isSameFor(this._coordinate).id) return;
1441
+ runningAction.addUpdateListeners([(update) => {
1442
+ if (update.type === "finished" && update.finishType === "success") this.getReturnHandlerForOrigin(originClient)?.sendReturnPayload(update.response, { targetLocalRuntime: this }).catch(() => {});
1443
+ }]);
1444
+ }
1445
+ };
1446
+ const runtimeState = {
1447
+ defaultLocalRuntime: void 0,
1448
+ assumedRuntimeInfo: void 0
1449
+ };
1450
+ function getDefaultActionRuntime() {
1451
+ if (runtimeState.assumedRuntimeInfo == null) runtimeState.assumedRuntimeInfo = getAssumedRuntimeInfo();
1452
+ if (runtimeState.defaultLocalRuntime == null) runtimeState.defaultLocalRuntime = new ActionRuntime(RuntimeCoordinate.unknown.specify({ perId: `${runtimeState.assumedRuntimeInfo?.runtimeName ?? "unknown"}-runtime` }));
1453
+ return runtimeState.defaultLocalRuntime;
1454
+ }
1455
+ //#endregion
1456
+ //#region src/ActionRuntime/Handler/Local/ActionLocalHandler.ts
1457
+ var ActionLocalHandler = class extends ActionHandler {
1458
+ handlerType = "local";
1459
+ actionRouter = new ActionRouter({
1460
+ contextType: "handler_route",
1461
+ handler: this
1462
+ });
1463
+ constructor() {
1464
+ super();
1465
+ }
1466
+ /**
1467
+ * Register a handler for all actions in a domain.
1468
+ * Receives the full primed action — use `matchAction()` to narrow to a specific action id.
1469
+ * Useful for forwarding all domain actions to a remote endpoint.
1470
+ * Lower priority than `forAction`.
1471
+ */
1472
+ forDomain(domain, handler) {
1473
+ this.actionRouter.forDomain(domain, handler);
1474
+ return this;
1475
+ }
1476
+ /**
1477
+ * Register a handler for a base action instance. Takes priority over domain-wide handlers.
1478
+ * Receives the full primed action with narrowed input type.
1479
+ * Useful for handling specific actions locally while forwarding the rest of the domain. For example, a local "ping" action that checks connectivity without needing a round trip.
1480
+ */
1481
+ forAction(action, handler) {
1482
+ this.actionRouter.forAction(action, handler);
1483
+ return this;
1484
+ }
1485
+ /**
1486
+ * Register a handler for multiple action IDs (first-match-wins among cases).
1487
+ * Receives the full primed action narrowed to the union of those IDs.
1488
+ * Use `act.coreAction.id` to branch on which action was dispatched.
1489
+ */
1490
+ forActionIds(domain, ids, handler) {
1491
+ this.actionRouter.forActionIds(domain, ids, handler);
1492
+ return this;
1493
+ }
1494
+ /**
1495
+ * Register per-action handlers for a domain using a single map, without needing
1496
+ * separate `forAction` calls. Unregistered action IDs are unaffected.
1497
+ *
1498
+ * @example
1499
+ * ```ts
1500
+ * handler.forDomainActionCases(userDomain, {
1501
+ * getUser: (primed) => db.getUser(primed.input.userId),
1502
+ * deleteUser: (primed) => db.deleteUser(primed.input.userId),
1503
+ * });
1504
+ * ```
1505
+ */
1506
+ forDomainActionCases(domain, cases) {
1507
+ this.actionRouter.forDomainActionCases(domain, cases);
1508
+ return this;
1509
+ }
1510
+ async handleActionRequest(action, config) {
1511
+ const targetLocalRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();
1512
+ const handler = this.actionRouter.getRouteDataForActionOrThrow(action, { targetLocalRuntime });
1513
+ action.context.addRouteItem({
1514
+ runtime: targetLocalRuntime.coordinate,
1515
+ handler: this.toHandlerRouteItem(),
1516
+ time: Date.now()
1517
+ });
1518
+ const runningAction = new RunningAction({
1519
+ context: action.context,
1520
+ request: action,
1521
+ parentCuid: peekHandlerCuid(),
1522
+ callSite: action._callSite ?? (/* @__PURE__ */ new Error()).stack
1523
+ });
1524
+ this._handleRunningAction(handler, runningAction).catch((err) => {
1525
+ if (err instanceof NiceError) runningAction._completeWithResult(action.errorResult(err));
1526
+ else if (isNiceErrorObject(err)) runningAction._completeWithResult(action.errorResult(castNiceError(err)));
1527
+ else runningAction._abort(err);
1528
+ });
1529
+ return runningAction;
1530
+ }
1531
+ async _handleRunningAction(handler, runningAction) {
1532
+ const state = runningAction.state;
1533
+ if (state.result != null) return;
1534
+ await Promise.resolve();
1535
+ pushHandlerCuid(runningAction.cuid);
1536
+ try {
1537
+ const rawResult = await handler(state.request);
1538
+ let result;
1539
+ if (rawResult instanceof ActionPayload_Result) result = rawResult;
1540
+ else if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) result = this.actionRouter.domainManager.getActionDomainOrThrow(state.request).hydrateResultPayload(rawResult);
1541
+ else result = state.request.successResult(rawResult);
1542
+ runningAction._completeWithResult(result);
1543
+ } finally {
1544
+ popHandlerCuid();
1545
+ }
1546
+ }
1547
+ async handlePayloadWireOrThrow(wire, config) {
1548
+ const hydratedAction = this.actionRouter.domainManager.hydrateActionPayload(wire);
1549
+ if (!(hydratedAction instanceof ActionPayload_Request)) throw err_nice_action.fromId("wire_action_not_payload", {
1550
+ domain: hydratedAction.domain,
1551
+ actionId: hydratedAction.id,
1552
+ actionState: hydratedAction.type ?? hydratedAction.form
1553
+ });
1554
+ return await this.handleActionRequest(hydratedAction, config);
1555
+ }
1556
+ toJsonObject() {
1557
+ return { type: this.handlerType };
1558
+ }
1559
+ toHandlerRouteItem() {
1560
+ return { type: this.handlerType };
1561
+ }
1562
+ };
1563
+ const createLocalHandler = () => {
1564
+ return new ActionLocalHandler();
1565
+ };
1566
+ //#endregion
1567
+ //#region src/ActionRuntime/Transport/crypto/actionHandshake.ts
1568
+ /**
1569
+ * Authenticated handshake for the WebSocket channel. Run once per connection, before any action
1570
+ * frames flow, it:
1571
+ * - exchanges each side's {@link RuntimeCoordinate} + public keys,
1572
+ * - checks both ends share the same wire dictionary version (closes the positional-dictionary footgun),
1573
+ * - has the client prove control of its verify (Ed25519) key by signing a fresh challenge that binds
1574
+ * both nonces, both identities, the dictionary version, the level, and every exchanged public key,
1575
+ * - establishes a `ClientCryptoKeyLink` link on both sides (so the server can verify the signature and,
1576
+ * for the `encrypted` level, both can derive a shared AES-GCM key with the verify keys folded in).
1577
+ *
1578
+ * This module is transport-agnostic: it produces/consumes message objects. The transport + server
1579
+ * handler drive the I/O and the connection phase (Step 4). Keep `none`-level connections from ever
1580
+ * reaching here — they skip the handshake entirely.
1581
+ */
1582
+ const HANDSHAKE_PROTOCOL = "nice-ws-hs/1";
1583
+ /** How much the channel protects after the handshake — chosen by the consumer (perf vs security). */
1584
+ let ESecurityLevel = /* @__PURE__ */ function(ESecurityLevel) {
1585
+ /** No handshake; identity is self-asserted (fastest, dev / trusted networks). */
1586
+ ESecurityLevel["none"] = "none";
1587
+ /** Handshake authenticates identity (sign/verify + key pin); frames stay plaintext over TLS. */
1588
+ ESecurityLevel["authenticated"] = "authenticated";
1589
+ /** Authenticated handshake + every frame AES-GCM encrypted with the derived shared key. */
1590
+ ESecurityLevel["encrypted"] = "encrypted";
1591
+ return ESecurityLevel;
1592
+ }({});
1593
+ let EHandshakeMessageType = /* @__PURE__ */ function(EHandshakeMessageType) {
1594
+ EHandshakeMessageType["hello"] = "hello";
1595
+ EHandshakeMessageType["welcome"] = "welcome";
1596
+ EHandshakeMessageType["prove"] = "prove";
1597
+ EHandshakeMessageType["accept"] = "accept";
1598
+ EHandshakeMessageType["reject"] = "reject";
1599
+ return EHandshakeMessageType;
1600
+ }({});
1601
+ const vEd25519Raw = v.custom((val) => typeof val === "string" && val.startsWith("ed25519::raw_base64::"));
1602
+ const vX25519Raw = v.custom((val) => typeof val === "string" && val.startsWith("x25519::raw_base64::"));
1603
+ const vCoordinate = v.object({
1604
+ envId: v.string(),
1605
+ perId: v.optional(v.string()),
1606
+ insId: v.optional(v.string())
1607
+ });
1608
+ const vSecurityLevel = v.picklist([
1609
+ "none",
1610
+ "authenticated",
1611
+ "encrypted"
1612
+ ]);
1613
+ const vHsHello = v.object({
1614
+ t: v.literal("hello"),
1615
+ protocol: v.string(),
1616
+ securityLevel: vSecurityLevel,
1617
+ dictionaryVersion: v.string(),
1618
+ client: vCoordinate,
1619
+ clientNonce: v.string(),
1620
+ verifyPublicKey: vEd25519Raw,
1621
+ exchangePublicKey: v.optional(vX25519Raw)
1622
+ });
1623
+ const vHsWelcome = v.object({
1624
+ t: v.literal("welcome"),
1625
+ securityLevel: vSecurityLevel,
1626
+ dictionaryVersion: v.string(),
1627
+ server: vCoordinate,
1628
+ serverNonce: v.string(),
1629
+ verifyPublicKey: vEd25519Raw,
1630
+ exchangePublicKey: v.optional(vX25519Raw)
1631
+ });
1632
+ const vHsProve = v.object({
1633
+ t: v.literal("prove"),
1634
+ signatureBase64: v.string()
1635
+ });
1636
+ const vHsAccept = v.object({
1637
+ t: v.literal("accept"),
1638
+ signatureBase64: v.optional(v.string())
1639
+ });
1640
+ const vHsReject = v.object({
1641
+ t: v.literal("reject"),
1642
+ reason: v.string()
1643
+ });
1644
+ const vHandshakeMessage = v.variant("t", [
1645
+ vHsHello,
1646
+ vHsWelcome,
1647
+ vHsProve,
1648
+ vHsAccept,
1649
+ vHsReject
1650
+ ]);
1651
+ /** Serialize a handshake message for the wire (handshake frames are JSON — they aren't the hot path). */
1652
+ function encodeHandshakeMessage(message) {
1653
+ return JSON.stringify(message);
1654
+ }
1655
+ /** Parse + structurally validate an incoming handshake frame; `undefined` if it isn't one. */
1656
+ function decodeHandshakeMessage(raw) {
1657
+ let parsed;
1658
+ try {
1659
+ parsed = JSON.parse(raw);
1660
+ } catch {
1661
+ return;
1662
+ }
1663
+ const result = v.safeParse(vHandshakeMessage, parsed);
1664
+ return result.success ? result.output : void 0;
1665
+ }
1666
+ /** Stable link id for a runtime coordinate — the key both the crypto link and the connection use. */
1667
+ function runtimeLinkId(coordinate) {
1668
+ return `runtime::${new RuntimeCoordinate(coordinate).stringId}`;
1669
+ }
1670
+ function coordId(coordinate) {
1671
+ return new RuntimeCoordinate(coordinate).stringId;
1672
+ }
1673
+ function sessionSalt(clientNonce, serverNonce) {
1674
+ return `${clientNonce}::${serverNonce}`;
1675
+ }
1676
+ function handshakeInfo(dictionaryVersion) {
1677
+ return `${HANDSHAKE_PROTOCOL}::${dictionaryVersion}`;
1678
+ }
1679
+ /**
1680
+ * The exact string both sides sign/verify. JSON-encoded ordered array so field boundaries are
1681
+ * unambiguous; binds identities, nonces (freshness), version, level, and all exchanged public keys
1682
+ * (authenticating the keys via the signature, complementing `bindVerifyKeysIntoDerivation`).
1683
+ */
1684
+ function buildHandshakeChallenge(parts) {
1685
+ return JSON.stringify([
1686
+ HANDSHAKE_PROTOCOL,
1687
+ parts.securityLevel,
1688
+ parts.dictionaryVersion,
1689
+ parts.clientCoordId,
1690
+ parts.serverCoordId,
1691
+ parts.clientNonce,
1692
+ parts.serverNonce,
1693
+ parts.clientVerifyKey,
1694
+ parts.serverVerifyKey,
1695
+ parts.clientExchangeKey ?? "_",
1696
+ parts.serverExchangeKey ?? "_"
1697
+ ]);
1698
+ }
1699
+ function reject(reason) {
1700
+ return {
1701
+ t: "reject",
1702
+ reason
1703
+ };
1704
+ }
1705
+ function tofuPinKey(client) {
1706
+ return `${client.envId}::${client.perId ?? client.insId ?? "_"}`;
1707
+ }
1708
+ /**
1709
+ * In-memory trust-on-first-use resolver: trusts (and pins) the first verify key seen for a client
1710
+ * identity, then rejects a different key for that identity. The default; replace with a storage-backed
1711
+ * resolver for cross-restart pinning (see Step 5).
1712
+ */
1713
+ function createInMemoryTofuVerifyKeyResolver() {
1714
+ const pinned = /* @__PURE__ */ new Map();
1715
+ return { async resolve({ client, verifyPublicKey }) {
1716
+ const key = tofuPinKey(client);
1717
+ const existing = pinned.get(key);
1718
+ if (existing == null) {
1719
+ pinned.set(key, verifyPublicKey);
1720
+ return { trusted: true };
1721
+ }
1722
+ if (existing === verifyPublicKey) return { trusted: true };
1723
+ return {
1724
+ trusted: false,
1725
+ reason: "verify key changed for client identity (pin mismatch)"
1726
+ };
1727
+ } };
1728
+ }
1729
+ /**
1730
+ * Storage-backed trust-on-first-use resolver: pins survive process restarts / Durable Object eviction
1731
+ * (e.g. back it with `createDurableObjectStorageAdapter`). Same policy as the in-memory variant — trust
1732
+ * + pin the first verify key per client identity, reject a different one thereafter.
1733
+ */
1734
+ function createStorageTofuVerifyKeyResolver(storageAdapter) {
1735
+ const storage = createTypedStorage({ storageAdapter });
1736
+ return { async resolve({ client, verifyPublicKey }) {
1737
+ const key = tofuPinKey(client);
1738
+ const existing = (await storage.getJson("pins"))?.[key];
1739
+ if (existing == null) {
1740
+ await storage.updateJsonWithDef("pins", {}, (current) => ({
1741
+ ...current,
1742
+ [key]: verifyPublicKey
1743
+ }));
1744
+ return { trusted: true };
1745
+ }
1746
+ if (existing === verifyPublicKey) return { trusted: true };
1747
+ return {
1748
+ trusted: false,
1749
+ reason: "verify key changed for client identity (pin mismatch)"
1750
+ };
1751
+ } };
1752
+ }
1753
+ function createClientHandshake(config) {
1754
+ const { link, localCoordinate, dictionaryVersion, securityLevel } = config;
1755
+ const wantsEncryption = securityLevel === "encrypted";
1756
+ const clientNonce = nanoid();
1757
+ let pending;
1758
+ return {
1759
+ async createHello() {
1760
+ return {
1761
+ t: "hello",
1762
+ protocol: HANDSHAKE_PROTOCOL,
1763
+ securityLevel,
1764
+ dictionaryVersion,
1765
+ client: localCoordinate,
1766
+ clientNonce,
1767
+ verifyPublicKey: await link.getLocalVerifyPublicKey(),
1768
+ exchangePublicKey: wantsEncryption ? await link.getLocalExchangePublicKey() : void 0
1769
+ };
1770
+ },
1771
+ async onWelcome(welcome) {
1772
+ if (welcome.dictionaryVersion !== dictionaryVersion) throw new Error("[ws-handshake] server dictionary version mismatch");
1773
+ if (welcome.securityLevel !== securityLevel) throw new Error("[ws-handshake] server security level mismatch");
1774
+ if (wantsEncryption && welcome.exchangePublicKey == null) throw new Error("[ws-handshake] server did not provide an exchange key for encryption");
1775
+ const linkedServerId = runtimeLinkId(welcome.server);
1776
+ await link.linkClient({
1777
+ linkedClientId: linkedServerId,
1778
+ verifyPublicKey: welcome.verifyPublicKey,
1779
+ ...wantsEncryption ? {
1780
+ exchangePublicKey: welcome.exchangePublicKey,
1781
+ saltString: sessionSalt(clientNonce, welcome.serverNonce),
1782
+ infoString: handshakeInfo(dictionaryVersion),
1783
+ bindVerifyKeysIntoDerivation: true
1784
+ } : {}
1785
+ });
1786
+ const challenge = buildHandshakeChallenge({
1787
+ securityLevel,
1788
+ dictionaryVersion,
1789
+ clientCoordId: coordId(localCoordinate),
1790
+ serverCoordId: coordId(welcome.server),
1791
+ clientNonce,
1792
+ serverNonce: welcome.serverNonce,
1793
+ clientVerifyKey: await link.getLocalVerifyPublicKey(),
1794
+ serverVerifyKey: welcome.verifyPublicKey,
1795
+ clientExchangeKey: wantsEncryption ? await link.getLocalExchangePublicKey() : void 0,
1796
+ serverExchangeKey: welcome.exchangePublicKey
1797
+ });
1798
+ pending = {
1799
+ linkedServerId,
1800
+ server: welcome.server,
1801
+ challenge
1802
+ };
1803
+ return {
1804
+ t: "prove",
1805
+ signatureBase64: (await link.signChallenge([challenge])).signatureBase64
1806
+ };
1807
+ },
1808
+ async onAccept(accept) {
1809
+ if (pending == null) throw new Error("[ws-handshake] accept before welcome");
1810
+ if (accept.signatureBase64 != null) {
1811
+ if (!await link.verifyChallengeFromLinkedClient({
1812
+ linkedClientId: pending.linkedServerId,
1813
+ challenge: pending.challenge,
1814
+ signatureBase64: accept.signatureBase64
1815
+ })) throw new Error("[ws-handshake] server signature invalid");
1816
+ }
1817
+ return {
1818
+ linkedClientId: pending.linkedServerId,
1819
+ remote: pending.server,
1820
+ securityLevel
1821
+ };
1822
+ }
1823
+ };
1824
+ }
1825
+ function createServerHandshake(config) {
1826
+ const { link, localCoordinate, dictionaryVersion } = config;
1827
+ const allowedLevels = Array.isArray(config.securityLevel) ? config.securityLevel : [config.securityLevel];
1828
+ const verifyKeyResolver = config.verifyKeyResolver ?? createInMemoryTofuVerifyKeyResolver();
1829
+ const serverNonce = nanoid();
1830
+ let pending;
1831
+ let result;
1832
+ return {
1833
+ async onHello(hello) {
1834
+ if (hello.protocol !== HANDSHAKE_PROTOCOL) return reject("unsupported handshake protocol");
1835
+ if (hello.dictionaryVersion !== dictionaryVersion) return reject("dictionary version mismatch");
1836
+ const negotiatedLevel = hello.securityLevel;
1837
+ if (negotiatedLevel === "none" || !allowedLevels.includes(negotiatedLevel)) return reject("security level not allowed");
1838
+ const wantsEncryption = negotiatedLevel === "encrypted";
1839
+ if (wantsEncryption && hello.exchangePublicKey == null) return reject("missing exchange key for encryption");
1840
+ const linkedClientId = runtimeLinkId(hello.client);
1841
+ await link.linkClient({
1842
+ linkedClientId,
1843
+ verifyPublicKey: hello.verifyPublicKey,
1844
+ ...wantsEncryption ? {
1845
+ exchangePublicKey: hello.exchangePublicKey,
1846
+ saltString: sessionSalt(hello.clientNonce, serverNonce),
1847
+ infoString: handshakeInfo(dictionaryVersion),
1848
+ bindVerifyKeysIntoDerivation: true
1849
+ } : {}
1850
+ });
1851
+ const serverVerifyKey = await link.getLocalVerifyPublicKey();
1852
+ const serverExchangeKey = wantsEncryption ? await link.getLocalExchangePublicKey() : void 0;
1853
+ const keyMaterial = wantsEncryption && hello.exchangePublicKey != null ? {
1854
+ verifyPublicKey: hello.verifyPublicKey,
1855
+ exchangePublicKey: hello.exchangePublicKey,
1856
+ saltString: sessionSalt(hello.clientNonce, serverNonce),
1857
+ infoString: handshakeInfo(dictionaryVersion),
1858
+ bindVerifyKeysIntoDerivation: true
1859
+ } : void 0;
1860
+ pending = {
1861
+ client: hello.client,
1862
+ linkedClientId,
1863
+ clientVerifyKey: hello.verifyPublicKey,
1864
+ negotiatedLevel,
1865
+ keyMaterial,
1866
+ challenge: buildHandshakeChallenge({
1867
+ securityLevel: negotiatedLevel,
1868
+ dictionaryVersion,
1869
+ clientCoordId: coordId(hello.client),
1870
+ serverCoordId: coordId(localCoordinate),
1871
+ clientNonce: hello.clientNonce,
1872
+ serverNonce,
1873
+ clientVerifyKey: hello.verifyPublicKey,
1874
+ serverVerifyKey,
1875
+ clientExchangeKey: hello.exchangePublicKey,
1876
+ serverExchangeKey
1877
+ })
1878
+ };
1879
+ return {
1880
+ t: "welcome",
1881
+ securityLevel: negotiatedLevel,
1882
+ dictionaryVersion,
1883
+ server: localCoordinate,
1884
+ serverNonce,
1885
+ verifyPublicKey: serverVerifyKey,
1886
+ exchangePublicKey: serverExchangeKey
1887
+ };
1888
+ },
1889
+ async onProve(prove) {
1890
+ if (pending == null) return reject("prove before hello");
1891
+ if (!await link.verifyChallengeFromLinkedClient({
1892
+ linkedClientId: pending.linkedClientId,
1893
+ challenge: pending.challenge,
1894
+ signatureBase64: prove.signatureBase64
1895
+ })) return reject("invalid client signature");
1896
+ const trust = await verifyKeyResolver.resolve({
1897
+ client: pending.client,
1898
+ verifyPublicKey: pending.clientVerifyKey
1899
+ });
1900
+ if (!trust.trusted) return reject(trust.reason ?? "client verify key not trusted");
1901
+ result = {
1902
+ linkedClientId: pending.linkedClientId,
1903
+ remote: pending.client,
1904
+ securityLevel: pending.negotiatedLevel,
1905
+ encryptionKeyMaterial: pending.keyMaterial
1906
+ };
1907
+ return {
1908
+ t: "accept",
1909
+ signatureBase64: (await link.signChallenge([pending.challenge])).signatureBase64
1910
+ };
1911
+ },
1912
+ /** The completed handshake result once `onProve` has accepted, else `undefined`. */
1913
+ getResult() {
1914
+ return result;
1915
+ }
1916
+ };
1917
+ }
1918
+ //#endregion
1919
+ //#region src/utils/decodeActionFrame.ts
1920
+ /**
1921
+ * Decode a single inbound channel frame (text or binary) into validated action wire JSON, or
1922
+ * `undefined` if it isn't a recognisable action payload.
1923
+ *
1924
+ * Shared by the WebSocket transport's message listener and the server-side `AcceptorHandler` so
1925
+ * both decode identically: a binary `decoder.incoming` (e.g. msgpackr) takes precedence, and plain
1926
+ * text frames fall back to JSON — keeping binary and JSON clients interoperable on one channel.
1927
+ */
1928
+ function decodeActionFrame(frame, decoder) {
1929
+ const decoded = decoder?.incoming?.(frame) ?? (typeof frame === "string" ? parseJsonActionFrame(frame) : void 0);
1930
+ return decoded != null && isActionPayload_Any_JsonObject(decoded) ? decoded : void 0;
1931
+ }
1932
+ function parseJsonActionFrame(message) {
1933
+ try {
1934
+ const json = JSON.parse(message);
1935
+ return isActionPayload_Any_JsonObject(json) ? json : void 0;
1936
+ } catch {
1937
+ return;
1938
+ }
1939
+ }
1940
+ //#endregion
1941
+ //#region src/ActionRuntime/Transport/crypto/actionFrameCrypto.ts
1942
+ const ENCRYPTED_ENVELOPE_LENGTH = 2;
1943
+ /**
1944
+ * Build the encrypt/decrypt transform for a connection whose handshake settled on the `encrypted`
1945
+ * level. Keyed by the link + `linkedClientId`, so it reuses the cached shared AES-GCM key.
1946
+ */
1947
+ function createActionFrameCrypto({ link, linkedClientId }) {
1948
+ return {
1949
+ async encryptFrame(frame) {
1950
+ const { nonce, ciphertext } = await link.encryptBytesForLinkedClient({
1951
+ linkedClientId,
1952
+ dataToEncrypt: frame
1953
+ });
1954
+ return pack([nonce, ciphertext]);
1955
+ },
1956
+ async decryptFrame(frame) {
1957
+ if (typeof frame === "string") throw new Error("[ws-crypto] expected an encrypted binary frame, received text");
1958
+ const envelope = unpack(frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame);
1959
+ if (!Array.isArray(envelope) || envelope.length !== ENCRYPTED_ENVELOPE_LENGTH) throw new Error("[ws-crypto] malformed encrypted frame envelope");
1960
+ const [nonce, ciphertext] = envelope;
1961
+ if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) throw new Error("[ws-crypto] malformed encrypted frame fields");
1962
+ return await link.decryptBytesFromLinkedClient({
1963
+ linkedClientId,
1964
+ dataToDecrypt: {
1965
+ nonce,
1966
+ ciphertext
1967
+ }
1968
+ });
1969
+ }
1970
+ };
1971
+ }
1972
+ //#endregion
1973
+ //#region src/ActionRuntime/Transport/crypto/frameBytes.ts
1974
+ /** Normalize any frame form to bytes (for the AES-GCM layer, which works on `Uint8Array`). */
1975
+ function toFrameBytes(frame) {
1976
+ if (typeof frame === "string") return new TextEncoder().encode(frame);
1977
+ if (frame instanceof ArrayBuffer) return new Uint8Array(frame);
1978
+ return frame;
1979
+ }
1980
+ //#endregion
1981
+ //#region src/ActionRuntime/Transport/SecureSession/frameCryptoPipe.ts
1982
+ function createFrameCryptoPipe(config) {
1983
+ const { write, isOpen, crypto, label = "link" } = config;
1984
+ let sendChain = Promise.resolve();
1985
+ const send = (frame) => {
1986
+ if (isOpen != null && !isOpen()) return;
1987
+ if (crypto == null) {
1988
+ write(frame);
1989
+ return;
1990
+ }
1991
+ const bytes = toFrameBytes(frame);
1992
+ sendChain = sendChain.then(() => crypto).then((c) => c.encryptFrame(bytes)).then((encrypted) => {
1993
+ if (isOpen == null || isOpen()) write(encrypted);
1994
+ }).catch((err) => console.error(`[${label}] failed to encrypt/send frame`, err));
1995
+ };
1996
+ const decryptIncoming = async (frame) => {
1997
+ if (crypto == null) return frame;
1998
+ try {
1999
+ return await (await crypto).decryptFrame(frame);
2000
+ } catch (err) {
2001
+ console.error(`[${label}] failed to decrypt incoming frame`, err);
2002
+ return;
2003
+ }
2004
+ };
2005
+ return {
2006
+ send,
2007
+ decryptIncoming
2008
+ };
2009
+ }
2010
+ //#endregion
2011
+ //#region src/ActionRuntime/Transport/SecureSession/acceptorSecureSession.ts
2012
+ /**
2013
+ * The acceptor (accept-in) counterpart to the connector's `establishLinkSession`: one connection's
2014
+ * secure session — the server-side handshake driving, the ordered frame crypto, and the per-connection
2015
+ * phase (undecided → plain | authenticated). The crypto itself (ordered encrypt-send / decrypt) lives in
2016
+ * the shared {@link createFrameCryptoPipe}, the same primitive the connector uses — so the secure logic
2017
+ * lives once for both link roles.
2018
+ *
2019
+ * The handler owns one of these per accepted connection and feeds it inbound frames via {@link receive};
2020
+ * identity binding, persistence, codec, and return routing stay in the handler (driven through the
2021
+ * config callbacks). Inbound processing is serialized per connection because the handshake and decryption
2022
+ * are async — this keeps handshake ordering and frame order intact.
2023
+ */
2024
+ var AcceptorSecureSession = class {
2025
+ config;
2026
+ _handshake;
2027
+ /** The ordered encrypt-send / decrypt pipe — present only for an `encrypted` connection. */
2028
+ _pipe;
2029
+ _authed = false;
2030
+ _plain = false;
2031
+ /** Serializes inbound processing (handshake + decryption are async). */
2032
+ _inboundChain = Promise.resolve();
2033
+ constructor(config) {
2034
+ this.config = config;
2035
+ }
2036
+ /** Feed one inbound frame. Serialized per connection; routes back through the config callbacks. */
2037
+ receive(frame) {
2038
+ this._inboundChain = this._inboundChain.then(() => this._receive(frame)).catch((err) => console.error("[ws-server] failed to process inbound frame", err));
2039
+ }
2040
+ async _receive(frame) {
2041
+ if (this._plain) {
2042
+ this.config.routePlain(frame);
2043
+ return;
2044
+ }
2045
+ if (!this._authed) {
2046
+ const message = typeof frame === "string" ? decodeHandshakeMessage(frame) : void 0;
2047
+ if (message == null) {
2048
+ if (this.config.noneAllowed) {
2049
+ this._plain = true;
2050
+ this.config.routePlain(frame);
2051
+ }
2052
+ return;
2053
+ }
2054
+ await this.config.link.initialize();
2055
+ if (this._handshake == null) this._handshake = createServerHandshake({
2056
+ link: this.config.link,
2057
+ localCoordinate: this.config.localCoordinate,
2058
+ dictionaryVersion: this.config.dictionaryVersion,
2059
+ securityLevel: this.config.securityLevel,
2060
+ verifyKeyResolver: this.config.verifyKeyResolver
2061
+ });
2062
+ if (message.t === "hello") this.config.send(encodeHandshakeMessage(await this._handshake.onHello(message)));
2063
+ else if (message.t === "prove") {
2064
+ const reply = await this._handshake.onProve(message);
2065
+ this.config.send(encodeHandshakeMessage(reply));
2066
+ const result = this._handshake.getResult();
2067
+ if (reply.t === "accept" && result != null) this._complete(result);
2068
+ }
2069
+ return;
2070
+ }
2071
+ const bytes = this._pipe != null ? await this._pipe.decryptIncoming(frame) : frame;
2072
+ if (bytes === void 0) return;
2073
+ this.config.routeAction(bytes);
2074
+ }
2075
+ _complete(result) {
2076
+ this._authed = true;
2077
+ this._handshake = void 0;
2078
+ if (result.securityLevel === "encrypted") this._pipe = this._buildPipe(createActionFrameCrypto({
2079
+ link: this.config.link,
2080
+ linkedClientId: result.linkedClientId
2081
+ }));
2082
+ this.config.onAuthenticated({
2083
+ client: new RuntimeCoordinate(result.remote),
2084
+ securityLevel: result.securityLevel,
2085
+ linkedClientId: result.linkedClientId,
2086
+ keyMaterial: result.encryptionKeyMaterial
2087
+ });
2088
+ }
2089
+ /**
2090
+ * Restore an already-authenticated session after eviction — no handshake. For an `encrypted`
2091
+ * connection the shared key is re-derived asynchronously (the acceptor re-links the client off its own
2092
+ * persisted identity); the pipe's crypto IS that promise, so the connection's first in/out frame
2093
+ * naturally waits for the key before encrypt/decrypt — no separate gate.
2094
+ */
2095
+ rehydrate(state) {
2096
+ this._authed = true;
2097
+ if (state.securityLevel !== "encrypted" || state.keyMaterial == null) return;
2098
+ const { link } = this.config;
2099
+ const { linkedClientId, keyMaterial } = state;
2100
+ const cryptoReady = link.initialize().then(() => link.linkClient({
2101
+ linkedClientId,
2102
+ verifyPublicKey: keyMaterial.verifyPublicKey,
2103
+ exchangePublicKey: keyMaterial.exchangePublicKey,
2104
+ saltString: keyMaterial.saltString,
2105
+ infoString: keyMaterial.infoString,
2106
+ bindVerifyKeysIntoDerivation: keyMaterial.bindVerifyKeysIntoDerivation
2107
+ })).then(() => createActionFrameCrypto({
2108
+ link,
2109
+ linkedClientId
2110
+ }));
2111
+ cryptoReady.catch((err) => console.error("[ws-server] failed to restore encrypted session", err));
2112
+ this._pipe = this._buildPipe(cryptoReady);
2113
+ }
2114
+ /** Send an outbound frame: through the encrypt pipe when encrypted, otherwise raw. */
2115
+ send(frame) {
2116
+ if (this._pipe != null) {
2117
+ this._pipe.send(frame);
2118
+ return;
2119
+ }
2120
+ this.config.send(frame);
2121
+ }
2122
+ _buildPipe(crypto) {
2123
+ return createFrameCryptoPipe({
2124
+ write: this.config.send,
2125
+ crypto,
2126
+ label: "ws-server"
2127
+ });
2128
+ }
2129
+ };
2130
+ //#endregion
2131
+ //#region src/ActionRuntime/Handler/PeerLink/Acceptor/AcceptorHandler.ts
2132
+ /**
2133
+ * Server-side handler for backends that accept many client connections over a single open channel
2134
+ * (WebSockets, Durable Objects, …). It is transport-agnostic: you feed it inbound frames with
2135
+ * {@link receive} and tell it how to write outbound frames via the `send` option.
2136
+ *
2137
+ * Add it alongside your local execution handler:
2138
+ * ```ts
2139
+ * const serverHandler = createAcceptorHandler({ clientEnv, formatMessage, send: (ws, f) => ws.send(f) });
2140
+ * runtime.addHandlers([localHandler, serverHandler]);
2141
+ * // per inbound message (e.g. a Durable Object's webSocketMessage):
2142
+ * serverHandler.receive(ws, message);
2143
+ * ```
2144
+ *
2145
+ * Inbound requests route to your local handler; the runtime's return dispatch then calls this
2146
+ * handler back (it is an external handler keyed to `clientEnv`) to send the result to the originating
2147
+ * connection. The handler keeps a per-connection identity registry so each result lands on the right
2148
+ * socket, and remembers each connection's encoding so binary and JSON clients can share the channel.
2149
+ *
2150
+ * It registers an empty action router, so it is never chosen to *execute* an inbound request — only
2151
+ * to ferry results/pushes back out.
2152
+ */
2153
+ var AcceptorHandler = class extends PeerLinkHandler {
2154
+ /** Accept-in over a live (duplex) connection registry — it pushes results/broadcasts to bound sockets. */
2155
+ canPush = true;
2156
+ _formatMessage;
2157
+ _createFormatMessage;
2158
+ _send;
2159
+ _runtime;
2160
+ _serverTimeout;
2161
+ _onConnectionBound;
2162
+ _security;
2163
+ /** Normalized accepted levels; whether `none` (plain) is allowed; whether any level needs a handshake. */
2164
+ _allowedLevels;
2165
+ _noneAllowed;
2166
+ _handshakeMode;
2167
+ _connByClient = /* @__PURE__ */ new Map();
2168
+ _clientByConn = /* @__PURE__ */ new Map();
2169
+ _connEncoding = /* @__PURE__ */ new Map();
2170
+ _codecByConn = /* @__PURE__ */ new Map();
2171
+ _sessionByConn = /* @__PURE__ */ new Map();
2172
+ constructor(options) {
2173
+ super(options.clientEnv);
2174
+ this._formatMessage = options.formatMessage;
2175
+ this._createFormatMessage = options.createFormatMessage;
2176
+ this._send = options.send;
2177
+ this._runtime = options.runtime;
2178
+ this._serverTimeout = options.defaultTimeout ?? 1e4;
2179
+ this._onConnectionBound = options.onConnectionBound;
2180
+ this._security = options.security;
2181
+ this._allowedLevels = options.security == null ? [] : Array.isArray(options.security.securityLevel) ? options.security.securityLevel : [options.security.securityLevel];
2182
+ this._noneAllowed = this._allowedLevels.includes("none");
2183
+ this._handshakeMode = this._allowedLevels.some((level) => level !== "none");
2184
+ }
2185
+ /**
2186
+ * The codec for a connection: a per-connection session (cached) when a factory was provided, else
2187
+ * the single shared `formatMessage`.
2188
+ */
2189
+ _codecFor(connection) {
2190
+ if (this._createFormatMessage != null) {
2191
+ let codec = this._codecByConn.get(connection);
2192
+ if (codec == null) {
2193
+ codec = this._createFormatMessage();
2194
+ this._codecByConn.set(connection, codec);
2195
+ }
2196
+ return codec;
2197
+ }
2198
+ if (this._formatMessage != null) return this._formatMessage;
2199
+ throw err_nice_transport.fromId("not_found", { actionId: "server-handler-codec (provide formatMessage or createFormatMessage)" });
2200
+ }
2201
+ /**
2202
+ * Register (or replace) the connection-bound persistence callback after construction. Used by
2203
+ * lifecycle helpers like {@link createHibernatableWsServerAdapter} so persistence and replay are
2204
+ * owned by one place instead of being split across the constructor options.
2205
+ */
2206
+ setOnConnectionBound(onConnectionBound) {
2207
+ this._onConnectionBound = onConnectionBound;
2208
+ }
2209
+ /**
2210
+ * Feed one inbound frame from a connection into the runtime. Decodes text or binary, binds the
2211
+ * connection to the requesting client's identity, then routes it (requests execute locally;
2212
+ * results/progress resolve pending server-initiated actions).
2213
+ */
2214
+ receive(connection, frame) {
2215
+ const security = this._security;
2216
+ if (security == null || !this._handshakeMode) {
2217
+ this._receivePlain(connection, frame);
2218
+ return;
2219
+ }
2220
+ this._sessionFor(connection, security).receive(frame);
2221
+ }
2222
+ _receivePlain(connection, frame) {
2223
+ const wire = decodeActionFrame(frame, this._codecFor(connection));
2224
+ if (wire == null) return;
2225
+ const encoding = typeof frame === "string" ? "json" : "binary";
2226
+ this._connEncoding.set(connection, encoding);
2227
+ if (wire.type === "request") this._resolveRequestIdentity(connection, wire, encoding);
2228
+ this._emitIncoming(wire);
2229
+ }
2230
+ /**
2231
+ * The secure session for a connection (built lazily on its first secure-mode frame), with the
2232
+ * handler-owned effects — raw send, identity binding + persistence, and inbound routing — wired in as
2233
+ * callbacks. The session owns all crypto/handshake/chain state; the handler keeps only the registry.
2234
+ */
2235
+ _sessionFor(connection, security) {
2236
+ let session = this._sessionByConn.get(connection);
2237
+ if (session == null) {
2238
+ session = new AcceptorSecureSession({
2239
+ link: security.link,
2240
+ localCoordinate: security.localCoordinate,
2241
+ dictionaryVersion: security.dictionaryVersion,
2242
+ securityLevel: security.securityLevel,
2243
+ verifyKeyResolver: security.verifyKeyResolver,
2244
+ noneAllowed: this._noneAllowed,
2245
+ send: (frame) => this._send(connection, frame),
2246
+ onAuthenticated: (auth) => this._onConnectionAuthenticated(connection, auth),
2247
+ routePlain: (frame) => this._receivePlain(connection, frame),
2248
+ routeAction: (bytes) => this._routeAuthedActionBytes(connection, bytes)
2249
+ });
2250
+ this._sessionByConn.set(connection, session);
2251
+ }
2252
+ return session;
2253
+ }
2254
+ /** Bind + persist a connection's authenticated identity once its handshake completes. */
2255
+ _onConnectionAuthenticated(connection, auth) {
2256
+ this._bindConnection(connection, auth.client);
2257
+ this._connEncoding.set(connection, "binary");
2258
+ this._onConnectionBound?.(connection, {
2259
+ client: auth.client.toJsonObject(),
2260
+ encoding: "binary",
2261
+ secure: {
2262
+ securityLevel: auth.securityLevel,
2263
+ linkedClientId: auth.linkedClientId,
2264
+ keyMaterial: auth.keyMaterial
2265
+ }
2266
+ });
2267
+ }
2268
+ /** Decode a decrypted authenticated frame, inject the *authenticated* identity, and route it. */
2269
+ _routeAuthedActionBytes(connection, bytes) {
2270
+ const wire = decodeActionFrame(bytes, this._codecFor(connection));
2271
+ if (wire == null) return;
2272
+ if (wire.type === "request") {
2273
+ const bound = this._clientByConn.get(connection);
2274
+ if (bound != null) wire.context.originClient = bound.toJsonObject();
2275
+ }
2276
+ this._emitIncoming(wire);
2277
+ }
2278
+ /**
2279
+ * Ensure an inbound request carries the client's identity and that this connection is bound to it,
2280
+ * so its result can be routed back. A session codec omits `originClient` after the first request, so
2281
+ * when it's missing we restore it from the (possibly rehydrated) binding instead. (Plain mode only;
2282
+ * secure mode binds the authenticated coordinate at handshake time.)
2283
+ */
2284
+ _resolveRequestIdentity(connection, wire, encoding) {
2285
+ const wireOrigin = wire.context.originClient;
2286
+ if (wireOrigin != null && wireOrigin.envId !== "_unset_") {
2287
+ const clientCoord = new RuntimeCoordinate(wireOrigin);
2288
+ const isNewBinding = this._clientByConn.get(connection)?.stringId !== clientCoord.stringId;
2289
+ this._bindConnection(connection, clientCoord);
2290
+ if (isNewBinding) this._onConnectionBound?.(connection, {
2291
+ client: clientCoord.toJsonObject(),
2292
+ encoding
2293
+ });
2294
+ return;
2295
+ }
2296
+ const bound = this._clientByConn.get(connection);
2297
+ if (bound != null) wire.context.originClient = bound.toJsonObject();
2298
+ }
2299
+ /**
2300
+ * Restore a connection→client binding without an inbound frame — for transports that resume after
2301
+ * eviction. Pair it with the {@link IAcceptorHandlerOptions.onConnectionBound} hook: persist
2302
+ * the binding there, then replay each live connection here when the channel comes back (e.g. a
2303
+ * Durable Object iterating `ctx.getWebSockets()` as it wakes from hibernation).
2304
+ */
2305
+ rehydrateConnection(connection, binding) {
2306
+ this._bindConnection(connection, new RuntimeCoordinate(binding.client));
2307
+ this._connEncoding.set(connection, binding.encoding);
2308
+ const secure = binding.secure;
2309
+ const security = this._security;
2310
+ if (secure == null || security == null) return;
2311
+ this._sessionFor(connection, security).rehydrate(secure);
2312
+ }
2313
+ toJsonObject() {
2314
+ return {
2315
+ type: this.handlerType,
2316
+ client: this.peerClient
2317
+ };
2318
+ }
2319
+ toHandlerRouteItem() {
2320
+ return {
2321
+ type: this.handlerType,
2322
+ client: this.peerClient,
2323
+ transShape: "duplex",
2324
+ transOrd: 0
2325
+ };
2326
+ }
2327
+ /** Forget a connection (call on socket close) so stale entries don't misroute later results. */
2328
+ dropConnection(connection) {
2329
+ const coord = this._clientByConn.get(connection);
2330
+ if (coord != null && this._connByClient.get(coord.stringId) === connection) this._connByClient.delete(coord.stringId);
2331
+ this._clientByConn.delete(connection);
2332
+ this._connEncoding.delete(connection);
2333
+ this._codecByConn.delete(connection);
2334
+ this._sessionByConn.delete(connection);
2335
+ }
2336
+ /** Live connection for a client coordinate, if currently registered. */
2337
+ getConnectionForClient(client) {
2338
+ return this._connByClient.get(client.stringId);
2339
+ }
2340
+ /** This acceptor owns the origin's return path when it currently holds a live connection bound to it. */
2341
+ ownsLiveConnectionFor(origin) {
2342
+ return this._connByClient.has(origin.stringId);
2343
+ }
2344
+ /** Whether this acceptor currently tracks `connection` — used to pick the owning handler among several. */
2345
+ hasConnection(connection) {
2346
+ return this._clientByConn.has(connection);
2347
+ }
2348
+ /**
2349
+ * Send (and optionally await) a server-initiated action to a specific connected client. Pass the
2350
+ * connection token directly (e.g. the `ws`) or a client `RuntimeCoordinate` to look one up.
2351
+ */
2352
+ pushToClient(runtime, target, request, options) {
2353
+ const connection = this._resolveConnection(target);
2354
+ return this._dispatch(runtime, connection, request, options?.timeout);
2355
+ }
2356
+ /**
2357
+ * Build a local handler whose cases are connection-aware: each case receives the primed request and
2358
+ * the originating client's live connection (resolved from `originClient`), so handlers don't repeat
2359
+ * the `getConnectionForClient(action.context.originClient)` lookup. Cases may return raw output or
2360
+ * nothing, just like {@link ActionLocalHandler.forDomainActionCases}. Add the returned handler to the
2361
+ * runtime alongside this server handler:
2362
+ * ```ts
2363
+ * runtime.addHandlers([serverHandler.forConnectionDomainCases(domain, { … }), serverHandler]);
2364
+ * ```
2365
+ */
2366
+ forConnectionDomainCases(domain, cases) {
2367
+ return this.forConnectionDomainCasesMulti([domain], cases, (connection) => connection);
2368
+ }
2369
+ /**
2370
+ * Like {@link forConnectionDomainCases} but spanning several domains with one merged case map — used
2371
+ * by channel-derived wiring (`acceptChannelConnections` / `serveChannel`) where the channel's
2372
+ * `toAcceptor` domains are served together. Each domain takes only the cases whose ids it owns, so a
2373
+ * single map can cover several domains and unrelated ids are ignored.
2374
+ *
2375
+ * `mapContext` turns the resolved connection into whatever the case's second argument should be: the
2376
+ * raw connection for the low-level helper, or an enriched `IConnectionContext` for `serveChannel`. It's
2377
+ * called once per inbound action, after the originating connection is resolved.
2378
+ */
2379
+ forConnectionDomainCasesMulti(domains, cases, mapContext) {
2380
+ const handler = new ActionLocalHandler();
2381
+ for (const domain of domains) {
2382
+ const ownedIds = new Set(Object.keys(domain.actionsMap()));
2383
+ const wrapped = {};
2384
+ for (const id in cases) {
2385
+ if (!ownedIds.has(id)) continue;
2386
+ const caseFn = cases[id];
2387
+ if (caseFn == null) continue;
2388
+ wrapped[id] = (request) => {
2389
+ return caseFn(request, mapContext(this.getConnectionForClient(request.context.originClient), request));
2390
+ };
2391
+ }
2392
+ handler.forDomainActionCases(domain, wrapped);
2393
+ }
2394
+ return handler;
2395
+ }
2396
+ /**
2397
+ * Fan a server-initiated request out to every currently-bound connection. A fresh request is built
2398
+ * per connection (each push mutates its own action context) and dispatched fire-and-forget. Pass
2399
+ * `except` to skip the originating socket and `where` to filter by connection (e.g. read its
2400
+ * attachment for a role). Iterating bound connections (rather than every accepted socket) skips
2401
+ * sockets that are still mid-handshake and so can't yet receive a frame.
2402
+ */
2403
+ broadcast(makeRequest, options) {
2404
+ const runtime = options?.runtime ?? this._runtime;
2405
+ if (runtime == null) throw err_nice_transport.fromId("not_found", { actionId: "server-handler-runtime (construct with `runtime` or pass `options.runtime`)" });
2406
+ for (const connection of this._clientByConn.keys()) {
2407
+ if (options?.except != null && connection === options.except) continue;
2408
+ if (options?.where != null && !options.where(connection)) continue;
2409
+ try {
2410
+ this.pushToClient(runtime, connection, makeRequest(), { timeout: options?.timeout });
2411
+ } catch (error) {
2412
+ if (options?.onError != null) options.onError(error, connection);
2413
+ else console.error("[ws-server] broadcast push failed", error);
2414
+ }
2415
+ }
2416
+ }
2417
+ async sendReturnPayload(payload, config) {
2418
+ const connection = this._connByClient.get(payload.context.originClient.stringId);
2419
+ if (connection == null) return false;
2420
+ this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate);
2421
+ return true;
2422
+ }
2423
+ async handleActionRequest(action, config) {
2424
+ const runtime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();
2425
+ const connection = this._resolveSingleConnection();
2426
+ return this._dispatch(runtime, connection, action, config?.timeout);
2427
+ }
2428
+ _dispatch(runtime, connection, action, timeout) {
2429
+ const timeoutMs = timeout ?? this._serverTimeout;
2430
+ action.context._setOriginClient(runtime.coordinate);
2431
+ action.context.addRouteItem({
2432
+ runtime: runtime.coordinate,
2433
+ handler: this.toHandlerRouteItem(),
2434
+ time: Date.now()
2435
+ });
2436
+ const runningAction = new RunningAction({
2437
+ context: action.context,
2438
+ request: action,
2439
+ parentCuid: peekHandlerCuid(),
2440
+ callSite: action._callSite
2441
+ });
2442
+ runtime.registerRunningAction(runningAction);
2443
+ if (action.schema.responseMode === "none") {
2444
+ try {
2445
+ this._sendPayload(connection, action, runtime.coordinate);
2446
+ runningAction._completeWithResult(action.successResult(void 0));
2447
+ } catch (err) {
2448
+ runningAction._abort(err);
2449
+ }
2450
+ return runningAction;
2451
+ }
2452
+ const timeoutId = setTimeout(() => {
2453
+ runningAction._abort(err_nice_transport.fromId("timeout", { timeout: timeoutMs }));
2454
+ }, timeoutMs);
2455
+ runningAction.addUpdateListeners([(update) => {
2456
+ if (update.type === "finished") clearTimeout(timeoutId);
2457
+ }]);
2458
+ try {
2459
+ this._sendPayload(connection, action, runtime.coordinate);
2460
+ } catch (err) {
2461
+ runningAction._abort(err);
2462
+ }
2463
+ return runningAction;
2464
+ }
2465
+ _sendPayload(connection, payload, localClient) {
2466
+ const frame = (this._connEncoding.get(connection) ?? "binary") === "json" ? JSON.stringify(payload.toJsonObject()) : this._codecFor(connection).outgoing({
2467
+ action: payload,
2468
+ localClient,
2469
+ externalClient: this.peerClient
2470
+ });
2471
+ const session = this._sessionByConn.get(connection);
2472
+ if (session == null) {
2473
+ this._send(connection, frame);
2474
+ return;
2475
+ }
2476
+ session.send(frame);
2477
+ }
2478
+ _bindConnection(connection, client) {
2479
+ this._connByClient.set(client.stringId, connection);
2480
+ this._clientByConn.set(connection, client);
2481
+ }
2482
+ _resolveConnection(target) {
2483
+ if (target instanceof RuntimeCoordinate) {
2484
+ const connection = this._connByClient.get(target.stringId);
2485
+ if (connection == null) throw err_nice_transport.fromId("not_found", { actionId: target.stringId });
2486
+ return connection;
2487
+ }
2488
+ return target;
2489
+ }
2490
+ _resolveSingleConnection() {
2491
+ if (this._clientByConn.size !== 1) throw err_nice_transport.fromId("not_found", { actionId: "server-handler-target (use pushToClient with an explicit connection or client coordinate)" });
2492
+ return this._clientByConn.keys().next().value;
2493
+ }
2494
+ };
2495
+ const createAcceptorHandler = (options) => {
2496
+ return new AcceptorHandler(options);
2497
+ };
2498
+ //#endregion
2499
+ //#region src/ActionRuntime/Handler/PeerLink/Acceptor/createSecureActionServer.ts
2500
+ /** Default accepted set: negotiate per connection to whatever the client picks. */
2501
+ const DEFAULT_SERVER_SECURITY_LEVELS$1 = [
2502
+ "none",
2503
+ "authenticated",
2504
+ "encrypted"
2505
+ ];
2506
+ /**
2507
+ * Build an {@link AcceptorHandler} for the secure binary channel with the boilerplate folded in:
2508
+ * it creates the {@link ClientCryptoKeyLink} and the storage-backed TOFU resolver from a single
2509
+ * `storageAdapter`, installs the channel's per-connection codec, and assembles the `security` block
2510
+ * from the runtime coordinate + channel version (accepting all three levels by default).
2511
+ *
2512
+ * For a hibernatable transport (e.g. a Durable Object), pair it with
2513
+ * {@link createHibernatableWsServerAdapter} to wire persistence + replay.
2514
+ */
2515
+ function createSecureAcceptorHandler(options) {
2516
+ const link = options.link ?? new ClientCryptoKeyLink({ storageAdapter: options.storageAdapter });
2517
+ return new AcceptorHandler({
2518
+ clientEnv: options.clientEnv,
2519
+ createFormatMessage: options.channel.createCodec,
2520
+ send: options.send,
2521
+ runtime: options.runtime,
2522
+ defaultTimeout: options.defaultTimeout,
2523
+ security: {
2524
+ securityLevel: options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS$1,
2525
+ link,
2526
+ localCoordinate: options.runtime.coordinate.toJsonObject(),
2527
+ dictionaryVersion: options.channel.dictionaryVersion,
2528
+ verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(options.storageAdapter)
2529
+ }
2530
+ });
2531
+ }
2532
+ //#endregion
2533
+ //#region src/ActionRuntime/Transport/Carrier/Carrier.types.ts
2534
+ /**
2535
+ * Narrow a carrier source to the exchange shape via its `shape` discriminant — the one branch the
2536
+ * transport factories ({@link secureTransport}, {@link plainTransport}) use to pick the duplex vs
2537
+ * exchange transport. A duplex source carries no `shape`, so the `else` branch is the duplex one.
2538
+ */
2539
+ function isExchangeCarrierSource(carrier) {
2540
+ return "shape" in carrier && carrier.shape === "exchange";
2541
+ }
2542
+ //#endregion
2543
+ //#region src/ActionRuntime/Transport/Transport.ts
2544
+ /**
2545
+ * Reusable transport definition. Devs construct these (`secureTransport({ carrier: wsCarrier(url) })`,
2546
+ * `plainTransport({ carrier: httpCarrier(...) })`, …) and pass them to a
2547
+ * `ConnectorHandler`. A single
2548
+ * definition can be shared across multiple handlers — each handler builds its own live
2549
+ * {@link TransportConnection} via {@link TransportConnection._createConnection}.
2550
+ */
2551
+ var Transport = class {};
2552
+ //#endregion
2553
+ //#region src/ActionRuntime/Transport/SecureSession/exchangeProtocol.ts
2554
+ function encodeExchange(envelope) {
2555
+ return JSON.stringify(envelope);
2556
+ }
2557
+ function decodeExchangeRequest(raw) {
2558
+ return parse(raw);
2559
+ }
2560
+ function decodeExchangeReply(raw) {
2561
+ return parse(raw);
2562
+ }
2563
+ function parse(raw) {
2564
+ try {
2565
+ return JSON.parse(raw);
2566
+ } catch {
2567
+ return;
2568
+ }
2569
+ }
2570
+ function bytesToBase64(bytes) {
2571
+ let binary = "";
2572
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
2573
+ return btoa(binary);
2574
+ }
2575
+ function base64ToBytes(base64) {
2576
+ const binary = atob(base64);
2577
+ const bytes = new Uint8Array(binary.length);
2578
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2579
+ return bytes;
2580
+ }
2581
+ //#endregion
2582
+ //#region src/ActionRuntime/Transport/SecureSession/establishExchangeSession.ts
2583
+ const textEncoder$1 = new TextEncoder();
2584
+ const textDecoder$1 = new TextDecoder();
2585
+ /** Plain path (no handshake/token): every action rides a bare `act` envelope, plaintext both ways. */
2586
+ function finalizePlainExchangeMethods(ctx) {
2587
+ return buildExchangeMethods(ctx, {});
2588
+ }
2589
+ /** Secure path: run the handshake (two exchanges) once at bring-up, then reuse the token + crypto. */
2590
+ async function finalizeSecureExchangeMethods(ctx) {
2591
+ return buildExchangeMethods(ctx, await runConnectorExchangeHandshake(ctx.carrier, ctx.secure));
2592
+ }
2593
+ function buildExchangeMethods(ctx, state) {
2594
+ const sendActionData = (inputs) => {
2595
+ runExchange(ctx.carrier, state, inputs).catch((err) => inputs.runningAction._abort(err));
2596
+ };
2597
+ return {
2598
+ sendActionData,
2599
+ updateRunConfig: ctx.updateRunConfig
2600
+ };
2601
+ }
2602
+ async function runExchange(carrier, state, inputs) {
2603
+ const { action, runningAction, timeout } = inputs;
2604
+ const ac = new AbortController();
2605
+ let timedOut = false;
2606
+ const timeoutId = setTimeout(() => {
2607
+ timedOut = true;
2608
+ ac.abort();
2609
+ }, timeout);
2610
+ const unsubscribe = runningAction.addUpdateListeners([(update) => {
2611
+ if (update.type === "finished") {
2612
+ clearTimeout(timeoutId);
2613
+ ac.abort();
2614
+ }
2615
+ }]);
2616
+ try {
2617
+ const request = await buildRequestEnvelope(state, action);
2618
+ const replyRaw = await carrier.exchange(encodeExchange(request), { signal: ac.signal });
2619
+ if (action.type !== "request") return;
2620
+ const reply = decodeExchangeReply(asString(replyRaw));
2621
+ if (reply == null) throw err_nice_transport.fromId("invalid_action_response", { actionId: action.id });
2622
+ if (reply.k === "err") throw err_nice_transport.fromId("send_failed", {
2623
+ actionState: action.type,
2624
+ actionId: action.id,
2625
+ message: reply.message
2626
+ });
2627
+ const wire = await extractReplyWire(state, reply);
2628
+ if (wire == null || !isActionPayload_Result_JsonObject(wire)) throw err_nice_transport.fromId("invalid_action_response", { actionId: action.id });
2629
+ runningAction._completeWithResult(action._domain.hydrateResultPayload(wire));
2630
+ } catch (err) {
2631
+ if (timedOut) throw err_nice_transport.fromId("timeout", { timeout });
2632
+ throw err;
2633
+ } finally {
2634
+ clearTimeout(timeoutId);
2635
+ unsubscribe();
2636
+ }
2637
+ }
2638
+ async function buildRequestEnvelope(state, action) {
2639
+ const wire = action.toJsonObject();
2640
+ if (state.crypto != null) {
2641
+ const ciphertext = await state.crypto.encryptFrame(textEncoder$1.encode(JSON.stringify(wire)));
2642
+ return {
2643
+ k: "act",
2644
+ t: state.token,
2645
+ c: bytesToBase64(ciphertext)
2646
+ };
2647
+ }
2648
+ return {
2649
+ k: "act",
2650
+ t: state.token,
2651
+ w: wire
2652
+ };
2653
+ }
2654
+ async function extractReplyWire(state, reply) {
2655
+ if (reply.k !== "act") return void 0;
2656
+ if ("c" in reply) {
2657
+ if (state.crypto == null) return void 0;
2658
+ const plain = await state.crypto.decryptFrame(base64ToBytes(reply.c));
2659
+ return JSON.parse(textDecoder$1.decode(plain));
2660
+ }
2661
+ return reply.w;
2662
+ }
2663
+ async function runConnectorExchangeHandshake(carrier, secure) {
2664
+ await secure.link.initialize();
2665
+ const handshake = createClientHandshake({
2666
+ link: secure.link,
2667
+ localCoordinate: secure.localCoordinate,
2668
+ dictionaryVersion: secure.dictionaryVersion,
2669
+ securityLevel: secure.securityLevel
2670
+ });
2671
+ const hsid = nanoid();
2672
+ const hello = await handshake.createHello();
2673
+ const welcomeReply = decodeExchangeReply(asString(await carrier.exchange(encodeExchange({
2674
+ k: "hs",
2675
+ hsid,
2676
+ m: encodeHandshakeMessage(hello)
2677
+ }))));
2678
+ if (welcomeReply?.k !== "hs") throw new Error("[exchange-handshake] expected a welcome reply");
2679
+ const welcome = decodeHandshakeMessage(welcomeReply.m);
2680
+ if (welcome == null) throw new Error("[exchange-handshake] malformed welcome");
2681
+ if (welcome.t === "reject") throw new Error(`[exchange-handshake] rejected by peer: ${welcome.reason}`);
2682
+ if (welcome.t !== "welcome") throw new Error(`[exchange-handshake] expected welcome, got ${welcome.t}`);
2683
+ const prove = await handshake.onWelcome(welcome);
2684
+ const acceptReply = decodeExchangeReply(asString(await carrier.exchange(encodeExchange({
2685
+ k: "hs",
2686
+ hsid,
2687
+ m: encodeHandshakeMessage(prove)
2688
+ }))));
2689
+ if (acceptReply?.k !== "hs") throw new Error("[exchange-handshake] expected an accept reply");
2690
+ const accept = decodeHandshakeMessage(acceptReply.m);
2691
+ if (accept == null) throw new Error("[exchange-handshake] malformed accept");
2692
+ if (accept.t === "reject") throw new Error(`[exchange-handshake] rejected by peer: ${accept.reason}`);
2693
+ if (accept.t !== "accept") throw new Error(`[exchange-handshake] expected accept, got ${accept.t}`);
2694
+ if (acceptReply.t == null) throw new Error("[exchange-handshake] accept missing session token");
2695
+ const result = await handshake.onAccept(accept);
2696
+ const crypto = result.securityLevel === "encrypted" ? createActionFrameCrypto({
2697
+ link: secure.link,
2698
+ linkedClientId: result.linkedClientId
2699
+ }) : void 0;
2700
+ return {
2701
+ token: acceptReply.t,
2702
+ crypto
2703
+ };
2704
+ }
2705
+ function asString(frame) {
2706
+ if (typeof frame === "string") return frame;
2707
+ return textDecoder$1.decode(frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame);
2708
+ }
2709
+ //#endregion
2710
+ //#region src/ActionRuntime/Transport/helpers/addTransportStatusMetadata.ts
2711
+ function addTransportStatusMetadata(transportStatus) {
2712
+ if (transportStatus.status === "ready") return {
2713
+ status: "ready",
2714
+ readyData: transportStatus.readyData
2715
+ };
2716
+ if (transportStatus.status === "initializing") return {
2717
+ status: "initializing",
2718
+ initializationPromise: transportStatus.initializationPromise,
2719
+ timeStarted: Date.now()
2720
+ };
2721
+ if (transportStatus.status === "failed") return {
2722
+ status: "failed",
2723
+ error: transportStatus.error,
2724
+ timeFailed: Date.now()
2725
+ };
2726
+ if (transportStatus.status === "unsupported") return { status: "unsupported" };
2727
+ return { status: "uninitialized" };
2728
+ }
2729
+ //#endregion
2730
+ //#region src/ActionRuntime/Transport/TransportConnection.ts
2731
+ let transportOrd = 0;
2732
+ /**
2733
+ * Live, per-handler transport runtime built from a reusable {@link Transport} definition. Holds the
2734
+ * connection-scoped state (ordinal, initialized config, sockets / abort sets) that must not be shared
2735
+ * across handlers. Construct these via `definition._createConnection(...)`, never directly.
2736
+ */
2737
+ var TransportConnection = class {
2738
+ def;
2739
+ transOrd = transportOrd++;
2740
+ type;
2741
+ initialized;
2742
+ /** Backref to the public definition that created this connection (used for devtools route info). */
2743
+ definition;
2744
+ constructor(def) {
2745
+ this.def = def;
2746
+ this.type = def.type;
2747
+ this.initialized = def.initialize();
2748
+ }
2749
+ /**
2750
+ * Devtools route info for an action routed through this live connection. Defaults to the stateless
2751
+ * {@link definition}'s info; connections override to enrich it from live state (e.g. the actual
2752
+ * resolved socket URL) when the definition couldn't resolve it on its own.
2753
+ */
2754
+ getRouteInfo(input) {
2755
+ return this.definition?.getRouteInfo(input);
2756
+ }
2757
+ /**
2758
+ * Whether a `ready`-status transport still needs asynchronous bring-up before its methods exist —
2759
+ * awaiting the carrier to open and/or running a handshake. Default `false`: a stateless transport
2760
+ * (HTTP) is usable the instant `getTransport` reports `ready`, so it stays a terminal *synchronous*
2761
+ * fallback in {@link ConnectionTransportManager}. Stream carriers (Link/WS) override to `true`.
2762
+ */
2763
+ _needsAsyncBringUp(_readyData) {
2764
+ return false;
2765
+ }
2766
+ /** Await the carrier becoming ready to send (e.g. a socket `open`). Default: nothing to await. */
2767
+ _awaitCarrierReady(_readyData) {
2768
+ return Promise.resolve();
2769
+ }
2770
+ /**
2771
+ * Finalize during async bring-up — may run a handshake, so it can be async. Defaults to the
2772
+ * synchronous {@link _finalizeTransportMethods}; secure stream carriers override to branch plain/secure.
2773
+ */
2774
+ _finalizeReady(readyData) {
2775
+ return this._finalizeTransportMethods(readyData);
2776
+ }
2777
+ _getCacheKey(input) {
2778
+ const parts = this.initialized.getTransportCacheKey?.(input);
2779
+ if (parts == null) return null;
2780
+ return parts.join("\0");
2781
+ }
2782
+ getCacheKey(input) {
2783
+ const inner = this._getCacheKey(input);
2784
+ if (inner == null) return null;
2785
+ return `${this.transOrd}:${inner}`;
2786
+ }
2787
+ /**
2788
+ * Whether this transport can serve the given action right now. Consulted by the manager before
2789
+ * cache-key resolution and `getTransport`; a `false` result skips this transport (treated as
2790
+ * `unsupported`) and the manager falls through to the next in preference order. Defaults to `true`
2791
+ * when the transport declares no gate.
2792
+ */
2793
+ isAvailable(input) {
2794
+ return this.initialized.isAvailable?.(input) ?? true;
2795
+ }
2796
+ getTransport(input) {
2797
+ return this._processTransportStatus(input);
2798
+ }
2799
+ _processTransportStatus(input) {
2800
+ const statusInfo = addTransportStatusMetadata(this.initialized.getTransport(input));
2801
+ if (statusInfo.status === "ready") {
2802
+ if (!this._needsAsyncBringUp(statusInfo.readyData)) return {
2803
+ status: "ready",
2804
+ readyData: this._finalizeTransportMethods(statusInfo.readyData)
2805
+ };
2806
+ return {
2807
+ status: "initializing",
2808
+ timeStarted: Date.now(),
2809
+ initializationPromise: this._bringUp(statusInfo.readyData)
2810
+ };
2811
+ }
2812
+ if (statusInfo.status === "initializing") {
2813
+ const initializationPromise = statusInfo.initializationPromise.then((result) => result.status === "ready" ? this._bringUp(result.readyData) : result);
2814
+ return {
2815
+ status: "initializing",
2816
+ timeStarted: statusInfo.timeStarted,
2817
+ initializationPromise
2818
+ };
2819
+ }
2820
+ return statusInfo;
2821
+ }
2822
+ /** Await carrier readiness, then finalize (possibly running a handshake) into the live methods. */
2823
+ async _bringUp(readyData) {
2824
+ await this._awaitCarrierReady(readyData);
2825
+ return {
2826
+ status: "ready",
2827
+ readyData: await this._finalizeReady(readyData)
2828
+ };
2829
+ }
2830
+ };
2831
+ //#endregion
2832
+ //#region src/ActionRuntime/Transport/Exchange/ExchangeConnection.ts
2833
+ /**
2834
+ * Carrier-agnostic live connection for the exchange (request → single reply) shape — the HTTP
2835
+ * counterpart to {@link LinkConnection}. It owns only the bring-up (run the secure handshake on first
2836
+ * use); the request/reply lifecycle + crypto live in the shared `establishExchangeSession`.
2837
+ */
2838
+ var ExchangeConnection = class extends TransportConnection {
2839
+ constructor(def) {
2840
+ super({
2841
+ ...def,
2842
+ type: "exchange"
2843
+ });
2844
+ }
2845
+ _getCacheKey(input) {
2846
+ return this.initialized.getTransportCacheKey?.(input).join("\0") ?? "";
2847
+ }
2848
+ _needsAsyncBringUp(data) {
2849
+ return data.secureChannel != null && data.secureChannel.securityLevel !== "none";
2850
+ }
2851
+ _finalizeReady(data) {
2852
+ const secure = data.secureChannel;
2853
+ if (secure != null && secure.securityLevel !== "none") return finalizeSecureExchangeMethods({
2854
+ ...this._sessionContext(data),
2855
+ secure
2856
+ });
2857
+ return this._finalizeTransportMethods(data);
2858
+ }
2859
+ _finalizeTransportMethods(data) {
2860
+ return finalizePlainExchangeMethods(this._sessionContext(data));
2861
+ }
2862
+ _sessionContext(data) {
2863
+ return {
2864
+ carrier: data.carrier,
2865
+ updateRunConfig: data.updateRunConfig,
2866
+ secure: data.secureChannel
2867
+ };
2868
+ }
2869
+ };
2870
+ //#endregion
2871
+ //#region src/ActionRuntime/Transport/Exchange/ExchangeTransport.ts
2872
+ /**
2873
+ * A carrier-agnostic exchange (request → single reply) transport: it drives nice-action's secure session
2874
+ * over any {@link IExchangeCarrier} (HTTP being the one built-in). The duplex counterpart is
2875
+ * {@link LinkTransport}; this is the no-push half — its reply rides the response to its own request, so it
2876
+ * can't deliver an unsolicited frame (the runtime never picks it for the return path).
2877
+ */
2878
+ var ExchangeTransport = class ExchangeTransport extends Transport {
2879
+ options;
2880
+ type = "exchange";
2881
+ constructor(options) {
2882
+ super();
2883
+ this.options = options;
2884
+ }
2885
+ static create(options) {
2886
+ return new ExchangeTransport(options);
2887
+ }
2888
+ _createConnection(_ctx) {
2889
+ const options = this.options;
2890
+ return new ExchangeConnection({ initialize: () => ({
2891
+ getTransportCacheKey: options.getTransportCacheKey,
2892
+ isAvailable: options.available,
2893
+ getTransport: (input) => ({
2894
+ status: "ready",
2895
+ readyData: {
2896
+ carrier: options.openCarrier(input),
2897
+ secureChannel: options.security,
2898
+ updateRunConfig: options.updateRunConfig
2899
+ }
2900
+ })
2901
+ }) });
2902
+ }
2903
+ getRouteInfo(input) {
2904
+ if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);
2905
+ return {
2906
+ carrierLabel: this.options.label ?? "exchange",
2907
+ summary: this.options.label ?? "exchange"
2908
+ };
2909
+ }
2910
+ };
2911
+ //#endregion
2912
+ //#region src/ActionRuntime/Transport/helpers/createUnsetTransportResolvers.ts
2913
+ const createUnsetTransportResolvers = (transportLabel) => ({ onIncomingActionDataJson: (json) => {
2914
+ console.warn(`Received incoming action JSON [${json.domain}:${json.id}] on Transport [${transportLabel}] but no incoming data listener has been set.`);
2915
+ } });
2916
+ //#endregion
2917
+ //#region src/ActionRuntime/Transport/SecureSession/establishLinkSession.ts
2918
+ const HANDSHAKE_TIMEOUT_MS = 15e3;
2919
+ /** Plain path (no handshake): route every inbound frame to the runtime; send without crypto. */
2920
+ function finalizePlainLinkMethods(ctx) {
2921
+ const disconnectListeners = [];
2922
+ const abortSet = /* @__PURE__ */ new Set();
2923
+ const pipe = makePipe(ctx, void 0);
2924
+ ctx.channel.attach({
2925
+ onMessage: (frame) => void handleIncomingActionFrame(ctx, pipe, frame),
2926
+ onClose: () => onChannelClosed(ctx, disconnectListeners, abortSet),
2927
+ onError: () => onChannelClosed(ctx, disconnectListeners, abortSet)
2928
+ });
2929
+ return buildSendMethods(ctx, pipe, disconnectListeners, abortSet);
2930
+ }
2931
+ /**
2932
+ * Secure path: a single message handler feeds the handshake until it completes, then routes action
2933
+ * frames (decrypting at the `encrypted` level). Frames that race ahead of activation are buffered and
2934
+ * flushed once the handshake lands, so nothing is lost.
2935
+ */
2936
+ async function finalizeSecureLinkMethods(ctx) {
2937
+ const disconnectListeners = [];
2938
+ const abortSet = /* @__PURE__ */ new Set();
2939
+ const session = {};
2940
+ let active = false;
2941
+ const handshakeQueue = [];
2942
+ const handshakeWaiters = [];
2943
+ const pendingActionFrames = [];
2944
+ ctx.channel.attach({
2945
+ onMessage: (frame) => {
2946
+ if (active && session.pipe != null) {
2947
+ handleIncomingActionFrame(ctx, session.pipe, frame);
2948
+ return;
2949
+ }
2950
+ if (typeof frame === "string") {
2951
+ const message = decodeHandshakeMessage(frame);
2952
+ if (message != null) {
2953
+ const waiter = handshakeWaiters.shift();
2954
+ if (waiter != null) waiter(message);
2955
+ else handshakeQueue.push(message);
2956
+ return;
2957
+ }
2958
+ }
2959
+ pendingActionFrames.push(frame);
2960
+ },
2961
+ onClose: () => onChannelClosed(ctx, disconnectListeners, abortSet),
2962
+ onError: () => onChannelClosed(ctx, disconnectListeners, abortSet)
2963
+ });
2964
+ const nextHandshakeMessage = () => {
2965
+ const queued = handshakeQueue.shift();
2966
+ if (queued != null) return Promise.resolve(queued);
2967
+ return new Promise((resolve, reject) => {
2968
+ const timeout = setTimeout(() => reject(/* @__PURE__ */ new Error("[link-handshake] timed out waiting for peer reply")), HANDSHAKE_TIMEOUT_MS);
2969
+ handshakeWaiters.push((message) => {
2970
+ clearTimeout(timeout);
2971
+ resolve(message);
2972
+ });
2973
+ });
2974
+ };
2975
+ const pipe = makePipe(ctx, await runClientHandshake(ctx.channel, ctx.secure, nextHandshakeMessage));
2976
+ session.pipe = pipe;
2977
+ active = true;
2978
+ for (const frame of pendingActionFrames) await handleIncomingActionFrame(ctx, pipe, frame);
2979
+ pendingActionFrames.length = 0;
2980
+ return buildSendMethods(ctx, pipe, disconnectListeners, abortSet);
2981
+ }
2982
+ function makePipe(ctx, crypto) {
2983
+ return createFrameCryptoPipe({
2984
+ write: (frame) => ctx.channel.send(frame),
2985
+ isOpen: () => ctx.channel.isOpen(),
2986
+ crypto
2987
+ });
2988
+ }
2989
+ async function runClientHandshake(channel, secure, nextHandshakeMessage) {
2990
+ await secure.link.initialize();
2991
+ const handshake = createClientHandshake({
2992
+ link: secure.link,
2993
+ localCoordinate: secure.localCoordinate,
2994
+ dictionaryVersion: secure.dictionaryVersion,
2995
+ securityLevel: secure.securityLevel
2996
+ });
2997
+ channel.send(encodeHandshakeMessage(await handshake.createHello()));
2998
+ const welcome = await nextHandshakeMessage();
2999
+ if (welcome.t === "reject") throw new Error(`[link-handshake] rejected by peer: ${welcome.reason}`);
3000
+ if (welcome.t !== "welcome") throw new Error(`[link-handshake] expected welcome, got ${welcome.t}`);
3001
+ channel.send(encodeHandshakeMessage(await handshake.onWelcome(welcome)));
3002
+ const accept = await nextHandshakeMessage();
3003
+ if (accept.t === "reject") throw new Error(`[link-handshake] rejected by peer: ${accept.reason}`);
3004
+ if (accept.t !== "accept") throw new Error(`[link-handshake] expected accept, got ${accept.t}`);
3005
+ const result = await handshake.onAccept(accept);
3006
+ return result.securityLevel === "encrypted" ? createActionFrameCrypto({
3007
+ link: secure.link,
3008
+ linkedClientId: result.linkedClientId
3009
+ }) : void 0;
3010
+ }
3011
+ function buildSendMethods(ctx, pipe, disconnectListeners, abortSet) {
3012
+ const channel = ctx.channel;
3013
+ const sendActionData = (inputs) => {
3014
+ const { action, runningAction, timeout } = inputs;
3015
+ if (!channel.isOpen()) {
3016
+ if (action.type === "request") runningAction._abort(ctx.makeDisconnectError(action.id));
3017
+ return;
3018
+ }
3019
+ if (action.type === "request") {
3020
+ abortSet.add(runningAction);
3021
+ const timeoutId = setTimeout(() => {
3022
+ runningAction._abort(err_nice_transport.fromId("timeout", { timeout }));
3023
+ }, timeout);
3024
+ runningAction.addUpdateListeners([(update) => {
3025
+ if (update.type === "finished") {
3026
+ clearTimeout(timeoutId);
3027
+ abortSet.delete(runningAction);
3028
+ }
3029
+ }]);
3030
+ }
3031
+ pipe.send(ctx.formatMessage?.outgoing(inputs) ?? JSON.stringify(inputs.action.toJsonObject()));
3032
+ };
3033
+ return {
3034
+ sendActionData,
3035
+ updateRunConfig: ctx.updateRunConfig,
3036
+ addOnDisconnectListener: (cb) => {
3037
+ disconnectListeners.push(cb);
3038
+ },
3039
+ disconnect: () => {
3040
+ try {
3041
+ channel.close();
3042
+ } catch {}
3043
+ },
3044
+ sendReturnData: (payload, clients) => {
3045
+ const formatted = clients != null ? ctx.formatMessage?.outgoing({
3046
+ action: payload,
3047
+ ...clients
3048
+ }) : void 0;
3049
+ pipe.send(formatted ?? JSON.stringify(payload.toJsonObject()));
3050
+ }
3051
+ };
3052
+ }
3053
+ async function handleIncomingActionFrame(ctx, pipe, frame) {
3054
+ const decoded = await pipe.decryptIncoming(frame);
3055
+ if (decoded === void 0) return;
3056
+ const rawJson = decodeActionFrame(decoded, ctx.formatMessage);
3057
+ if (rawJson != null) ctx.resolvers.onIncomingActionDataJson(rawJson);
3058
+ }
3059
+ function onChannelClosed(ctx, disconnectListeners, abortSet) {
3060
+ for (const cb of disconnectListeners) cb();
3061
+ const error = ctx.makeDisconnectError("—");
3062
+ for (const ra of [...abortSet]) ra._abort(error);
3063
+ }
3064
+ //#endregion
3065
+ //#region src/ActionRuntime/Transport/Link/LinkConnection.ts
3066
+ /** Abort error for a closed link channel (carrier-neutral — the carrier itself isn't named). */
3067
+ function linkDisconnectError(actionId) {
3068
+ return err_nice_transport.fromId("send_failed", {
3069
+ actionId,
3070
+ actionState: "request",
3071
+ message: "link channel disconnected"
3072
+ });
3073
+ }
3074
+ /**
3075
+ * Carrier-agnostic live connection. It owns only the *bring-up* (open the carrier, then run the secure
3076
+ * session); the session itself — handshake, frame crypto, codec, send/receive — lives in the shared
3077
+ * {@link finalizeSecureLinkMethods}/{@link finalizePlainLinkMethods}, so a WebSocket, a WebRTC data
3078
+ * channel, a Bluetooth characteristic, and an in-memory pipe all run the identical secure layer.
3079
+ */
3080
+ var LinkConnection = class extends TransportConnection {
3081
+ resolvers;
3082
+ constructor(def, resolvers) {
3083
+ super({
3084
+ ...def,
3085
+ type: "duplex"
3086
+ });
3087
+ this.resolvers = resolvers ?? createUnsetTransportResolvers("link");
3088
+ }
3089
+ _getCacheKey(input) {
3090
+ return this.initialized.getTransportCacheKey?.(input).join("\0") ?? "";
3091
+ }
3092
+ _needsAsyncBringUp() {
3093
+ return true;
3094
+ }
3095
+ _awaitCarrierReady(data) {
3096
+ return data.channel.ready;
3097
+ }
3098
+ _finalizeReady(data) {
3099
+ const secure = data.secureChannel;
3100
+ if (secure != null && secure.securityLevel !== "none") return finalizeSecureLinkMethods({
3101
+ ...this._sessionContext(data),
3102
+ secure
3103
+ });
3104
+ return this._finalizeTransportMethods(data);
3105
+ }
3106
+ _sessionContext(data) {
3107
+ return {
3108
+ channel: data.channel,
3109
+ resolvers: this.resolvers,
3110
+ formatMessage: data.formatMessage,
3111
+ updateRunConfig: data.updateRunConfig,
3112
+ makeDisconnectError: linkDisconnectError
3113
+ };
3114
+ }
3115
+ _finalizeTransportMethods(data) {
3116
+ return finalizePlainLinkMethods(this._sessionContext(data));
3117
+ }
3118
+ };
3119
+ //#endregion
3120
+ //#region src/ActionRuntime/Transport/Link/LinkTransport.ts
3121
+ /**
3122
+ * A carrier-agnostic transport: it drives nice-action's secure session + action routing over any
3123
+ * {@link IDuplexCarrier}. The WebSocket transport is the special case that opens a `WebSocket`;
3124
+ * this opens whatever `openChannel` returns, so the identical secure layer works over WebRTC, Bluetooth,
3125
+ * or an in-memory pipe. Reported with an overridable carrier label in the devtools (defaults to "link").
3126
+ */
3127
+ var LinkTransport = class LinkTransport extends Transport {
3128
+ options;
3129
+ type = "duplex";
3130
+ constructor(options) {
3131
+ super();
3132
+ this.options = options;
3133
+ }
3134
+ static create(options) {
3135
+ return new LinkTransport(options);
3136
+ }
3137
+ _createConnection(ctx) {
3138
+ const options = this.options;
3139
+ return new LinkConnection({ initialize: () => ({
3140
+ getTransportCacheKey: options.getTransportCacheKey,
3141
+ isAvailable: options.available,
3142
+ getTransport: (input) => ({
3143
+ status: "ready",
3144
+ readyData: {
3145
+ channel: options.openChannel(input),
3146
+ formatMessage: options.createFormatMessage?.() ?? options.formatMessage,
3147
+ updateRunConfig: options.updateRunConfig,
3148
+ secureChannel: options.security
3149
+ }
3150
+ })
3151
+ }) }, ctx.resolvers);
3152
+ }
3153
+ getRouteInfo(input) {
3154
+ if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);
3155
+ return {
3156
+ carrierLabel: this.options.label ?? "link",
3157
+ summary: this.options.label ?? "link"
3158
+ };
3159
+ }
3160
+ };
3161
+ //#endregion
3162
+ //#region src/ActionRuntime/Transport/plainTransport.ts
3163
+ function plainTransport(options) {
3164
+ const carrier = options.carrier;
3165
+ if (isExchangeCarrierSource(carrier)) return ExchangeTransport.create({
3166
+ openCarrier: carrier.open,
3167
+ getTransportCacheKey: carrier.getCacheKey,
3168
+ available: options.available,
3169
+ getRouteInfo: carrier.getRouteInfo,
3170
+ label: options.label ?? carrier.carrierLabel,
3171
+ updateRunConfig: options.updateRunConfig
3172
+ });
3173
+ return LinkTransport.create({
3174
+ openChannel: carrier.open,
3175
+ formatMessage: options.formatMessage,
3176
+ createFormatMessage: options.createFormatMessage,
3177
+ getTransportCacheKey: carrier.getCacheKey,
3178
+ available: options.available,
3179
+ getRouteInfo: carrier.getRouteInfo,
3180
+ label: options.label ?? carrier.carrierLabel,
3181
+ updateRunConfig: options.updateRunConfig
3182
+ });
3183
+ }
3184
+ //#endregion
3185
+ //#region src/ActionRuntime/Transport/secureTransport.ts
3186
+ function secureTransport(options) {
3187
+ const link = options.link ?? (options.storageAdapter != null ? new ClientCryptoKeyLink({ storageAdapter: options.storageAdapter }) : void 0);
3188
+ if (link == null) throw new Error("secureTransport: provide `link` or `storageAdapter` for the crypto identity.");
3189
+ const security = {
3190
+ securityLevel: options.securityLevel,
3191
+ link,
3192
+ localCoordinate: options.runtime.coordinate.toJsonObject(),
3193
+ dictionaryVersion: options.channel.dictionaryVersion
3194
+ };
3195
+ const carrier = options.carrier;
3196
+ if (isExchangeCarrierSource(carrier)) return ExchangeTransport.create({
3197
+ openCarrier: carrier.open,
3198
+ getTransportCacheKey: carrier.getCacheKey,
3199
+ available: options.available,
3200
+ getRouteInfo: carrier.getRouteInfo,
3201
+ label: carrier.carrierLabel,
3202
+ security
3203
+ });
3204
+ return LinkTransport.create({
3205
+ openChannel: carrier.open,
3206
+ createFormatMessage: options.channel.createCodec,
3207
+ getTransportCacheKey: carrier.getCacheKey,
3208
+ available: options.available,
3209
+ getRouteInfo: carrier.getRouteInfo,
3210
+ label: carrier.carrierLabel,
3211
+ security
3212
+ });
3213
+ }
3214
+ //#endregion
3215
+ //#region src/ActionRuntime/Channel/ActionChannel.ts
3216
+ /**
3217
+ * Declare a transport-agnostic channel by role. Use it for HTTP, custom transports, or as the routing
3218
+ * half of a richer channel. The order of each list is part of the contract for wire formats that pack
3219
+ * positionally (see `defineSecureChannel`) — add new domains to the end of their list. (`domains` is
3220
+ * accepted as a legacy alias for `toAcceptor`.)
3221
+ */
3222
+ function defineChannel(options) {
3223
+ return {
3224
+ toAcceptorDomains: options.toAcceptor,
3225
+ toConnectorDomains: options.toConnector
3226
+ };
3227
+ }
3228
+ /**
3229
+ * Open a connection to a peer from a single call — the dial-out dual of `serveChannel`. The channel is
3230
+ * the single source of truth for *what* is routed (`toAcceptor` domains forwarded to the peer,
3231
+ * `toConnector` pushes handled locally from `onPush`); the call binds the shared facts — the channel's
3232
+ * codec/dictionary version, the runtime, and one crypto identity (a {@link ClientCryptoKeyLink} over
3233
+ * `storage`) — into every transport in `transports`, so none of them restate the channel or runtime.
3234
+ * List several transports to make the path transport-agnostic (secure WS preferred, HTTP fallback):
3235
+ * ```ts
3236
+ * const handler = connectChannel(runtime, lobbyChannel, {
3237
+ * peer: runtime_coordinate_lobby_do,
3238
+ * storage,
3239
+ * transports: [{ carrier: wsCarrier(url) }, { carrier: httpCarrier(...), secure: false }],
3240
+ * onPush: { player_joined: (p) => { … } },
3241
+ * });
3242
+ * ```
3243
+ * Returns the {@link ConnectorHandler} so the caller can later `clearTransportCache()` it.
3244
+ */
3245
+ function connectChannel(runtime, channel, options) {
3246
+ const securityLevel = options.securityLevel ?? "authenticated";
3247
+ const anySecure = options.transports.some((transport) => transport.secure ?? true);
3248
+ let link = options.link;
3249
+ if (anySecure && link == null) {
3250
+ if (options.storage == null) throw new Error("connectChannel: a secure transport requires `storage` (or `link`). Pass it, or set `secure: false` on the transport for a plain connection.");
3251
+ link = new ClientCryptoKeyLink({ storageAdapter: options.storage });
3252
+ }
3253
+ const transports = options.transports.map((transport) => {
3254
+ const carrier = transport.carrier;
3255
+ const secure = transport.secure ?? true;
3256
+ if (isExchangeCarrierSource(carrier)) return secure ? secureTransport({
3257
+ channel,
3258
+ runtime,
3259
+ link,
3260
+ securityLevel: transport.securityLevel ?? securityLevel,
3261
+ available: transport.available,
3262
+ carrier
3263
+ }) : plainTransport({
3264
+ carrier,
3265
+ available: transport.available,
3266
+ label: transport.label
3267
+ });
3268
+ return secure ? secureTransport({
3269
+ channel,
3270
+ runtime,
3271
+ link,
3272
+ securityLevel: transport.securityLevel ?? securityLevel,
3273
+ available: transport.available,
3274
+ carrier
3275
+ }) : plainTransport({
3276
+ carrier,
3277
+ createFormatMessage: channel.createCodec,
3278
+ available: transport.available,
3279
+ label: transport.label
3280
+ });
3281
+ });
3282
+ const pushHandlers = options.onPush != null ? channel.toConnectorDomains.map((domain) => domain.wrapAsPartialLocalHandler(options.onPush)) : [];
3283
+ return runtime.connectTo(options.peer, {
3284
+ transports,
3285
+ domains: [...channel.toAcceptorDomains],
3286
+ localHandlers: pushHandlers,
3287
+ defaultTimeout: options.defaultTimeout
3288
+ });
3289
+ }
3290
+ /**
3291
+ * Register an acceptor handler's execution for a channel straight from its definition: the channel's
3292
+ * `toAcceptor` domains are served together with one merged, connection-aware case map (each case gets
3293
+ * the primed request + the originating connection, as with
3294
+ * {@link AcceptorHandler.forConnectionDomainCases}). The domain list is taken from the channel,
3295
+ * never restated. Add the returned handler to the runtime alongside the acceptor handler:
3296
+ * ```ts
3297
+ * runtime.addHandlers([acceptChannelConnections(serverHandler, channel, { … }), serverHandler]);
3298
+ * ```
3299
+ *
3300
+ * The case's second argument is the raw connection (`TConn | undefined`). For the richer state +
3301
+ * broadcast + pushBack context, serve the channel through `serveChannel`'s `channelCases` instead.
3302
+ */
3303
+ function acceptChannelConnections(serverHandler, channel, cases) {
3304
+ return serverHandler.forConnectionDomainCasesMulti(channel.toAcceptorDomains, cases, (connection) => connection);
3305
+ }
3306
+ /**
3307
+ * Build the secure {@link AcceptorHandler} for a channel — the accept-in counterpart to
3308
+ * {@link connectChannel}. It folds in the same boilerplate as {@link createSecureAcceptorHandler} (the
3309
+ * `ClientCryptoKeyLink` + storage-backed TOFU resolver from one `storageAdapter`, the channel's codec +
3310
+ * dictionary version, the `security` block from the runtime coordinate) but takes the `(runtime, channel,
3311
+ * options)` shape of the channel family. Pair it with {@link acceptChannelConnections} for execution:
3312
+ * ```ts
3313
+ * const acceptor = acceptChannel(runtime, gameChannel, { clientEnv, storageAdapter, send });
3314
+ * runtime.addHandlers([acceptChannelConnections(acceptor, gameChannel, { … }), acceptor]);
3315
+ * ```
3316
+ */
3317
+ function acceptChannel(runtime, channel, options) {
3318
+ return createSecureAcceptorHandler({
3319
+ channel,
3320
+ runtime,
3321
+ clientEnv: options.clientEnv,
3322
+ storageAdapter: options.storageAdapter,
3323
+ link: options.link,
3324
+ send: options.send,
3325
+ securityLevel: options.securityLevel,
3326
+ verifyKeyResolver: options.verifyKeyResolver,
3327
+ defaultTimeout: options.defaultTimeout
3328
+ });
3329
+ }
3330
+ //#endregion
3331
+ //#region src/ActionRuntime/Transport/SecureSession/exchangeAcceptor.ts
3332
+ const textEncoder = new TextEncoder();
3333
+ const textDecoder = new TextDecoder();
3334
+ /**
3335
+ * Acceptor (accept-in) side of the secure exchange protocol — the HTTP counterpart to
3336
+ * {@link AcceptorSecureSession}. Each POST body is one {@link decodeExchangeRequest} envelope; the
3337
+ * acceptor drives the server handshake over the two `hs` POSTs (correlated by `hsid`, since stateless
3338
+ * requests can't rely on channel ordering), mints a session **token** on accept, and on every later `act`
3339
+ * POST resolves the session by token, decrypts the body (at `encrypted`), routes it through the runtime,
3340
+ * and returns the (encrypted) result inline as the reply.
3341
+ *
3342
+ * Sessions and in-flight handshakes are held in memory — fine for a single-instance server. (Surviving a
3343
+ * Durable-Object eviction would persist each token's `keyMaterial` and re-derive the key on a miss, the
3344
+ * same primitive `AcceptorSecureSession.rehydrate` uses; left as a follow-up.)
3345
+ */
3346
+ var ExchangeAcceptor = class {
3347
+ _security;
3348
+ _runtime;
3349
+ _allowedLevels;
3350
+ _noneAllowed;
3351
+ _pendingHandshakes = /* @__PURE__ */ new Map();
3352
+ _sessions = /* @__PURE__ */ new Map();
3353
+ constructor(config) {
3354
+ this._security = config.security;
3355
+ this._runtime = config.runtime;
3356
+ this._allowedLevels = Array.isArray(config.security.securityLevel) ? config.security.securityLevel : [config.security.securityLevel];
3357
+ this._noneAllowed = this._allowedLevels.includes("none");
3358
+ }
3359
+ /** Process one POST body (an exchange envelope), returning the reply body to send back. */
3360
+ async handlePost(body) {
3361
+ const request = decodeExchangeRequest(body);
3362
+ if (request == null) return this._err("malformed exchange request");
3363
+ if (request.k === "hs") return encodeExchange(await this._handleHandshake(request));
3364
+ return encodeExchange(await this._handleAction(request));
3365
+ }
3366
+ async _handleHandshake(request) {
3367
+ const message = decodeHandshakeMessage(request.m);
3368
+ if (message == null) return {
3369
+ k: "err",
3370
+ message: "malformed handshake message"
3371
+ };
3372
+ const security = this._security;
3373
+ await security.link.initialize();
3374
+ let handshake = this._pendingHandshakes.get(request.hsid);
3375
+ if (handshake == null) {
3376
+ handshake = createServerHandshake({
3377
+ link: security.link,
3378
+ localCoordinate: security.localCoordinate,
3379
+ dictionaryVersion: security.dictionaryVersion,
3380
+ securityLevel: security.securityLevel,
3381
+ verifyKeyResolver: security.verifyKeyResolver
3382
+ });
3383
+ this._pendingHandshakes.set(request.hsid, handshake);
3384
+ }
3385
+ if (message.t === "hello") return {
3386
+ k: "hs",
3387
+ m: encodeHandshakeMessage(await handshake.onHello(message))
3388
+ };
3389
+ if (message.t === "prove") {
3390
+ const reply = await handshake.onProve(message);
3391
+ this._pendingHandshakes.delete(request.hsid);
3392
+ const result = handshake.getResult();
3393
+ if (reply.t === "accept" && result != null) {
3394
+ const token = nanoid();
3395
+ this._sessions.set(token, {
3396
+ client: new RuntimeCoordinate(result.remote),
3397
+ securityLevel: result.securityLevel,
3398
+ crypto: result.securityLevel === "encrypted" ? createActionFrameCrypto({
3399
+ link: security.link,
3400
+ linkedClientId: result.linkedClientId
3401
+ }) : void 0
3402
+ });
3403
+ return {
3404
+ k: "hs",
3405
+ m: encodeHandshakeMessage(reply),
3406
+ t: token
3407
+ };
3408
+ }
3409
+ return {
3410
+ k: "hs",
3411
+ m: encodeHandshakeMessage(reply)
3412
+ };
3413
+ }
3414
+ return {
3415
+ k: "err",
3416
+ message: `unexpected handshake message ${message.t}`
3417
+ };
3418
+ }
3419
+ async _handleAction(request) {
3420
+ let session;
3421
+ let candidate;
3422
+ if (request.t != null) {
3423
+ session = this._sessions.get(request.t);
3424
+ if (session == null) return {
3425
+ k: "err",
3426
+ message: "unknown or expired session token"
3427
+ };
3428
+ if ("c" in request) {
3429
+ if (session.crypto == null) return {
3430
+ k: "err",
3431
+ message: "session is not encrypted"
3432
+ };
3433
+ const plain = await session.crypto.decryptFrame(base64ToBytes(request.c));
3434
+ candidate = JSON.parse(textDecoder.decode(plain));
3435
+ } else candidate = request.w;
3436
+ } else {
3437
+ if (!this._noneAllowed || "c" in request) return {
3438
+ k: "err",
3439
+ message: "missing session token"
3440
+ };
3441
+ candidate = request.w;
3442
+ }
3443
+ if (!isActionPayload_Any_JsonObject(candidate)) return {
3444
+ k: "err",
3445
+ message: "malformed action wire"
3446
+ };
3447
+ const wire = candidate;
3448
+ if (session != null && wire.type === "request") wire.context.originClient = session.client.toJsonObject();
3449
+ const resultWire = (await (await this._runtime.handleActionPayloadWire(wire)).waitForResultPayload()).toJsonObject();
3450
+ if (session?.crypto != null) return {
3451
+ k: "act",
3452
+ c: bytesToBase64(await session.crypto.encryptFrame(textEncoder.encode(JSON.stringify(resultWire))))
3453
+ };
3454
+ return {
3455
+ k: "act",
3456
+ w: resultWire
3457
+ };
3458
+ }
3459
+ _err(message) {
3460
+ return encodeExchange({
3461
+ k: "err",
3462
+ message
3463
+ });
3464
+ }
3465
+ };
3466
+ //#endregion
3467
+ //#region src/ActionRuntime/Handler/PeerLink/Acceptor/createActionFetchHandler.ts
3468
+ /** Permissive defaults — fine for a public action endpoint; override (or disable) via `cors`. */
3469
+ const DEFAULT_CORS_HEADERS = {
3470
+ "Access-Control-Allow-Origin": "*",
3471
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
3472
+ "Access-Control-Allow-Headers": "Content-Type",
3473
+ "Access-Control-Max-Age": "86400"
3474
+ };
3475
+ /**
3476
+ * Build the `fetch` handler a server/Durable-Object exposes for action traffic, folding in the
3477
+ * boilerplate every endpoint repeats: CORS (incl. the `OPTIONS` preflight), routing the `/action`
3478
+ * `POST` body through the runtime (`handleActionPayloadWire` → `waitForResultPayload` →
3479
+ * `toHttpResponse`), an optional WebSocket-upgrade hook, and a `404` fallback.
3480
+ *
3481
+ * It only touches web-standard `Request`/`Response`, so it stays transport-agnostic — the one
3482
+ * environment-specific bit (the WS upgrade) is injected via {@link IActionFetchHandlerOptions.onWebSocketUpgrade}:
3483
+ * ```ts
3484
+ * this.fetchHandler = createActionFetchHandler(this.runtime, {
3485
+ * onWebSocketUpgrade: () => {
3486
+ * const pair = new WebSocketPair();
3487
+ * this.ctx.acceptWebSocket(pair[1]);
3488
+ * return new Response(null, { status: 101, webSocket: pair[0] });
3489
+ * },
3490
+ * });
3491
+ * // async fetch(request) { return this.fetchHandler(request); }
3492
+ * ```
3493
+ */
3494
+ function createActionFetchHandler(runtime, options = {}) {
3495
+ const corsHeaders = options.cors === false ? {} : options.cors ?? DEFAULT_CORS_HEADERS;
3496
+ const isActionPath = options.isActionPath ?? ((url) => url.pathname.endsWith("/action"));
3497
+ const isWebSocketPath = options.isWebSocketPath ?? ((url) => url.pathname.endsWith("/ws"));
3498
+ const exchangeAcceptor = options.security != null ? new ExchangeAcceptor({
3499
+ runtime,
3500
+ security: options.security
3501
+ }) : void 0;
3502
+ const withCors = (response) => {
3503
+ if (options.cors === false) return response;
3504
+ const headers = new Headers(response.headers);
3505
+ for (const [key, value] of Object.entries(corsHeaders)) headers.set(key, value);
3506
+ return new Response(response.body, {
3507
+ status: response.status,
3508
+ headers
3509
+ });
3510
+ };
3511
+ return async (request) => {
3512
+ if (request.method === "OPTIONS") return withCors(new Response(null, { status: 204 }));
3513
+ const url = new URL(request.url);
3514
+ const isWebSocketUpgrade = options.isWebSocketUpgrade ?? ((req, u) => req.headers.get("Upgrade") === "websocket" && isWebSocketPath(u));
3515
+ if (options.onWebSocketUpgrade != null && isWebSocketUpgrade(request, url)) return options.onWebSocketUpgrade(request, url);
3516
+ if (request.method === "POST" && isActionPath(url)) {
3517
+ if (exchangeAcceptor != null) {
3518
+ const reply = await exchangeAcceptor.handlePost(await request.text());
3519
+ return withCors(new Response(reply, {
3520
+ status: 200,
3521
+ headers: { "Content-Type": "application/json" }
3522
+ }));
3523
+ }
3524
+ return withCors((await (await runtime.handleActionPayloadWire(await request.json())).waitForResultPayload()).toHttpResponse({ useErrorStatus: options.useErrorStatus }));
3525
+ }
3526
+ return withCors(new Response("Not found", { status: 404 }));
3527
+ };
3528
+ }
3529
+ //#endregion
3530
+ //#region src/ActionRuntime/Handler/PeerLink/Acceptor/Hibernation/ConnectionStateStore.ts
3531
+ /**
3532
+ * A typed per-connection state store that co-owns the app state and the acceptor handler's routing
3533
+ * binding in one attachment, so neither the consumer nor the handler has to hand-merge the two. Create
3534
+ * it through {@link createConnectionStateStore} (which also wires binding persistence and replays
3535
+ * surviving connections after a wake), then `get`/`set`/`clearApp` the app state directly.
3536
+ *
3537
+ * The mechanism is carrier-neutral — it only needs read/write/enumerate callbacks for the connection's
3538
+ * attachment — but it pays off on transports whose connections outlive process eviction (e.g. a
3539
+ * Durable Object's hibernatable WebSockets), which is why it lives beside the hibernation adapter.
3540
+ *
3541
+ * ```ts
3542
+ * const players = createConnectionStateStore(serverHandler, {
3543
+ * schema: vs_player,
3544
+ * read: (ws) => ws.deserializeAttachment(),
3545
+ * write: (ws, v) => ws.serializeAttachment(v),
3546
+ * getConnections: () => ctx.getWebSockets(),
3547
+ * });
3548
+ * players.set(ws, player); // binding is preserved automatically
3549
+ * const player = players.get(ws);
3550
+ * ```
3551
+ */
3552
+ var ConnectionStateStore = class {
3553
+ options;
3554
+ constructor(options) {
3555
+ this.options = options;
3556
+ }
3557
+ /** The validated app state for a connection, or `null` if unset / invalid. */
3558
+ get(connection) {
3559
+ return this._readAttachment(connection).app ?? null;
3560
+ }
3561
+ /** Set the app state, preserving the runtime binding already pinned to the connection. */
3562
+ set(connection, app) {
3563
+ const existing = this._readAttachment(connection);
3564
+ this.options.write(connection, {
3565
+ app,
3566
+ binding: existing.binding
3567
+ });
3568
+ }
3569
+ /** Clear the app state but keep the binding (e.g. a spectator that stopped watching). */
3570
+ clearApp(connection) {
3571
+ const existing = this._readAttachment(connection);
3572
+ this.options.write(connection, { binding: existing.binding });
3573
+ }
3574
+ /** Every live connection paired with its (validated) app state — for rebuilding in-memory state after a wake. */
3575
+ entries() {
3576
+ return this.options.getConnections().map((connection) => [connection, this._readAttachment(connection).app ?? null]);
3577
+ }
3578
+ /** @internal Persist a freshly-bound connection's binding, preserving any app state already stored. */
3579
+ _persistBinding(connection, binding) {
3580
+ const existing = this._readAttachment(connection);
3581
+ this.options.write(connection, {
3582
+ app: existing.app,
3583
+ binding
3584
+ });
3585
+ }
3586
+ /** @internal The persisted binding for a connection, if any (used to replay routing after a wake). */
3587
+ _readBinding(connection) {
3588
+ return this._readAttachment(connection).binding;
3589
+ }
3590
+ _readAttachment(connection) {
3591
+ try {
3592
+ const raw = this.options.read(connection);
3593
+ if (typeof raw !== "object" || raw === null) return {};
3594
+ const attachment = raw;
3595
+ const result = {};
3596
+ if (attachment.binding != null) result.binding = attachment.binding;
3597
+ if (attachment.app !== void 0) {
3598
+ const app = this._validateApp(attachment.app);
3599
+ if (app !== void 0) result.app = app;
3600
+ }
3601
+ return result;
3602
+ } catch {
3603
+ return {};
3604
+ }
3605
+ }
3606
+ _validateApp(value) {
3607
+ const schema = this.options.schema;
3608
+ if (schema == null) return value;
3609
+ const result = schema["~standard"].validate(value);
3610
+ if (result instanceof Promise) return void 0;
3611
+ if (result.issues != null) return void 0;
3612
+ return result.value;
3613
+ }
3614
+ };
3615
+ /**
3616
+ * Build a per-connection {@link ConnectionStateStore} bound to an {@link AcceptorHandler}: it registers
3617
+ * itself as the handler's connection-bound persistence callback (so bindings are written without
3618
+ * overwriting app state) and immediately replays every live connection's stored binding via
3619
+ * {@link AcceptorHandler.rehydrateConnection} — so on a transport that resumes after eviction (e.g. a
3620
+ * Durable Object waking from hibernation) both the app identity and the action routing come back from a
3621
+ * single attachment, with no storage reads and no hand-rolled merge.
3622
+ *
3623
+ * Lives outside the handler so the generic {@link AcceptorHandler} stays free of any attachment/
3624
+ * hibernation concern — it exposes only the neutral `setOnConnectionBound` + `rehydrateConnection`
3625
+ * hooks this builder drives.
3626
+ */
3627
+ function createConnectionStateStore(handler, options) {
3628
+ const store = new ConnectionStateStore(options);
3629
+ handler.setOnConnectionBound((connection, binding) => store._persistBinding(connection, binding));
3630
+ for (const connection of options.getConnections()) {
3631
+ const binding = store._readBinding(connection);
3632
+ if (binding != null) handler.rehydrateConnection(connection, binding);
3633
+ }
3634
+ return store;
3635
+ }
3636
+ //#endregion
3637
+ //#region src/ActionRuntime/Handler/PeerLink/Acceptor/Hibernation/createHibernatableWsServerAdapter.ts
3638
+ /**
3639
+ * Wire the hibernation lifecycle for an acceptor handler on a transport whose connections outlive process
3640
+ * eviction (e.g. a Durable Object's hibernatable WebSockets). It owns persistence end to end:
3641
+ * registers `setAttachment` as the handler's connection-bound callback and immediately replays every
3642
+ * live connection's stored binding via `getAttachment`, so results/pushes still route after a wake.
3643
+ *
3644
+ * Layered on top of the generic {@link AcceptorHandler} — it touches only the handler's neutral
3645
+ * `setOnConnectionBound` / `rehydrateConnection` / `receive` / `dropConnection` surface, so no
3646
+ * hibernation concern leaks into the handler itself.
3647
+ *
3648
+ * Construct it once when the handler is built, then forward connection events:
3649
+ * ```ts
3650
+ * const duplex = createHibernatableWsServerAdapter({ handler, getConnections, getAttachment, setAttachment });
3651
+ * // webSocketMessage(ws, msg) => duplex.receive(ws, msg);
3652
+ * // webSocketClose/Error(ws) => duplex.drop(ws);
3653
+ * ```
3654
+ */
3655
+ function createHibernatableWsServerAdapter(options) {
3656
+ const { handler, getConnections, getAttachment, setAttachment } = options;
3657
+ handler.setOnConnectionBound(setAttachment);
3658
+ for (const connection of getConnections()) {
3659
+ const binding = getAttachment(connection);
3660
+ if (binding != null) handler.rehydrateConnection(connection, binding);
3661
+ }
3662
+ return {
3663
+ receive: (connection, frame) => handler.receive(connection, frame),
3664
+ drop: (connection) => handler.dropConnection(connection)
3665
+ };
3666
+ }
3667
+ //#endregion
3668
+ //#region src/ActionRuntime/Transport/Carrier/AcceptorCarrier.types.ts
3669
+ /**
3670
+ * Build the inert lifecycle slot a duplex carrier factory spreads into its handle: `receive`/`drop` throw
3671
+ * (or no-op) until `serveChannel` calls `_activate` with the carrier's live router. Shared by every duplex
3672
+ * carrier factory (`wsAcceptorCarrier`, a WebRTC carrier, the Cloudflare DO helper, …) so the
3673
+ * stateful-handle wiring lives in exactly one place.
3674
+ */
3675
+ function createDuplexCarrierLifecycle() {
3676
+ let router;
3677
+ return {
3678
+ receive(connection, frame) {
3679
+ if (router == null) throw new Error("acceptor carrier not served yet — pass it to serveChannel() before feeding frames");
3680
+ router.receive(connection, frame);
3681
+ },
3682
+ drop(connection) {
3683
+ router?.drop(connection);
3684
+ },
3685
+ _activate(liveRouter) {
3686
+ router = liveRouter;
3687
+ }
3688
+ };
3689
+ }
3690
+ /**
3691
+ * Narrow an acceptor carrier to the exchange shape via its `shape` discriminant — the one branch
3692
+ * `serveChannel` uses to pick the duplex (push-capable) vs exchange (request/reply) wiring. A duplex
3693
+ * carrier carries `shape: ETransportShape.duplex`, so the `else` branch is the duplex one.
3694
+ */
3695
+ function isExchangeAcceptorCarrier(carrier) {
3696
+ return carrier.shape === "exchange";
3697
+ }
3698
+ //#endregion
3699
+ //#region src/ActionRuntime/Channel/serveChannel.ts
3700
+ /** Default accepted set, shared by every carrier: negotiate per connection to whatever the client picks. */
3701
+ const DEFAULT_SERVER_SECURITY_LEVELS = [
3702
+ "none",
3703
+ "authenticated",
3704
+ "encrypted"
3705
+ ];
3706
+ function serveChannel(runtime, channel, options) {
3707
+ const duplexCarriers = options.carriers.filter((carrier) => !isExchangeAcceptorCarrier(carrier));
3708
+ const exchangeCarriers = options.carriers.filter(isExchangeAcceptorCarrier);
3709
+ if (exchangeCarriers.length > 1) throw new Error("serveChannel: at most one exchange carrier is supported");
3710
+ const exchangeCarrier = exchangeCarriers[0];
3711
+ const singleDuplex = duplexCarriers.length === 1;
3712
+ if (options.connectionState != null && !singleDuplex) throw new Error("serveChannel: `connectionState` requires exactly one duplex carrier");
3713
+ if (options.channelCases != null && !singleDuplex) throw new Error("serveChannel: `channelCases` requires exactly one duplex carrier");
3714
+ const exchangeSecure = exchangeCarrier != null && (exchangeCarrier.secure ?? true);
3715
+ const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
3716
+ const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
3717
+ let secure;
3718
+ if (anyDuplexSecure || exchangeSecure) {
3719
+ const storage = options.storage;
3720
+ if (storage == null) throw new Error("serveChannel: a secure carrier requires `storage`. Pass it, or set `secure: false` on the carrier for a plain endpoint.");
3721
+ secure = {
3722
+ storage,
3723
+ link: options.link ?? new ClientCryptoKeyLink({ storageAdapter: storage }),
3724
+ verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(storage)
3725
+ };
3726
+ }
3727
+ const plainRouter = (handler) => ({
3728
+ receive: (connection, frame) => handler.receive(connection, frame),
3729
+ drop: (connection) => handler.dropConnection(connection)
3730
+ });
3731
+ const asObject = (value) => typeof value === "object" && value != null ? value : {};
3732
+ const handlers = [];
3733
+ let connections;
3734
+ for (const carrier of duplexCarriers) {
3735
+ const handler = (carrier.secure ?? true) && secure != null ? acceptChannel(runtime, channel, {
3736
+ clientEnv: options.clientEnv,
3737
+ storageAdapter: secure.storage,
3738
+ link: secure.link,
3739
+ verifyKeyResolver: secure.verifyKeyResolver,
3740
+ securityLevel,
3741
+ send: carrier.send,
3742
+ defaultTimeout: options.defaultTimeout
3743
+ }) : createAcceptorHandler({
3744
+ clientEnv: options.clientEnv,
3745
+ createFormatMessage: channel.createCodec,
3746
+ send: carrier.send,
3747
+ runtime,
3748
+ defaultTimeout: options.defaultTimeout
3749
+ });
3750
+ const attach = carrier.attachmentStore;
3751
+ let router;
3752
+ if (attach == null) router = plainRouter(handler);
3753
+ else if (options.connectionState != null) {
3754
+ connections = createConnectionStateStore(handler, {
3755
+ schema: options.connectionState.schema,
3756
+ getConnections: attach.getConnections,
3757
+ read: attach.read,
3758
+ write: attach.write
3759
+ });
3760
+ router = plainRouter(handler);
3761
+ } else router = createHibernatableWsServerAdapter({
3762
+ handler,
3763
+ getConnections: attach.getConnections,
3764
+ getAttachment: (connection) => attach.read(connection)?.binding,
3765
+ setAttachment: (connection, binding) => attach.write(connection, {
3766
+ ...asObject(attach.read(connection)),
3767
+ binding
3768
+ })
3769
+ });
3770
+ carrier._activate(router);
3771
+ handlers.push(handler);
3772
+ }
3773
+ runtime.addHandlers([...options.handlers ?? [], ...handlers]);
3774
+ const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
3775
+ const receive = (connection, frame) => {
3776
+ if (soleDuplex == null) throw new Error(duplexCarriers.length === 0 ? "serveChannel: no duplex carrier to receive on (this server has no socket transport)" : "serveChannel: several duplex carriers — feed each carrier handle's receive() directly");
3777
+ soleDuplex.receive(connection, frame);
3778
+ };
3779
+ const drop = (connection) => {
3780
+ soleDuplex?.drop(connection);
3781
+ };
3782
+ const pushToClient = (target, request, pushOptions) => {
3783
+ const owner = target instanceof RuntimeCoordinate ? handlers.find((handler) => handler.ownsLiveConnectionFor(target)) : handlers.find((handler) => handler.hasConnection(target));
3784
+ if (owner == null) throw new Error("serveChannel: no duplex carrier holds a connection for the push target");
3785
+ return owner.pushToClient(runtime, target, request, pushOptions);
3786
+ };
3787
+ const broadcast = (makeRequest, broadcastOptions) => {
3788
+ if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific handlers[i] instead");
3789
+ handlers[0].broadcast(makeRequest, {
3790
+ runtime,
3791
+ ...broadcastOptions
3792
+ });
3793
+ };
3794
+ const makeConnectionContext = (connection, request) => ({
3795
+ connection: connection ?? null,
3796
+ origin: request.context.originClient,
3797
+ get state() {
3798
+ return connection != null && connections != null ? connections.get(connection) : null;
3799
+ },
3800
+ setState(value) {
3801
+ if (connection != null && connections != null) connections.set(connection, value);
3802
+ },
3803
+ clearState() {
3804
+ if (connection != null && connections != null) connections.clearApp(connection);
3805
+ },
3806
+ broadcast(makeRequest, contextOptions) {
3807
+ broadcast(makeRequest, {
3808
+ except: contextOptions?.exceptSelf ? connection ?? null : null,
3809
+ where: contextOptions?.where,
3810
+ timeout: contextOptions?.timeout,
3811
+ onError: contextOptions?.onError
3812
+ });
3813
+ },
3814
+ pushBack(pushRequest, pushOptions) {
3815
+ if (connection == null) throw new Error("serveChannel: connection context has no live socket to push back to (HTTP-exchange path)");
3816
+ return pushToClient(connection, pushRequest, pushOptions);
3817
+ }
3818
+ });
3819
+ if (options.channelCases != null) runtime.addHandlers([handlers[0].forConnectionDomainCasesMulti(channel.toAcceptorDomains, options.channelCases, makeConnectionContext)]);
3820
+ const exchangeSecurity = exchangeSecure && secure != null ? {
3821
+ link: secure.link,
3822
+ verifyKeyResolver: secure.verifyKeyResolver,
3823
+ localCoordinate: runtime.coordinate.toJsonObject(),
3824
+ dictionaryVersion: channel.dictionaryVersion,
3825
+ securityLevel
3826
+ } : void 0;
3827
+ const defaultIsUpgrade = (request) => request.headers.get("Upgrade") === "websocket";
3828
+ const upgraders = [];
3829
+ for (const carrier of duplexCarriers) {
3830
+ if (carrier.upgrade == null) continue;
3831
+ upgraders.push({
3832
+ isUpgrade: carrier.isUpgrade ?? defaultIsUpgrade,
3833
+ upgrade: carrier.upgrade
3834
+ });
3835
+ }
3836
+ return {
3837
+ handlers,
3838
+ fetch: createActionFetchHandler(runtime, {
3839
+ cors: exchangeCarrier?.cors,
3840
+ onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
3841
+ isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
3842
+ isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
3843
+ security: exchangeSecurity,
3844
+ useErrorStatus: exchangeCarrier?.useErrorStatus
3845
+ }),
3846
+ receive,
3847
+ drop,
3848
+ pushToClient,
3849
+ broadcast,
3850
+ connections
3851
+ };
3852
+ }
3853
+ //#endregion
3854
+ //#region src/ActionRuntime/Channel/serveHost.ts
3855
+ function serveHost(runtime, channel, host, options) {
3856
+ const server = serveChannel(runtime, channel, {
3857
+ ...options,
3858
+ carriers: host.carriers,
3859
+ storage: host.storage
3860
+ });
3861
+ host.onServed?.(server);
3862
+ return server;
3863
+ }
3864
+ //#endregion
3865
+ //#region src/ActionRuntime/Transport/Carrier/duplex/ws/wsAcceptorCarrier.ts
3866
+ /**
3867
+ * A WebSocket {@link IDuplexAcceptorCarrier}: the accept-in dual of {@link wsCarrier}. It describes how to
3868
+ * write frames back to a live socket, how to upgrade an inbound request into one, and (optionally) how to
3869
+ * persist bindings across hibernation. Hand it to `serveChannel`'s `carriers` list — the secure session,
3870
+ * codec, and crypto identity are supplied centrally there, so this only carries the WS-specific surface.
3871
+ */
3872
+ function wsAcceptorCarrier(options) {
3873
+ return {
3874
+ ...createDuplexCarrierLifecycle(),
3875
+ shape: "duplex",
3876
+ carrierLabel: options.carrierLabel ?? "ws",
3877
+ secure: options.secure,
3878
+ send: options.send,
3879
+ upgrade: options.upgrade,
3880
+ isUpgrade: options.isUpgrade ?? ((request) => request.headers.get("Upgrade") === "websocket"),
3881
+ attachmentStore: options.attachmentStore
3882
+ };
3883
+ }
3884
+ //#endregion
3885
+ //#region src/ActionRuntime/Transport/Carrier/exchange/http/httpAcceptorCarrier.ts
3886
+ /**
3887
+ * An HTTP {@link IExchangeAcceptorCarrier}: the accept-in dual of {@link httpCarrier}. It serves the
3888
+ * secure exchange protocol (handshake → token session → encrypted frames) over web-standard
3889
+ * `Request`/`Response`. The crypto identity, runtime coordinate, dictionary version, and accepted security
3890
+ * levels are all supplied centrally by `serveChannel`, so this only needs to say which requests carry an
3891
+ * action envelope and how to answer CORS.
3892
+ */
3893
+ function httpAcceptorCarrier(options = {}) {
3894
+ return {
3895
+ shape: "exchange",
3896
+ carrierLabel: options.carrierLabel ?? "http",
3897
+ secure: options.secure,
3898
+ isActionPath: options.isActionPath,
3899
+ cors: options.cors,
3900
+ useErrorStatus: options.useErrorStatus
3901
+ };
3902
+ }
3903
+ //#endregion
3904
+ export { EErrId_NiceAction as $, createServerHandshake as A, PeerLinkHandler as B, createAcceptorHandler as C, ESecurityLevel as D, EHandshakeMessageType as E, ActionLocalHandler as F, err_nice_external_client as G, ETransportStatus as H, createLocalHandler as I, ActionSchema as J, isActionPayload_Any_JsonObject as K, ActionRuntime as L, decodeHandshakeMessage as M, encodeHandshakeMessage as N, createClientHandshake as O, runtimeLinkId as P, isAction_Base_JsonObject as Q, ConnectorHandler as R, AcceptorHandler as S, decodeActionFrame as T, EErrId_NiceTransport as U, ETransportShape as V, err_nice_transport as W, actionSchema as X, EActionResponseMode as Y, isActionPayload_Result_JsonObject as Z, decodeExchangeReply as _, isExchangeAcceptorCarrier as a, EActionProgressType as at, Transport as b, createConnectionStateStore as c, RuntimeCoordinate as ct, acceptChannel as d, err_nice_action as et, acceptChannelConnections as f, ExchangeTransport as g, LinkTransport as h, serveChannel as i, EActionPayloadType as it, createStorageTofuVerifyKeyResolver as j, createInMemoryTofuVerifyKeyResolver as k, createActionFetchHandler as l, runtimeCoordinateToStringIds as lt, defineChannel as m, wsAcceptorCarrier as n, ActionPayload_Request as nt, createHibernatableWsServerAdapter as o, ActionPayload as ot, connectChannel as p, isActionPayload_Request_JsonObject as q, serveHost as r, ActionPayload_Result as rt, ConnectionStateStore as s, ActionBase as st, httpAcceptorCarrier as t, RunningAction as tt, ExchangeAcceptor as u, UNSET_RUNTIME_ENV_ID as ut, decodeExchangeRequest as v, createActionFrameCrypto as w, createSecureAcceptorHandler as x, encodeExchange as y, createConnectorHandler as z };
3905
+
3906
+ //# sourceMappingURL=httpAcceptorCarrier-DL8lf0xB.mjs.map