@directive-run/core 1.22.0 → 1.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/adapter-utils.cjs +1 -1
  2. package/dist/adapter-utils.d.cts +1 -1
  3. package/dist/adapter-utils.d.ts +1 -1
  4. package/dist/adapter-utils.js +1 -1
  5. package/dist/chunk-C3FW27S5.js +3 -0
  6. package/dist/chunk-C3FW27S5.js.map +1 -0
  7. package/dist/chunk-IZNOPHPL.js +3 -0
  8. package/dist/chunk-IZNOPHPL.js.map +1 -0
  9. package/dist/chunk-LN5H74CU.js +2 -0
  10. package/dist/{chunk-RBF653NR.js.map → chunk-LN5H74CU.js.map} +1 -1
  11. package/dist/chunk-PTT4MWNL.cjs +3 -0
  12. package/dist/chunk-PTT4MWNL.cjs.map +1 -0
  13. package/dist/chunk-QR2756CJ.js +2 -0
  14. package/dist/chunk-QR2756CJ.js.map +1 -0
  15. package/dist/{chunk-GKMJ7NMP.cjs → chunk-RD2HO5NZ.cjs} +2 -2
  16. package/dist/{chunk-GKMJ7NMP.cjs.map → chunk-RD2HO5NZ.cjs.map} +1 -1
  17. package/dist/{chunk-GACC2DMS.cjs → chunk-S6W6Y44G.cjs} +2 -2
  18. package/dist/{chunk-GACC2DMS.cjs.map → chunk-S6W6Y44G.cjs.map} +1 -1
  19. package/dist/{chunk-YJEDX2JX.js → chunk-SERVIHA3.js} +3 -3
  20. package/dist/chunk-SERVIHA3.js.map +1 -0
  21. package/dist/{chunk-OAPD3HIG.cjs → chunk-UDSP7U54.cjs} +3 -3
  22. package/dist/chunk-UDSP7U54.cjs.map +1 -0
  23. package/dist/chunk-UQZ2SMGS.cjs +2 -0
  24. package/dist/chunk-UQZ2SMGS.cjs.map +1 -0
  25. package/dist/{chunk-6PF2FRBG.js → chunk-WD47DB52.js} +2 -2
  26. package/dist/{chunk-6PF2FRBG.js.map → chunk-WD47DB52.js.map} +1 -1
  27. package/dist/chunk-WU4AXN3P.cjs +3 -0
  28. package/dist/chunk-WU4AXN3P.cjs.map +1 -0
  29. package/dist/{index-DRPkZ8HE.d.cts → index-Bz6DOdDN.d.ts} +32 -5
  30. package/dist/{index-BgKC_ZT_.d.ts → index-Cpgj4byM.d.cts} +32 -5
  31. package/dist/index.cjs +2 -2
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +8 -130
  34. package/dist/index.d.ts +8 -130
  35. package/dist/index.js +2 -2
  36. package/dist/index.js.map +1 -1
  37. package/dist/internals.cjs +1 -1
  38. package/dist/internals.d.cts +10 -4
  39. package/dist/internals.d.ts +10 -4
  40. package/dist/internals.js +1 -1
  41. package/dist/plugins/index.cjs +2 -2
  42. package/dist/plugins/index.cjs.map +1 -1
  43. package/dist/plugins/index.d.cts +202 -3
  44. package/dist/plugins/index.d.ts +202 -3
  45. package/dist/plugins/index.js +2 -2
  46. package/dist/plugins/index.js.map +1 -1
  47. package/dist/{plugins-5Supk7it.d.cts → plugins-CaPMTICa.d.cts} +323 -2
  48. package/dist/{plugins-5Supk7it.d.ts → plugins-CaPMTICa.d.ts} +323 -2
  49. package/dist/{predicate-DYb-3Mvl.d.cts → predicate-CU0YC1i6.d.cts} +1 -1
  50. package/dist/{predicate-C9oMO_ny.d.ts → predicate-CgpwJqf4.d.ts} +1 -1
  51. package/dist/system-T6EZ6EYN.js +2 -0
  52. package/dist/{system-6YWCXQOQ.js.map → system-T6EZ6EYN.js.map} +1 -1
  53. package/dist/system-V7B4YUIR.cjs +2 -0
  54. package/dist/{system-5FKUBLLV.cjs.map → system-V7B4YUIR.cjs.map} +1 -1
  55. package/dist/testing.cjs +1 -1
  56. package/dist/testing.cjs.map +1 -1
  57. package/dist/testing.d.cts +1 -1
  58. package/dist/testing.d.ts +1 -1
  59. package/dist/testing.js +1 -1
  60. package/dist/testing.js.map +1 -1
  61. package/dist/worker.cjs +1 -1
  62. package/dist/worker.cjs.map +1 -1
  63. package/dist/worker.d.cts +1 -1
  64. package/dist/worker.d.ts +1 -1
  65. package/dist/worker.js +1 -1
  66. package/dist/worker.js.map +1 -1
  67. package/package.json +2 -2
  68. package/dist/chunk-6NCC6RBC.js +0 -3
  69. package/dist/chunk-6NCC6RBC.js.map +0 -1
  70. package/dist/chunk-GBCWXTXW.cjs +0 -3
  71. package/dist/chunk-GBCWXTXW.cjs.map +0 -1
  72. package/dist/chunk-KGTBTGOY.js +0 -2
  73. package/dist/chunk-KGTBTGOY.js.map +0 -1
  74. package/dist/chunk-MARZI3EY.cjs +0 -2
  75. package/dist/chunk-MARZI3EY.cjs.map +0 -1
  76. package/dist/chunk-OAPD3HIG.cjs.map +0 -1
  77. package/dist/chunk-QTY2FXZY.cjs +0 -3
  78. package/dist/chunk-QTY2FXZY.cjs.map +0 -1
  79. package/dist/chunk-RBF653NR.js +0 -2
  80. package/dist/chunk-SFUVPP4L.js +0 -3
  81. package/dist/chunk-SFUVPP4L.js.map +0 -1
  82. package/dist/chunk-YJEDX2JX.js.map +0 -1
  83. package/dist/system-5FKUBLLV.cjs +0 -2
  84. package/dist/system-6YWCXQOQ.js +0 -2
