@nice-code/commander 0.113.0 → 0.115.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.
package/build/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { t as COMMANDER_ID_PATTERN } from "./types-B3WIUo4S.mjs";
3
3
  import { createRequire } from "node:module";
4
- import { mkdir, open, readFile, realpath, rename, unlink, writeFile } from "node:fs/promises";
4
+ import { mkdir, open, readFile, readlink, realpath, rename, unlink, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
6
6
  import { createNiceProcess, detectCapability, matchProcessStartStamp, openProcessLedger, readProcessStartStamp, signalProcessGroup, taskkillTree } from "@nice-code/process";
7
7
  import { closeSync, existsSync, openSync, readFileSync, realpathSync, statSync } from "node:fs";
@@ -1514,24 +1514,35 @@ function staggerFor(config, terms) {
1514
1514
  }
1515
1515
  return stagger;
1516
1516
  }
1517
- //#endregion
1518
- //#region ../nice-wire/src/Carrier/AcceptorCarrier.ts
1517
+ /** Whether a frame is over `maxBytes`, encoding a text frame only when its length cannot settle it. */
1518
+ function isFrameOver(frame, maxBytes) {
1519
+ if (typeof frame !== "string") return frame.byteLength > maxBytes;
1520
+ if (frame.length > maxBytes) return true;
1521
+ if (frame.length * 3 <= maxBytes) return false;
1522
+ return new TextEncoder().encode(frame).byteLength > maxBytes;
1523
+ }
1519
1524
  /** Build the inert lifecycle slot shared by duplex acceptor carrier factories. */
