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