@@ -0,0 +1,3 @@
1
+ var S=typeof process<"u"&&process.env?.NODE_ENV!=="production";function l(e,o=new WeakSet){if(e===null||typeof e!="object")return e;let t=e;if(o.has(t)||Object.isFrozen(t))return e;if(o.add(t),Array.isArray(t))for(let s of t)l(s,o);else for(let s of Object.keys(t))l(t[s],o);return Object.freeze(t),e}function A(e){return l(e)}function T(e,o,t){return (...s)=>{try{return t(...s)}catch(u){throw u instanceof Error&&u.message.startsWith("[Directive] ")?new Error(`[Directive] ${e} '${o}': ${u.message.slice(12)}`,{cause:u}):u}}}var w=Symbol.for("@directive-run/core.timeout-marker");async function E(e,o,t){let s,u=new Promise((g,d)=>{s=setTimeout(()=>{let c=new Error(t);Object.defineProperty(c,w,{value:true,enumerable:false,configurable:false,writable:false}),d(c);},o);});try{return await Promise.race([e,u])}finally{clearTimeout(s);}}function m(e,o=50){let t=new WeakSet;function s(r){if(r===null)return "null";if(r===void 0)return "undefined";let n=typeof r;if(n==="string")return JSON.stringify(r);if(n==="number"||n==="boolean")return String(r);if(n==="function")return '"[function]"';if(n==="symbol")return '"[symbol]"'}function u(r,n){if(t.has(r))return '"[circular]"';t.add(r);let i=n();return t.delete(r),i}function g(r,n){return u(r,()=>`[${r.map(i=>c(i,n+1)).join(",")}]`)}function d(r,n){return u(r,()=>`{${Object.keys(r).sort().map(f=>`${JSON.stringify(f)}:${c(r[f],n+1)}`).join(",")}}`)}function c(r,n){if(n>o)return '"[max depth exceeded]"';if(typeof r=="bigint")return `${r.toString()}n`;let i=s(r);if(i!==void 0)return i;if(r instanceof Date)return `D:${r.toISOString()}`;if(r instanceof RegExp)return `R:${r.source}:${r.flags}`;if(r instanceof Map){let a=[...r.entries()].sort();return `M:${c(a,n+1)}`}if(r instanceof Set){let a=[...r].sort();return `S:${c(a,n+1)}`}return Array.isArray(r)?g(r,n):typeof r=="object"?d(r,n):'"[unknown]"'}return c(e,0)}function D(e,o=50){let t=new Set(["__proto__","constructor","prototype"]),s=new WeakSet;function u(r,n){if(s.has(r))return true;s.add(r);let i=n();return s.delete(r),i}function g(r,n){for(let i of r)if(!c(i,n+1))return false;return true}function d(r,n){for(let i of Object.keys(r))if(t.has(i)||!c(r[i],n+1))return false;return true}function c(r,n){if(n>o)return false;if(r==null||typeof r!="object")return true;let i=r;return Array.isArray(i)?u(i,()=>g(i,n)):u(i,()=>d(i,n))}return c(e,0)}function $(e,o){if(e===o)return true;if(!e||!o)return false;let t=Object.keys(e),s=Object.keys(o);if(t.length!==s.length)return false;for(let u of t)if(e[u]!==o[u])return false;return true}function R(e){let o=m(e),t=5381;for(let s=0;s<o.length;s++)t=(t<<5)+t^o.charCodeAt(s);return (t>>>0).toString(16)}function k(e,o=Date.now()){return e.expiresAt!==void 0&&o>e.expiresAt}function P(e,o=Date.now()){if(!e||typeof e!="object")throw new Error("[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.");if(!("data"in e))throw new Error("[Directive] Invalid snapshot: missing required 'data' property.");if(!("createdAt"in e)||typeof e.createdAt!="number")throw new Error("[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).");if(k(e,o)){let t=new Date(e.expiresAt).toISOString();throw new Error(`[Directive] Snapshot expired at ${t}. Obtain a fresh snapshot from the source.`)}return e.data}function v(e,o){let t=[];function s(n,i,a,f){t.push({path:n,oldValue:i,newValue:a,type:f});}function u(n,i,a){return n==null?(i!=null&&s(a,n,i,"added"),true):i==null?(s(a,n,i,"removed"),true):false}function g(n,i,a){if(n.length!==i.length){s(a,n,i,"changed");return}for(let f=0;f<n.length;f++)c(n[f],i[f],`${a}[${f}]`);}function d(n,i,a){let f=new Set([...Object.keys(n),...Object.keys(i)]);for(let y of f){let p=a?`${a}.${y}`:y;y in n?y in i?c(n[y],i[y],p):s(p,n[y],void 0,"removed"):s(p,void 0,i[y],"added");}}function c(n,i,a){if(!u(n,i,a)){if(typeof n!="object"||typeof i!="object"){Object.is(n,i)||s(a,n,i,"changed");return}if(Array.isArray(n)&&Array.isArray(i)){g(n,i,a);return}d(n,i,a);}}c(e.data,o.data,"");let r=e.version!==o.version&&(e.version!==void 0||o.version!==void 0);return {identical:t.length===0,changes:t,versionChanged:r,oldVersion:e.version,newVersion:o.version}}function C(e){return "signature"in e&&typeof e.signature=="string"}async function I(e,o){let t=m({data:e.data,createdAt:e.createdAt,expiresAt:e.expiresAt,version:e.version,metadata:e.metadata}),s=await h(t,o);return {...e,signature:s,algorithm:"hmac-sha256"}}async function _(e,o,t){if(!e.signature||e.algorithm!=="hmac-sha256")return false;let s=m({data:e.data,createdAt:e.createdAt,expiresAt:e.expiresAt,version:e.version,metadata:e.metadata}),u=await h(s,o);return !(!b(e.signature,u)||!t?.ignoreExpiry&&k(e,t?.now))}async function h(e,o){let t=typeof o=="string"?new TextEncoder().encode(o):o,s={name:"HMAC",hash:{name:"SHA-256"}},u=await crypto.subtle.importKey("raw",t,s,false,["sign"]),g=new TextEncoder().encode(e),d=await crypto.subtle.sign("HMAC",u,g);return Array.from(new Uint8Array(d)).map(c=>c.toString(16).padStart(2,"0")).join("")}function b(e,o){if(e.length!==o.length)return false;let t=0;for(let s=0;s<e.length;s++)t|=e.charCodeAt(s)^o.charCodeAt(s);return t===0}function L(e,o=500){try{let t=JSON.stringify(e,(s,u)=>typeof u=="bigint"?`${u}n`:u,2);return t?t.length<=o?t:`${t.slice(0,o)}
2
+ ... (truncated, ${t.length} chars total)`:"[undefined]"}catch{return "[unserializable]"}}export{S as a,A as b,T as c,w as d,E as e,m as f,D as g,$ as h,R as i,k as j,P as k,v as l,C as m,I as n,_ as o,L as p};//# sourceMappingURL=chunk-IZNOPHPL.js.map
3
+ //# sourceMappingURL=chunk-IZNOPHPL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/dev-true.ts","../src/utils/utils.ts"],"names":["dev_true_default","deepFreeze","value","seen","obj","item","key","freezeSpec","spec","attributeError","category","id","fn","args","e","TIMEOUT_MARKER","withTimeout","promise","ms","errorMessage","timeoutId","timeoutPromise","_","reject","err","stableStringify","maxDepth","stringifyPrimitive","val","type","withCircularGuard","result","stringifyArray","depth","v","stringify","stringifyObject","k","primitive","entries","items","isPrototypeSafe","dangerousKeys","objVal","checkArray","arr","check","checkObject","shallowEqual","a","b","keysA","keysB","hashObject","str","hash","i","isSnapshotExpired","snapshot","now","validateSnapshot","expiredAt","diffSnapshots","oldSnapshot","newSnapshot","changes","pushChange","path","oldValue","newValue","compareNullish","oldObj","newObj","compareArrays","oldArr","newArr","compare","compareObjects","oldRecord","newRecord","allKeys","childPath","versionChanged","isSignedSnapshot","signSnapshot","secret","payload","signature","hmacSha256","verifySnapshotSignature","signedSnapshot","options","expectedSignature","timingSafeEqual","message","secretBytes","algorithm","messageBytes","safeStringify","data","maxLen","_key"],"mappings":"AAIA,IAAOA,EAAQ,OAAO,OAAA,CAAY,GAAA,EAChC,OAAA,CAAQ,KAAK,QAAA,GAAa,aCarB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AAA,CAAcC,CAAAA,CAAeC,CAAAA,CAAS,IAAa,CACjE,GAAI,CACF,IAAM9C,EAAM,IAAA,CAAK,SAAA,CACf6C,CAAAA,CACA,CAACE,EAAMnG,CAAAA,GACD,OAAOA,CAAAA,EAAU,QAAA,CACZ,GAAGA,CAAK,CAAA,CAAA,CAAA,CAGVA,CAAAA,CAET,CACF,EACA,OAAKoD,CAAAA,CAGDA,CAAAA,CAAI,MAAA,EAAU8C,EACT9C,CAAAA,CAGF,CAAA,EAAGA,EAAI,KAAA,CAAM,CAAA,CAAG8C,CAAM,CAAC;AAAA,gBAAA,EAAqB9C,CAAAA,CAAI,MAAM,CAAA,aAAA,CAAA,CANpD,aAOX,MAAQ,CACN,OAAO,kBACT,CACF","file":"chunk-IZNOPHPL.js","sourcesContent":["// Runtime check that bundlers (webpack, esbuild, turbopack, rollup) inline\n// based on the consumer's NODE_ENV. Without this, the published bundle bakes\n// in `true` and dev-mode validation runs in every consumer's production\n// build — a real footgun the v1.5/v1.6 release hit.\nexport default typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\";\n","/**\n * Shared utilities for Directive\n */\n\n// ============================================================================\n// Deep freeze\n// ============================================================================\n\n/**\n * Recursively `Object.freeze` an object including nested objects, arrays, and\n * array elements. Uses a `WeakSet` to handle cycles. Skips primitives and\n * already-frozen values to avoid wasted work.\n *\n * Used at definition-registration sites (constraints, derivations, effects,\n * events, prefixed specs) so post-registration mutation of a nested operand\n * cannot silently change the compiled closure's behavior. Prefer\n * {@link freezeSpec} at registration sites — it documents the convention.\n */\nexport function deepFreeze<T>(\n value: T,\n seen: WeakSet<object> = new WeakSet(),\n): T {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n const obj = value as unknown as object;\n if (seen.has(obj) || Object.isFrozen(obj)) {\n return value;\n }\n seen.add(obj);\n\n if (Array.isArray(obj)) {\n for (const item of obj) {\n deepFreeze(item, seen);\n }\n } else {\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key], seen);\n }\n }\n\n Object.freeze(obj);\n return value;\n}\n\n/**\n * Freeze a definition spec at registration. Centralizes the deepFreeze\n * convention so a new definition arm cannot forget it — every constraint,\n * derivation, effect, event, and prefixed-spec registration funnels through\n * this single helper.\n *\n * @param spec - The definition spec to freeze (mutated in place, returned)\n * @returns The same `spec` value, now deeply frozen\n *\n * @example\n * ```ts\n * // At registration time, freeze user-supplied specs so post-registration\n * // mutation cannot silently change the compiled closure's behavior.\n * const spec = freezeSpec(userPredicate);\n * memoizePredicate(spec);\n * ```\n */\nexport function freezeSpec<T>(spec: T): T {\n return deepFreeze(spec);\n}\n\n/**\n * Wrap a synthesized definition function so a `[Directive]`-prefixed error\n * thrown from inside it is re-thrown with the owning definition's category +\n * id injected, and the original error preserved as `cause`. Non-`[Directive]`\n * errors (user code, native) pass through untouched.\n *\n * Centralizes the owner-attribution wrap shared by the data-form `when`\n * (constraints), `on` (effects), and `compute` (derivations) closures — a\n * `[Directive]`-prefixed throw (e.g. `$matches: string`) is re-pointed at the\n * owning definition so the stack trace blames user config, not the runtime.\n *\n * @param category - The owning definition kind, used in the re-thrown message.\n * @param id - The owning definition's id.\n * @param fn - The synthesized function to wrap.\n * @returns A function with identical signature that re-attributes Directive errors.\n */\nexport function attributeError<A extends unknown[], R>(\n category: \"constraint\" | \"effect\" | \"derivation\",\n id: string,\n fn: (...args: A) => R,\n): (...args: A) => R {\n // Synchronous by design: the wrapped definition functions (memoized\n // predicate `when`/`on` closures, template closures) always return\n // synchronously. A `try/catch` only re-attributes a synchronous throw — an\n // async-returning fn's rejected promise would escape un-re-attributed.\n return (...args: A): R => {\n try {\n return fn(...args);\n } catch (e) {\n if (e instanceof Error && e.message.startsWith(\"[Directive] \")) {\n throw new Error(\n `[Directive] ${category} '${id}': ${e.message.slice(\"[Directive] \".length)}`,\n { cause: e },\n );\n }\n throw e;\n }\n };\n}\n\n/**\n * Execute a promise with a timeout, properly cleaning up the timer.\n * Used by both constraints and resolvers for timeout handling.\n *\n * @param promise - The promise to wrap with a timeout\n * @param ms - Timeout duration in milliseconds\n * @param errorMessage - Error message if timeout occurs\n * @returns The promise result\n * @throws Error if timeout is exceeded\n */\n/**\n * Symbol marker attached to the Error thrown when {@link withTimeout}\n * fires. The retry path in `resolvers.ts` reads this to construct\n * `ShouldRetryContext.reason = \"timeout\"` so user-supplied\n * `shouldRetry(err, attempt, ctx)` can branch on `ctx.reason === \"timeout\"`.\n *\n * Non-enumerable so it doesn't leak into JSON serialization of the\n * thrown error.\n *\n * @internal\n */\nexport const TIMEOUT_MARKER: unique symbol = Symbol.for(\n \"@directive-run/core.timeout-marker\",\n);\n\nexport async function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n errorMessage: string,\n): Promise<T> {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n const err = new Error(errorMessage);\n Object.defineProperty(err, TIMEOUT_MARKER, {\n value: true,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n reject(err);\n }, ms);\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n clearTimeout(timeoutId!);\n }\n}\n\n/**\n * Normalize an error to an Error instance.\n * Ensures consistent error handling throughout the library.\n *\n * @param error - The error to normalize (can be anything)\n * @returns An Error instance\n */\nexport function normalizeError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n/**\n * Create a stable JSON string with sorted keys.\n * Handles circular references and deeply nested objects safely.\n *\n * @param value - The value to stringify\n * @param maxDepth - Maximum nesting depth (default: 50)\n * @returns A stable JSON string\n */\nexport function stableStringify(value: unknown, maxDepth = 50): string {\n const seen = new WeakSet();\n\n /** Stringify a primitive value (null, undefined, string, number, boolean, function, symbol). */\n function stringifyPrimitive(val: unknown): string | undefined {\n if (val === null) return \"null\";\n if (val === undefined) return \"undefined\";\n\n const type = typeof val;\n if (type === \"string\") return JSON.stringify(val);\n if (type === \"number\" || type === \"boolean\") return String(val);\n if (type === \"function\") return '\"[function]\"';\n if (type === \"symbol\") return '\"[symbol]\"';\n\n return undefined;\n }\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(obj: object, fn: () => string): string {\n if (seen.has(obj)) {\n return '\"[circular]\"';\n }\n seen.add(obj);\n const result = fn();\n seen.delete(obj);\n\n return result;\n }\n\n /** Stringify an array with circular reference protection. */\n function stringifyArray(val: unknown[], depth: number): string {\n return withCircularGuard(\n val,\n () => `[${val.map((v) => stringify(v, depth + 1)).join(\",\")}]`,\n );\n }\n\n /** Stringify an object with sorted keys and circular reference protection. */\n function stringifyObject(\n obj: Record<string, unknown>,\n depth: number,\n ): string {\n return withCircularGuard(obj, () => {\n const keys = Object.keys(obj).sort();\n const pairs = keys.map(\n (k) => `${JSON.stringify(k)}:${stringify(obj[k], depth + 1)}`,\n );\n\n return `{${pairs.join(\",\")}}`;\n });\n }\n\n /** Recursively stringify a value with depth limit and circular detection. */\n function stringify(val: unknown, depth: number): string {\n if (depth > maxDepth) {\n return '\"[max depth exceeded]\"';\n }\n\n // BigInt is not JSON-serializable; encode with a trailing 'n' to remain\n // distinct from numeric strings.\n if (typeof val === \"bigint\") {\n return `${val.toString()}n`;\n }\n\n const primitive = stringifyPrimitive(val);\n if (primitive !== undefined) {\n return primitive;\n }\n\n // Typed-value branches: each prefix is bare (no outer quotes) so it can\n // never collide with a JSON-encoded string. `JSON.stringify(\"D:...\")`\n // emits `\"D:...\"` (the wrapping quotes ARE part of the output string),\n // whereas the Date branch emits `D:...` (no quotes). Distinct outputs.\n if (val instanceof Date) {\n return `D:${val.toISOString()}`;\n }\n if (val instanceof RegExp) {\n return `R:${val.source}:${val.flags}`;\n }\n if (val instanceof Map) {\n const entries = [...val.entries()].sort();\n return `M:${stringify(entries, depth + 1)}`;\n }\n if (val instanceof Set) {\n const items = [...val].sort();\n return `S:${stringify(items, depth + 1)}`;\n }\n\n if (Array.isArray(val)) {\n return stringifyArray(val, depth);\n }\n\n if (typeof val === \"object\") {\n return stringifyObject(val as Record<string, unknown>, depth);\n }\n\n return '\"[unknown]\"';\n }\n\n return stringify(value, 0);\n}\n\n/**\n * Check for prototype pollution in an object, including nested objects.\n * Returns true if the object is safe, false if dangerous keys are found.\n *\n * @param obj - The object to check\n * @param maxDepth - Maximum nesting depth to check (default: 50)\n * @returns True if safe, false if dangerous keys found\n */\nexport function isPrototypeSafe(obj: unknown, maxDepth = 50): boolean {\n const dangerousKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n const seen = new WeakSet();\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(objVal: object, fn: () => boolean): boolean {\n if (seen.has(objVal)) return true;\n seen.add(objVal);\n const result = fn();\n seen.delete(objVal);\n\n return result;\n }\n\n /** Check array elements for prototype pollution keys. */\n function checkArray(arr: unknown[], depth: number): boolean {\n for (const item of arr) {\n if (!check(item, depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Check object keys and values for prototype pollution. */\n function checkObject(\n objVal: Record<string, unknown>,\n depth: number,\n ): boolean {\n for (const key of Object.keys(objVal)) {\n if (dangerousKeys.has(key)) {\n return false;\n }\n if (!check(objVal[key], depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Recursively check a value tree for dangerous prototype keys. */\n function check(val: unknown, depth: number): boolean {\n if (depth > maxDepth) return false; // Fail safe at max depth - don't assume safety\n if (val === null || val === undefined) return true;\n if (typeof val !== \"object\") return true;\n\n const objVal = val as Record<string, unknown>;\n\n if (Array.isArray(objVal)) {\n return withCircularGuard(objVal, () => checkArray(objVal, depth));\n }\n\n return withCircularGuard(objVal, () => checkObject(objVal, depth));\n }\n\n return check(obj, 0);\n}\n\n/**\n * Shallow equality comparison for objects.\n * Used by React hooks to avoid unnecessary re-renders.\n *\n * @param a - First object\n * @param b - Second object\n * @returns True if objects are shallowly equal\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n a: T,\n b: T,\n): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (a[key] !== b[key]) return false;\n }\n\n return true;\n}\n\n/**\n * Generate a simple hash string from an object.\n * Uses djb2 algorithm on the stable stringified value.\n *\n * **Limitations:**\n * - 32-bit hash output means collision probability increases with data set size\n * (birthday paradox: ~50% collision chance at ~77,000 distinct values)\n * - Suitable for: cache invalidation, change detection, deduplication of small sets\n * - NOT suitable for: cryptographic use, security-sensitive operations, large-scale deduplication\n *\n * For security-sensitive use cases requiring stronger collision resistance,\n * consider using a cryptographic hash like SHA-256.\n *\n * @param value - The value to hash\n * @returns A hex hash string (8 characters, 32 bits)\n */\nexport function hashObject(value: unknown): string {\n const str = stableStringify(value);\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n // Convert to unsigned 32-bit and then to hex\n return (hash >>> 0).toString(16);\n}\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\n/**\n * Distributable snapshot type for type-safe helper functions.\n */\nexport interface DistributableSnapshotLike<T = Record<string, unknown>> {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Check if a distributable snapshot has expired.\n * Returns false if the snapshot has no expiresAt field.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({ ttlSeconds: 3600 });\n * // ... later ...\n * if (isSnapshotExpired(snapshot)) {\n * // Refresh the snapshot\n * }\n * ```\n *\n * @param snapshot - The snapshot to check\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns True if the snapshot has expired, false otherwise\n */\nexport function isSnapshotExpired<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): boolean {\n return snapshot.expiresAt !== undefined && now > snapshot.expiresAt;\n}\n\n/**\n * Validate a distributable snapshot and return its data.\n * Throws if the snapshot is malformed or has expired.\n *\n * @example\n * ```typescript\n * const cached = JSON.parse(await redis.get(`entitlements:${userId}`));\n * try {\n * const data = validateSnapshot(cached);\n * // Use data.canUseFeature, etc.\n * } catch (e) {\n * // Snapshot invalid or expired, refresh it\n * }\n * ```\n *\n * @example Using custom timestamp for testing\n * ```typescript\n * const snapshot = { data: { test: true }, createdAt: 1000, expiresAt: 2000 };\n * validateSnapshot(snapshot, 1500); // Returns { test: true }\n * validateSnapshot(snapshot, 2500); // Throws: Snapshot expired\n * ```\n *\n * @param snapshot - The snapshot to validate\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns The snapshot data if valid\n * @throws Error if the snapshot is malformed or has expired\n */\nexport function validateSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): T {\n // Structural validation\n if (!snapshot || typeof snapshot !== \"object\") {\n throw new Error(\n \"[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.\",\n );\n }\n if (!(\"data\" in snapshot)) {\n throw new Error(\n \"[Directive] Invalid snapshot: missing required 'data' property.\",\n );\n }\n if (!(\"createdAt\" in snapshot) || typeof snapshot.createdAt !== \"number\") {\n throw new Error(\n \"[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).\",\n );\n }\n\n // Expiration validation\n if (isSnapshotExpired(snapshot, now)) {\n const expiredAt = new Date(snapshot.expiresAt!).toISOString();\n throw new Error(\n `[Directive] Snapshot expired at ${expiredAt}. Obtain a fresh snapshot from the source.`,\n );\n }\n return snapshot.data;\n}\n\n/**\n * Diff result for a single changed value.\n */\nexport interface SnapshotDiffEntry {\n /** The key path that changed (e.g., \"canUseApi\" or \"limits.apiCalls\") */\n path: string;\n /** The value in the old snapshot */\n oldValue: unknown;\n /** The value in the new snapshot */\n newValue: unknown;\n /** Type of change: \"added\", \"removed\", or \"changed\" */\n type: \"added\" | \"removed\" | \"changed\";\n}\n\n/**\n * Result of diffing two snapshots.\n */\nexport interface SnapshotDiff {\n /** Whether the snapshots are identical */\n identical: boolean;\n /** List of changes between snapshots */\n changes: SnapshotDiffEntry[];\n /** Whether the version changed (if both have versions) */\n versionChanged: boolean;\n /** Old version (if available) */\n oldVersion?: string;\n /** New version (if available) */\n newVersion?: string;\n}\n\n/**\n * Compare two distributable snapshots and return the differences.\n * Useful for debugging, audit logs, and webhook payloads.\n *\n * @example\n * ```typescript\n * const oldSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n * system.dispatch({ type: \"upgradePlan\", plan: \"pro\" });\n * const newSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n *\n * const diff = diffSnapshots(oldSnapshot, newSnapshot);\n * if (!diff.identical) {\n * console.log(\"Changes:\", diff.changes);\n * // [{ path: \"canUseApi\", oldValue: false, newValue: true, type: \"changed\" }]\n * }\n * ```\n *\n * @param oldSnapshot - The previous snapshot\n * @param newSnapshot - The new snapshot\n * @returns A diff result with all changes\n */\nexport function diffSnapshots<T = Record<string, unknown>>(\n oldSnapshot: DistributableSnapshotLike<T>,\n newSnapshot: DistributableSnapshotLike<T>,\n): SnapshotDiff {\n const changes: SnapshotDiffEntry[] = [];\n\n /** Push a change entry to the diff results. */\n function pushChange(\n path: string,\n oldValue: unknown,\n newValue: unknown,\n type: SnapshotDiffEntry[\"type\"],\n ): void {\n changes.push({ path, oldValue, newValue, type });\n }\n\n /** Handle null/undefined comparison cases. Returns true if fully handled. */\n function compareNullish(\n oldObj: unknown,\n newObj: unknown,\n path: string,\n ): boolean {\n if (oldObj === null || oldObj === undefined) {\n if (newObj !== null && newObj !== undefined) {\n pushChange(path, oldObj, newObj, \"added\");\n }\n\n return true;\n }\n if (newObj === null || newObj === undefined) {\n pushChange(path, oldObj, newObj, \"removed\");\n\n return true;\n }\n\n return false;\n }\n\n /** Compare two arrays element by element, recursing into each. */\n function compareArrays(\n oldArr: unknown[],\n newArr: unknown[],\n path: string,\n ): void {\n if (oldArr.length !== newArr.length) {\n pushChange(path, oldArr, newArr, \"changed\");\n\n return;\n }\n for (let i = 0; i < oldArr.length; i++) {\n compare(oldArr[i], newArr[i], `${path}[${i}]`);\n }\n }\n\n /** Compare two objects by key union, detecting added/removed/changed. */\n function compareObjects(\n oldRecord: Record<string, unknown>,\n newRecord: Record<string, unknown>,\n path: string,\n ): void {\n const allKeys = new Set([\n ...Object.keys(oldRecord),\n ...Object.keys(newRecord),\n ]);\n\n for (const key of allKeys) {\n const childPath = path ? `${path}.${key}` : key;\n if (!(key in oldRecord)) {\n pushChange(childPath, undefined, newRecord[key], \"added\");\n } else if (!(key in newRecord)) {\n pushChange(childPath, oldRecord[key], undefined, \"removed\");\n } else {\n compare(oldRecord[key], newRecord[key], childPath);\n }\n }\n }\n\n /** Recursively compare two values and record differences. */\n function compare(oldObj: unknown, newObj: unknown, path: string): void {\n if (compareNullish(oldObj, newObj, path)) {\n return;\n }\n\n // Handle primitives\n if (typeof oldObj !== \"object\" || typeof newObj !== \"object\") {\n if (!Object.is(oldObj, newObj)) {\n pushChange(path, oldObj, newObj, \"changed\");\n }\n\n return;\n }\n\n // Handle arrays\n if (Array.isArray(oldObj) && Array.isArray(newObj)) {\n compareArrays(oldObj, newObj, path);\n\n return;\n }\n\n // Handle objects\n compareObjects(\n oldObj as Record<string, unknown>,\n newObj as Record<string, unknown>,\n path,\n );\n }\n\n // Compare data\n compare(oldSnapshot.data, newSnapshot.data, \"\");\n\n // Check version change\n const versionChanged =\n oldSnapshot.version !== newSnapshot.version &&\n (oldSnapshot.version !== undefined || newSnapshot.version !== undefined);\n\n return {\n identical: changes.length === 0,\n changes,\n versionChanged,\n oldVersion: oldSnapshot.version,\n newVersion: newSnapshot.version,\n };\n}\n\n// ============================================================================\n// Snapshot Signing (HMAC)\n// ============================================================================\n\n/**\n * A signed distributable snapshot.\n * Contains the original snapshot plus a cryptographic signature.\n */\nexport interface SignedSnapshot<T = Record<string, unknown>>\n extends DistributableSnapshotLike<T> {\n /** HMAC-SHA256 signature in hex format */\n signature: string;\n /** Signing algorithm used */\n algorithm: \"hmac-sha256\";\n}\n\n/**\n * Check if a snapshot is signed.\n *\n * @param snapshot - The snapshot to check\n * @returns True if the snapshot has a signature\n */\nexport function isSignedSnapshot<T>(\n snapshot: DistributableSnapshotLike<T> | SignedSnapshot<T>,\n): snapshot is SignedSnapshot<T> {\n return \"signature\" in snapshot && typeof snapshot.signature === \"string\";\n}\n\n/**\n * Sign a distributable snapshot using HMAC-SHA256.\n * Creates a tamper-proof signature that can be verified later.\n *\n * **Security Notes:**\n * - Use a cryptographically random secret of at least 32 bytes\n * - Store the secret securely (environment variable, secrets manager)\n * - Never expose the secret to clients\n * - The signature covers all snapshot fields for integrity\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['canUseFeature', 'limits'],\n * ttlSeconds: 3600,\n * });\n *\n * // Sign the snapshot (server-side only)\n * const signed = await signSnapshot(snapshot, process.env.SNAPSHOT_SECRET);\n *\n * // Store in JWT, Redis, or send to client\n * const jwt = createJWT({ snapshot: signed });\n *\n * // Later, verify the signature\n * const isValid = await verifySnapshotSignature(signed, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Snapshot has been tampered with');\n * }\n * ```\n *\n * @param snapshot - The snapshot to sign\n * @param secret - The HMAC secret (string or Uint8Array)\n * @returns A signed snapshot with the signature attached\n */\nexport async function signSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n secret: string | Uint8Array,\n): Promise<SignedSnapshot<T>> {\n // Create a canonical representation for signing\n const payload = stableStringify({\n data: snapshot.data,\n createdAt: snapshot.createdAt,\n expiresAt: snapshot.expiresAt,\n version: snapshot.version,\n metadata: snapshot.metadata,\n });\n\n const signature = await hmacSha256(payload, secret);\n\n return {\n ...snapshot,\n signature,\n algorithm: \"hmac-sha256\",\n };\n}\n\n/**\n * Verify the signature of a signed snapshot.\n * Returns true if the signature is valid, false otherwise.\n *\n * **Important:** Always verify signatures before trusting snapshot data,\n * especially if the snapshot was received from an untrusted source (client, cache).\n *\n * The default verification enforces `expiresAt` — a captured-and-replayed\n * snapshot stops verifying once its `expiresAt` is in the past. Callers\n * that legitimately need signature-only validation (testing infrastructure,\n * archival validation) can pass `{ ignoreExpiry: true }`.\n *\n * @example\n * ```typescript\n * // Receive signed snapshot from client or cache\n * const snapshot = JSON.parse(cachedData);\n *\n * // Verify before using. `verifySnapshotSignature` returns false for an\n * // expired snapshot even when the HMAC is valid; treat it as the\n * // single attestation gate.\n * const isValid = await verifySnapshotSignature(snapshot, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Invalid or expired snapshot');\n * }\n *\n * // Now safe to use snapshot.data\n * processSnapshotData(snapshot.data);\n * ```\n *\n * @param signedSnapshot - The signed snapshot to verify\n * @param secret - The HMAC secret (must match the signing secret)\n * @param options - Optional flags:\n * - `ignoreExpiry`: skip the `expiresAt` check (signature-only mode)\n * - `now`: override the current time used for expiry comparison\n * (test helper)\n * @returns True if signature is valid AND (unless `ignoreExpiry`) not\n * expired; false otherwise\n */\nexport async function verifySnapshotSignature<T>(\n signedSnapshot: SignedSnapshot<T>,\n secret: string | Uint8Array,\n options?: { ignoreExpiry?: boolean; now?: number },\n): Promise<boolean> {\n if (!signedSnapshot.signature || signedSnapshot.algorithm !== \"hmac-sha256\") {\n return false;\n }\n\n // Recreate the canonical payload (same as signing)\n const payload = stableStringify({\n data: signedSnapshot.data,\n createdAt: signedSnapshot.createdAt,\n expiresAt: signedSnapshot.expiresAt,\n version: signedSnapshot.version,\n metadata: signedSnapshot.metadata,\n });\n\n const expectedSignature = await hmacSha256(payload, secret);\n\n // Use timing-safe comparison\n if (!timingSafeEqual(signedSnapshot.signature, expectedSignature)) {\n return false;\n }\n\n // Enforce expiresAt unless the caller explicitly opted out. Without\n // this check, a captured-and-replayed valid signature is accepted\n // forever — the canonical replay-attack chain. Treating the signature\n // as a full attestation gate requires checking the attestation window.\n if (\n !options?.ignoreExpiry &&\n isSnapshotExpired(signedSnapshot, options?.now)\n ) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Create HMAC-SHA256 signature of a message.\n * Uses Web Crypto API for cross-platform support (Node.js, browsers, Deno, Bun).\n */\nasync function hmacSha256(\n message: string,\n secret: string | Uint8Array,\n): Promise<string> {\n // Convert secret to Uint8Array if string\n const secretBytes: Uint8Array =\n typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\n // Import key for HMAC\n const algorithm: HmacImportParams = {\n name: \"HMAC\",\n hash: { name: \"SHA-256\" },\n };\n const key = await crypto.subtle.importKey(\n \"raw\",\n secretBytes as unknown as ArrayBuffer,\n algorithm,\n false,\n [\"sign\"],\n );\n\n // Sign the message\n const messageBytes = new TextEncoder().encode(message);\n const signature = await crypto.subtle.sign(\"HMAC\", key, messageBytes);\n\n // Convert to hex string\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Timing-safe string comparison to prevent timing attacks.\n * Both strings should be the same length (hex signatures from same algorithm).\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return result === 0;\n}\n\n/**\n * Safely stringify any value for display. Handles circular references,\n * BigInt, throwing toJSON, and optional truncation.\n *\n * This is the canonical implementation – all packages should import this\n * instead of maintaining local copies.\n */\nexport function safeStringify(data: unknown, maxLen = 500): string {\n try {\n const str = JSON.stringify(\n data,\n (_key, value) => {\n if (typeof value === \"bigint\") {\n return `${value}n`;\n }\n\n return value;\n },\n 2,\n );\n if (!str) {\n return \"[undefined]\";\n }\n if (str.length <= maxLen) {\n return str;\n }\n\n return `${str.slice(0, maxLen)}\\n... (truncated, ${str.length} chars total)`;\n } catch {\n return \"[unserializable]\";\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {a,f as f$1}from'./chunk-IZNOPHPL.js';var g=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),Q=new Set(["$all","$any","$not"]);var T=new Set(["number","string","boolean","bigint","date","unknown"]);function P(e){if(!e)return {kind:"unknown"};let n=/^Branded<(.+)>$/.exec(e);return n?{kind:"branded",inner:P(n[1])}:e.endsWith(" | null")||e.endsWith(" | undefined")?{...P(e.replace(/ \| (null|undefined)$/,"")),nullable:true}:T.has(e)?{kind:e}:/^(email|uuid|url|cuid|datetime|iso\b)/i.test(e)?{kind:"string"}:e.includes(" | ")?{kind:"union",members:e.split(" | ").map(P)}:e==="array"?{kind:"array",element:{kind:"unknown"}}:e==="object"?{kind:"object",shape:{}}:e==="record"?{kind:"record",value:{kind:"unknown"}}:e==="tuple"?{kind:"tuple",elements:[]}:e==="union"?{kind:"union",members:[]}:{kind:"unknown"}}function z(e){if(e==null)return {kind:"unknown"};if(typeof e=="function")return a&&console.warn("[Directive] getKind: received a function \u2014 did you forget () on a t.* builder? Example: write `t.number()`, not `t.number`."),{kind:"unknown"};if(typeof e!="object")return {kind:"unknown"};let n=e,r;try{r=n._kind;}catch{return {kind:"unknown"}}if(r)return r;let i;try{i=n._typeName;}catch{return {kind:"unknown"}}return P(i)}function H(e){let n=new Map;if(!e||typeof e!="object")return n;let r=e,t="facts"in r&&r.facts&&typeof r.facts=="object"?r.facts:r;for(let[a,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let o;try{o=z(s);}catch{continue}if(n.set(a,o),o.kind==="object")for(let[c,l]of Object.entries(o.shape))n.set(`${a}.${c}`,l);}return n.size===0&&a&&console.warn("[Directive] getSchemaFieldKinds: schema appears empty (no introspectable keys). Did you pass the module instead of its schema? Pass `myModule.schema`, not `myModule`."),n}var k=["$eq","$ne","$in","$nin","$exists"],D=["$gt","$gte","$lt","$lte","$between"],W=["$matches","$startsWith","$endsWith","$contains"];function w(e){switch(e.kind){case "number":case "bigint":case "date":return [...k,...D];case "string":return [...k,...D,...W];case "boolean":case "unknown":return k;case "array":return [...k,"$contains"];case "object":case "record":case "tuple":return k;case "literal":case "enum":return w(e.primitive==="number"?{kind:"number"}:e.primitive==="boolean"?{kind:"boolean"}:e.primitive==="null"?{kind:"unknown"}:{kind:"string"});case "branded":return w(e.inner);case "union":{if(e.members.length===0)return k;let n=e.members.map(t=>new Set(w(t))),r=n[0],i=[];for(let t of r)n.every(a=>a.has(t))&&i.push(t);return i}default:{return k}}}function X(){return Array.from(g)}var O=64;function u(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function x(e){if(typeof e!="object"||e===null||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function E(e){if(!u(e))return false;let n=0,r=false;for(let i of Object.keys(e)){if(i.startsWith("$"))r=true,g.has(i)||f(`predicate: unknown operator "${i}" \u2014 looks like a typo. Known operators: ${[...g].join(", ")}`);else if(r||n===0)return false;n++;}return r?n>0:false}function re(e){return e===null?false:Array.isArray(e)?e.every(n=>x(n)&&"fact"in n&&"op"in n):x(e)}function h(e,n,r="",i=new WeakSet,t=0){if(t>O){a&&console.warn(`[Directive] predicate depth limit (${O}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),n.bail?.("depth");return}if(Array.isArray(e)){e.forEach((s,o)=>{if(!u(s))return;let c=s;if(typeof c.fact=="string"&&typeof c.op=="string"){let l=r?`${r}[${o}]`:`[${o}]`;n.operator?.(r?`${r}.${c.fact}`:c.fact,c.op,c.value,`${l}.value`);}});return}if(!u(e))return;if(i.has(e)){a&&console.warn("[Directive] walkPredicate: cyclic predicate spec"),n.bail?.("cycle");return}i.add(e);let a$1=e;for(let s of ["$all","$any","$not"])if(s in a$1){if(n.combinator?.(s)===false)return;let c=s==="$not"?[a$1.$not]:a$1[s]??[];for(let l of c)h(l,n,r,i,t+1);return}for(let s of Object.keys(a$1)){let o=r?`${r}.${s}`:s;if(s.startsWith("$")){n.strayOperatorKey?.(s,o);continue}let c=a$1[s];if(E(c)){let l=c;for(let p of Object.keys(l))n.operator?.(o,p,l[p],`${o}.${p}`);continue}if(x(c)){if(n.nested?.(s)===false)continue;h(c,n,o,i,t+1);continue}n.literal?.(o,c);}}function ie(e){if(!x(e))return false;let n=false;return h(e,{operator(){n=true;},literal(){n=true;},combinator(){n=true;},strayOperatorKey(){n=true;},bail(){n=true;}}),!n}function I(e){return u(e)&&Object.hasOwn(e,"$template")&&typeof e.$template=="string"}function oe(e,n=""){function r(t,a,s,o){if(typeof t=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${a}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(t instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${a}" is not JSON-serializable (serializes to {} and loses all members).`);if(t instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${a}" is not JSON-serializable (serializes to {} and loses all entries).`);if(t instanceof RegExp)throw new Error(`[Directive] validatePredicate: RegExp operand at "${a}" is not JSON-serializable (a regex lost to JSON.parse becomes {}). Only a direct $matches operand may be a RegExp.`);if(!(t===null||typeof t!="object")&&!(o>O)&&!s.has(t)){if(s.add(t),Array.isArray(t)){t.forEach((c,l)=>{r(c,`${a}[${l}]`,s,o+1);});return}for(let c of Object.keys(t))r(t[c],a?`${a}.${c}`:c,s,o+1);}}function i(t,a,s){if(typeof t=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${s}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(t instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${s}" is not JSON-serializable (serializes to {} and loses all members).`);if(t instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${s}" is not JSON-serializable (serializes to {} and loses all entries).`);if(a==="$matches"&&!(t instanceof RegExp))throw new Error(`[Directive] validatePredicate: $matches operand at "${s}" must be a RegExp; got ${t===null?"null":typeof t}. A regex lost to JSON.parse becomes {} \u2014 reify with new RegExp(pattern, flags) before installing.`);if(Array.isArray(t))t.forEach((o,c)=>{r(o,`${s}[${c}]`,new WeakSet,1);});else if(x(t))for(let o of Object.keys(t))r(t[o],`${s}.${o}`,new WeakSet,1);}if(e instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand${n?` at "${n}"`:""} is not JSON-serializable (serializes to {} and loses all members).`);if(e instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand${n?` at "${n}"`:""} is not JSON-serializable (serializes to {} and loses all entries).`);h(e,{operator(t,a,s,o){i(s,a,n?`${n}.${o}`:o);},literal(t,a){i(a,"",n?`${n}.${t}`:t);}});}function M(e){return typeof e!="string"||e.length===0?false:!!(/\)(?:[+*]\??|\{\d+,?\d*\})\s*[+*?]\s*[+*]/.test(e)||/\(([^()]*?[+*]|[^()]*?\{\d+,?\d*\})[^()]*\)\s*[+*]/.test(e)||/\(\??:?([^()|]+)\|\1\)\s*[+*]/.test(e))}function se(e,n,r={}){let i=[],t=0,a=r.maxOperatorCount,s=r.maxArrayOperandLength;return h(e,{operator(o,c,l,p){if(t++,a!==void 0&&t>a){i.some($=>$.reason.includes("maxOperatorCount"))||i.push({path:o,op:c,reason:`Predicate exceeds maxOperatorCount=${a} \u2014 too many clauses (DoS guard).`});return}if(s!==void 0&&(c==="$in"||c==="$nin")&&Array.isArray(l)&&l.length>s){i.push({path:o,op:c,reason:`Operator ${c} operand exceeds maxArrayOperandLength=${s} (got ${l.length}) \u2014 too large for a query planner.`});return}if(c==="$matches"){let $;if(l instanceof RegExp?$=l.source:typeof l=="string"&&($=l),$!==void 0&&M($)){i.push({path:o,op:c,reason:`Operator $matches operand at "${o}" contains nested quantifiers (ReDoS risk: ${JSON.stringify($)}). Reject untrusted regex or rewrite without nested + / *.`});return}}let m=n.get(o);if(!m){i.push({path:o,op:c,reason:`Unknown fact "${o}" \u2014 not in schema. Known facts: ${n.size===0?"(empty schema)":Array.from(n.keys()).join(", ")}`});return}let y=w(m);y.includes(c)||i.push({path:o,op:c,kind:m,allowedOps:y,reason:`Operator "${c}" is not allowed on fact "${o}" of kind "${m.kind}". Allowed operators for this kind: ${y.join(", ")}.`});},literal(o,c){t++,n.has(o)||i.push({path:o,op:"$eq",reason:`Unknown fact "${o}" \u2014 not in schema.`});},strayOperatorKey(o,c){i.push({path:c,op:o,reason:`Stray operator key "${o}" at "${c}" \u2014 operators must live inside a fact's operator object, not at the predicate top level.`});}}),i.length===0?{ok:true,operatorCount:t}:{ok:false,errors:i,operatorCount:t}}function _(){return {ids:new WeakMap,next:{v:1},pairs:new Set}}function v(e,n){let r=e.ids.get(n);return r===void 0&&(r=e.next.v++,e.ids.set(n,r)),r}function d(e,n,r){if(Object.is(e,n))return true;if(e instanceof Date&&n instanceof Date)return e.getTime()===n.getTime();if(typeof e!="object"||typeof n!="object"||e===null||n===null)return false;let i=r??_(),t=`${v(i,e)}:${v(i,n)}`;if(i.pairs.has(t))return true;if(i.pairs.add(t),Array.isArray(e)||Array.isArray(n))return !Array.isArray(e)||!Array.isArray(n)||e.length!==n.length?false:e.every((o,c)=>d(o,n[c],i));if(e instanceof Set||n instanceof Set){if(!(e instanceof Set)||!(n instanceof Set)||e.size!==n.size)return false;let o=[...n];return [...e].every(c=>o.some(l=>d(c,l,i)))}if(e instanceof Map||n instanceof Map){if(!(e instanceof Map)||!(n instanceof Map)||e.size!==n.size)return false;let o=[...n.entries()],c=new Array(o.length).fill(false);for(let[l,p]of e){let m=false;for(let y=0;y<o.length;y++){if(c[y])continue;let[$,N]=o[y];if(d(l,$,i)&&d(p,N,i)){c[y]=true,m=true;break}}if(!m)return false}return true}let a=Object.keys(e),s=Object.keys(n);return a.length!==s.length?false:a.every(o=>Object.hasOwn(n,o)&&d(e[o],n[o],i))}function j(e){if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e=="bigint"||typeof e=="string")return e}function A(e,n,r){let i=j(n),t=j(r);if(i===void 0||t===void 0||typeof i!=typeof t)return false;switch(e){case "$gt":return i>t;case "$gte":return i>=t;case "$lt":return i<t;case "$lte":return i<=t;default:return false}}function R(e,n,r,i){switch(e){case "$eq":return d(n,r);case "$ne":return !d(n,r);case "$in":return Array.isArray(r)&&r.some(t=>d(n,t));case "$nin":return Array.isArray(r)&&!r.some(t=>d(n,t));case "$exists":return r===(n!==void 0);case "$changed":return !d(n,i);case "$gt":case "$gte":case "$lt":case "$lte":return A(e,n,r);case "$between":{if(!Array.isArray(r)||r.length!==2)return false;let t=j(r[0]),a=j(r[1]);return t!==void 0&&a!==void 0&&typeof t==typeof a&&t>a?(f("$between: reversed pair \u2014 [min, max] required"),false):A("$gte",n,r[0])&&A("$lte",n,r[1])}case "$matches":{if(!(r instanceof RegExp))throw new Error("[Directive] $matches: operand must be a RegExp (string operands are no longer accepted; pass /pattern/flags directly).");return typeof n!="string"?false:r.test(n)}case "$startsWith":return typeof n!="string"?false:n.startsWith(String(r));case "$endsWith":return typeof n!="string"?false:n.endsWith(String(r));case "$contains":return typeof n=="string"?n.includes(String(r)):Array.isArray(n)?n.some(t=>d(t,r)):n instanceof Set?n.has(r):false;default:return false}}function f(e){a&&console.warn(`[Directive] ${e}`);}function q(e,n,r,i){if(E(e)){let t=Object.keys(e);t.length>1&&f(`predicate: operator object has ${t.length} operators (${t.join(", ")}) \u2014 write the array form or $all instead. The runtime ANDs them as a best-effort fallback.`);for(let a of t)if(!R(a,n,e[a],r))return false;return true}return u(e)?S(e,u(n)?n:Object.create(null),u(r)?r:void 0,i+1):d(n,e)}function S(e,n,r,i=0){if(i>O)return f(`predicate depth limit (${O}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),false;if(Array.isArray(e))return e.every(t=>{if(!u(t))return false;let{fact:a,op:s,value:o}=t;return R(s,n?.[a],o,r?.[a])});if(!u(e))return !!e;if("$all"in e)return e.$all.every(t=>S(t,n,r,i+1));if("$any"in e)return e.$any.some(t=>S(t,n,r,i+1));if("$not"in e)return !S(e.$not,n,r,i+1);for(let t of Object.keys(e)){if(g.has(t))return f(`predicate: operator "${t}" mixed with fact keys \u2014 wrap operators in a per-fact object`),false;if(!q(e[t],n?.[t],r?.[t],i))return false}return true}function V(e,n,r,i=""){let t=[];if(Array.isArray(e)){for(let a of e){if(!u(a))continue;let{fact:s,op:o,value:c}=a,l=n?.[s];t.push({path:i+s,op:o,expected:c,actual:l,pass:R(o,l,c,r?.[s])});}return t}if(!u(e))return t;for(let a of ["$all","$any","$not"])if(a in e){let s=a==="$not"?[e.$not]:e[a],o=[];for(let p of s)o.push(...V(p,n,r,i));let c=o.filter(p=>p.pass).length,l;return a==="$all"?l=o.length===0||c===o.length:a==="$any"?l=o.length>0&&c>0:l=!o.every(p=>p.pass),t.push({path:i||a,op:a,expected:s.length,actual:c,pass:l,children:o}),t}for(let a of Object.keys(e)){if(g.has(a))continue;let s=e[a],o=n?.[a],c=i+a;if(E(s))for(let l of Object.keys(s))t.push({path:c,op:l,expected:s[l],actual:o,pass:R(l,o,s[l],r?.[a])});else u(s)?t.push(...V(s,u(o)?o:Object.create(null),u(r?.[a])?r?.[a]:void 0,`${c}.`)):t.push({path:c,op:"$eq",expected:s,actual:o,pass:d(o,s)});}return t}var F=new WeakMap;function ce(e){if(e===null||typeof e!="object")throw new Error(`[Directive] memoizePredicate: predicate must be a plain object or array; got ${typeof e}`);let n=F.get(e);if(n)return n;let r=(i,t)=>S(e,i,t);return F.set(e,r),r}function le(e,n=""){let r=new Set;return h(e,{operator(i){r.add(n+i);},literal(i){r.add(n+i);},strayOperatorKey(i){g.has(i)||f(`extractDeps: unknown operator "${i}" \u2014 skipping. Known operators: ${[...g].join(", ")}`);}}),r}var C=/^[A-Za-z_][A-Za-z0-9_]*$/;function J(e){return typeof e=="symbol"||e==null?"":String(e)}function B(e,n){return typeof e=="symbol"?(f("template: cannot interpolate a symbol value \u2014 using empty string"),""):e===void 0?(f(`template: ${n?`key "${n}" is `:""}undefined \u2014 using empty string`),""):e===null?(f(`template: ${n?`key "${n}" is `:""}null \u2014 using empty string`),""):String(e)}function L(e,n){let r=e.$template,i="",t=0;for(;t<r.length;){if(r[t]==="$"&&r[t+1]==="$"&&r[t+2]==="{"){i+="${",t+=3;continue}if(r[t]==="$"&&r[t+1]==="{"){let a=r.indexOf("}",t+2);if(a===-1){f(`template: unterminated "\${" in ${JSON.stringify(r)}`),i+=r.slice(t);break}let s=r.slice(t+2,a);if(!C.test(s))f(`template: invalid placeholder "\${${s}}" \u2014 not an identifier`);else {let o=n!=null&&Object.hasOwn(n,s),c=o?n[s]:void 0;o?i+=B(c,s):(f(`template: unknown key "${s}"`),i+=J(c));}t=a+1;continue}i+=r[t],t++;}return i}function ue(e){let n=new Set,r=e.$template,i=0;for(;i<r.length;){if(r[i]==="$"&&r[i+1]==="$"&&r[i+2]==="{"){i+=3;continue}if(r[i]==="$"&&r[i+1]==="{"){let t=r.indexOf("}",i+2);if(t===-1)break;let a=r.slice(i+2,t);C.test(a)&&n.add(a),i=t+1;continue}i++;}return n}function de(e,n){return e.map(r=>f$1(n?.[r])).join("|")}function fe(e,n,r){let i=e.$set,t=r??{};for(let a of Object.keys(i)){let s=i[a];if(I(s))n[a]=L(s,t);else if(u(s)&&Object.hasOwn(s,"$ref")&&typeof s.$ref=="string"){let o=s.$ref;Object.hasOwn(t,o)||f(`applyPatch: $ref "${o}" is missing from event payload \u2014 assigning undefined to fact "${a}"`),n[a]=t[o];}else n[a]=s;}}export{g as a,Q as b,z as c,H as d,w as e,X as f,O as g,re as h,h as i,ie as j,I as k,oe as l,M as m,se as n,S as o,V as p,ce as q,le as r,L as s,ue as t,de as u,fe as v};//# sourceMappingURL=chunk-LN5H74CU.js.map
2
+ //# sourceMappingURL=chunk-LN5H74CU.js.map