1520
1525
  function createDuplexCarrierLifecycle(limits) {
1521
1526
  let router;
1522
1527
  let disposed = false;
1523
1528
  const windows = /* @__PURE__ */ new Map();
1524
- const maxFrameBytes = limits?.maxFrameBytes;
1529
+ const maxFrameBytes = limits?.maxFrameBytes ?? 1048576;
1525
1530
  const rate = limits?.rate;
1526
- if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
1531
+ if (maxFrameBytes !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer, or Infinity for no limit");
1532
+ const exceeded = (connection, reason) => {
1533
+ if (limits?.onExceeded != null) {
1534
+ limits.onExceeded(connection, reason);
1535
+ return;
1536
+ }
1537
+ console.warn(reason === "frame_bytes" ? `[nice-wire] dropped an inbound frame over ${maxFrameBytes} bytes (inboundLimits.maxFrameBytes)` : "[nice-wire] dropped an inbound frame over the message rate (inboundLimits.rate)");
1538
+ };
1527
1539
  if (rate != null && (!Number.isSafeInteger(rate.maxMessages) || rate.maxMessages <= 0 || !Number.isSafeInteger(rate.windowMs) || rate.windowMs <= 0)) throw new Error("inbound rate limits must be positive safe integers");
1528
- const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
1529
1540
  return {
1530
1541
  receive(connection, frame) {
1531
1542
  if (disposed) return;
1532
1543
  if (router == null) throw new Error("acceptor carrier not served yet — activate it before feeding frames");
1533
- if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
1534
- limits?.onExceeded(connection, "frame_bytes");
1544
+ if (isFrameOver(frame, maxFrameBytes)) {
1545
+ exceeded(connection, "frame_bytes");
1535
1546
  return;
1536
1547
  }
1537
1548
  if (rate != null) {
@@ -1546,7 +1557,7 @@ function createDuplexCarrierLifecycle(limits) {
1546
1557
  }
1547
1558
  window.count += 1;
1548
1559
  if (window.count > rate.maxMessages) {
1549
- limits?.onExceeded(connection, "message_rate");
1560
+ exceeded(connection, "message_rate");
1550
1561
  return;
1551
1562
  }
1552
1563
  }
@@ -1584,6 +1595,25 @@ function wsAcceptorCarrier(options) {
1584
1595
  };
1585
1596
  }
1586
1597
  //#endregion
1598
+ //#region ../nice-error/src/NiceError/nice_error.static.ts
1599
+ const DUR_OBJ_PACK_PREFIX = "NE_DUROBJ[[";
1600
+ const DUR_OBJ_PACK_SUFFIX = "]]NE_DUROBJ";
1601
+ /**
1602
+ * The domain of the generic wrapper `castNiceError` produces for anything that
1603
+ * wasn't already a `NiceError` (native throws, error-like objects, nullish,
1604
+ * primitives). `NiceError.isUnhandled` is defined as "belongs to this domain" —
1605
+ * i.e. an error we never accounted for and had to wrap. Kept here (not imported
1606
+ * from `nice_core_errors`) so `NiceError` can reference it without an import cycle.
1607
+ */
1608
+ const ERR_CAST_NOT_NICE_DOMAIN = "err_cast_not_nice";
1609
+ /**
1610
+ * The sealed failure: the one id, sentence and status a peer is sent in place of an error this
1611
+ * side never accounted for. Shared by the cast domain's schema and `NiceError.toWireJsonObject`,
1612
+ * which cannot import that domain.
1613
+ */
1614
+ const SEALED_FAILURE_ID = "unhandled";
1615
+ const SEALED_FAILURE_MESSAGE = "The other side failed and did not say how. The detail is in its own log, not in this error.";
1616
+ //#endregion
1587
1617
  //#region ../nice-error/src/internal/internal_errors.ts
1588
1618
  let _build;
1589
1619
  /** Wired once by `nice_core_errors` at module init to avoid an import cycle. */
@@ -1613,18 +1643,54 @@ function getErrorDomainProps(holder) {
1613
1643
  }
1614
1644
  //#endregion
1615
1645
  //#region ../nice-error/src/utils/jsErrorOrCastJsError.ts
1646
+ function messageOfThrown(thrown) {
1647
+ if (typeof thrown === "string") return thrown;
1648
+ if (typeof thrown === "object" && thrown != null && "message" in thrown && typeof thrown.message === "string") return thrown.message;
1649
+ return "No error message found";
1650
+ }
1616
1651
  function jsErrorOrCastJsError(error, logMessage = true) {
1617
- if (error instanceof Error) return Object.assign(error, { message: error.message });
1618
- const message = error?.message ?? (typeof error === "string" ? error : "No error message found");
1652
+ if (error instanceof Error) return error;
1653
+ const message = messageOfThrown(error);
1619
1654
  if (logMessage) console.error(`An unknown and unstructured error was thrown: ${message}`, error);
1620
- return {
1621
- ...new Error(message),
1622
- ...error
1623
- };
1655
+ return new Error(message, { cause: error });
1656
+ }
1657
+ //#endregion
1658
+ //#region ../nice-error/src/utils/jsonSafe.ts
1659
+ const CIRCULAR = "[Circular]";
1660
+ const UNSERIALIZABLE = "[Unserializable]";
1661
+ function jsonSafeCopy(value) {
1662
+ const ancestors = [];
1663
+ try {
1664
+ const text = JSON.stringify(value, function(_key, nested) {
1665
+ if (typeof nested === "bigint") return nested.toString();
1666
+ if (typeof nested !== "object" || nested == null) return nested;
1667
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) ancestors.pop();
1668
+ if (ancestors.includes(nested)) return CIRCULAR;
1669
+ ancestors.push(nested);
1670
+ return nested;
1671
+ });
1672
+ return text == null ? void 0 : JSON.parse(text);
1673
+ } catch {
1674
+ return UNSERIALIZABLE;
1675
+ }
1676
+ }
1677
+ /**
1678
+ * `value` itself when `JSON.stringify` accepts it. Otherwise a copy that it does accept: a BigInt
1679
+ * becomes its decimal string and a circular reference becomes `"[Circular]"`.
1680
+ */
1681
+ function jsonSafe(value) {
1682
+ if (typeof value === "bigint") return value.toString();
1683
+ if (typeof value !== "object" || value == null) return value;
1684
+ try {
1685
+ JSON.stringify(value);
1686
+ return value;
1687
+ } catch {
1688
+ return jsonSafeCopy(value);
1689
+ }
1624
1690
  }
1625
1691
  //#endregion
1626
1692
  //#region ../nice-error/package.json
1627
- var version = "0.113.0";
1693
+ var version = "0.115.0";
1628
1694
  //#endregion
1629
1695
  //#region ../nice-error/src/utils/logger.ts
1630
1696
  let activeLogger = {
@@ -1672,18 +1738,6 @@ function warnOfUnversionedCopy() {
1672
1738
  } catch {}
1673
1739
  }
1674
1740
  //#endregion
1675
- //#region ../nice-error/src/NiceError/nice_error.static.ts
1676
- const DUR_OBJ_PACK_PREFIX = "NE_DUROBJ[[";
1677
- const DUR_OBJ_PACK_SUFFIX = "]]NE_DUROBJ";
1678
- /**
1679
- * The domain of the generic wrapper `castNiceError` produces for anything that
1680
- * wasn't already a `NiceError` (native throws, error-like objects, nullish,
1681
- * primitives). `NiceError.isUnhandled` is defined as "belongs to this domain" —
1682
- * i.e. an error we never accounted for and had to wrap. Kept here (not imported
1683
- * from `nice_core_errors`) so `NiceError` can reference it without an import cycle.
1684
- */
1685
- const ERR_CAST_NOT_NICE_DOMAIN = "err_cast_not_nice";
1686
- //#endregion
1687
1741
  //#region ../nice-error/src/utils/packError/causePack.ts
1688
1742
  const causePack = (error) => {
1689
1743
  error._packedState = {
@@ -1862,14 +1916,24 @@ var NiceError = class extends Error {
1862
1916
  if (myIds.length !== otherIds.length) return false;
1863
1917
  return myIds.every((id, i) => id === otherIds[i]);
1864
1918
  }
1865
- toJsonObject() {
1866
- const originError = this.originError ? {
1867
- name: this.originError.name,
1868
- message: this.originError.cleanMessage ?? this.originError.message,
1919
+ _originErrorJson(summary) {
1920
+ if (this.originError == null) return void 0;
1921
+ const name = this.originError.name;
1922
+ const message = this.originError.cleanMessage ?? this.originError.message;
1923
+ if (summary) return {
1924
+ name,
1925
+ message
1926
+ };
1927
+ return {
1928
+ name,
1929
+ message,
1869
1930
  stack: this.originError.stack,
1870
1931
  cause: serializeErrorCause(this.originError.cause),
1871
1932
  ...Array.isArray(this.originError.errors) ? { errors: this.originError.errors.map((e) => serializeErrorCause(e)) } : {}
1872
- } : void 0;
1933
+ };
1934
+ }
1935
+ toJsonObject(options = {}) {
1936
+ const originErrorDetail = options.originError ?? "full";
1873
1937
  const def = {
1874
1938
  domain: this.def.domain,
1875
1939
  allDomains: this.def.allDomains
@@ -1886,6 +1950,10 @@ var NiceError = class extends Error {
1886
1950
  kind: "unhydrated",
1887
1951
  serialized: data.contextState.serialized
1888
1952
  };
1953
+ else if (data.contextState.kind === "serde_unset") contextState = {
1954
+ kind: "serde_unset",
1955
+ value: jsonSafe(data.contextState.value)
1956
+ };
1889
1957
  else contextState = data.contextState;
1890
1958
  errorData[id] = {
1891
1959
  contextState,
@@ -1903,32 +1971,49 @@ var NiceError = class extends Error {
1903
1971
  message: this.cleanMessage,
1904
1972
  httpStatusCode: this.httpStatusCode,
1905
1973
  timeCreated: this.timeCreated,
1906
- ...this.stack != null ? { stack: this.stack } : {},
1907
- originError
1974
+ ...options.stack !== false && this.stack != null ? { stack: this.stack } : {},
1975
+ ...originErrorDetail === "omit" ? {} : { originError: this._originErrorJson(originErrorDetail === "summary") }
1908
1976
  };
1909
1977
  }
1910
1978
  toJSON() {
1911
1979
  return this.toJsonObject();
1912
1980
  }
1913
1981
  /**
1914
- * The **wire form** — {@link toJsonObject} minus the server-only diagnostic fields (`stack`,
1915
- * `originError`) that disclose server internals and fatten the frame. Everything a peer needs to
1916
- * reconstruct a fully-typed error survives — ids, per-id context, rendered message, `isUnhandled`,
1917
- * and the domain definition — so `castNiceError` on the far side yields an error whose `getIds()`,
1918
- * `getContext()`, `message`, and `isUnknownOutcomeRejection(...)` all behave identically.
1982
+ * The **wire form**: what an untrusted peer is sent.
1983
+ *
1984
+ * - An error a domain defines is sent whole, without `stack` and `originError`: its ids, per-id
1985
+ * context, message and domain, so `castNiceError` on the far side rebuilds the same error.
1986
+ * - An error that {@link isUnhandled} is sent as the **sealed failure**: the cast domain's
1987
+ * `unhandled` id, one fixed sentence and status 500. Nothing of what was thrown is kept, since
1988
+ * a cast's message and context are the thrown value itself.
1919
1989
  *
1920
- * Use this whenever an error crosses a trust/observability boundary to an untrusted peer (e.g. a
1921
- * realm reject frame fanned out to every client): the stack must not leave the process, and at
1922
- * high frequency (a cursor-write reject storm) the ~1.5 kB full form is mostly stack. Keep the
1923
- * complete {@link toJsonObject} for server-side logs and hooks.
1990
+ * Keep {@link toJsonObject} for this side's own logs.
1924
1991
  */
1925
1992
  toWireJsonObject() {
1926
- const { stack: _stack, originError: _originError, ...wire } = this.toJsonObject();
1927
- return wire;
1993
+ const wire = this.toJsonObject({
1994
+ stack: false,
1995
+ originError: "omit"
1996
+ });
1997
+ if (!this.isUnhandled) return wire;
1998
+ return {
1999
+ ...wire,
2000
+ ids: [SEALED_FAILURE_ID],
2001
+ errorData: { [SEALED_FAILURE_ID]: {
2002
+ contextState: {
2003
+ kind: "serde_unset",
2004
+ value: void 0
2005
+ },
2006
+ message: SEALED_FAILURE_MESSAGE,
2007
+ httpStatusCode: 500,
2008
+ timeAdded: this.timeCreated
2009
+ } },
2010
+ message: SEALED_FAILURE_MESSAGE,
2011
+ httpStatusCode: 500
2012
+ };
1928
2013
  }
1929
2014
  /**
1930
2015
  * A flat, log-friendly object for telemetry / structured logging — distinct
1931
- * from {@link toJsonObject} (the wire form). Surfaces {@link isUnhandled} so a
2016
+ * from {@link toJsonObject} (the serialized form). Surfaces {@link isUnhandled} so a
1932
2017
  * sink can separate "an error we accounted for" from "one we didn't".
1933
2018
  */
1934
2019
  toStructuredLog() {
@@ -2513,6 +2598,10 @@ const err_cast_not_nice = err_nice.createChildDomain({
2513
2598
  } catch {}
2514
2599
  return `An unhandled type [${typeof jsDataValue}] with value [${inspectedValue ?? "UNSERIALIZABLE"}] was encountered during casting, which is not a valid error type`;
2515
2600
  }
2601
+ }),
2602
+ ["unhandled"]: err({
2603
+ message: SEALED_FAILURE_MESSAGE,
2604
+ httpStatusCode: 500
2516
2605
  })
2517
2606
  }
2518
2607
  });
@@ -2698,6 +2787,15 @@ async function niceTryAsync(fn) {
2698
2787
  }
2699
2788
  }
2700
2789
  //#endregion
2790
+ //#region ../nice-error/src/utils/sealedFailure.ts
2791
+ /**
2792
+ * The sealed failure as an error: what an error that `isUnhandled` is sent as. For a server that
2793
+ * answers with it itself, in place of something it caught and will not send.
2794
+ */
2795
+ function sealedFailure() {
2796
+ return err_cast_not_nice.fromId("unhandled");
2797
+ }
2798
+ //#endregion
2701
2799
  //#region ../nice-wire/src/Connect/err_wire_connect.ts
2702
2800
  /**
2703
2801
  * The Connect layer's error domain. Declared with the types
@@ -2775,11 +2873,13 @@ const err_wire_connect = err_nice.createChildDomain({
2775
2873
  */
2776
2874
  peer_identity_mismatch: err({ message: ({ expected, actual, endpoint }) => `Secure peer identity mismatch: expected envId=${JSON.stringify(expected.envId)}${expected.perId != null ? `, perId=${JSON.stringify(expected.perId)}` : ""}; received envId=${JSON.stringify(actual.envId)}${actual.perId != null ? `, perId=${JSON.stringify(actual.perId)}` : ""}. ${endpoint != null ? `Dialed ${endpoint}. ` : ""}Carrier fallback and automatic redial are parked until an explicit retry.` }),
2777
2875
  /**
2778
- * This runtime has no WebCrypto (`crypto.subtle`), so a secure transport cannot handshake.
2779
- * Raised before any dial. Not a network condition: transport selection moves on to a plain
2780
- * carrier when one is configured, and otherwise automatic redial parks on it.
2876
+ * This runtime cannot do the handshake's cryptography, so a secure transport cannot connect.
2877
+ * Not a network condition: transport selection moves on to a plain carrier when one is
2878
+ * configured, and otherwise automatic redial parks on it. No frame is sent. The first two
2879
+ * reasons are raised before any dial; `algorithm_unsupported` is found at the first key, by
2880
+ * which time a socket carrier has opened its socket.
2781
2881
  */
2782
- crypto_unavailable: err({ message: ({ reason, pageOrigin }) => reason === "insecure_context" ? `A secure connection needs WebCrypto (crypto.subtle), which a browser provides only to a secure context — and this page${pageOrigin != null ? ` (${pageOrigin})` : ""} is not one. Open it over HTTPS or on localhost. Automatic redial is parked.` : "A secure connection needs WebCrypto (crypto.subtle), which this runtime does not provide. Install a WebCrypto polyfill before connecting (on React Native, react-native-quick-crypto), or set `secure: false` on the carrier for a plain connection. Automatic redial is parked." }),
2882
+ crypto_unavailable: err({ message: ({ reason, pageOrigin, algorithm }) => reason === "insecure_context" ? `A secure connection needs WebCrypto (crypto.subtle), which a browser provides only to a secure context — and this page${pageOrigin != null ? ` (${pageOrigin})` : ""} is not one. Open it over HTTPS or on localhost. Automatic redial is parked.` : reason === "algorithm_unsupported" ? `A secure connection needs ${algorithm ?? "a curve"}, which this runtime's WebCrypto (crypto.subtle) does not provide: the browser is older than its support for it. Update the browser, or list a plain carrier (\`secure: false\`) after the secure one. Automatic redial is parked.` : "A secure connection needs WebCrypto (crypto.subtle), which this runtime does not provide. Install a WebCrypto polyfill before connecting (on React Native, react-native-quick-crypto), or set `secure: false` on the carrier for a plain connection. Automatic redial is parked." }),
2783
2883
  /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */
2784
2884
  protocol_unsupported: err({ message: ({ protocolId }) => `Protocol "${protocolId}" cannot speak on this connection — the peer did not advertise "proto:${protocolId}" (or it is not registered here).` }),
2785
2885
  /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; the protocol contract). */
@@ -3068,244 +3168,6 @@ function endpointFromConnectFailure(error) {
3068
3168
  if (error.hasId("peer_identity_mismatch")) return sanitizeEndpoint(error.getContext("peer_identity_mismatch").endpoint);
3069
3169
  }
3070
3170
  //#endregion
3071
- //#region ../nice-wire/src/Connect/ConnectionTransportManager.ts
3072
- /**
3073
- * Preference-ordered transport selection over a shared connection cache — moved from nice-action
3074
- * with the routing params (`RP`), finalized methods
3075
- * (`METHODS`), and connection type (`CONN`) generic. Behavior is byte-for-byte the pre-move
3076
- * logic: strict preference order with parallel warm-up, cache adoption guarded against teardown
3077
- * races, and disconnect-driven eviction.
3078
- */
3079
- var ConnectionTransportManager$1 = class {
3080
- _cache;
3081
- _errors;
3082
- _transports = [];
3083
- constructor(_cache, _errors) {
3084
- this._cache = _cache;
3085
- this._errors = _errors;
3086
- }
3087
- addTransport(transport) {
3088
- this._transports.push(transport);
3089
- }
3090
- /**
3091
- * The highest-priority transport (first declared). Used to label a dispatch's route *before* the
3092
- * transport has finished connecting — so a still-connecting dispatch shows its (expected)
3093
- * destination instead of an "unknown" hop. {@link getReadyTransport} still decides the real winner,
3094
- * and the caller corrects the hop if a lower-priority transport ends up serving it.
3095
- */
3096
- getPreferredTransport() {
3097
- return this._transports[0];
3098
- }
3099
- async getReadyTransport(input) {
3100
- const candidates = [];
3101
- const unavailableTransports = [];
3102
- let cryptoUnavailable;
3103
- for (const transport of this._transports) {
3104
- let cacheKey = null;
3105
- try {
3106
- if (!transport.isAvailable(input)) {
3107
- unavailableTransports.push(transport);
3108
- continue;
3109
- }
3110
- cacheKey = transport.getCacheKey(input);
3111
- if (cacheKey != null) {
3112
- const cached = this._cache.get(cacheKey);
3113
- if (cached != null) {
3114
- if (cached instanceof Promise) {
3115
- candidates.push({
3116
- transport,
3117
- promise: cached,
3118
- cacheKey,
3119
- fresh: false
3120
- });
3121
- continue;
3122
- }
3123
- candidates.push({
3124
- transport,
3125
- promise: Promise.resolve({
3126
- ...cached,
3127
- transport
3128
- }),
3129
- cacheKey,
3130
- fresh: false
3131
- });
3132
- break;
3133
- }
3134
- }
3135
- const statusInfo = transport.getTransport(input);
3136
- if (statusInfo.status === "ready") {
3137
- const readyData = statusInfo.readyData;
3138
- if (cacheKey != null) {
3139
- const key = cacheKey;
3140
- const entry = {
3141
- methods: readyData,
3142
- transport
3143
- };
3144
- this._cache.set(key, entry);
3145
- readyData.addOnDisconnectListener?.(() => {
3146
- if (this._cache.get(key) === entry) this._cache.delete(key);
3147
- });
3148
- }
3149
- candidates.push({
3150
- transport,
3151
- promise: Promise.resolve({
3152
- methods: readyData,
3153
- transport
3154
- }),
3155
- cacheKey,
3156
- fresh: true
3157
- });
3158
- break;
3159
- }
3160
- if (statusInfo.status === "unsupported") {
3161
- unavailableTransports.push(transport);
3162
- continue;
3163
- }
3164
- if (statusInfo.status === "initializing") {
3165
- const key = cacheKey;
3166
- const promise = statusInfo.initializationPromise.then((info) => {
3167
- if (info.status === "failed") throw info.error;
3168
- if (info.status === "unsupported") throw this._errors.unsupported([transport.type]);
3169
- const readyData = info.readyData;
3170
- const entry = {
3171
- methods: readyData,
3172
- transport
3173
- };
3174
- if (key != null) if (this._cache.get(key) === promise) {
3175
- this._cache.set(key, entry);
3176
- readyData.addOnDisconnectListener?.(() => {
3177
- if (this._cache.get(key) === entry) this._cache.delete(key);
3178
- });
3179
- } else readyData.disconnect?.();
3180
- return entry;
3181
- }).catch((e) => {
3182
- if (key != null && this._cache.get(key) === promise) this._cache.delete(key);
3183
- throw e;
3184
- });
3185
- promise.catch(() => {});
3186
- if (key != null) this._cache.set(key, promise);
3187
- candidates.push({
3188
- transport,
3189
- promise,
3190
- cacheKey: key,
3191
- fresh: true
3192
- });
3193
- }
3194
- } catch (e) {
3195
- if (isDialUnavailable$1(e)) {
3196
- if (candidates.length === 0) throw e;
3197
- unavailableTransports.push(transport);
3198
- continue;
3199
- }
3200
- if (isCryptoUnavailable(e)) {
3201
- cryptoUnavailable ??= e;
3202
- continue;
3203
- }
3204
- const failed = Promise.reject(e);
3205
- failed.catch(() => {});
3206
- candidates.push({
3207
- transport,
3208
- promise: failed,
3209
- cacheKey,
3210
- fresh: true,
3211
- callerThrew: true
3212
- });
3213
- }
3214
- }
3215
- if (candidates.length === 0) {
3216
- if (cryptoUnavailable != null) throw cryptoUnavailable;
3217
- if (unavailableTransports.length > 0) throw this._errors.unsupported(unavailableTransports.map((t) => t.type));
3218
- throw this._errors.notFound(input);
3219
- }
3220
- let lastError;
3221
- let lastTransport;
3222
- let lastCallerThrew = false;
3223
- for (const candidate of candidates) {
3224
- let ready;
3225
- try {
3226
- ready = await candidate.promise;
3227
- } catch (e) {
3228
- if (isTerminalSelectionError(e)) {
3229
- this._abandonWarmUps(candidates, candidate);
3230
- throw this._withDialedEndpoint(e, candidate.transport, input);
3231
- }
3232
- lastError = e;
3233
- lastTransport = candidate.transport;
3234
- lastCallerThrew = candidate.callerThrew === true;
3235
- continue;
3236
- }
3237
- ready.methods.onSelected?.();
3238
- return ready;
3239
- }
3240
- if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch") || lastError.hasId("protocol_version_mismatch") || lastError.hasId("peer_identity_mismatch"))) throw lastError;
3241
- if (lastCallerThrew && !err_wire_connect.isExact(lastError)) throw lastError;
3242
- throw this._errors.initializationFailed(input, {
3243
- cause: describeTransportFailure(lastError),
3244
- endpoint: endpointFromConnectFailure(lastError) ?? routeEndpoint(lastTransport, input),
3245
- kind: classifyConnectFailure(lastError),
3246
- origin: lastError
3247
- });
3248
- }
3249
- /**
3250
- * Close the parallel warm-ups this selection started besides `failed`. Each one's cache slot is
3251
- * released so a later dispatch re-dials; a warm-up still connecting closes itself when it lands.
3252
- */
3253
- _abandonWarmUps(candidates, failed) {
3254
- for (const candidate of candidates) {
3255
- if (candidate === failed || !candidate.fresh) continue;
3256
- const key = candidate.cacheKey;
3257
- if (key != null && this._cache.get(key) === candidate.promise) this._cache.delete(key);
3258
- candidate.promise.then((entry) => {
3259
- if (key == null) {
3260
- entry.methods.disconnect?.();
3261
- return;
3262
- }
3263
- const cached = this._cache.get(key);
3264
- if (cached != null && !(cached instanceof Promise) && cached.methods === entry.methods) {
3265
- this._cache.delete(key);
3266
- entry.methods.disconnect?.();
3267
- }
3268
- }, () => {});
3269
- }
3270
- }
3271
- /** Attach the sanitized dialed endpoint to a peer-identity mismatch that lacks one. */
3272
- _withDialedEndpoint(error, transport, input) {
3273
- if (!err_wire_connect.isExact(error) || !error.hasId("peer_identity_mismatch")) return error;
3274
- const context = error.getContext("peer_identity_mismatch");
3275
- if (context.endpoint != null) return error;
3276
- const endpoint = routeEndpoint(transport, input);
3277
- if (endpoint == null) return error;
3278
- return err_wire_connect.fromId("peer_identity_mismatch", {
3279
- ...context,
3280
- endpoint
3281
- }).withOriginError(error);
3282
- }
3283
- };
3284
- const isDialUnavailable$1 = (error) => err_wire_connect.isExact(error) && error.hasId("dial_unavailable");
3285
- const isCryptoUnavailable = (error) => err_wire_connect.isExact(error) && error.hasId("crypto_unavailable");
3286
- const isTerminalSelectionError = (error) => err_wire_connect.isExact(error) && (error.hasId("peer_identity_mismatch") || error.hasId("protocol_version_mismatch"));
3287
- /** The transport's sanitized route URL for diagnostics; a throwing route resolver yields none. */
3288
- function routeEndpoint(transport, input) {
3289
- if (transport == null) return void 0;
3290
- try {
3291
- return sanitizeEndpoint(transport.getRouteInfo(input)?.url);
3292
- } catch {
3293
- return;
3294
- }
3295
- }
3296
- /**
3297
- * A short, human-readable reason for a transport failing to connect — surfaced in the
3298
- * consumer's initialization-failed message so the caller sees *why* (e.g. a rejected handshake) rather
3299
- * than a bare "not ready". The full error is still attached as the origin error for the complete
3300
- * chain/stack.
3301
- */
3302
- function describeTransportFailure(error) {
3303
- if (error == null) return void 0;
3304
- if (error instanceof Error) return error.message;
3305
- if (typeof error === "string") return error;
3306
- return String(error);
3307
- }
3308
- //#endregion
3309
3171
  //#region ../nice-util/src/data_type/string/nullEmpty.ts
3310
3172
  const notNullEmpty = (str) => {
3311
3173
  return str != null && str.length > 0;
@@ -4136,9 +3998,43 @@ function createTypedStorage({ storageAdapter, schemas, onInvalid }) {
4136
3998
  };
4137
3999
  }
4138
4000
  //#endregion
4001
+ //#region ../nice-util/src/crypto/webCryptoCurveSupport.ts
4002
+ const UNSUPPORTED_NAME = "WebCryptoAlgorithmUnsupportedError";
4003
+ /**
4004
+ * `crypto.subtle` exists but refused the curve itself: a browser from before it shipped the
4005
+ * algorithm (Chrome before 137 has no Ed25519).
4006
+ */
4007
+ var WebCryptoAlgorithmUnsupportedError = class extends Error {
4008
+ algorithm;
4009
+ constructor(algorithm, cause) {
4010
+ super(`This runtime's WebCrypto does not support ${algorithm}.`, { cause });
4011
+ this.name = UNSUPPORTED_NAME;
4012
+ this.algorithm = algorithm;
4013
+ }
4014
+ };
4015
+ /** Matches by shape, so a second copy of this package in a bundle still matches. */
4016
+ function isWebCryptoAlgorithmUnsupportedError(error) {
4017
+ return error instanceof Error && error.name === UNSUPPORTED_NAME && "algorithm" in error && (error.algorithm === "Ed25519" || error.algorithm === "X25519");
4018
+ }
4019
+ function isNotSupportedError(error) {
4020
+ return typeof error === "object" && error != null && "name" in error && error.name === "NotSupportedError";
4021
+ }
4022
+ /**
4023
+ * Run one `crypto.subtle` call that names `algorithm`. A runtime answers an algorithm it does not
4024
+ * have with a `NotSupportedError`, which says nothing of which one: rethrown here with its name.
4025
+ */
4026
+ async function withCurveSupport(algorithm, call) {
4027
+ try {
4028
+ return await call();
4029
+ } catch (error) {
4030
+ if (isNotSupportedError(error)) throw new WebCryptoAlgorithmUnsupportedError(algorithm, error);
4031
+ throw error;
4032
+ }
4033
+ }
4034
+ //#endregion
4139
4035
  //#region ../nice-util/src/crypto/ed25519/generateEd25519KeyPair.ts
4140
4036
  const generateEd25519KeyPair = async () => {
4141
- return await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]);
4037
+ return await withCurveSupport("Ed25519", () => crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]));
4142
4038
  };
