@nice-code/commander 0.78.0 → 0.80.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
@@ -2694,12 +2694,309 @@ const encryptTextDataWithAesGcmKey = async ({ aesGcmKey, dataToEncrypt }) => {
2694
2694
  };
2695
2695
  };
2696
2696
  //#endregion
2697
+ //#region ../nice-util/src/crypto/canonical/stringifyCanonicalJson.ts
2698
+ /**
2699
+ * Deterministic, signing-grade JSON serialization: the same data always produces the same bytes,
2700
+ * regardless of key insertion order — the foundation for content hashes, idempotency keys, and
2701
+ * signed challenges. This is a **frozen project contract** (guarded by byte-level test vectors),
2702
+ * not RFC 8785/JCS. The exact rules:
2703
+ *
2704
+ * - `null`, booleans, strings, and finite numbers serialize with native `JSON.stringify` spelling
2705
+ * and escaping (so `-0` emits `0`).
2706
+ * - Objects contribute their **own enumerable string-keyed** entries only, sorted by UTF-16
2707
+ * code-unit order; entries whose value is `undefined` are omitted. Symbol keys and prototype
2708
+ * properties are ignored. `toJSON` is **never** invoked — a Date/Map/Set/class instance
2709
+ * contributes only its own enumerable entries.
2710
+ * - Arrays retain element order. A sparse **hole** serializes as `null` (native JSON behavior); an
2711
+ * **explicit** `undefined`/function/symbol/bigint element throws.
2712
+ * - Non-finite numbers, bigints, functions/symbols as values, top-level `undefined`, and circular
2713
+ * references throw. Repeated (non-cyclic) references are allowed.
2714
+ *
2715
+ * Error *messages* are not part of the contract; accepted-value bytes are.
2716
+ */
2717
+ function stringifyCanonicalJson(value) {
2718
+ return writeCanonical(value, "$", /* @__PURE__ */ new Set());
2719
+ }
2720
+ function writeCanonical(value, path, ancestors) {
2721
+ if (value === null) return "null";
2722
+ switch (typeof value) {
2723
+ case "string": return JSON.stringify(value);
2724
+ case "boolean": return value ? "true" : "false";
2725
+ case "number":
2726
+ if (!Number.isFinite(value)) throw new Error(`stringifyCanonicalJson: non-finite number at ${path}`);
2727
+ return JSON.stringify(value);
2728
+ case "undefined":
2729
+ case "bigint":
2730
+ case "function":
2731
+ case "symbol": throw new Error(`stringifyCanonicalJson: unsupported ${typeof value} at ${path}`);
2732
+ default: break;
2733
+ }
2734
+ const obj = value;
2735
+ if (ancestors.has(obj)) throw new Error(`stringifyCanonicalJson: circular reference at ${path}`);
2736
+ ancestors.add(obj);
2737
+ try {
2738
+ if (Array.isArray(obj)) {
2739
+ let out = "[";
2740
+ for (let i = 0; i < obj.length; i++) {
2741
+ if (i > 0) out += ",";
2742
+ out += i in obj ? writeCanonical(obj[i], `${path}[${i}]`, ancestors) : "null";
2743
+ }
2744
+ return `${out}]`;
2745
+ }
2746
+ const record = obj;
2747
+ const keys = Object.keys(record).sort();
2748
+ const parts = [];
2749
+ for (const key of keys) {
2750
+ const entry = record[key];
2751
+ if (entry === void 0) continue;
2752
+ parts.push(`${JSON.stringify(key)}:${writeCanonical(entry, `${path}.${key}`, ancestors)}`);
2753
+ }
2754
+ return `{${parts.join(",")}}`;
2755
+ } finally {
2756
+ ancestors.delete(obj);
2757
+ }
2758
+ }
2759
+ //#endregion
2760
+ //#region ../nice-util/src/crypto/canonical/buildCanonicalChallenge.ts
2761
+ /**
2762
+ * The canonical string a {@link ICanonicalChallenge} signs:
2763
+ * `stringifyCanonicalJson({ domainTag, version, fields })`. Both signer and verifier call this,
2764
+ * so the signed bytes are constructed one way, everywhere.
2765
+ *
2766
+ * Unlike the general serializer (which accepts `unknown` with documented compatibility
2767
+ * behaviors), this **rejects** anything that is not a strict {@link TCanonicalJsonValue}: values
2768
+ * that alias to the same JSON (`undefined` entries, sparse arrays, non-plain objects) are refused
2769
+ * rather than normalized — a signing API must not guess. An empty `domainTag` or a non-positive /
2770
+ * unsafe `version` throws.
2771
+ */
2772
+ function buildCanonicalChallenge(challenge) {
2773
+ if (typeof challenge.domainTag !== "string" || challenge.domainTag.length === 0) throw new Error("buildCanonicalChallenge: domainTag must be a non-empty string");
2774
+ if (typeof challenge.version !== "number" || !Number.isSafeInteger(challenge.version) || challenge.version < 1) throw new Error("buildCanonicalChallenge: version must be a positive safe integer");
2775
+ if (!isPlainObject$3(challenge.fields)) throw new Error("buildCanonicalChallenge: fields must be a plain object");
2776
+ for (const [key, value] of Object.entries(challenge.fields)) assertStrictCanonicalValue(value, `fields.${key}`);
2777
+ return stringifyCanonicalJson({
2778
+ domainTag: challenge.domainTag,
2779
+ version: challenge.version,
2780
+ fields: challenge.fields
2781
+ });
2782
+ }
2783
+ function isPlainObject$3(value) {
2784
+ if (typeof value !== "object" || value === null) return false;
2785
+ const proto = Object.getPrototypeOf(value);
2786
+ return proto === Object.prototype || proto === null;
2787
+ }
2788
+ function assertStrictCanonicalValue(value, path) {
2789
+ if (value === void 0) throw new Error(`buildCanonicalChallenge: undefined entry at ${path}`);
2790
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
2791
+ if (typeof value === "number") {
2792
+ if (!Number.isFinite(value)) throw new Error(`buildCanonicalChallenge: non-finite number at ${path}`);
2793
+ return;
2794
+ }
2795
+ if (Array.isArray(value)) {
2796
+ for (let i = 0; i < value.length; i++) {
2797
+ if (!(i in value)) throw new Error(`buildCanonicalChallenge: sparse array hole at ${path}[${i}]`);
2798
+ assertStrictCanonicalValue(value[i], `${path}[${i}]`);
2799
+ }
2800
+ return;
2801
+ }
2802
+ if (isPlainObject$3(value)) {
2803
+ for (const [key, entry] of Object.entries(value)) {
2804
+ if (entry === void 0) throw new Error(`buildCanonicalChallenge: undefined entry at ${path}.${key}`);
2805
+ assertStrictCanonicalValue(entry, `${path}.${key}`);
2806
+ }
2807
+ return;
2808
+ }
2809
+ throw new Error(`buildCanonicalChallenge: unsupported value at ${path} — strict JSON values only (null, boolean, finite number, string, dense array, plain object)`);
2810
+ }
2811
+ //#endregion
2812
+ //#region ../nice-util/src/data_type/bytes/base64.ts
2813
+ /**
2814
+ * Byte ⇄ base64 conversions that work in **every** JavaScript runtime — browsers, Node, Cloudflare
2815
+ * Workers, Deno, Bun, and React Native (Hermes) — without leaning on environment-specific interfaces:
2816
+ * the browser-only `btoa`/`atob` globals (absent in Hermes), or Node's `Buffer` (absent in browsers /
2817
+ * Workers / RN). Built on `@scure/base` (pure JS, audited, zero-dependency) — the same base64
2818
+ * implementation the crypto layer already uses, so the whole library stays consistent.
2819
+ *
2820
+ * Produces / consumes **standard** base64 (RFC 4648 §4: `+` and `/`, `=` padding) — byte-for-byte
2821
+ * interchangeable with `btoa`/`atob` and Node's `Buffer.toString("base64")`, so it interoperates with
2822
+ * any peer regardless of how that peer encodes.
2823
+ *
2824
+ * NOTE: the TC39 `Uint8Array.prototype.toBase64()` / `Uint8Array.fromBase64()` methods would be the
2825
+ * "native" choice, but as of 2026 they are not yet available across all target runtimes (notably Hermes),
2826
+ * so a pure-JS implementation remains the portable option.
2827
+ */
2828
+ function bytesToBase64(bytes) {
2829
+ return base64$1.encode(bytes);
2830
+ }
2831
+ function base64ToBytes(encoded) {
2832
+ return base64$1.decode(encoded);
2833
+ }
2834
+ //#endregion
2835
+ //#region ../nice-util/src/crypto/canonical/sha256.ts
2836
+ /**
2837
+ * Synchronous SHA-256 (FIPS 180-4) over a UTF-8 string or raw bytes. Synchronous on purpose:
2838
+ * definition-time hashes (e.g. nice-realm's schema hash at `defineRealm`) must be computable
2839
+ * during module evaluation in both Node and workerd, and `crypto.subtle.digest` is async — a
2840
+ * small pure implementation keeps callers synchronous and platform-stable. Moved here from
2841
+ * nice-realm (which re-exports `sha256Hex` from its `/internals` for compatibility); verified
2842
+ * against the FIPS 180-4 test vectors in `canonical.test.ts`.
2843
+ */
2844
+ const K = new Uint32Array([
2845
+ 1116352408,
2846
+ 1899447441,
2847
+ 3049323471,
2848
+ 3921009573,
2849
+ 961987163,
2850
+ 1508970993,
2851
+ 2453635748,
2852
+ 2870763221,
2853
+ 3624381080,
2854
+ 310598401,
2855
+ 607225278,
2856
+ 1426881987,
2857
+ 1925078388,
2858
+ 2162078206,
2859
+ 2614888103,
2860
+ 3248222580,
2861
+ 3835390401,
2862
+ 4022224774,
2863
+ 264347078,
2864
+ 604807628,
2865
+ 770255983,
2866
+ 1249150122,
2867
+ 1555081692,
2868
+ 1996064986,
2869
+ 2554220882,
2870
+ 2821834349,
2871
+ 2952996808,
2872
+ 3210313671,
2873
+ 3336571891,
2874
+ 3584528711,
2875
+ 113926993,
2876
+ 338241895,
2877
+ 666307205,
2878
+ 773529912,
2879
+ 1294757372,
2880
+ 1396182291,
2881
+ 1695183700,
2882
+ 1986661051,
2883
+ 2177026350,
2884
+ 2456956037,
2885
+ 2730485921,
2886
+ 2820302411,
2887
+ 3259730800,
2888
+ 3345764771,
2889
+ 3516065817,
2890
+ 3600352804,
2891
+ 4094571909,
2892
+ 275423344,
2893
+ 430227734,
2894
+ 506948616,
2895
+ 659060556,
2896
+ 883997877,
2897
+ 958139571,
2898
+ 1322822218,
2899
+ 1537002063,
2900
+ 1747873779,
2901
+ 1955562222,
2902
+ 2024104815,
2903
+ 2227730452,
2904
+ 2361852424,
2905
+ 2428436474,
2906
+ 2756734187,
2907
+ 3204031479,
2908
+ 3329325298
2909
+ ]);
2910
+ function rotr(x, n) {
2911
+ return x >>> n | x << 32 - n;
2912
+ }
2913
+ /** SHA-256 of a UTF-8 string or raw bytes, as the 32-byte digest. */
2914
+ function sha256Bytes(input) {
2915
+ const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
2916
+ const bitLen = bytes.length * 8;
2917
+ const paddedLen = (bytes.length + 8 >> 6) + 1 << 6;
2918
+ const padded = new Uint8Array(paddedLen);
2919
+ padded.set(bytes);
2920
+ padded[bytes.length] = 128;
2921
+ const view = new DataView(padded.buffer);
2922
+ view.setUint32(paddedLen - 8, Math.floor(bitLen / 4294967296), false);
2923
+ view.setUint32(paddedLen - 4, bitLen >>> 0, false);
2924
+ const h = new Uint32Array([
2925
+ 1779033703,
2926
+ 3144134277,
2927
+ 1013904242,
2928
+ 2773480762,
2929
+ 1359893119,
2930
+ 2600822924,
2931
+ 528734635,
2932
+ 1541459225
2933
+ ]);
2934
+ const w = new Uint32Array(64);
2935
+ for (let offset = 0; offset < paddedLen; offset += 64) {
2936
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
2937
+ for (let i = 16; i < 64; i++) {
2938
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
2939
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
2940
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
2941
+ }
2942
+ let a = h[0];
2943
+ let b = h[1];
2944
+ let c = h[2];
2945
+ let d = h[3];
2946
+ let e = h[4];
2947
+ let f = h[5];
2948
+ let g = h[6];
2949
+ let hh = h[7];
2950
+ for (let i = 0; i < 64; i++) {
2951
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
2952
+ const ch = e & f ^ ~e & g;
2953
+ const temp1 = hh + s1 + ch + K[i] + w[i] >>> 0;
2954
+ const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
2955
+ hh = g;
2956
+ g = f;
2957
+ f = e;
2958
+ e = d + temp1 >>> 0;
2959
+ d = c;
2960
+ c = b;
2961
+ b = a;
2962
+ a = temp1 + temp2 >>> 0;
2963
+ }
2964
+ h[0] = h[0] + a >>> 0;
2965
+ h[1] = h[1] + b >>> 0;
2966
+ h[2] = h[2] + c >>> 0;
2967
+ h[3] = h[3] + d >>> 0;
2968
+ h[4] = h[4] + e >>> 0;
2969
+ h[5] = h[5] + f >>> 0;
2970
+ h[6] = h[6] + g >>> 0;
2971
+ h[7] = h[7] + hh >>> 0;
2972
+ }
2973
+ const digest = new Uint8Array(32);
2974
+ const digestView = new DataView(digest.buffer);
2975
+ for (let i = 0; i < 8; i++) digestView.setUint32(i * 4, h[i], false);
2976
+ return digest;
2977
+ }
2978
+ /** SHA-256 of a UTF-8 string or raw bytes, as lowercase hex. */
2979
+ function sha256Hex(input) {
2980
+ const digest = sha256Bytes(input);
2981
+ let hex = "";
2982
+ for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
2983
+ return hex;
2984
+ }
2985
+ //#endregion
2697
2986
  //#region ../nice-util/src/crypto/ed25519/signTextDataWithKeyEd25519.ts
