@directive-run/core 1.4.0 → 1.5.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.
Files changed (71) 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-FK7BD7XT.js → chunk-EH2Q754B.js} +3 -3
  6. package/dist/chunk-EH2Q754B.js.map +1 -0
  7. package/dist/chunk-HAF5JCET.js +16 -0
  8. package/dist/chunk-HAF5JCET.js.map +1 -0
  9. package/dist/{chunk-4CMO5OVZ.js → chunk-M5KZXNZX.js} +2 -2
  10. package/dist/chunk-M5KZXNZX.js.map +1 -0
  11. package/dist/chunk-PGUTGWUI.cjs +3 -0
  12. package/dist/chunk-PGUTGWUI.cjs.map +1 -0
  13. package/dist/{chunk-DDUARSUH.cjs → chunk-S3CFYDIB.cjs} +3 -3
  14. package/dist/chunk-S3CFYDIB.cjs.map +1 -0
  15. package/dist/chunk-SQVKCJHE.cjs +16 -0
  16. package/dist/chunk-SQVKCJHE.cjs.map +1 -0
  17. package/dist/chunk-YCCQ73C6.js +3 -0
  18. package/dist/chunk-YCCQ73C6.js.map +1 -0
  19. package/dist/{chunk-BEJ6ICA7.cjs → chunk-ZHS3EW2Z.cjs} +2 -2
  20. package/dist/chunk-ZHS3EW2Z.cjs.map +1 -0
  21. package/dist/{helpers-D6LcRum7.d.ts → helpers-B1MiHave.d.cts} +12 -2
  22. package/dist/{helpers-BUY1lYCX.d.cts → helpers-h9PR2JSJ.d.ts} +12 -2
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +183 -5
  26. package/dist/index.d.ts +183 -5
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/internals.cjs +1 -1
  30. package/dist/internals.d.cts +49 -39
  31. package/dist/internals.d.ts +49 -39
  32. package/dist/internals.js +1 -1
  33. package/dist/plugins/index.cjs +1 -1
  34. package/dist/plugins/index.cjs.map +1 -1
  35. package/dist/plugins/index.d.cts +11 -8
  36. package/dist/plugins/index.d.ts +11 -8
  37. package/dist/plugins/index.js +1 -1
  38. package/dist/plugins/index.js.map +1 -1
  39. package/dist/{plugins-Dy1C8GtT.d.cts → plugins-Bakr7js6.d.cts} +369 -69
  40. package/dist/{plugins-Dy1C8GtT.d.ts → plugins-Bakr7js6.d.ts} +369 -69
  41. package/dist/system-744ZPPES.js +2 -0
  42. package/dist/{system-JIO36ALC.js.map → system-744ZPPES.js.map} +1 -1
  43. package/dist/system-CK3SHMXZ.cjs +2 -0
  44. package/dist/{system-2THXJBFM.cjs.map → system-CK3SHMXZ.cjs.map} +1 -1
  45. package/dist/testing.cjs +1 -1
  46. package/dist/testing.cjs.map +1 -1
  47. package/dist/testing.d.cts +1 -1
  48. package/dist/testing.d.ts +1 -1
  49. package/dist/testing.js +1 -1
  50. package/dist/testing.js.map +1 -1
  51. package/dist/worker.cjs +1 -1
  52. package/dist/worker.cjs.map +1 -1
  53. package/dist/worker.d.cts +1 -1
  54. package/dist/worker.d.ts +1 -1
  55. package/dist/worker.js +1 -1
  56. package/dist/worker.js.map +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunk-4CMO5OVZ.js.map +0 -1
  59. package/dist/chunk-BEJ6ICA7.cjs.map +0 -1
  60. package/dist/chunk-DDUARSUH.cjs.map +0 -1
  61. package/dist/chunk-E2WETPLH.js +0 -3
  62. package/dist/chunk-E2WETPLH.js.map +0 -1
  63. package/dist/chunk-FK7BD7XT.js.map +0 -1
  64. package/dist/chunk-LFMRWCIG.js +0 -16
  65. package/dist/chunk-LFMRWCIG.js.map +0 -1
  66. package/dist/chunk-TUS5WDVE.cjs +0 -3
  67. package/dist/chunk-TUS5WDVE.cjs.map +0 -1
  68. package/dist/chunk-VSHSYVSY.cjs +0 -16
  69. package/dist/chunk-VSHSYVSY.cjs.map +0 -1
  70. package/dist/system-2THXJBFM.cjs +0 -2
  71. package/dist/system-JIO36ALC.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/types/adapter-utils.ts","../src/dev-true.ts","../src/core/tracking.ts"],"names":["setBridgeFact","facts","key","value","getBridgeFact","createCallbackPlugin","name","callbacks","req","requirementGuard","type","requirementGuardMultiple","types","typeSet","dev_true_default","depStack","getCurrentDeps","len","isTracking","withTracking","fn","deps","withoutTracking","saved","ctx","trackAccess","BLOCKED_PROPS","detectNonJsonValueType","proto","nonJsonWarningCache","nonJsonHints","warnNonJsonFactAssignment","factPath","valueType","cacheKey","hint"],"mappings":"AA8FO,SAASA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACM,CACLF,CAAAA,CAAkCC,CAAG,CAAA,CAAIC,EAC5C,CAWO,SAASC,CAAAA,CAAiBH,CAAAA,CAAsBC,CAAAA,CAAgB,CACrE,OAAQD,CAAAA,CAAkCC,CAAG,CAC/C,CAyJO,SAASG,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACa,CACb,OAAO,CACL,IAAA,CAAAD,CAAAA,CACA,qBAAsBC,CAAAA,CAAU,oBAAA,CAC3BC,CAAAA,EAAQD,CAAAA,CAAU,qBAAsBC,CAAAA,CAAI,WAAW,CAAA,CACxD,MAAA,CACJ,gBAAA,CAAkBD,CAAAA,CAAU,qBAAA,CACvBC,CAAAA,EAAQD,EAAU,qBAAA,CAAuBC,CAAAA,CAAI,WAAW,CAAA,CACzD,OACJ,OAAA,CAASD,CAAAA,CAAU,OACrB,CACF,CAyCO,SAASE,CAAAA,CACdC,CAAAA,CACgC,CAChC,OAAQF,CAAAA,EAAkBA,CAAAA,CAAI,IAAA,GAASE,CACzC,CAUO,SAASC,CAAAA,CACdC,CAAAA,CACgC,CAChC,IAAMC,CAAAA,CAAU,IAAI,GAAA,CAAID,CAAK,EAC7B,OAAQJ,CAAAA,EAAkBK,CAAAA,CAAQ,GAAA,CAA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AO,IAAA,CAET,GAAIA,aAAiB,IAAA,CACnB,OAAO,MAAA,CAET,GAAIA,aAAiB,GAAA,CACnB,OAAO,KAAA,CAET,GAAIA,aAAiB,GAAA,CACnB,OAAO,KAAA,CAET,GAAI,OAAO,IAAA,CAAS,GAAA,EAAeA,CAAAA,YAAiB,IAAA,CAClD,OAAO,MAAA,CAGT,GAAI,KAAA,CAAM,QAAQA,CAAK,CAAA,CACrB,OAAO,IAAA,CAMT,IAAMyB,CAAAA,CAAQ,MAAA,CAAO,cAAA,CAAezB,CAAK,EACzC,OAAIyB,CAAAA,GAAU,IAAA,EAAQA,CAAAA,GAAU,OAAO,SAAA,CAC9B,eAAA,CAGF,IACT,CASA,IAAMC,CAAAA,CAAsB,IAAI,GAAA,CAE1BC,CAAAA,CAAuC,CAC3C,IAAA,CAAM,2BAAA,CACN,GAAA,CAAK,qBAAA,CACL,IAAK,2CAAA,CACL,IAAA,CAAM,iDAAA,CACN,aAAA,CAAe,yBACjB,CAAA,CAeO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACM,CACN,IAAMC,CAAAA,CAAW,GAAGF,CAAQ,CAAA,CAAA,EAAIC,CAAS,CAAA,CAAA,CACzC,GAAIJ,CAAAA,CAAoB,GAAA,CAAIK,CAAQ,CAAA,CAClC,OAEFL,CAAAA,CAAoB,GAAA,CAAIK,CAAQ,CAAA,CAEhC,IAAMC,CAAAA,CAAOL,CAAAA,CAAaG,CAAS,CAAA,EAAK,8BACxC,OAAA,CAAQ,IAAA,CACN,CAAA,kBAAA,EAAqBD,CAAQ,gBAAgBC,CAAS,CAAA;AAAA;AAAA,EAEjDA,CAAS,CAAA;AAAA,IAAA,EACLE,CAAI,CAAA;AAAA,+CAAA,CAEf,EACF","file":"chunk-FK7BD7XT.js","sourcesContent":["/**\n * Adapter Type Utilities - Shared types and helpers for framework adapters\n *\n * These utilities reduce type assertions in adapters by providing:\n * - Schema composition types\n * - Constraint/resolver converters\n * - Plugin factory helpers\n */\n\nimport type { Facts } from \"./facts.js\";\nimport type { Plugin } from \"./plugins.js\";\nimport type { ConstraintDef, Requirement } from \"./requirements.js\";\nimport type { ResolverContext, ResolverDef } from \"./resolvers.js\";\nimport type { InferSchema, Schema } from \"./schema.js\";\n\n// ============================================================================\n// Schema Composition Types\n// ============================================================================\n\n/**\n * Merge two schemas into one.\n * Useful for adapters that add bridge-specific facts to user schemas.\n *\n * @example\n * ```typescript\n * type BridgeFields = { __state: SchemaType<Record<string, unknown>> };\n * type Combined = MergedSchema<UserSchema, BridgeFields>;\n * ```\n */\nexport type MergedSchema<Base extends Schema, Extra extends Schema> = Base &\n Extra;\n\n/**\n * Create a schema type from a fields definition.\n * Helper for defining adapter bridge schemas.\n *\n * @example\n * ```typescript\n * type AdapterBridgeSchema = BridgeSchema<{\n * __adapterState: SchemaType<Record<string, unknown>>;\n * }>;\n * ```\n */\nexport type BridgeSchema<Fields extends Schema> = Fields;\n\n// ============================================================================\n// Bridge Schema Helper\n// ============================================================================\n\n/**\n * Create a bridge schema definition for adapters.\n * Returns a schema object compatible with createModule().\n *\n * @example\n * ```typescript\n * const bridgeSchema = createBridgeSchema({\n * __state: t.object<Record<string, unknown>>(),\n * });\n * ```\n */\nexport function createBridgeSchema<S extends Schema>(schema: S): S {\n return schema;\n}\n\n// ============================================================================\n// Type-Safe Fact Mutation\n// ============================================================================\n\n/**\n * Type-safe fact setter for known schema keys.\n * Use when you have a typed schema and want to set a specific fact.\n *\n * @example\n * ```typescript\n * setFact(facts, \"count\", 10); // Type-checked\n * ```\n */\nexport function setFact<S extends Schema, K extends keyof InferSchema<S>>(\n facts: Facts<S>,\n key: K,\n value: InferSchema<S>[K],\n): void {\n (facts as Record<string, unknown>)[key as string] = value;\n}\n\n/**\n * Set a bridge fact without strict typing.\n * Use for adapter-internal bridge fields like `__adapterState`.\n *\n * @example\n * ```typescript\n * setBridgeFact(facts, \"__adapterState\", currentState);\n * ```\n */\nexport function setBridgeFact<V>(\n facts: Facts<Schema>,\n key: string,\n value: V,\n): void {\n (facts as Record<string, unknown>)[key] = value;\n}\n\n/**\n * Get a bridge fact without strict typing.\n * Use for adapter-internal bridge fields.\n *\n * @example\n * ```typescript\n * const state = getBridgeFact<MyState>(facts, \"__adapterState\");\n * ```\n */\nexport function getBridgeFact<V>(facts: Facts<Schema>, key: string): V {\n return (facts as Record<string, unknown>)[key] as V;\n}\n\n// ============================================================================\n// Constraint Converters\n// ============================================================================\n\n/**\n * Adapter constraint definition (generic form used by adapters).\n */\nexport interface AdapterConstraint<TState> {\n when: (state: TState) => boolean | Promise<boolean>;\n require: Requirement | ((state: TState) => Requirement | null);\n priority?: number;\n}\n\n/**\n * Convert adapter-style constraints to Directive format.\n * Maps adapter constraints that work with external state (TState) to\n * Directive constraints that work with Facts<Schema>.\n *\n * @param constraints - Adapter constraints keyed by name\n * @param extractState - Function to extract adapter state from facts\n *\n * @example\n * ```typescript\n * const directiveConstraints = convertConstraints<MyState, BridgeSchema>(\n * adapterConstraints,\n * (facts) => getBridgeFact<MyState>(facts, \"__state\"),\n * );\n * ```\n */\nexport function convertConstraints<TState, S extends Schema>(\n constraints: Record<string, AdapterConstraint<TState>>,\n extractState: (facts: Facts<S>) => TState,\n): Record<string, ConstraintDef<S, Requirement>> {\n const result: Record<string, ConstraintDef<S, Requirement>> = {};\n\n for (const [id, constraint] of Object.entries(constraints)) {\n result[id] = {\n priority: constraint.priority ?? 0,\n when: (facts) => constraint.when(extractState(facts)),\n require: (facts) => {\n const req =\n typeof constraint.require === \"function\"\n ? constraint.require(extractState(facts))\n : constraint.require;\n return req;\n },\n };\n }\n\n return result;\n}\n\n// ============================================================================\n// Resolver Converters\n// ============================================================================\n\n/**\n * Adapter resolver context (generic form used by adapters).\n */\nexport interface AdapterResolverContext<TContext> {\n context: TContext;\n signal: AbortSignal;\n}\n\n/**\n * Adapter resolver definition (generic form used by adapters).\n */\nexport interface AdapterResolver<\n TContext,\n R extends Requirement = Requirement,\n> {\n requirement: (req: Requirement) => req is R;\n key?: (req: R) => string;\n resolve: (\n req: R,\n ctx: AdapterResolverContext<TContext>,\n ) => void | Promise<void>;\n}\n\n/**\n * Convert adapter-style resolvers to Directive format.\n * Maps adapter resolvers that work with external context (TContext) to\n * Directive resolvers that work with ResolverContext<Schema>.\n *\n * @param resolvers - Adapter resolvers keyed by name\n * @param createContext - Function to create adapter context from Directive context\n *\n * @example\n * ```typescript\n * const directiveResolvers = convertResolvers<MyContext, BridgeSchema>(\n * adapterResolvers,\n * (ctx) => ({\n * getState: () => getBridgeFact<MyState>(ctx.facts, \"__state\"),\n * setState: (update) => setBridgeFact(ctx.facts, \"__state\", update),\n * signal: ctx.signal,\n * }),\n * );\n * ```\n */\nexport function convertResolvers<TContext, S extends Schema>(\n resolvers: Record<string, AdapterResolver<TContext, Requirement>>,\n createContext: (ctx: ResolverContext<S>) => TContext,\n): Record<string, ResolverDef<S, Requirement>> {\n const result: Record<string, ResolverDef<S, Requirement>> = {};\n\n for (const [id, resolver] of Object.entries(resolvers)) {\n result[id] = {\n requirement: resolver.requirement,\n key: resolver.key,\n resolve: async (req, ctx) => {\n const adapterCtx = createContext(ctx);\n await resolver.resolve(req, {\n context: adapterCtx,\n signal: ctx.signal,\n });\n },\n };\n }\n\n return result;\n}\n\n// ============================================================================\n// Plugin Factory\n// ============================================================================\n\n/**\n * Callback definitions for adapter plugins.\n */\nexport interface AdapterCallbacks {\n onRequirementCreated?: (req: Requirement) => void;\n onRequirementResolved?: (req: Requirement) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Create a callback plugin for adapter events.\n * Wraps adapter callbacks in a Directive plugin.\n *\n * @param name - Plugin name (for debugging)\n * @param callbacks - Callback functions to invoke\n *\n * @example\n * ```typescript\n * const callbackPlugin = createCallbackPlugin(\"adapter-callbacks\", {\n * onRequirementCreated: (req) => console.log(\"Created:\", req),\n * onRequirementResolved: (req) => console.log(\"Resolved:\", req),\n * });\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema type\nexport function createCallbackPlugin(\n name: string,\n callbacks: AdapterCallbacks,\n): Plugin<any> {\n return {\n name,\n onRequirementCreated: callbacks.onRequirementCreated\n ? (req) => callbacks.onRequirementCreated!(req.requirement)\n : undefined,\n onRequirementMet: callbacks.onRequirementResolved\n ? (req) => callbacks.onRequirementResolved!(req.requirement)\n : undefined,\n onError: callbacks.onError,\n };\n}\n\n// ============================================================================\n// Module Config Helpers\n// ============================================================================\n\n/**\n * Cast constraints to the correct type for createModule.\n * Use this when TypeScript can't infer the constraint types correctly.\n */\nexport function asConstraints<S extends Schema>(\n constraints: Record<string, ConstraintDef<S, Requirement>>,\n): Record<string, ConstraintDef<S, Requirement>> {\n return constraints;\n}\n\n/**\n * Cast resolvers to the correct type for createModule.\n * Use this when TypeScript can't infer the resolver types correctly.\n */\nexport function asResolvers<S extends Schema>(\n resolvers: Record<string, ResolverDef<S, Requirement>>,\n): Record<string, ResolverDef<S, Requirement>> {\n return resolvers;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Create a type guard for a specific requirement type.\n * Simplifies the common pattern of checking req.type.\n *\n * @example\n * ```typescript\n * const isResetReq = requirementGuard<ResetReq>(\"RESET\");\n * // Use in resolver:\n * { requirement: isResetReq, resolve: ... }\n * ```\n */\nexport function requirementGuard<R extends Requirement>(\n type: R[\"type\"],\n): (req: Requirement) => req is R {\n return (req): req is R => req.type === type;\n}\n\n/**\n * Create a type guard that matches multiple requirement types.\n *\n * @example\n * ```typescript\n * const isDataReq = requirementGuardMultiple<FetchReq | RefreshReq>([\"FETCH\", \"REFRESH\"]);\n * ```\n */\nexport function requirementGuardMultiple<R extends Requirement>(\n types: Array<R[\"type\"]>,\n): (req: Requirement) => req is R {\n const typeSet = new Set(types);\n return (req): req is R => typeSet.has(req.type);\n}\n","export default true;\n","/**\n * Dependency tracking context for auto-tracking derivations\n *\n * Uses a stack-based approach to handle nested derivation computations.\n * When a derivation accesses a fact, the tracking context records it.\n */\n\n/** Stack of active dependency sets (bare Sets for zero-allocation hot path) */\nconst depStack: Set<string>[] = [];\n\n/**\n * Get the current dependency set, or null if not tracking.\n *\n * @returns The active dependency Set, or `null` if no tracking is active.\n *\n * @internal\n */\nexport function getCurrentDeps(): Set<string> | null {\n const len = depStack.length;\n return len === 0 ? null : depStack[len - 1]!;\n}\n\n/**\n * Check if dependency tracking is currently active.\n *\n * @returns `true` if inside a {@link withTracking} call, `false` otherwise.\n *\n * @internal\n */\nexport function isTracking(): boolean {\n return depStack.length > 0;\n}\n\n/**\n * Run a function with dependency tracking.\n *\n * @remarks\n * Pushes a fresh Set onto the stack, executes `fn`, then pops it.\n * Any fact reads inside `fn` are recorded as dependencies.\n * Nesting is supported — inner calls get their own independent Set.\n *\n * @param fn - The function to execute under tracking.\n * @returns An object with the computed `value` and a `deps` Set of accessed\n * fact keys.\n *\n * @internal\n */\nexport function withTracking<T>(fn: () => T): { value: T; deps: Set<string> } {\n const deps = new Set<string>();\n depStack.push(deps);\n\n try {\n const value = fn();\n return { value, deps };\n } finally {\n depStack.pop();\n }\n}\n\n/**\n * Run a function without tracking.\n *\n * @remarks\n * Temporarily clears the tracking stack so that fact reads inside `fn` do\n * not register as dependencies. The stack is restored after `fn` returns\n * (even on error). Useful for side-effect reads that should not trigger\n * derivation invalidation.\n *\n * @param fn - The function to execute without tracking.\n * @returns The return value of `fn`.\n *\n * @internal\n */\nexport function withoutTracking<T>(fn: () => T): T {\n const saved = depStack.splice(0, depStack.length);\n\n try {\n return fn();\n } finally {\n for (const ctx of saved) {\n depStack.push(ctx);\n }\n }\n}\n\n/**\n * Track a specific key in the current context.\n *\n * @remarks\n * No-op if no tracking context is active.\n *\n * @param key - The fact key to record as a dependency.\n *\n * @internal\n */\nexport function trackAccess(key: string): void {\n const len = depStack.length;\n if (len === 0) {\n return;\n }\n depStack[len - 1]!.add(key);\n}\n\n/**\n * Prototype pollution guard — shared across all proxy handlers.\n *\n * @remarks\n * Contains `__proto__`, `constructor`, and `prototype`. Every proxy `get`\n * and `has` trap checks this set and returns `undefined` / `false` for\n * matching keys, preventing prototype pollution via proxy-based objects.\n *\n * @internal\n */\nexport const BLOCKED_PROPS: ReadonlySet<string> = Object.freeze(\n new Set([\"__proto__\", \"constructor\", \"prototype\"]),\n);\n\n// ============================================================================\n// Non-JSON value-type detection (MIGRATION_FEEDBACK item 20)\n// ============================================================================\n\n/**\n * Detect whether `value` is a non-JSON-roundtrippable type whose mutations\n * the facts proxy cannot track for reactivity.\n *\n * Returns the kind label (`\"Date\"`, `\"Set\"`, `\"Map\"`, `\"File\"`, or\n * `\"ClassInstance\"`) when one is detected, or `null` for plain objects,\n * arrays, primitives, and `null`/`undefined`.\n *\n * The `File` check is SSR-safe: if the runtime has no `File` global the\n * branch is skipped without throwing.\n *\n * The `ClassInstance` check fires for any object whose prototype is not\n * `Object.prototype` and which is not an array — e.g. instances of user\n * classes whose mutations bypass reactivity.\n *\n * @internal\n */\nexport function detectNonJsonValueType(value: unknown): string | null {\n if (value === null || typeof value !== \"object\") {\n return null;\n }\n if (value instanceof Date) {\n return \"Date\";\n }\n if (value instanceof Set) {\n return \"Set\";\n }\n if (value instanceof Map) {\n return \"Map\";\n }\n if (typeof File !== \"undefined\" && value instanceof File) {\n return \"File\";\n }\n // Plain objects and arrays are JSON-friendly.\n if (Array.isArray(value)) {\n return null;\n }\n // Class instances: prototype is not Object.prototype.\n // Plain `{}` literals have prototype `Object.prototype`; objects created\n // via `Object.create(null)` have a `null` prototype which we treat as\n // \"plain\" (it's still JSON-roundtrippable).\n const proto = Object.getPrototypeOf(value);\n if (proto !== null && proto !== Object.prototype) {\n return \"ClassInstance\";\n }\n\n return null;\n}\n\n/**\n * Per-(path, valueType) dedupe cache — once a warning fires for a given\n * combo we never re-emit. Keeps the dev console quiet under loops that\n * assign the same Date 100 times in a row.\n *\n * @internal\n */\nconst nonJsonWarningCache = new Set<string>();\n\nconst nonJsonHints: Record<string, string> = {\n Date: \".getTime() for timestamps\",\n Set: \"[...set] for arrays\",\n Map: \"Object.fromEntries(map) for plain objects\",\n File: \"{ name, size, type, lastModified } for metadata\",\n ClassInstance: \"a plain-object snapshot\",\n};\n\n/**\n * Emit a one-time dev-mode warning when a non-JSON value is assigned to a\n * fact. Called from the proxy `set` traps in both `createFactsProxy`\n * (single-module / standalone facts) and `createModuleFactsProxy`\n * (system-namespaced facts). No-ops in production builds — the call sites\n * are gated on `isDevelopment` so this entire helper is tree-shakable.\n *\n * @param factPath - Display path for the warning (e.g. `auth.token` or\n * bare `token` for non-namespaced stores).\n * @param valueType - The label returned from {@link detectNonJsonValueType}.\n *\n * @internal\n */\nexport function warnNonJsonFactAssignment(\n factPath: string,\n valueType: string,\n): void {\n const cacheKey = `${factPath}|${valueType}`;\n if (nonJsonWarningCache.has(cacheKey)) {\n return;\n }\n nonJsonWarningCache.add(cacheKey);\n\n const hint = nonJsonHints[valueType] ?? \"a JSON-roundtrippable value\";\n console.warn(\n `[Directive] Fact \"${factPath}\" assigned a ${valueType} instance.\\n` +\n `Facts must be JSON-roundtrippable for reactivity to work correctly.\\n` +\n `${valueType} mutations are not tracked.\\n` +\n `Use ${hint} instead.\\n` +\n `See: https://directive.run/docs/facts#json-rule`,\n );\n}\n\n/**\n * Reset the warning dedupe cache. Test-only — exported via internals for\n * vitest spec setup. Not part of the public API.\n *\n * @internal\n */\nexport function _resetNonJsonWarningCache(): void {\n nonJsonWarningCache.clear();\n}\n"]}
