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