2698
2987
  const signTextDataWithKeyEd25519 = async (data, cryptoKey) => {
2699
2988
  const dataBuffer = new TextEncoder().encode(data);
2700
2989
  const signature = await crypto.subtle.sign({ name: "ED25519" }, cryptoKey, dataBuffer);
2701
2990
  return new Uint8Array(signature);
2702
2991
  };
2992
+ /**
2993
+ * ⚠ Separator-joining caller-controlled strings is a **concatenation-ambiguity** hazard: the parts
2994
+ * have no escaping, so `["a::b"]` and `["a","b"]` sign identical bytes, and two operations'
2995
+ * challenges can collide unless every call site adds its own fixed tag. For new signing surfaces
2996
+ * prefer the canonical challenge form (`buildCanonicalChallenge` /
2997
+ * `ClientCryptoKeyLink.signChallengeCanonical`) — exact field boundaries by construction. This
2998
+ * helper stays byte-for-byte for deployed contracts.
2999
+ */
2703
3000
  const signCombinedTextDataWithKeyEd25519 = async (data, cryptoKey, separator = "::") => {
2704
3001
  return await signTextDataWithKeyEd25519(data.join(separator), cryptoKey);
2705
3002
  };
@@ -2723,25 +3020,79 @@ const buildVerifyKeyBoundInfoString = ({ infoString, verifyPublicKeys }) => {
2723
3020
  return [...infoString != null ? [infoString] : [], ...sortedKeys].join("::");
2724
3021
  };
2725
3022
  //#endregion
3023
+ //#region ../nice-util/src/storage_adapter/typed_storage/StorageValidationError.ts
3024
+ /**
3025
+ * A typed-storage read, default, write, or update failed schema validation. Always thrown —
3026
+ * validation is fail-closed; the `onInvalid` option observes, it never suppresses. Carries the
3027
+ * storage `key` and the schema's `issues` so callers can branch (e.g. treat a corrupt record as
3028
+ * absent, run a migration, or surface telemetry).
3029
+ */
3030
+ var StorageValidationError = class extends Error {
3031
+ key;
3032
+ issues;
3033
+ constructor(key, issues) {
3034
+ const rendered = issues.map((issue, index) => {
3035
+ const path = issue.path?.map((segment) => typeof segment === "object" ? String(segment.key) : String(segment)).join(".");
3036
+ return ` (issue ${index + 1})${path ? ` [${path}]` : ""}: ${issue.message}`;
3037
+ }).join("\n");
3038
+ super(`Typed storage validation failed for key "${key}":\n${rendered}`);
3039
+ this.name = "StorageValidationError";
3040
+ this.key = key;
3041
+ this.issues = issues;
3042
+ }
3043
+ };
3044
+ //#endregion
2726
3045
  //#region ../nice-util/src/storage_adapter/typed_storage/createTypedStorage.ts
2727
- function createTypedStorage({ storageAdapter }) {
3046
+ /**
3047
+ * A typed view over a {@link StorageAdapter}. Without `schemas` it is types-only (the stored value
3048
+ * is trusted to match `T` — fine for values only your own code writes). With `schemas`, the
3049
+ * storage boundary gets the same treatment the action layer gives the wire: values are validated
3050
+ * on the way out **and** in, because durable storage is where stale shapes live longest — a value
3051
+ * written by version N and read by version N+3 has crossed every schema change in between.
3052
+ */
3053
+ function createTypedStorage({ storageAdapter, schemas, onInvalid }) {
3054
+ const validate = (key, value) => {
3055
+ const schema = schemas?.[key];
3056
+ if (schema == null) return value;
3057
+ const result = schema["~standard"].validate(value);
3058
+ let issues;
3059
+ if (result instanceof Promise) issues = [{ message: "async schema validation is not supported for typed storage" }];
3060
+ else if (result.issues != null) issues = result.issues;
3061
+ else return result.value;
3062
+ const error = new StorageValidationError(key, issues);
3063
+ onInvalid?.(error);
3064
+ throw error;
3065
+ };
3066
+ const hasSchema = (key) => schemas?.[key] != null;
2728
3067
  const getJson = async (key) => {
2729
- return storageAdapter.getJson(key);
3068
+ const stored = await storageAdapter.getJson(key);
3069
+ if (stored === void 0 || !hasSchema(key)) return stored;
3070
+ return validate(key, stored);
2730
3071
  };
2731
3072
  const getJsonOrDef = async (key, defVal) => {
2732
- return await storageAdapter.getJson(key) ?? defVal;
3073
+ const value = await storageAdapter.getJson(key) ?? defVal;
3074
+ if (!hasSchema(key)) return value;
3075
+ return validate(key, value);
2733
3076
  };
2734
3077
  const setJson = async (key, val) => {
2735
- return storageAdapter.setJson(key, val);
3078
+ return storageAdapter.setJson(key, hasSchema(key) ? validate(key, val) : val);
2736
3079
  };
2737
3080
  const removeItem = async (key) => {
2738
3081
  await storageAdapter.removeItem(key);
2739
3082
  };
2740
3083
  const updateJson = async (key, updater) => {
2741
- await storageAdapter.updateJson(key, updater);
3084
+ if (!hasSchema(key)) {
3085
+ await storageAdapter.updateJson(key, updater);
3086
+ return;
3087
+ }
3088
+ await storageAdapter.updateJson(key, (currentVal) => validate(key, updater(currentVal === void 0 ? void 0 : validate(key, currentVal))));
2742
3089
  };
2743
3090
  const updateJsonWithDef = async (key, defaultVal, updater) => {
2744
- await storageAdapter.updateJsonOrDef(key, defaultVal, updater);
3091
+ if (!hasSchema(key)) {
3092
+ await storageAdapter.updateJsonOrDef(key, defaultVal, updater);
3093
+ return;
3094
+ }
3095
+ await storageAdapter.updateJsonOrDef(key, defaultVal, (currentVal) => validate(key, updater(validate(key, currentVal))));
2745
3096
  };
2746
3097
  return {
2747
3098
  getJson,
@@ -4024,6 +4375,13 @@ var ClientCryptoKeyLink = class {
4024
4375
  })
4025
4376
  };
4026
4377
  }