4143
4039
  //#endregion
4144
4040
  //#region ../nice-util/src/core/createDataStringConverter_stringToObject.ts
@@ -4816,10 +4712,10 @@ const convertX25519FormattedStringToSerializedKeyData = (input) => {
4816
4712
  //#region ../nice-util/src/crypto/ed25519/importEd25519Key.ts
4817
4713
  const fromBase64$1 = async (dataBase64, keyUsage, extractable) => {
4818
4714
  const keyBuffer = Uint8Array.from(base64$1.decode(dataBase64));
4819
- return await crypto.subtle.importKey("raw", keyBuffer, { name: "Ed25519" }, extractable, keyUsage);
4715
+ return await withCurveSupport("Ed25519", () => crypto.subtle.importKey("raw", keyBuffer, { name: "Ed25519" }, extractable, keyUsage));
4820
4716
  };
4821
4717
  const fromJwk$1 = async (jwk, keyUsage, extractable = true) => {
4822
- return await crypto.subtle.importKey("jwk", jwk, { name: "Ed25519" }, extractable, keyUsage);
4718
+ return await withCurveSupport("Ed25519", () => crypto.subtle.importKey("jwk", jwk, { name: "Ed25519" }, extractable, keyUsage));
4823
4719
  };
4824
4720
  const fromSerializedObject$1 = async (serialized, keyUsage, extractable = true) => {
4825
4721
  if (serialized.format === "jwk") return await fromJwk$1(serialized.data, keyUsage, extractable);
@@ -4886,16 +4782,16 @@ const verifyWithKeyEd25519 = async ({ challenge, signatureBase64, publicKey }) =
4886
4782
  //#endregion
4887
4783
  //#region ../nice-util/src/crypto/x25519/generateX25519KeyPair.ts
4888
4784
  const generateX25519KeyPair = async () => {
4889
- return await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveKey", "deriveBits"]);
4785
+ return await withCurveSupport("X25519", () => crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveKey", "deriveBits"]));
4890
4786
  };
4891
4787
  //#endregion
4892
4788
  //#region ../nice-util/src/crypto/x25519/importX25519Key.ts
4893
4789
  const fromBase64 = async (dataBase64, keyUsage, extractable) => {
4894
4790
  const keyBuffer = Uint8Array.from(base64$1.decode(dataBase64));
4895
- return await crypto.subtle.importKey("raw", keyBuffer, { name: "X25519" }, extractable, keyUsage);
4791
+ return await withCurveSupport("X25519", () => crypto.subtle.importKey("raw", keyBuffer, { name: "X25519" }, extractable, keyUsage));
4896
4792
  };
4897
4793
  const fromJwk = async (jwk, keyUsage, extractable = true) => {
4898
- return await crypto.subtle.importKey("jwk", jwk, { name: "X25519" }, extractable, keyUsage);
4794
+ return await withCurveSupport("X25519", () => crypto.subtle.importKey("jwk", jwk, { name: "X25519" }, extractable, keyUsage));
4899
4795
  };
4900
4796
  const fromSerializedObject = async (serialized, keyUsage, extractable = true) => {
4901
4797
  if (serialized.format === "jwk") return await fromJwk(serialized.data, keyUsage, extractable);
@@ -5746,6 +5642,276 @@ function unrefTimer(timer) {
5746
5642
  if (typeof timer !== "number") timer.unref?.();
5747
5643
  }
5748
5644
  //#endregion
5645
+ //#region ../nice-wire/src/Connect/webCryptoPreflight.ts
5646
+ /**
5647
+ * The one check before a secure transport dials. A browser gives `crypto.subtle` only to a secure
5648
+ * context (HTTPS, or localhost), and some runtimes ship none until a polyfill is installed; either
5649
+ * way the handshake cannot run, and no retry will change that.
5650
+ */
5651
+ function assertWebCryptoAvailable() {
5652
+ const runtime = globalThis;
5653
+ if (runtime.crypto?.subtle != null) return;
5654
+ if (runtime.isSecureContext === false) throw err_wire_connect.fromId("crypto_unavailable", {
5655
+ reason: "insecure_context",
5656
+ pageOrigin: runtime.location?.origin
5657
+ });
5658
+ throw err_wire_connect.fromId("crypto_unavailable", { reason: "no_webcrypto" });
5659
+ }
5660
+ /**
5661
+ * The same condition found later: `crypto.subtle` exists and passed the check above, then refused
5662
+ * a curve at the first key. Returns any other failure as it was given.
5663
+ */
5664
+ function asCryptoUnavailable(error) {
5665
+ if (!isWebCryptoAlgorithmUnsupportedError(error)) return error;
5666
+ return err_wire_connect.fromId("crypto_unavailable", {
5667
+ reason: "algorithm_unsupported",
5668
+ algorithm: error.algorithm
5669
+ }).withOriginError(error);
5670
+ }
5671
+ //#endregion
5672
+ //#region ../nice-wire/src/Connect/ConnectionTransportManager.ts
5673
+ /**
5674
+ * Preference-ordered transport selection over a shared connection cache — moved from nice-action
5675
+ * with the routing params (`RP`), finalized methods
5676
+ * (`METHODS`), and connection type (`CONN`) generic. Behavior is byte-for-byte the pre-move
5677
+ * logic: strict preference order with parallel warm-up, cache adoption guarded against teardown
5678
+ * races, and disconnect-driven eviction.
5679
+ */
5680
+ var ConnectionTransportManager$1 = class {
5681
+ _cache;
5682
+ _errors;
5683
+ _transports = [];
5684
+ constructor(_cache, _errors) {
5685
+ this._cache = _cache;
5686
+ this._errors = _errors;
5687
+ }
5688
+ addTransport(transport) {
5689
+ this._transports.push(transport);
5690
+ }
5691
+ /**
5692
+ * The highest-priority transport (first declared). Used to label a dispatch's route *before* the
5693
+ * transport has finished connecting — so a still-connecting dispatch shows its (expected)
5694
+ * destination instead of an "unknown" hop. {@link getReadyTransport} still decides the real winner,
5695
+ * and the caller corrects the hop if a lower-priority transport ends up serving it.
5696
+ */
5697
+ getPreferredTransport() {
5698
+ return this._transports[0];
5699
+ }
5700
+ async getReadyTransport(input) {
5701
+ const candidates = [];
5702
+ const unavailableTransports = [];
5703
+ let cryptoUnavailable;
5704
+ for (const transport of this._transports) {
5705
+ let cacheKey = null;
5706
+ try {
5707
+ if (!transport.isAvailable(input)) {
5708
+ unavailableTransports.push(transport);
5709
+ continue;
5710
+ }
5711
+ cacheKey = transport.getCacheKey(input);
5712
+ if (cacheKey != null) {
5713
+ const cached = this._cache.get(cacheKey);
5714
+ if (cached != null) {
5715
+ if (cached instanceof Promise) {
5716
+ candidates.push({
5717
+ transport,
5718
+ promise: cached,
5719
+ cacheKey,
5720
+ fresh: false
5721
+ });
5722
+ continue;
5723
+ }
5724
+ candidates.push({
5725
+ transport,
5726
+ promise: Promise.resolve({
5727
+ ...cached,
5728
+ transport
5729
+ }),
5730
+ cacheKey,
5731
+ fresh: false
5732
+ });
5733
+ break;
5734
+ }
5735
+ }
5736
+ const statusInfo = transport.getTransport(input);
5737
+ if (statusInfo.status === "ready") {
5738
+ const readyData = statusInfo.readyData;
5739
+ if (cacheKey != null) {
5740
+ const key = cacheKey;
5741
+ const entry = {
5742
+ methods: readyData,
5743
+ transport
5744
+ };
5745
+ this._cache.set(key, entry);
5746
+ readyData.addOnDisconnectListener?.(() => {
5747
+ if (this._cache.get(key) === entry) this._cache.delete(key);
5748
+ });
5749
+ }
5750
+ candidates.push({
5751
+ transport,
5752
+ promise: Promise.resolve({
5753
+ methods: readyData,
5754
+ transport
5755
+ }),
5756
+ cacheKey,
5757
+ fresh: true
5758
+ });
5759
+ break;
5760
+ }
5761
+ if (statusInfo.status === "unsupported") {
5762
+ unavailableTransports.push(transport);
5763
+ continue;
5764
+ }
5765
+ if (statusInfo.status === "initializing") {
5766
+ const key = cacheKey;
5767
+ const promise = statusInfo.initializationPromise.then((info) => {
5768
+ if (info.status === "failed") throw info.error;
5769
+ if (info.status === "unsupported") throw this._errors.unsupported([transport.type]);
5770
+ const readyData = info.readyData;
5771
+ const entry = {
5772
+ methods: readyData,
5773
+ transport
5774
+ };
5775
+ if (key != null) if (this._cache.get(key) === promise) {
5776
+ this._cache.set(key, entry);
5777
+ readyData.addOnDisconnectListener?.(() => {
5778
+ if (this._cache.get(key) === entry) this._cache.delete(key);
5779
+ });
5780
+ } else readyData.disconnect?.();
5781
+ return entry;
5782
+ }).catch((e) => {
5783
+ if (key != null && this._cache.get(key) === promise) this._cache.delete(key);
5784
+ throw asCryptoUnavailable(e);
5785
+ });
5786
+ promise.catch(() => {});
5787
+ if (key != null) this._cache.set(key, promise);
5788
+ candidates.push({
5789
+ transport,
5790
+ promise,
5791
+ cacheKey: key,
5792
+ fresh: true
5793
+ });
5794
+ }
5795
+ } catch (e) {
5796
+ if (isDialUnavailable$1(e)) {
5797
+ if (candidates.length === 0) throw e;
5798
+ unavailableTransports.push(transport);
5799
+ continue;
5800
+ }
5801
+ if (isCryptoUnavailable(e)) {
5802
+ cryptoUnavailable ??= e;
5803
+ continue;
5804
+ }
5805
+ const failed = Promise.reject(e);
5806
+ failed.catch(() => {});
5807
+ candidates.push({
5808
+ transport,
5809
+ promise: failed,
5810
+ cacheKey,
5811
+ fresh: true,
5812
+ callerThrew: true
5813
+ });
5814
+ }
5815
+ }
5816
+ if (candidates.length === 0) {
5817
+ if (cryptoUnavailable != null) throw cryptoUnavailable;
5818
+ if (unavailableTransports.length > 0) throw this._errors.unsupported(unavailableTransports.map((t) => t.type));
5819
+ throw this._errors.notFound(input);
5820
+ }
5821
+ let lastError;
5822
+ let lastTransport;
5823
+ let lastCallerThrew = false;
5824
+ for (const candidate of candidates) {
5825
+ let ready;
5826
+ try {
5827
+ ready = await candidate.promise;
5828
+ } catch (e) {
5829
+ if (isTerminalSelectionError(e)) {
5830
+ this._abandonWarmUps(candidates, candidate);
5831
+ throw this._withDialedEndpoint(e, candidate.transport, input);
5832
+ }
5833
+ if (isCryptoUnavailable(e)) {
5834
+ cryptoUnavailable ??= e;
5835
+ continue;
5836
+ }
5837
+ lastError = e;
5838
+ lastTransport = candidate.transport;
5839
+ lastCallerThrew = candidate.callerThrew === true;
5840
+ continue;
5841
+ }
5842
+ ready.methods.onSelected?.();
5843
+ return ready;
5844
+ }
5845
+ if (lastTransport == null && cryptoUnavailable != null) throw cryptoUnavailable;
5846
+ if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch") || lastError.hasId("protocol_version_mismatch") || lastError.hasId("peer_identity_mismatch"))) throw lastError;
5847
+ if (lastCallerThrew && !err_wire_connect.isExact(lastError)) throw lastError;
5848
+ throw this._errors.initializationFailed(input, {
5849
+ cause: describeTransportFailure(lastError),
5850
+ endpoint: endpointFromConnectFailure(lastError) ?? routeEndpoint(lastTransport, input),
5851
+ kind: classifyConnectFailure(lastError),
5852
+ origin: lastError
5853
+ });
5854
+ }
5855
+ /**
5856
+ * Close the parallel warm-ups this selection started besides `failed`. Each one's cache slot is
5857
+ * released so a later dispatch re-dials; a warm-up still connecting closes itself when it lands.
5858
+ */
5859
+ _abandonWarmUps(candidates, failed) {
5860
+ for (const candidate of candidates) {
5861
+ if (candidate === failed || !candidate.fresh) continue;
5862
+ const key = candidate.cacheKey;
5863
+ if (key != null && this._cache.get(key) === candidate.promise) this._cache.delete(key);
5864
+ candidate.promise.then((entry) => {
5865
+ if (key == null) {
5866
+ entry.methods.disconnect?.();
5867
+ return;
5868
+ }
5869
+ const cached = this._cache.get(key);
5870
+ if (cached != null && !(cached instanceof Promise) && cached.methods === entry.methods) {
5871
+ this._cache.delete(key);
5872
+ entry.methods.disconnect?.();
5873
+ }
5874
+ }, () => {});
5875
+ }
5876
+ }
5877
+ /** Attach the sanitized dialed endpoint to a peer-identity mismatch that lacks one. */
5878
+ _withDialedEndpoint(error, transport, input) {
5879
+ if (!err_wire_connect.isExact(error) || !error.hasId("peer_identity_mismatch")) return error;
5880
+ const context = error.getContext("peer_identity_mismatch");
5881
+ if (context.endpoint != null) return error;
5882
+ const endpoint = routeEndpoint(transport, input);
5883
+ if (endpoint == null) return error;
5884
+ return err_wire_connect.fromId("peer_identity_mismatch", {
5885
+ ...context,
5886
+ endpoint
5887
+ }).withOriginError(error);
5888
+ }
5889
+ };
5890
+ const isDialUnavailable$1 = (error) => err_wire_connect.isExact(error) && error.hasId("dial_unavailable");
5891
+ const isCryptoUnavailable = (error) => err_wire_connect.isExact(error) && error.hasId("crypto_unavailable");
5892
+ const isTerminalSelectionError = (error) => err_wire_connect.isExact(error) && (error.hasId("peer_identity_mismatch") || error.hasId("protocol_version_mismatch"));
5893
+ /** The transport's sanitized route URL for diagnostics; a throwing route resolver yields none. */
5894
+ function routeEndpoint(transport, input) {
5895
+ if (transport == null) return void 0;
5896
+ try {
5897
+ return sanitizeEndpoint(transport.getRouteInfo(input)?.url);
5898
+ } catch {
5899
+ return;
5900
+ }
5901
+ }
5902
+ /**
5903
+ * A short, human-readable reason for a transport failing to connect — surfaced in the
5904
+ * consumer's initialization-failed message so the caller sees *why* (e.g. a rejected handshake) rather
5905
+ * than a bare "not ready". The full error is still attached as the origin error for the complete
5906
+ * chain/stack.
5907
+ */
5908
+ function describeTransportFailure(error) {
5909
+ if (error == null) return void 0;
5910
+ if (error instanceof Error) return error.message;
5911
+ if (typeof error === "string") return error;
5912
+ return String(error);
5913
+ }
5914
+ //#endregion
5749
5915
  //#region ../../node_modules/nanoid/url-alphabet/index.js
5750
5916
  let urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
5751
5917
  //#endregion
@@ -6430,7 +6596,7 @@ const isDialUnavailable = (e) => err_wire_connect.isExact(e) && e.hasId("dial_un
6430
6596
  * right now ({@link isDialUnavailable}), or the peer rejected the handshake with
6431
6597
  * `identity_pin_mismatch` (the peer has a different key pinned) or
6432
6598
  * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation), or this
6433
- * runtime has no WebCrypto to handshake with at all (`crypto_unavailable`).
6599
+ * runtime cannot do the handshake's cryptography at all (`crypto_unavailable`).
6434
6600
  * Parking is not terminal: the next explicit `connect()`/dispatch may try again after the app has
6435
6601
  * upgraded or changed endpoints. Other handshake rejections (e.g. a dictionary mismatch) retain
6436
6602
  * the existing retry behavior because a matching deploy can heal them.
@@ -9776,22 +9942,6 @@ function onChannelClosed(disconnectListeners, lane) {
9776
9942
  lane.onDetach?.();
9777
9943
  }
9778
9944
  //#endregion
9779
- //#region ../nice-wire/src/Connect/webCryptoPreflight.ts
9780
- /**
9781
- * The one check before a secure transport dials. A browser gives `crypto.subtle` only to a secure
9782
- * context (HTTPS, or localhost), and some runtimes ship none until a polyfill is installed; either
9783
- * way the handshake cannot run, and no retry will change that.
9784
- */
9785
- function assertWebCryptoAvailable() {
9786
- const runtime = globalThis;
9787
- if (runtime.crypto?.subtle != null) return;
9788
- if (runtime.isSecureContext === false) throw err_wire_connect.fromId("crypto_unavailable", {
9789
- reason: "insecure_context",
9790
- pageOrigin: runtime.location?.origin
9791
- });
9792
- throw err_wire_connect.fromId("crypto_unavailable", { reason: "no_webcrypto" });
9793
- }
9794
- //#endregion
9795
9945
  //#region ../nice-wire/src/Connect/TransportConnection.ts
9796
9946
  let transportOrd = 0;
9797
9947
  /**
@@ -10392,7 +10542,9 @@ function makeSession(carrier, source, insId) {
10392
10542
  if (reply.k === "err") return {
10393
10543
  ok: false,
10394
10544
  reason: "peer_error",
10395
- message: reply.message
10545
+ message: reply.message,
10546
+ id: reply.id,
10547
+ peerReason: reply.reason
10396
10548
  };
10397
10549
  const replyWire = await extractReplyWire(state, reply);
10398
10550
  if (replyWire === void 0) return {
@@ -10513,6 +10665,23 @@ function asString(frame) {
10513
10665
  return textDecoder$1.decode(frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame);
10514
10666
  }
10515
10667
  //#endregion
10668
+ //#region ../nice-wire/src/Connect/requestOrigin.ts
10669
+ /**
10670
+ * The `403` for a request whose `Origin` is not allowed, or `undefined` when it may proceed. A
10671
+ * request that names no `Origin` passes: only a browser sends one, so this stops another site's
10672
+ * page, not a native or server client.
10673
+ */
10674
+ function refuseUnlistedOrigin(request, allowedOrigins) {
10675
+ if (allowedOrigins == null) return void 0;
10676
+ const origin = request.headers.get("Origin");
10677
+ if (origin == null) return void 0;
10678
+ if (typeof allowedOrigins === "function" ? allowedOrigins(origin) : allowedOrigins.includes(origin)) return void 0;
10679
+ return new Response(JSON.stringify({ error: "origin not allowed" }), {
10680
+ status: 403,
10681
+ headers: { "Content-Type": "application/json" }
10682
+ });
10683
+ }
10684
+ //#endregion
10516
10685
  //#region ../nice-wire/src/SecureSession/acceptorSecureSession.ts
10517
10686
  /**
10518
10687
  * The acceptor (accept-in) counterpart to the connector's `establishLinkSession`: one connection's
@@ -11230,10 +11399,18 @@ var WireExchangeAcceptor = class {
11230
11399
  securityLevel,
11231
11400
  encrypted: crypto != null
11232
11401
  });
11233
- if (!laneReply.ok) return {
11234
- k: "err",
11235
- message: laneReply.message
11236
- };
11402
+ if (!laneReply.ok) {
11403
+ const { message, id, reason } = laneReply;
11404
+ return id == null ? {
11405
+ k: "err",
11406
+ message
11407
+ } : {
11408
+ k: "err",
11409
+ message,
11410
+ id,
11411
+ reason
11412
+ };
11413
+ }
11237
11414
  if (crypto != null) return {
11238
11415
  k: "act",
11239
11416
  c: bytesToBase64(await crypto.encryptFrame(textEncoder.encode(JSON.stringify(laneReply.wire))))
@@ -11892,26 +12069,32 @@ var ActionPayload_Result = class extends ActionPayload {
11892
12069
  }
11893
12070
  }
11894
12071
  toJsonObject() {
11895
- const wireResult = this.result.ok ? {
11896
- ok: true,
11897
- output: this.context.schema.serializeOutput(this.result.output)
11898
- } : {
11899
- ok: false,
11900
- expected: this.result.expected,
11901
- error: this.result.error.toJsonObject()
12072
+ if (this.result.ok) return {
12073
+ ...this.toBaseJsonObject(),
12074
+ result: {
12075
+ ok: true,
12076
+ output: this.context.schema.serializeOutput(this.result.output)
12077
+ },
12078
+ outputHash: this.outputHash
11902
12079
  };
12080
+ const error = this.result.error.toWireJsonObject();
11903
12081
  return {
11904
12082
  ...this.toBaseJsonObject(),
11905
- result: wireResult,
11906
- outputHash: this.outputHash
12083
+ result: {
12084
+ ok: false,
12085
+ expected: this.result.expected,
12086
+ error
12087
+ },
12088
+ outputHash: hashPayloadData(error.message)
11907
12089
  };
11908
12090
  }
11909
12091
  toJsonString() {
11910
12092
  return JSON.stringify(this.toJsonObject());
11911
12093
  }
11912
12094
  toHttpResponse({ useErrorStatus = true } = {}) {
11913
- return new Response(this.toJsonString(), {
11914
- status: this.result.ok ? 200 : useErrorStatus ? this.result.error.httpStatusCode : 500,
12095
+ const json = this.toJsonObject();
12096
+ return new Response(JSON.stringify(json), {
12097
+ status: json.result.ok ? 200 : useErrorStatus ? json.result.error.httpStatusCode : 500,
11915
12098
  headers: { "Content-Type": "application/json" }
11916
12099
  });
11917
12100
  }
@@ -12342,6 +12525,26 @@ const err_nice_action = err_nice.createChildDomain({
12342
12525
  }
12343
12526
  });
12344
12527
  //#endregion
12528
+ //#region ../nice-action/src/utils/actionPayloadContextProblem.ts
12529
+ function isRouteItem(item) {
12530
+ return typeof item === "object" && item != null && "runtime" in item && typeof item.runtime === "object" && item.runtime != null;
12531
+ }
12532
+ /**
12533
+ * What stops a payload's `context` from being hydrated, or `undefined` when nothing does. `cuid`,
12534
+ * `timeCreated` and `originClient` may be absent; `routing` may not.
12535
+ */
12536
+ function actionPayloadContextProblem(context) {
12537
+ if (typeof context !== "object" || context == null) return "missing";
12538
+ if (!("routing" in context) || !Array.isArray(context.routing)) return "routing";
12539
+ if (!context.routing.every(isRouteItem)) return "route_item";
12540
+ if ("cuid" in context && context.cuid != null && typeof context.cuid !== "string") return "cuid";
12541
+ if ("originClient" in context && context.originClient != null && typeof context.originClient !== "object") return "origin_client";
12542
+ }
12543
+ /** Whether a payload's `context` can be hydrated. */
12544
+ function hasHydratableContext(payload) {
12545
+ return "context" in payload && actionPayloadContextProblem(payload.context) == null;
12546
+ }
12547
+ //#endregion
12345
12548
  //#region ../nice-action/src/utils/isAction_Base_JsonObject.ts
12346
12549
  const isAction_Base_JsonObject = (obj) => {
12347
12550
  return typeof obj === "object" && obj !== null && typeof obj.domain === "string" && typeof obj.id === "string" && typeof obj.form === "string";
@@ -12349,7 +12552,7 @@ const isAction_Base_JsonObject = (obj) => {
12349
12552
  //#endregion
12350
12553
  //#region ../nice-action/src/utils/isActionPayload_Result_JsonObject.ts
12351
12554
  const isActionPayload_Result_JsonObject = (obj) => {
12352
- return isAction_Base_JsonObject(obj) && obj.result != null && obj.form === "data" && obj.type === "result";
12555
+ return isAction_Base_JsonObject(obj) && "result" in obj && obj.result != null && obj.form === "data" && "type" in obj && obj.type === "result" && hasHydratableContext(obj);
12353
12556
  };
12354
12557
  //#endregion
12355
12558
  //#region ../../node_modules/http-status-codes/build/cjs/legacy.js
@@ -14038,12 +14241,12 @@ const getAssumedRuntimeInfo = () => {
14038
14241
  //#endregion
14039
14242
  //#region ../nice-action/src/utils/isActionPayload_Progress_JsonObject.ts
14040
14243
  const isActionPayload_Progress_JsonObject = (obj) => {
14041
- return isAction_Base_JsonObject(obj) && "progress" in obj && obj.form === "data" && obj.type === "progress";
14244
+ return isAction_Base_JsonObject(obj) && "progress" in obj && obj.form === "data" && "type" in obj && obj.type === "progress" && hasHydratableContext(obj);
14042
14245
  };
14043
14246
  //#endregion
14044
14247
  //#region ../nice-action/src/utils/isActionPayload_Request_JsonObject.ts
14045
14248
  const isActionPayload_Request_JsonObject = (obj) => {
14046
- return isAction_Base_JsonObject(obj) && obj.form === "data" && obj.type === "request";
14249
+ return isAction_Base_JsonObject(obj) && obj.form === "data" && "type" in obj && obj.type === "request" && hasHydratableContext(obj);
14047
14250
  };
14048
14251
  //#endregion
14049
14252
  //#region ../nice-action/src/utils/isActionPayload_Any_JsonObject.ts
@@ -14083,6 +14286,14 @@ const err_nice_transport = err_nice_action.createChildDomain({
14083
14286
  httpStatusCode: ({ httpStatusCode }) => httpStatusCode ?? 500
14084
14287
  }),
14085
14288
  ["invalid_action_response"]: err({ message: ({ actionId }) => `Invalid action response JSON structure for action "${actionId}"` }),
14289
+ /**
14290
+ * The peer was reached and refused the request before any action ran. Over HTTP the call rejects
14291
+ * with this; on a socket it is the error of a failed result.
14292
+ */
14293
+ ["action_not_served"]: err({
14294
+ message: ({ domain, actionId, reason }) => `The peer does not serve action "${domain}:${actionId}" (${reason}).`,
14295
+ httpStatusCode: 404
14296
+ }),
14086
14297
  ["reliable_outbox_overflow"]: err({ message: ({ actionId, maxUnacked }) => `Reliable outbox for action "${actionId}" exceeded its unacked window (${maxUnacked}) — the peer is not acknowledging. Send rejected to bound memory.` }),
14087
14298
  ["reliable_delivery_abandoned"]: err({ message: ({ actionId, timeout }) => `Reliable action "${actionId}" was abandoned: not acknowledged within its ${timeout}ms delivery deadline (or swept with an aborted earlier frame on its stream). The stream skips past it and continues.` }),
14088
14299
  ["reliable_stream_closed"]: err({ message: ({ actionId, streamId }) => `Reliable action "${actionId}" was abandoned because its stream ("${streamId}") was closed (closeReliableStream) while the send was still unacknowledged.` })
@@ -15148,9 +15359,13 @@ var ActionRuntime = class {
15148
15359
  }
15149
15360
  /** @internal Hydrate a wire request and attach receiver-owned metadata before application dispatch. */
15150
15361
  async _handleActionPayloadWireFromReceiver(wire, metadata) {
15362
+ return this.handleActionPayload(this._hydrateWireFromReceiver(wire, metadata));
15363
+ }
15364
+ /** @internal Throws for a wire this runtime cannot hydrate: an unknown domain or action. */
15365
+ _hydrateWireFromReceiver(wire, metadata) {
15151
15366
  const action = this._hydrateActionPayloadWire(wire);
15152
15367
  if (metadata != null) action.context._setReceiverMetadata(metadata);
15153
- return this.handleActionPayload(action);
15368
+ return action;
15154
15369
  }
15155
15370
  _hydrateActionPayloadWire(wire) {
15156
15371
  if (isActionPayload_Any_JsonObject(wire)) return this.actionRouter.domainManager.getActionDomainOrThrow(wire).hydrateAnyAction(wire);
@@ -15182,6 +15397,10 @@ var ActionRuntime = class {
15182
15397
  reliabilityTierForWire(wire) {
15183
15398
  return this.reliabilityTierForRoute(wire.domain, wire.id);
15184
15399
  }
15400
+ /** @internal The registered domain a wire names, if this runtime has it. */
15401
+ _domainForWire(wire) {
15402
+ return this.actionRouter.domainManager.getActionDomain(wire);
15403
+ }
15185
15404
  /**
15186
15405
  * {@link reliabilityTierForWire} by bare `domain:id` route — for callers holding only a route, e.g. the
15187
15406
  * reliable acceptor resolving which receive store an `rskip` control message (no action payload) applies to.
@@ -15609,6 +15828,7 @@ var ActionLocalHandler = class extends ActionHandler {
15609
15828
  const metadata = state.request.context._getReceiverMetadata();
15610
15829
  const context = {
15611
15830
  runtime,
15831
+ cuid: state.request.context.cuid,
15612
15832
  origin: state.request.context.originClient,
15613
15833
  authenticatedOrigin: metadata?.originAuthenticated === true ? state.request.context.originClient : void 0,
15614
15834
  securityLevel: metadata?.securityLevel,
@@ -15915,7 +16135,7 @@ var ActionDomain = class ActionDomain extends ActionDomainBase {
15915
16135
  hydrateContext(id, contextData) {
15916
16136
  return new ActionContext(this, id, {
15917
16137
  timeCreated: contextData.timeCreated,
15918
- cuid: contextData.cuid,
16138
+ cuid: contextData.cuid ?? nanoid(),
15919
16139
  routing: contextData.routing.map((item) => {
15920
16140
  return {
15921
16141
  runtime: new RuntimeCoordinate(item.runtime),
@@ -16028,6 +16248,7 @@ function actionServeRequestInfo(wire, meta) {
16028
16248
  domain: wire.domain,
16029
16249
  action: wire.id,
16030
16250
  actionId: `${wire.domain}/${wire.id}`,
16251
+ cuid: wire.context.cuid,
16031
16252
  origin,
16032
16253
  securityLevel: meta.securityLevel,
16033
16254
  input: wire.input,
@@ -16047,6 +16268,22 @@ function serveResultErrorInfo(error) {
16047
16268
  message: error.cleanMessage ?? error.message
16048
16269
  };
16049
16270
  }
16271
+ /** A failed action's outcome, as the line a serve logger's reporter takes. */
16272
+ function failedResultInfo(thrown, sealed, served) {
16273
+ return {
16274
+ ok: false,
16275
+ ...served,
16276
+ error: serveResultErrorInfo(thrown),
16277
+ thrown,
16278
+ sealed
16279
+ };
16280
+ }
16281
+ /** What a log prints for a failed action: the value a handler threw, and not the cast around it. */
16282
+ function thrownForLog(error) {
16283
+ return error.isUnhandled ? error.originError ?? error : error;
16284
+ }
16285
+ /** Their messages quote the value the schema rejected, which a log hides as it hides an input. */
16286
+ const VALIDATION_FAILURE_IDS = new Set(["err_nice_action/action_input_validation_failed", "err_nice_action/action_output_validation_failed"]);
16050
16287
  /**
16051
16288
  * A ready-made {@link IActionServeLogger} that prints one line when a request arrives and one when it has
16052
16289
  * been served, to `console` (or any `sink` you pass). Drop it straight into `serveChannel` so a "host and
@@ -16056,7 +16293,9 @@ function serveResultErrorInfo(error) {
16056
16293
  * // → [nice-action] ▶ demo_basic/greet via http from envId[web_app]… [encrypted]
16057
16294
  * // ← [nice-action] ✓ demo_basic/greet ok via http 12ms
16058
16295
  * ```
16059
- * Inputs are hidden by default (`logInputs: true` to include them).
16296
+ * Inputs are hidden by default (`logInputs: true` to include them). A failed line ends with the
16297
+ * request's `cuid`. For a failure the caller was sent sealed, the sink is also handed what the
16298
+ * handler threw.
16060
16299
  */
16061
16300
  function createDefaultServeLogger(options = {}) {
16062
16301
  const sink = options.sink ?? console;
@@ -16088,11 +16327,19 @@ function createDefaultServeLogger(options = {}) {
16088
16327
  `${result.durationMs}ms`
16089
16328
  ];
16090
16329
  if (result.bytes != null) line.push(`${result.bytes}B`);
16091
- if (!result.ok && result.error != null) {
16092
- const prefix = result.error.id != null ? `${result.error.id}: ` : "";
16093
- line.push(`— ${prefix}${result.error.message}`);
16330
+ if (result.ok) {
16331
+ sink.log(line.join(" "));
16332
+ return;
16094
16333
  }
16095
- (result.ok ? sink.log : sink.error)(line.join(" "));
16334
+ if (result.error != null) {
16335
+ const { id, message } = result.error;
16336
+ const hidden = id != null && VALIDATION_FAILURE_IDS.has(id) && !options.logInputs;
16337
+ line.push(`— ${hidden ? id : id != null ? `${id}: ${message}` : message}`);
16338
+ }
16339
+ if (result.sealed) line.push("[sealed]");
16340
+ line.push(`cuid=${info.cuid}`);
16341
+ if (result.sealed && result.thrown != null) sink.error(line.join(" "), thrownForLog(result.thrown));
16342
+ else sink.error(line.join(" "));
16096
16343
  };
16097
16344
  } };
16098
16345
  }
@@ -16104,6 +16351,201 @@ function safeJson(value) {
16104
16351
  }
16105
16352
  }
16106
16353
  //#endregion
16354
+ //#region ../nice-action/src/ActionRuntime/actionFailureSealing.ts
16355
+ function isOwn(error, id) {
16356
+ return err_nice_action.isExact(error) && error.hasId(id);
16357
+ }
16358
+ /** What `"off"` sends: the failure with its stack and origin error, and unsealed. */
16359
+ var WholeFailureResult = class extends ActionPayload_Result {
16360
+ toJsonObject() {
16361
+ const json = super.toJsonObject();
16362
+ if (this.result.ok || json.result.ok) return json;
16363
+ const error = this.result.error.toJsonObject();
16364
+ return {
16365
+ ...json,
16366
+ result: {
16367
+ ...json.result,
16368
+ error
16369
+ },
16370
+ outputHash: hashPayloadData(error.message)
16371
+ };
16372
+ }
16373
+ };
16374
+ /**
16375
+ * A server's policy for what a failed action tells its caller. A function and not a runtime
16376
+ * method, so that a client bundle does not carry it.
16377
+ */
16378
+ function createFailureSealer(options) {
16379
+ const sealing = options.sealFailures ?? "undeclared";
16380
+ const warned = /* @__PURE__ */ new Set();
16381
+ const mustSeal = (error, declared) => {
16382
+ if (error.isUnhandled) return true;
16383
+ if (sealing === "unhandled" || declared) return false;
16384
+ return !isOwn(error, "action_input_validation_failed");
16385
+ };
16386
+ return { seal(result) {
16387
+ if (result.result.ok) return {
16388
+ sent: result,
16389
+ sealed: false
16390
+ };
16391
+ const error = result.result.error;
16392
+ if (sealing === "off") return {
16393
+ sent: new WholeFailureResult({ context: result.context }, {
16394
+ ok: false,
16395
+ error
16396
+ }, { time: result.time }),
16397
+ sealed: false
16398
+ };
16399
+ if (!mustSeal(error, result.result.expected)) return {
16400
+ sent: result,
16401
+ sealed: false
16402
+ };
16403
+ const action = `${result.domain}/${result.id}`;
16404
+ if (!error.isUnhandled && !isOwn(error, "action_output_validation_failed")) {
16405
+ const thrown = serveResultErrorInfo(error).id;
16406
+ if (!warned.has(`${action} ${thrown}`)) {
16407
+ warned.add(`${action} ${thrown}`);
16408
+ console.warn(`[nice-action] ${action} failed with ${thrown}, which the action does not declare, so its caller was sent the sealed failure. Declare it with .throws() to send it whole.`);
16409
+ }
16410
+ }
16411
+ if (!options.hasLogger) console.error(`[nice-action] ${action} failed, and its caller was sent the sealed failure (cuid ${result.context.cuid})`, thrownForLog(error));
16412
+ return {
16413
+ sent: new ActionPayload_Result({ context: result.context }, {
16414
+ ok: false,
16415
+ error: sealedFailure()
16416
+ }, { time: result.time }),
16417
+ sealed: true
16418
+ };
16419
+ } };
16420
+ }
16421
+ //#endregion
16422
+ //#region ../nice-action/src/utils/requestWireProblem.ts
16423
+ const CONTEXT_PROBLEM_SENTENCES = {
16424
+ missing: "Action wire has no \"context\": it needs at least { \"routing\": [] }.",
16425
+ routing: "Action wire \"context.routing\" must be an array ([] when written by hand).",
16426
+ route_item: "Action wire \"context.routing\" holds an entry with no \"runtime\".",
16427
+ cuid: "Action wire \"context.cuid\" must be a string.",
16428
+ origin_client: "Action wire \"context.originClient\" must be a runtime coordinate."
16429
+ };
16430
+ /** Why `wire` fails `isActionPayload_Request_JsonObject`, as a sentence for whoever sent it. */
16431
+ function requestWireProblem(wire) {
16432
+ const notActionData = () => err_nice_action.fromId("wire_not_action_data").message;
16433
+ if (!isAction_Base_JsonObject(wire) || wire.form !== "data" || !("type" in wire)) return notActionData();
16434
+ if (wire.type !== "request") return `An action endpoint takes a "request" wire, got "${String(wire.type)}".`;
16435
+ const problem = actionPayloadContextProblem("context" in wire ? wire.context : void 0);
16436
+ return problem != null ? CONTEXT_PROBLEM_SENTENCES[problem] : notActionData();
16437
+ }
16438
+ //#endregion
16439
+ //#region ../nice-action/src/ActionRuntime/actionRequestRefusal.ts
16440
+ function isNotServedRefusal(refusal) {
16441
+ return refusal.reason !== "malformed";
16442
+ }
16443
+ /**
16444
+ * A refusal as an `err` envelope's fields, and as a raw `404`'s: only a route this side does not
16445
+ * serve is given the id a client branches on.
16446
+ */
16447
+ function refusalReplyFields(refusal) {
16448
+ return isNotServedRefusal(refusal) ? {
16449
+ message: refusal.message,
16450
+ id: "action_not_served",
16451
+ reason: refusal.reason
16452
+ } : { message: refusal.message };
16453
+ }
16454
+ /**
16455
+ * A request written by hand may send no `cuid`. It is given one at the door, so the log, the
16456
+ * handler and the reply all name the same request.
16457
+ */
16458
+ function ensureRequestCuid(wire) {
16459
+ if (wire.context.cuid == null) wire.context.cuid = nanoid();
16460
+ }
16461
+ /** The refusal for a wire that is not a request this side can hydrate. */
16462
+ function refuseMalformedRequestWire(wire) {
16463
+ return {
16464
+ reason: "malformed",
16465
+ message: requestWireProblem(wire)
16466
+ };
16467
+ }
16468
+ /** The refusal for a request wire whose hydration threw. */
16469
+ function refuseUnhydratedRequestWire(thrown) {
16470
+ if (!err_nice_action.isExact(thrown)) return {
16471
+ reason: "malformed",
16472
+ message: "The request wire could not be read.",
16473
+ error: castNiceError(thrown)
16474
+ };
16475
+ return {
16476
+ reason: thrown.hasId("domain_no_handler") ? "unknown_domain" : thrown.hasId("hydration_action_id_not_found") ? "unknown_action" : "malformed",
16477
+ message: thrown.message,
16478
+ error: thrown
16479
+ };
16480
+ }
16481
+ /**
16482
+ * The refusal for a request whose domain or action this runtime does not have, found without
16483
+ * hydrating it. `undefined` when the route is served.
16484
+ */
16485
+ function refuseUnservedRoute(runtime, wire) {
16486
+ const domain = runtime._domainForWire(wire);
16487
+ const error = domain == null ? err_nice_action.fromId("domain_no_handler", { domain: wire.domain }) : domain.actionSchema[wire.id] == null ? err_nice_action.fromId("hydration_action_id_not_found", {
16488
+ domain: wire.domain,
16489
+ actionId: wire.id
16490
+ }) : void 0;
16491
+ if (error == null) return void 0;
16492
+ return {
16493
+ reason: domain == null ? "unknown_domain" : "unknown_action",
16494
+ message: error.message,
16495
+ error
16496
+ };
16497
+ }
16498
+ /**
16499
+ * The failed result that answers a request this side does not serve, where a result is the only
16500
+ * reply the carrier has. Built as a wire: a request for an unknown route cannot be hydrated.
16501
+ */
16502
+ function notServedResultWire(wire, refusal) {
16503
+ const { input: _input, inputHash: _inputHash, ...route } = wire;
16504
+ return {
16505
+ ...route,
16506
+ type: "result",
16507
+ time: Date.now(),
16508
+ result: {
16509
+ ok: false,
16510
+ expected: false,
16511
+ error: err_nice_transport.fromId("action_not_served", {
16512
+ domain: wire.domain,
16513
+ actionId: wire.id,
16514
+ reason: refusal.reason
16515
+ }).toJsonObject()
16516
+ },
16517
+ outputHash: ""
16518
+ };
16519
+ }
16520
+ /**
16521
+ * The request/reply door: hydrate a request wire and dispatch it, or say why it was turned away.
16522
+ * A wire the runtime cannot serve is a refusal, never a rejection. A function and not a runtime
16523
+ * method, so that a client bundle does not carry it.
16524
+ */
16525
+ async function admitRequestWire(runtime, wire, metadata) {
16526
+ let request;
16527
+ try {
16528
+ request = runtime._hydrateWireFromReceiver(wire, metadata);
16529
+ } catch (thrown) {
16530
+ return {
16531
+ admitted: false,
16532
+ refusal: refuseUnhydratedRequestWire(thrown)
16533
+ };
16534
+ }
16535
+ return {
16536
+ admitted: true,
16537
+ running: await runtime.handleActionPayload(request)
16538
+ };
16539
+ }
16540
+ /** A refused request's outcome, as the line a serve logger's reporter takes. */
16541
+ function refusalResultInfo(refusal, served) {
16542
+ return {
16543
+ ok: false,
16544
+ ...served,
16545
+ error: refusal.error != null ? serveResultErrorInfo(refusal.error) : { message: refusal.message }
16546
+ };
16547
+ }
16548
+ //#endregion
16107
16549
  //#region ../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/ChannelAcceptor.ts
16108
16550
  /** Validate + read a rehydrated binding's opaque lane slot back into the lane's shape. */
16109
16551
  function readLaneBindingState(lane) {
@@ -16171,6 +16613,7 @@ var ChannelAcceptor = class extends PeerLink {
16171
16613
  _maxKeyedStreams;
16172
16614
  _resyncRequested = /* @__PURE__ */ new Set();
16173
16615
  _logger;
16616
+ _sealer;
16174
16617
  _transportLabel;
16175
16618
  _pendingReports = /* @__PURE__ */ new Map();
16176
16619
  constructor(options) {
@@ -16181,6 +16624,10 @@ var ChannelAcceptor = class extends PeerLink {
16181
16624
  this._runtime = options.runtime;
16182
16625
  this._serverTimeout = options.defaultTimeout ?? 1e4;
16183
16626
  this._logger = options.logger;
16627
+ this._sealer = createFailureSealer({
16628
+ sealFailures: options.sealFailures,
16629
+ hasLogger: options.logger != null
16630
+ });
16184
16631
  this._transportLabel = options.transportLabel ?? "ws";
16185
16632
  this._persistedReceiver = options.persistedReceiver;
16186
16633
  this._maxKeyedStreams = options.maxKeyedStreamsPerClient ?? 256;
@@ -16271,25 +16718,21 @@ var ChannelAcceptor = class extends PeerLink {
16271
16718
  });
16272
16719
  }
16273
16720
  /** Report a served result back to the reporter stashed by {@link _logRequestIn} (no-op if none/not a result). */
16274
- _reportServed(payload, bytes) {
16721
+ _reportServed(payload, sealed, bytes) {
16275
16722
  if (payload.type !== "result") return;
16276
16723
  const entry = this._pendingReports.get(payload.context.cuid);
16277
16724
  if (entry == null) return;
16278
16725
  this._pendingReports.delete(payload.context.cuid);
16279
- const durationMs = Date.now() - entry.startedAt;
16726
+ const served = {
16727
+ returnedVia: this._transportLabel,
16728
+ durationMs: Date.now() - entry.startedAt,
16729
+ bytes
16730
+ };
16280
16731
  const outcome = payload.result;
16281
16732
  entry.report(outcome.ok ? {
16282
16733
  ok: true,
16283
- returnedVia: this._transportLabel,
16284
- durationMs,
16285
- bytes
16286
- } : {
16287
- ok: false,
16288
- returnedVia: this._transportLabel,
16289
- durationMs,
16290
- bytes,
16291
- error: serveResultErrorInfo(outcome.error)
16292
- });
16734
+ ...served
16735
+ } : failedResultInfo(outcome.error, sealed, served));
16293
16736
  }
16294
16737
  /**
16295
16738
  * The codec for a connection: a per-connection session (cached) when a factory was provided, else
@@ -16353,6 +16796,7 @@ var ChannelAcceptor = class extends PeerLink {
16353
16796
  const codec = this._codecFor(connection);
16354
16797
  const wire = decodeActionFrame(frame, codec);
16355
16798
  if (wire == null) return;
16799
+ if (wire.type === "request") ensureRequestCuid(wire);
16356
16800
  if (level === "none") {
16357
16801
  const encoding = typeof frame === "string" ? "json" : "binary";
16358
16802
  this._connEncoding.set(connection, encoding);
@@ -16478,6 +16922,7 @@ var ChannelAcceptor = class extends PeerLink {
16478
16922
  _emitIncomingFromReceiver(wire, reliability, arrivalOverride) {
16479
16923
  const arrival = arrivalOverride ?? this._receiverMetadataByWire.get(wire);
16480
16924
  this._receiverMetadataByWire.delete(wire);
16925
+ if (wire.type === "request" && this._refuseUnserved(wire, arrival, reliability)) return;
16481
16926
  const securityLevel = arrival?.securityLevel;
16482
16927
  this._emitIncoming(wire, {
16483
16928
  receiver: this,
@@ -16489,6 +16934,53 @@ var ChannelAcceptor = class extends PeerLink {
16489
16934
  });
16490
16935
  }
16491
16936
  /**
16937
+ * Answer a request for a domain or action the runtime does not have with a failed result. Nothing
16938
+ * past this point can: such a request cannot be hydrated, so its caller would wait out its
16939
+ * timeout. A refused reliable frame has been through the inbox, and its ack rides the answer.
16940
+ */
16941
+ _refuseUnserved(wire, arrival, reliability) {
16942
+ const runtime = this._incomingRuntime;
16943
+ const refusal = runtime == null ? void 0 : refuseUnservedRoute(runtime, wire);
16944
+ const connection = arrival == null ? void 0 : this._liveArrivalConnection(arrival);
16945
+ if (refusal == null || connection == null) return false;
16946
+ const answer = notServedResultWire(wire, refusal);
16947
+ let frame;
16948
+ if (this._connEncoding.get(connection) === "json") frame = JSON.stringify(answer);
16949
+ else {
16950
+ const client = this.wireAcceptor.clientForConnection(connection);
16951
+ frame = this._codecFor(connection).outgoingWire?.(answer, reliability == null || client == null ? void 0 : this._replyAck(client, wire.domain, wire.id, reliability.streamKey));
16952
+ }
16953
+ if (frame == null) return false;
16954
+ this.wireAcceptor.sendTo(connection, frame);
16955
+ const pending = this._pendingReports.get(wire.context.cuid);
16956
+ if (pending != null) {
16957
+ this._pendingReports.delete(wire.context.cuid);
16958
+ pending.report({
16959
+ ...refusalResultInfo(refusal, {
16960
+ returnedVia: this._transportLabel,
16961
+ durationMs: Date.now() - pending.startedAt
16962
+ }),
16963
+ bytes: wireFrameByteSize(frame)
16964
+ });
16965
+ }
16966
+ return true;
16967
+ }
16968
+ /** The cumulative ack a reply on this stream carries, when the stream is a reliable one. */
16969
+ _replyAck(client, domain, id, streamKey) {
16970
+ const streamId = reliableStreamId(client, domain, id, streamKey);
16971
+ const receiver = this._persistedReceiver?.hasStream(streamId) ? this._persistedReceiver : this._inbox.hasStream(streamId) ? this._inbox : void 0;
16972
+ if (receiver == null) return void 0;
16973
+ const ack = receiver.contiguousSeq(streamId);
16974
+ return streamKey == null ? {
16975
+ streamId,
16976
+ ack
16977
+ } : {
16978
+ streamId,
16979
+ ack,
16980
+ streamKey
16981
+ };
16982
+ }
16983
+ /**
16492
16984
  * Log + emit each frame the receiver decided to deliver in this receive. Only the **first** (the frame
16493
16985
  * actually received this call) carries the reliability facts for the *logger*; drained buffered frames
16494
16986
  * were logged/seq'd on their own earlier arrivals, so they log without a (stale) seq. Every delivered
@@ -16756,8 +17248,12 @@ var ChannelAcceptor = class extends PeerLink {
16756
17248
  const arrival = config.arrival ?? payload.context._getReceiverMetadata();
16757
17249
  const connection = arrival == null ? this.wireAcceptor.connectionForClient(payload.context.originClient.stringId) : arrival.receiver === this ? this._liveArrivalConnection(arrival) : void 0;
16758
17250
  if (connection == null) return false;
16759
- const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate, arrival?.reliability);
16760
- this._reportServed(payload, bytes);
17251
+ const { sent, sealed } = payload.type === "result" ? this._sealer.seal(payload) : {
17252
+ sent: payload,
17253
+ sealed: false
17254
+ };
17255
+ const bytes = this._sendPayload(connection, sent, config.targetLocalRuntime.coordinate, arrival?.reliability);
17256
+ this._reportServed(payload, sealed, bytes);
16761
17257
  return true;
16762
17258
  }
16763
17259
  async handleActionRequest(action, config) {
@@ -16815,23 +17311,7 @@ var ChannelAcceptor = class extends PeerLink {
16815
17311
  /** Encode + send one payload; returns the encoded frame's size so a logger can report it. */
16816
17312
  _sendPayload(connection, payload, localClient, answered) {
16817
17313
  const encoding = this._connEncoding.get(connection) ?? "binary";
16818
- let rel;
16819
- if (payload.type === "result") {
16820
- const streamKey = (answered ?? payload.context.reliability)?.streamKey;
16821
- const streamId = reliableStreamId(payload.context.originClient, payload.domain, payload.id, streamKey);
16822
- const receiver = this._persistedReceiver?.hasStream(streamId) ? this._persistedReceiver : this._inbox.hasStream(streamId) ? this._inbox : void 0;
16823
- if (receiver != null) {
16824
- const ack = receiver.contiguousSeq(streamId);
16825
- rel = streamKey == null ? {
16826
- streamId,
16827
- ack
16828
- } : {
16829
- streamId,
16830
- ack,
16831
- streamKey
16832
- };
16833
- }
16834
- }
17314
+ const rel = payload.type === "result" ? this._replyAck(payload.context.originClient, payload.domain, payload.id, (answered ?? payload.context.reliability)?.streamKey) : void 0;
16835
17315
  const frame = encoding === "json" ? JSON.stringify(payload.toJsonObject()) : this._codecFor(connection).outgoing({
16836
17316
  action: payload,
16837
17317
  localClient,
@@ -16896,6 +17376,7 @@ function createSecureChannelAcceptor(options) {
16896
17376
  runtime: options.runtime,
16897
17377
  defaultTimeout: options.defaultTimeout,
16898
17378
  logger: options.logger,
17379
+ sealFailures: options.sealFailures,
16899
17380
  wireTap: options.wireTap,
16900
17381
  transportLabel: options.transportLabel,
16901
17382
  persistedReceiver: options.persistedReceiver,
@@ -17121,44 +17602,45 @@ function createBinaryWireSessionFactory(domains, options) {
17121
17602
  const cuidToCorr = /* @__PURE__ */ new Map();
17122
17603
  let selfIdentity;
17123
17604
  let peerIdentity;
17124
- return {
17125
- outgoing: (input) => {
17126
- const json = input.action.toJsonObject();
17127
- const routeKey = `${json.domain}:${json.id}`;
17128
- const routeInt = routeToInt.get(routeKey);
17129
- if (routeInt == null) throw new Error(`[binary-wire] Cannot pack unregistered action route: ${routeKey}`);
17130
- const now = Date.now();
17131
- pruneExpired(corrToCuid, now, ttlMs);
17132
- pruneExpired(cuidToCorr, now, ttlMs);
17133
- let corr;
17134
- let wireIdentity;
17135
- if (json.type === "request") {
17136
- corr = outCounter++;
17137
- corrToCuid.set(corr, {
17138
- value: json.context.cuid,
17139
- time: now
17140
- });
17141
- if (selfIdentity == null && isKnownIdentity(json.context.originClient)) {
17142
- selfIdentity = json.context.originClient;
17143
- wireIdentity = json.context.originClient;
17144
- }
17145
- } else {
17146
- corr = cuidToCorr.get(json.context.cuid)?.value ?? -1;
17147
- if (json.type === "result") cuidToCorr.delete(json.context.cuid);
17605
+ const packWire = (json, reliability) => {
17606
+ const routeKey = `${json.domain}:${json.id}`;
17607
+ const routeInt = routeToInt.get(routeKey);
17608
+ if (routeInt == null) throw new Error(`[binary-wire] Cannot pack unregistered action route: ${routeKey}`);
17609
+ const now = Date.now();
17610
+ pruneExpired(corrToCuid, now, ttlMs);
17611
+ pruneExpired(cuidToCorr, now, ttlMs);
17612
+ let corr;
17613
+ let wireIdentity;
17614
+ if (json.type === "request") {
17615
+ corr = outCounter++;
17616
+ corrToCuid.set(corr, {
17617
+ value: json.context.cuid,
17618
+ time: now
17619
+ });
17620
+ if (selfIdentity == null && isKnownIdentity(json.context.originClient)) {
17621
+ selfIdentity = json.context.originClient;
17622
+ wireIdentity = json.context.originClient;
17148
17623
  }
17149
- const reliabilitySlot = encodeReliabilitySlot(input.reliability, json.type);
17150
- const streamKey = input.reliability?.streamKey;
17151
- const envelope = new Array(streamKey != null ? ENVELOPE_LENGTH_RELIABLE_KEYED : reliabilitySlot == null ? ENVELOPE_LENGTH : ENVELOPE_LENGTH_RELIABLE);
17152
- envelope[ENVELOPE.route] = routeInt;
17153
- envelope[ENVELOPE.type] = PayloadTypeToInt[json.type];
17154
- envelope[ENVELOPE.corr] = corr;
17155
- envelope[ENVELOPE.time] = json.time;
17156
- envelope[ENVELOPE.originClient] = wireIdentity;
17157
- envelope[ENVELOPE.payload] = extractWirePayload(json);
17158
- if (reliabilitySlot != null) envelope[ENVELOPE.reliability] = reliabilitySlot;
17159
- if (streamKey != null) envelope[ENVELOPE.streamKey] = streamKey;
17160
- return pack(envelope);
17161
- },
17624
+ } else {
17625
+ corr = cuidToCorr.get(json.context.cuid)?.value ?? -1;
17626
+ if (json.type === "result") cuidToCorr.delete(json.context.cuid);
17627
+ }
17628
+ const reliabilitySlot = encodeReliabilitySlot(reliability, json.type);
17629
+ const streamKey = reliability?.streamKey;
17630
+ const envelope = new Array(streamKey != null ? ENVELOPE_LENGTH_RELIABLE_KEYED : reliabilitySlot == null ? ENVELOPE_LENGTH : ENVELOPE_LENGTH_RELIABLE);
17631
+ envelope[ENVELOPE.route] = routeInt;
17632
+ envelope[ENVELOPE.type] = PayloadTypeToInt[json.type];
17633
+ envelope[ENVELOPE.corr] = corr;
17634
+ envelope[ENVELOPE.time] = json.time;
17635
+ envelope[ENVELOPE.originClient] = wireIdentity;
17636
+ envelope[ENVELOPE.payload] = extractWirePayload(json);
17637
+ if (reliabilitySlot != null) envelope[ENVELOPE.reliability] = reliabilitySlot;
17638
+ if (streamKey != null) envelope[ENVELOPE.streamKey] = streamKey;
17639
+ return pack(envelope);
17640
+ };
17641
+ return {
17642
+ outgoing: (input) => packWire(input.action.toJsonObject(), input.reliability),
17643
+ outgoingWire: packWire,
17162
17644
  incoming: (frame) => {
17163
17645
  let buffer;
17164
17646
  if (frame instanceof ArrayBuffer) buffer = new Uint8Array(frame);
@@ -17291,11 +17773,18 @@ async function runExchange(session, inputs) {
17291
17773
  return;
17292
17774
  }
17293
17775
  const outcome = await session.exchange(action.toJsonObject(), { signal: ac.signal });
17294
- if (!outcome.ok && outcome.reason === "peer_error") throw err_nice_transport.fromId("send_failed", {
17295
- actionState: action.type,
17296
- actionId: action.id,
17297
- message: outcome.message
17298
- });
17776
+ if (!outcome.ok && outcome.reason === "peer_error") {
17777
+ if (outcome.id === "action_not_served") throw err_nice_transport.fromId("action_not_served", {
17778
+ domain: action.domain,
17779
+ actionId: action.id,
17780
+ reason: outcome.peerReason === "unknown_domain" ? "unknown_domain" : "unknown_action"
17781
+ });
17782
+ throw err_nice_transport.fromId("send_failed", {
17783
+ actionState: action.type,
17784
+ actionId: action.id,
17785
+ message: outcome.message
17786
+ });
17787
+ }
17299
17788
  if (!outcome.ok || !isActionPayload_Result_JsonObject(outcome.wire)) throw err_nice_transport.fromId("invalid_action_response", { actionId: action.id });
17300
17789
  runningAction._completeWithResult(action._domain.hydrateResultPayload(outcome.wire));
17301
17790
  } catch (err) {
@@ -17930,9 +18419,14 @@ var ExchangeAcceptor = class {
17930
18419
  _runtime;
17931
18420
  _logger;
17932
18421
  _transportLabel;
18422
+ _sealer;
17933
18423
  constructor(config) {
17934
18424
  this._runtime = config.runtime;
17935
18425
  this._logger = config.logger;
18426
+ this._sealer = createFailureSealer({
18427
+ sealFailures: config.sealFailures,
18428
+ hasLogger: config.logger != null
18429
+ });
17936
18430
  this._transportLabel = config.transportLabel ?? "http";
17937
18431
  this._core = new WireExchangeAcceptor({
17938
18432
  security: {
@@ -17954,46 +18448,82 @@ var ExchangeAcceptor = class {
17954
18448
  }
17955
18449
  /** Serve one opened `act` wire: validate → bind identity → log → run → return the result wire. */
17956
18450
  async _onExchange(request) {
17957
- if (!isActionPayload_Any_JsonObject(request.wire)) return {
18451
+ if (!isActionPayload_Request_JsonObject(request.wire)) return {
17958
18452
  ok: false,
17959
- message: "malformed action wire"
18453
+ message: refuseMalformedRequestWire(request.wire).message
17960
18454
  };
17961
18455
  const wire = request.wire;
17962
18456
  const client = request.client;
17963
- if (client != null && wire.type === "request") wire.context.originClient = client.toJsonObject();
17964
- const report = this._logger != null && wire.type === "request" ? this._logger.onRequest(actionServeRequestInfo(wire, {
18457
+ if (client != null) wire.context.originClient = client.toJsonObject();
18458
+ ensureRequestCuid(wire);
18459
+ const report = this._logger?.onRequest(actionServeRequestInfo(wire, {
17965
18460
  transport: this._transportLabel,
17966
18461
  securityLevel: request.securityLevel,
17967
18462
  origin: client?.stringId
17968
- })) : void 0;
18463
+ }));
17969
18464
  const startedAt = Date.now();
17970
- const result = await (await this._runtime._handleActionPayloadWireFromReceiver(wire, {
18465
+ const returnedVia = request.encrypted ? `${this._transportLabel} (encrypted)` : this._transportLabel;
18466
+ const admission = await admitRequestWire(this._runtime, wire, {
17971
18467
  receiver: this,
17972
18468
  securityLevel: request.securityLevel,
17973
18469
  originAuthenticated: client != null && request.securityLevel !== "none"
17974
- })).waitForResultPayload();
17975
- const resultWire = result.toJsonObject();
17976
- if (report != null) {
17977
- const returnedVia = request.encrypted ? `${this._transportLabel} (encrypted)` : this._transportLabel;
17978
- report(result.result.ok ? {
17979
- ok: true,
18470
+ });
18471
+ if (!admission.admitted) {
18472
+ report?.(refusalResultInfo(admission.refusal, {
17980
18473
  returnedVia,
17981
18474
  durationMs: Date.now() - startedAt
17982
- } : {
18475
+ }));
18476
+ return {
17983
18477
  ok: false,
17984
- returnedVia,
17985
- durationMs: Date.now() - startedAt,
17986
- error: serveResultErrorInfo(result.result.error)
17987
- });
18478
+ ...refusalReplyFields(admission.refusal)
18479
+ };
17988
18480
  }
18481
+ const result = await admission.running.waitForResultPayload();
18482
+ const { sent, sealed } = this._sealer.seal(result);
18483
+ const served = {
18484
+ returnedVia,
18485
+ durationMs: Date.now() - startedAt
18486
+ };
18487
+ report?.(result.result.ok ? {
18488
+ ok: true,
18489
+ ...served
18490
+ } : failedResultInfo(result.result.error, sealed, served));
17989
18491
  return {
17990
18492
  ok: true,
17991
- wire: resultWire
18493
+ wire: sent.toJsonObject()
17992
18494
  };
17993
18495
  }
17994
18496
  };
17995
18497
  //#endregion
17996
- //#region ../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/createActionFetchHandler.ts
18498
+ //#region ../nice-action/src/ActionRuntime/Handler/PeerLink/Acceptor/readBodyWithin.ts
18499
+ /**
18500
+ * A request's body as text, or `undefined` once it is over `maxBytes`. The declared length is
18501
+ * checked first, so an honest oversized body is never read; the read is then capped, since a
18502
+ * chunked body declares no length and a declared one can be understated.
18503
+ */
18504
+ async function readBodyWithin(request, maxBytes) {
18505
+ if (Number(request.headers.get("Content-Length")) > maxBytes) return void 0;
18506
+ if (request.body == null) return "";
18507
+ const reader = request.body.getReader();
18508
+ const decoder = new TextDecoder();
18509
+ let text = "";
18510
+ let received = 0;
18511
+ for (;;) {
18512
+ const { done, value } = await reader.read();
18513
+ if (done) break;
18514
+ received += value.byteLength;
18515
+ if (received > maxBytes) {
18516
+ await reader.cancel();
18517
+ return;
18518
+ }
18519
+ text += decoder.decode(value, { stream: true });
18520
+ }
18521
+ return text + decoder.decode();
18522
+ }
18523
+ function isJsonContentType(request) {
18524
+ const contentType = request.headers.get("Content-Type");
18525
+ return contentType != null && contentType.split(";", 1)[0].trim().toLowerCase() === "application/json";
18526
+ }
17997
18527
  /** Permissive defaults — fine for a public action endpoint; override (or disable) via `cors`. */
17998
18528
  const DEFAULT_CORS_HEADERS = {
17999
18529
  "Access-Control-Allow-Origin": "*",
@@ -18025,12 +18555,20 @@ function createActionFetchHandler(runtime, options = {}) {
18025
18555
  const isActionPath = options.isActionPath ?? ((url) => url.pathname.endsWith("/action"));
18026
18556
  const isWebSocketPath = options.isWebSocketPath ?? ((url) => url.pathname.endsWith("/ws"));
18027
18557
  const transportLabel = options.transportLabel ?? "http";
18558
+ const requireJsonContentType = options.requireJsonContentType ?? true;
18559
+ const maxBodyBytes = options.maxBodyBytes ?? 1048576;
18560
+ if (!(maxBodyBytes > 0)) throw new Error("maxBodyBytes must be a positive number of bytes, or Infinity for no limit");
18028
18561
  const exchangeAcceptor = options.security != null ? new ExchangeAcceptor({
18029
18562
  runtime,
18030
18563
  security: options.security,
18031
18564
  logger: options.logger,
18032
- transportLabel
18565
+ transportLabel,
18566
+ sealFailures: options.sealFailures
18033
18567
  }) : void 0;
18568
+ const sealer = createFailureSealer({
18569
+ sealFailures: options.sealFailures,
18570
+ hasLogger: options.logger != null
18571
+ });
18034
18572
  const withCors = (response) => {
18035
18573
  if (options.cors === false) return response;
18036
18574
  const headers = new Headers(response.headers);
@@ -18040,8 +18578,8 @@ function createActionFetchHandler(runtime, options = {}) {
18040
18578
  headers
18041
18579
  });
18042
18580
  };
18043
- const badRequest = (message) => new Response(JSON.stringify({ error: message }), {
18044
- status: 400,
18581
+ const errorResponse = (status, message) => new Response(JSON.stringify({ error: message }), {
18582
+ status,
18045
18583
  headers: { "Content-Type": "application/json" }
18046
18584
  });
18047
18585
  const envelopeReply = (reply) => new Response(encodeExchange(reply), {
@@ -18053,19 +18591,23 @@ function createActionFetchHandler(runtime, options = {}) {
18053
18591
  message
18054
18592
  });
18055
18593
  return async (request) => {
18594
+ const originRefusal = refuseUnlistedOrigin(request, options.allowedOrigins);
18595
+ if (originRefusal != null) return withCors(originRefusal);
18056
18596
  if (request.method === "OPTIONS") return withCors(new Response(null, { status: 204 }));
18057
18597
  const url = new URL(request.url);
18058
18598
  const isWebSocketUpgrade = options.isWebSocketUpgrade ?? ((req, u) => req.headers.get("Upgrade") === "websocket" && isWebSocketPath(u));
18059
18599
  if (options.onWebSocketUpgrade != null && isWebSocketUpgrade(request, url)) return options.onWebSocketUpgrade(request, url);
18060
18600
  if (request.method === "POST" && isActionPath(url)) {
18601
+ if (requireJsonContentType && !isJsonContentType(request)) return withCors(errorResponse(415, "an action POST needs the header \"Content-Type: application/json\""));
18602
+ const text = await readBodyWithin(request, maxBodyBytes);
18603
+ if (text == null) return withCors(errorResponse(413, `request body is over this endpoint's limit of ${maxBodyBytes} bytes (maxBodyBytes)`));
18061
18604
  if (exchangeAcceptor != null) {
18062
- const reply = await exchangeAcceptor.handlePost(await request.text());
18605
+ const reply = await exchangeAcceptor.handlePost(text);
18063
18606
  return withCors(new Response(reply, {
18064
18607
  status: 200,
18065
18608
  headers: { "Content-Type": "application/json" }
18066
18609
  }));
18067
18610
  }
18068
- const text = await request.text();
18069
18611
  const envelope = decodeExchangeRequest(text);
18070
18612
  if (envelope?.k === "hs") return withCors(envelopeError("plain endpoint: no handshake here — connect with `{ carrier: httpCarrier(...), secure: false }`"));
18071
18613
  if (envelope != null && "c" in envelope) return withCors(envelopeError("plain endpoint: cannot open an encrypted frame"));
@@ -18074,45 +18616,53 @@ function createActionFetchHandler(runtime, options = {}) {
18074
18616
  else try {
18075
18617
  body = JSON.parse(text);
18076
18618
  } catch {
18077
- return withCors(badRequest("request body is not valid JSON"));
18619
+ return withCors(errorResponse(400, "request body is not valid JSON"));
18078
18620
  }
18079
- const answerError = (message) => envelope != null ? envelopeError(message) : badRequest(message);
18080
- const report = options.logger != null && isActionPayload_Any_JsonObject(body) && body.type === "request" ? options.logger.onRequest(actionServeRequestInfo(body, { transport: transportLabel })) : void 0;
18621
+ const refuse = (refusal) => {
18622
+ const { message, ...named } = refusalReplyFields(refusal);
18623
+ if (envelope != null) return withCors(envelopeReply({
18624
+ k: "err",
18625
+ message,
18626
+ ...named
18627
+ }));
18628
+ return withCors(new Response(JSON.stringify({
18629
+ error: message,
18630
+ ...named
18631
+ }), {
18632
+ status: refusal.reason === "malformed" ? 400 : 404,
18633
+ headers: { "Content-Type": "application/json" }
18634
+ }));
18635
+ };
18636
+ if (!isActionPayload_Request_JsonObject(body)) return refuse(refuseMalformedRequestWire(body));
18637
+ ensureRequestCuid(body);
18638
+ const report = options.logger?.onRequest(actionServeRequestInfo(body, { transport: transportLabel }));
18081
18639
  const startedAt = Date.now();
18082
- let running;
18083
- try {
18084
- running = await runtime._handleActionPayloadWireFromReceiver(body, {
18085
- receiver: runtime,
18086
- securityLevel: "none"
18087
- });
18088
- } catch (error) {
18089
- if (isNiceError(error) && error.getIds().some((id) => id === "wire_not_action_data" || id === "wire_action_not_payload")) {
18090
- report?.({
18091
- ok: false,
18092
- returnedVia: transportLabel,
18093
- durationMs: Date.now() - startedAt,
18094
- error: serveResultErrorInfo(error)
18095
- });
18096
- return withCors(answerError(error.message));
18097
- }
18098
- throw error;
18640
+ const admission = await admitRequestWire(runtime, body, {
18641
+ receiver: runtime,
18642
+ securityLevel: "none"
18643
+ });
18644
+ if (!admission.admitted) {
18645
+ report?.(refusalResultInfo(admission.refusal, {
18646
+ returnedVia: transportLabel,
18647
+ durationMs: Date.now() - startedAt
18648
+ }));
18649
+ return refuse(admission.refusal);
18099
18650
  }
18100
- const result = await running.waitForResultPayload();
18101
- report?.(result.result.ok ? {
18102
- ok: true,
18651
+ const result = await admission.running.waitForResultPayload();
18652
+ const { sent, sealed } = sealer.seal(result);
18653
+ const served = {
18103
18654
  returnedVia: transportLabel,
18104
18655
  durationMs: Date.now() - startedAt
18105
- } : {
18106
- ok: false,
18107
- returnedVia: transportLabel,
18108
- durationMs: Date.now() - startedAt,
18109
- error: serveResultErrorInfo(result.result.error)
18110
- });
18656
+ };
18657
+ report?.(result.result.ok ? {
18658
+ ok: true,
18659
+ ...served
18660
+ } : failedResultInfo(result.result.error, sealed, served));
18111
18661
  if (envelope != null) return withCors(envelopeReply({
18112
18662
  k: "act",
18113
- w: result.toJsonObject()
18663
+ w: sent.toJsonObject()
18114
18664
  }));
18115
- return withCors(result.toHttpResponse({ useErrorStatus: options.useErrorStatus }));
18665
+ return withCors(sent.toHttpResponse({ useErrorStatus: options.useErrorStatus }));
18116
18666
  }
18117
18667
  return withCors(new Response("Not found", { status: 404 }));
18118
18668
  };
@@ -18360,6 +18910,7 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
18360
18910
  defaultTimeout: options.defaultTimeout,
18361
18911
  resolveChannel,
18362
18912
  logger: options.logger,
18913
+ sealFailures: options.sealFailures,
18363
18914
  wireTap: options.wireTap,
18364
18915
  transportLabel: carrier.carrierLabel,
18365
18916
  persistedReceiver: options.reliableStore,
@@ -18371,6 +18922,7 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
18371
18922
  runtime,
18372
18923
  defaultTimeout: options.defaultTimeout,
18373
18924
  logger: options.logger,
18925
+ sealFailures: options.sealFailures,
18374
18926
  wireTap: options.wireTap,
18375
18927
  transportLabel: carrier.carrierLabel,
18376
18928
  persistedReceiver: options.reliableStore,
@@ -18481,6 +19033,9 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
18481
19033
  });
18482
19034
  }
18483
19035
  const activeFetch = createActionFetchHandler(runtime, {
19036
+ allowedOrigins: options.allowedOrigins,
19037
+ requireJsonContentType: exchangeCarrier?.requireJsonContentType,
19038
+ maxBodyBytes: exchangeCarrier?.maxBodyBytes,
18484
19039
  cors: exchangeCarrier?.cors,
18485
19040
  onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
18486
19041
  isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
@@ -18488,6 +19043,7 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
18488
19043
  security: exchangeSecurity,
18489
19044
  useErrorStatus: exchangeCarrier?.useErrorStatus,
18490
19045
  logger: options.logger,
19046
+ sealFailures: options.sealFailures,
18491
19047
  transportLabel: exchangeCarrier?.carrierLabel
18492
19048
  });
18493
19049
  const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
@@ -18570,7 +19126,9 @@ function httpAcceptorCarrier(options = {}) {
18570
19126
  secure: options.secure,
18571
19127
  isActionPath: options.isActionPath,
18572
19128
  cors: options.cors,
18573
- useErrorStatus: options.useErrorStatus
19129
+ useErrorStatus: options.useErrorStatus,
19130
+ requireJsonContentType: options.requireJsonContentType,
19131
+ maxBodyBytes: options.maxBodyBytes
18574
19132
  };
18575
19133
  }
18576
19134
  //#endregion
@@ -24902,8 +25460,9 @@ var RealmServerEngine = class {
24902
25460
  if (conn.bucket.breaches >= this._limits.maxBreachesBeforeDetach) this.detachConnection(conn.key, "repeated limit breaches", true);
24903
25461
  }
24904
25462
  /**
24905
- * Send a rejection to one connection. The wire carries **only** the error's public
24906
- * `toJsonObject()` (ids, user-provided error context, message, stack) — never the realm's
25463
+ * Send a rejection to one connection. The wire carries **only** the error's
25464
+ * `toWireJsonObject()` (ids, user-provided error context, message; no stack, and the sealed
25465
+ * failure for anything that is not a rule's own `NiceError`) — never the realm's
24907
25466
  * `serverContext` (`ctx`), which the engine never places on an error (the protocol contract
24908
25467
  * secret-scrub, verified). Discipline this implies for realm authors: a rule/intent error's
24909
25468
  * **context and message are wire-visible**, so they must not embed server secrets (`ctx` values,
@@ -26686,26 +27245,38 @@ function addressMatches(address, port, hosts) {
26686
27245
  const host = normalize$1(address.slice(0, split));
26687
27246
  return host === "*" || host === "0.0.0.0" || host === "::" || hosts.includes(host) || hosts.includes("0.0.0.0") || hosts.includes("::");
26688
27247
  }
27248
+ /**
27249
+ * On Linux `comm` is the main thread's name, which a runtime may set: Node's reads `MainThread`.
27250
+ * The executable's own name is in `/proc`. Elsewhere, or for a process we may not read, `comm` stands.
27251
+ */
27252
+ async function executableName(pid) {
27253
+ if (process.platform !== "linux") return void 0;
27254
+ return readlink(`/proc/${pid}/exe`).then(basename, () => void 0);
27255
+ }
26689
27256
  async function processDetails(pid) {
26690
- const [ps, cwd] = await Promise.all([exec("ps", [
26691
- "-p",
26692
- String(pid),
26693
- "-o",
26694
- "ppid=",
26695
- "-o",
26696
- "comm="
26697
- ], { timeout: 5e3 }).catch(() => null), exec("lsof", [
26698
- "-a",
26699
- "-p",
26700
- String(pid),
26701
- "-d",
26702
- "cwd",
26703
- "-Fn"
26704
- ], { timeout: 5e3 }).catch(() => null)]);
27257
+ const [executable, ps, cwd] = await Promise.all([
27258
+ executableName(pid),
27259
+ exec("ps", [
27260
+ "-p",
27261
+ String(pid),
27262
+ "-o",
27263
+ "ppid=",
27264
+ "-o",
27265
+ "comm="
27266
+ ], { timeout: 5e3 }).catch(() => null),
27267
+ exec("lsof", [
27268
+ "-a",
27269
+ "-p",
27270
+ String(pid),
27271
+ "-d",
27272
+ "cwd",
27273
+ "-Fn"
27274
+ ], { timeout: 5e3 }).catch(() => null)
27275
+ ]);
26705
27276
  const match = ps?.stdout.trim().match(/^(\d+)\s+(.+)$/);
26706
27277
  return {
26707
27278
  ppid: match ? Number(match[1]) : null,
26708
- command: match?.[2],
27279
+ command: executable ?? match?.[2],
26709
27280
  cwd: cwd?.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) ?? null
26710
27281
  };
26711
27282
  }