@nice-code/commander 0.77.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 +1004 -271
- package/build/cli.cjs.map +1 -1
- package/build/cli.mjs +1004 -271
- package/build/cli.mjs.map +1 -1
- package/build/client/assets/index-Cw6AoXd7.js +19 -0
- package/build/client/assets/index-Cw6AoXd7.js.map +1 -0
- package/build/client/index.html +1 -1
- package/package.json +6 -6
- package/build/client/assets/index-DvBR18K2.js +0 -18
- package/build/client/assets/index-DvBR18K2.js.map +0 -1
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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;
|
|
@@ -4076,6 +4432,7 @@ var StorageAdapter = class StorageAdapter {
|
|
|
4076
4432
|
* `true` on localStorage / Durable Object / KV, `undefined` (unknown) on custom methods.
|
|
4077
4433
|
*/
|
|
4078
4434
|
durable;
|
|
4435
|
+
trackKeysForClearing;
|
|
4079
4436
|
adapterStorage;
|
|
4080
4437
|
/**
|
|
4081
4438
|
* Serializes mutations of the `__usedKeys__` index so its read-modify-write cycles can't
|
|
@@ -4091,6 +4448,7 @@ var StorageAdapter = class StorageAdapter {
|
|
|
4091
4448
|
this.durable = methods.durable;
|
|
4092
4449
|
this.keyPrefix = keyPrefix ?? "";
|
|
4093
4450
|
const _trackKeys = trackKeys ?? true;
|
|
4451
|
+
this.trackKeysForClearing = _trackKeys;
|
|
4094
4452
|
this.adapterStorage = _trackKeys ? createTypedStorage({ storageAdapter: new StorageAdapter({
|
|
4095
4453
|
methods,
|
|
4096
4454
|
keyPrefix,
|
|
@@ -4113,12 +4471,14 @@ var StorageAdapter = class StorageAdapter {
|
|
|
4113
4471
|
/**
|
|
4114
4472
|
* Derive a new adapter over the *same* backing store with an extra key-prefix segment appended.
|
|
4115
4473
|
* Lets an independent namespace (e.g. a second crypto identity) share one underlying storage without
|
|
4116
|
-
* key collisions
|
|
4474
|
+
* key collisions. Key-tracking policy is inherited: deriving from an intentionally untracked
|
|
4475
|
+
* adapter must not silently create a `__usedKeys__` index.
|
|
4117
4476
|
*/
|
|
4118
4477
|
withKeyPrefix(extraPrefix) {
|
|
4119
4478
|
return new StorageAdapter({
|
|
4120
4479
|
methods: this.implementation,
|
|
4121
|
-
keyPrefix: `${this.keyPrefix}${extraPrefix}
|
|
4480
|
+
keyPrefix: `${this.keyPrefix}${extraPrefix}`,
|
|
4481
|
+
trackKeysForClearing: this.trackKeysForClearing
|
|
4122
4482
|
});
|
|
4123
4483
|
}
|
|
4124
4484
|
async trackUsedKey(rawKey) {
|
|
@@ -4543,6 +4903,14 @@ function createInMemoryTofuVerifyKeyResolver() {
|
|
|
4543
4903
|
};
|
|
4544
4904
|
} };
|
|
4545
4905
|
}
|
|
4906
|
+
const tofuPinStorageKey = async (identity) => {
|
|
4907
|
+
return `pin:${[...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`nice-wire-tofu-v1:${identity}`)))].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
4908
|
+
};
|
|
4909
|
+
const pinMismatch = () => ({
|
|
4910
|
+
trusted: false,
|
|
4911
|
+
reason: "verify key changed for client identity (pin mismatch)",
|
|
4912
|
+
rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH
|
|
4913
|
+
});
|
|
4546
4914
|
/**
|
|
4547
4915
|
* Storage-backed trust-on-first-use resolver: pins survive process restarts / Durable Object eviction
|
|
4548
4916
|
* (e.g. back it with `createDurableObjectStorageAdapter`). Same policy as the in-memory variant — trust
|
|
@@ -4557,8 +4925,46 @@ function createInMemoryTofuVerifyKeyResolver() {
|
|
|
4557
4925
|
* On an *eventually-consistent* store a stale "absent" read re-pins the **same** verify key the client
|
|
4558
4926
|
* just presented (it is signature-verified before this runs), so the worst case is a harmless re-write,
|
|
4559
4927
|
* never a weakened trust decision. Cross-isolate-strong pinning still wants a strongly-consistent store.
|
|
4928
|
+
*
|
|
4929
|
+
* Switching an existing host from `document` to `per_identity` is safe: on each identity's next
|
|
4930
|
+
* contact the legacy pin is honored and migrated to its per-identity record. The reverse switch is
|
|
4931
|
+
* NOT migrated — pins recorded per-identity are invisible to the `document` layout.
|
|
4560
4932
|
*/
|
|
4561
|
-
function createStorageTofuVerifyKeyResolver(storageAdapter) {
|
|
4933
|
+
function createStorageTofuVerifyKeyResolver(storageAdapter, options = {}) {
|
|
4934
|
+
if (options.layout === "per_identity") {
|
|
4935
|
+
const identityLocks = /* @__PURE__ */ new Map();
|
|
4936
|
+
return { async resolve({ client, verifyPublicKey }) {
|
|
4937
|
+
const identity = tofuPinKey(client);
|
|
4938
|
+
const storageKey = await tofuPinStorageKey(identity);
|
|
4939
|
+
const operation = (identityLocks.get(storageKey) ?? Promise.resolve()).catch(() => void 0).then(async () => {
|
|
4940
|
+
const existing = await storageAdapter.getJson(storageKey);
|
|
4941
|
+
if (existing == null) {
|
|
4942
|
+
const legacy = (await storageAdapter.getJson("pins"))?.[identity];
|
|
4943
|
+
if (legacy != null) {
|
|
4944
|
+
await storageAdapter.setJson(storageKey, {
|
|
4945
|
+
identity,
|
|
4946
|
+
verifyPublicKey: legacy
|
|
4947
|
+
});
|
|
4948
|
+
return legacy === verifyPublicKey ? { trusted: true } : pinMismatch();
|
|
4949
|
+
}
|
|
4950
|
+
await storageAdapter.setJson(storageKey, {
|
|
4951
|
+
identity,
|
|
4952
|
+
verifyPublicKey
|
|
4953
|
+
});
|
|
4954
|
+
return { trusted: true };
|
|
4955
|
+
}
|
|
4956
|
+
if (existing.identity === identity && existing.verifyPublicKey === verifyPublicKey) return { trusted: true };
|
|
4957
|
+
return pinMismatch();
|
|
4958
|
+
});
|
|
4959
|
+
const tail = operation.then(() => void 0, () => void 0);
|
|
4960
|
+
identityLocks.set(storageKey, tail);
|
|
4961
|
+
try {
|
|
4962
|
+
return await operation;
|
|
4963
|
+
} finally {
|
|
4964
|
+
if (identityLocks.get(storageKey) === tail) identityLocks.delete(storageKey);
|
|
4965
|
+
}
|
|
4966
|
+
} };
|
|
4967
|
+
}
|
|
4562
4968
|
const storage = createTypedStorage({ storageAdapter });
|
|
4563
4969
|
return { async resolve({ client, verifyPublicKey }) {
|
|
4564
4970
|
const key = tofuPinKey(client);
|
|
@@ -4571,11 +4977,7 @@ function createStorageTofuVerifyKeyResolver(storageAdapter) {
|
|
|
4571
4977
|
return { trusted: true };
|
|
4572
4978
|
}
|
|
4573
4979
|
if (existing === verifyPublicKey) return { trusted: true };
|
|
4574
|
-
return
|
|
4575
|
-
trusted: false,
|
|
4576
|
-
reason: "verify key changed for client identity (pin mismatch)",
|
|
4577
|
-
rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH
|
|
4578
|
-
};
|
|
4980
|
+
return pinMismatch();
|
|
4579
4981
|
} };
|
|
4580
4982
|
}
|
|
4581
4983
|
function createClientHandshake(config) {
|
|
@@ -8621,6 +9023,7 @@ var WireAcceptor = class {
|
|
|
8621
9023
|
_noneAllowed;
|
|
8622
9024
|
_handshakeMode;
|
|
8623
9025
|
_onConnectionBound;
|
|
9026
|
+
_disposed = false;
|
|
8624
9027
|
_connByClient = /* @__PURE__ */ new Map();
|
|
8625
9028
|
_clientByConn = /* @__PURE__ */ new Map();
|
|
8626
9029
|
_levelByConn = /* @__PURE__ */ new Map();
|
|
@@ -8647,6 +9050,7 @@ var WireAcceptor = class {
|
|
|
8647
9050
|
}
|
|
8648
9051
|
/** Feed one inbound frame from a connection: keepalive, then handshake/session, then dispatch. */
|
|
8649
9052
|
receive(connection, frame) {
|
|
9053
|
+
if (this._disposed) return;
|
|
8650
9054
|
const wireBytes = this._tap != null ? wireFrameByteSize(frame) : 0;
|
|
8651
9055
|
if (frame === KEEPALIVE_PING) {
|
|
8652
9056
|
this._tapIn(connection, wireBytes, "keepalive");
|
|
@@ -8661,12 +9065,14 @@ var WireAcceptor = class {
|
|
|
8661
9065
|
this._sessionFor(connection, security).receive(frame, wireBytes);
|
|
8662
9066
|
}
|
|
8663
9067
|
_receivePlain(connection, frame, wireBytes = 0) {
|
|
9068
|
+
if (this._disposed) return;
|
|
8664
9069
|
this._tapIn(connection, wireBytes, this._laneFor(frame));
|
|
8665
9070
|
if (this._dispatchProtocolFrame(connection, frame)) return;
|
|
8666
9071
|
this._lane.onFrame(connection, frame, "none");
|
|
8667
9072
|
}
|
|
8668
9073
|
/** Route a decrypted frame from an authenticated connection: protocols first, then the lane. */
|
|
8669
9074
|
_routeAuthed(connection, bytes, wireBytes = 0) {
|
|
9075
|
+
if (this._disposed) return;
|
|
8670
9076
|
this._tapIn(connection, wireBytes, this._laneFor(bytes));
|
|
8671
9077
|
if (this._dispatchProtocolFrame(connection, bytes)) return;
|
|
8672
9078
|
this._lane.onFrame(connection, bytes, this._levelByConn.get(connection) ?? "authenticated");
|
|
@@ -8797,6 +9203,7 @@ var WireAcceptor = class {
|
|
|
8797
9203
|
}
|
|
8798
9204
|
/** Bind + persist a connection's authenticated identity once its handshake completes. */
|
|
8799
9205
|
_onAuthenticated(connection, auth) {
|
|
9206
|
+
if (this._disposed) return;
|
|
8800
9207
|
this._bind(connection, auth.client);
|
|
8801
9208
|
this._levelByConn.set(connection, auth.securityLevel);
|
|
8802
9209
|
this._lane.onAuthenticated?.(connection, auth);
|
|
@@ -8824,6 +9231,7 @@ var WireAcceptor = class {
|
|
|
8824
9231
|
* Secure mode never calls this — the handshake binds the authenticated coordinate instead.
|
|
8825
9232
|
*/
|
|
8826
9233
|
bindPlainConnection(connection, client) {
|
|
9234
|
+
if (this._disposed) return;
|
|
8827
9235
|
const isNewBinding = this._clientByConn.get(connection)?.stringId !== client.stringId;
|
|
8828
9236
|
this._bind(connection, client);
|
|
8829
9237
|
if (isNewBinding) this._persist(connection, {
|
|
@@ -8840,6 +9248,7 @@ var WireAcceptor = class {
|
|
|
8840
9248
|
* is ignored with a warning — the socket is simply treated as fresh (its client re-handshakes).
|
|
8841
9249
|
*/
|
|
8842
9250
|
rehydrate(connection, binding) {
|
|
9251
|
+
if (this._disposed) return;
|
|
8843
9252
|
if (binding.v !== 1) {
|
|
8844
9253
|
console.warn(`[wire-acceptor] ignored a persisted connection binding of unknown schema version ${JSON.stringify(binding.v)} (expected 1) — treating the connection as fresh (err_nice_wire_connect.binding_version_mismatch).`);
|
|
8845
9254
|
return;
|
|
@@ -8856,6 +9265,7 @@ var WireAcceptor = class {
|
|
|
8856
9265
|
this._attachProtocols(connection, new Set(binding.protocols ?? []));
|
|
8857
9266
|
}
|
|
8858
9267
|
_persist(connection, binding) {
|
|
9268
|
+
if (this._disposed) return;
|
|
8859
9269
|
this._bindingByConn.set(connection, binding);
|
|
8860
9270
|
this._onConnectionBound?.(connection, binding);
|
|
8861
9271
|
}
|
|
@@ -8865,6 +9275,11 @@ var WireAcceptor = class {
|
|
|
8865
9275
|
}
|
|
8866
9276
|
/** Forget a connection (call on socket close) so stale entries don't misroute later traffic. */
|
|
8867
9277
|
drop(connection) {
|
|
9278
|
+
if (this._disposed) return;
|
|
9279
|
+
this._drop(connection);
|
|
9280
|
+
}
|
|
9281
|
+
/** Internal detach path used once during terminal disposal after public entry points are closed. */
|
|
9282
|
+
_drop(connection) {
|
|
8868
9283
|
const client = this._clientByConn.get(connection);
|
|
8869
9284
|
if (client != null && this._connByClient.get(client.stringId) === connection) this._connByClient.delete(client.stringId);
|
|
8870
9285
|
this._lane.onDrop?.(connection, client);
|
|
@@ -8877,6 +9292,7 @@ var WireAcceptor = class {
|
|
|
8877
9292
|
}
|
|
8878
9293
|
/** Send a raw (already lane/protocol-encoded) frame — through the secure session when present. */
|
|
8879
9294
|
sendTo(connection, frame) {
|
|
9295
|
+
if (this._disposed) return;
|
|
8880
9296
|
const lane = this._laneFor(frame);
|
|
8881
9297
|
const session = this._sessionByConn.get(connection);
|
|
8882
9298
|
if (session == null) {
|
|
@@ -8917,6 +9333,20 @@ var WireAcceptor = class {
|
|
|
8917
9333
|
bindingFor(connection) {
|
|
8918
9334
|
return this._bindingByConn.get(connection);
|
|
8919
9335
|
}
|
|
9336
|
+
/** Quiesce permanently: detach every known connection and ignore late/in-flight traffic. */
|
|
9337
|
+
dispose() {
|
|
9338
|
+
if (this._disposed) return;
|
|
9339
|
+
this._disposed = true;
|
|
9340
|
+
const connections = new Set([
|
|
9341
|
+
...this._clientByConn.keys(),
|
|
9342
|
+
...this._sessionByConn.keys(),
|
|
9343
|
+
...this._bindingByConn.keys()
|
|
9344
|
+
]);
|
|
9345
|
+
for (const connection of connections) this._drop(connection);
|
|
9346
|
+
}
|
|
9347
|
+
get disposed() {
|
|
9348
|
+
return this._disposed;
|
|
9349
|
+
}
|
|
8920
9350
|
};
|
|
8921
9351
|
//#endregion
|
|
8922
9352
|
//#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
|
|
@@ -10140,6 +10570,7 @@ const err_nice_action = err_nice.createChildDomain({
|
|
|
10140
10570
|
["not_implemented"]: err({ message: ({ label }) => `The "${label}" functionality is not implemented yet.` }),
|
|
10141
10571
|
["action_id_not_in_domain"]: err({ message: ({ actionId, domain }) => `Action with id "${actionId}" does not exist in domain "${domain}".` }),
|
|
10142
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.` }),
|
|
10143
10574
|
["domain_no_handler"]: err({ message: ({ domain }) => `Domain "${domain}" has no action handler registered.` }),
|
|
10144
10575
|
["hydration_domain_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: domain mismatch. Expected "${expected}", got "${received}".` }),
|
|
10145
10576
|
["hydration_action_state_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: action state type mismatch. Expected "${expected}", got "${received}".` }),
|
|
@@ -11567,6 +11998,11 @@ var ActionSchema = class {
|
|
|
11567
11998
|
* Declare the input schema (JSON-native or with explicit SERDE type param).
|
|
11568
11999
|
* For non-JSON-native inputs, prefer the 3-argument form below to avoid
|
|
11569
12000
|
* needing explicit type parameters.
|
|
12001
|
+
*
|
|
12002
|
+
* The schema runs at `request()` AND again on the receiving runtime before the handler executes,
|
|
12003
|
+
* so it must accept its own validated output. Plain validators always do; a `transform` whose
|
|
12004
|
+
* output fails its own input schema will reject valid requests on arrival — type conversion
|
|
12005
|
+
* belongs in the SERDE pack/unpack arguments, not in schema transforms.
|
|
11570
12006
|
*/
|
|
11571
12007
|
input(options) {
|
|
11572
12008
|
this.inputOptions = options;
|
|
@@ -11927,6 +12363,13 @@ var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
|
|
|
11927
12363
|
var ActionDomainManager = class {
|
|
11928
12364
|
_domains = /* @__PURE__ */ new Map();
|
|
11929
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
|
+
});
|
|
11930
12373
|
this._domains.set(domain.domain, domain);
|
|
11931
12374
|
}
|
|
11932
12375
|
getDomains() {
|
|
@@ -12940,7 +13383,21 @@ var ActionRuntime = class {
|
|
|
12940
13383
|
runningAction._completeWithResult(action.errorResult(castNiceError(err)));
|
|
12941
13384
|
return runningAction;
|
|
12942
13385
|
}
|
|
12943
|
-
|
|
13386
|
+
let validatedAction;
|
|
13387
|
+
try {
|
|
13388
|
+
validatedAction = new ActionPayload_Request({ context: action.context }, action.context.validateInput(action.input), { time: action.time });
|
|
13389
|
+
validatedAction._callSite = action._callSite;
|
|
13390
|
+
} catch (err) {
|
|
13391
|
+
const runningAction = new RunningAction({
|
|
13392
|
+
context: action.context,
|
|
13393
|
+
request: action
|
|
13394
|
+
});
|
|
13395
|
+
runningAction.addUpdateListeners(observers);
|
|
13396
|
+
runningAction._completeWithResult(action.errorResult(castNiceError(err)));
|
|
13397
|
+
this._trySetupReturnDispatch(runningAction);
|
|
13398
|
+
return runningAction;
|
|
13399
|
+
}
|
|
13400
|
+
const runningAction = await handlerForAction.handleActionRequest(validatedAction, {
|
|
12944
13401
|
...options,
|
|
12945
13402
|
targetLocalRuntime: this
|
|
12946
13403
|
});
|
|
@@ -14153,6 +14610,10 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
|
|
|
14153
14610
|
drop(connection) {
|
|
14154
14611
|
this.wireAcceptor.drop(connection);
|
|
14155
14612
|
}
|
|
14613
|
+
/** Permanently quiesce this acceptor and detach every live/rehydrated connection. */
|
|
14614
|
+
dispose() {
|
|
14615
|
+
this.wireAcceptor.dispose();
|
|
14616
|
+
}
|
|
14156
14617
|
/** Lane cleanup when the wire acceptor drops a connection (fired with the bound client, if any). */
|
|
14157
14618
|
_onConnectionDropped(connection, client) {
|
|
14158
14619
|
if (client != null) {
|
|
@@ -15631,18 +16092,55 @@ function createHibernatableWsServerAdapter(options) {
|
|
|
15631
16092
|
* carrier factory (`wsAcceptorCarrier`, a WebRTC carrier, the Cloudflare DO helper, …) so the
|
|
15632
16093
|
* stateful-handle wiring lives in exactly one place.
|
|
15633
16094
|
*/
|
|
15634
|
-
function createDuplexCarrierLifecycle() {
|
|
16095
|
+
function createDuplexCarrierLifecycle(limits) {
|
|
15635
16096
|
let router;
|
|
16097
|
+
let disposed = false;
|
|
16098
|
+
const windows = /* @__PURE__ */ new Map();
|
|
16099
|
+
const maxFrameBytes = limits?.maxFrameBytes;
|
|
16100
|
+
const rate = limits?.rate;
|
|
16101
|
+
if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
|
|
16102
|
+
if (rate != null && (!Number.isSafeInteger(rate.maxMessages) || rate.maxMessages <= 0 || !Number.isSafeInteger(rate.windowMs) || rate.windowMs <= 0)) throw new Error("inbound rate limits must be positive safe integers");
|
|
16103
|
+
const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
|
|
15636
16104
|
return {
|
|
15637
16105
|
receive(connection, frame) {
|
|
16106
|
+
if (disposed) return;
|
|
15638
16107
|
if (router == null) throw new Error("acceptor carrier not served yet — pass it to serveChannel() before feeding frames");
|
|
16108
|
+
if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
|
|
16109
|
+
limits?.onExceeded(connection, "frame_bytes");
|
|
16110
|
+
return;
|
|
16111
|
+
}
|
|
16112
|
+
if (rate != null) {
|
|
16113
|
+
const now = Date.now();
|
|
16114
|
+
let window = windows.get(connection);
|
|
16115
|
+
if (window == null || now - window.startedAt >= rate.windowMs) {
|
|
16116
|
+
window = {
|
|
16117
|
+
count: 0,
|
|
16118
|
+
startedAt: now
|
|
16119
|
+
};
|
|
16120
|
+
windows.set(connection, window);
|
|
16121
|
+
}
|
|
16122
|
+
window.count++;
|
|
16123
|
+
if (window.count > rate.maxMessages) {
|
|
16124
|
+
limits?.onExceeded(connection, "message_rate");
|
|
16125
|
+
return;
|
|
16126
|
+
}
|
|
16127
|
+
}
|
|
15639
16128
|
router.receive(connection, frame);
|
|
15640
16129
|
},
|
|
15641
16130
|
drop(connection) {
|
|
16131
|
+
if (disposed) return;
|
|
16132
|
+
windows.delete(connection);
|
|
15642
16133
|
router?.drop(connection);
|
|
15643
16134
|
},
|
|
15644
16135
|
_activate(liveRouter) {
|
|
16136
|
+
if (disposed) throw new Error("acceptor carrier already disposed");
|
|
15645
16137
|
router = liveRouter;
|
|
16138
|
+
},
|
|
16139
|
+
_dispose() {
|
|
16140
|
+
if (disposed) return;
|
|
16141
|
+
disposed = true;
|
|
16142
|
+
router = void 0;
|
|
16143
|
+
windows.clear();
|
|
15646
16144
|
}
|
|
15647
16145
|
};
|
|
15648
16146
|
}
|
|
@@ -15656,6 +16154,35 @@ function isExchangeAcceptorCarrier(carrier) {
|
|
|
15656
16154
|
}
|
|
15657
16155
|
//#endregion
|
|
15658
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
|
+
}
|
|
15659
16186
|
/** Default accepted set, shared by every carrier: negotiate per connection to whatever the client picks. */
|
|
15660
16187
|
const DEFAULT_SERVER_SECURITY_LEVELS = [
|
|
15661
16188
|
"none",
|
|
@@ -15674,19 +16201,7 @@ function serveChannel(runtime, channel, options) {
|
|
|
15674
16201
|
const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
|
|
15675
16202
|
const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
|
|
15676
16203
|
const registry = options.channels;
|
|
15677
|
-
const resolveChannel = registry != null && registry.length > 1 ? (
|
|
15678
|
-
const byTag = new Map(registry.map((entry) => [entry.tag, entry]));
|
|
15679
|
-
return (tags) => {
|
|
15680
|
-
if (tags == null || tags.length === 0) return channel;
|
|
15681
|
-
const selected = [];
|
|
15682
|
-
for (const tag of tags) {
|
|
15683
|
-
const found = byTag.get(tag);
|
|
15684
|
-
if (found == null) return null;
|
|
15685
|
-
selected.push(found);
|
|
15686
|
-
}
|
|
15687
|
-
return selected.length === 1 ? selected[0] : combineChannels(selected);
|
|
15688
|
-
};
|
|
15689
|
-
})() : void 0;
|
|
16204
|
+
const resolveChannel = registry != null && registry.length > 1 ? buildChannelSubsetResolver(channel, registry) : void 0;
|
|
15690
16205
|
let secure;
|
|
15691
16206
|
if (anyDuplexSecure || exchangeSecure) {
|
|
15692
16207
|
const storage = options.storage;
|
|
@@ -15757,19 +16272,24 @@ function serveChannel(runtime, channel, options) {
|
|
|
15757
16272
|
}
|
|
15758
16273
|
runtime.addHandlers([...options.handlers ?? [], ...acceptors]);
|
|
15759
16274
|
const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
|
|
16275
|
+
let disposed = false;
|
|
15760
16276
|
const receive = (connection, frame) => {
|
|
16277
|
+
if (disposed) return;
|
|
15761
16278
|
if (soleDuplex == null) throw new Error(duplexCarriers.length === 0 ? "serveChannel: no duplex carrier to receive on (this server has no socket transport)" : "serveChannel: several duplex carriers — feed each carrier handle's receive() directly");
|
|
15762
16279
|
soleDuplex.receive(connection, frame);
|
|
15763
16280
|
};
|
|
15764
16281
|
const drop = (connection) => {
|
|
16282
|
+
if (disposed) return;
|
|
15765
16283
|
soleDuplex?.drop(connection);
|
|
15766
16284
|
};
|
|
15767
16285
|
const pushToClient = (target, request, pushOptions) => {
|
|
16286
|
+
if (disposed) throw new Error("serveChannel: server disposed");
|
|
15768
16287
|
const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
|
|
15769
16288
|
if (owner == null) throw new Error("serveChannel: no duplex carrier holds a connection for the push target");
|
|
15770
16289
|
return owner.pushToClient(runtime, target, request, pushOptions);
|
|
15771
16290
|
};
|
|
15772
16291
|
const broadcast = (makeRequest, broadcastOptions) => {
|
|
16292
|
+
if (disposed) throw new Error("serveChannel: server disposed");
|
|
15773
16293
|
if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead");
|
|
15774
16294
|
acceptors[0].broadcast(makeRequest, {
|
|
15775
16295
|
runtime,
|
|
@@ -15819,20 +16339,32 @@ function serveChannel(runtime, channel, options) {
|
|
|
15819
16339
|
upgrade: carrier.upgrade
|
|
15820
16340
|
});
|
|
15821
16341
|
}
|
|
16342
|
+
const activeFetch = createActionFetchHandler(runtime, {
|
|
16343
|
+
cors: exchangeCarrier?.cors,
|
|
16344
|
+
onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
|
|
16345
|
+
isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
|
|
16346
|
+
isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
|
|
16347
|
+
security: exchangeSecurity,
|
|
16348
|
+
useErrorStatus: exchangeCarrier?.useErrorStatus,
|
|
16349
|
+
logger: options.logger,
|
|
16350
|
+
transportLabel: exchangeCarrier?.carrierLabel
|
|
16351
|
+
});
|
|
16352
|
+
const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
|
|
16353
|
+
status: 503,
|
|
16354
|
+
headers: { "cache-control": "no-store" }
|
|
16355
|
+
})) : activeFetch(request);
|
|
16356
|
+
const dispose = () => {
|
|
16357
|
+
if (disposed) return;
|
|
16358
|
+
disposed = true;
|
|
16359
|
+
for (const carrier of duplexCarriers) carrier._dispose?.();
|
|
16360
|
+
for (const acceptor of acceptors) acceptor.dispose();
|
|
16361
|
+
};
|
|
15822
16362
|
return {
|
|
15823
16363
|
acceptors,
|
|
15824
|
-
fetch
|
|
15825
|
-
cors: exchangeCarrier?.cors,
|
|
15826
|
-
onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
|
|
15827
|
-
isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
|
|
15828
|
-
isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
|
|
15829
|
-
security: exchangeSecurity,
|
|
15830
|
-
useErrorStatus: exchangeCarrier?.useErrorStatus,
|
|
15831
|
-
logger: options.logger,
|
|
15832
|
-
transportLabel: exchangeCarrier?.carrierLabel
|
|
15833
|
-
}),
|
|
16364
|
+
fetch,
|
|
15834
16365
|
receive,
|
|
15835
16366
|
drop,
|
|
16367
|
+
dispose,
|
|
15836
16368
|
pushToClient,
|
|
15837
16369
|
broadcast,
|
|
15838
16370
|
connections
|
|
@@ -15882,7 +16414,7 @@ err_nice_transport.createChildDomain({
|
|
|
15882
16414
|
*/
|
|
15883
16415
|
function wsAcceptorCarrier(options) {
|
|
15884
16416
|
return {
|
|
15885
|
-
...createDuplexCarrierLifecycle(),
|
|
16417
|
+
...createDuplexCarrierLifecycle(options.inboundLimits),
|
|
15886
16418
|
shape: "duplex",
|
|
15887
16419
|
carrierLabel: options.carrierLabel ?? "ws",
|
|
15888
16420
|
secure: options.secure,
|
|
@@ -16404,11 +16936,11 @@ var VALUE = "value";
|
|
|
16404
16936
|
var isDraft = (value) => !!value && !!value[DRAFT_STATE];
|
|
16405
16937
|
function isDraftable(value) {
|
|
16406
16938
|
if (!value) return false;
|
|
16407
|
-
return isPlainObject$
|
|
16939
|
+
return isPlainObject$2(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
|
|
16408
16940
|
}
|
|
16409
16941
|
var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
|
|
16410
16942
|
var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
|
|
16411
|
-
function isPlainObject$
|
|
16943
|
+
function isPlainObject$2(value) {
|
|
16412
16944
|
if (!value || !isObjectish(value)) return false;
|
|
16413
16945
|
const proto = getPrototypeOf(value);
|
|
16414
16946
|
if (proto === null || proto === O[PROTOTYPE]) return true;
|
|
@@ -16463,7 +16995,7 @@ function shallowCopy(base, strict) {
|
|
|
16463
16995
|
if (isMap(base)) return new Map(base);
|
|
16464
16996
|
if (isSet(base)) return new Set(base);
|
|
16465
16997
|
if (isArray(base)) return Array[PROTOTYPE].slice.call(base);
|
|
16466
|
-
const isPlain = isPlainObject$
|
|
16998
|
+
const isPlain = isPlainObject$2(base);
|
|
16467
16999
|
if (strict === true || strict === "class_only" && !isPlain) {
|
|
16468
17000
|
const descriptors = O.getOwnPropertyDescriptors(base);
|
|
16469
17001
|
delete descriptors[DRAFT_STATE];
|
|
@@ -17747,20 +18279,44 @@ const err_realm = err_nice.createChildDomain({
|
|
|
17747
18279
|
});
|
|
17748
18280
|
//#endregion
|
|
17749
18281
|
//#region ../nice-realm/src/RealmDefinition/Schema/validateValue.ts
|
|
17750
|
-
function isPlainObject(value) {
|
|
18282
|
+
function isPlainObject$1(value) {
|
|
17751
18283
|
return typeof value === "object" && value != null && !Array.isArray(value) && !(value instanceof Uint8Array);
|
|
17752
18284
|
}
|
|
17753
18285
|
/** `undefined` = valid; otherwise where and what was expected. */
|
|
17754
18286
|
function validateValue(node, value) {
|
|
17755
18287
|
switch (node.kind) {
|
|
17756
|
-
case "string":
|
|
17757
|
-
|
|
17758
|
-
|
|
17759
|
-
|
|
17760
|
-
|
|
17761
|
-
|
|
17762
|
-
|
|
17763
|
-
|
|
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;
|
|
17764
18320
|
case "boolean": return typeof value === "boolean" ? void 0 : {
|
|
17765
18321
|
path: [],
|
|
17766
18322
|
expected: "boolean"
|
|
@@ -17777,7 +18333,7 @@ function validateValue(node, value) {
|
|
|
17777
18333
|
expected: "one of the union options"
|
|
17778
18334
|
};
|
|
17779
18335
|
case "object":
|
|
17780
|
-
if (!isPlainObject(value)) return {
|
|
18336
|
+
if (!isPlainObject$1(value)) return {
|
|
17781
18337
|
path: [],
|
|
17782
18338
|
expected: "object"
|
|
17783
18339
|
};
|
|
@@ -17802,10 +18358,14 @@ function validateValue(node, value) {
|
|
|
17802
18358
|
}
|
|
17803
18359
|
return;
|
|
17804
18360
|
case "record":
|
|
17805
|
-
if (!isPlainObject(value)) return {
|
|
18361
|
+
if (!isPlainObject$1(value)) return {
|
|
17806
18362
|
path: [],
|
|
17807
18363
|
expected: "record"
|
|
17808
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
|
+
};
|
|
17809
18369
|
for (const [key, entry] of Object.entries(value)) {
|
|
17810
18370
|
const invalid = validateValue(node.value, entry);
|
|
17811
18371
|
if (invalid != null) return {
|
|
@@ -17819,6 +18379,10 @@ function validateValue(node, value) {
|
|
|
17819
18379
|
path: [],
|
|
17820
18380
|
expected: "array"
|
|
17821
18381
|
};
|
|
18382
|
+
if (node.maxItems != null && value.length > node.maxItems) return {
|
|
18383
|
+
path: [],
|
|
18384
|
+
expected: `an array of at most ${node.maxItems} items`
|
|
18385
|
+
};
|
|
17822
18386
|
for (let i = 0; i < value.length; i++) {
|
|
17823
18387
|
const invalid = validateValue(node.item, value[i]);
|
|
17824
18388
|
if (invalid != null) return {
|
|
@@ -18303,8 +18867,8 @@ const WIRE_OP_TO_IMMER = {
|
|
|
18303
18867
|
[REALM_OP.add]: "add",
|
|
18304
18868
|
[REALM_OP.remove]: "remove"
|
|
18305
18869
|
};
|
|
18306
|
-
function unwrapOptional$
|
|
18307
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
18870
|
+
function unwrapOptional$6(node) {
|
|
18871
|
+
return node.kind === "optional" ? unwrapOptional$6(node.inner) : node;
|
|
18308
18872
|
}
|
|
18309
18873
|
/** The schema node a name path addresses (undefined when the path leaves the schema). */
|
|
18310
18874
|
function schemaNodeAtPath(root, path) {
|
|
@@ -18315,7 +18879,7 @@ function schemaNodeAtPath(root, path) {
|
|
|
18315
18879
|
node = typeof seg === "string" ? entries[seg] : void 0;
|
|
18316
18880
|
entries = void 0;
|
|
18317
18881
|
} else if (node != null) {
|
|
18318
|
-
const inner = unwrapOptional$
|
|
18882
|
+
const inner = unwrapOptional$6(node);
|
|
18319
18883
|
if (inner.kind === "object") node = inner.entries[seg];
|
|
18320
18884
|
else if (inner.kind === "record") node = inner.value;
|
|
18321
18885
|
else return void 0;
|
|
@@ -18324,7 +18888,7 @@ function schemaNodeAtPath(root, path) {
|
|
|
18324
18888
|
}
|
|
18325
18889
|
return node;
|
|
18326
18890
|
}
|
|
18327
|
-
function getAtPath$
|
|
18891
|
+
function getAtPath$6(state, path) {
|
|
18328
18892
|
let current = state;
|
|
18329
18893
|
for (const seg of path) {
|
|
18330
18894
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -18336,7 +18900,7 @@ function getAtPath$5(state, path) {
|
|
|
18336
18900
|
function arrayCutIndex(root, path) {
|
|
18337
18901
|
for (let i = 1; i < path.length; i++) {
|
|
18338
18902
|
const node = schemaNodeAtPath(root, path.slice(0, i));
|
|
18339
|
-
if (node != null && unwrapOptional$
|
|
18903
|
+
if (node != null && unwrapOptional$6(node).kind === "array") return i;
|
|
18340
18904
|
}
|
|
18341
18905
|
}
|
|
18342
18906
|
/**
|
|
@@ -18360,7 +18924,7 @@ function canonicalizeStatePatches(patches, stateAfter, schemaRoot) {
|
|
|
18360
18924
|
out.push({
|
|
18361
18925
|
op: "replace",
|
|
18362
18926
|
path: arrayPath,
|
|
18363
|
-
value: getAtPath$
|
|
18927
|
+
value: getAtPath$6(stateAfter, arrayPath)
|
|
18364
18928
|
});
|
|
18365
18929
|
}
|
|
18366
18930
|
return out;
|
|
@@ -18560,10 +19124,10 @@ function viewSignatureKey(avatar) {
|
|
|
18560
19124
|
* leaves are covered too). For `remove`, from the current state alone. Expansion is bounded by
|
|
18561
19125
|
* `maxLeaves` (an ingress limit — a hostile deep-subtree write must not become CPU).
|
|
18562
19126
|
*/
|
|
18563
|
-
function unwrapOptional$
|
|
18564
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
19127
|
+
function unwrapOptional$5(node) {
|
|
19128
|
+
return node.kind === "optional" ? unwrapOptional$5(node.inner) : node;
|
|
18565
19129
|
}
|
|
18566
|
-
function getAtPath$
|
|
19130
|
+
function getAtPath$5(state, path) {
|
|
18567
19131
|
let current = state;
|
|
18568
19132
|
for (const seg of path) {
|
|
18569
19133
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -18585,7 +19149,7 @@ function expandWriteToLeaves(options) {
|
|
|
18585
19149
|
leaves.push(leaf);
|
|
18586
19150
|
};
|
|
18587
19151
|
const walk = (schemaNode, path, value, prev) => {
|
|
18588
|
-
const inner = unwrapOptional$
|
|
19152
|
+
const inner = unwrapOptional$5(schemaNode);
|
|
18589
19153
|
if (inner.kind === "object") {
|
|
18590
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]);
|
|
18591
19155
|
return;
|
|
@@ -18599,7 +19163,7 @@ function expandWriteToLeaves(options) {
|
|
|
18599
19163
|
}
|
|
18600
19164
|
push(path);
|
|
18601
19165
|
};
|
|
18602
|
-
const prev = getAtPath$
|
|
19166
|
+
const prev = getAtPath$5(options.state, options.path);
|
|
18603
19167
|
walk(node, [...options.path], options.op === "remove" ? void 0 : options.value, prev);
|
|
18604
19168
|
return leaves;
|
|
18605
19169
|
}
|
|
@@ -18611,6 +19175,14 @@ function expandWriteToLeaves(options) {
|
|
|
18611
19175
|
* slice of optimism that can later roll back), `prev`/`state` come from the writer's projected
|
|
18612
19176
|
* view. A NiceError here rejects the write in the same tick, before anything renders.
|
|
18613
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
|
+
}
|
|
18614
19186
|
function predictWrite(options) {
|
|
18615
19187
|
const { realm, avatar, state, basisVersion } = options;
|
|
18616
19188
|
for (const patch of options.patches) {
|
|
@@ -18626,6 +19198,17 @@ function predictWrite(options) {
|
|
|
18626
19198
|
path: [...path, ...invalid.path].join("."),
|
|
18627
19199
|
expected: invalid.expected
|
|
18628
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
|
+
}
|
|
18629
19212
|
}
|
|
18630
19213
|
const leaves = expandWriteToLeaves({
|
|
18631
19214
|
schemaRoot: realm.stateDef,
|
|
@@ -18642,8 +19225,8 @@ function predictWrite(options) {
|
|
|
18642
19225
|
const verdict = evalAlterCond(match.rule.alter, {
|
|
18643
19226
|
avatar,
|
|
18644
19227
|
params: match.params,
|
|
18645
|
-
prev: getAtPath$
|
|
18646
|
-
next: patch.op === "remove" ? void 0 : getAtPath$
|
|
19228
|
+
prev: getAtPath$4(state, leafPath),
|
|
19229
|
+
next: patch.op === "remove" ? void 0 : getAtPath$4(patch.value, rel),
|
|
18647
19230
|
state,
|
|
18648
19231
|
basisVersion
|
|
18649
19232
|
}, void 0);
|
|
@@ -18653,7 +19236,7 @@ function predictWrite(options) {
|
|
|
18653
19236
|
}
|
|
18654
19237
|
return true;
|
|
18655
19238
|
}
|
|
18656
|
-
function getAtPath$
|
|
19239
|
+
function getAtPath$4(state, path) {
|
|
18657
19240
|
let current = state;
|
|
18658
19241
|
for (const seg of path) {
|
|
18659
19242
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -18685,10 +19268,10 @@ function withStructuralParents(state, patches, schemaRoot) {
|
|
|
18685
19268
|
const prefix = patch.path.slice(0, depth);
|
|
18686
19269
|
if (prefixResolves(state, out ?? patches.slice(0, index), prefix)) continue;
|
|
18687
19270
|
const parentNode = depth === 1 ? void 0 : schemaNodeAtPath(schemaRoot, prefix.slice(0, -1));
|
|
18688
|
-
if (parentNode != null && unwrapOptional$
|
|
19271
|
+
if (parentNode != null && unwrapOptional$4(parentNode).kind === "record") break;
|
|
18689
19272
|
const node = schemaNodeAtPath(schemaRoot, prefix);
|
|
18690
19273
|
if (node == null) break;
|
|
18691
|
-
const kind = unwrapOptional$
|
|
19274
|
+
const kind = unwrapOptional$4(node).kind;
|
|
18692
19275
|
if (kind !== "object" && kind !== "record") break;
|
|
18693
19276
|
out ??= patches.slice(0, index);
|
|
18694
19277
|
out.push({
|
|
@@ -18708,14 +19291,14 @@ function prefixResolves(state, earlier, prefix) {
|
|
|
18708
19291
|
if (patch.path.length > prefix.length) continue;
|
|
18709
19292
|
if (!patch.path.every((seg, j) => String(seg) === String(prefix[j]))) continue;
|
|
18710
19293
|
if (patch.op === "remove") return false;
|
|
18711
|
-
return getAtPath$
|
|
19294
|
+
return getAtPath$3(patch.value, prefix.slice(patch.path.length)) !== void 0;
|
|
18712
19295
|
}
|
|
18713
|
-
return getAtPath$
|
|
19296
|
+
return getAtPath$3(state, prefix) !== void 0;
|
|
18714
19297
|
}
|
|
18715
|
-
function unwrapOptional$
|
|
18716
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
19298
|
+
function unwrapOptional$4(node) {
|
|
19299
|
+
return node.kind === "optional" ? unwrapOptional$4(node.inner) : node;
|
|
18717
19300
|
}
|
|
18718
|
-
function getAtPath$
|
|
19301
|
+
function getAtPath$3(value, path) {
|
|
18719
19302
|
let current = value;
|
|
18720
19303
|
for (const seg of path) {
|
|
18721
19304
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -20270,20 +20853,20 @@ function assertTransientRoots(root, dotPaths) {
|
|
|
20270
20853
|
/** Walk a concrete (literal-only) path through the schema; `undefined` if it leaves the schema. */
|
|
20271
20854
|
function resolveConcretePath(node, segments, index) {
|
|
20272
20855
|
if (index >= segments.length) return node;
|
|
20273
|
-
const inner = unwrapOptional$
|
|
20856
|
+
const inner = unwrapOptional$3(node);
|
|
20274
20857
|
if (inner.kind === "object") {
|
|
20275
20858
|
const child = inner.entries[segments[index]];
|
|
20276
20859
|
return child == null ? void 0 : resolveConcretePath(child, segments, index + 1);
|
|
20277
20860
|
}
|
|
20278
20861
|
if (inner.kind === "record") return resolveConcretePath(inner.value, segments, index + 1);
|
|
20279
20862
|
}
|
|
20280
|
-
function unwrapOptional$
|
|
20281
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
20863
|
+
function unwrapOptional$3(node) {
|
|
20864
|
+
return node.kind === "optional" ? unwrapOptional$3(node.inner) : node;
|
|
20282
20865
|
}
|
|
20283
20866
|
/** `undefined` = the pattern can match; otherwise a description of why it never will. */
|
|
20284
20867
|
function checkSegments(node, segments, index) {
|
|
20285
20868
|
if (index >= segments.length) return void 0;
|
|
20286
|
-
const inner = unwrapOptional$
|
|
20869
|
+
const inner = unwrapOptional$3(node);
|
|
20287
20870
|
const seg = segments[index];
|
|
20288
20871
|
const at = describePrefix(segments, index);
|
|
20289
20872
|
if (inner.kind === "object") {
|
|
@@ -20402,147 +20985,6 @@ var RealmRuleTrie = class {
|
|
|
20402
20985
|
}
|
|
20403
20986
|
};
|
|
20404
20987
|
//#endregion
|
|
20405
|
-
//#region ../nice-realm/src/RealmDefinition/Schema/sha256.ts
|
|
20406
|
-
/**
|
|
20407
|
-
* Synchronous SHA-256 over a UTF-8 string → lowercase hex. The schema hash must be computable at
|
|
20408
|
-
* `defineRealm` time (module evaluation, both Node and workerd) — `crypto.subtle.digest` is async,
|
|
20409
|
-
* so a small pure implementation keeps the definition object synchronous and platform-stable.
|
|
20410
|
-
* Verified against the FIPS 180-4 test vectors in `sha256.test.ts`.
|
|
20411
|
-
*/
|
|
20412
|
-
const K = new Uint32Array([
|
|
20413
|
-
1116352408,
|
|
20414
|
-
1899447441,
|
|
20415
|
-
3049323471,
|
|
20416
|
-
3921009573,
|
|
20417
|
-
961987163,
|
|
20418
|
-
1508970993,
|
|
20419
|
-
2453635748,
|
|
20420
|
-
2870763221,
|
|
20421
|
-
3624381080,
|
|
20422
|
-
310598401,
|
|
20423
|
-
607225278,
|
|
20424
|
-
1426881987,
|
|
20425
|
-
1925078388,
|
|
20426
|
-
2162078206,
|
|
20427
|
-
2614888103,
|
|
20428
|
-
3248222580,
|
|
20429
|
-
3835390401,
|
|
20430
|
-
4022224774,
|
|
20431
|
-
264347078,
|
|
20432
|
-
604807628,
|
|
20433
|
-
770255983,
|
|
20434
|
-
1249150122,
|
|
20435
|
-
1555081692,
|
|
20436
|
-
1996064986,
|
|
20437
|
-
2554220882,
|
|
20438
|
-
2821834349,
|
|
20439
|
-
2952996808,
|
|
20440
|
-
3210313671,
|
|
20441
|
-
3336571891,
|
|
20442
|
-
3584528711,
|
|
20443
|
-
113926993,
|
|
20444
|
-
338241895,
|
|
20445
|
-
666307205,
|
|
20446
|
-
773529912,
|
|
20447
|
-
1294757372,
|
|
20448
|
-
1396182291,
|
|
20449
|
-
1695183700,
|
|
20450
|
-
1986661051,
|
|
20451
|
-
2177026350,
|
|
20452
|
-
2456956037,
|
|
20453
|
-
2730485921,
|
|
20454
|
-
2820302411,
|
|
20455
|
-
3259730800,
|
|
20456
|
-
3345764771,
|
|
20457
|
-
3516065817,
|
|
20458
|
-
3600352804,
|
|
20459
|
-
4094571909,
|
|
20460
|
-
275423344,
|
|
20461
|
-
430227734,
|
|
20462
|
-
506948616,
|
|
20463
|
-
659060556,
|
|
20464
|
-
883997877,
|
|
20465
|
-
958139571,
|
|
20466
|
-
1322822218,
|
|
20467
|
-
1537002063,
|
|
20468
|
-
1747873779,
|
|
20469
|
-
1955562222,
|
|
20470
|
-
2024104815,
|
|
20471
|
-
2227730452,
|
|
20472
|
-
2361852424,
|
|
20473
|
-
2428436474,
|
|
20474
|
-
2756734187,
|
|
20475
|
-
3204031479,
|
|
20476
|
-
3329325298
|
|
20477
|
-
]);
|
|
20478
|
-
function rotr(x, n) {
|
|
20479
|
-
return x >>> n | x << 32 - n;
|
|
20480
|
-
}
|
|
20481
|
-
/** SHA-256 of a UTF-8 string, as lowercase hex. */
|
|
20482
|
-
function sha256Hex(input) {
|
|
20483
|
-
const bytes = new TextEncoder().encode(input);
|
|
20484
|
-
const bitLen = bytes.length * 8;
|
|
20485
|
-
const paddedLen = (bytes.length + 8 >> 6) + 1 << 6;
|
|
20486
|
-
const padded = new Uint8Array(paddedLen);
|
|
20487
|
-
padded.set(bytes);
|
|
20488
|
-
padded[bytes.length] = 128;
|
|
20489
|
-
const view = new DataView(padded.buffer);
|
|
20490
|
-
view.setUint32(paddedLen - 8, Math.floor(bitLen / 4294967296), false);
|
|
20491
|
-
view.setUint32(paddedLen - 4, bitLen >>> 0, false);
|
|
20492
|
-
const h = new Uint32Array([
|
|
20493
|
-
1779033703,
|
|
20494
|
-
3144134277,
|
|
20495
|
-
1013904242,
|
|
20496
|
-
2773480762,
|
|
20497
|
-
1359893119,
|
|
20498
|
-
2600822924,
|
|
20499
|
-
528734635,
|
|
20500
|
-
1541459225
|
|
20501
|
-
]);
|
|
20502
|
-
const w = new Uint32Array(64);
|
|
20503
|
-
for (let offset = 0; offset < paddedLen; offset += 64) {
|
|
20504
|
-
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
|
|
20505
|
-
for (let i = 16; i < 64; i++) {
|
|
20506
|
-
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
|
|
20507
|
-
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
|
|
20508
|
-
w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
|
|
20509
|
-
}
|
|
20510
|
-
let a = h[0];
|
|
20511
|
-
let b = h[1];
|
|
20512
|
-
let c = h[2];
|
|
20513
|
-
let d = h[3];
|
|
20514
|
-
let e = h[4];
|
|
20515
|
-
let f = h[5];
|
|
20516
|
-
let g = h[6];
|
|
20517
|
-
let hh = h[7];
|
|
20518
|
-
for (let i = 0; i < 64; i++) {
|
|
20519
|
-
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
20520
|
-
const ch = e & f ^ ~e & g;
|
|
20521
|
-
const temp1 = hh + s1 + ch + K[i] + w[i] >>> 0;
|
|
20522
|
-
const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
|
|
20523
|
-
hh = g;
|
|
20524
|
-
g = f;
|
|
20525
|
-
f = e;
|
|
20526
|
-
e = d + temp1 >>> 0;
|
|
20527
|
-
d = c;
|
|
20528
|
-
c = b;
|
|
20529
|
-
b = a;
|
|
20530
|
-
a = temp1 + temp2 >>> 0;
|
|
20531
|
-
}
|
|
20532
|
-
h[0] = h[0] + a >>> 0;
|
|
20533
|
-
h[1] = h[1] + b >>> 0;
|
|
20534
|
-
h[2] = h[2] + c >>> 0;
|
|
20535
|
-
h[3] = h[3] + d >>> 0;
|
|
20536
|
-
h[4] = h[4] + e >>> 0;
|
|
20537
|
-
h[5] = h[5] + f >>> 0;
|
|
20538
|
-
h[6] = h[6] + g >>> 0;
|
|
20539
|
-
h[7] = h[7] + hh >>> 0;
|
|
20540
|
-
}
|
|
20541
|
-
let hex = "";
|
|
20542
|
-
for (let i = 0; i < 8; i++) hex += h[i].toString(16).padStart(8, "0");
|
|
20543
|
-
return hex;
|
|
20544
|
-
}
|
|
20545
|
-
//#endregion
|
|
20546
20988
|
//#region ../nice-realm/src/RealmDefinition/Schema/schemaHash.ts
|
|
20547
20989
|
/**
|
|
20548
20990
|
* The realm schema hash (plan §4.1/§7.1-of-proposal): SHA-256 over a canonical serialization of
|
|
@@ -20552,13 +20994,24 @@ function sha256Hex(input) {
|
|
|
20552
20994
|
* stale mobile client would be data corruption, not an error.
|
|
20553
20995
|
*
|
|
20554
20996
|
* Known, documented limitation: an embedded standard-schema validator (`t.schema(...)`) is opaque
|
|
20555
|
-
* — its internals don't affect the hash (canonicalized as just `std`)
|
|
20556
|
-
*
|
|
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.
|
|
20557
21000
|
*/
|
|
20558
21001
|
function canonNode(node) {
|
|
20559
21002
|
switch (node.kind) {
|
|
20560
|
-
case "string":
|
|
21003
|
+
case "string": return node.maxLength == null ? node.kind : {
|
|
21004
|
+
k: "string",
|
|
21005
|
+
max: node.maxLength
|
|
21006
|
+
};
|
|
20561
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
|
+
};
|
|
20562
21015
|
case "boolean": return node.kind;
|
|
20563
21016
|
case "literal": return {
|
|
20564
21017
|
k: "lit",
|
|
@@ -20576,16 +21029,31 @@ function canonNode(node) {
|
|
|
20576
21029
|
k: "obj",
|
|
20577
21030
|
e: Object.keys(node.entries).sort().map((n) => [n, canonNode(node.entries[n])])
|
|
20578
21031
|
};
|
|
20579
|
-
case "record":
|
|
20580
|
-
|
|
20581
|
-
|
|
20582
|
-
|
|
20583
|
-
|
|
20584
|
-
|
|
20585
|
-
|
|
20586
|
-
|
|
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
|
|
20587
21056
|
};
|
|
20588
|
-
case "standard": return { k: "std" };
|
|
20589
21057
|
}
|
|
20590
21058
|
}
|
|
20591
21059
|
/** Canonical serialization (deterministic across platforms — everything sorted). */
|
|
@@ -20604,11 +21072,11 @@ function computeSchemaHash(inputs) {
|
|
|
20604
21072
|
}
|
|
20605
21073
|
//#endregion
|
|
20606
21074
|
//#region ../nice-realm/src/RealmDefinition/Schema/tokenMap.ts
|
|
20607
|
-
function unwrapOptional$
|
|
20608
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
21075
|
+
function unwrapOptional$2(node) {
|
|
21076
|
+
return node.kind === "optional" ? unwrapOptional$2(node.inner) : node;
|
|
20609
21077
|
}
|
|
20610
21078
|
function buildLevelForNode(node) {
|
|
20611
|
-
const inner = unwrapOptional$
|
|
21079
|
+
const inner = unwrapOptional$2(node);
|
|
20612
21080
|
if (inner.kind === "object") return buildLevel(inner.entries);
|
|
20613
21081
|
if (inner.kind === "record") return {
|
|
20614
21082
|
toToken: /* @__PURE__ */ new Map(),
|
|
@@ -20730,6 +21198,24 @@ function defineRealm(input) {
|
|
|
20730
21198
|
}
|
|
20731
21199
|
//#endregion
|
|
20732
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
|
+
}
|
|
20733
21219
|
function union(...args) {
|
|
20734
21220
|
const options = args.flatMap((arg) => Array.isArray(arg) ? arg : [arg]);
|
|
20735
21221
|
if (options.length < 2) throw new Error(`t.union needs at least 2 options, got ${options.length}`);
|
|
@@ -20744,11 +21230,18 @@ function union(...args) {
|
|
|
20744
21230
|
* schema hash, and (M4) the server-side value validator.
|
|
20745
21231
|
*/
|
|
20746
21232
|
const t = {
|
|
20747
|
-
string() {
|
|
20748
|
-
|
|
21233
|
+
string(options = {}) {
|
|
21234
|
+
const maxLength = checkCount("string maxLength", options.maxLength);
|
|
21235
|
+
return {
|
|
21236
|
+
kind: "string",
|
|
21237
|
+
...maxLength != null ? { maxLength } : {}
|
|
21238
|
+
};
|
|
20749
21239
|
},
|
|
20750
|
-
number() {
|
|
20751
|
-
return {
|
|
21240
|
+
number(options = {}) {
|
|
21241
|
+
return {
|
|
21242
|
+
kind: "number",
|
|
21243
|
+
...checkNumberOptions(options)
|
|
21244
|
+
};
|
|
20752
21245
|
},
|
|
20753
21246
|
boolean() {
|
|
20754
21247
|
return { kind: "boolean" };
|
|
@@ -20779,29 +21272,36 @@ const t = {
|
|
|
20779
21272
|
varName
|
|
20780
21273
|
};
|
|
20781
21274
|
},
|
|
20782
|
-
record(key, value) {
|
|
21275
|
+
record(key, value, options = {}) {
|
|
21276
|
+
const maxKeys = checkCount("record maxKeys", options.maxKeys);
|
|
20783
21277
|
return {
|
|
20784
21278
|
kind: "record",
|
|
20785
21279
|
keyVar: key.varName,
|
|
20786
|
-
value
|
|
21280
|
+
value,
|
|
21281
|
+
...maxKeys != null ? { maxKeys } : {}
|
|
20787
21282
|
};
|
|
20788
21283
|
},
|
|
20789
21284
|
/** Leaf-replace semantics only in v1 (proposal §7.8) — prefer keyed {@link t.record} collections. */
|
|
20790
|
-
array(item) {
|
|
21285
|
+
array(item, options = {}) {
|
|
21286
|
+
const maxItems = checkCount("array maxItems", options.maxItems);
|
|
20791
21287
|
return {
|
|
20792
21288
|
kind: "array",
|
|
20793
|
-
item
|
|
21289
|
+
item,
|
|
21290
|
+
...maxItems != null ? { maxItems } : {}
|
|
20794
21291
|
};
|
|
20795
21292
|
},
|
|
20796
21293
|
/**
|
|
20797
|
-
* Embed a standard-schema validator (e.g. valibot) at a leaf.
|
|
20798
|
-
*
|
|
20799
|
-
*
|
|
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.
|
|
20800
21298
|
*/
|
|
20801
|
-
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");
|
|
20802
21301
|
return {
|
|
20803
21302
|
kind: "standard",
|
|
20804
|
-
schema
|
|
21303
|
+
schema,
|
|
21304
|
+
...options.hashTag != null ? { hashTag: options.hashTag } : {}
|
|
20805
21305
|
};
|
|
20806
21306
|
},
|
|
20807
21307
|
/**
|
|
@@ -20814,6 +21314,202 @@ const t = {
|
|
|
20814
21314
|
}
|
|
20815
21315
|
};
|
|
20816
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
|
|
20817
21513
|
//#region ../nice-realm/src/RealmServer/viewSlice.ts
|
|
20818
21514
|
function leafVisible(ctx, path) {
|
|
20819
21515
|
const match = ctx.trie.match(path);
|
|
@@ -20971,6 +21667,8 @@ var RealmServerEngine = class {
|
|
|
20971
21667
|
_now;
|
|
20972
21668
|
_instanceId;
|
|
20973
21669
|
_state;
|
|
21670
|
+
/** Whether the schema declares any bounds — false skips every bounded-state walk. */
|
|
21671
|
+
_hasBounds;
|
|
20974
21672
|
_version = 0;
|
|
20975
21673
|
_mutating = false;
|
|
20976
21674
|
/** The log epoch (review B.3): identifies this history — replay requires an exact match. */
|
|
@@ -21055,6 +21753,14 @@ var RealmServerEngine = class {
|
|
|
21055
21753
|
this._state = typeof options.initialState === "function" ? options.initialState({ instanceId: this._instanceId }) : options.initialState;
|
|
21056
21754
|
this._epoch = mintEpoch();
|
|
21057
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
|
+
}
|
|
21058
21764
|
}
|
|
21059
21765
|
get state() {
|
|
21060
21766
|
return this._state;
|
|
@@ -21421,6 +22127,13 @@ var RealmServerEngine = class {
|
|
|
21421
22127
|
const [nextState, patches] = produced;
|
|
21422
22128
|
if (patches.length === 0) return;
|
|
21423
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
|
+
}
|
|
21424
22137
|
this._commit(nextState, canonical, { source: "server" });
|
|
21425
22138
|
this._flushEgress();
|
|
21426
22139
|
}
|
|
@@ -21540,6 +22253,16 @@ var RealmServerEngine = class {
|
|
|
21540
22253
|
this._reject(conn, frame.clientSeq, err_realm.fromId("write_target_missing", { path }));
|
|
21541
22254
|
return;
|
|
21542
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
|
+
}
|
|
21543
22266
|
const version = this._commit(nextState, namePatches, {
|
|
21544
22267
|
source: "write",
|
|
21545
22268
|
avatar: conn.avatar
|
|
@@ -21605,6 +22328,16 @@ var RealmServerEngine = class {
|
|
|
21605
22328
|
this._reject(conn, frame.clientSeq, err_realm.fromId("frame_invalid", { reason: "unsafe record key" }));
|
|
21606
22329
|
return;
|
|
21607
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
|
+
}
|
|
21608
22341
|
const version = this._commit(nextState, canonical, {
|
|
21609
22342
|
source: "intent",
|
|
21610
22343
|
avatar: conn.avatar
|