@nice-code/action 0.20.0 → 0.22.0

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