@@ -1,16 +0,0 @@
1
- import {z as z$1,a}from'./chunk-E2WETPLH.js';import {f,l,m,n}from'./chunk-FK7BD7XT.js';import {c}from'./chunk-4CMO5OVZ.js';var y="::",ie=Symbol.for("nodejs.util.inspect.custom");function ae(n){if(!n.ownKeys)return {};let e={};for(let t of n.ownKeys())e[t]=n.get(t);return e}function x(n){return new Proxy({},{get(e,t){if(typeof t=="symbol")return t===ie?()=>ae(n):void 0;if(!l.has(t))return n.get(t)},set(e,t,o){return typeof t=="symbol"||l.has(t)?false:n.set?n.set(t,o):false},has(e,t){return typeof t=="symbol"||l.has(t)?false:n.has?n.has(t):false},deleteProperty(e,t){return typeof t=="symbol"||l.has(t)?false:n.delete?n.delete(t):false},ownKeys(){return n.ownKeys?n.ownKeys():[]},getOwnPropertyDescriptor(e,t){if(typeof t!="symbol"&&n.has&&typeof t=="string"&&n.has(t))return {configurable:true,enumerable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var z=new WeakMap,V=new WeakMap,U=new WeakMap,J=new WeakMap,G=new WeakMap,L=new WeakMap;function D(n$1,e){let t=z.get(n$1);if(t){let r=t.get(e);if(r)return r}else t=new Map,z.set(n$1,t);let o=x({get:r=>r==="$store"||r==="$snapshot"?n$1[r]:n$1[`${e}${y}${r}`],set:(r,a)=>{if(f){let c=m(a);c&&n(`${e}.${r}`,c);}return n$1[`${e}${y}${r}`]=a,true},has:r=>`${e}${y}${r}`in n$1,delete:r=>(delete n$1[`${e}${y}${r}`],true)});return t.set(e,o),o}function Z(n,e,t){let o=V.get(n);if(o)return o;let r=x({get:a=>{if(Object.hasOwn(e,a))return D(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return V.set(n,r),r}function Q(n,e,t){let o=`${e}|${t.join(",")}`,r=G.get(n);if(r){let i=r.get(o);if(i)return i}else r=new Map,G.set(n,r);let a=new Set(t),c=["self",...t],f$1=x({get:i=>{if(i==="self")return D(n,e);if(a.has(i))return D(n,i);f&&console.warn(`[Directive] Module "${e}" accessed undeclared cross-module property "${i}". Add it to crossModuleDeps or use "facts.self.${i}" for own module facts.`);},has:i=>i==="self"||a.has(i),ownKeys:()=>c});return r.set(o,f$1),f$1}function A(n,e){let t=J.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,J.set(n,t);let o=x({get:r=>n[`${e}${y}${r}`],has:r=>`${e}${y}${r}`in n});return t.set(e,o),o}function X(n,e,t){let o=U.get(n);if(o)return o;let r=x({get:a=>{if(Object.hasOwn(e,a))return A(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return U.set(n,r),r}function Y(n,e,t){let o=L.get(n);return o||(o=new Map,L.set(n,o)),x({get:r=>{if(!Object.hasOwn(e,r))return;let a=o.get(r);if(a)return a;let c=x({get:f=>i=>{n.dispatch({type:`${r}${y}${f}`,...i});}});return o.set(r,c),c},has:r=>Object.hasOwn(e,r),ownKeys:()=>t()})}function b(n){if(n.includes(".")){let[e,...t]=n.split(".");return `${e}${y}${t.join(y)}`}return n}function N(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.indexOf(y);if(r>0){let a=t.slice(0,r),c=t.slice(r+y.length);e[a]||(e[a]={}),e[a][c]=o;}else e._root||(e._root={}),e._root[t]=o;}return e}function O(n,e,t,o){return t?Q(n,e,o):D(n,e)}function M(n,e){return `${n}${y}${e}`}function P(n){return Object.keys(n).length>0?n:void 0}function ce(n,e){let t={};for(let[o,r]of Object.entries(n.schema.facts))t[M(e,o)]=r;return t}function ue(n,e){if(n.init)return t=>{let o=D(t,e);n.init(o);}}function de(n,e,t,o){if(!n.derive)return;let r={};for(let[a$1,c]of Object.entries(n.derive)){let f=a(c),i=f?c.compute:c,w=f?c.meta:void 0,g=(d,m)=>{let R=O(d,e,t,o),h=A(m,e);return i(R,h)};r[M(e,a$1)]=w?{compute:g,meta:w}:g;}return P(r)}function le(n,e){if(!n.events)return;let t={};for(let[o,r]of Object.entries(n.events)){let a=typeof r=="object"&&r!==null&&Object.hasOwn(r,"handler"),c=a?r.handler:r,f=a?r.meta:void 0,i=(w,g)=>{let d=D(w,e);c(d,g);};t[M(e,o)]=f?{handler:i,meta:f}:i;}return P(t)}function fe(n,e,t,o){if(!n.constraints)return;let r={};for(let[a,c]of Object.entries(n.constraints)){let f=c;r[M(e,a)]={...f,deps:f.deps?.map(i=>M(e,i)),after:f.after?.map(i=>i.includes(y)?i:M(e,i)),when:i=>{let w=O(i,e,t,o);return f.when(w)},require:typeof f.require=="function"?i=>{let w=O(i,e,t,o);return f.require(w)}:f.require};}return P(r)}function ye(n,e,t,o){if(!n.resolvers)return;let r={};for(let[c,f]of Object.entries(n.resolvers)){let w=function(g){return {facts:O(g.facts,e,t,o),signal:g.signal}};let i=f;r[M(e,c)]={...i,...i.resolve&&{resolve:async(g,d)=>{await i.resolve(g,w(d));}},...i.resolveBatch&&{resolveBatch:async(g,d)=>{await i.resolveBatch(g,w(d));}},...i.resolveBatchWithResults&&{resolveBatchWithResults:async(g,d)=>i.resolveBatchWithResults(g,w(d))}};}return P(r)}function ge(n,e,t,o){if(!n.effects)return;let r={};for(let[a,c]of Object.entries(n.effects)){let f=c;r[M(e,a)]={...f,run:(i,w)=>{let g=O(i,e,t,o),d=w?O(w,e,t,o):void 0;return f.run(g,d)},deps:f.deps?.map(i=>M(e,i))};}return P(r)}function he(n,e,t){return {snapshotEvents:t&&!t.has(e)?[]:n.history?.snapshotEvents?.map(o=>M(e,o))}}function _(n){let{mod:e,namespace:t,snapshotModulesSet:o}=n,r=!!(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0),a=r?Object.keys(e.crossModuleDeps):[];return {id:e.id,schema:ce(e,t),requirements:e.schema.requirements??{},init:ue(e,t),derive:de(e,t,r,a),events:le(e,t),effects:ge(e,t,r,a),constraints:fe(e,t,r,a),resolvers:ye(e,t,r,a),hooks:e.hooks,meta:e.meta,history:he(e,t,o)}}function me(n){let e=Object.keys(n),t=new Set(e),o=new Set,r=new Set,a=[],c=[];function f(i){if(o.has(i))return;if(r.has(i)){let g=c.indexOf(i),d=[...c.slice(g),i].join(" \u2192 ");throw new Error(`[Directive] Circular dependency detected: ${d}. Modules cannot have circular crossModuleDeps. Break the cycle by removing one of the cross-module references.`)}r.add(i),c.push(i);let w=n[i];if(w?.crossModuleDeps)for(let g of Object.keys(w.crossModuleDeps))t.has(g)&&f(g);c.pop(),r.delete(i),o.add(i),a.push(i);}for(let i of e)f(i);return a}function ee(n,e){let t=[];for(let o of Object.keys(e.schema.facts))t.push(`${n}${y}${o}`);if(e.schema.derivations)for(let o of Object.keys(e.schema.derivations))t.push(`${n}${y}${o}`);return t}function Ee(n){if("module"in n){if(!n.module)throw new Error("[Directive] createSystem requires a module. Got: "+typeof n.module);return ke(n)}let e=n;if(Array.isArray(e.modules))throw new Error(`[Directive] createSystem expects modules as an object, not an array.
2
-
3
- Instead of:
4
- createSystem({ modules: [authModule, dataModule] })
5
-
6
- Use:
7
- createSystem({ modules: { auth: authModule, data: dataModule } })
8
-
9
- Or for a single module:
10
- createSystem({ module: counterModule })`);let t=e.modules;if(t&&typeof t=="object"&&"id"in t&&"schema"in t)throw new Error(`[Directive] A single module was passed to \`modules:\`. For a single module, use \`module:\` instead:
11
-
12
- createSystem({ module: myModule })
13
-
14
- For multiple modules, wrap in an object:
15
- createSystem({ modules: { myName: myModule } })`);return we(e)}function we(n){let e=n.modules,t=new Set(Object.keys(e)),o=typeof n.history=="object"?n.history:null,r=o?.snapshotModules?new Set(o.snapshotModules):null;if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(f){for(let[s,u]of Object.entries(e))if(u.crossModuleDeps)for(let l of Object.keys(u.crossModuleDeps))l===s?console.warn(`[Directive] Module "${s}" references itself in crossModuleDeps. Use "facts.self" to access own module's facts instead.`):t.has(l)||console.warn(`[Directive] Module "${s}" declares crossModuleDeps.${l}, but no module with namespace "${l}" exists in the system. Available modules: ${[...t].join(", ")}`);}if(f&&o?.snapshotModules)for(let s of o.snapshotModules)t.has(s)||console.warn(`[Directive] history.snapshotModules entry "${s}" doesn't match any module. Available modules: ${[...t].join(", ")}`);let a,c$1=n.initOrder??"auto";if(Array.isArray(c$1)){let s=c$1,u=Object.keys(e).filter(l=>!s.includes(l));if(u.length>0)throw new Error(`[Directive] initOrder is missing modules: ${u.join(", ")}. All modules must be included in the explicit order.`);a=s;}else c$1==="declaration"?a=Object.keys(e):a=me(e);let{history:f$1,trace:i,errorBoundary:w}=ne(n);for(let s of Object.keys(e)){if(s.includes(y))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${y}". Module names cannot contain "${y}".`);let u=e[s];if(u){for(let l of Object.keys(u.schema.facts))if(l.includes(y))throw new Error(`[Directive] Schema key "${l}" in module "${s}" contains the reserved separator "${y}". Schema keys cannot contain "${y}".`)}}let g={names:null};function d(){return g.names===null&&(g.names=Object.keys(e)),g.names}let m=a.map(s=>{let u=e[s];return u?_({mod:u,namespace:s,snapshotModulesSet:r}):null}).filter(s=>s!==null);f&&n.tickMs&&n.tickMs>0&&(m.some(u=>u.events&&Object.keys(u.events).some(l=>l.endsWith(`${y}tick`)))||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but no module defines a "tick" event handler.`));let R=null,h=null;function K(s){for(let[u,l$1]of Object.entries(s)){if(l.has(u)){f&&console.warn(`[Directive] initialFacts/hydrate contains blocked namespace "${u}". Skipping.`);continue}if(!t.has(u)){f&&console.warn(`[Directive] initialFacts/hydrate contains unknown namespace "${u}". Available modules: ${[...t].join(", ")}`);continue}if(l$1&&typeof l$1=="object"&&!c(l$1))throw new Error(`[Directive] initialFacts/hydrate for namespace "${u}" contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.`);for(let[v,S]of Object.entries(l$1))l.has(v)||(h.facts[`${u}${y}${v}`]=S);}}h=z$1({modules:m,plugins:n.plugins,history:f$1,trace:i,errorBoundary:w,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{n.initialFacts&&K(n.initialFacts),R&&(K(R),R=null);}});let $=new Map;for(let s of Object.keys(e)){let u=e[s];u&&$.set(s,ee(s,u));}let B=Z(h.facts,e,d),se=X(h.derive,e,d),oe=Y(h,e,d),j=null,C=n.tickMs,T={_mode:"namespaced",facts:B,history:h.history,derive:se,events:oe,constraints:h.constraints,effects:h.effects,resolvers:h.resolvers,async hydrate(s){if(h.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let u=await s();u&&typeof u=="object"&&(R=u);},initialize(){h.initialize();},start(){if(h.start(),C&&C>0){let s;for(let u of m)if(u?.events&&(s=Object.keys(u.events).find(l=>l.endsWith(`${y}tick`)),s))break;if(s){let u=s;j=setInterval(()=>{h.dispatch({type:u});},C);}}},stop(){j&&(clearInterval(j),j=null),h.stop();},destroy(){this.stop(),h.destroy();},dispatch(s){h.dispatch(s);},read(s){return h.read(b(s))},subscribe(s,u){let l=[];for(let v of s)if(v.endsWith(".*")){let S=v.slice(0,-2),H=$.get(S);H?l.push(...H):f&&console.warn(`[Directive] subscribe wildcard "${v}" \u2014 namespace "${S}" not found.`);}else l.push(b(v));return h.subscribe(l,u)},subscribeModule(s,u){let l=$.get(s);return !l||l.length===0?(f&&console.warn(`[Directive] subscribeModule("${s}") \u2014 namespace not found. Available: ${[...$.keys()].join(", ")}`),()=>{}):h.subscribe(l,u)},watch(s,u,l){return h.watch(b(s),u,l)},when(s,u){return h.when(()=>s(B),u)},getDistributableSnapshot(s){let u={...s,includeDerivations:s?.includeDerivations?.map(b),excludeDerivations:s?.excludeDerivations?.map(b),includeFacts:s?.includeFacts?.map(b)},l=h.getDistributableSnapshot(u);return {...l,data:N(l.data)}},watchDistributableSnapshot(s,u){let l={...s,includeDerivations:s?.includeDerivations?.map(b),excludeDerivations:s?.excludeDerivations?.map(b),includeFacts:s?.includeFacts?.map(b)};return h.watchDistributableSnapshot(l,v=>{u({...v,data:N(v.data)});})},registerModule(s,u){if(t.has(s))throw new Error(`[Directive] Module namespace "${s}" already exists. Cannot register a duplicate namespace.`);if(s.includes(y))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${y}".`);if(l.has(s))throw new Error(`[Directive] Module name "${s}" is a blocked property.`);for(let S of Object.keys(u.schema.facts))if(S.includes(y))throw new Error(`[Directive] Schema key "${S}" in module "${s}" contains the reserved separator "${y}".`);let l$1=u,v=_({mod:l$1,namespace:s,snapshotModulesSet:r});t.add(s),e[s]=l$1,g.names=null,$.set(s,ee(s,l$1)),h.registerModule(v);}};return te(T,h),re(T),T}function ne(n){let e=n.history,t=n.trace,o=n.errorBoundary;return n.zeroConfig&&(e=e??f,o={onConstraintError:"skip",onResolverError:"skip",onEffectError:"skip",onDerivationError:"skip",...n.errorBoundary}),{history:e,trace:t,errorBoundary:o}}function te(n,e){Object.defineProperties(n,{trace:{get(){return e.trace},enumerable:true,configurable:true},meta:{value:e.meta,enumerable:true,configurable:true},isRunning:{get(){return e.isRunning},enumerable:true,configurable:true},isSettled:{get(){return e.isSettled},enumerable:true,configurable:true},isInitialized:{get(){return e.isInitialized},enumerable:true,configurable:true},isReady:{get(){return e.isReady},enumerable:true,configurable:true}}),n.whenReady=e.whenReady.bind(e),n.batch=e.batch.bind(e),n.onSettledChange=e.onSettledChange.bind(e),n.onHistoryChange=e.onHistoryChange.bind(e),n.inspect=e.inspect.bind(e),n.settle=e.settle.bind(e),n.explain=e.explain.bind(e),n.getSnapshot=e.getSnapshot.bind(e),n.restore=e.restore.bind(e),n.observe=e.observe.bind(e);let t=["dispatch","read","subscribe","watch","when","getDistributableSnapshot","watchDistributableSnapshot"];for(let o of t)o in n||(n[o]=e[o].bind(e));}function re(n){f&&process.env.NODE_ENV!=="test"&&setTimeout(()=>{!n.isRunning&&!n.isInitialized&&console.warn("[Directive] System created but start() was never called. Constraints, resolvers, and effects will not run until you call system.start().");},0);}function ke(n){let e=n.module;if(!e)throw new Error("[Directive] createSystem requires a module. Got: "+typeof e);if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(n.initialFacts&&!c(n.initialFacts))throw new Error("[Directive] initialFacts contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");f&&(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0&&console.warn("[Directive] Single module mode ignores crossModuleDeps. Use multiple modules if cross-module access is needed: createSystem({ modules: { ... } })"),n.tickMs&&n.tickMs>0&&(e.events&&"tick"in e.events||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but module has no "tick" event handler.`)),(typeof n.history=="object"?n.history:null)?.snapshotModules&&console.warn("[Directive] history.snapshotModules has no effect in single-module mode. Use history.snapshotEvents on the module definition instead, or switch to createSystem({ modules: { ... } }) for multi-module filtering."));let{history:t,trace:o,errorBoundary:r}=ne(n),a=null,c$1=null;c$1=z$1({modules:[{id:e.id,schema:e.schema.facts,requirements:e.schema.requirements,init:e.init,derive:e.derive,events:e.events,effects:e.effects,constraints:e.constraints,resolvers:e.resolvers,hooks:e.hooks,meta:e.meta,history:e.history}],plugins:n.plugins,history:t,trace:o,errorBoundary:r,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{if(n.initialFacts)for(let[d,m]of Object.entries(n.initialFacts))l.has(d)||(c$1.facts[d]=m);if(a){if(!c(a))f&&console.warn("[Directive] hydrate() data contains potentially dangerous keys. Skipping.");else for(let[d,m]of Object.entries(a))l.has(d)||(c$1.facts[d]=m);a=null;}}});let f$1=new Proxy({},{get(d,m){if(typeof m!="symbol"&&!l.has(m))return R=>{c$1.dispatch({type:m,...R});}},has(d,m){return typeof m=="symbol"||l.has(m)?false:e.events?m in e.events:false},ownKeys(){return e.events?Object.keys(e.events):[]},getOwnPropertyDescriptor(d,m){if(typeof m!="symbol"&&!l.has(m)&&e.events&&m in e.events)return {configurable:true,enumerable:true}},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),i=null,w=n.tickMs,g={_mode:"single",facts:c$1.facts,history:c$1.history,derive:c$1.derive,events:f$1,constraints:c$1.constraints,effects:c$1.effects,resolvers:c$1.resolvers,async hydrate(d){if(c$1.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let m=await d();m&&typeof m=="object"&&(a=m);},initialize(){c$1.initialize();},start(){c$1.start(),w&&w>0&&e.events&&"tick"in e.events&&(i=setInterval(()=>{c$1.dispatch({type:"tick"});},w));},stop(){i&&(clearInterval(i),i=null),c$1.stop();},destroy(){this.stop(),c$1.destroy();},registerModule(d){c$1.registerModule({id:d.id,schema:d.schema.facts,requirements:d.schema.requirements,init:d.init,derive:d.derive,events:d.events,effects:d.effects,constraints:d.constraints,resolvers:d.resolvers,hooks:d.hooks,history:d.history});}};return te(g,c$1),re(g),g}export{Ee as a};//# sourceMappingURL=chunk-LFMRWCIG.js.map
16
- //# sourceMappingURL=chunk-LFMRWCIG.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/system-proxies.ts","../src/core/system-module-transform.ts","../src/core/system.ts"],"names":["SEPARATOR","NODE_INSPECT_CUSTOM","buildHardenedSnapshot","config","snapshot","key","createHardenedProxy","_","prop","BLOCKED_PROPS","value","moduleFactsProxyCache","namespacedFactsProxyCache","namespacedDeriveProxyCache","moduleDeriveProxyCache","crossModuleFactsProxyCache","moduleEventsProxyCache","createModuleFactsProxy","facts","namespace","namespaceCache","cached","proxy","dev_true_default","nonJsonType","detectNonJsonValueType","warnNonJsonFactAssignment","createNamespacedFactsProxy","modulesMap","getModuleNames","createCrossModuleFactsProxy","selfNamespace","depNamespaces","cacheKey","depNamesSet","allKeys","createModuleDeriveProxy","derive","createNamespacedDeriveProxy","createNamespacedEventsProxy","engine","moduleEventsProxy","eventName","payload","toInternalKey","rest","denormalizeFlatKeys","flatData","result","sepIndex","ns","local","createScopedFactsProxy","hasCrossModuleDeps","prefixKey","nonEmpty","rec","prefixSchema","mod","prefixInit","moduleFactsProxy","prefixDerive","raw","isObj","isDerivationWithMeta","fn","meta","wrapper","factsProxy","deriveProxy","prefixEventHandlers","handler","event","prefixConstraints","constraint","constraintDef","dep","prefixResolvers","resolver","wrapCtx","ctx","resolverDef","req","reqs","prefixEffects","effect","effectDef","prev","prevProxy","prefixHistory","snapshotModulesSet","e","prefixModuleDefinition","options","topologicalSort","namespaces","namespacesSet","visited","visiting","path","visit","cycleStart","cycle","depNamespace","collectNamespaceKeys","keys","createSystem","createSingleModuleSystem","namedOptions","mods","createNamespacedSystem","moduleNamespaces","historyConfig","name","orderedNamespaces","initOrder","explicitOrder","missingModules","history","trace","errorBoundary","applyZeroConfigDefaults","moduleNamesCache","flatModules","m","k","hydratedFacts","applyNamespacedFacts","namespacedFacts","isPrototypeSafe","createEngine","namespaceKeysMap","namespacedFactsProxy","namespacedDeriveProxy","namespacedEventsProxy","tickInterval","tickMs","system","loader","tickEventKey","derivationId","ids","listener","internalIds","id","callback","predicate","internalOptions","moduleDef","flat","bindEnginePassthroughs","warnIfNotStarted","overridableMethods","method","eventsProxy"],"mappings":"2HAuBO,IAAMA,CAAAA,CAAY,KAgCnBC,EAAAA,CAAsB,MAAA,CAAO,IAAI,4BAA4B,CAAA,CASnE,SAASC,EAAAA,CAAsBC,CAAAA,CAAsC,CACnE,GAAI,CAACA,CAAAA,CAAO,OAAA,CACV,OAAO,EAAC,CAEV,IAAMC,CAAAA,CAAoC,EAAC,CAC3C,IAAA,IAAWC,CAAAA,IAAOF,CAAAA,CAAO,SAAQ,CAC/BC,CAAAA,CAASC,CAAG,CAAA,CAAIF,CAAAA,CAAO,GAAA,CAAIE,CAAG,CAAA,CAGhC,OAAOD,CACT,CA2BA,SAASE,CAAAA,CAAsCH,EAAgC,CAC7E,OAAO,IAAI,KAAA,CAAM,EAAC,CAAQ,CACxB,GAAA,CAAII,CAAAA,CAAGC,CAAAA,CAAuB,CAC5B,GAAI,OAAOA,GAAS,QAAA,CAGlB,OAAIA,IAASP,EAAAA,CACJ,IAAMC,GAAsBC,CAAM,CAAA,CAE3C,MAAA,CAEF,GAAI,CAAAM,CAAAA,CAAc,IAAID,CAAI,CAAA,CAI1B,OAAOL,CAAAA,CAAO,GAAA,CAAIK,CAAI,CACxB,CAAA,CACA,GAAA,CAAID,CAAAA,CAAGC,CAAAA,CAAuBE,CAAAA,CAAgB,CAI5C,OAHI,OAAOF,CAAAA,EAAS,QAAA,EAGhBC,CAAAA,CAAc,GAAA,CAAID,CAAI,EACjB,KAAA,CAGFL,CAAAA,CAAO,GAAA,CAAMA,CAAAA,CAAO,GAAA,CAAIK,CAAAA,CAAME,CAAK,CAAA,CAAI,KAChD,CAAA,CACA,GAAA,CAAIH,CAAAA,CAAGC,C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A,CACvB,SAAA,CAAWA,CAAAA,CAAU,UACrB,KAAA,CAAOA,CAAAA,CAAU,KAAA,CACjB,OAAA,CAASA,CAAAA,CAAU,OACrB,CAAC,EACH,CAEF,CAAA,CAEA,OAAAE,EAAAA,CAAuBb,CAAAA,CAAQjG,GAAM,CAAA,CACrC+G,EAAAA,CAAiBd,CAAM,CAAA,CAEhBA,CACT","file":"chunk-LFMRWCIG.js","sourcesContent":["/**\n * Proxy factory functions for system-level namespace translation.\n *\n * Extracted from system.ts to reduce file size. All functions are pure\n * proxy factories — they create proxies that translate between unprefixed\n * module keys and prefixed internal keys (e.g., `token` ↔ `auth::token`).\n *\n * @internal\n */\n\nimport isDevelopment from \"#is-development\";\nimport {\n BLOCKED_PROPS,\n detectNonJsonValueType,\n warnNonJsonFactAssignment,\n} from \"./tracking.js\";\nimport type { ModulesMap } from \"./types.js\";\n\n/**\n * Namespace separator for internal key prefixing (e.g., \"auth::token\").\n *\n * @internal\n */\nexport const SEPARATOR = \"::\";\n\n// ============================================================================\n// Hardened Proxy Factory\n// ============================================================================\n\n/**\n * Configuration for creating a hardened proxy with consistent security traps.\n *\n * @internal\n */\ninterface HardenedProxyConfig {\n /** Return the value for a string property access */\n get: (prop: string) => unknown;\n /** Handle property assignment. Omit for read-only proxies (returns false). */\n set?: (prop: string, value: unknown) => boolean;\n /** Check if a string property exists */\n has?: (prop: string) => boolean;\n /** Return all own keys for enumeration */\n ownKeys?: () => string[];\n /** Handle property deletion. Omit to reject deletions. */\n delete?: (prop: string) => boolean;\n}\n\n/**\n * Symbol used by Node.js's `util.inspect` (and vitest's pretty-format)\n * to ask an object for a custom inspection representation. Returning a\n * plain-object snapshot here avoids reflective walks on the proxy that\n * crash printers (e.g. `printComplexValue` reading `val.constructor.name`).\n *\n * @internal\n */\nconst NODE_INSPECT_CUSTOM = Symbol.for(\"nodejs.util.inspect.custom\");\n\n/**\n * Build a plain-object snapshot from a hardened proxy config. Used as the\n * inspection hook so that printers see real keys/values instead of trapping\n * on the proxy.\n *\n * @internal\n */\nfunction buildHardenedSnapshot(config: HardenedProxyConfig): unknown {\n if (!config.ownKeys) {\n return {};\n }\n const snapshot: Record<string, unknown> = {};\n for (const key of config.ownKeys()) {\n snapshot[key] = config.get(key);\n }\n\n return snapshot;\n}\n\n/**\n * Create a proxy with consistent security hardening.\n *\n * Every proxy created by this factory includes:\n * - Symbol access returns `undefined` (except the inspection hook below)\n * - `Symbol.for('nodejs.util.inspect.custom')` returns a function that\n * produces a plain-object snapshot, so vitest pretty-format / Node's\n * `util.inspect` / `console.log` render the proxy correctly without\n * tripping on reflective walks (e.g. `printComplexValue` reading\n * `val.constructor.name`).\n * - `Symbol.toPrimitive` is intentionally NOT set: the get trap returns\n * `undefined` for it so JS falls back to default `toString`/`valueOf`\n * coercion. Returning a snapshot object here would `TypeError` because\n * the protocol requires a primitive return.\n * - BLOCKED_PROPS (`__proto__`, `constructor`, `prototype`) rejected\n * - `defineProperty` returns `false`\n * - `getPrototypeOf` returns `null`\n * - `setPrototypeOf` returns `false`\n *\n * Note: per the Risk reviewer we deliberately do NOT add a `toJSON` shim —\n * that would change `JSON.stringify(proxy)` semantics for users who already\n * rely on the existing shape.\n *\n * @internal\n */\nfunction createHardenedProxy<T extends object>(config: HardenedProxyConfig): T {\n return new Proxy({} as T, {\n get(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n // Inspection hook: return a snapshot function so printers\n // don't walk the proxy reflectively (which crashes pretty-format).\n if (prop === NODE_INSPECT_CUSTOM) {\n return () => buildHardenedSnapshot(config);\n }\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n\n return config.get(prop);\n },\n set(_, prop: string | symbol, value: unknown) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.set ? config.set(prop, value) : false;\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.has ? config.has(prop) : false;\n },\n deleteProperty(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.delete ? config.delete(prop) : false;\n },\n ownKeys() {\n return config.ownKeys ? config.ownKeys() : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (config.has && typeof prop === \"string\" && config.has(prop)) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n });\n}\n\n// ============================================================================\n// Proxy Cache (Performance)\n// ============================================================================\n\n/**\n * WeakMap to cache module facts proxies. Keyed by the facts store object.\n * Inner map is keyed by namespace string.\n */\nconst moduleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced facts proxies.\n */\nconst namespacedFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced derive proxies.\n */\nconst namespacedDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache module derive proxies.\n */\nconst moduleDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache cross-module facts proxies.\n * Keyed by facts store, then by \"selfNamespace|depKeys\" string.\n */\nconst crossModuleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, Record<string, unknown>>>\n>();\n\n/**\n * WeakMap to cache module events proxies.\n */\nconst moduleEventsProxyCache = new WeakMap<\n // biome-ignore lint/suspicious/noExplicitAny: Engine type for cache key\n any,\n Map<string, Record<string, (payload?: Record<string, unknown>) => void>>\n>();\n\n// ============================================================================\n// Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's facts (used in init, event handlers).\n * Translates unprefixed keys to prefixed: `token` → `auth::token`\n *\n * Proxies are cached per facts store and namespace for performance.\n *\n * @param facts - The flat facts store\n * @param namespace - The module namespace for key prefixing\n * @returns A proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => {\n // Reserved properties bypass namespace prefixing (used by engine internals)\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return facts[prop];\n }\n\n return facts[`${namespace}${SEPARATOR}${prop}`];\n },\n set: (prop, value) => {\n // Dev-mode: warn (once per path/type) when assigning non-JSON values\n // that break reactivity. See `warnNonJsonFactAssignment` in tracking.ts.\n if (isDevelopment) {\n const nonJsonType = detectNonJsonValueType(value);\n if (nonJsonType) {\n warnNonJsonFactAssignment(`${namespace}.${prop}`, nonJsonType);\n }\n }\n\n facts[`${namespace}${SEPARATOR}${prop}`] = value;\n\n return true;\n },\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in facts,\n delete: (prop) => {\n delete facts[`${namespace}${SEPARATOR}${prop}`];\n\n return true;\n },\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Facts Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced facts access.\n * `facts.auth.token` → reads `auth::token` from flat store\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param facts - The flat facts store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names (supports dynamic registration)\n * @returns A proxy that delegates to per-module facts proxies\n *\n * @internal\n */\nexport function createNamespacedFactsProxy(\n facts: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedFactsProxyCache.get(facts);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleFactsProxy(facts, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedFactsProxyCache.set(facts, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Cross-Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for cross-module facts access with \"self\" for own module.\n * `facts.self.users` → reads own module's facts\n * `facts.auth.token` → reads dependency module's facts\n *\n * Used when a module has crossModuleDeps defined.\n *\n * @param facts - The flat facts store\n * @param selfNamespace - The namespace of the module that owns this proxy\n * @param depNamespaces - Array of declared dependency namespaces\n * @returns A proxy that provides `self` and declared dependency access\n *\n * @internal\n */\nexport function createCrossModuleFactsProxy(\n facts: Record<string, unknown>,\n selfNamespace: string,\n depNamespaces: string[],\n): Record<string, Record<string, unknown>> {\n // depNamespaces comes from Object.keys() which has stable order per module,\n // so join is sufficient (no need to sort)\n const cacheKey = `${selfNamespace}|${depNamespaces.join(\",\")}`;\n\n // Check cache first\n let namespaceCache = crossModuleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n crossModuleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const depNamesSet = new Set(depNamespaces);\n const allKeys = [\"self\", ...depNamespaces];\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (key) => {\n // \"self\" maps to own module's namespace\n if (key === \"self\") {\n return createModuleFactsProxy(facts, selfNamespace);\n }\n\n // Check if it's a declared dependency\n if (depNamesSet.has(key)) {\n return createModuleFactsProxy(facts, key);\n }\n\n // Dev-mode warning for undeclared cross-module access\n if (isDevelopment) {\n console.warn(\n `[Directive] Module \"${selfNamespace}\" accessed undeclared cross-module property \"${key}\". ` +\n `Add it to crossModuleDeps or use \"facts.self.${key}\" for own module facts.`,\n );\n }\n\n return undefined;\n },\n has: (key) => key === \"self\" || depNamesSet.has(key),\n ownKeys: () => allKeys,\n });\n\n namespaceCache.set(cacheKey, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Module Derive Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's derivations.\n * Translates unprefixed keys to prefixed: `status` → `auth::status`\n *\n * Proxies are cached per derive store and namespace for performance.\n *\n * @param derive - The flat derivations store\n * @param namespace - The module namespace for key prefixing\n * @returns A read-only proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleDeriveProxy(\n derive: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleDeriveProxyCache.get(derive);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleDeriveProxyCache.set(derive, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => derive[`${namespace}${SEPARATOR}${prop}`],\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in derive,\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Derive Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced derivations access.\n * `derive.auth.status` → reads `auth::status` from flat derive\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param derive - The flat derivations store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that delegates to per-module derive proxies\n *\n * @internal\n */\nexport function createNamespacedDeriveProxy(\n derive: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedDeriveProxyCache.get(derive);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleDeriveProxy(derive, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedDeriveProxyCache.set(derive, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Events Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced events access.\n * `events.auth.login({ token })` → dispatches `{ type: \"auth::login\", token }`\n *\n * Uses Set for O(1) namespace lookups and caches proxies for performance.\n *\n * @param engine - The engine instance (used for dispatch)\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that returns event dispatcher functions per namespace\n *\n * @internal\n */\nexport function createNamespacedEventsProxy(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, (payload?: Record<string, unknown>) => void>> {\n // Get or create the namespace cache for this engine\n let namespaceCache = moduleEventsProxyCache.get(engine);\n if (!namespaceCache) {\n namespaceCache = new Map();\n moduleEventsProxyCache.set(engine, namespaceCache);\n }\n\n return createHardenedProxy<\n Record<string, Record<string, (payload?: Record<string, unknown>) => void>>\n >({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n // Check cache for this namespace's event proxy\n const cached = namespaceCache!.get(namespace);\n if (cached) {\n return cached;\n }\n\n // Create and cache the module events proxy\n const moduleEventsProxy = createHardenedProxy<\n Record<string, (payload?: Record<string, unknown>) => void>\n >({\n get: (eventName) => {\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({\n type: `${namespace}${SEPARATOR}${eventName}`,\n ...payload,\n });\n };\n },\n });\n\n namespaceCache!.set(namespace, moduleEventsProxy);\n\n return moduleEventsProxy;\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n}\n\n// ============================================================================\n// Key Conversion Helpers\n// ============================================================================\n\n/**\n * Convert a namespaced key (e.g., \"auth.status\") to internal prefixed format (\"auth::status\").\n * If the key is already in prefixed format, returns it unchanged.\n *\n * @param key - The key to convert (dot-separated or already prefixed)\n * @returns The internal prefixed key\n *\n * @example\n * toInternalKey(\"auth.status\") // → \"auth::status\"\n * toInternalKey(\"auth::status\") // → \"auth::status\" (unchanged)\n * toInternalKey(\"status\") // → \"status\" (unchanged)\n *\n * @internal\n */\nexport function toInternalKey(key: string): string {\n // If key contains a dot, convert to separator format\n if (key.includes(\".\")) {\n const [namespace, ...rest] = key.split(\".\");\n\n return `${namespace}${SEPARATOR}${rest.join(SEPARATOR)}`;\n }\n // Already in internal format or simple key\n\n return key;\n}\n\n// ============================================================================\n// Snapshot Helpers\n// ============================================================================\n\n/**\n * Convert flat internal keys (e.g., `\"auth::token\"`) to nested namespaced\n * format (e.g., `{ auth: { token: ... } }`).\n *\n * Keys without a separator are grouped under `_root`.\n *\n * @param flatData - Object with internal prefixed keys\n * @returns Nested object grouped by namespace\n *\n * @internal\n */\nexport function denormalizeFlatKeys(\n flatData: Record<string, unknown>,\n): Record<string, Record<string, unknown>> {\n const result: Record<string, Record<string, unknown>> = {};\n\n for (const [key, value] of Object.entries(flatData)) {\n const sepIndex = key.indexOf(SEPARATOR);\n if (sepIndex > 0) {\n const ns = key.slice(0, sepIndex);\n const local = key.slice(sepIndex + SEPARATOR.length);\n if (!result[ns]) {\n result[ns] = {};\n }\n result[ns][local] = value;\n } else {\n if (!result._root) {\n result._root = {};\n }\n result._root[key] = value;\n }\n }\n\n return result;\n}\n","/**\n * Module transformation for namespaced systems.\n *\n * Converts a module's unprefixed keys to prefixed internal format\n * (e.g., `token` → `auth::token`). Used by both the initial system\n * setup loop and `registerModule()`.\n *\n * @internal\n */\n\nimport {\n SEPARATOR,\n createCrossModuleFactsProxy,\n createModuleDeriveProxy,\n createModuleFactsProxy,\n} from \"./system-proxies.js\";\nimport type { ModuleDef, ModuleSchema } from \"./types.js\";\nimport { isDerivationWithMeta } from \"./types/meta.js\";\n\n/**\n * The flat engine module format produced by prefixModuleDefinition.\n * Ready to be passed to createEngine or engine.registerModule.\n *\n * @internal\n */\nexport interface FlatModuleDefinition {\n id: string;\n schema: Record<string, unknown>;\n requirements: Record<string, unknown>;\n init: ((facts: Record<string, unknown>) => void) | undefined;\n derive: Record<string, unknown> | undefined;\n events: Record<string, unknown> | undefined;\n effects: Record<string, unknown> | undefined;\n constraints: Record<string, unknown> | undefined;\n resolvers: Record<string, unknown> | undefined;\n hooks: ModuleDef<ModuleSchema>[\"hooks\"];\n meta?: ModuleDef<ModuleSchema>[\"meta\"];\n history: { snapshotEvents?: string[] };\n}\n\n/**\n * Options for prefixModuleDefinition.\n *\n * @internal\n */\nexport interface PrefixModuleOptions {\n /** The module to transform */\n mod: ModuleDef<ModuleSchema>;\n /** The namespace to prefix keys with */\n namespace: string;\n /** Set of modules to snapshot (null = all). Used for history filtering. */\n snapshotModulesSet: Set<string> | null;\n}\n\n/**\n * Create a facts proxy appropriate for the module's cross-module configuration.\n * Returns a cross-module proxy when deps are declared, otherwise a module proxy.\n *\n * @internal\n */\nfunction createScopedFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> {\n return hasCrossModuleDeps\n ? createCrossModuleFactsProxy(facts, namespace, depNamespaces)\n : createModuleFactsProxy(facts, namespace);\n}\n\n/** Prefix a key with the namespace separator */\nfunction prefixKey(namespace: string, key: string): string {\n return `${namespace}${SEPARATOR}${key}`;\n}\n\n/** Return a non-empty record or undefined */\nfunction nonEmpty<T extends Record<string, unknown>>(rec: T): T | undefined {\n return Object.keys(rec).length > 0 ? rec : undefined;\n}\n\n/** Prefix schema fact keys */\nfunction prefixSchema(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(mod.schema.facts)) {\n result[prefixKey(namespace, key)] = value;\n }\n\n return result;\n}\n\n/** Create a prefixed init function */\nfunction prefixInit(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): ((facts: Record<string, unknown>) => void) | undefined {\n if (!mod.init) {\n return undefined;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Facts proxy type coercion\n return (facts: any) => {\n const moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n // biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n (mod.init as any)(moduleFactsProxy);\n };\n}\n\n/** Prefix derivation keys and wrap derivation functions with scoped proxies */\nfunction prefixDerive(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.derive) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(mod.derive)) {\n const isObj = isDerivationWithMeta(raw);\n const fn = isObj ? raw.compute : raw;\n const meta = isObj ? raw.meta : undefined;\n\n const wrapper = (facts: unknown, derive: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const deriveProxy = createModuleDeriveProxy(\n derive as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n return (fn as any)(factsProxy, deriveProxy);\n };\n\n // Pass through as { compute, meta } so derivationsManager can unwrap\n result[prefixKey(namespace, key)] = meta\n ? { compute: wrapper, meta }\n : wrapper;\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix event handler keys and wrap handlers with module-scoped proxies */\nfunction prefixEventHandlers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, unknown> | undefined {\n if (!mod.events) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(mod.events)) {\n // Unwrap { handler, meta } form\n const isObj =\n typeof raw === \"object\" && raw !== null && Object.hasOwn(raw, \"handler\");\n const handler = isObj\n ? (raw as { handler: Function }).handler\n : raw;\n const meta = isObj\n ? (raw as { meta?: unknown }).meta\n : undefined;\n\n const wrapper = (facts: unknown, event: unknown) => {\n const moduleFactsProxy = createModuleFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n (handler as any)(moduleFactsProxy, event);\n };\n\n // Pass through as { handler, meta } so engine can extract meta\n result[prefixKey(namespace, key)] = meta\n ? { handler: wrapper, meta }\n : wrapper;\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix constraint keys and wrap when/require with scoped proxies */\nfunction prefixConstraints(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.constraints) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, constraint] of Object.entries(mod.constraints)) {\n const constraintDef = constraint as {\n when: (facts: unknown) => boolean | Promise<boolean>;\n require: unknown | ((facts: unknown) => unknown);\n priority?: number;\n async?: boolean;\n timeout?: number;\n deps?: string[];\n after?: string[];\n };\n\n result[prefixKey(namespace, key)] = {\n ...constraintDef,\n deps: constraintDef.deps?.map((dep) => prefixKey(namespace, dep)),\n after: constraintDef.after?.map((dep) =>\n dep.includes(SEPARATOR) ? dep : prefixKey(namespace, dep),\n ),\n when: (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return constraintDef.when(factsProxy);\n },\n require:\n typeof constraintDef.require === \"function\"\n ? (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return (constraintDef.require as (facts: unknown) => unknown)(\n factsProxy,\n );\n }\n : constraintDef.require,\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix resolver keys and wrap resolve/resolveBatch/resolveBatchWithResults with scoped proxies */\nfunction prefixResolvers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.resolvers) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, resolver] of Object.entries(mod.resolvers)) {\n const resolverDef = resolver as {\n requirement: string;\n resolve?: (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatch?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatchWithResults?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<unknown>;\n key?: (req: unknown) => string;\n retry?: unknown;\n timeout?: number;\n };\n\n /** Wrap resolver ctx.facts with the module-scoped proxy */\n function wrapCtx(ctx: { facts: unknown; signal: AbortSignal }): {\n facts: unknown;\n signal: AbortSignal;\n } {\n return {\n facts: createScopedFactsProxy(\n ctx.facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n signal: ctx.signal,\n };\n }\n\n result[prefixKey(namespace, key)] = {\n ...resolverDef,\n ...(resolverDef.resolve && {\n resolve: async (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolve!(req, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatch && {\n resolveBatch: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolveBatch!(reqs, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatchWithResults && {\n resolveBatchWithResults: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n return resolverDef.resolveBatchWithResults!(reqs, wrapCtx(ctx));\n },\n }),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix effect keys and wrap run functions with scoped proxies */\nfunction prefixEffects(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.effects) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, effect] of Object.entries(mod.effects)) {\n const effectDef = effect as {\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n run: (facts: any, prev: any) => void | Promise<void>;\n deps?: string[];\n };\n\n result[prefixKey(namespace, key)] = {\n ...effectDef,\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n run: (facts: any, prev: any) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const prevProxy = prev\n ? createScopedFactsProxy(\n prev as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n )\n : undefined;\n\n return effectDef.run(factsProxy, prevProxy);\n },\n deps: effectDef.deps?.map((dep) => prefixKey(namespace, dep)),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Compute history config with prefixed snapshot events */\nfunction prefixHistory(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n snapshotModulesSet: Set<string> | null,\n): { snapshotEvents?: string[] } {\n return {\n snapshotEvents:\n snapshotModulesSet && !snapshotModulesSet.has(namespace)\n ? [] // Module excluded from snapshots\n : mod.history?.snapshotEvents?.map((e: string) =>\n prefixKey(namespace, e),\n ),\n };\n}\n\n/**\n * Transform a module definition by prefixing all keys with a namespace.\n *\n * Handles: facts, derivations, events schema, init, derive, events handlers,\n * constraints (with deps/after), resolvers, and effects.\n *\n * @returns A flat module definition ready for the engine\n *\n * @internal\n */\nexport function prefixModuleDefinition(\n options: PrefixModuleOptions,\n): FlatModuleDefinition {\n const { mod, namespace, snapshotModulesSet } = options;\n\n // Compute cross-module deps info once (used by derive, constraints, effects)\n const hasCrossModuleDeps = !!(\n mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0\n );\n const depNamespaces = hasCrossModuleDeps\n ? Object.keys(mod.crossModuleDeps!)\n : [];\n\n return {\n id: mod.id,\n schema: prefixSchema(mod, namespace),\n requirements: mod.schema.requirements ?? {},\n init: prefixInit(mod, namespace),\n derive: prefixDerive(mod, namespace, hasCrossModuleDeps, depNamespaces),\n events: prefixEventHandlers(mod, namespace),\n effects: prefixEffects(mod, namespace, hasCrossModuleDeps, depNamespaces),\n constraints: prefixConstraints(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n resolvers: prefixResolvers(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n hooks: mod.hooks,\n meta: mod.meta,\n history: prefixHistory(mod, namespace, snapshotModulesSet),\n };\n}\n","/**\n * System - The top-level API for creating a Directive runtime\n *\n * A system combines modules with plugins and configuration.\n * Modules are passed as an object with namespaced access:\n *\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n *\n * system.facts.auth.token // Namespaced facts\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport isDevelopment from \"#is-development\";\nimport { isPrototypeSafe } from \"../utils/utils.js\";\nimport { createEngine } from \"./engine.js\";\nimport { prefixModuleDefinition } from \"./system-module-transform.js\";\nimport {\n SEPARATOR,\n createNamespacedDeriveProxy,\n createNamespacedEventsProxy,\n createNamespacedFactsProxy,\n denormalizeFlatKeys,\n toInternalKey,\n} from \"./system-proxies.js\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n CreateSystemOptionsNamed,\n CreateSystemOptionsSingle,\n ErrorBoundaryConfig,\n HistoryOption,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n SingleModuleSystem,\n TraceOption,\n} from \"./types.js\";\n\n// ============================================================================\n// Topological Sort for Module Dependencies\n// ============================================================================\n\n/**\n * Perform topological sort on modules based on crossModuleDeps.\n * Returns module namespaces in dependency order (dependencies first).\n *\n * @throws Error if circular dependency detected\n */\nfunction topologicalSort<Modules extends ModulesMap>(\n modulesMap: Modules,\n): Array<keyof Modules & string> {\n const namespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n const namespacesSet = new Set<string>(namespaces);\n const visited = new Set<string>();\n const visiting = new Set<string>(); // For cycle detection\n const result: Array<keyof Modules & string> = [];\n const path: string[] = []; // Reuse array to avoid O(n²) memory\n\n function visit(namespace: string): void {\n if (visited.has(namespace)) return;\n\n // Cycle detection\n if (visiting.has(namespace)) {\n const cycleStart = path.indexOf(namespace);\n const cycle = [...path.slice(cycleStart), namespace].join(\" → \");\n throw new Error(\n `[Directive] Circular dependency detected: ${cycle}. ` +\n \"Modules cannot have circular crossModuleDeps. \" +\n \"Break the cycle by removing one of the cross-module references.\",\n );\n }\n\n visiting.add(namespace);\n path.push(namespace);\n\n // Visit dependencies first\n const mod = modulesMap[namespace];\n if (mod?.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (namespacesSet.has(depNamespace)) {\n visit(depNamespace);\n }\n }\n }\n\n path.pop();\n visiting.delete(namespace);\n visited.add(namespace);\n result.push(namespace as keyof Modules & string);\n }\n\n for (const namespace of namespaces) {\n visit(namespace);\n }\n\n return result;\n}\n\n/**\n * Build the list of internal prefixed keys (facts + derivations) for a module namespace.\n * Used by subscribe/subscribeModule to map namespaces to their engine keys.\n */\nfunction collectNamespaceKeys(\n namespace: string,\n mod: ModuleDef<ModuleSchema>,\n): string[] {\n const keys: string[] = [];\n for (const key of Object.keys(mod.schema.facts)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n if (mod.schema.derivations) {\n for (const key of Object.keys(mod.schema.derivations)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n }\n\n return keys;\n}\n\n// ============================================================================\n// createSystem\n// ============================================================================\n\n/**\n * Create a Directive system.\n *\n * Supports two modes:\n * - **Single module**: Use `module` prop for direct access without namespace\n * - **Multiple modules**: Use `modules` prop for namespaced access\n *\n * @remarks\n * The system is the top-level runtime object. It owns the reconciliation loop,\n * manages plugins, and exposes reactive accessors for facts, derivations, and events.\n * Call `system.start()` to begin the lifecycle (init → ready → running → settled).\n *\n * @param options - System configuration with either `module` (single) or `modules` (namespaced)\n * @returns A fully-typed {@link System} instance with reactive accessors\n *\n * @example Single module (direct access)\n * ```ts\n * const system = createSystem({ module: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * @example Multiple modules (namespaced access)\n * ```ts\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.events.auth.login() // Namespaced events\n * ```\n *\n * @public\n */\nexport function createSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S>;\nexport function createSystem<const Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createSystem<\n S extends ModuleSchema,\n Modules extends ModulesMap,\n>(\n options: CreateSystemOptionsSingle<S> | CreateSystemOptionsNamed<Modules>,\n): SingleModuleSystem<S> | NamespacedSystem<Modules> {\n // Single module mode (module prop)\n if (\"module\" in options) {\n if (!options.module) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" +\n typeof options.module,\n );\n }\n return createSingleModuleSystem(\n options as CreateSystemOptionsSingle<S>,\n ) as SingleModuleSystem<S>;\n }\n\n // Namespaced mode (modules prop)\n const namedOptions = options as CreateSystemOptionsNamed<Modules>;\n\n // Validate not an array\n if (Array.isArray(namedOptions.modules)) {\n throw new Error(\n \"[Directive] createSystem expects modules as an object, not an array.\\n\\n\" +\n \"Instead of:\\n\" +\n \" createSystem({ modules: [authModule, dataModule] })\\n\\n\" +\n \"Use:\\n\" +\n \" createSystem({ modules: { auth: authModule, data: dataModule } })\\n\\n\" +\n \"Or for a single module:\\n\" +\n \" createSystem({ module: counterModule })\",\n );\n }\n\n // Detect single ModuleDef accidentally passed to `modules:` instead of `module:`\n const mods = namedOptions.modules as Record<string, unknown>;\n if (mods && typeof mods === \"object\" && \"id\" in mods && \"schema\" in mods) {\n throw new Error(\n \"[Directive] A single module was passed to `modules:`. \" +\n \"For a single module, use `module:` instead:\\n\\n\" +\n \" createSystem({ module: myModule })\\n\\n\" +\n \"For multiple modules, wrap in an object:\\n\" +\n \" createSystem({ modules: { myName: myModule } })\",\n );\n }\n\n return createNamespacedSystem(namedOptions) as NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Internal Implementation\n// ============================================================================\n\nfunction createNamespacedSystem<Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules> {\n const modulesMap = options.modules;\n const moduleNamespaces = new Set(Object.keys(modulesMap));\n\n // Build snapshot module filter set (null = all modules snapshot)\n const historyConfig =\n typeof options.history === \"object\" ? options.history : null;\n const snapshotModulesSet = historyConfig?.snapshotModules\n ? new Set(historyConfig.snapshotModules)\n : null;\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Dev-mode: Validate crossModuleDeps reference existing modules\n if (isDevelopment) {\n for (const [namespace, mod] of Object.entries(modulesMap)) {\n if (mod.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (depNamespace === namespace) {\n console.warn(\n `[Directive] Module \"${namespace}\" references itself in crossModuleDeps. ` +\n `Use \"facts.self\" to access own module's facts instead.`,\n );\n } else if (!moduleNamespaces.has(depNamespace)) {\n console.warn(\n `[Directive] Module \"${namespace}\" declares crossModuleDeps.${depNamespace}, ` +\n `but no module with namespace \"${depNamespace}\" exists in the system. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n }\n }\n\n // Dev-mode: Validate snapshotModules references existing modules\n if (isDevelopment && historyConfig?.snapshotModules) {\n for (const name of historyConfig.snapshotModules) {\n if (!moduleNamespaces.has(name)) {\n console.warn(\n `[Directive] history.snapshotModules entry \"${name}\" doesn't match any module. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n\n // Determine module initialization order\n let orderedNamespaces: Array<keyof Modules & string>;\n const initOrder = options.initOrder ?? \"auto\";\n\n if (Array.isArray(initOrder)) {\n // Explicit order provided - validate it includes all modules\n const explicitOrder = initOrder as Array<keyof Modules & string>;\n const missingModules = Object.keys(modulesMap).filter(\n (ns) => !explicitOrder.includes(ns as keyof Modules & string),\n );\n if (missingModules.length > 0) {\n throw new Error(\n `[Directive] initOrder is missing modules: ${missingModules.join(\", \")}. ` +\n \"All modules must be included in the explicit order.\",\n );\n }\n orderedNamespaces = explicitOrder;\n } else if (initOrder === \"declaration\") {\n // Use object key order (current behavior)\n orderedNamespaces = Object.keys(modulesMap) as Array<\n keyof Modules & string\n >;\n } else {\n // \"auto\" - use topological sort based on crossModuleDeps\n orderedNamespaces = topologicalSort(modulesMap);\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Validate module names and schema keys don't contain the separator\n for (const namespace of Object.keys(modulesMap)) {\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Module names cannot contain \"${SEPARATOR}\".`,\n );\n }\n const mod = modulesMap[namespace];\n if (mod) {\n for (const key of Object.keys(mod.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Schema keys cannot contain \"${SEPARATOR}\".`,\n );\n }\n }\n }\n }\n\n // Cached module names array, shared by all namespaced proxies.\n // Set to null on registerModule to lazily recompute.\n const moduleNamesCache: { names: string[] | null } = { names: null };\n function getModuleNames(): string[] {\n if (moduleNamesCache.names === null) {\n moduleNamesCache.names = Object.keys(modulesMap);\n }\n\n return moduleNamesCache.names;\n }\n\n // Transform modules to flat format with prefixed keys\n // auth.token → auth::token internally\n // Process in dependency order (determined above)\n const flatModules = orderedNamespaces\n .map((namespace) => {\n const mod = modulesMap[namespace];\n if (!mod) return null; // TypeScript guard - should never happen\n\n return prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n })\n .filter((m): m is NonNullable<typeof m> => m !== null);\n\n // Dev-mode warning: tickMs set without tick event handler\n if (\n isDevelopment &&\n options.tickMs &&\n options.tickMs > 0\n ) {\n const hasTickHandler = flatModules.some(\n (m) =>\n m.events &&\n Object.keys(m.events).some((k) => k.endsWith(`${SEPARATOR}tick`)),\n );\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but no module defines a \"tick\" event handler.`,\n );\n }\n }\n\n // Store for hydrated facts (set by hydrate(), applied during init)\n let hydratedFacts: Record<string, Record<string, unknown>> | null = null;\n\n // Engine reference (set after creation, used by applyNamespacedFacts)\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n /**\n * Apply namespaced facts to the engine's flat store.\n * Converts { auth: { token: \"x\" } } to { \"auth::token\": \"x\" }\n * Includes prototype pollution protection.\n */\n function applyNamespacedFacts(\n namespacedFacts: Record<string, Record<string, unknown>>,\n ): void {\n for (const [namespace, facts] of Object.entries(namespacedFacts)) {\n // Skip blocked property names\n if (BLOCKED_PROPS.has(namespace)) {\n if (isDevelopment) {\n console.warn(\n `[Directive] initialFacts/hydrate contains blocked namespace \"${namespace}\". Skipping.`,\n );\n }\n continue;\n }\n\n if (!moduleNamespaces.has(namespace)) {\n if (isDevelopment) {\n console.warn(\n `[Directive] initialFacts/hydrate contains unknown namespace \"${namespace}\". ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n continue;\n }\n\n // Validate facts object for prototype pollution\n if (facts && typeof facts === \"object\" && !isPrototypeSafe(facts)) {\n throw new Error(\n `[Directive] initialFacts/hydrate for namespace \"${namespace}\" contains potentially ` +\n \"dangerous keys (__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n for (const [key, value] of Object.entries(facts)) {\n // Skip blocked keys\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[\n `${namespace}${SEPARATOR}${key}`\n ] = value;\n }\n }\n }\n\n // Create engine with flat modules\n engine = createEngine({\n // biome-ignore lint/suspicious/noExplicitAny: Module format conversion\n modules: flatModules as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n // Callback to apply initialFacts/hydrate during init phase (after module inits, before reconcile)\n onAfterModuleInit: () => {\n // Apply initialFacts first\n if (options.initialFacts) {\n applyNamespacedFacts(\n options.initialFacts as Record<string, Record<string, unknown>>,\n );\n }\n // Apply hydrated facts second (takes precedence)\n if (hydratedFacts) {\n applyNamespacedFacts(hydratedFacts);\n hydratedFacts = null;\n }\n },\n });\n\n // Build namespace → internal keys map (for subscribeModule / wildcard support)\n const namespaceKeysMap = new Map<string, string[]>();\n for (const namespace of Object.keys(modulesMap)) {\n const mod = modulesMap[namespace];\n if (!mod) continue;\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n }\n\n // Create namespaced proxies for external access\n const namespacedFactsProxy = createNamespacedFactsProxy(\n engine.facts as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedDeriveProxy = createNamespacedDeriveProxy(\n engine.derive as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedEventsProxy = createNamespacedEventsProxy(\n engine,\n modulesMap,\n getModuleNames,\n );\n\n // Build the namespaced system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: NamespacedSystem<Modules> = {\n _mode: \"namespaced\",\n facts: namespacedFactsProxy,\n history: engine.history,\n derive: namespacedDeriveProxy,\n events: namespacedEventsProxy,\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () =>\n | Promise<Record<string, Record<string, unknown>>>\n | Record<string, Record<string, unknown>>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n // Engine.start() runs module inits, then applies initialFacts/hydrate via callback\n engine.start();\n\n if (tickMs && tickMs > 0) {\n // Find the first module with a tick event and dispatch to it\n let tickEventKey: string | undefined;\n for (const m of flatModules) {\n if (m?.events) {\n tickEventKey = Object.keys(m.events).find((k) =>\n k.endsWith(`${SEPARATOR}tick`),\n );\n if (tickEventKey) break;\n }\n }\n if (tickEventKey) {\n const key = tickEventKey;\n tickInterval = setInterval(() => {\n engine.dispatch({ type: key });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n dispatch(event: { type: string; [key: string]: unknown }) {\n engine.dispatch(event);\n },\n\n /**\n * Read a derivation value using namespaced syntax.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.read(\"auth.status\") // → \"authenticated\"\n * system.read(\"data.count\") // → 5\n */\n read<T = unknown>(derivationId: string): T {\n return engine.read(toInternalKey(derivationId));\n },\n\n /**\n * Subscribe to derivation changes using namespaced syntax.\n * Accepts \"namespace.key\" format.\n * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n *\n * @example\n * system.subscribe([\"auth.status\", \"data.count\"], () => {\n * console.log(\"Auth or data changed\");\n * });\n *\n * @example Wildcard\n * system.subscribe([\"game.*\", \"chat.*\"], () => render());\n */\n subscribe(ids: string[], listener: () => void): () => void {\n const internalIds: string[] = [];\n for (const id of ids) {\n if (id.endsWith(\".*\")) {\n const ns = id.slice(0, -2);\n const keys = namespaceKeysMap.get(ns);\n if (keys) {\n internalIds.push(...keys);\n } else if (isDevelopment) {\n console.warn(\n `[Directive] subscribe wildcard \"${id}\" — namespace \"${ns}\" not found.`,\n );\n }\n } else {\n internalIds.push(toInternalKey(id));\n }\n }\n return engine.subscribe(internalIds, listener);\n },\n\n /**\n * Subscribe to ALL fact and derivation changes in a module namespace.\n * Shorthand for subscribing to every key in a module.\n *\n * @example\n * const unsub = system.subscribeModule(\"game\", () => render());\n */\n subscribeModule(namespace: string, listener: () => void): () => void {\n const keys = namespaceKeysMap.get(namespace);\n if (!keys || keys.length === 0) {\n if (isDevelopment) {\n console.warn(\n `[Directive] subscribeModule(\"${namespace}\") — namespace not found. ` +\n `Available: ${[...namespaceKeysMap.keys()].join(\", \")}`,\n );\n }\n return () => {};\n }\n return engine.subscribe(keys, listener);\n },\n\n /**\n * Watch a fact or derivation for changes using namespaced syntax.\n * The key is auto-detected -- works with both fact keys and derivation keys.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.watch(\"auth.token\", (newVal, oldVal) => { ... }) // fact\n * system.watch(\"auth.status\", (newVal, oldVal) => { ... }) // derivation\n */\n watch<T = unknown>(\n id: string,\n callback: (newValue: T, previousValue: T | undefined) => void,\n options?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n ): () => void {\n return engine.watch(toInternalKey(id), callback, options);\n },\n\n /**\n * Returns a promise that resolves when the predicate becomes true.\n * The predicate receives namespaced facts (e.g., facts.auth.token).\n */\n when(\n predicate: (facts: Record<string, unknown>) => boolean,\n options?: { timeout?: number },\n ): Promise<void> {\n // Wrap predicate to provide namespaced facts view\n return engine.when(\n () =>\n predicate(namespacedFactsProxy as unknown as Record<string, unknown>),\n options,\n );\n },\n\n /**\n * Get a distributable snapshot with namespaced key translation.\n * Accepts \"namespace.key\" format in options (e.g., \"auth.effectivePlan\").\n * Returns data with namespaced keys (e.g., { auth: { effectivePlan: ... } }).\n */\n getDistributableSnapshot<T = Record<string, unknown>>(options?: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n }): {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n } {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n const snapshot = engine.getDistributableSnapshot(internalOptions);\n\n // Transform data keys from internal format (auth::status) to namespaced format (auth: { status })\n return {\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n };\n },\n\n /**\n * Watch for changes to distributable snapshot derivations.\n * Accepts \"namespace.key\" format in options.\n * Callback receives data with namespaced keys.\n */\n watchDistributableSnapshot<T = Record<string, unknown>>(\n options: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n },\n callback: (snapshot: {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => void,\n ): () => void {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n return engine.watchDistributableSnapshot(\n internalOptions,\n (snapshot: {\n data: Record<string, unknown>;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => {\n // Transform data keys from internal format to namespaced format\n callback({\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n });\n },\n );\n },\n registerModule(\n namespace: string,\n moduleDef: ModuleDef<ModuleSchema>,\n ): void {\n // Validate namespace\n if (moduleNamespaces.has(namespace)) {\n throw new Error(\n `[Directive] Module namespace \"${namespace}\" already exists. ` +\n \"Cannot register a duplicate namespace.\",\n );\n }\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n if (BLOCKED_PROPS.has(namespace)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" is a blocked property.`,\n );\n }\n\n // Validate schema keys\n for (const key of Object.keys(moduleDef.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n }\n\n const mod = moduleDef;\n\n // Transform module definition with namespace prefixing\n const flat = prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n\n // Register namespace\n moduleNamespaces.add(namespace);\n (modulesMap as Record<string, ModuleDef<ModuleSchema>>)[namespace] = mod;\n // Invalidate cached module names so proxies see the new namespace\n moduleNamesCache.names = null;\n\n // Update namespace keys map\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n\n // Delegate to engine's registerModule\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule(flat);\n },\n\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for NamespacedSystem\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n\n// ============================================================================\n// Shared Helpers (deduplication between single-module and namespaced systems)\n// ============================================================================\n\n/**\n * Apply zero-config defaults to system options (history, trace, errorBoundary).\n * Returns the resolved values; does not mutate the options object.\n */\nfunction applyZeroConfigDefaults(options: {\n zeroConfig?: boolean;\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n}): {\n history: HistoryOption | undefined;\n trace: TraceOption | undefined;\n errorBoundary: ErrorBoundaryConfig | undefined;\n} {\n let history: HistoryOption | undefined = options.history;\n const trace: TraceOption | undefined = options.trace;\n let errorBoundary: ErrorBoundaryConfig | undefined = options.errorBoundary;\n\n if (options.zeroConfig) {\n const isDev = isDevelopment;\n\n history = history ?? isDev;\n\n errorBoundary = {\n onConstraintError: \"skip\",\n onResolverError: \"skip\",\n onEffectError: \"skip\",\n onDerivationError: \"skip\",\n ...options.errorBoundary,\n };\n }\n\n return { history, trace, errorBoundary };\n}\n\n/**\n * Bind shared engine passthrough properties and methods onto a system object.\n * These are identical between single-module and namespaced systems.\n *\n * For methods that namespaced systems override (dispatch, read, subscribe,\n * watch, when, getDistributableSnapshot, watchDistributableSnapshot),\n * only binds them if not already defined on the system object.\n */\nfunction bindEnginePassthroughs(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n system: any,\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n): void {\n Object.defineProperties(system, {\n trace: {\n get() {\n return engine.trace;\n },\n enumerable: true,\n configurable: true,\n },\n meta: {\n value: engine.meta,\n enumerable: true,\n configurable: true,\n },\n isRunning: {\n get() {\n return engine.isRunning;\n },\n enumerable: true,\n configurable: true,\n },\n isSettled: {\n get() {\n return engine.isSettled;\n },\n enumerable: true,\n configurable: true,\n },\n isInitialized: {\n get() {\n return engine.isInitialized;\n },\n enumerable: true,\n configurable: true,\n },\n isReady: {\n get() {\n return engine.isReady;\n },\n enumerable: true,\n configurable: true,\n },\n });\n\n system.whenReady = engine.whenReady.bind(engine);\n system.batch = engine.batch.bind(engine);\n system.onSettledChange = engine.onSettledChange.bind(engine);\n system.onHistoryChange = engine.onHistoryChange.bind(engine);\n system.inspect = engine.inspect.bind(engine);\n system.settle = engine.settle.bind(engine);\n system.explain = engine.explain.bind(engine);\n system.getSnapshot = engine.getSnapshot.bind(engine);\n system.restore = engine.restore.bind(engine);\n system.observe = engine.observe.bind(engine);\n\n // Direct engine passthroughs — only bind if not already defined\n // (namespaced systems override these with key-translating versions)\n const overridableMethods = [\n \"dispatch\",\n \"read\",\n \"subscribe\",\n \"watch\",\n \"when\",\n \"getDistributableSnapshot\",\n \"watchDistributableSnapshot\",\n ] as const;\n for (const method of overridableMethods) {\n if (!(method in system)) {\n system[method] = engine[method].bind(engine);\n }\n }\n}\n\n/**\n * Emit a dev-mode warning if system.start() is never called.\n */\nfunction warnIfNotStarted(\n // biome-ignore lint/suspicious/noExplicitAny: System type\n system: any,\n): void {\n if (\n isDevelopment &&\n process.env.NODE_ENV !== \"test\"\n ) {\n setTimeout(() => {\n if (!system.isRunning && !system.isInitialized) {\n console.warn(\n \"[Directive] System created but start() was never called. \" +\n \"Constraints, resolvers, and effects will not run until you call system.start().\",\n );\n }\n }, 0);\n }\n}\n\n// Proxy helpers and key conversion utilities are in system-proxies.ts\n\n// ============================================================================\n// Single Module System\n// ============================================================================\n\n/**\n * Create a system with a single module (no namespacing).\n * Facts, derivations, and events are accessed directly.\n */\nfunction createSingleModuleSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S> {\n const mod = options.module;\n\n // Validate module is provided\n if (!mod) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" + typeof mod,\n );\n }\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Validate initialFacts for prototype pollution\n if (options.initialFacts && !isPrototypeSafe(options.initialFacts)) {\n throw new Error(\n \"[Directive] initialFacts contains potentially dangerous keys \" +\n \"(__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n // Dev-mode warnings\n if (isDevelopment) {\n // Warn if crossModuleDeps is defined (ignored in single module mode)\n if (mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0) {\n console.warn(\n \"[Directive] Single module mode ignores crossModuleDeps. \" +\n \"Use multiple modules if cross-module access is needed: \" +\n \"createSystem({ modules: { ... } })\",\n );\n }\n\n // Warn if tickMs set without tick event handler\n if (options.tickMs && options.tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but module has no \"tick\" event handler.`,\n );\n }\n }\n\n // Warn if snapshotModules is set (has no effect in single-module mode)\n const singleHistoryConfig =\n typeof options.history === \"object\" ? options.history : null;\n if (singleHistoryConfig?.snapshotModules) {\n console.warn(\n \"[Directive] history.snapshotModules has no effect in single-module mode. \" +\n \"Use history.snapshotEvents on the module definition instead, or switch to \" +\n \"createSystem({ modules: { ... } }) for multi-module filtering.\",\n );\n }\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Store for hydrated facts\n let hydratedFacts: Record<string, unknown> | null = null;\n\n // Engine reference\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n // Create engine with the module directly (no prefixing needed)\n engine = createEngine({\n modules: [\n {\n id: mod.id,\n schema: mod.schema.facts,\n requirements: mod.schema.requirements,\n init: mod.init,\n derive: mod.derive,\n events: mod.events,\n effects: mod.effects,\n constraints: mod.constraints,\n resolvers: mod.resolvers,\n hooks: mod.hooks,\n meta: mod.meta,\n history: mod.history,\n },\n // biome-ignore lint/suspicious/noExplicitAny: Module format\n ] as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n onAfterModuleInit: () => {\n // Apply initialFacts (already validated for prototype safety above)\n if (options.initialFacts) {\n for (const [key, value] of Object.entries(options.initialFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n // Apply hydrated facts (takes precedence)\n if (hydratedFacts) {\n if (!isPrototypeSafe(hydratedFacts)) {\n if (isDevelopment) {\n console.warn(\n \"[Directive] hydrate() data contains potentially dangerous keys. Skipping.\",\n );\n }\n } else {\n for (const [key, value] of Object.entries(hydratedFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n hydratedFacts = null;\n }\n },\n });\n\n // Create events proxy for direct access\n const eventsProxy = new Proxy(\n {} as Record<string, (payload?: Record<string, unknown>) => void>,\n {\n get(_, eventName: string | symbol) {\n if (typeof eventName === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(eventName)) {\n return undefined;\n }\n\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({ type: eventName, ...payload });\n };\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return mod.events ? prop in mod.events : false;\n },\n ownKeys() {\n return mod.events ? Object.keys(mod.events) : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n if (mod.events && prop in mod.events) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n set() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n },\n );\n\n // Build the single module system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: SingleModuleSystem<S> = {\n _mode: \"single\",\n facts: engine.facts,\n history: engine.history,\n derive: engine.derive,\n events: eventsProxy as SingleModuleSystem<S>[\"events\"],\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () => Promise<Record<string, unknown>> | Record<string, unknown>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result as Record<string, unknown>;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n engine.start();\n\n if (tickMs && tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (hasTickHandler) {\n tickInterval = setInterval(() => {\n engine.dispatch({ type: \"tick\" });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n registerModule(moduleDef: ModuleDef<ModuleSchema>): void {\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule({\n id: moduleDef.id,\n schema: moduleDef.schema.facts,\n requirements: moduleDef.schema.requirements,\n init: moduleDef.init,\n derive: moduleDef.derive,\n events: moduleDef.events,\n effects: moduleDef.effects,\n constraints: moduleDef.constraints,\n resolvers: moduleDef.resolvers,\n hooks: moduleDef.hooks,\n history: moduleDef.history,\n });\n },\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n"]}
@@ -1,3 +0,0 @@
1
- 'use strict';var chunkDDUARSUH_cjs=require('./chunk-DDUARSUH.cjs'),chunkBEJ6ICA7_cjs=require('./chunk-BEJ6ICA7.cjs');var De=class extends Error{constructor(P,S,O,m,p=true){super(P);this.source=S;this.sourceId=O;this.context=m;this.recoverable=p;this.name="DirectiveError";}};function Qe(){return {create(d){return d}}}function et(){return {create(d){return d}}}function tt(d){return d}function nt(d){return d}function ht(d){return d._mode==="single"}function St(d){return d._mode==="namespaced"}function le(d){if(!d)return;let r=Object.assign(Object.create(null),d);return Array.isArray(r.tags)&&Object.freeze(r.tags),Object.freeze(r)}function Ie(d){return typeof d=="object"&&d!==null&&Object.hasOwn(d,"compute")&&typeof d.compute=="function"}function rt(d){return typeof d=="boolean"?{enabled:d,maxSnapshots:100}:{enabled:true,maxSnapshots:d.maxSnapshots??100}}function $e(d){let{historyOption:r,facts:P,store:S,onSnapshot:O,onHistoryChange:m}=d,{enabled:p,maxSnapshots:_}=rt(r),B=[],w=-1,J=1,U=false,F=false,j=[],K=null,W=-1;function k(){return S.toObject()}function N(){let V=k();try{return structuredClone(V)}catch{try{return JSON.parse(JSON.stringify(V))}catch{return {...V}}}}function G(V){if(!chunkBEJ6ICA7_cjs.c(V)){console.error("[Directive] Potential prototype pollution detected in snapshot data, skipping restore");return}S.batch(()=>{for(let[H,X]of Object.entries(V)){if(H==="__proto__"||H==="constructor"||H==="prototype"){console.warn(`[Directive] Skipping dangerous key "${H}" during fact restoration`);continue}P[H]=X;}});}return {get isEnabled(){return p},get isRestoring(){return F},get isPaused(){return U},get snapshots(){return [...B]},get currentIndex(){return w},takeSnapshot(V){if(!p||U)return {id:-1,timestamp:Date.now(),facts:{},trigger:V};let H={id:J++,timestamp:Date.now(),facts:N(),trigger:V};for(w<B.length-1&&B.splice(w+1),B.push(H),w=B.length-1;B.length>_;)B.shift(),w--;return O?.(H),H},restore(V){if(p){U=true,F=true;try{G(V.facts);}finally{U=false,F=false;}}},goBack(V=1){if(!p||B.length===0)return;let H=w,X=w,g=j.find(u=>w>u.startIndex&&w<=u.endIndex);if(g)X=g.startIndex;else if(j.find(a=>w===a.startIndex)){let a=j.find(R=>R.endIndex<w&&w-R.endIndex<=V);X=a?a.startIndex:Math.max(0,w-V);}else X=Math.max(0,w-V);if(H===X)return;w=X;let f=B[w];f&&(this.restore(f),m?.(H,X));},goForward(V=1){if(!p||B.length===0)return;let H=w,X=w,g=j.find(u=>w>=u.startIndex&&w<u.endIndex);if(g?X=g.endIndex:X=Math.min(B.length-1,w+V),H===X)return;w=X;let f=B[w];f&&(this.restore(f),m?.(H,X));},goTo(V){if(!p)return;let H=B.findIndex(f=>f.id===V);if(H===-1){console.warn(`[Directive] Snapshot ${V} not found`);return}let X=w;w=H;let g=B[w];g&&(this.restore(g),m?.(X,H));},replay(){if(!p||B.length===0)return;w=0;let V=B[0];V&&this.restore(V);},export(){return JSON.stringify({version:1,snapshots:B,currentIndex:w})},import(V){if(p)try{let H=JSON.parse(V);if(typeof H!="object"||H===null)throw new Error("[Directive] Invalid history data: expected object");if(H.version!==1)throw new Error(`[Directive] Unsupported history export version: ${H.version}`);if(!Array.isArray(H.snapshots))throw new Error("[Directive] Invalid history data: snapshots must be an array");if(typeof H.currentIndex!="number")throw new Error("Invalid history data: currentIndex must be a number");for(let g of H.snapshots){if(typeof g!="object"||g===null)throw new Error("[Directive] Invalid snapshot: expected object");if(typeof g.id!="number"||typeof g.timestamp!="number"||typeof g.trigger!="string"||typeof g.facts!="object")throw new Error("Invalid snapshot structure");if(!chunkBEJ6ICA7_cjs.c(g.facts))throw new Error("[Directive] Invalid fact data: potential prototype pollution detected in nested objects")}B.length=0,B.push(...H.snapshots),w=H.currentIndex;let X=B[w];X&&this.restore(X);}catch(H){console.error("[Directive] Failed to import history data:",H);}},beginChangeset(V){p&&(K=V,W=w);},endChangeset(){!p||K===null||(w>W&&j.push({label:K,startIndex:W,endIndex:w}),K=null,W=-1);},pause(){U=true;},resume(){U=false;}}}function Fe(){let d={id:-1,timestamp:0,facts:{},trigger:""};return {isEnabled:false,isRestoring:false,isPaused:false,snapshots:[],currentIndex:-1,takeSnapshot:()=>d,restore:()=>{},goBack:()=>{},goForward:()=>{},goTo:()=>{},replay:()=>{},export:()=>"{}",import:()=>{},beginChangeset:()=>{},endChangeset:()=>{},pause:()=>{},resume:()=>{}}}var Ke=new WeakMap;function it(d,r){if(r)return r(d);let P=Ke.get(d);if(P!==void 0)return P;let{type:S,...O}=d,m=chunkBEJ6ICA7_cjs.b(O),p=`${S}:${m}`;return Ke.set(d,p),p}function qe(d,r,P){return {requirement:d,id:it(d,P),fromConstraint:r}}function xt(d){return r=>({type:d,...r})}function It(d,r){return d.type===r}function qt(d){return r=>r.type===d}var Re=class d{map=new Map;add(r){this.map.has(r.id)||this.map.set(r.id,r);}remove(r){return this.map.delete(r)}has(r){return this.map.has(r)}get(r){return this.map.get(r)}all(){return [...this.map.values()]}ids(){return [...this.map.keys()]}get size(){return this.map.size}clear(){this.map.clear();}clone(){let r=new d;for(let P of this.map.values())r.add(P);return r}diff(r){let P=[],S=[];for(let O of this.map.values())r.has(O.id)||P.push(O);for(let O of r.map.values())this.map.has(O.id)||S.push(O);return {added:P,removed:S}}};var st=5e3;function Be(d){let{definitions:r,facts:P,requirementKeys:S={},defaultTimeout:O=st,onEvaluate:m,onError:p}=d,_=new Map,B=new Set,w=new Set,J=new Map,U=new Map,F=new Set,j=new Map,K=new Map,W=false,k=new Set,N=new Set,G=new Map,ie=[],V=new Map;function H(t,i){r[t]&&(G.has(t)||G.set(t,new Set),G.get(t).add(i));}function X(){G.clear();for(let[t,i]of Object.entries(r))if(i.after)for(let l of i.after)H(l,t);}function g(t,i,l,C,T){if(l.has(t))return;if(C.has(t)){let se=i.indexOf(t),ae=[...i.slice(se),t].join(" \u2192 ");throw new Error(`[Directive] Constraint cycle detected: ${ae}. Remove one of the \`after\` dependencies to break the cycle.`)}C.add(t),i.push(t);let Z=r[t];if(Z?.after)for(let se of Z.after)r[se]&&g(se,i,l,C,T);i.pop(),C.delete(t),l.add(t),T.push(t);}function f(){let t=new Set,i=new Set,l=[];for(let C of Object.keys(r))g(C,[],t,i,l);ie=l,V=new Map(ie.map((C,T)=>[C,T]));}f(),X();function u(){for(let[t,i]of Object.entries(r))if(i.after)for(let l of i.after)r[l]||console.warn(`[Directive] Constraint "${t}" references unknown constraint "${l}" in \`after\`. This dependency will be ignored. Check for typos or ensure the constraint exists.`);}chunkDDUARSUH_cjs.f&&u();function a(t,i){return i.async!==void 0?i.async:!!w.has(t)}function R(t){let i=r[t];if(!i)throw new Error(`[Directive] Unknown constraint: ${t}`);let l=a(t,i);l&&w.add(t);let C={id:t,priority:i.priority??0,isAsync:l,lastResult:null,isEvaluating:false,error:null,lastResolvedAt:null,after:i.after??[],hitCount:0,lastActiveAt:null};return _.set(t,C),C}function I(t){return _.get(t)??R(t)}function Q(t,i){if(t.size!==i.size||t.size===0)return false;for(let l of i)if(!t.has(l))return false;return true}function ee(t,i){for(let l of i){let C=U.get(l);C&&(C.delete(t),C.size===0&&U.delete(l));}}function ue(t,i){for(let l of i)U.has(l)||U.set(l,new Set),U.get(l).add(t);}function h(t){let i=J.get(t);i&&(ee(t,i),J.delete(t));}function b(t){G.delete(t);for(let i of G.values())i.delete(t);}function c(t,i){let l=J.get(t)??new Set;Q(l,i)||(ee(t,l),ue(t,i),J.set(t,i));}function E(t,i){if(i.deps)return j.set(t,new Set(i.deps)),i.when(P);let l=chunkDDUARSUH_cjs.i(()=>i.when(P));return j.set(t,l.deps),l.value}function A(t,i,l){i.lastResult=l,l&&(i.hitCount++,i.lastActiveAt=Date.now()),i.isEvaluating=false,m?.(t,l);}function te(t,i,l){i.error=l instanceof Error?l:new Error(String(l)),i.lastResult=false,i.isEvaluating=false,p?.(t,l);}function me(t,i,l){return w.add(t),i.isAsync=true,chunkDDUARSUH_cjs.f&&console.warn(`[Directive] Constraint "${t}" returned a Promise but was not marked as async. Add \`async: true\` to the constraint definition to avoid this warning and improve performance.`),l.then(C=>(A(t,i,C),C)).catch(C=>(te(t,i,C),false))}function fe(t){let i=r[t];if(!i)return false;let l=I(t);l.isEvaluating=true,l.error=null;try{let C=E(t,i);return C instanceof Promise?me(t,l,C):(A(t,l,C),C)}catch(C){return te(t,l,C),false}}async function ge(t){let i=r[t];if(!i)return false;let l=I(t),C=i.timeout??O;if(l.isEvaluating=true,l.error=null,i.deps?.length){let T=new Set(i.deps);c(t,T),j.set(t,T);}try{let T=i.when(P),Z=await chunkBEJ6ICA7_cjs.a(T,C,`Constraint "${t}" timed out after ${C}ms`);return l.lastResult=Z,Z&&(l.hitCount++,l.lastActiveAt=Date.now()),l.isEvaluating=!1,m?.(t,Z),Z}catch(T){return l.error=T instanceof Error?T:new Error(String(T)),l.lastResult=false,l.isEvaluating=false,p?.(t,T),false}}let ve=10;function pe(t,i){if(t==null)return [];if(Array.isArray(t)){let l=t.filter(C=>C!=null);return chunkDDUARSUH_cjs.f&&l.length>ve&&i&&console.warn(`[Directive] Constraint "${i}" produced ${l.length} requirements. Consider splitting into multiple constraints for better performance.`),l}return [t]}function he(t){let i=r[t];if(!i)return {requirements:[],deps:new Set};let l=i.require;if(typeof l=="function"){let{value:T,deps:Z}=chunkDDUARSUH_cjs.i(()=>l(P));return {requirements:pe(T,t),deps:Z}}return {requirements:pe(l,t),deps:new Set}}function ye(t,i){if(i.size===0)return;let l=J.get(t)??new Set;for(let C of i)l.add(C);ue(t,i),J.set(t,l);}let $=null;function oe(){return $||($=Object.keys(r).sort((t,i)=>{let l=I(t),T=I(i).priority-l.priority;if(T!==0)return T;let Z=V.get(t)??0,se=V.get(i)??0;return Z-se})),$}for(let t of Object.keys(r))R(t);function de(t){for(let[i,l]of Object.entries(t))l.async&&!l.deps&&console.warn(`[Directive] Async constraint "${i}" has no \`deps\` declared. Auto-tracking cannot work across async boundaries. Add \`deps: ["key1", "key2"]\` to enable dependency tracking.`);}chunkDDUARSUH_cjs.f&&de(r);function Se(t){return !r[t]||B.has(t)||N.has(t)?true:k.has(t)}function we(t){let i=_.get(t);if(!i||i.after.length===0)return true;for(let l of i.after)if(!Se(l))return false;return true}function o(t){let i=j.get(t);i!==void 0&&c(t,i),N.add(t),K.set(t,[]);}function v(t,i,l){if(i!==void 0){let C=new Set(i);for(let T of l)C.add(T);c(t,C);}else ye(t,l);}function y(t,i,l){if(i.length===0){K.set(t,[]);return}let C=i.map(T=>qe(T,t,S[T.type]));for(let T of C)l.add(T);K.set(t,C);}function q(t,i){for(let l of t)i.add(l);}function z(t,i,l){if(B.has(t))return;if(!i){o(t);return}N.delete(t);let C=j.get(t),T,Z;try{let se=he(t);T=se.requirements,Z=se.deps;}catch(se){p?.(t,se),o(t);return}v(t,C,Z),y(t,T,l);}function e(t,i){let l=[],C=[];for(let T of t){if(we(T)){C.push(T);continue}l.push(T);let Z=K.get(T);Z&&q(Z,i);}return {blocked:l,ready:C}}function n(t,i){let l=[];for(let C of t){let T=fe(C);if(T instanceof Promise){l.push({id:C,promise:T});continue}z(C,T,i);}return l}async function s(t,i){let l=await Promise.all(t.map(async({id:C,promise:T})=>({id:C,active:await T})));for(let{id:C,active:T}of l)z(C,T,i);}async function D(t,i){let{blocked:l,ready:C}=e(t,i);if(C.length===0)return l;let T=[],Z=[];for(let ae of C)I(ae).isAsync?Z.push(ae):T.push(ae);let se=n(T,i);if(se.length>0&&await s(se,i),Z.length>0){let ae=Z.map(ke=>({id:ke,promise:ge(ke)}));await s(ae,i);}return l}function x(t,i){for(let l of t){let C=U.get(l);if(C)for(let T of C)B.has(T)||i.add(T);}}function M(t){for(let i of F)B.has(i)||t.add(i);F.clear();}function L(t){let i=new Set;return x(t,i),M(i),i}function Y(t,i,l){for(let C of t){if(i.has(C))continue;let T=K.get(C);T&&q(T,l);}}return {async evaluate(t){let i=new Re;N.clear();let l=oe(),C=B.size===0?l:l.filter(ae=>!B.has(ae)),T;if(!W||!t||t.size===0)T=C,W=true;else {let ae=L(t);T=[...ae],Y(C,ae,i);}let Z=T,se=T.length+1;for(;Z.length>0&&se>0;){let ae=Z.length;if(Z=await D(Z,i),Z.length===ae)break;se--;}return i.all()},getState(t){return _.get(t)},getDependencies(t){return J.get(t)},getAllStates(){return [..._.values()]},disable(t){if(!_.has(t)){console.warn(`[Directive] constraints.disable("${t}") \u2014 no such constraint`);return}B.add(t),$=null,K.delete(t),h(t),j.delete(t);},enable(t){if(!_.has(t)){console.warn(`[Directive] constraints.enable("${t}") \u2014 no such constraint`);return}B.delete(t),$=null,F.add(t);},isDisabled(t){return B.has(t)},invalidate(t){let i=U.get(t);if(i)for(let l of i)F.add(l);},markResolved(t){k.add(t);let i=_.get(t);i&&(i.lastResolvedAt=Date.now());let l=G.get(t);if(l)for(let C of l)F.add(C);},isResolved(t){return k.has(t)},registerDefinitions(t){let i=false;for(let[l,C]of Object.entries(t))r[l]=C,R(l),F.add(l),C.after?.length&&(i=true);$=null,i&&f(),X();},assignDefinition(t,i){if(!r[t])throw new Error(`[Directive] Cannot assign constraint "${t}" \u2014 it does not exist. Use register() to create it.`);r[t]=i,R(t),F.add(t),$=null,f(),X();},unregisterDefinition(t){r[t]&&(delete r[t],_.delete(t),B.delete(t),w.delete(t),F.delete(t),N.delete(t),k.delete(t),K.delete(t),j.delete(t),h(t),b(t),$=null,f(),X());},async callOne(t,i){if(!r[t])throw new Error(`[Directive] Cannot call constraint "${t}" \u2014 it does not exist.`);if(B.has(t))return [];let C=I(t),T;if(C.isAsync)T=await ge(t);else {let ae=fe(t);T=ae instanceof Promise?await ae:ae;}if(!T)return [];let{requirements:Z}=he(t);if(Z.length===0)return [];let se=[];for(let ae of Z){let ke=i?{...ae,...i}:ae;se.push(qe(ke,t,S[ke.type]));}return se},setRequirementKey(t,i){S[t]=i;},removeRequirementKey(t){delete S[t];}}}function _e(d){let{definitions:r,facts:P,onCompute:S,onInvalidate:O,onError:m}=d,p=3,_=new Map;for(let[h,b]of Object.entries(r))if(Ie(b)){r[h]=b.compute;let c=le(b.meta);c&&_.set(h,c);}let B=new Map,w=new Map,J=new Map,U=new Map,F=0,j=new Set,K=false,W=100,k;function N(h,b){let c=B.has(h)?U:J,E=c.get(h);E?.delete(b),E&&E.size===0&&c.delete(h);}function G(h,b){let c=r[h]?U:J,E=c.get(h);E||(E=new Set,c.set(h,E)),E.add(b);}function ie(h){let b=B.get(h);if(b)for(let c of b.dependencies)N(c,h);}function V(h){let b=U.get(h);if(b){F++;try{for(let c of b)ee(c);}finally{F--;}U.delete(h);}}function H(h){delete r[h],B.delete(h),w.delete(h),j.delete(h),_.delete(h);}function X(h){if(!r[h])throw new Error(`[Directive] Unknown derivation: ${h}`);let c={id:h,compute:()=>f(h),cachedValue:void 0,dependencies:new Set,isStale:true,isComputing:false,stableRunCount:0,depsStable:false};return B.set(h,c),c}function g(h){return B.get(h)??X(h)}function f(h){let b=g(h),c=r[h];if(!c)throw new Error(`[Directive] Unknown derivation: ${h}`);if(b.isComputing)throw new Error(`[Directive] Circular dependency detected in derivation: ${h}`);b.isComputing=true;try{let E=b.cachedValue,A,te;if(b.depsStable&&b.dependencies.size>0)A=c(P,k),te=b.dependencies;else {let me=chunkDDUARSUH_cjs.i(()=>c(P,k));A=me.value,te=me.deps,b.dependencies.size>0&&u(te,b.dependencies)?(b.stableRunCount++,b.stableRunCount>=p&&(b.depsStable=!0)):b.stableRunCount=0;}return b.cachedValue=A,b.isStale=!1,a(h,te),S&&S(h,A,E,[...te]),A}catch(E){throw m?.(h,E),E}finally{b.isComputing=false;}}function u(h,b){if(h.size!==b.size)return false;for(let c of b)if(!h.has(c))return false;return true}function a(h,b){let c=g(h),E=c.dependencies;if(!u(E,b)){for(let A of E)N(A,h);for(let A of b)G(A,h);c.dependencies=b;}}function R(h){for(let b of h){let c=w.get(b);if(c)for(let E of c)E();}}function I(){if(!(F>0||K)){K=true;try{let h=0;for(;j.size>0;){if(++h>W){let c=[...j];throw j.clear(),new Error(`[Directive] Infinite derivation notification loop detected after ${W} iterations. Remaining: ${c.join(", ")}. This usually means a derivation listener is mutating facts that re-trigger the same derivation.`)}let b=[...j];j.clear(),R(b);}}finally{K=false;}}}function Q(h,b){let c=U.get(h);if(c)for(let E of c)b.push(E);}function ee(h,b=new Set){let c=[h];for(;c.length>0;){let E=c.pop();if(b.has(E))continue;b.add(E);let A=B.get(E);!A||A.isStale||(A.isStale=true,A.depsStable=false,A.stableRunCount=0,O?.(E),j.add(E),Q(E,c));}}return k=new Proxy({},{get(h,b){if(typeof b=="symbol"||chunkDDUARSUH_cjs.l.has(b)||!r[b])return;chunkDDUARSUH_cjs.k(b);let c=g(b);return c.isStale&&f(b),c.cachedValue},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),{get(h){let b=g(h);return b.isStale&&f(h),b.cachedValue},isStale(h){return B.get(h)?.isStale??true},invalidate(h){let b=J.get(h);if(!b)return;F++;let c=new Set;try{for(let E of b)ee(E,c);}finally{F--,I();}},invalidateMany(h){F++;let b=new Set;try{for(let c of h){let E=J.get(c);if(E)for(let A of E)ee(A,b);}}finally{F--,I();}},invalidateAll(){F++;try{for(let h of B.values())h.isStale||(h.isStale=!0,h.depsStable=!1,h.stableRunCount=0,j.add(h.id));}finally{F--,I();}},subscribe(h,b){for(let c of h){let E=c;w.has(E)||w.set(E,new Set),w.get(E).add(b);}return ()=>{for(let c of h){let E=c,A=w.get(E);A?.delete(b),A&&A.size===0&&w.delete(E);}}},getProxy(){return k},getDependencies(h){return g(h).dependencies},registerDefinitions(h){for(let[b,c]of Object.entries(h)){if(Ie(c)){r[b]=c.compute;let E=le(c.meta);E&&_.set(b,E);}else r[b]=c;X(b);}},assignDefinition(h,b){if(!r[h])throw new Error(`[Directive] Cannot assign derivation "${h}" \u2014 it does not exist. Use register() to create it.`);if(Ie(b)){r[h]=b.compute;let E=le(b.meta);E?_.set(h,E):_.delete(h);}else r[h]=b;let c=B.get(h);c&&(c.isStale=true,c.depsStable=false,c.stableRunCount=0,j.add(h)),I();},unregisterDefinition(h){r[h]&&(ie(h),V(h),H(h),I());},getMeta(h){return _.get(h)},callOne(h){if(!r[h])throw new Error(`[Directive] Cannot call derivation "${h}" \u2014 it does not exist.`);return f(h)}}}var ot=3;function We(d){let{definitions:r,facts:P,store:S,onRun:O,onError:m}=d,p=new Map,_=null,B=false;function w(g){let f=r[g];if(!f)throw new Error(`[Directive] Unknown effect: ${g}`);let u={id:g,enabled:true,hasExplicitDeps:!!f.deps,dependencies:f.deps?new Set(f.deps):null,cleanup:null,stableRunCount:0,depsStable:false};return p.set(g,u),u}function J(g){return p.get(g)??w(g)}function U(){return S.toObject()}function F(g){g.depsStable=false,g.stableRunCount=0;}function j(g,f){for(let u of g)if(f.has(u))return true;return false}function K(g,f){let u=J(g);return u.enabled?u.dependencies?j(u.dependencies,f)?(u.depsStable&&F(u),true):false:true:false}function W(g){if(g.cleanup){try{g.cleanup();}catch(f){m?.(g.id,f),console.error(`[Directive] Effect "${g.id}" cleanup threw an error:`,f);}g.cleanup=null;}}function k(g,f){if(typeof f=="function")if(B)try{f();}catch(u){m?.(g.id,u),console.error(`[Directive] Effect "${g.id}" cleanup threw an error:`,u);}else g.cleanup=f;}async function N(g,f){let u;if(S.batch(()=>{u=f.run(P,_);}),u instanceof Promise){let a=await u;k(g,a);}else k(g,u);}function G(g,f){if(g.size!==f.size)return false;for(let u of f)if(!g.has(u))return false;return true}function ie(g,f){if(!(g.dependencies&&G(g.dependencies,f))){F(g);return}g.stableRunCount++,g.stableRunCount>=ot&&(g.depsStable=true);}async function V(g,f){if(g.depsStable&&g.dependencies){await N(g,f);return}let u,a=chunkDDUARSUH_cjs.i(()=>(S.batch(()=>{u=f.run(P,_);}),u)),R=a.deps,I=a.value;I instanceof Promise&&(I=await I),k(g,I),ie(g,R),g.dependencies=R.size>0?R:null;}async function H(g){let f=J(g),u=r[g];if(!(!f.enabled||!u)){W(f),O?.(g,f.dependencies?[...f.dependencies]:[]);try{f.hasExplicitDeps?await N(f,u):await V(f,u);}catch(a){m?.(g,a),console.error(`[Directive] Effect "${g}" threw an error:`,a),f.hasExplicitDeps||F(f);}}}for(let g of Object.keys(r))w(g);return {async runEffects(g){let f=[];for(let u of Object.keys(r))K(u,g)&&f.push(u);await Promise.all(f.map(H)),_=U();},async runAll(){let g=Object.keys(r);await Promise.all(g.map(f=>{let u=J(f);return u.enabled?(F(u),H(f)):Promise.resolve()})),_=U();},disable(g){let f=J(g);f.enabled=false;},enable(g){let f=J(g);f.enabled=true;},isEnabled(g){return J(g).enabled},cleanupAll(){B=true;for(let g of p.values())W(g);},registerDefinitions(g){for(let[f,u]of Object.entries(g))r[f]=u,w(f);},assignDefinition(g,f){if(!r[g])throw new Error(`[Directive] Cannot assign effect "${g}" \u2014 it does not exist. Use register() to create it.`);let u=p.get(g);u&&W(u),r[g]=f,w(g);},unregisterDefinition(g){if(!r[g])return;let f=p.get(g);f&&W(f),delete r[g],p.delete(g);},async callOne(g){let f=r[g];if(!f)throw new Error(`[Directive] Cannot call effect "${g}" \u2014 it does not exist.`);let u=J(g);if(u.enabled){W(u),O?.(g,u.dependencies?[...u.dependencies]:[]);try{let a;if(S.batch(()=>{a=f.run(P,_);}),a instanceof Promise){let R=await a;k(u,R);}else k(u,a);}catch(a){m?.(g,a),console.error(`[Directive] Effect "${g}" threw an error:`,a);}}}}}function at(d={}){let{delayMs:r=1e3,maxRetries:P=3,backoffMultiplier:S=2,maxDelayMs:O=3e4}=d,m=new Map;function p(_){let B=r*S**(_-1);return Math.min(B,O)}return {scheduleRetry(_,B,w,J,U){if(J>P)return null;let F=p(J),j={source:_,sourceId:B,context:w,attempt:J,nextRetryTime:Date.now()+F,callback:U};return m.set(B,j),j},getPendingRetries(){return Array.from(m.values())},processDueRetries(){let _=Date.now(),B=[];for(let[w,J]of m)J.nextRetryTime<=_&&(B.push(J),m.delete(w));return B},cancelRetry(_){m.delete(_);},clearAll(){m.clear();}}}var ct={constraint:"skip",resolver:"skip",effect:"skip",derivation:"skip",system:"throw"};function ze(d={}){let{config:r={},onError:P,onRecovery:S}=d,O=[],m=100,p=at(r.retryLater),_=new Map,B=1e3;function w(K,W,k,N){if(k instanceof De)return k;let G=k instanceof Error?k.message:String(k),ie=K!=="system";return new De(G,K,W,N,ie)}function J(K,W,k){let N=(()=>{switch(K){case "constraint":return r.onConstraintError;case "resolver":return r.onResolverError;case "effect":return r.onEffectError;case "derivation":return r.onDerivationError;default:return}})();if(typeof N=="function"){try{let G=N(k,W);if(typeof G=="string")return G}catch(G){console.error("[Directive] Error in error handler callback:",G);}return "skip"}return typeof N=="string"?N:ct[K]}function U(K){O.push(K),O.length>m&&O.shift();try{P?.(K);}catch(W){console.error("[Directive] Error in onError callback:",W);}try{r.onError?.(K);}catch(W){console.error("[Directive] Error in config.onError callback:",W);}}function F(K,W,k){let N=(_.get(W)??0)+1;if(_.set(W,N),_.size>B){let ie=_.keys().next().value;ie!==void 0&&_.delete(ie);}return p.scheduleRetry(K,W,k,N)?"retry-later":(_.delete(W),typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[Directive] ${K} "${W}" exceeded max retry-later attempts. Skipping.`),"skip")}return {handleError(K,W,k,N){let G=w(K,W,k,N);U(G);let ie=J(K,W,k instanceof Error?k:new Error(String(k)));ie==="retry-later"&&(ie=F(K,W,N));try{S?.(G,ie);}catch(V){console.error("[Directive] Error in onRecovery callback:",V);}if(ie==="throw")throw G;return ie},getLastError(){return O[O.length-1]??null},getAllErrors(){return [...O]},clearErrors(){O.length=0;},getRetryLaterManager(){return p},processDueRetries(){return p.processDueRetries()},clearRetryAttempts(K){_.delete(K),p.cancelRetry(K);}}}function lt(d,r=100){try{return JSON.stringify(d)?.slice(0,r)??String(d)}catch{return "[circular or non-serializable]"}}function ut(d){let{schema:r,onChange:P,onBatch:S}=d,m=Object.keys(r).length===0,p=d.validate??chunkDDUARSUH_cjs.f,_=d.strictKeys??(chunkDDUARSUH_cjs.f&&!m),B=d.redactErrors??false,w=new Map,J=new Set,U=new Map,F=new Set,j=0,K=[],W=new Set,k=false,N=[],G=100;function ie(c){return c!==null&&typeof c=="object"&&"safeParse"in c&&typeof c.safeParse=="function"&&"_def"in c&&"parse"in c&&typeof c.parse=="function"}function V(c){let E=c;if(E._typeName)return E._typeName;if(ie(c)){let A=c._def;if(A?.typeName)return A.typeName.replace(/^Zod/,"").toLowerCase()}return "unknown"}function H(c){return B?"[redacted]":lt(c)}function X(c){return c===null?"null":Array.isArray(c)?"array":typeof c}function g(c,E,A){let te=A.safeParse(E);if(te.success)return;let me=X(E),fe=H(E),ge=te.error?.message??te.error?.issues?.[0]?.message??"Validation failed",ve=V(A);throw new Error(`[Directive] Validation failed for "${c}": expected ${ve}, got ${me} ${fe}. ${ge}`)}function f(c){if(typeof c._lastFailedIndex=="number"&&c._lastFailedIndex>=0){let E=` (element at index ${c._lastFailedIndex} failed)`;return c._lastFailedIndex=-1,E}return ""}function u(c,E,A){let te=A._validators;if(!te||!Array.isArray(te)||te.length===0)return;let me=A._typeName??"unknown";for(let fe=0;fe<te.length;fe++){let ge=te[fe];if(typeof ge!="function"||ge(E))continue;let ve=X(E),pe=H(E),he=f(A),ye=fe===0?"":` (validator ${fe+1} failed)`;throw new Error(`[Directive] Validation failed for "${c}": expected ${me}, got ${ve} ${pe}${ye}${he}`)}}function a(c){if(_)throw new Error(`[Directive] Unknown fact key: "${c}". Key not defined in schema.`);console.warn(`[Directive] Unknown fact key: "${c}"`);}function R(c,E){if(!p)return;let A=r[c];if(!A){a(c);return}if(ie(A)){g(c,E,A);return}u(c,E,A);}function I(c){U.get(c)?.forEach(E=>E());}function Q(){F.forEach(c=>c());}function ee(c,E,A){if(k){N.push({key:c,value:E,prev:A});return}k=true;try{P?.(c,E,A),I(c),Q(),ue(". A listener is repeatedly mutating facts that re-trigger notifications");}finally{k=false;}}function ue(c){let E=0;for(;N.length>0;){if(++E>G)throw N.length=0,new Error(`[Directive] Infinite notification loop detected after ${G} iterations${c}.`);let A=[...N];N.length=0;for(let te of A)P?.(te.key,te.value,te.prev),I(te.key);Q();}}function h(){if(!(j>0)){if(S&&K.length>0&&S([...K]),W.size>0){k=true;try{for(let c of W)I(c);Q(),ue(" during flush");}finally{k=false;}}K.length=0,W.clear();}}let b={get(c){return chunkDDUARSUH_cjs.k(c),w.get(c)},has(c){return chunkDDUARSUH_cjs.k(c),w.has(c)},set(c,E){chunkDDUARSUH_cjs.f&&R(c,E);let A=w.get(c);Object.is(A,E)||(w.set(c,E),J.add(c),j>0?(K.push({key:c,value:E,prev:A,type:"set"}),W.add(c)):ee(c,E,A));},delete(c){let E=w.get(c);w.delete(c),J.delete(c),j>0?(K.push({key:c,value:void 0,prev:E,type:"delete"}),W.add(c)):ee(c,void 0,E);},batch(c){j++;try{c();}finally{j--,h();}},subscribe(c,E){for(let A of c){let te=A;U.has(te)||U.set(te,new Set),U.get(te).add(E);}return ()=>{for(let A of c){let te=U.get(A);te&&(te.delete(E),te.size===0&&U.delete(A));}}},subscribeAll(c){return F.add(c),()=>F.delete(c)},toObject(){let c={};for(let E of J)w.has(E)&&(c[E]=w.get(E));return c}};return b.destroy=()=>{U.clear(),F.clear();},b.registerKeys=c=>{for(let E of Object.keys(c))chunkDDUARSUH_cjs.l.has(E)||(r[E]=c[E],J.add(E));},b}var Te=new WeakMap;function Ne(d,r,P=r){return new Proxy(d,{get(S,O){if(typeof O=="string"&&chunkDDUARSUH_cjs.l.has(O))return;if(O===Symbol.for("nodejs.util.inspect.custom"))return ()=>S;let m=Reflect.get(S,O);if(typeof O=="symbol"||typeof m!="object"||m===null)return m;if(Te.has(m))return Te.get(m);let p=Ne(m,r,`${P}.${String(O)}`);return Te.set(m,p),p},set(S,O,m){return typeof O!="symbol"&&console.warn(`[Directive] Nested mutation on "facts.${P}.${String(O)}" will not trigger reactivity. Use: facts.${r} = { ...facts.${r}, ... }`),Reflect.set(S,O,m)}})}function ft(d,r){let P=()=>({get:O=>chunkDDUARSUH_cjs.j(()=>d.get(O)),has:O=>chunkDDUARSUH_cjs.j(()=>d.has(O))});return new Proxy({},{get(O,m){if(typeof m=="symbol")return m===Symbol.for("nodejs.util.inspect.custom")?()=>chunkDDUARSUH_cjs.j(()=>d.toObject()):void 0;if(chunkDDUARSUH_cjs.l.has(m))return;if(m==="$store")return d;if(m==="$snapshot")return P;let p=d.get(m);return chunkDDUARSUH_cjs.f&&p!==null&&typeof p=="object"?Ne(p,m):p},set(O,m,p){if(typeof m=="symbol"||m==="$store"||m==="$snapshot"||chunkDDUARSUH_cjs.l.has(m))return false;if(chunkDDUARSUH_cjs.f){let _=chunkDDUARSUH_cjs.m(p);_&&chunkDDUARSUH_cjs.n(m,_);}return d.set(m,p),true},deleteProperty(O,m){return typeof m=="symbol"||m==="$store"||m==="$snapshot"||chunkDDUARSUH_cjs.l.has(m)?false:(d.delete(m),true)},has(O,m){return m==="$store"||m==="$snapshot"?true:typeof m=="symbol"||chunkDDUARSUH_cjs.l.has(m)?false:d.has(m)},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(O,m){return m==="$store"||m==="$snapshot"?{configurable:true,enumerable:false,writable:false}:{configurable:true,enumerable:true,writable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function He(d){let r=ut(d),P=ft(r,d.schema);return {store:r,facts:P}}function Le(){let d=[];function r(m){if(m)try{return m()}catch(p){console.error("[Directive] Plugin error:",p);return}}async function P(m){if(m)try{return await m()}catch(p){console.error("[Directive] Plugin error:",p);return}}function S(m){return (...p)=>{for(let _ of d)r(()=>_[m]?.(...p));}}return {register(m){d.some(p=>p.name===m.name)&&(console.warn(`[Directive] Plugin "${m.name}" is already registered, replacing...`),this.unregister(m.name)),d.push(m);},unregister(m){let p=d.findIndex(_=>_.name===m);p!==-1&&d.splice(p,1);},getPlugins(){return [...d]},async emitInit(m){for(let p of d)await P(()=>p.onInit?.(m));},emitStart:S("onStart"),emitStop:S("onStop"),emitDestroy:S("onDestroy"),emitFactSet:S("onFactSet"),emitFactDelete:S("onFactDelete"),emitFactsBatch:S("onFactsBatch"),emitDerivationCompute:S("onDerivationCompute"),emitDerivationInvalidate:S("onDerivationInvalidate"),emitReconcileStart:S("onReconcileStart"),emitReconcileEnd:S("onReconcileEnd"),emitConstraintEvaluate:S("onConstraintEvaluate"),emitConstraintError:S("onConstraintError"),emitRequirementCreated:S("onRequirementCreated"),emitRequirementMet:S("onRequirementMet"),emitRequirementCanceled:S("onRequirementCanceled"),emitResolverStart:S("onResolverStart"),emitResolverComplete:S("onResolverComplete"),emitResolverError:S("onResolverError"),emitResolverRetry:S("onResolverRetry"),emitResolverCancel:S("onResolverCancel"),emitEffectRun:S("onEffectRun"),emitEffectError:S("onEffectError"),emitSnapshot:S("onSnapshot"),emitHistoryNavigate:S("onHistoryNavigate"),emitError:S("onError"),emitErrorRecovery:S("onErrorRecovery"),emitDefinitionRegister:S("onDefinitionRegister"),emitDefinitionAssign:S("onDefinitionAssign"),emitDefinitionUnregister:S("onDefinitionUnregister"),emitDefinitionCall:S("onDefinitionCall"),emitTraceComplete:S("onTraceComplete")}}var Ve={attempts:1,backoff:"none",initialDelay:100,maxDelay:3e4},Ue={enabled:false,windowMs:50};function dt(d,r){if(!r||r==="none")return d;if(r==="full")return Math.floor(Math.random()*d);if(r==="equal"){let P=d/2;return Math.floor(P+Math.random()*P)}if(typeof r=="object"&&"maxMs"in r){let P=Number.isFinite(r.maxMs)&&r.maxMs>0?r.maxMs:0;return d+Math.floor(Math.random()*P)}return d}function gt(d,r){let{backoff:P,initialDelay:S=100,maxDelay:O=3e4}=d,m;switch(P){case "none":m=S;break;case "linear":m=S*r;break;case "exponential":m=S*2**(r-1);break;default:m=S;}let p=Math.min(m,O),_=dt(p,d.jitter);return Math.max(1,_)}function mt(d){if(chunkDDUARSUH_cjs.f)for(let[r,P]of Object.entries(d)){if(!P.resolve&&!P.resolveBatch&&!P.resolveBatchWithResults)throw new Error(`[Directive] Resolver "${r}" must define either resolve() or resolveBatch(). Add one of these methods to handle requirements.`);if(!(!P.batch?.enabled||P.resolveBatch||P.resolveBatchWithResults))if(P.resolve)console.warn(`[Directive] Resolver "${r}" has batch.enabled but no resolveBatch(). Falling back to individual resolve() calls. Add resolveBatch() for true bulk operations.`);else throw new Error(`[Directive] Resolver "${r}" has batch.enabled=true but no resolve(), resolveBatch(), or resolveBatchWithResults() method.`)}}function Je(d){let{definitions:r,facts:P,store:S,getConstraintBinding:O,onStart:m,onComplete:p,onError:_,onRetry:B,onCancel:w,onResolutionComplete:J,onRequeue:U}=d;mt(r);let F=new Map,j=new Map,K=1e3,W=new Map,k=new Map,N=1e3;function G(){if(j.size>K){let o=j.size-K,v=j.keys();for(let y=0;y<o;y++){let q=v.next().value;q&&j.delete(q);}}}function ie(o){return typeof o=="object"&&o!==null&&"requirement"in o&&typeof o.requirement=="string"}function V(o){return typeof o=="object"&&o!==null&&"requirement"in o&&typeof o.requirement=="function"}function H(o,v){return ie(o)?v.type===o.requirement:V(o)?o.requirement(v):false}function X(o,v){let y=k.get(o);if(!y)return null;k.delete(o),k.set(o,y);for(let q of y){let z=r[q];if(z&&H(z,v))return q}return null}function g(o,v){if(!k.has(o)){if(k.size>=N){let y=k.keys().next().value;y!==void 0&&k.delete(y);}k.set(o,new Set);}k.get(o).add(v);}function f(o){let v=o.type,y=X(v,o);if(y)return y;for(let[q,z]of Object.entries(r))if(H(z,o))return g(v,q),q;return null}function u(o){if(!O||!o||!o.fromConstraint)return null;let v=O(o.fromConstraint);return !v||v.mode!=="auto"||!v.when?null:v}function a(o,v){let y=false;return new Proxy(P,{get(q,z,e){return Reflect.get(P,z,e)},set(q,z,e,n){if(y)return true;if(z==="$store"||z==="$snapshot")return Reflect.set(P,z,e);let s;try{s=o.when(P);}catch{s=false;}return s?Reflect.set(P,z,e):(y=true,v.abort(),true)},deleteProperty(q,z){if(y)return true;let e;try{e=o.when(P);}catch{e=false;}return e?Reflect.deleteProperty(P,z):(y=true,v.abort(),true)},has(q,z){return Reflect.has(P,z)},ownKeys(){return Reflect.ownKeys(P)},getOwnPropertyDescriptor(q,z){return Reflect.getOwnPropertyDescriptor(P,z)}})}function R(o,v,y,q){return {facts:y&&q?a(y,q):P,signal:o,snapshot:()=>P.$snapshot(),requeue:()=>{if(U)for(let e of v)U(e);}}}async function I(o,v,y,q){let z=o instanceof Error?o:new Error(String(o));if(q.signal.aborted)return {action:"abort",error:z};if(y.shouldRetry&&!y.shouldRetry(z,v))return {action:"break",error:z};if(v<y.attempts){if(q.signal.aborted)return {action:"abort",error:z};let e=gt(y,v);if(await new Promise(n=>{let s=setTimeout(n,e),D=()=>{clearTimeout(s),n();};q.signal.addEventListener("abort",D,{once:true});}),q.signal.aborted)return {action:"abort",error:z}}return {action:"continue",error:z}}async function Q(o,v,y,q,z){if(!o.resolve)return;let e=u(y),n;S.batch(()=>{n=o.resolve(y.requirement,R(q,[y.id],e,z));});let s=o.timeout;if(s&&s>0){await chunkBEJ6ICA7_cjs.a(n,s,`Resolver "${v}" timed out after ${s}ms`);return}await n;}function ee(o,v,y){let q=Date.now()-y;j.set(v.id,{state:"success",requirementId:v.id,completedAt:Date.now(),duration:q}),G(),p?.(o,v,q);}function ue(o,v,y,q){j.set(v.id,{state:"error",requirementId:v.id,error:y,failedAt:Date.now(),attempts:q}),G(),_?.(o,v,y);}function h(o,v,y){let q=F.get(o);q&&(q.attempt=v,q.status={state:"running",requirementId:o,startedAt:y,attempt:v});}async function b(o,v,y,q,z){let e=await I(o,v,y,q);return e.action==="continue"&&v<y.attempts&&z(v+1),{lastError:e.error,shouldContinue:e.action==="continue"}}async function c(o,v,y){let q=r[o];if(!q)return;let z={...Ve,...q.retry},e=null,n=F.get(v.id)?.startedAt??Date.now();for(let s=1;s<=z.attempts;s++){if(y.signal.aborted)return;h(v.id,s,n);try{await Q(q,o,v,y.signal,y),ee(o,v,n);return}catch(D){let x=await b(D,s,z,y,M=>B?.(o,v,M));if(e=x.lastError,!x.shouldContinue)break}}ue(o,v,e,z.attempts);}async function E(o,v,y){return v&&v>0?chunkBEJ6ICA7_cjs.a(o,v,y):o}async function A(o,v,y,q,z,e,n,s){let D;S.batch(()=>{D=o.resolveBatchWithResults(q,z);});let x=await E(D,e,`Batch resolver "${v}" timed out after ${e}ms`);if(x.length!==y.length)throw new Error(`[Directive] Batch resolver "${v}" returned ${x.length} results but expected ${y.length}. Results array must match input order.`);let M=false;for(let L=0;L<y.length;L++){let Y=y[L],ne=x[L];if(ne.success){ee(v,Y,n);continue}M=true;let t=ne.error??new Error("Batch item failed");j.set(Y.id,{state:"error",requirementId:Y.id,error:t,failedAt:Date.now(),attempts:s}),_?.(v,Y,t);}return !M||y.some((L,Y)=>x[Y]?.success)?"done":"retry"}async function te(o,v,y,q,z,e,n){let s;S.batch(()=>{s=o.resolveBatch(q,z);}),await E(s,e,`Batch resolver "${v}" timed out after ${e}ms`);for(let D of y)ee(v,D,n);}function me(o,v,y,q){for(let z of v)ue(o,z,y,q);}async function fe(o,v){await Promise.all(v.map(y=>{let q=new AbortController;return c(o,y,q)}));}async function ge(o,v,y,q,z,e,n,s){let D=null;if(y.length>0){let L=y[0];y.every(ne=>ne.fromConstraint===L.fromConstraint)&&(D=u(L));}let x=R(q,y.map(L=>L.id),D,z),M=y.map(L=>L.requirement);return o.resolveBatchWithResults?A(o,v,y,M,x,e,n,s):(await te(o,v,y,M,x,e,n),"done")}function ve(o,v,y){for(let q of v)B?.(o,q,y);}async function pe(o,v,y,q,z){let e=new AbortController,n=Date.now(),s=null;for(let D=1;D<=q.attempts;D++){if(e.signal.aborted)return null;try{if(await ge(o,v,y,e.signal,e,z,n,D)==="done")return null}catch(x){let M=await b(x,D,q,e,L=>ve(v,y,L));if(s=M.lastError,!M.shouldContinue)break}}return s}async function he(o,v){let y=r[o];if(!y)return;if(!y.resolveBatch&&!y.resolveBatchWithResults){await fe(o,v);return}let q={...Ve,...y.retry},e={...Ue,...y.batch}.timeoutMs??y.timeout,n=await pe(y,o,v,q,e);n&&me(o,v,n,q.attempts);}let ye=1e4;function $(o){o.timer&&(clearTimeout(o.timer),o.timer=null);}function oe(o){return W.has(o)||W.set(o,{resolverId:o,requirements:[],timer:null}),W.get(o)}function de(o,v){let y=r[o];if(!y)return;let q={...Ue,...y.batch},z=oe(o),e=q.maxSize||ye;if(z.requirements.length>=e&&($(z),Se(o)),z.requirements.push(v),q.maxSize&&z.requirements.length>=q.maxSize){$(z),Se(o);return}$(z),z.timer=setTimeout(()=>{Se(o);},q.windowMs);}function Se(o){let v=W.get(o);if(!v||v.requirements.length===0)return;let y=[...v.requirements];v.requirements=[],v.timer=null,he(o,y).then(()=>{J?.();});}return {resolve(o){if(F.has(o.id))return;let v=f(o.requirement);if(!v){chunkDDUARSUH_cjs.f&&console.warn(`[Directive] No resolver found for requirement type "${o.requirement.type}" (id: ${o.id})`);return}let y=r[v];if(!y)return;if(y.batch?.enabled){de(v,o);return}let q=new AbortController,z=Date.now(),e={requirementId:o.id,resolverId:v,controller:q,startedAt:z,attempt:1,status:{state:"pending",requirementId:o.id,startedAt:z},originalRequirement:o};F.set(o.id,e),m?.(v,o),c(v,o,q).finally(()=>{F.delete(o.id)&&J?.();});},cancel(o){let v=F.get(o);if(v){v.controller.abort(),F.delete(o),j.set(o,{state:"canceled",requirementId:o,canceledAt:Date.now()}),G(),w?.(v.resolverId,v.originalRequirement);return}for(let y of W.values()){let q=y.requirements.findIndex(z=>z.id===o);if(q!==-1){let[z]=y.requirements.splice(q,1);j.set(o,{state:"canceled",requirementId:o,canceledAt:Date.now()}),G(),z&&w?.(y.resolverId,z);return}}},cancelAll(){let o=[...F.keys()];for(let v of o)this.cancel(v);for(let v of W.values()){v.timer&&clearTimeout(v.timer);for(let y of v.requirements)j.set(y.id,{state:"canceled",requirementId:y.id,canceledAt:Date.now()}),w?.(v.resolverId,y);}W.clear(),G();},getStatus(o){let v=F.get(o);if(v)return v.status;let y=j.get(o);return y||{state:"idle"}},getInflight(){return [...F.keys()]},getInflightInfo(){return [...F.values()].map(o=>({id:o.requirementId,resolverId:o.resolverId,startedAt:o.startedAt}))},getInflightCount(){return F.size},isResolving(o){return F.has(o)},processBatches(){for(let o of W.keys())Se(o);},hasPendingBatches(){for(let o of W.values())if(o.requirements.length>0)return true;return false},registerDefinitions(o){for(let[v,y]of Object.entries(o))r[v]=y;k.clear();},assignDefinition(o,v){if(!r[o])throw new Error(`[Directive] Cannot assign resolver "${o}" \u2014 it does not exist. Use register() to create it.`);r[o]=v,k.clear();},unregisterDefinition(o){if(!r[o])return;for(let[y,q]of F)q.resolverId===o&&(q.controller.abort(),F.delete(y),j.set(y,{state:"canceled",requirementId:y,canceledAt:Date.now()}),w?.(o,q.originalRequirement));let v=W.get(o);if(v){v.timer&&clearTimeout(v.timer);for(let y of v.requirements)j.set(y.id,{state:"canceled",requirementId:y.id,canceledAt:Date.now()}),w?.(o,y);W.delete(o);}delete r[o],k.clear(),G();},async callOne(o,v){let y=r[o];if(!y)throw new Error(`[Directive] Cannot call resolver "${o}" \u2014 it does not exist.`);let q=new AbortController,z=R(q.signal,[]);if(y.resolve){let e;S.batch(()=>{e=y.resolve(v,z);}),await e;}},destroy(){this.cancelAll(),j.clear(),k.clear();}}}function Xe(d){let{mergedDerive:r,getDerivation:P,definitions:S}=d,O={register:(m,p)=>S.register("derivation",m,p),assign:(m,p)=>S.assign("derivation",m,p),unregister:m=>S.unregister("derivation",m),call:m=>S.call("derivation",m),isDynamic:m=>S.isDynamic("derivation",m),listDynamic:()=>S.listDynamic("derivation")};return new Proxy({},{get(m,p){if(typeof p!="symbol"&&!chunkDDUARSUH_cjs.l.has(p)){if(p in O)return O[p];if(p in r)return P(p)}},has(m,p){return typeof p=="symbol"||chunkDDUARSUH_cjs.l.has(p)?false:p in r||p in O},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(m,p){if(typeof p!="symbol"&&!chunkDDUARSUH_cjs.l.has(p)&&(p in r||p in O))return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function Ge(d){let{mergedEvents:r,dispatchEvent:P}=d;return new Proxy({},{get(S,O){if(typeof O!="symbol"&&!chunkDDUARSUH_cjs.l.has(O))return m=>{P(O,m);}},has(S,O){return typeof O=="symbol"||chunkDDUARSUH_cjs.l.has(O)?false:O in r},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(S,O){if(typeof O!="symbol"&&!chunkDDUARSUH_cjs.l.has(O)&&O in r)return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var vt=new Set(["register","assign","unregister","call","isDynamic","listDynamic"]);function Ze(d){let{mergedConstraints:r,mergedResolvers:P,mergedDerive:S,mergedEffects:O,constraintsManager:m,resolversManager:p,derivationsManager:_,effectsManager:B,pluginManager:w,getState:J,scheduleReconcile:U,maxDeferredRegistrations:F}=d,j={constraints:new Set,resolvers:new Set,derivations:new Set,effects:new Set},K={constraints:new Map,resolvers:new Map,derivations:new Map,effects:new Map},W=[];function k(f){if(vt.has(f))throw new Error(`[Directive] Derivation ID "${f}" conflicts with a reserved derive method name.`)}let N={constraint:{label:"Constraint",mergedMap:r,manager:m,dynamicSet:j.constraints,originalsMap:K.constraints,reconciles:true},resolver:{label:"Resolver",mergedMap:P,manager:p,dynamicSet:j.resolvers,originalsMap:K.resolvers,reconciles:true},derivation:{label:"Derivation",mergedMap:S,manager:_,dynamicSet:j.derivations,originalsMap:K.derivations,reconciles:false,validateId:k},effect:{label:"Effect",mergedMap:O,manager:B,dynamicSet:j.effects,originalsMap:K.effects,reconciles:false}};function G(f){if(typeof f!="string"||f.length===0)throw new Error(`[Directive] Definition ID must be a non-empty string. Received: ${String(f)}`);if(chunkDDUARSUH_cjs.l.has(f))throw new Error(`[Directive] Security: Definition ID "${f}" is a blocked property.`);if(f.includes("::"))throw new Error(`[Directive] Definition ID "${f}" cannot contain "::". This separator is reserved for namespacing.`)}function ie(f,u,a){let R=N[f];if(R.validateId?.(u),u in R.mergedMap)throw new Error(`[Directive] ${R.label} "${u}" already exists. Use assign() to override.`);if(f!=="derivation"){let I=a;I.meta&&(I.meta=le(I.meta));}R.mergedMap[u]=a,R.manager.registerDefinitions({[u]:a}),R.dynamicSet.add(u),w.emitDefinitionRegister(f,u,a),R.reconciles&&U();}function V(f,u,a){let R=N[f];if(R.validateId?.(u),!(u in R.mergedMap))throw new Error(`[Directive] ${R.label} "${u}" does not exist. Use register() to create it.`);if(f!=="derivation"){let Q=a;Q.meta&&(Q.meta=le(Q.meta));}let I=R.mergedMap[u];R.manager.assignDefinition(u,a),R.originalsMap.set(u,I),R.mergedMap[u]=a,w.emitDefinitionAssign(f,u,a,I),R.reconciles&&U();}function H(f,u){let a=N[f];if(!a.dynamicSet.has(u)){chunkDDUARSUH_cjs.f&&console.warn(`[Directive] Cannot unregister static ${f} "${u}". Only dynamically registered ${f}s can be removed.`);return}a.manager.unregisterDefinition(u),delete a.mergedMap[u],a.dynamicSet.delete(u),a.originalsMap.delete(u),w.emitDefinitionUnregister(f,u),a.reconciles&&U();}function X(){if(W.length===0)return;let f=W.splice(0);for(let u of f)try{switch(u.op){case "register":ie(u.type,u.id,u.def);break;case "assign":V(u.type,u.id,u.def);break;case "unregister":H(u.type,u.id);break}}catch(a){chunkDDUARSUH_cjs.f&&console.error(`[Directive] Error in deferred ${u.op} for ${u.type} "${u.id}":`,a);}}function g(f,u,a,R){let{isDestroyed:I,isReconciling:Q}=J();if(I)throw new Error(`[Directive] Cannot ${f} ${u} "${a}" on a destroyed system.`);if(G(a),Q){if(W.length>=F)throw new Error(`[Directive] Too many deferred registrations (max ${F}). Avoid calling register/assign/unregister in resolver or effect callbacks during reconciliation.`);f==="unregister"?W.push({op:f,type:u,id:a}):W.push({op:f,type:u,id:a,def:R});return}switch(f){case "register":ie(u,a,R);break;case "assign":V(u,a,R);break;case "unregister":H(u,a);break}}return {register(f,u,a){g("register",f,u,a);},assign(f,u,a){g("assign",f,u,a);},unregister(f,u){g("unregister",f,u);},call(f,u,a){let{isDestroyed:R}=J();if(R)throw new Error(`[Directive] Cannot call ${f} "${u}" on a destroyed system.`);switch(G(u),w.emitDefinitionCall(f,u,a),f){case "constraint":return m.callOne(u,a);case "resolver":return p.callOne(u,a);case "derivation":return _.callOne(u);case "effect":return B.callOne(u)}},isDynamic(f,u){switch(f){case "constraint":return j.constraints.has(u);case "resolver":return j.resolvers.has(u);case "derivation":return j.derivations.has(u);case "effect":return j.effects.has(u)}},listDynamic(f){switch(f){case "constraint":return [...j.constraints];case "resolver":return [...j.resolvers];case "derivation":return [...j.derivations];case "effect":return [...j.effects]}},flushDeferred:X,getOriginal(f,u){let R={constraint:K.constraints,resolver:K.resolvers,derivation:K.derivations,effect:K.effects}[f];if(R)return R.get(u)},restoreOriginal(f,u){let R={constraint:K.constraints,resolver:K.resolvers,derivation:K.derivations,effect:K.effects}[f];if(!R||!R.has(u))return false;let I=R.get(u);return g("assign",f,u,I),R.delete(u),true},destroy(){W.length=0,j.constraints.clear(),j.resolvers.clear(),j.derivations.clear(),j.effects.clear(),K.constraints.clear(),K.resolvers.clear(),K.derivations.clear(),K.effects.clear();}}}function Ye(d){let{traceConfig:r,pluginManager:P,resolverMetaLookup:S}=d;if(!(r===true||typeof r=="object"&&r!==null))return {enabled:false,recordFactChange(){},startRun(){return 0},currentTrace:null,getEntries(){return null},attributeResolverStart(){},recordResolverComplete(){},recordResolverError(){},decrementInflight(){},finalizeCurrentRun(){},drainPendingChanges(){},destroy(){}};let m=(typeof r=="object"&&r!==null?r.maxRuns:void 0)??100,p=[],_=new Map,B=0,w=null,J=[],U=new Map,F=new Map,j=new Map,K=null,W=0,k=0,N={count:0,totalDuration:0,avgDuration:0,maxDuration:0,avgResolverCount:0,totalResolverCount:0,avgFactChangeCount:0,totalFactChangeCount:0};function G(a){let R=_.get(a);if(R&&R.status==="pending"){R.status="settled";let I=j.get(a);R.duration=I!==void 0?performance.now()-I:Date.now()-R.timestamp,j.delete(a),F.delete(a),R.causalChain=H(R),X(R),k++,P.emitTraceComplete(R);}}function ie(a){let R=U.get(a);if(U.delete(a),R!==void 0){let I=(F.get(R)??1)-1;I<=0?G(R):F.set(R,I);}}function V(){let a=p.shift();if(a&&(_.delete(a.id),j.delete(a.id),a.status==="pending")){F.delete(a.id);for(let[R,I]of U)I===a.id&&U.delete(R);}}function H(a){let R=[];for(let I of a.factChanges)R.push(`${I.key} changed`);for(let I of a.derivationsRecomputed)R.push(`${I.id} recomputed`);for(let I of a.constraintsHit)R.push(`${I.id} constraint hit`);for(let I of a.requirementsAdded)R.push(`${I.type} requirement added`);for(let I of a.resolversCompleted)R.push(`${I.resolver} resolved (${I.duration.toFixed(0)}ms)`);for(let I of a.resolversErrored)R.push(`${I.resolver} errored`);for(let I of a.effectsRun)R.push(`${I.id} effect ran`);return R.join(" \u2192 ")}function X(a){N.count++,N.totalDuration+=a.duration,N.avgDuration=N.totalDuration/N.count,a.duration>N.maxDuration&&(N.maxDuration=a.duration);let R=a.resolversStarted.length;N.totalResolverCount+=R,N.avgResolverCount=N.totalResolverCount/N.count;let I=a.factChanges.length;N.totalFactChangeCount+=I,N.avgFactChangeCount=N.totalFactChangeCount/N.count;let Q=[];N.count>3&&a.duration>N.avgDuration*5&&Q.push(`Duration ${a.duration.toFixed(0)}ms is 5x+ above average (${N.avgDuration.toFixed(0)}ms)`),a.resolversErrored.length>0&&Q.push(`${a.resolversErrored.length} resolver(s) errored`),Q.length>0&&(a.anomalies=Q);}function g(a){p.push(a),_.set(a.id,a),p.length>m&&V(),k++;}function f(a){return a.factChanges.length>0||a.constraintsHit.length>0||a.requirementsAdded.length>0||a.effectsRun.length>0}return {enabled:true,get currentTrace(){return w},set currentTrace(a){w=a;},recordFactChange(a,R,I){J.push({key:a,oldValue:R,newValue:I});},startRun(){let a=performance.now(),R=++B;return j.set(R,a),w={id:R,timestamp:Date.now(),duration:0,status:"pending",factChanges:J.splice(0),derivationsRecomputed:[],constraintsHit:[],requirementsAdded:[],requirementsRemoved:[],resolversStarted:[],resolversCompleted:[],resolversErrored:[],effectsRun:[],effectErrors:[]},a},getEntries(){return (!K||W!==k)&&(K=[...p],W=k),K},attributeResolverStart(a){w&&U.set(a,w.id);},recordResolverComplete(a,R,I){let Q=U.get(a);if(Q!==void 0){let ee=_.get(Q);ee&&ee.resolversCompleted.push({resolver:R,requirementId:a,duration:I,meta:S?.(R)});}},recordResolverError(a,R,I){let Q=U.get(a);if(Q!==void 0){let ee=_.get(Q);ee&&ee.resolversErrored.push({resolver:R,requirementId:a,error:I,meta:S?.(R)});}},decrementInflight(a){ie(a);},finalizeCurrentRun(a){if(!w)return;if(w.duration=performance.now()-a,!f(w)){j.delete(w.id),w=null;return}let R=w.resolversStarted.length;R===0?(w.status="settled",w.causalChain=H(w),X(w),g(w),P.emitTraceComplete(w)):(w.status="pending",g(w),F.set(w.id,R)),w=null;},drainPendingChanges(){J.length=0;},destroy(){p.length=0,_.clear(),U.clear(),F.clear(),j.clear(),J.length=0,w=null,K=null;}}}function bn(d){let r=Object.create(null),P=Object.create(null),S=Object.create(null),O=Object.create(null),m=Object.create(null),p=Object.create(null),_=new Map,B=new Map,w=new Map,J=new Map,U=new Map;for(let e of d.modules){let n=(D,x)=>{if(D)for(let M of Object.keys(D)){if(chunkDDUARSUH_cjs.l.has(M))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${M}" in ${x}. This could indicate a prototype pollution attempt.`);if(x==="schema"&&M.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${M}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let D of Object.keys(e.schema)){let x=w.get(D);if(x)throw new Error(`[Directive] Schema collision: Fact "${D}" is defined in both module "${x}" and "${e.id}". Use namespacing (e.g., "${e.id}::${D}") or merge into one module.`);w.set(D,e.id);}let s=(D,x)=>{if(D)for(let M of Object.keys(D)){let L=J.get(M);if(L&&L!==e.id)throw new Error(`[Directive] Definition collision: ${x} "${M}" is defined in both module "${L}" and "${e.id}". Use namespacing or rename to avoid conflicts.`);J.set(M,e.id);}};if(s(e.derive,"derivation"),s(e.effects,"effect"),s(e.constraints,"constraint"),s(e.resolvers,"resolver"),s(e.events,"event"),Object.assign(r,e.schema),e.events){for(let[D,x]of Object.entries(e.events))if(typeof x=="object"&&x!==null&&Object.hasOwn(x,"handler")){let M=x;if(e.events[D]=M.handler,M.meta){let L=le(M.meta);L&&B.set(D,L);}}Object.assign(P,e.events);}if(e.derive&&Object.assign(S,e.derive),e.effects&&Object.assign(O,e.effects),e.constraints&&Object.assign(m,e.constraints),e.resolvers){Object.assign(p,e.resolvers);for(let D of Object.keys(e.resolvers))U.set(D,e);}if(e.meta){let D=le(e.meta);D&&_.set(e.id,D);}}for(let e of Object.values(m))e.meta&&(e.meta=le(e.meta));for(let e of Object.values(p))e.meta&&(e.meta=le(e.meta));for(let e of Object.values(O)){let n=e;n.meta&&(n.meta=le(n.meta));}for(let e of Object.values(r)){let n=e;n._meta&&(n._meta=le(n._meta));}let F=null;if(d.modules.some(e=>e.history?.snapshotEvents)){F=new Set;for(let e of d.modules){let n=e;if(n.history?.snapshotEvents)for(let s of n.history.snapshotEvents)F.add(s);else if(n.events)for(let s of Object.keys(n.events))F.add(s);}}let K=0,W=false;if(chunkDDUARSUH_cjs.f){let e=new Set(Object.keys(S));for(let n of Object.keys(r))e.has(n)&&console.warn(`[Directive] "${n}" exists as both a fact and a derivation. This may cause unexpected dependency tracking behavior.`);}let k=Le();for(let e of d.plugins??[])k.register(e);let N=k.getPlugins().length>0,G=k.register.bind(k),ie=k.unregister.bind(k);k.register=e=>{G(e),N=true;},k.unregister=e=>{ie(e),N=k.getPlugins().length>0;};let V=()=>N,H=ze({config:d.errorBoundary,onError:e=>k.emitError(e),onRecovery:(e,n)=>k.emitErrorRecovery(e,n)}),X=null,g=()=>{},f=()=>{},u=null,a=Ye({traceConfig:d.trace,pluginManager:k,resolverMetaLookup:e=>p[e]?.meta}),R=a.enabled,{store:I,facts:Q}=He({schema:r,onChange:(e,n,s)=>{k.emitFactSet(e,n,s),g(e),R&&a.recordFactChange(String(e),s,n),!u?.isRestoring&&(K===0&&(W=true),$.changedKeys.add(e),de());},onBatch:e=>{k.emitFactsBatch(e);let n=[];for(let s of e)n.push(s.key);if(R)for(let s of e)a.recordFactChange(s.key,s.prev,s.type==="delete"?void 0:s.value);if(f(n),!u?.isRestoring){K===0&&(W=true);for(let s of e)$.changedKeys.add(s.key);de();}}}),ee=_e({definitions:S,facts:Q,onCompute:(e,n,s,D)=>{V()&&k.emitDerivationCompute(e,n,D),a.currentTrace&&a.currentTrace.derivationsRecomputed.push({id:e,deps:D?[...D]:[],oldValue:s,newValue:n,meta:ee.getMeta(e)});},onInvalidate:e=>{V()&&k.emitDerivationInvalidate(e);},onError:(e,n)=>{H.handleError("derivation",e,n)==="retry"&&ee.invalidate(e);}});g=e=>ee.invalidate(e),f=e=>ee.invalidateMany(e);let ue=We({definitions:O,facts:Q,store:I,onRun:(e,n)=>{V()&&k.emitEffectRun(e),a.currentTrace&&a.currentTrace.effectsRun.push({id:e,triggeredBy:n,meta:O[e]?.meta});},onError:(e,n)=>{let s=H.handleError("effect",e,n);V()&&k.emitEffectError(e,n),a.currentTrace&&a.currentTrace.effectErrors.push({id:e,error:String(n),meta:O[e]?.meta}),s==="disable"&&ue.disable(e),s==="retry"&&($.changedKeys.add("*"),de());}}),h=Object.create(null);for(let e of Object.values(p))e.key&&typeof e.requirement=="string"&&(h[e.requirement]=e.key);let b=Be({definitions:m,facts:Q,requirementKeys:h,onEvaluate:(e,n)=>{V()&&k.emitConstraintEvaluate(e,n);},onError:(e,n)=>{let s=H.handleError("constraint",e,n);V()&&k.emitConstraintError(e,n),s==="disable"&&b.disable(e);}});function c(e){for(let n of Object.values(e))n.key&&typeof n.requirement=="string"&&b.setRequirementKey(n.requirement,n.key);}let E=new Set,A=Je({definitions:p,facts:Q,store:I,getConstraintBinding:e=>{let n=m[e];return n?(n.bind??"none")==="none"?{mode:"none",when:null}:b.getState(e)?.isAsync||n.async?(chunkDDUARSUH_cjs.f&&console.warn(`[Directive] Constraint "${e}" has bind: 'auto' but is async. Binding is disabled \u2014 async predicates cannot be re-evaluated synchronously on every fact write.`),{mode:"none",when:null}):{mode:"auto",when:n.when}:void 0},onStart:(e,n)=>{V()&&k.emitResolverStart(e,n);},onComplete:(e,n,s)=>{H.clearRetryAttempts(e),V()&&(k.emitResolverComplete(e,n,s),k.emitRequirementMet(n,e)),b.markResolved(n.fromConstraint),R&&(a.recordResolverComplete(n.id,e,s),a.decrementInflight(n.id));},onError:(e,n,s)=>{let D=H.handleError("resolver",e,s,n);if(V()&&k.emitResolverError(e,n,s),D==="disable"&&b.disable(n.fromConstraint),D==="retry"&&($.previousRequirements.remove(n.id),de()),D==="retry-later"){let Y=H.getRetryLaterManager().getPendingRetries().find(ne=>ne.sourceId===e);Y&&!Y.callback&&(Y.callback=()=>{de();});}R&&(a.recordResolverError(n.id,e,String(s)),a.decrementInflight(n.id));let x=U.get(e),M=x?.hooks?.onResolverError;if(M){let L=s instanceof Error?s:new Error(String(s));try{M(L,n.requirement,{facts:Q});}catch(Y){console.error(`[Directive] onResolverError hook for module "${x?.id}" threw:`,Y);}}},onRetry:(e,n,s)=>k.emitResolverRetry(e,n,s),onCancel:(e,n)=>{k.emitResolverCancel(e,n),k.emitRequirementCanceled(n),R&&a.decrementInflight(n.id);},onResolutionComplete:()=>{ve(),de();},onRequeue:e=>{E.add(e);}}),te=new Set;function me(){for(let e of te)e();}let fe=d.history?$e({historyOption:d.history,facts:Q,store:I,onSnapshot:e=>{k.emitSnapshot(e),me();},onHistoryChange:(e,n)=>{k.emitHistoryNavigate(e,n),me();}}):Fe();u=fe;let ge=new Set;function ve(){for(let e of ge)e();}let pe=50,he=100,ye=0,$={isRunning:false,isReconciling:false,reconcileScheduled:false,isInitializing:false,isInitialized:false,isReady:false,isDestroyed:false,changedKeys:new Set,previousRequirements:new Re,readyPromise:null,readyResolve:null},oe=Ze({mergedConstraints:m,mergedResolvers:p,mergedDerive:S,mergedEffects:O,constraintsManager:b,resolversManager:A,derivationsManager:ee,effectsManager:ue,pluginManager:k,getState:()=>$,scheduleReconcile:de,maxDeferredRegistrations:he});function de(){!$.isRunning||$.reconcileScheduled||$.isInitializing||($.reconcileScheduled=true,ve(),queueMicrotask(()=>{$.reconcileScheduled=false,$.isRunning&&!$.isInitializing&&Se().catch(e=>{chunkDDUARSUH_cjs.f&&console.error("[Directive] Unexpected error in reconcile:",e);});}));}async function Se(){if($.isReconciling)return;if(ye++,ye>pe){chunkDDUARSUH_cjs.f&&console.warn(`[Directive] Reconcile loop exceeded ${pe} iterations. This usually means resolvers are creating circular requirement chains. Check that resolvers aren't mutating facts that re-trigger their own constraints.`),R&&a.drainPendingChanges(),$.previousRequirements=new Re,ye=0;return}$.isReconciling=true,ve();let e=R?a.startRun():0,n=a.currentTrace;if(n)for(let s of n.factChanges){let D=r[s.key];s.meta=D?._meta;}try{if($.changedKeys.size>0){if(F===null||W){let t=$.changedKeys,i=t.size<=5?`facts-changed:${[...t].join(",")}`:`facts-changed:${[...t].slice(0,5).join(",")}+${t.size-5}more`;fe.takeSnapshot(i);}W=!1;}let s=Q.$snapshot();k.emitReconcileStart(s),await ue.runEffects($.changedKeys);let D=new Set($.changedKeys);$.changedKeys.clear();let x=await b.evaluate(D),M=new Re;for(let t of x)M.add(t),k.emitRequirementCreated(t);if(n){let t=new Set(x.map(i=>i.fromConstraint));for(let i of t){let l=b.getState(i);if(l){let C=b.getDependencies(i);n.constraintsHit.push({id:i,priority:l.priority,deps:C?[...C]:[],meta:m[i]?.meta});}}}let{added:L,removed:Y}=M.diff($.previousRequirements);if(n){for(let t of L)n.requirementsAdded.push({id:t.id,type:t.requirement.type,fromConstraint:t.fromConstraint});for(let t of Y)n.requirementsRemoved.push({id:t.id,type:t.requirement.type,fromConstraint:t.fromConstraint});}for(let t of Y)A.cancel(t.id);for(let t of L)A.resolve(t);if(n){let t=A.getInflightInfo(),i=new Map(t.map(l=>[l.id,l]));for(let l of L){let T=i.get(l.id)?.resolverId??"unknown";n.resolversStarted.push({resolver:T,requirementId:l.id,meta:p[T]?.meta}),a.attributeResolverStart(l.id);}}if($.previousRequirements=M,E.size>0){for(let t of E)$.previousRequirements.remove(t);E.clear(),de();}let ne=A.getInflightInfo();if(d.plugins&&d.plugins.length>0){let t=Y.length>0?new Map(ne.map(l=>[l.id,l.resolverId])):void 0,i={unmet:x.filter(l=>!A.isResolving(l.id)),inflight:ne,completed:[],canceled:Y.map(l=>({id:l.id,resolverId:t?.get(l.id)??"unknown"}))};k.emitReconcileEnd(i);}$.isReady||($.isReady=!0,$.readyResolve&&($.readyResolve(),$.readyResolve=null));}finally{R&&a.finalizeCurrentRun(e),$.isReconciling=false,oe.flushDeferred(),ye=0,$.changedKeys.size>0&&de(),ve();}}function we(e,n){let s=P[e];if(s){K++,(F===null||F.has(e))&&(W=true);try{I.batch(()=>{s(Q,{type:e,...n});});}finally{K--;}}else chunkDDUARSUH_cjs.f&&console.warn(`[Directive] Unknown event type "${e}". No handler is registered for this event. Available events: ${Object.keys(P).join(", ")||"(none)"}`);}let o=Xe({mergedDerive:S,getDerivation:e=>ee.get(e),definitions:oe}),v=Ge({mergedEvents:P,dispatchEvent:we});function y(){let e=[];for(let[n,s]of _)e.push({type:"module",id:n,meta:s});for(let n of Object.keys(r)){let s=r[n]?._meta;s&&e.push({type:"fact",id:n,meta:s});}for(let[n,s]of B)e.push({type:"event",id:n,meta:s});for(let[n,s]of Object.entries(m))s.meta&&e.push({type:"constraint",id:n,meta:s.meta});for(let[n,s]of Object.entries(p))s.meta&&e.push({type:"resolver",id:n,meta:s.meta});for(let[n,s]of Object.entries(O)){let D=s.meta;D&&e.push({type:"effect",id:n,meta:D});}for(let n of Object.keys(S)){let s=ee.getMeta(n);s&&e.push({type:"derivation",id:n,meta:s});}return e}let q={facts:Q,history:fe.isEnabled?fe:null,derive:o,events:v,constraints:{disable:e=>b.disable(e),enable:e=>b.enable(e),isDisabled:e=>b.isDisabled(e),register:(e,n)=>{oe.register("constraint",e,n);},assign:(e,n)=>{oe.assign("constraint",e,n);},unregister:e=>{oe.unregister("constraint",e);},call:(e,n)=>oe.call("constraint",e,n),isDynamic:e=>oe.isDynamic("constraint",e),listDynamic:()=>oe.listDynamic("constraint")},effects:{disable:e=>ue.disable(e),enable:e=>ue.enable(e),isEnabled:e=>ue.isEnabled(e),register:(e,n)=>{oe.register("effect",e,n);},assign:(e,n)=>{oe.assign("effect",e,n);},unregister:e=>{oe.unregister("effect",e);},call:e=>oe.call("effect",e),isDynamic:e=>oe.isDynamic("effect",e),listDynamic:()=>oe.listDynamic("effect")},resolvers:{register:(e,n)=>{oe.register("resolver",e,n),c({[e]:n});},assign:(e,n)=>{oe.assign("resolver",e,n),c({[e]:n});},unregister:e=>{let n=p[e];n?.key&&typeof n.requirement=="string"&&b.removeRequirementKey(n.requirement),oe.unregister("resolver",e);},call:(e,n)=>oe.call("resolver",e,n),isDynamic:e=>oe.isDynamic("resolver",e),listDynamic:()=>oe.listDynamic("resolver")},get trace(){return a.getEntries()},meta:{module(e){return _.get(e)},fact(e){return r[e]?._meta},event(e){return B.get(e)},constraint(e){return m[e]?.meta},resolver(e){return p[e]?.meta},effect(e){return O[e]?.meta},derivation(e){return ee.getMeta(e)},byCategory(e){return y().filter(n=>n.meta.category===e)},byTag(e){return y().filter(n=>n.meta.tags?.includes(e))}},observe(e){if(k.getPlugins().filter(x=>x.name.startsWith("__observer_")).length>=100)return chunkDDUARSUH_cjs.f&&console.warn("[Directive] Maximum observer limit (100) reached. Call the unsubscribe function returned by observe() to clean up."),()=>{};let s=`__observer_${Date.now()}_${Math.random().toString(36).slice(2)}`,D={name:s,onInit:()=>e({type:"system.init"}),onStart:()=>e({type:"system.start"}),onStop:()=>e({type:"system.stop"}),onDestroy:()=>e({type:"system.destroy"}),onFactSet:(x,M,L)=>e({type:"fact.change",key:x,prev:L,next:M}),onConstraintEvaluate:(x,M)=>e({type:"constraint.evaluate",id:x,active:M}),onConstraintError:(x,M)=>e({type:"constraint.error",id:x,error:M}),onRequirementCreated:x=>e({type:"requirement.created",id:x.id,requirementType:x.requirement.type}),onRequirementMet:(x,M)=>e({type:"requirement.met",id:x.id,byResolver:M}),onRequirementCanceled:x=>e({type:"requirement.canceled",id:x.id}),onResolverStart:(x,M)=>e({type:"resolver.start",resolver:x,requirementId:M.id}),onResolverComplete:(x,M,L)=>e({type:"resolver.complete",resolver:x,requirementId:M.id,duration:L}),onResolverError:(x,M,L)=>e({type:"resolver.error",resolver:x,requirementId:M.id,error:L}),onEffectRun:x=>e({type:"effect.run",id:x}),onEffectError:(x,M)=>e({type:"effect.error",id:x,error:M}),onDerivationCompute:(x,M)=>e({type:"derivation.compute",id:x,value:M}),onReconcileStart:()=>e({type:"reconcile.start"}),onReconcileEnd:x=>{let M=x;e({type:"reconcile.end",resolversCompleted:Array.isArray(M.completed)?M.completed.length:0,resolversCanceled:Array.isArray(M.canceled)?M.canceled.length:0});}};return k.register(D),()=>k.unregister(s)},initialize(){if(!$.isInitialized){$.isInitializing=true;for(let e of d.modules)e.init&&I.batch(()=>{e.init(Q);});d.onAfterModuleInit&&I.batch(()=>{d.onAfterModuleInit();}),$.isInitializing=false,$.isInitialized=true;for(let e of Object.keys(S))ee.get(e);}},start(){if(!$.isRunning){$.isInitialized||this.initialize(),$.isRunning=true;for(let e of d.modules)e.hooks?.onStart?.(q);if(k.emitStart(q),d.errorBoundary?.retryLater&&!X){let e=Math.max(d.errorBoundary.retryLater.delayMs??1e3,250);X=setInterval(()=>{let n=H.processDueRetries();for(let s of n)s.callback?s.callback():de();},Math.min(e,500));}de();}},stop(){if($.isRunning){$.isRunning=false,X!==null&&(clearInterval(X),X=null),H.getRetryLaterManager().clearAll(),A.cancelAll(),ue.cleanupAll();for(let e of d.modules)e.hooks?.onStop?.(q);k.emitStop(q);}},destroy(){$.isDestroyed||(this.stop(),$.isDestroyed=true,I.destroy?.(),A.destroy(),H.clearErrors(),ge.clear(),te.clear(),a.destroy(),oe.destroy(),_.clear(),B.clear(),E.clear(),k.emitDestroy(q));},dispatch(e){chunkDDUARSUH_cjs.l.has(e.type)||we(e.type,e);},read(e){return ee.get(e)},subscribe(e,n){let s=[],D=[];for(let M of e)M in S?s.push(M):M in r?D.push(M):chunkDDUARSUH_cjs.f&&console.warn(`[Directive] subscribe: unknown key "${M}"`);let x=[];return s.length>0&&x.push(ee.subscribe(s,n)),D.length>0&&x.push(I.subscribe(D,n)),()=>{for(let M of x)M();}},watch(e,n,s){let D=s?.equalityFn?(M,L)=>s.equalityFn(M,L):(M,L)=>Object.is(M,L);if(e in S){let M=ee.get(e);return ee.subscribe([e],()=>{let L=ee.get(e);if(!D(L,M)){let Y=M;M=L,n(L,Y);}})}chunkDDUARSUH_cjs.f&&(e in r||console.warn(`[Directive] watch: unknown key "${e}"`));let x=I.get(e);return I.subscribe([e],()=>{let M=I.get(e);if(!D(M,x)){let L=x;x=M,n(M,L);}})},when(e,n){return new Promise((s,D)=>{let x=I.toObject();if(e(x)){s();return}let M,L,Y=()=>{M?.(),L!==void 0&&clearTimeout(L);};M=I.subscribeAll(()=>{let ne=I.toObject();e(ne)&&(Y(),s());}),n?.timeout!==void 0&&n.timeout>0&&(L=setTimeout(()=>{Y(),D(new Error(`[Directive] when: timed out after ${n.timeout}ms`));},n.timeout));})},inspect(){return {unmet:$.previousRequirements.all(),inflight:A.getInflightInfo(),facts:Object.keys(r).map(e=>({key:e,meta:r[e]?._meta})),events:Object.keys(P).map(e=>({name:e,meta:B.get(e)})),constraints:b.getAllStates().map(e=>({id:e.id,active:e.lastResult??false,disabled:b.isDisabled(e.id),priority:e.priority,hitCount:e.hitCount,lastActiveAt:e.lastActiveAt,meta:m[e.id]?.meta})),resolvers:Object.fromEntries(A.getInflight().map(e=>[e,A.getStatus(e)])),resolverDefs:Object.entries(p).map(([e,n])=>({id:e,requirement:typeof n.requirement=="string"?n.requirement:"(predicate)",meta:n.meta})),effects:Object.entries(O).map(([e,n])=>({id:e,meta:n.meta})),derivations:Object.keys(S).map(e=>({id:e,meta:ee.getMeta(e)})),modules:d.modules.map(e=>({id:e.id,meta:_.get(e.id)})),traceEnabled:R,...R?{trace:structuredClone(a.getEntries()??[])}:{}}},explain(e){let s=$.previousRequirements.all().find(C=>C.id===e);if(!s)return null;let D=b.getState(s.fromConstraint),x=A.getStatus(e),M={},L=b.getDependencies(s.fromConstraint);if(L)for(let C of L)M[C]=I.get(C);else for(let[C,T]of Object.entries(I.toObject()))M[C]=T;let Y=m[s.fromConstraint],ne=Y?.meta?.label??s.fromConstraint,t=[`Requirement "${s.requirement.type}" (id: ${s.id})`,`\u251C\u2500 Produced by constraint: ${ne}`,`\u251C\u2500 Constraint priority: ${D?.priority??0}`,`\u251C\u2500 Constraint active: ${D?.lastResult??"unknown"}`,`\u251C\u2500 Resolver status: ${x.state}`];Y?.meta?.description&&t.push(`\u251C\u2500 Description: ${Y.meta.description}`);let i=Object.entries(s.requirement).filter(([C])=>C!=="type").map(([C,T])=>`${C}=${JSON.stringify(T)}`).join(", ");i&&t.push(`\u251C\u2500 Requirement payload: { ${i} }`);let l=Object.entries(M).slice(0,10);return l.length>0&&(t.push("\u2514\u2500 Relevant facts:"),l.forEach(([C,T],Z)=>{let se=Z===l.length-1?" \u2514\u2500":" \u251C\u2500",ae=typeof T=="object"?JSON.stringify(T):String(T);t.push(`${se} ${C} = ${ae.slice(0,50)}${ae.length>50?"...":""}`);})),t.join(`
2
- `)},getOriginal(e,n){return oe.getOriginal(e,n)},restoreOriginal(e,n){return oe.restoreOriginal(e,n)},async settle(e=5e3){let n=()=>A.getInflightCount()===0&&!$.isReconciling&&!$.reconcileScheduled&&!A.hasPendingBatches();if(A.hasPendingBatches()&&A.processBatches(),await new Promise(s=>queueMicrotask(s)),!n())return new Promise((s,D)=>{let x=false,M=()=>{x||(x=true,clearTimeout(L),Y());},L=setTimeout(()=>{M();let ne=[],t=A.getInflightInfo();t.length>0&&ne.push(`${t.length} resolvers inflight: ${t.map(l=>l.resolverId).join(", ")}`),$.isReconciling&&ne.push("reconciliation in progress"),$.reconcileScheduled&&ne.push("reconcile scheduled");let i=$.previousRequirements.all();i.length>0&&ne.push(`${i.length} unmet requirements: ${i.map(l=>l.requirement.type).join(", ")}`),D(new Error(`[Directive] settle() timed out after ${e}ms. ${ne.join("; ")}`));},e),Y=this.onSettledChange(()=>{A.hasPendingBatches()&&A.processBatches(),queueMicrotask(()=>{!x&&n()&&(M(),s());});});})},getSnapshot(){return {facts:I.toObject(),version:1}},getDistributableSnapshot(e={}){let{includeDerivations:n,excludeDerivations:s,includeFacts:D,ttlSeconds:x,metadata:M,includeVersion:L}=e,Y={},ne=Object.keys(S),t=new Set(ne),i;if(n){if(i=n.filter(T=>t.has(T)),chunkDDUARSUH_cjs.f){let T=n.filter(Z=>!t.has(Z));T.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${T.join(", ")}. Available: ${ne.join(", ")||"(none)"}`);}}else i=ne;if(s){let T=new Set(s);i=i.filter(Z=>!T.has(Z));}for(let T of i)try{Y[T]=ee.get(T);}catch(Z){chunkDDUARSUH_cjs.f&&console.warn(`[Directive] getDistributableSnapshot: Skipping derivation "${T}" due to error:`,Z);}if(D&&D.length>0){let T=I.toObject(),Z=Object.keys(T);if(chunkDDUARSUH_cjs.f){let se=D.filter(ae=>!(ae in T));se.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${se.join(", ")}. Available: ${Z.join(", ")||"(none)"}`);}for(let se of D)se in T&&(Y[se]=T[se]);}let l=Date.now(),C={data:Y,createdAt:l};return x!==void 0&&x>0&&(C.expiresAt=l+x*1e3),L&&(C.version=chunkBEJ6ICA7_cjs.e(Y)),M&&(C.metadata=M),C},watchDistributableSnapshot(e,n){let{includeDerivations:s,excludeDerivations:D}=e,x=Object.keys(S),M;if(s?M=s.filter(ne=>x.includes(ne)):M=x,D){let ne=new Set(D);M=M.filter(t=>!ne.has(t));}if(M.length===0)return chunkDDUARSUH_cjs.f&&console.warn("[Directive] watchDistributableSnapshot: No derivations to watch. Callback will never be called."),()=>{};let Y=this.getDistributableSnapshot({...e,includeVersion:true}).version;return ee.subscribe(M,()=>{let ne=this.getDistributableSnapshot({...e,includeVersion:true});ne.version!==Y&&(Y=ne.version,n(ne));})},restore(e){if(!e||typeof e!="object")throw new Error("[Directive] restore() requires a valid snapshot object");if(!e.facts||typeof e.facts!="object")throw new Error("[Directive] restore() snapshot must have a facts object");if(!chunkBEJ6ICA7_cjs.c(e))throw new Error("[Directive] restore() rejected: snapshot contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");I.batch(()=>{for(let[n,s]of Object.entries(e.facts))chunkDDUARSUH_cjs.l.has(n)||I.set(n,s);});},onSettledChange(e){return ge.add(e),()=>{ge.delete(e);}},onHistoryChange(e){return te.add(e),()=>{te.delete(e);}},batch(e){I.batch(e);},get isSettled(){return A.getInflightCount()===0&&!A.hasPendingBatches()&&!$.isReconciling&&!$.reconcileScheduled},get isRunning(){return $.isRunning},get isInitialized(){return $.isInitialized},get isReady(){return $.isReady},whenReady(){return $.isReady?Promise.resolve():$.isRunning?($.readyPromise||($.readyPromise=new Promise(e=>{$.readyResolve=e;})),$.readyPromise):Promise.reject(new Error("[Directive] whenReady() called before start(). Call system.start() first, then await system.whenReady()."))}};function z(e){if($.isReconciling)throw new Error(`[Directive] Cannot register module "${e.id}" during reconciliation. Wait for the current reconciliation cycle to complete.`);if($.isDestroyed)throw new Error(`[Directive] Cannot register module "${e.id}" on a destroyed system.`);let n=(s,D)=>{if(s)for(let x of Object.keys(s)){if(chunkDDUARSUH_cjs.l.has(x))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${x}" in ${D}.`);if(D==="schema"&&x.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${x}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let s of Object.keys(e.schema))if(s in r)throw new Error(`[Directive] Schema collision: Fact "${s}" already exists. Cannot register module "${e.id}".`);if(chunkDDUARSUH_cjs.f&&e.derive){let s=new Set(Object.keys(r));for(let D of Object.keys(e.derive))s.has(D)&&console.warn(`[Directive] "${D}" exists as both a fact and a derivation after registering module "${e.id}".`);}if(e.history?.snapshotEvents){F===null&&(F=new Set(Object.keys(P)));for(let s of e.history.snapshotEvents)F.add(s);}else if(F!==null&&e.events)for(let s of Object.keys(e.events))F.add(s);Object.assign(r,e.schema);for(let s of Object.values(e.schema)){let D=s;D._meta&&(D._meta=le(D._meta));}if(e.events){for(let[s,D]of Object.entries(e.events))if(typeof D=="object"&&D!==null&&Object.hasOwn(D,"handler")){let x=D;if(e.events[s]=x.handler,x.meta){let M=le(x.meta);M&&B.set(s,M);}}Object.assign(P,e.events);}if(e.derive&&(Object.assign(S,e.derive),ee.registerDefinitions(e.derive)),e.effects){for(let s of Object.values(e.effects)){let D=s;D.meta&&(D.meta=le(D.meta));}Object.assign(O,e.effects),ue.registerDefinitions(e.effects);}if(e.constraints){for(let s of Object.values(e.constraints)){let D=s;D.meta&&(D.meta=le(D.meta));}Object.assign(m,e.constraints),b.registerDefinitions(e.constraints);}if(e.resolvers){for(let s of Object.values(e.resolvers)){let D=s;D.meta&&(D.meta=le(D.meta));}Object.assign(p,e.resolvers);for(let s of Object.keys(e.resolvers))U.set(s,e);A.registerDefinitions(e.resolvers),c(e.resolvers);}if(I.registerKeys(e.schema),e.meta){let s=le(e.meta);s&&_.set(e.id,s);}d.modules.push(e),e.init&&I.batch(()=>{e.init(Q);}),e.hooks?.onInit?.(q),$.isRunning&&(e.hooks?.onStart?.(q),de());}q.registerModule=z,k.emitInit(q);for(let e of d.modules)e.hooks?.onInit?.(q);return q}exports.a=Ie;exports.b=De;exports.c=Qe;exports.d=et;exports.e=tt;exports.f=nt;exports.g=ht;exports.h=St;exports.i=$e;exports.j=Fe;exports.k=it;exports.l=xt;exports.m=It;exports.n=qt;exports.o=Re;exports.p=Be;exports.q=_e;exports.r=We;exports.s=at;exports.t=ze;exports.u=ut;exports.v=ft;exports.w=He;exports.x=Le;exports.y=Je;exports.z=bn;//# sourceMappingURL=chunk-TUS5WDVE.cjs.map
3
- //# sourceMappingURL=chunk-TUS5WDVE.cjs.map