4378
+ /**
4379
+ * ⚠ Multi-part challenges join with `"::"` — a **concatenation-ambiguity** hazard: when a caller
4380
+ * controls two adjacent parts, distinct tuples can produce identical signed bytes (`["a::b"]`
4381
+ * vs `["a","b"]`), and two operations' challenges can collide unless every call site remembers
4382
+ * its own fixed tag. Prefer {@link signChallengeCanonical}: domain-tagged, versioned, exact
4383
+ * field boundaries by construction. This method stays byte-for-byte for deployed contracts.
4384
+ */
4027
4385
  async signChallenge(challenge) {
4028
4386
  if (challenge.length === 0) throw new Error("Challenge must contain at least one string");
4029
4387
  const localVerifyKeyPair = await this.ensureLocalVerifyKeyPair();
@@ -4031,6 +4389,27 @@ var ClientCryptoKeyLink = class {
4031
4389
  return { signatureBase64: base64$1.encode(signature) };
4032
4390
  }
4033
4391
  /**
4392
+ * Sign a {@link ICanonicalChallenge} — the canonical, domain-tagged, versioned challenge form
4393
+ * ({@link buildCanonicalChallenge} defines the signed bytes). Same key and signature scheme as
4394
+ * {@link signChallenge}, safer byte layout; the verify dual is
4395
+ * {@link verifyChallengeCanonicalFromLinkedClient}, which takes the same structured challenge.
4396
+ */
4397
+ async signChallengeCanonical(challenge) {
4398
+ return this.signChallenge([buildCanonicalChallenge(challenge)]);
4399
+ }
4400
+ /**
4401
+ * Verify a signature produced by {@link signChallengeCanonical} against the linked client's
4402
+ * verify key. Takes the **structured** challenge and rebuilds the canonical string itself, so
4403
+ * signer and verifier can never disagree on byte construction.
4404
+ */
4405
+ async verifyChallengeCanonicalFromLinkedClient({ linkedClientId, challenge, signatureBase64 }) {
4406
+ return this.verifyChallengeFromLinkedClient({
4407
+ linkedClientId,
4408
+ challenge: buildCanonicalChallenge(challenge),
4409
+ signatureBase64
4410
+ });
4411
+ }
4412
+ /**
4034
4413
  * Verifies a signature over `challenge` against the linked client's verify (Ed25519) public key.
4035
4414
  */
4036
4415
  async verifyChallengeFromLinkedClient({ linkedClientId, challenge, signatureBase64 }) {
@@ -4044,29 +4423,6 @@ var ClientCryptoKeyLink = class {
4044
4423
  }
4045
4424
  };
4046
4425
  //#endregion
4047
- //#region ../nice-util/src/data_type/bytes/base64.ts
4048
- /**
4049
- * Byte ⇄ base64 conversions that work in **every** JavaScript runtime — browsers, Node, Cloudflare
4050
- * Workers, Deno, Bun, and React Native (Hermes) — without leaning on environment-specific interfaces:
4051
- * the browser-only `btoa`/`atob` globals (absent in Hermes), or Node's `Buffer` (absent in browsers /
4052
- * Workers / RN). Built on `@scure/base` (pure JS, audited, zero-dependency) — the same base64
4053
- * implementation the crypto layer already uses, so the whole library stays consistent.
4054
- *
4055
- * Produces / consumes **standard** base64 (RFC 4648 §4: `+` and `/`, `=` padding) — byte-for-byte
4056
- * interchangeable with `btoa`/`atob` and Node's `Buffer.toString("base64")`, so it interoperates with
4057
- * any peer regardless of how that peer encodes.
4058
- *
4059
- * NOTE: the TC39 `Uint8Array.prototype.toBase64()` / `Uint8Array.fromBase64()` methods would be the
4060
- * "native" choice, but as of 2026 they are not yet available across all target runtimes (notably Hermes),
4061
- * so a pure-JS implementation remains the portable option.
4062
- */
4063
- function bytesToBase64(bytes) {
4064
- return base64$1.encode(bytes);
4065
- }
4066
- function base64ToBytes(encoded) {
4067
- return base64$1.decode(encoded);
4068
- }
4069
- //#endregion
4070
4426
  //#region ../nice-util/src/storage_adapter/StorageAdapter.ts
4071
4427
  var StorageAdapter = class StorageAdapter {
4072
4428
  implementation;
@@ -10215,6 +10571,7 @@ const err_nice_action = err_nice.createChildDomain({
10215
10571
  ["not_implemented"]: err({ message: ({ label }) => `The "${label}" functionality is not implemented yet.` }),
10216
10572
  ["action_id_not_in_domain"]: err({ message: ({ actionId, domain }) => `Action with id "${actionId}" does not exist in domain "${domain}".` }),
10217
10573
  ["domain_already_exists_in_hierarchy"]: err({ message: ({ domain, allParentDomains, parentDomain }) => `Domain "${domain}" already exists in the hierarchy under the parent "${parentDomain}". All parent domains ["${allParentDomains.join(", ")}"]` }),
10574
+ ["domain_name_collision"]: err({ message: ({ domain, existingParentDomains, incomingParentDomains }) => `Two different domain definitions named "${domain}" were registered on one runtime router (existing under [${existingParentDomains.join(" > ")}], incoming under [${incomingParentDomains.join(" > ")}]). Wire routing is by name only, so the later registration would silently shadow the earlier one — give the domains distinct names, or register the same instance.` }),
10218
10575
  ["domain_no_handler"]: err({ message: ({ domain }) => `Domain "${domain}" has no action handler registered.` }),
10219
10576
  ["hydration_domain_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: domain mismatch. Expected "${expected}", got "${received}".` }),
10220
10577
  ["hydration_action_state_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: action state type mismatch. Expected "${expected}", got "${received}".` }),
@@ -12007,6 +12364,13 @@ var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
12007
12364
  var ActionDomainManager = class {
12008
12365
  _domains = /* @__PURE__ */ new Map();
12009
12366
  addDomain(domain) {
12367
+ const existing = this._domains.get(domain.domain);
12368
+ if (existing === domain) return;
12369
+ if (existing != null) throw err_nice_action.fromId("domain_name_collision", {
12370
+ domain: domain.domain,
12371
+ existingParentDomains: existing.allDomains,
12372
+ incomingParentDomains: domain.allDomains
12373
+ });
12010
12374
  this._domains.set(domain.domain, domain);
12011
12375
  }
12012
12376
  getDomains() {
@@ -15791,6 +16155,35 @@ function isExchangeAcceptorCarrier(carrier) {
15791
16155
  }
15792
16156
  //#endregion
15793
16157
  //#region ../nice-action/src/ActionRuntime/Channel/serveChannel.ts
16158
+ /**
16159
+ * Build the per-connection subset resolver a multi-channel acceptor uses: advertised `hello.channels`
16160
+ * tags → the channel that connection speaks (its own codec + dictionary version for a single tag, the
16161
+ * composed union for several, the combined `channel` for none). Returns `null` — the handshake then
16162
+ * rejects — for an unknown tag, and for a repeated tag: a repeat would compose the same channel twice
16163
+ * into the positional wire dictionary and desync every later route index.
16164
+ *
16165
+ * Throws immediately (setup time, not per connection) when two served channels share a tag — a
16166
+ * last-write-wins registry could never route that deterministically.
16167
+ */
16168
+ function buildChannelSubsetResolver(combined, registry) {
16169
+ const byTag = /* @__PURE__ */ new Map();
16170
+ for (const entry of registry) {
16171
+ if (byTag.has(entry.tag)) throw new Error(`serveChannel: duplicate channel tag "${entry.tag}" in \`channels\` — every served channel needs a distinct tag, or subset selection cannot route deterministically.`);
16172
+ byTag.set(entry.tag, entry);
16173
+ }
16174
+ return (tags) => {
16175
+ if (tags == null || tags.length === 0) return combined;
16176
+ const selected = [];
16177
+ const seen = /* @__PURE__ */ new Set();
16178
+ for (const tag of tags) {
16179
+ const found = byTag.get(tag);
16180
+ if (found == null || seen.has(tag)) return null;
16181
+ seen.add(tag);
16182
+ selected.push(found);
16183
+ }
16184
+ return selected.length === 1 ? selected[0] : combineChannels(selected);
16185
+ };
16186
+ }
15794
16187
  /** Default accepted set, shared by every carrier: negotiate per connection to whatever the client picks. */
15795
16188
  const DEFAULT_SERVER_SECURITY_LEVELS = [
15796
16189
  "none",
@@ -15809,19 +16202,7 @@ function serveChannel(runtime, channel, options) {
15809
16202
  const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
15810
16203
  const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
15811
16204
  const registry = options.channels;
15812
- const resolveChannel = registry != null && registry.length > 1 ? (() => {
15813
- const byTag = new Map(registry.map((entry) => [entry.tag, entry]));
15814
- return (tags) => {
15815
- if (tags == null || tags.length === 0) return channel;
15816
- const selected = [];
15817
- for (const tag of tags) {
15818
- const found = byTag.get(tag);
15819
- if (found == null) return null;
15820
- selected.push(found);
15821
- }
15822
- return selected.length === 1 ? selected[0] : combineChannels(selected);
15823
- };
15824
- })() : void 0;
16205
+ const resolveChannel = registry != null && registry.length > 1 ? buildChannelSubsetResolver(channel, registry) : void 0;
15825
16206
  let secure;
15826
16207
  if (anyDuplexSecure || exchangeSecure) {
15827
16208
  const storage = options.storage;
@@ -16556,11 +16937,11 @@ var VALUE = "value";
16556
16937
  var isDraft = (value) => !!value && !!value[DRAFT_STATE];
16557
16938
  function isDraftable(value) {
16558
16939
  if (!value) return false;
16559
- return isPlainObject$1(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
16940
+ return isPlainObject$2(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
16560
16941
  }
16561
16942
  var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
16562
16943
  var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
16563
- function isPlainObject$1(value) {
16944
+ function isPlainObject$2(value) {
16564
16945
  if (!value || !isObjectish(value)) return false;
16565
16946
  const proto = getPrototypeOf(value);
16566
16947
  if (proto === null || proto === O[PROTOTYPE]) return true;
@@ -16615,7 +16996,7 @@ function shallowCopy(base, strict) {
16615
16996
  if (isMap(base)) return new Map(base);
16616
16997
  if (isSet(base)) return new Set(base);
16617
16998
  if (isArray(base)) return Array[PROTOTYPE].slice.call(base);
16618
- const isPlain = isPlainObject$1(base);
16999
+ const isPlain = isPlainObject$2(base);
16619
17000
  if (strict === true || strict === "class_only" && !isPlain) {
16620
17001
  const descriptors = O.getOwnPropertyDescriptors(base);
16621
17002
  delete descriptors[DRAFT_STATE];
@@ -17899,21 +18280,45 @@ const err_realm = err_nice.createChildDomain({
17899
18280
  });
17900
18281
  //#endregion
17901
18282
  //#region ../nice-realm/src/RealmDefinition/Schema/validateValue.ts
17902
- function isPlainObject(value) {
18283
+ function isPlainObject$1(value) {
17903
18284
  return typeof value === "object" && value != null && !Array.isArray(value) && !(value instanceof Uint8Array);
17904
18285
  }
17905
18286
  /** `undefined` = valid; otherwise where and what was expected. */
17906
18287
  function validateValue(node, value) {
17907
18288
  switch (node.kind) {
17908
- case "string": return typeof value === "string" ? void 0 : {
17909
- path: [],
17910
- expected: "string"
17911
- };
17912
- case "number": return typeof value === "number" ? void 0 : {
17913
- path: [],
17914
- expected: "number"
17915
- };
17916
- case "boolean": return typeof value === "boolean" ? void 0 : {
18289
+ case "string":
18290
+ if (typeof value !== "string") return {
18291
+ path: [],
18292
+ expected: "string"
18293
+ };
18294
+ if (node.maxLength != null && value.length > node.maxLength) return {
18295
+ path: [],
18296
+ expected: `a string of at most ${node.maxLength} characters`
18297
+ };
18298
+ return;
18299
+ case "number":
18300
+ if (typeof value !== "number") return {
18301
+ path: [],
18302
+ expected: "number"
18303
+ };
18304
+ if ((node.min != null || node.max != null || node.integer === true) && !Number.isFinite(value)) return {
18305
+ path: [],
18306
+ expected: "a finite number"
18307
+ };
18308
+ if (node.integer === true && !Number.isInteger(value)) return {
18309
+ path: [],
18310
+ expected: "an integer"
18311
+ };
18312
+ if (node.min != null && value < node.min) return {
18313
+ path: [],
18314
+ expected: `a number >= ${node.min}`
18315
+ };
18316
+ if (node.max != null && value > node.max) return {
18317
+ path: [],
18318
+ expected: `a number <= ${node.max}`
18319
+ };
18320
+ return;
18321
+ case "boolean": return typeof value === "boolean" ? void 0 : {
17917
18322
  path: [],
17918
18323
  expected: "boolean"
17919
18324
  };
@@ -17929,7 +18334,7 @@ function validateValue(node, value) {
17929
18334
  expected: "one of the union options"
17930
18335
  };
17931
18336
  case "object":
17932
- if (!isPlainObject(value)) return {
18337
+ if (!isPlainObject$1(value)) return {
17933
18338
  path: [],
17934
18339
  expected: "object"
17935
18340
  };
@@ -17954,10 +18359,14 @@ function validateValue(node, value) {
17954
18359
  }
17955
18360
  return;
17956
18361
  case "record":
17957
- if (!isPlainObject(value)) return {
18362
+ if (!isPlainObject$1(value)) return {
17958
18363
  path: [],
17959
18364
  expected: "record"
17960
18365
  };
18366
+ if (node.maxKeys != null && Object.keys(value).length > node.maxKeys) return {
18367
+ path: [],
18368
+ expected: `a record with at most ${node.maxKeys} entries`
18369
+ };
17961
18370
  for (const [key, entry] of Object.entries(value)) {
17962
18371
  const invalid = validateValue(node.value, entry);
17963
18372
  if (invalid != null) return {
@@ -17971,6 +18380,10 @@ function validateValue(node, value) {
17971
18380
  path: [],
17972
18381
  expected: "array"
17973
18382
  };
18383
+ if (node.maxItems != null && value.length > node.maxItems) return {
18384
+ path: [],
18385
+ expected: `an array of at most ${node.maxItems} items`
18386
+ };
17974
18387
  for (let i = 0; i < value.length; i++) {
17975
18388
  const invalid = validateValue(node.item, value[i]);
17976
18389
  if (invalid != null) return {
@@ -18455,8 +18868,8 @@ const WIRE_OP_TO_IMMER = {
18455
18868
  [REALM_OP.add]: "add",
18456
18869
  [REALM_OP.remove]: "remove"
18457
18870
  };
18458
- function unwrapOptional$5(node) {
18459
- return node.kind === "optional" ? unwrapOptional$5(node.inner) : node;
18871
+ function unwrapOptional$6(node) {
18872
+ return node.kind === "optional" ? unwrapOptional$6(node.inner) : node;
18460
18873
  }
18461
18874
  /** The schema node a name path addresses (undefined when the path leaves the schema). */
18462
18875
  function schemaNodeAtPath(root, path) {
@@ -18467,7 +18880,7 @@ function schemaNodeAtPath(root, path) {
18467
18880
  node = typeof seg === "string" ? entries[seg] : void 0;
18468
18881
  entries = void 0;
18469
18882
  } else if (node != null) {
18470
- const inner = unwrapOptional$5(node);
18883
+ const inner = unwrapOptional$6(node);
18471
18884
  if (inner.kind === "object") node = inner.entries[seg];
18472
18885
  else if (inner.kind === "record") node = inner.value;
18473
18886
  else return void 0;
@@ -18476,7 +18889,7 @@ function schemaNodeAtPath(root, path) {
18476
18889
  }
18477
18890
  return node;
18478
18891
  }
18479
- function getAtPath$5(state, path) {
18892
+ function getAtPath$6(state, path) {
18480
18893
  let current = state;
18481
18894
  for (const seg of path) {
18482
18895
  if (current == null || typeof current !== "object") return void 0;
@@ -18488,7 +18901,7 @@ function getAtPath$5(state, path) {
18488
18901
  function arrayCutIndex(root, path) {
18489
18902
  for (let i = 1; i < path.length; i++) {
18490
18903
  const node = schemaNodeAtPath(root, path.slice(0, i));
18491
- if (node != null && unwrapOptional$5(node).kind === "array") return i;
18904
+ if (node != null && unwrapOptional$6(node).kind === "array") return i;
18492
18905
  }
18493
18906
  }
18494
18907
  /**
@@ -18512,7 +18925,7 @@ function canonicalizeStatePatches(patches, stateAfter, schemaRoot) {
18512
18925
  out.push({
18513
18926
  op: "replace",
18514
18927
  path: arrayPath,
18515
- value: getAtPath$5(stateAfter, arrayPath)
18928
+ value: getAtPath$6(stateAfter, arrayPath)
18516
18929
  });
18517
18930
  }
18518
18931
  return out;
@@ -18712,10 +19125,10 @@ function viewSignatureKey(avatar) {
18712
19125
  * leaves are covered too). For `remove`, from the current state alone. Expansion is bounded by
18713
19126
  * `maxLeaves` (an ingress limit — a hostile deep-subtree write must not become CPU).
18714
19127
  */
18715
- function unwrapOptional$4(node) {
18716
- return node.kind === "optional" ? unwrapOptional$4(node.inner) : node;
19128
+ function unwrapOptional$5(node) {
19129
+ return node.kind === "optional" ? unwrapOptional$5(node.inner) : node;
18717
19130
  }
18718
- function getAtPath$4(state, path) {
19131
+ function getAtPath$5(state, path) {
18719
19132
  let current = state;
18720
19133
  for (const seg of path) {
18721
19134
  if (current == null || typeof current !== "object") return void 0;
@@ -18737,7 +19150,7 @@ function expandWriteToLeaves(options) {
18737
19150
  leaves.push(leaf);
18738
19151
  };
18739
19152
  const walk = (schemaNode, path, value, prev) => {
18740
- const inner = unwrapOptional$4(schemaNode);
19153
+ const inner = unwrapOptional$5(schemaNode);
18741
19154
  if (inner.kind === "object") {
18742
19155
  for (const [key, child] of Object.entries(inner.entries)) walk(child, [...path, key], value == null ? void 0 : value[key], prev == null ? void 0 : prev[key]);
18743
19156
  return;
@@ -18751,7 +19164,7 @@ function expandWriteToLeaves(options) {
18751
19164
  }
18752
19165
  push(path);
18753
19166
  };
18754
- const prev = getAtPath$4(options.state, options.path);
19167
+ const prev = getAtPath$5(options.state, options.path);
18755
19168
  walk(node, [...options.path], options.op === "remove" ? void 0 : options.value, prev);
18756
19169
  return leaves;
18757
19170
  }
@@ -18763,6 +19176,14 @@ function expandWriteToLeaves(options) {
18763
19176
  * slice of optimism that can later roll back), `prev`/`state` come from the writer's projected
18764
19177
  * view. A NiceError here rejects the write in the same tick, before anything renders.
18765
19178
  */
19179
+ function getProjectedAtPath(state, path) {
19180
+ let current = state;
19181
+ for (const seg of path) {
19182
+ if (current == null || typeof current !== "object") return void 0;
19183
+ current = current[seg];
19184
+ }
19185
+ return current;
19186
+ }
18766
19187
  function predictWrite(options) {
18767
19188
  const { realm, avatar, state, basisVersion } = options;
18768
19189
  for (const patch of options.patches) {
@@ -18778,6 +19199,17 @@ function predictWrite(options) {
18778
19199
  path: [...path, ...invalid.path].join("."),
18779
19200
  expected: invalid.expected
18780
19201
  });
19202
+ for (let i = 1; i < path.length; i++) {
19203
+ let ancestor = schemaNodeAtPath(realm.stateDef, path.slice(0, i));
19204
+ while (ancestor?.kind === "optional") ancestor = ancestor.inner;
19205
+ if (ancestor?.kind !== "record" || ancestor.maxKeys == null) continue;
19206
+ const container = getProjectedAtPath(state, path.slice(0, i));
19207
+ if (container == null || typeof container !== "object" || Array.isArray(container)) continue;
19208
+ if (!(path[i] in container) && Object.keys(container).length >= ancestor.maxKeys) return err_realm.fromId("value_invalid", {
19209
+ path: path.slice(0, i).join("."),
19210
+ expected: `a record with at most ${ancestor.maxKeys} entries`
19211
+ });
19212
+ }
18781
19213
  }
18782
19214
  const leaves = expandWriteToLeaves({
18783
19215
  schemaRoot: realm.stateDef,
@@ -18794,8 +19226,8 @@ function predictWrite(options) {
18794
19226
  const verdict = evalAlterCond(match.rule.alter, {
18795
19227
  avatar,
18796
19228
  params: match.params,
18797
- prev: getAtPath$3(state, leafPath),
18798
- next: patch.op === "remove" ? void 0 : getAtPath$3(patch.value, rel),
19229
+ prev: getAtPath$4(state, leafPath),
19230
+ next: patch.op === "remove" ? void 0 : getAtPath$4(patch.value, rel),
18799
19231
  state,
18800
19232
  basisVersion
18801
19233
  }, void 0);
@@ -18805,7 +19237,7 @@ function predictWrite(options) {
18805
19237
  }
18806
19238
  return true;
18807
19239
  }
18808
- function getAtPath$3(state, path) {
19240
+ function getAtPath$4(state, path) {
18809
19241
  let current = state;
18810
19242
  for (const seg of path) {
18811
19243
  if (current == null || typeof current !== "object") return void 0;
@@ -18837,10 +19269,10 @@ function withStructuralParents(state, patches, schemaRoot) {
18837
19269
  const prefix = patch.path.slice(0, depth);
18838
19270
  if (prefixResolves(state, out ?? patches.slice(0, index), prefix)) continue;
18839
19271
  const parentNode = depth === 1 ? void 0 : schemaNodeAtPath(schemaRoot, prefix.slice(0, -1));
18840
- if (parentNode != null && unwrapOptional$3(parentNode).kind === "record") break;
19272
+ if (parentNode != null && unwrapOptional$4(parentNode).kind === "record") break;
18841
19273
  const node = schemaNodeAtPath(schemaRoot, prefix);
18842
19274
  if (node == null) break;
18843
- const kind = unwrapOptional$3(node).kind;
19275
+ const kind = unwrapOptional$4(node).kind;
18844
19276
  if (kind !== "object" && kind !== "record") break;
18845
19277
  out ??= patches.slice(0, index);
18846
19278
  out.push({
@@ -18860,14 +19292,14 @@ function prefixResolves(state, earlier, prefix) {
18860
19292
  if (patch.path.length > prefix.length) continue;
18861
19293
  if (!patch.path.every((seg, j) => String(seg) === String(prefix[j]))) continue;
18862
19294
  if (patch.op === "remove") return false;
18863
- return getAtPath$2(patch.value, prefix.slice(patch.path.length)) !== void 0;
19295
+ return getAtPath$3(patch.value, prefix.slice(patch.path.length)) !== void 0;
18864
19296
  }
18865
- return getAtPath$2(state, prefix) !== void 0;
19297
+ return getAtPath$3(state, prefix) !== void 0;
18866
19298
  }
18867
- function unwrapOptional$3(node) {
18868
- return node.kind === "optional" ? unwrapOptional$3(node.inner) : node;
19299
+ function unwrapOptional$4(node) {
19300
+ return node.kind === "optional" ? unwrapOptional$4(node.inner) : node;
18869
19301
  }
18870
- function getAtPath$2(value, path) {
19302
+ function getAtPath$3(value, path) {
18871
19303
  let current = value;
18872
19304
  for (const seg of path) {
18873
19305
  if (current == null || typeof current !== "object") return void 0;
@@ -20422,20 +20854,20 @@ function assertTransientRoots(root, dotPaths) {
20422
20854
  /** Walk a concrete (literal-only) path through the schema; `undefined` if it leaves the schema. */
20423
20855
  function resolveConcretePath(node, segments, index) {
20424
20856
  if (index >= segments.length) return node;
20425
- const inner = unwrapOptional$2(node);
20857
+ const inner = unwrapOptional$3(node);
20426
20858
  if (inner.kind === "object") {
20427
20859
  const child = inner.entries[segments[index]];
20428
20860
  return child == null ? void 0 : resolveConcretePath(child, segments, index + 1);
20429
20861
  }
20430
20862
  if (inner.kind === "record") return resolveConcretePath(inner.value, segments, index + 1);
20431
20863
  }
20432
- function unwrapOptional$2(node) {
20433
- return node.kind === "optional" ? unwrapOptional$2(node.inner) : node;
20864
+ function unwrapOptional$3(node) {
20865
+ return node.kind === "optional" ? unwrapOptional$3(node.inner) : node;
20434
20866
  }
20435
20867
  /** `undefined` = the pattern can match; otherwise a description of why it never will. */
20436
20868
  function checkSegments(node, segments, index) {
20437
20869
  if (index >= segments.length) return void 0;
20438
- const inner = unwrapOptional$2(node);
20870
+ const inner = unwrapOptional$3(node);
20439
20871
  const seg = segments[index];
20440
20872
  const at = describePrefix(segments, index);
20441
20873
  if (inner.kind === "object") {
@@ -20554,147 +20986,6 @@ var RealmRuleTrie = class {
20554
20986
  }
20555
20987
  };
20556
20988
  //#endregion
20557
- //#region ../nice-realm/src/RealmDefinition/Schema/sha256.ts
20558
- /**
20559
- * Synchronous SHA-256 over a UTF-8 string → lowercase hex. The schema hash must be computable at
20560
- * `defineRealm` time (module evaluation, both Node and workerd) — `crypto.subtle.digest` is async,
20561
- * so a small pure implementation keeps the definition object synchronous and platform-stable.
20562
- * Verified against the FIPS 180-4 test vectors in `sha256.test.ts`.
20563
- */
20564
- const K = new Uint32Array([
20565
- 1116352408,
20566
- 1899447441,
20567
- 3049323471,
20568
- 3921009573,
20569
- 961987163,
20570
- 1508970993,
20571
- 2453635748,
20572
- 2870763221,
20573
- 3624381080,
20574
- 310598401,
20575
- 607225278,
20576
- 1426881987,
20577
- 1925078388,
20578
- 2162078206,
20579
- 2614888103,
20580
- 3248222580,
20581
- 3835390401,
20582
- 4022224774,
20583
- 264347078,
20584
- 604807628,
20585
- 770255983,
20586
- 1249150122,
20587
- 1555081692,
20588
- 1996064986,
20589
- 2554220882,
20590
- 2821834349,
20591
- 2952996808,
20592
- 3210313671,
20593
- 3336571891,
20594
- 3584528711,
20595
- 113926993,
20596
- 338241895,
20597
- 666307205,
20598
- 773529912,
20599
- 1294757372,
20600
- 1396182291,
20601
- 1695183700,
20602
- 1986661051,
20603
- 2177026350,
20604
- 2456956037,
20605
- 2730485921,
20606
- 2820302411,
20607
- 3259730800,
20608
- 3345764771,
20609
- 3516065817,
20610
- 3600352804,
20611
- 4094571909,
20612
- 275423344,
20613
- 430227734,
20614
- 506948616,
20615
- 659060556,
20616
- 883997877,
20617
- 958139571,
20618
- 1322822218,
20619
- 1537002063,
20620
- 1747873779,
20621
- 1955562222,
20622
- 2024104815,
20623
- 2227730452,
20624
- 2361852424,
20625
- 2428436474,
20626
- 2756734187,
20627
- 3204031479,
20628
- 3329325298
20629
- ]);
20630
- function rotr(x, n) {
20631
- return x >>> n | x << 32 - n;
20632
- }
20633
- /** SHA-256 of a UTF-8 string, as lowercase hex. */
20634
- function sha256Hex(input) {
20635
- const bytes = new TextEncoder().encode(input);
20636
- const bitLen = bytes.length * 8;
20637
- const paddedLen = (bytes.length + 8 >> 6) + 1 << 6;
20638
- const padded = new Uint8Array(paddedLen);
20639
- padded.set(bytes);
20640
- padded[bytes.length] = 128;
20641
- const view = new DataView(padded.buffer);
20642
- view.setUint32(paddedLen - 8, Math.floor(bitLen / 4294967296), false);
20643
- view.setUint32(paddedLen - 4, bitLen >>> 0, false);
20644
- const h = new Uint32Array([
20645
- 1779033703,
20646
- 3144134277,
20647
- 1013904242,
20648
- 2773480762,
20649
- 1359893119,
20650
- 2600822924,
20651
- 528734635,
20652
- 1541459225
20653
- ]);
20654
- const w = new Uint32Array(64);
20655
- for (let offset = 0; offset < paddedLen; offset += 64) {
20656
- for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
20657
- for (let i = 16; i < 64; i++) {
20658
- const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
20659
- const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
20660
- w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
20661
- }
20662
- let a = h[0];
20663
- let b = h[1];
20664
- let c = h[2];
20665
- let d = h[3];
20666
- let e = h[4];
20667
- let f = h[5];
20668
- let g = h[6];
20669
- let hh = h[7];
20670
- for (let i = 0; i < 64; i++) {
20671
- const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
20672
- const ch = e & f ^ ~e & g;
20673
- const temp1 = hh + s1 + ch + K[i] + w[i] >>> 0;
20674
- const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
20675
- hh = g;
20676
- g = f;
20677
- f = e;
20678
- e = d + temp1 >>> 0;
20679
- d = c;
20680
- c = b;
20681
- b = a;
20682
- a = temp1 + temp2 >>> 0;
20683
- }
20684
- h[0] = h[0] + a >>> 0;
20685
- h[1] = h[1] + b >>> 0;
20686
- h[2] = h[2] + c >>> 0;
20687
- h[3] = h[3] + d >>> 0;
20688
- h[4] = h[4] + e >>> 0;
20689
- h[5] = h[5] + f >>> 0;
20690
- h[6] = h[6] + g >>> 0;
20691
- h[7] = h[7] + hh >>> 0;
20692
- }
20693
- let hex = "";
20694
- for (let i = 0; i < 8; i++) hex += h[i].toString(16).padStart(8, "0");
20695
- return hex;
20696
- }
20697
- //#endregion
20698
20989
  //#region ../nice-realm/src/RealmDefinition/Schema/schemaHash.ts
20699
20990
  /**
20700
20991
  * The realm schema hash (plan §4.1/§7.1-of-proposal): SHA-256 over a canonical serialization of
@@ -20704,13 +20995,24 @@ function sha256Hex(input) {
20704
20995
  * stale mobile client would be data corruption, not an error.
20705
20996
  *
20706
20997
  * Known, documented limitation: an embedded standard-schema validator (`t.schema(...)`) is opaque
20707
- * — its internals don't affect the hash (canonicalized as just `std`). Treat embedded-validator
20708
- * edits as value-rule changes, not shape changes.
20998
+ * — its internals don't affect the hash (canonicalized as just `std`) unless the leaf opts in
20999
+ * with `t.schema(v, { hashTag })`, which the consumer bumps on contract changes. Untagged, treat
21000
+ * embedded-validator edits as value-rule changes, not shape changes.
20709
21001
  */
20710
21002
  function canonNode(node) {
20711
21003
  switch (node.kind) {
20712
- case "string":
21004
+ case "string": return node.maxLength == null ? node.kind : {
21005
+ k: "string",
21006
+ max: node.maxLength
21007
+ };
20713
21008
  case "number":
21009
+ if (node.min == null && node.max == null && node.integer !== true) return node.kind;
21010
+ return {
21011
+ k: "number",
21012
+ ...node.min != null ? { min: node.min } : {},
21013
+ ...node.max != null ? { max: node.max } : {},
21014
+ ...node.integer === true ? { int: true } : {}
21015
+ };
20714
21016
  case "boolean": return node.kind;
20715
21017
  case "literal": return {
20716
21018
  k: "lit",
@@ -20728,16 +21030,31 @@ function canonNode(node) {
20728
21030
  k: "obj",
20729
21031
  e: Object.keys(node.entries).sort().map((n) => [n, canonNode(node.entries[n])])
20730
21032
  };
20731
- case "record": return {
20732
- k: "rec",
20733
- id: node.keyVar,
20734
- v: canonNode(node.value)
20735
- };
20736
- case "array": return {
20737
- k: "arr",
20738
- i: canonNode(node.item)
21033
+ case "record": {
21034
+ const base = {
21035
+ k: "rec",
21036
+ id: node.keyVar,
21037
+ v: canonNode(node.value)
21038
+ };
21039
+ return node.maxKeys == null ? base : {
21040
+ ...base,
21041
+ max: node.maxKeys
21042
+ };
21043
+ }
21044
+ case "array": {
21045
+ const base = {
21046
+ k: "arr",
21047
+ i: canonNode(node.item)
21048
+ };
21049
+ return node.maxItems == null ? base : {
21050
+ ...base,
21051
+ max: node.maxItems
21052
+ };
21053
+ }
21054
+ case "standard": return node.hashTag == null ? { k: "std" } : {
21055
+ k: "std",
21056
+ tag: node.hashTag
20739
21057
  };
20740
- case "standard": return { k: "std" };
20741
21058
  }
20742
21059
  }
20743
21060
  /** Canonical serialization (deterministic across platforms — everything sorted). */
@@ -20756,11 +21073,11 @@ function computeSchemaHash(inputs) {
20756
21073
  }
20757
21074
  //#endregion
20758
21075
  //#region ../nice-realm/src/RealmDefinition/Schema/tokenMap.ts
20759
- function unwrapOptional$1(node) {
20760
- return node.kind === "optional" ? unwrapOptional$1(node.inner) : node;
21076
+ function unwrapOptional$2(node) {
21077
+ return node.kind === "optional" ? unwrapOptional$2(node.inner) : node;
20761
21078
  }
20762
21079
  function buildLevelForNode(node) {
20763
- const inner = unwrapOptional$1(node);
21080
+ const inner = unwrapOptional$2(node);
20764
21081
  if (inner.kind === "object") return buildLevel(inner.entries);
20765
21082
  if (inner.kind === "record") return {
20766
21083
  toToken: /* @__PURE__ */ new Map(),
@@ -20882,6 +21199,24 @@ function defineRealm(input) {
20882
21199
  }
20883
21200
  //#endregion
20884
21201
  //#region ../nice-realm/src/RealmDefinition/Schema/t.ts
21202
+ /** Bounds are declaration errors when malformed — caught at `defineRealm` time, not at runtime. */
21203
+ function checkCount(name, value) {
21204
+ if (value == null) return void 0;
21205
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`t: ${name} must be a non-negative safe integer, got ${value}`);
21206
+ return value;
21207
+ }
21208
+ function checkNumberOptions(options) {
21209
+ const { min, max, integer } = options;
21210
+ if (min != null && !Number.isFinite(min)) throw new Error(`t: number min must be finite, got ${min}`);
21211
+ if (max != null && !Number.isFinite(max)) throw new Error(`t: number max must be finite, got ${max}`);
21212
+ if (min != null && max != null && min > max) throw new Error(`t: number min (${min}) must be <= max (${max})`);
21213
+ if (integer != null && typeof integer !== "boolean") throw new Error(`t: number integer must be a boolean`);
21214
+ return {
21215
+ ...min != null ? { min } : {},
21216
+ ...max != null ? { max } : {},
21217
+ ...integer === true ? { integer: true } : {}
21218
+ };
21219
+ }
20885
21220
  function union(...args) {
20886
21221
  const options = args.flatMap((arg) => Array.isArray(arg) ? arg : [arg]);
20887
21222
  if (options.length < 2) throw new Error(`t.union needs at least 2 options, got ${options.length}`);
@@ -20896,11 +21231,18 @@ function union(...args) {
20896
21231
  * schema hash, and (M4) the server-side value validator.
20897
21232
  */
20898
21233
  const t = {
20899
- string() {
20900
- return { kind: "string" };
21234
+ string(options = {}) {
21235
+ const maxLength = checkCount("string maxLength", options.maxLength);
21236
+ return {
21237
+ kind: "string",
21238
+ ...maxLength != null ? { maxLength } : {}
21239
+ };
20901
21240
  },
20902
- number() {
20903
- return { kind: "number" };
21241
+ number(options = {}) {
21242
+ return {
21243
+ kind: "number",
21244
+ ...checkNumberOptions(options)
21245
+ };
20904
21246
  },
20905
21247
  boolean() {
20906
21248
  return { kind: "boolean" };
@@ -20931,29 +21273,36 @@ const t = {
20931
21273
  varName
20932
21274
  };
20933
21275
  },
20934
- record(key, value) {
21276
+ record(key, value, options = {}) {
21277
+ const maxKeys = checkCount("record maxKeys", options.maxKeys);
20935
21278
  return {
20936
21279
  kind: "record",
20937
21280
  keyVar: key.varName,
20938
- value
21281
+ value,
21282
+ ...maxKeys != null ? { maxKeys } : {}
20939
21283
  };
20940
21284
  },
20941
21285
  /** Leaf-replace semantics only in v1 (proposal §7.8) — prefer keyed {@link t.record} collections. */
20942
- array(item) {
21286
+ array(item, options = {}) {
21287
+ const maxItems = checkCount("array maxItems", options.maxItems);
20943
21288
  return {
20944
21289
  kind: "array",
20945
- item
21290
+ item,
21291
+ ...maxItems != null ? { maxItems } : {}
20946
21292
  };
20947
21293
  },
20948
21294
  /**
20949
- * Embed a standard-schema validator (e.g. valibot) at a leaf. Note: the embedded schema's
20950
- * internals are opaque to the schema hash — editing it does NOT change the realm's schemaHash,
20951
- * so treat embedded-validator changes as value-rule changes, not shape changes.
21295
+ * Embed a standard-schema validator (e.g. valibot) at a leaf. The embedded schema's internals
21296
+ * are opaque to the schema hash — editing it does NOT change the realm's schemaHash. Pass a
21297
+ * `hashTag` (and bump it on every contract change) to opt the leaf's contract into the hash;
21298
+ * untagged, treat embedded-validator changes as value-rule changes, not shape changes.
20952
21299
  */
20953
- schema(schema) {
21300
+ schema(schema, options = {}) {
21301
+ if (options.hashTag != null && (typeof options.hashTag !== "string" || options.hashTag === "")) throw new Error("t.schema: hashTag must be a non-empty string");
20954
21302
  return {
20955
21303
  kind: "standard",
20956
- schema
21304
+ schema,
21305
+ ...options.hashTag != null ? { hashTag: options.hashTag } : {}
20957
21306
  };
20958
21307
  },
20959
21308
  /**
@@ -20966,6 +21315,202 @@ const t = {
20966
21315
  }
20967
21316
  };
20968
21317
  //#endregion
21318
+ //#region ../nice-realm/src/RealmDefinition/Schema/boundedState.ts
21319
+ /**
21320
+ * State-aware bound enforcement (the second layer over `validateValue`'s per-value checks).
21321
+ * `validateValue` only ever sees the value being written, so it cannot catch a bound whose truth
21322
+ * lives in the *surrounding* state — the canonical case: `t.record(…, { maxKeys: 8 })` filled one
21323
+ * incremental `record.$id` add at a time, where each child value is individually valid. These
21324
+ * walks run against the **candidate next state** after a whole patch batch (so remove+add nets
21325
+ * out), and once over the full tree at boot/restore/migration.
21326
+ *
21327
+ * Everything here is bounds-only and skip-fast: a schema without bounds costs one memoized lookup
21328
+ * and nothing else, and subtrees carrying no bounds are never entered.
21329
+ */
21330
+ const HAS_BOUNDS = /* @__PURE__ */ new WeakMap();
21331
+ function nodeHasBounds(node) {
21332
+ const cached = HAS_BOUNDS.get(node);
21333
+ if (cached != null) return cached;
21334
+ let result;
21335
+ switch (node.kind) {
21336
+ case "string":
21337
+ result = node.maxLength != null;
21338
+ break;
21339
+ case "number":
21340
+ result = node.min != null || node.max != null || node.integer === true;
21341
+ break;
21342
+ case "boolean":
21343
+ case "literal":
21344
+ case "standard":
21345
+ result = false;
21346
+ break;
21347
+ case "optional":
21348
+ result = nodeHasBounds(node.inner);
21349
+ break;
21350
+ case "union":
21351
+ result = node.options.some(nodeHasBounds);
21352
+ break;
21353
+ case "object":
21354
+ result = Object.values(node.entries).some(nodeHasBounds);
21355
+ break;
21356
+ case "record":
21357
+ result = node.maxKeys != null || nodeHasBounds(node.value);
21358
+ break;
21359
+ case "array":
21360
+ result = node.maxItems != null || nodeHasBounds(node.item);
21361
+ break;
21362
+ }
21363
+ HAS_BOUNDS.set(node, result);
21364
+ return result;
21365
+ }
21366
+ /** Whether any node in the state tree declares a bound — the engine's do-nothing fast path. */
21367
+ function schemaRootHasBounds(root) {
21368
+ return Object.values(root).some(nodeHasBounds);
21369
+ }
21370
+ function unwrapOptional$1(node) {
21371
+ return node.kind === "optional" ? unwrapOptional$1(node.inner) : node;
21372
+ }
21373
+ function isPlainObject(value) {
21374
+ return typeof value === "object" && value != null && !Array.isArray(value);
21375
+ }
21376
+ function getAtPath$2(state, path) {
21377
+ let current = state;
21378
+ for (const seg of path) {
21379
+ if (current == null || typeof current !== "object") return void 0;
21380
+ current = current[seg];
21381
+ }
21382
+ return current;
21383
+ }
21384
+ /**
21385
+ * Bounds-only walk of a value against its node. Type mismatches are NOT reported here — shape
21386
+ * validation belongs to `validateValue` on the paths that run it; this walk only answers "does
21387
+ * any declared bound fail". The one exception is a union carrying bounds: bounds inside a union
21388
+ * are only checkable by structurally matching an option, so `validateValue` (which includes
21389
+ * bounds) is the matcher and a value matching no option reports as invalid.
21390
+ */
21391
+ function checkBoundsDeep(node, value) {
21392
+ if (!nodeHasBounds(node)) return void 0;
21393
+ switch (node.kind) {
21394
+ case "string":
21395
+ if (typeof value === "string" && node.maxLength != null && value.length > node.maxLength) return {
21396
+ path: [],
21397
+ expected: `a string of at most ${node.maxLength} characters`
21398
+ };
21399
+ return;
21400
+ case "number": return typeof value === "number" ? validateValue(node, value) : void 0;
21401
+ case "optional": return value === void 0 ? void 0 : checkBoundsDeep(node.inner, value);
21402
+ case "union": return validateValue(node, value);
21403
+ case "object":
21404
+ if (!isPlainObject(value)) return void 0;
21405
+ for (const [key, child] of Object.entries(node.entries)) {
21406
+ const childValue = value[key];
21407
+ if (childValue === void 0) continue;
21408
+ const invalid = checkBoundsDeep(child, childValue);
21409
+ if (invalid != null) return {
21410
+ path: [key, ...invalid.path],
21411
+ expected: invalid.expected
21412
+ };
21413
+ }
21414
+ return;
21415
+ case "record":
21416
+ if (!isPlainObject(value)) return void 0;
21417
+ if (node.maxKeys != null && Object.keys(value).length > node.maxKeys) return {
21418
+ path: [],
21419
+ expected: `a record with at most ${node.maxKeys} entries`
21420
+ };
21421
+ if (!nodeHasBounds(node.value)) return void 0;
21422
+ for (const [key, entry] of Object.entries(value)) {
21423
+ const invalid = checkBoundsDeep(node.value, entry);
21424
+ if (invalid != null) return {
21425
+ path: [key, ...invalid.path],
21426
+ expected: invalid.expected
21427
+ };
21428
+ }
21429
+ return;
21430
+ case "array":
21431
+ if (!Array.isArray(value)) return void 0;
21432
+ if (node.maxItems != null && value.length > node.maxItems) return {
21433
+ path: [],
21434
+ expected: `an array of at most ${node.maxItems} items`
21435
+ };
21436
+ if (!nodeHasBounds(node.item)) return void 0;
21437
+ for (let i = 0; i < value.length; i++) {
21438
+ const invalid = checkBoundsDeep(node.item, value[i]);
21439
+ if (invalid != null) return {
21440
+ path: [i, ...invalid.path],
21441
+ expected: invalid.expected
21442
+ };
21443
+ }
21444
+ return;
21445
+ default: return;
21446
+ }
21447
+ }
21448
+ /** Full-tree bounds walk — boot, restore, and migration output, before any client attaches. */
21449
+ function validateBoundedStateTree(root, state) {
21450
+ for (const [name, node] of Object.entries(root)) {
21451
+ if (!nodeHasBounds(node)) continue;
21452
+ const invalid = checkBoundsDeep(node, state[name]);
21453
+ if (invalid != null) return {
21454
+ path: [name, ...invalid.path],
21455
+ expected: invalid.expected
21456
+ };
21457
+ }
21458
+ }
21459
+ /**
21460
+ * Bounds gate for one commit: given the **candidate next state** and the batch's canonical patch
21461
+ * paths, check (a) `maxKeys` on every record *ancestor* a path descends into — the constraint an
21462
+ * incremental entry add changes without ever writing the record itself — and (b) all bounds
21463
+ * within each patched subtree's final value. Checks dedupe across the batch and run against the
21464
+ * final state, so remove+add sequences net out and multi-patch frames are judged once, atomically.
21465
+ */
21466
+ function validateBoundedPatches(root, stateAfter, paths) {
21467
+ const checked = /* @__PURE__ */ new Set();
21468
+ for (const path of paths) {
21469
+ let entries = root;
21470
+ let node;
21471
+ for (let i = 0; i < path.length; i++) {
21472
+ const seg = path[i];
21473
+ if (entries != null) {
21474
+ node = typeof seg === "string" ? entries[seg] : void 0;
21475
+ entries = void 0;
21476
+ } else if (node != null) {
21477
+ const inner = unwrapOptional$1(node);
21478
+ if (inner.kind === "object") node = inner.entries[seg];
21479
+ else if (inner.kind === "record") node = inner.value;
21480
+ else node = void 0;
21481
+ }
21482
+ if (node == null) break;
21483
+ const inner = unwrapOptional$1(node);
21484
+ if (inner.kind === "record" && inner.maxKeys != null && i + 1 < path.length) {
21485
+ const prefix = path.slice(0, i + 1);
21486
+ const key = `A:${prefix.join("\0")}`;
21487
+ if (!checked.has(key)) {
21488
+ checked.add(key);
21489
+ const value = getAtPath$2(stateAfter, prefix);
21490
+ if (isPlainObject(value) && Object.keys(value).length > inner.maxKeys) return {
21491
+ path: [...prefix],
21492
+ expected: `a record with at most ${inner.maxKeys} entries`
21493
+ };
21494
+ }
21495
+ }
21496
+ }
21497
+ if (node != null) {
21498
+ const key = `T:${path.join("\0")}`;
21499
+ if (!checked.has(key)) {
21500
+ checked.add(key);
21501
+ const value = getAtPath$2(stateAfter, path);
21502
+ if (value !== void 0) {
21503
+ const invalid = checkBoundsDeep(node, value);
21504
+ if (invalid != null) return {
21505
+ path: [...path, ...invalid.path],
21506
+ expected: invalid.expected
21507
+ };
21508
+ }
21509
+ }
21510
+ }
21511
+ }
21512
+ }
21513
+ //#endregion
20969
21514
  //#region ../nice-realm/src/RealmServer/viewSlice.ts
20970
21515
  function leafVisible(ctx, path) {
20971
21516
  const match = ctx.trie.match(path);
@@ -21123,6 +21668,8 @@ var RealmServerEngine = class {
21123
21668
  _now;
21124
21669
  _instanceId;
21125
21670
  _state;
21671
+ /** Whether the schema declares any bounds — false skips every bounded-state walk. */
21672
+ _hasBounds;
21126
21673
  _version = 0;
21127
21674
  _mutating = false;
21128
21675
  /** The log epoch (review B.3): identifies this history — replay requires an exact match. */
@@ -21207,6 +21754,14 @@ var RealmServerEngine = class {
21207
21754
  this._state = typeof options.initialState === "function" ? options.initialState({ instanceId: this._instanceId }) : options.initialState;
21208
21755
  this._epoch = mintEpoch();
21209
21756
  }
21757
+ this._hasBounds = schemaRootHasBounds(this._realm.stateDef);
21758
+ if (this._hasBounds) {
21759
+ const invalid = validateBoundedStateTree(this._realm.stateDef, this._state);
21760
+ if (invalid != null) throw err_realm.fromId("value_invalid", {
21761
+ path: invalid.path.join("."),
21762
+ expected: invalid.expected
21763
+ });
21764
+ }
21210
21765
  }
21211
21766
  get state() {
21212
21767
  return this._state;
@@ -21573,6 +22128,13 @@ var RealmServerEngine = class {
21573
22128
  const [nextState, patches] = produced;
21574
22129
  if (patches.length === 0) return;
21575
22130
  const canonical = canonicalizeStatePatches(patches, nextState, this._realm.stateDef);
22131
+ if (this._hasBounds) {
22132
+ const bounded = validateBoundedPatches(this._realm.stateDef, nextState, canonical.map((patch) => patch.path));
22133
+ if (bounded != null) throw err_realm.fromId("value_invalid", {
22134
+ path: bounded.path.join("."),
22135
+ expected: bounded.expected
22136
+ });
22137
+ }
21576
22138
  this._commit(nextState, canonical, { source: "server" });
21577
22139
  this._flushEgress();
21578
22140
  }
@@ -21692,6 +22254,16 @@ var RealmServerEngine = class {
21692
22254
  this._reject(conn, frame.clientSeq, err_realm.fromId("write_target_missing", { path }));
21693
22255
  return;
21694
22256
  }
22257
+ if (this._hasBounds) {
22258
+ const bounded = validateBoundedPatches(this._realm.stateDef, nextState, namePatches.map((patch) => patch.path));
22259
+ if (bounded != null) {
22260
+ this._reject(conn, frame.clientSeq, err_realm.fromId("value_invalid", {
22261
+ path: bounded.path.join("."),
22262
+ expected: bounded.expected
22263
+ }));
22264
+ return;
22265
+ }
22266
+ }
21695
22267
  const version = this._commit(nextState, namePatches, {
21696
22268
  source: "write",
21697
22269
  avatar: conn.avatar
@@ -21757,6 +22329,16 @@ var RealmServerEngine = class {
21757
22329
  this._reject(conn, frame.clientSeq, err_realm.fromId("frame_invalid", { reason: "unsafe record key" }));
21758
22330
  return;
21759
22331
  }
22332
+ if (this._hasBounds) {
22333
+ const bounded = validateBoundedPatches(this._realm.stateDef, nextState, canonical.map((patch) => patch.path));
22334
+ if (bounded != null) {
22335
+ this._reject(conn, frame.clientSeq, err_realm.fromId("value_invalid", {
22336
+ path: bounded.path.join("."),
22337
+ expected: bounded.expected
22338
+ }));
22339
+ return;
22340
+ }
22341
+ }
21760
22342
  const version = this._commit(nextState, canonical, {
21761
22343
  source: "intent",
21762
22344
  avatar: conn.avatar
@@ -22833,6 +23415,14 @@ const commanderStatusRealm = defineRealm({
22833
23415
  state: t.string(),
22834
23416
  pid: t.optional(t.number()),
22835
23417
  startedAt: t.optional(t.number()),
23418
+ sawOutputAt: t.optional(t.number()),
23419
+ lastTask: t.optional(t.object({
23420
+ outcome: t.string(),
23421
+ reason: t.optional(t.string()),
23422
+ timedOut: t.boolean(),
23423
+ endedAt: t.number(),
23424
+ durationMs: t.optional(t.number())
23425
+ })),
22836
23426
  restarts: t.number(),
22837
23427
  lastExit: t.optional(t.object({
22838
23428
  code: t.optional(t.number()),
@@ -23840,7 +24430,7 @@ async function cmdLogs(ctx) {
23840
24430
  }
23841
24431
  //#endregion
23842
24432
  //#region src/cli/commands/run.ts
23843
- const ACTIVE_STATES = new Set([
24433
+ const ACTIVE_STATES$1 = new Set([
23844
24434
  "starting",
23845
24435
  "running",
23846
24436
  "ready",
@@ -23928,7 +24518,7 @@ async function cmdRun(ctx) {
23928
24518
  if (handle != null) {
23929
24519
  const client = await connectDaemon(handle);
23930
24520
  try {
23931
- const owned = defs.filter((def) => ACTIVE_STATES.has(client.state().processes[def.id]?.state ?? ""));
24521
+ const owned = defs.filter((def) => ACTIVE_STATES$1.has(client.state().processes[def.id]?.state ?? ""));
23932
24522
  if (owned.length > 0) throw new CliExit(EXIT.failure, `"${owned.map((def) => def.id).join("\", \"")}" is owned by the running daemon — \`down\` it there first (silent double-start is never allowed).`);
23933
24523
  } finally {
23934
24524
  client.dispose();
@@ -24147,7 +24737,7 @@ async function cmdRun(ctx) {
24147
24737
  }
24148
24738
  for (const depId of def.dependsOn) {
24149
24739
  const dep = procs.find((candidate) => candidate.id === depId);
24150
- if (dep != null && byId.get(depId)?.kind === "service" && ACTIVE_STATES.has(dep.state)) await dep.whenReady().catch(() => {
24740
+ if (dep != null && byId.get(depId)?.kind === "service" && ACTIVE_STATES$1.has(dep.state)) await dep.whenReady().catch(() => {
24151
24741
  out.warn(out.paint("yellow", `⚠ dependency "${depId}" did not become ready — starting anyway`));
24152
24742
  });
24153
24743
  }
@@ -24230,28 +24820,54 @@ function formatUptime(sinceMs, now = Date.now()) {
24230
24820
  }
24231
24821
  //#endregion
24232
24822
  //#region src/cli/commands/status.ts
24233
- function notesFor(proc) {
24823
+ const ACTIVE_STATES = new Set([
24824
+ "starting",
24825
+ "running",
24826
+ "ready",
24827
+ "unready",
24828
+ "backoff",
24829
+ "stopping"
24830
+ ]);
24831
+ /** Beyond this, a run that has printed nothing reads as wedged, not quiet — say so. */
24832
+ const SILENT_START_NOTE_MS = 15e3;
24833
+ function notesFor(proc, now) {
24234
24834
  const notes = [];
24235
24835
  if (proc.blockedBy != null) notes.push(`blocked: ${proc.blockedBy}`);
24236
24836
  if (proc.degradedBy.length > 0) notes.push(`degraded by ${proc.degradedBy.join(", ")}`);
24237
24837
  if (proc.unreadyReason != null) notes.push(`unready: ${proc.unreadyReason}`);
24838
+ if (ACTIVE_STATES.has(proc.state) && proc.sawOutputAt == null && proc.startedAt != null && now - proc.startedAt > SILENT_START_NOTE_MS) notes.push(`no output since start (${formatUptime(proc.startedAt, now)})`);
24839
+ const lastTask = proc.lastTask;
24840
+ if (!ACTIVE_STATES.has(proc.state) && lastTask?.outcome === "failed" && lastTask.reason != null) notes.push(`last run failed: ${lastTask.reason} (${formatUptime(lastTask.endedAt, now)} ago)`);
24238
24841
  if (proc.stale) notes.push("stale (config changed — restart to apply)");
24239
24842
  const sticky = proc.detail.envVars.filter((declared) => declared.source === "override").length;
24240
24843
  if (sticky > 0) notes.push(`${sticky} sticky env override${sticky === 1 ? "" : "s"} (see \`env\`)`);
24241
24844
  if (proc.envDrift) notes.push("env override changed — restart to apply");
24242
24845
  if (proc.removed) notes.push("removed from config");
24243
- if (proc.capability?.degraded === true) notes.push(proc.capability.treeMechanism);
24244
24846
  return notes.join("; ");
24245
24847
  }
24848
+ /**
24849
+ * Degraded tree ownership is a host-wide fact (every process shares one mechanism), so it prints
24850
+ * once under the table instead of drowning every row's NOTES — on WSL that would be every row.
24851
+ */
24852
+ function capabilityFooter(state) {
24853
+ const seen = /* @__PURE__ */ new Set();
24854
+ for (const proc of Object.values(state.processes)) {
24855
+ if (proc.capability?.degraded !== true) continue;
24856
+ const notes = proc.capability.notes.length > 0 ? `: ${proc.capability.notes.join(" ")}` : "";
24857
+ seen.add(`⚠ tree ownership degraded (${proc.capability.treeMechanism})${notes}`);
24858
+ }
24859
+ return [...seen].map((line) => `\n${line}`).join("");
24860
+ }
24246
24861
  function renderTable(out, state) {
24862
+ const now = Date.now();
24247
24863
  const rows = Object.entries(state.processes).map(([id, proc]) => [
24248
24864
  id,
24249
24865
  proc.kind,
24250
24866
  proc.state,
24251
24867
  proc.pid != null ? String(proc.pid) : "-",
24252
- proc.startedAt != null ? formatUptime(proc.startedAt) : "-",
24868
+ ACTIVE_STATES.has(proc.state) && proc.startedAt != null ? formatUptime(proc.startedAt, now) : "-",
24253
24869
  String(proc.restarts),
24254
- notesFor(proc)
24870
+ notesFor(proc, now)
24255
24871
  ]);
24256
24872
  const head = `generation ${state.generation} · revision ${state.configRevisionHash}`;
24257
24873
  const configError = state.configError.length > 0 ? `\nconfig error (last-good kept): ${state.configError[0]}` : "";
@@ -24263,7 +24879,7 @@ function renderTable(out, state) {
24263
24879
  "UPTIME",
24264
24880
  "R",
24265
24881
  "NOTES"
24266
- ], rows)}${configError}`;
24882
+ ], rows)}${capabilityFooter(state)}${configError}`;
24267
24883
  }
24268
24884
  async function cmdStatus(ctx) {
24269
24885
  const bad = unknownFlags(ctx.args.flags, ["--watch"]);
@@ -24462,7 +25078,7 @@ async function withTimeout(ctx, run) {
24462
25078
  async function main() {
24463
25079
  const argv = process.argv.slice(2);
24464
25080
  if (argv[0] === "daemon") {
24465
- const { runCommanderDaemon } = await import("./main-B5pT7VaY.mjs");
25081
+ const { runCommanderDaemon } = await import("./main-BfXI8q29.mjs");
24466
25082
  return runCommanderDaemon(argv.slice(1));
24467
25083
  }
24468
25084
  const parsed = parseCliArgs(argv);