@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
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/schema-builders.ts","../src/core/module.ts","../src/utils/requirement-status.ts","../src/utils/system-with-status.ts","../src/core/clock.ts","../src/core/timer.ts","../src/index.ts"],"names":["createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","value","v","intermediate","desc","predicate","message","newRefinements","m","unionImpl","types","typeNames","schemaType","t","createChainableString","fm","n","regex","createChainableNumber","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","i","validator","createChainableObject","shapeSchema","key","schemaT","keys","k","values","dev_true_default","valueSet","innerType","innerTypeName","valueType","valueTypeName","val","uuidRegex","emailRegex","validateModuleId","id","validateKeyAlignment","implKeys","schemaKeys","implLabel","schemaLabel","missingImplMessage","validateSnapshotEvents","snapshotEvents","schemaEvents","schemaEventKeys","eventName","validateResolverRequirements","resolvers","requirements","requirementTypes","resolverName","resolver","resolverDef","validateModuleConfig","config","createModule","crossModuleDeps","createModuleFactory","name","createRequirementStatusPlugin","state","notify","listener","getOrCreateSet","map","type","set","getStatus","pendingSet","inflightSet","failedSet","lastError","getAllStatus","allTypes","result","subscribe","reset","req","_resolver","error","createStatusHook","statusPlugin","createSystemWithStatus","options","allPlugins","createSystem","realClock","cb","ms","handle","virtualClock","initialMs","nowMs","nextId","queue","entry","targetMs","ready","e","a","b","next","defaultClock","initialTimerState","elapsedMs","remainingMs","totalMs","startTimer","pauseTimer","resumeTimer","pausedFor","resetTimer","completeTimer","registerRepeat","tickTimer","opts","elapsed","timerOps","Backoff"],"mappings":"8hBAuCA,SAASA,EACPC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CACAC,EACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACuB,CACvB,OAAO,CACL,KAAA,CAAO,MAAA,CACP,YAAaN,CAAAA,CACb,SA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AAAA,CAAOgC,CAAK,CAAA,CAEtC,OAAIuB,EAAK,IAAA,GAAS,IAAA,CAET,CAAE,IAAA,CAAM,OAAQ,EAGrBA,CAAAA,CAAK,IAAA,GAAS,QAAA,CACZC,CAAAA,EAAWD,EAAK,EAAA,CAAW,CAAE,IAAA,CAAM,QAAS,EACzC,CAAE,IAAA,CAAM,OAAQ,CAAA,CAIrBC,GAAWD,CAAAA,CAAK,EAAA,CAAW,CAAE,IAAA,CAAM,UAAW,CAAA,CAC3C,CAAE,IAAA,CAAM,OAAQ,CACzB,CAsCO,SAASE,EAAAA,CAASF,CAAAA,CAAqB,CAC5C,OAAO,CACL,OAAA,CAASZ,CAAAA,CACT,MAAOI,CAAAA,CACP,KAAA,CAAOC,EACP,MAAA,CAAQC,CAAAA,CACR,MAAOE,CAAAA,CACP,QAAA,CAAUC,CAAAA,CACV,cAAA,CAAiBpD,GAA0BqD,CAAAA,CAAerD,CAAAA,CAAOuD,CAAAA,CAAK,EAAE,EACxE,IAAA,CAAM,CAACvD,CAAAA,CAAuBgC,CAAAA,GAAkBsB,EAAUtD,CAAAA,CAAOgC,CAAAA,CAAOuB,CAAI,CAAA,CAC5E,UAAAX,CAAAA,CACA,WAAA,CAAa,CAAC5C,CAAAA,CAAuBgC,IACnCa,CAAAA,CAAY7C,CAAAA,CAAOgC,CAAAA,CAAOuB,CAAAA,CAAK,EAAE,CACrC,CACF,CC5HO,IAAMG,GAAU,CAErB,IAAA,CAAM,OAEN,MAAA,CAAQ,QAAA,CAER,YAAa,aACf","file":"index.js","sourcesContent":["/**\n * Schema Type Builders\n *\n * Provides type-safe schema definitions with optional runtime validation.\n * Used to define fact types, derivation types, event payload types, etc.\n *\n * This module has no dependency on the facts store or tracking system.\n */\n\nimport isDevelopment from \"#is-development\";\nimport type { SchemaType } from \"./types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/** Brand symbol for branded types */\ndeclare const Brand: unique symbol;\n\n/** Branded type - adds a unique brand to a base type */\nexport type Branded<T, B extends string> = T & { readonly [Brand]: B };\n\n/** Extended SchemaType with type name for better error messages */\nexport interface ExtendedSchemaType<T> extends SchemaType<T> {\n readonly _typeName?: string;\n readonly _default?: T | (() => T);\n readonly _transform?: (value: unknown) => T;\n readonly _description?: string;\n readonly _refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>;\n /** Mutable - set by array validators to indicate which element failed */\n _lastFailedIndex?: number;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n readonly _meta?: import(\"./types/meta.js\").DefinitionMeta;\n}\n\n/** Create a schema type builder with optional type name */\nfunction createSchemaType<T>(\n validators: Array<(v: T) => boolean> = [],\n typeName?: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n meta?: import(\"./types/meta.js\").DefinitionMeta,\n): ExtendedSchemaType<T> {\n return {\n _type: undefined as unknown as T,\n _validators: validators,\n _typeName: typeName,\n _default: defaultValue,\n _transform: transform,\n _description: description,\n _refinements: refinements,\n _meta: meta,\n validate(fn: (value: T) => boolean) {\n return createSchemaType(\n [...validators, fn],\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n meta,\n );\n },\n };\n}\n\n/** Chainable schema type with all common methods */\nexport interface ChainableSchemaType<T> extends ExtendedSchemaType<T> {\n default(value: T | (() => T)): ChainableSchemaType<T>;\n transform<U>(fn: (value: T) => U): ChainableSchemaType<U>;\n brand<B extends string>(): ChainableSchemaType<Branded<T, B>>;\n describe(description: string): ChainableSchemaType<T>;\n refine(\n predicate: (value: T) => boolean,\n message: string,\n ): ChainableSchemaType<T>;\n nullable(): ChainableSchemaType<T | null>;\n optional(): ChainableSchemaType<T | undefined>;\n /** Attach metadata for debugging and devtools. */\n meta(\n meta: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableSchemaType<T>;\n}\n\n/** Create a chainable schema type with common methods */\nfunction createChainableType<T>(\n validators: Array<(v: T) => boolean>,\n typeName: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n fieldMeta?: import(\"./types/meta.js\").DefinitionMeta,\n): ChainableSchemaType<T> {\n const base = createSchemaType<T>(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n return {\n ...base,\n default(value: T | (() => T)) {\n return createChainableType(\n validators,\n typeName,\n value,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n },\n transform<U>(fn: (value: T) => U) {\n const newTransform = (v: unknown) => {\n const intermediate = transform ? transform(v) : (v as T);\n return fn(intermediate);\n };\n return createChainableType<U>(\n [],\n typeName,\n undefined,\n newTransform as (v: unknown) => U,\n description,\n undefined,\n fieldMeta,\n );\n },\n brand<B extends string>() {\n return createChainableType<Branded<T, B>>(\n validators as Array<(v: Branded<T, B>) => boolean>,\n `Branded<${typeName}>`,\n defaultValue as Branded<T, B> | (() => Branded<T, B>),\n transform as (value: unknown) => Branded<T, B>,\n description,\n refinements as Array<{\n predicate: (value: Branded<T, B>) => boolean;\n message: string;\n }>,\n fieldMeta,\n );\n },\n describe(desc: string) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n desc,\n refinements,\n fieldMeta,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [...(refinements ?? []), { predicate, message }];\n return createChainableType(\n [...validators, predicate],\n typeName,\n defaultValue,\n transform,\n description,\n newRefinements,\n fieldMeta,\n );\n },\n nullable() {\n return createChainableType<T | null>(\n [\n (v): v is T | null =>\n v === null || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | null`,\n defaultValue as (T | null) | (() => T | null),\n transform as (value: unknown) => T | null,\n description,\n undefined,\n fieldMeta,\n );\n },\n optional() {\n return createChainableType<T | undefined>(\n [\n (v): v is T | undefined =>\n v === undefined || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | undefined`,\n defaultValue as (T | undefined) | (() => T | undefined),\n transform as (value: unknown) => T | undefined,\n description,\n undefined,\n fieldMeta,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n}\n\n/**\n * Two-form union schema constructor.\n *\n * Hoisted out of the `t` object literal because the overload-cast pattern\n * (`(impl) as { ovl1; ovl2 }`) inside an object literal triggers a TS\n * declaration-emit \"implicitly has type any\" cycle. Annotating the const\n * with the explicit overload type breaks the cycle so DTS can emit `t`'s\n * shape without recursing through the runtime expression.\n *\n * @internal\n */\ntype UnionFn = {\n <T = unknown>(): ChainableSchemaType<T>;\n <T extends SchemaType<unknown>[]>(\n ...types: T\n ): ChainableSchemaType<T[number] extends SchemaType<infer U> ? U : never>;\n};\n\nconst unionImpl: UnionFn = (<T extends SchemaType<unknown>[]>(...types: T) => {\n if (types.length === 0) {\n return createChainableType<unknown>([], \"union\");\n }\n type UnionType = T[number] extends SchemaType<infer U> ? U : never;\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<UnionType>(\n [\n (v): v is UnionType =>\n types.some((schemaType) =>\n schemaType._validators.every((fn) => fn(v)),\n ),\n ],\n typeNames.join(\" | \"),\n );\n}) as UnionFn;\n\n/**\n * Schema type builders for defining fact types.\n *\n * @remarks\n * Each builder returns a chainable {@link ExtendedSchemaType} with validation\n * methods (`.min()`, `.max()`, `.pattern()`, etc.) and dev-mode runtime\n * type checking. Validators are tree-shaken in production builds.\n *\n * @example\n * ```typescript\n * const module = createModule(\"example\", {\n * schema: {\n * name: t.string(),\n * age: t.number().min(0).max(150),\n * active: t.boolean(),\n * tags: t.array<string>().of(t.string()),\n * user: t.object<{ id: string; email: string }>(),\n * },\n * });\n * ```\n *\n * @public\n */\nexport const t = {\n /**\n * Create a string schema type.\n *\n * @example\n * ```typescript\n * // Basic string\n * schema: { name: t.string() }\n *\n * // String literal union (for type safety)\n * schema: { phase: t.string<\"red\" | \"green\" | \"yellow\">() }\n *\n * // With custom validation\n * schema: { email: t.string().validate(s => s.includes(\"@\")) }\n *\n * // With transform\n * schema: { trimmed: t.string().transform(s => s.trim()) }\n *\n * // With brand\n * schema: { userId: t.string().brand<\"UserId\">() }\n * ```\n */\n string<T extends string = string>() {\n type ChainableString = ChainableSchemaType<T> & {\n minLength(n: number): ChainableString;\n maxLength(n: number): ChainableString;\n pattern(regex: RegExp): ChainableString;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableString;\n };\n\n const createChainableString = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableString => {\n const chainable = createChainableType<T>(\n validators,\n \"string\",\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n return {\n ...chainable,\n minLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length >= n],\n defaultValue, transform, description, refinements, fm,\n );\n },\n maxLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length <= n],\n defaultValue, transform, description, refinements, fm,\n );\n },\n pattern(regex: RegExp) {\n return createChainableString(\n [...validators, (v) => regex.test(v as string)],\n defaultValue, transform, description, refinements, fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableString(\n validators, value, transform, description, refinements, fm,\n );\n },\n describe(desc: string) {\n return createChainableString(\n validators, defaultValue, transform, desc, refinements, fm,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableString(\n [...validators, predicate],\n defaultValue, transform, description, newRefinements, fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableString(\n validators, defaultValue, transform, description, refinements, m,\n );\n },\n };\n };\n\n return createChainableString([(v): v is T => typeof v === \"string\"]);\n },\n\n /**\n * Create a number schema type with optional min/max constraints.\n *\n * @example\n * ```typescript\n * // Basic number\n * schema: { count: t.number() }\n *\n * // With range constraints\n * schema: { age: t.number().min(0).max(150) }\n *\n * // With custom validation\n * schema: { even: t.number().validate(n => n % 2 === 0) }\n *\n * // With default\n * schema: { count: t.number().default(0) }\n *\n * // With transform (from string)\n * schema: { age: t.number().transform(v => parseInt(String(v), 10)) }\n * ```\n */\n number() {\n type ChainableNumber = ChainableSchemaType<number> & {\n min(n: number): ChainableNumber;\n max(n: number): ChainableNumber;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableNumber;\n };\n\n const createChainableNumber = (\n validators: Array<(v: number) => boolean>,\n defaultValue?: number | (() => number),\n transform?: (value: unknown) => number,\n description?: string,\n refinements?: Array<{\n predicate: (value: number) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableNumber => {\n const chainable = createChainableType<number>(\n validators, \"number\", defaultValue, transform, description, refinements, fm,\n );\n return {\n ...chainable,\n min(n: number) {\n return createChainableNumber(\n [...validators, (v) => v >= n],\n defaultValue, transform, description, refinements, fm,\n );\n },\n max(n: number) {\n return createChainableNumber(\n [...validators, (v) => v <= n],\n defaultValue, transform, description, refinements, fm,\n );\n },\n default(value: number | (() => number)) {\n return createChainableNumber(\n validators, value, transform, description, refinements, fm,\n );\n },\n describe(desc: string) {\n return createChainableNumber(\n validators, defaultValue, transform, desc, refinements, fm,\n );\n },\n refine(predicate: (value: number) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableNumber(\n [...validators, predicate],\n defaultValue, transform, description, newRefinements, fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableNumber(\n validators, defaultValue, transform, description, refinements, m,\n );\n },\n };\n };\n return createChainableNumber([(v) => typeof v === \"number\"]);\n },\n\n /**\n * Create a boolean schema type.\n *\n * @example\n * ```typescript\n * schema: {\n * active: t.boolean(),\n * verified: t.boolean().default(false),\n * }\n * ```\n */\n boolean() {\n return createChainableType<boolean>(\n [(v) => typeof v === \"boolean\"],\n \"boolean\",\n );\n },\n\n /**\n * Create an array schema type.\n * Can be used with or without element validation:\n * - `t.array<string>()` - Type-only, no element validation\n * - `t.array<string>().of(t.string())` - With element validation\n */\n array<T>() {\n type ChainableArray = ChainableSchemaType<T[]> & {\n of(elementType: SchemaType<T>): ChainableArray;\n nonEmpty(): ChainableArray;\n maxLength(n: number): ChainableArray;\n minLength(n: number): ChainableArray;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableArray;\n _lastFailedIndex?: number;\n };\n\n const createChainableArray = (\n validators: Array<(v: T[]) => boolean>,\n elementType?: SchemaType<T>,\n defaultValue?: T[] | (() => T[]),\n description?: string,\n indexRef?: { value: number },\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableArray => {\n const chainable = createChainableType<T[]>(\n validators,\n \"array\",\n defaultValue,\n undefined,\n description,\n undefined,\n fm,\n );\n // Use ref for storing failed index (shared with validator closure)\n const ref = indexRef ?? { value: -1 };\n const result: ChainableArray = {\n ...chainable,\n get _lastFailedIndex() {\n return ref.value;\n },\n set _lastFailedIndex(v: number) {\n ref.value = v;\n },\n of(et: SchemaType<T>) {\n const newRef = { value: -1 };\n return createChainableArray(\n [...validators, (v) => {\n for (let i = 0; i < v.length; i++) {\n if (!et._validators.every((validator) => validator(v[i]))) {\n newRef.value = i;\n return false;\n }\n }\n return true;\n }],\n et, defaultValue, description, newRef, fm,\n );\n },\n nonEmpty() {\n return createChainableArray(\n [...validators, (v) => v.length > 0],\n elementType, defaultValue, description, ref, fm,\n );\n },\n maxLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length <= n],\n elementType, defaultValue, description, ref, fm,\n );\n },\n minLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length >= n],\n elementType, defaultValue, description, ref, fm,\n );\n },\n default(value: T[] | (() => T[])) {\n return createChainableArray(\n validators, elementType, value, description, ref, fm,\n );\n },\n describe(desc: string) {\n return createChainableArray(\n validators, elementType, defaultValue, desc, ref, fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableArray(\n validators, elementType, defaultValue, description, ref, m,\n );\n },\n };\n return result;\n };\n return createChainableArray([(v) => Array.isArray(v)]);\n },\n\n /**\n * Create an object schema type for any complex value.\n * Can be used with or without shape validation:\n * - `t.object<User>()` - Type-only, no property validation\n * - `t.object<User>().shape({ name: t.string(), age: t.number() })` - With property validation\n *\n * For arrays, prefer `t.array<T>()` which adds `Array.isArray` validation.\n */\n object<T>() {\n type ChainableObject = ChainableSchemaType<T> & {\n shape(schema: { [K in keyof T]?: SchemaType<T[K]> }): ChainableObject;\n nonNull(): ChainableObject;\n hasKeys(...keys: string[]): ChainableObject;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableObject;\n };\n\n const createChainableObject = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n description?: string,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableObject => {\n const chainable = createChainableType<T>(\n validators, \"object\", defaultValue, undefined, description, undefined, fm,\n );\n return {\n ...chainable,\n shape(shapeSchema: { [K in keyof T]?: SchemaType<T[K]> }) {\n return createChainableObject(\n [...validators, (v) => {\n for (const [key, schemaType] of Object.entries(shapeSchema)) {\n const value = (v as Record<string, unknown>)[key];\n const schemaT = schemaType as SchemaType<unknown>;\n if (schemaT && !schemaT._validators.every((validator) => validator(value))) {\n return false;\n }\n }\n return true;\n }],\n defaultValue, description, fm,\n );\n },\n nonNull() {\n return createChainableObject(\n [...validators, (v) => v !== null && v !== undefined],\n defaultValue, description, fm,\n );\n },\n hasKeys(...keys: string[]) {\n return createChainableObject(\n [...validators, (v) => keys.every((k) => k in (v as Record<string, unknown>))],\n defaultValue, description, fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableObject(validators, value, description, fm);\n },\n describe(desc: string) {\n return createChainableObject(validators, defaultValue, desc, fm);\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableObject(validators, defaultValue, description, m);\n },\n };\n };\n return createChainableObject([\n (v) => typeof v === \"object\" && v !== null && !Array.isArray(v),\n ]);\n },\n\n /**\n * Create an enum schema type for string literal unions.\n *\n * @example\n * ```typescript\n * // Define allowed values\n * schema: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") }\n *\n * // Type is inferred as \"idle\" | \"loading\" | \"success\" | \"error\"\n * ```\n */\n enum<T extends string>(...values: T[]) {\n if (isDevelopment && values.length === 0) {\n console.warn(\n \"[Directive] t.enum() called with no values - this will reject all strings\",\n );\n }\n const valueSet = new Set(values);\n return createChainableType<T>(\n [(v): v is T => typeof v === \"string\" && valueSet.has(v as T)],\n `enum(${values.join(\"|\")})`,\n );\n },\n\n /**\n * Create a literal schema type for exact value matching.\n *\n * @example\n * ```typescript\n * // Exact string match\n * schema: { type: t.literal(\"user\") }\n *\n * // Exact number match\n * schema: { version: t.literal(1) }\n *\n * // Exact boolean\n * schema: { enabled: t.literal(true) }\n * ```\n */\n literal<T extends string | number | boolean>(value: T) {\n return createChainableType<T>(\n [(v): v is T => v === value],\n `literal(${String(value)})`,\n );\n },\n\n /**\n * Create a nullable schema type (T | null).\n *\n * @example\n * ```typescript\n * // Nullable string\n * schema: { name: t.nullable(t.string()) }\n *\n * // Nullable object\n * schema: { user: t.nullable(t.object<User>()) }\n * ```\n */\n nullable<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | null>(\n [\n (v): v is T | null => {\n if (v === null) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | null`,\n ) as SchemaType<T | null>;\n },\n\n /**\n * Create an optional schema type (T | undefined).\n *\n * @example\n * ```typescript\n * // Optional string\n * schema: { nickname: t.optional(t.string()) }\n *\n * // Optional number\n * schema: { age: t.optional(t.number()) }\n * ```\n */\n optional<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | undefined>(\n [\n (v): v is T | undefined => {\n if (v === undefined) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | undefined`,\n ) as SchemaType<T | undefined>;\n },\n\n /**\n * Create a union schema type.\n *\n * **Two forms:**\n * - `t.union(t.string(), t.number())` — variadic schema args; the runtime\n * validator checks that the value matches at least one inner schema.\n * - `t.union<string | number | boolean>()` — generic-only form with no\n * schema args; the runtime validator accepts ANY value (mirrors\n * {@link unknown} plus generic narrowing). Use this for polymorphic\n * payloads where the union is too dynamic to enumerate as inner schemas\n * (e.g. an `UPDATE_FIELD` event whose `value` may be `string | number |\n * boolean | Date`).\n *\n * Chainable methods (`.validate`, `.transform`, `.default`, `.describe`,\n * `.refine`, `.optional`, `.nullable`) work the same for both forms.\n *\n * @example\n * ```typescript\n * // Variadic — runtime validation against inner schemas\n * schema: { value: t.union(t.string(), t.number()) }\n *\n * // Generic-only — type-only narrowing, runtime accepts any value\n * schema: {\n * payload: t.union<string | number | boolean>(),\n * }\n *\n * // Add a custom predicate via .validate when you still want a runtime check\n * schema: {\n * strict: t.union<string | number>().validate(\n * (v) => typeof v === \"string\" || typeof v === \"number\",\n * ),\n * }\n * ```\n */\n union: unionImpl,\n\n /**\n * Create a record schema type for dynamic key-value maps.\n *\n * @example\n * ```typescript\n * // Record with string values\n * schema: { metadata: t.record(t.string()) }\n *\n * // Record with number values\n * schema: { scores: t.record(t.number()) }\n * ```\n */\n record<V>(valueType: SchemaType<V>) {\n const valueTypeName =\n (valueType as ExtendedSchemaType<V>)._typeName ?? \"unknown\";\n return createChainableType<Record<string, V>>(\n [\n (v): v is Record<string, V> => {\n if (typeof v !== \"object\" || v === null || Array.isArray(v))\n return false;\n return Object.values(v).every((val) =>\n valueType._validators.every((validator) => validator(val)),\n );\n },\n ],\n `Record<string, ${valueTypeName}>`,\n );\n },\n\n /**\n * Create a tuple schema type for fixed-length arrays with specific types.\n *\n * @example\n * ```typescript\n * // [string, number] tuple\n * schema: { coord: t.tuple(t.string(), t.number()) }\n *\n * // [x, y, z] coordinates\n * schema: { position: t.tuple(t.number(), t.number(), t.number()) }\n * ```\n */\n tuple<T extends SchemaType<unknown>[]>(...types: T) {\n if (isDevelopment && types.length === 0) {\n console.warn(\n \"[Directive] t.tuple() called with no types - this will only accept empty arrays\",\n );\n }\n type TupleType = {\n [K in keyof T]: T[K] extends SchemaType<infer U> ? U : never;\n };\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<TupleType>(\n [\n (v): v is TupleType => {\n if (!Array.isArray(v) || v.length !== types.length) {\n return false;\n }\n return types.every((schemaType, i) =>\n schemaType._validators.every((validator) => validator(v[i])),\n );\n },\n ],\n `[${typeNames.join(\", \")}]`,\n );\n },\n\n /**\n * Create a date schema type.\n *\n * @example\n * ```typescript\n * schema: { createdAt: t.date() }\n * ```\n */\n date() {\n return createChainableType<Date>(\n [(v): v is Date => v instanceof Date && !Number.isNaN(v.getTime())],\n \"Date\",\n );\n },\n\n /**\n * Create a UUID schema type.\n *\n * @example\n * ```typescript\n * schema: { id: t.uuid() }\n * ```\n */\n uuid() {\n const uuidRegex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && uuidRegex.test(v)],\n \"uuid\",\n );\n },\n\n /**\n * Create an email schema type.\n *\n * @example\n * ```typescript\n * schema: { email: t.email() }\n * ```\n */\n email() {\n // Simple email regex - for comprehensive validation use Zod\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && emailRegex.test(v)],\n \"email\",\n );\n },\n\n /**\n * Create a URL schema type.\n *\n * @example\n * ```typescript\n * schema: { website: t.url() }\n * ```\n */\n url() {\n return createChainableType<string>(\n [\n (v): v is string => {\n if (typeof v !== \"string\") {\n return false;\n }\n try {\n new URL(v);\n return true;\n } catch {\n return false;\n }\n },\n ],\n \"url\",\n );\n },\n\n /**\n * Create a bigint schema type.\n *\n * @example\n * ```typescript\n * schema: { largeNumber: t.bigint() }\n * ```\n */\n bigint() {\n return createChainableType<bigint>(\n [(v): v is bigint => typeof v === \"bigint\"],\n \"bigint\",\n );\n },\n\n /**\n * Create an `any` schema type that accepts all values without validation.\n *\n * @example\n * ```typescript\n * schema: { payload: t.any() }\n * ```\n */\n // biome-ignore lint/suspicious/noExplicitAny: Intentional any type for schema builder\n any() {\n return createChainableType<any>([], \"any\");\n },\n\n /**\n * Create an `unknown` schema type that accepts all values without validation.\n * Prefer `t.unknown()` over `t.any()` for stricter downstream type checking.\n *\n * @example\n * ```typescript\n * schema: { data: t.unknown() }\n * ```\n */\n unknown() {\n return createChainableType<unknown>([], \"unknown\");\n },\n};\n","/**\n * Module - The declarative API for defining Directive modules\n *\n * Modules group related facts, constraints, resolvers, effects, and derivations.\n */\n\nimport isDevelopment from \"#is-development\";\nimport type {\n CrossModuleConstraintsDef,\n CrossModuleDeps,\n CrossModuleDerivationsDef,\n CrossModuleEffectsDef,\n DefinitionMeta,\n EffectsDef,\n Facts,\n ModuleDef,\n ModuleHooks,\n ModuleSchema,\n TypedConstraintsDef,\n TypedDerivationsDef,\n TypedEventsDef,\n TypedResolversDef,\n} from \"./types.js\";\n\n// ============================================================================\n// Module Configuration\n// ============================================================================\n\n/**\n * Module configuration with consolidated schema.\n *\n * derive and events are optional - omit them if your schema has empty derivations/events.\n */\nexport interface ModuleConfig<M extends ModuleSchema> {\n schema: M;\n init?: (facts: Facts<M[\"facts\"]>) => void;\n derive?: TypedDerivationsDef<M>;\n events?: TypedEventsDef<M>;\n effects?: EffectsDef<M[\"facts\"]>;\n constraints?: TypedConstraintsDef<M>;\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n/**\n * Module configuration with cross-module dependencies for type-safe access\n * to other modules' facts in effects and constraints.\n *\n * When crossModuleDeps is provided:\n * - Own module facts: `facts.self.*`\n * - Cross-module facts: `facts.{dep}.*`\n *\n * @example\n * ```typescript\n * import { authSchema } from './auth';\n * import { dataSchema } from './data';\n *\n * const uiModule = createModule(\"ui\", {\n * schema: uiSchema,\n * crossModuleDeps: { auth: authSchema, data: dataSchema },\n * effects: {\n * onAuthChange: {\n * run: (facts) => {\n * facts.self.notifications // ✅ own module via \"self\"\n * facts.auth.isAuthenticated // ✅ cross-module (namespaced)\n * facts.data.users // ✅ cross-module (namespaced)\n * }\n * }\n * },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * require: { type: \"FETCH_USERS\" },\n * }\n * }\n * });\n * ```\n */\nexport interface ModuleConfigWithDeps<\n M extends ModuleSchema,\n Deps extends CrossModuleDeps,\n> {\n schema: M;\n /**\n * Cross-module dependencies for type-safe access in derive/effects/constraints.\n *\n * **Access patterns by context:**\n * - `derive`, `effects`, `constraints`: Use `facts.self.*` for own module, `facts.{dep}.*` for cross-module\n * - `init`, `events`, `resolvers`: Use flat access (`facts.myFact`) - no cross-module access\n *\n * This separation ensures initialization and event handling stay scoped to own module,\n * while observers (derive/effects/constraints) can see across modules.\n *\n * @example\n * ```typescript\n * crossModuleDeps: { auth: authSchema },\n * init: (facts) => { facts.users = []; }, // flat access\n * derive: { count: (facts) => facts.self.users.length }, // facts.self.*\n * effects: { log: { run: (facts) => console.log(facts.auth.token) } }, // facts.{dep}.*\n * ```\n */\n crossModuleDeps: Deps;\n /** Initialize module facts. Uses flat access (`facts.myFact`) to ensure modules initialize independently. */\n init?: (facts: Facts<M[\"facts\"]>) => void;\n /** Derivations with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n derive?: CrossModuleDerivationsDef<M, Deps>;\n /** Event handlers. Uses flat access (`facts.myFact`) to keep mutations scoped to own module. */\n events?: TypedEventsDef<M>;\n /** Effects with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n effects?: CrossModuleEffectsDef<M, Deps>;\n /** Constraints with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n constraints?: CrossModuleConstraintsDef<M, Deps>;\n /** Resolvers. Uses flat access (`ctx.facts.myFact`) to keep async mutations scoped to own module. */\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n// ============================================================================\n// Module Validation Helpers (dev-mode only)\n// ============================================================================\n\n/** Validate module ID follows naming conventions */\nfunction validateModuleId(id: string): void {\n if (!id || typeof id !== \"string\") {\n console.warn(\"[Directive] Module ID must be a non-empty string\");\n\n return;\n }\n if (!/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(id)) {\n console.warn(\n `[Directive] Module ID \"${id}\" should follow kebab-case convention (e.g., \"my-module\")`,\n );\n }\n}\n\n/** Warn when keys in `implKeys` are missing from `schemaKeys` and vice versa */\nfunction validateKeyAlignment(\n implKeys: Set<string>,\n schemaKeys: Set<string>,\n implLabel: string,\n schemaLabel: string,\n missingImplMessage: string,\n): void {\n for (const key of implKeys) {\n if (!schemaKeys.has(key)) {\n console.warn(\n `[Directive] ${implLabel} \"${key}\" not declared in ${schemaLabel}`,\n );\n }\n }\n for (const key of schemaKeys) {\n if (!implKeys.has(key)) {\n console.warn(\n `[Directive] ${schemaLabel}[\"${key}\"] ${missingImplMessage}`,\n );\n }\n }\n}\n\n/** Validate history.snapshotEvents reference valid event names */\nfunction validateSnapshotEvents(\n snapshotEvents: string[],\n schemaEvents: Record<string, unknown>,\n): void {\n if (snapshotEvents.length === 0) {\n console.warn(\n \"[Directive] history.snapshotEvents is an empty array — no events will create history snapshots. \" +\n \"Omit history.snapshotEvents entirely to snapshot all events, or list specific events.\",\n );\n }\n const schemaEventKeys = new Set(Object.keys(schemaEvents));\n for (const eventName of snapshotEvents) {\n if (!schemaEventKeys.has(eventName)) {\n console.warn(\n `[Directive] history.snapshotEvents entry \"${eventName}\" not declared in schema.events. ` +\n `Available events: ${[...schemaEventKeys].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/** Validate resolvers reference valid requirement types */\nfunction validateResolverRequirements(\n resolvers: Record<string, unknown>,\n requirements: Record<string, unknown>,\n): void {\n const requirementTypes = new Set(Object.keys(requirements));\n for (const [resolverName, resolver] of Object.entries(resolvers)) {\n const resolverDef = resolver as { requirement?: string };\n if (\n typeof resolverDef.requirement === \"string\" &&\n !requirementTypes.has(resolverDef.requirement)\n ) {\n console.warn(\n `[Directive] Resolver \"${resolverName}\" references unknown requirement type \"${resolverDef.requirement}\". ` +\n `Available types: ${[...requirementTypes].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/** Run all dev-mode validations for a module config */\nfunction validateModuleConfig<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n validateModuleId(id);\n\n if (!config.schema) {\n console.warn(\"[Directive] Module schema is required\");\n } else if (!config.schema.facts) {\n console.warn(\"[Directive] Module schema.facts is required\");\n }\n\n validateKeyAlignment(\n new Set(Object.keys(config.derive ?? {})),\n new Set(Object.keys(config.schema?.derivations ?? {})),\n \"Derivation\",\n \"schema.derivations\",\n \"has no matching implementation in derive\",\n );\n\n validateKeyAlignment(\n new Set(Object.keys(config.events ?? {})),\n new Set(Object.keys(config.schema?.events ?? {})),\n \"Event\",\n \"schema.events\",\n \"has no matching handler in events\",\n );\n\n if (config.history?.snapshotEvents) {\n validateSnapshotEvents(\n config.history.snapshotEvents as string[],\n config.schema?.events ?? {},\n );\n }\n\n if (config.resolvers && config.schema?.requirements) {\n validateResolverRequirements(\n config.resolvers as Record<string, unknown>,\n config.schema.requirements,\n );\n }\n}\n\n// ============================================================================\n// createModule\n// ============================================================================\n\n/**\n * Create a module definition with full type inference.\n *\n * The consolidated schema provides:\n * - Derivation composition (`derived.otherDerivation` is typed)\n * - Event dispatch (`system.dispatch({ type: \"...\" })` has autocomplete)\n * - Resolver requirements (`req.payload` is typed based on requirement type)\n *\n * @param id - Unique module identifier (kebab-case recommended)\n * @param config - Module configuration including schema, init, derive, constraints, resolvers, etc.\n * @returns A frozen module definition ready for use with `createSystem`\n *\n * @example\n * ```ts\n * const trafficLight = createModule(\"traffic-light\", {\n * schema: {\n * facts: {\n * phase: t.string<\"red\" | \"green\" | \"yellow\">(),\n * elapsed: t.number(),\n * },\n * derivations: {\n * isRed: t.boolean(),\n * timeRemaining: t.number(),\n * },\n * events: {\n * tick: {},\n * setPhase: { phase: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * requirements: {\n * TRANSITION: { to: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * },\n * init: (facts) => {\n * facts.phase = \"red\";\n * facts.elapsed = 0;\n * },\n * derive: {\n * isRed: (facts) => facts.phase === \"red\",\n * timeRemaining: (facts, derived) => {\n * // derived.isRed is typed as boolean!\n * return derived.isRed ? 30 - facts.elapsed : 0;\n * },\n * },\n * events: {\n * tick: (facts) => { facts.elapsed += 1; },\n * setPhase: (facts, { phase }) => { facts.phase = phase; }, // phase is typed!\n * },\n * constraints: {\n * shouldTransition: {\n * when: (facts) => facts.phase === \"red\" && facts.elapsed > 30,\n * require: { type: \"TRANSITION\", to: \"green\" },\n * },\n * },\n * resolvers: {\n * transition: {\n * requirement: \"TRANSITION\",\n * resolve: async (req, ctx) => {\n * ctx.facts.phase = req.to; // req.to is typed!\n * ctx.facts.elapsed = 0;\n * },\n * },\n * },\n * hooks: {\n * // Optional: observe resolver failures owned by this module.\n * // Fires AFTER retries are exhausted and the engine has handled the error\n * // (error boundary, plugin emit, retry decision). Use it as a side-channel\n * // observer for module-local logging/telemetry — not for recovery.\n * onResolverError: (error, requirement, ctx) => {\n * console.warn(`[traffic-light] resolver failed for ${requirement.type}`, error);\n * },\n * },\n * });\n * ```\n *\n * @example With cross-module dependencies\n * ```ts\n * import { authSchema } from './auth';\n *\n * const dataModule = createModule(\"data\", {\n * schema: dataSchema,\n * crossModuleDeps: { auth: authSchema },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => {\n * // facts.self.* for own module, facts.auth.* for cross-module\n * return facts.auth.isAuthenticated && facts.self.users.length === 0;\n * },\n * require: { type: \"FETCH_USERS\" },\n * },\n * },\n * derive: {\n * canFetch: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * },\n * });\n * ```\n *\n * @public\n */\n// Overload 1: With crossModuleDeps\nexport function createModule<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(id: string, config: ModuleConfigWithDeps<M, Deps>): ModuleDef<M>;\n\n// Overload 2: Without crossModuleDeps (original signature)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Overload 3: Union (used by createModuleFactory)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfigWithDeps<M, CrossModuleDeps> | ModuleConfig<M>,\n): ModuleDef<M>;\n\n/** @internal Implementation overload — see public overloads above. */\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): ModuleDef<M> {\n if (isDevelopment) {\n validateModuleConfig(id, config);\n }\n\n // Extract crossModuleDeps if present (for runtime proxy creation)\n const crossModuleDeps =\n \"crossModuleDeps\" in config ? config.crossModuleDeps : undefined;\n\n return {\n id,\n schema: config.schema,\n init: config.init,\n // Cast to TypedDerivationsDef for ModuleDef compatibility (runtime handles both types)\n derive: (config.derive ?? {}) as TypedDerivationsDef<M>,\n events: config.events ?? ({} as TypedEventsDef<M>),\n effects: config.effects as EffectsDef<M[\"facts\"]> | undefined,\n constraints: config.constraints as TypedConstraintsDef<M> | undefined,\n resolvers: config.resolvers,\n hooks: config.hooks,\n meta: config.meta,\n history: config.history,\n // Store crossModuleDeps for runtime proxy creation\n crossModuleDeps: crossModuleDeps as CrossModuleDeps | undefined,\n };\n}\n\n/**\n * Create a module factory that produces named instances from a single definition.\n * Useful for multi-instance UIs (tabs, panels, multi-tenant) where you need\n * isolated state from the same schema.\n *\n * @param config - Module configuration (same shape as `createModule` minus the `id`)\n * @returns A factory function that accepts a name and returns a `ModuleDef`\n *\n * @example\n * ```typescript\n * const chatRoom = createModuleFactory({\n * schema: {\n * facts: { messages: t.array<string>(), users: t.array<string>() },\n * derivations: { count: t.number() },\n * },\n * init: (facts) => { facts.messages = []; facts.users = []; },\n * derive: { count: (facts) => facts.messages.length },\n * });\n *\n * const system = createSystem({\n * modules: {\n * lobby: chatRoom(\"lobby\"),\n * support: chatRoom(\"support\"),\n * },\n * });\n * ```\n *\n * @public\n */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(config: ModuleConfigWithDeps<M, Deps>): (name: string) => ModuleDef<M>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): (name: string) => ModuleDef<M> {\n // Pass config directly — createModule's implementation overload handles both types.\n // Do NOT cast to ModuleConfig<M> which would strip crossModuleDeps.\n return (name: string) => createModule(name, config);\n}\n","/**\n * Requirement Status Utilities\n *\n * Provides reactive tracking of requirement status for UI feedback.\n */\n\nimport type { Plugin, RequirementWithId } from \"../core/types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Status of a requirement type */\nexport interface RequirementTypeStatus {\n /** Number of pending (unmet) requirements of this type */\n pending: number;\n /** Number of inflight (being resolved) requirements of this type */\n inflight: number;\n /** Number of failed requirements of this type */\n failed: number;\n /** Whether any requirements of this type are loading (pending or inflight) */\n isLoading: boolean;\n /** Whether any requirements of this type have failed */\n hasError: boolean;\n /** Last error for this type (if any) */\n lastError: Error | null;\n}\n\n/** Status tracking state */\ninterface StatusState {\n pending: Map<string, Set<string>>; // type -> set of requirement IDs\n inflight: Map<string, Set<string>>; // type -> set of requirement IDs\n failed: Map<string, Set<string>>; // type -> set of requirement IDs\n errors: Map<string, Error>; // type -> last error\n listeners: Set<() => void>;\n}\n\n// ============================================================================\n// Requirement Status Plugin\n// ============================================================================\n\n/**\n * Create a plugin that tracks requirement status for reactive UI updates.\n *\n * @example\n * ```typescript\n * import { createRequirementStatusPlugin } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n *\n * const system = createSystem({\n * modules: [myModule],\n * plugins: [statusPlugin.plugin],\n * });\n *\n * // Get status for a requirement type\n * const status = statusPlugin.getStatus(\"FETCH_USER\");\n * console.log(status.isLoading, status.hasError);\n *\n * // Subscribe to status changes\n * const unsubscribe = statusPlugin.subscribe(() => {\n * console.log(\"Status changed:\", statusPlugin.getStatus(\"FETCH_USER\"));\n * });\n * ```\n */\nexport function createRequirementStatusPlugin(): {\n plugin: Plugin<never>;\n getStatus: (type: string) => RequirementTypeStatus;\n getAllStatus: () => Map<string, RequirementTypeStatus>;\n subscribe: (listener: () => void) => () => void;\n reset: () => void;\n} {\n const state: StatusState = {\n pending: new Map(),\n inflight: new Map(),\n failed: new Map(),\n errors: new Map(),\n listeners: new Set(),\n };\n\n /** Notify all listeners */\n function notify(): void {\n for (const listener of state.listeners) {\n listener();\n }\n }\n\n /** Get or create a set for a type in a map */\n function getOrCreateSet(\n map: Map<string, Set<string>>,\n type: string,\n ): Set<string> {\n let set = map.get(type);\n if (!set) {\n set = new Set();\n map.set(type, set);\n }\n return set;\n }\n\n /** Get status for a requirement type */\n function getStatus(type: string): RequirementTypeStatus {\n const pendingSet = state.pending.get(type) ?? new Set();\n const inflightSet = state.inflight.get(type) ?? new Set();\n const failedSet = state.failed.get(type) ?? new Set();\n const lastError = state.errors.get(type) ?? null;\n\n return {\n pending: pendingSet.size,\n inflight: inflightSet.size,\n failed: failedSet.size,\n isLoading: pendingSet.size > 0 || inflightSet.size > 0,\n hasError: failedSet.size > 0,\n lastError,\n };\n }\n\n /** Get status for all tracked types */\n function getAllStatus(): Map<string, RequirementTypeStatus> {\n const allTypes = new Set([\n ...state.pending.keys(),\n ...state.inflight.keys(),\n ...state.failed.keys(),\n ]);\n\n const result = new Map<string, RequirementTypeStatus>();\n for (const type of allTypes) {\n result.set(type, getStatus(type));\n }\n return result;\n }\n\n /** Subscribe to status changes */\n function subscribe(listener: () => void): () => void {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n }\n\n /** Reset all status */\n function reset(): void {\n state.pending.clear();\n state.inflight.clear();\n state.failed.clear();\n state.errors.clear();\n notify();\n }\n\n const plugin: Plugin<never> = {\n name: \"requirement-status\",\n\n onRequirementCreated(req: RequirementWithId) {\n const type = req.requirement.type;\n getOrCreateSet(state.pending, type).add(req.id);\n // Clear from failed when a new requirement is created\n state.failed.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverStart(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Move from pending to inflight\n state.pending.get(type)?.delete(req.id);\n getOrCreateSet(state.inflight, type).add(req.id);\n notify();\n },\n\n onResolverComplete(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from inflight\n state.inflight.get(type)?.delete(req.id);\n state.pending.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverError(_resolver: string, req: RequirementWithId, error: unknown) {\n const type = req.requirement.type;\n // Move from inflight to failed\n state.inflight.get(type)?.delete(req.id);\n getOrCreateSet(state.failed, type).add(req.id);\n state.errors.set(\n type,\n error instanceof Error ? error : new Error(String(error)),\n );\n notify();\n },\n\n onResolverCancel(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from all tracking\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n\n onRequirementMet(req: RequirementWithId) {\n const type = req.requirement.type;\n // Clean up when requirement is met\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n };\n\n return {\n plugin,\n getStatus,\n getAllStatus,\n subscribe,\n reset,\n };\n}\n\n// ============================================================================\n// React Hook Helper (for use with React adapter)\n// ============================================================================\n\n/**\n * Create a hook factory for requirement status.\n * This is designed to be used with React's useSyncExternalStore.\n *\n * @example\n * ```typescript\n * import { useSyncExternalStore } from 'react';\n * import { createRequirementStatusPlugin, createStatusHook } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n * const useRequirementStatus = createStatusHook(statusPlugin);\n *\n * function MyComponent() {\n * const status = useRequirementStatus(\"FETCH_USER\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error error={status.lastError} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createStatusHook(\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>,\n): (type: string) => RequirementTypeStatus {\n // This returns a function that can be used with useSyncExternalStore\n // The actual hook implementation would be in the React adapter\n return (type: string) => statusPlugin.getStatus(type);\n}\n","/**\n * System with Status Plugin Helper\n *\n * Convenience function for creating a system with status tracking enabled.\n */\n\nimport { createSystem } from \"../core/system.js\";\nimport type {\n ErrorBoundaryConfig,\n ModuleDef,\n ModuleSchema,\n Plugin,\n SingleModuleSystem,\n TraceOption,\n} from \"../core/types.js\";\nimport { createRequirementStatusPlugin } from \"./requirement-status.js\";\n\n/** Options for createSystemWithStatus */\nexport interface CreateSystemWithStatusOptions<M extends ModuleSchema> {\n /** The module to use for the system */\n module: ModuleDef<M>;\n /** Additional plugins to include alongside the status plugin */\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic contravariance issues\n plugins?: Plugin<any>[];\n /** Trace: per-run reconciliation changelog */\n trace?: TraceOption;\n /** Error boundary configuration */\n errorBoundary?: ErrorBoundaryConfig;\n /** Tick interval in milliseconds */\n tickMs?: number;\n /** Enable zero-config mode */\n zeroConfig?: boolean;\n /** Initial facts to set on the system */\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies by module\n initialFacts?: Record<string, any>;\n}\n\n/** Return type for createSystemWithStatus */\nexport interface SystemWithStatus<M extends ModuleSchema> {\n /**\n * The Directive system instance.\n * This is a SingleModuleSystem - use system.facts, system.dispatch(), etc.\n */\n system: SingleModuleSystem<M>;\n /** The status plugin for use with useRequirementStatus hooks */\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>;\n}\n\n/**\n * Create a Directive system with a status plugin pre-configured.\n *\n * This is a convenience wrapper around `createSystem` and `createRequirementStatusPlugin`\n * that handles the wiring automatically. The status plugin is added to the system's\n * plugins array so it receives lifecycle events.\n *\n * @param options - System configuration options\n * @returns An object containing both the system and the statusPlugin\n *\n * @example\n * ```tsx\n * import { createSystemWithStatus } from '@directive-run/core';\n * import { useRequirementStatus, useFact } from '@directive-run/react';\n *\n * // Simple setup - no provider needed\n * const { system, statusPlugin } = createSystemWithStatus({\n * module: myModule,\n * });\n * system.start();\n *\n * function App() {\n * const data = useFact(system, \"data\");\n * return <LoadingIndicator />;\n * }\n *\n * function LoadingIndicator() {\n * const status = useRequirementStatus(statusPlugin, \"FETCH_DATA\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error message={status.lastError?.message} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createSystemWithStatus<M extends ModuleSchema>(\n options: CreateSystemWithStatusOptions<M>,\n): SystemWithStatus<M> {\n // Create the status plugin\n const statusPlugin = createRequirementStatusPlugin();\n\n // Add the plugin to the options\n const existingPlugins = options.plugins ?? [];\n\n // Create the system with the status plugin included\n // Use type assertion to bypass overload resolution issues\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const allPlugins = [...existingPlugins, statusPlugin.plugin] as Plugin<any>[];\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: options.module,\n plugins: allPlugins,\n trace: options.trace,\n errorBoundary: options.errorBoundary,\n tickMs: options.tickMs,\n zeroConfig: options.zeroConfig,\n initialFacts: options.initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n\n return {\n // The system returned by createSystem with a single module is a SingleModuleSystem\n system: system as SingleModuleSystem<M>,\n statusPlugin,\n };\n}\n","/**\n * SignalClock — injectable clock source for declarative timers (RFC 0001).\n *\n * The clock interface decouples Directive's timer primitives from any\n * single time source. Production uses `realClock()`. Tests use\n * `virtualClock()` which advances synchronously via `clock.advanceBy()`.\n * Replay / dehydrate scenarios use a clock seeded from the recorded\n * stream.\n *\n * Auto-detection: `defaultClock()` returns `virtualClock()` when running\n * under Vitest (process.env.VITEST === 'true'), otherwise `realClock()`.\n * Consumers can pass an explicit clock to `createSystem({ clock })` to\n * override.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n/**\n * Stable interface for any time source.\n */\nexport interface SignalClock {\n /** Current time, in milliseconds since the Unix epoch. */\n now(): number;\n /**\n * Schedule a callback to fire after `ms` milliseconds. Returns a\n * cancellation function. Implementations may queue callbacks or fire\n * them on a tick boundary; the only contract is \"fires no earlier\n * than `ms` from now.\"\n */\n setTimeout(cb: () => void, ms: number): () => void;\n /**\n * (Test-only.) Synchronously advance the clock by `ms` milliseconds,\n * firing all scheduled callbacks whose deadlines fall within the\n * advanced window. Real clocks throw if called.\n */\n advanceBy?(ms: number): void;\n}\n\n/**\n * Production clock — wraps `Date.now()` and `globalThis.setTimeout`.\n * No mocking, no virtualization.\n */\nexport function realClock(): SignalClock {\n return {\n now: () => Date.now(),\n setTimeout: (cb, ms) => {\n const handle = globalThis.setTimeout(cb, ms);\n return () => globalThis.clearTimeout(handle);\n },\n };\n}\n\n/**\n * Virtual clock — advances only when `advanceBy(ms)` is called. All\n * scheduled callbacks fire synchronously in order of their deadlines.\n *\n * Two scheduled callbacks at the same deadline fire in registration order.\n * Cancellation is O(1).\n */\nexport function virtualClock(initialMs = 0): SignalClock {\n let nowMs = initialMs;\n let nextId = 0;\n interface Scheduled {\n id: number;\n deadlineMs: number;\n cb: () => void;\n canceled: boolean;\n }\n const queue: Scheduled[] = [];\n\n return {\n now: () => nowMs,\n setTimeout: (cb, ms) => {\n const entry: Scheduled = {\n id: nextId++,\n deadlineMs: nowMs + ms,\n cb,\n canceled: false,\n };\n queue.push(entry);\n return () => {\n entry.canceled = true;\n };\n },\n advanceBy: (ms) => {\n const targetMs = nowMs + ms;\n // Fire all callbacks whose deadlines fall in [nowMs, targetMs].\n // Sort live entries by deadline + registration order so ties\n // resolve deterministically.\n while (true) {\n const ready = queue\n .filter((e) => !e.canceled && e.deadlineMs <= targetMs)\n .sort((a, b) =>\n a.deadlineMs !== b.deadlineMs\n ? a.deadlineMs - b.deadlineMs\n : a.id - b.id,\n );\n if (ready.length === 0) break;\n const next = ready[0]!;\n // Advance \"now\" monotonically — never let a callback that\n // schedules another callback in the past pull `nowMs`\n // backward. Without this clamp, `setTimeout(cb2, -5)` from\n // inside a callback would make `clock.now()` return a smaller\n // value mid-advance, breaking elapsedMs (negative results)\n // and replay determinism. (R1 sec C3.)\n nowMs = Math.max(nowMs, next.deadlineMs);\n next.canceled = true;\n next.cb();\n }\n // Final advance — even if no callbacks fired in [nowMs, targetMs],\n // wall clock still moves forward.\n nowMs = Math.max(nowMs, targetMs);\n },\n };\n}\n\n/**\n * Returns `realClock()` always.\n *\n * Earlier drafts auto-detected vitest (`process.env.VITEST === 'true'`)\n * and returned a `virtualClock()` in that environment. AE review\n * flagged this as a footgun: tests that legitimately need real time\n * (sleep-based debounce checks, real-`setTimeout`-bound integration\n * fixtures) silently received a virtual clock that never advanced\n * unless the test author called `advanceBy()`, producing apparent\n * deadlocks indistinguishable from genuine bugs. Auto-detection is\n * therefore opt-in.\n *\n * Use {@link virtualClock} explicitly in tests:\n *\n * ```ts\n * const clock = virtualClock(0);\n * const sys = createSystem({ module, clock });\n * clock.advanceBy(1_000);\n * ```\n */\nexport function defaultClock(): SignalClock {\n return realClock();\n}\n","/**\n * Timer fact — a runtime container that advances over time on a\n * SignalClock (RFC 0001 v0.1).\n *\n * Produced by `createTimerFact(clock, opts)`. Holds the durable state\n * (startedAtMs, pausedDurationMs, status) and exposes a control surface\n * (start, pause, resume, reset) plus reactive reads (elapsedMs,\n * remainingMs, status).\n *\n * v0.1 SCOPE: timer is a \"thick fact\" — a single object you store in a\n * regular Directive fact (e.g. `t.object<TimerFactState>()`). The\n * engine doesn't auto-tick it; the consumer is responsible for calling\n * `timer.tick()` when they want elapsedMs / remainingMs to update.\n * Typical wiring: a setInterval in the consumer that calls `timer.tick()`\n * and dispatches an event when status changes.\n *\n * v0.2 (deferred): true `t.timer({ms})` schema integration where the\n * engine subscribes to the clock and writes the fact deltas itself,\n * eliminating the consumer-side tick wiring.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n// SignalClock is the canonical time source for timer ops; consumers\n// pass `clock.now()` into the helpers below. Re-exported by index.ts\n// alongside this module so they can `import { realClock, timerOps,\n// initialTimerState } from \"@directive-run/core\"` together.\n\n/**\n * Persistent timer state — JSON-roundtrippable, suitable for storing\n * inside a Directive fact.\n */\nexport interface TimerFactState {\n /** Unix-ms when the timer last started or resumed. null = not running. */\n startedAtMs: number | null;\n /** Total ms accumulated while paused. */\n pausedDurationMs: number;\n /** ms when the timer was paused, if currently paused. null otherwise. */\n pausedAtMs: number | null;\n /**\n * - 'idle': not yet started, or reset.\n * - 'running': currently counting.\n * - 'paused': paused; pausedAtMs is set.\n * - 'completed': hit the deadline (countdown mode only).\n */\n status: \"idle\" | \"running\" | \"paused\" | \"completed\";\n /** Number of times the timer has fired (repeat mode only). */\n repeats: number;\n}\n\nexport interface TimerFactOpts {\n /** Duration in ms. Countdown mode counts this down; up mode counts up to ∞. */\n ms: number;\n /**\n * - 'down' (default): counts down from `ms` to 0; status → 'completed' at 0.\n * - 'up': counts elapsed time; never completes.\n * - 'repeat': fires every `ms`; increments `repeats`; status stays 'running'.\n */\n mode?: \"down\" | \"up\" | \"repeat\";\n}\n\n/**\n * Initial state for a newly-created timer. Pass this to your Directive\n * `init()` to seed the fact.\n */\nexport function initialTimerState(): TimerFactState {\n return {\n startedAtMs: null,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"idle\",\n repeats: 0,\n };\n}\n\n/**\n * Compute elapsed ms for a given timer state at a given clock-now.\n * Pure function — no side effects, no reads beyond its inputs.\n *\n * @example\n * ```ts\n * const elapsed = elapsedMs(facts.countdown, clock.now());\n * if (elapsed >= 60_000) {\n * facts.countdown = { ...facts.countdown, status: 'completed' };\n * }\n * ```\n */\nexport function elapsedMs(state: TimerFactState, nowMs: number): number {\n if (state.startedAtMs === null) return 0;\n // Clamp at 0 — a clock step-back (NTP correction, virtual-clock\n // re-entrancy, replay seeded from older snapshot) would otherwise\n // produce negative elapsed values that:\n // - make tickTimer never report 'complete' (because `elapsed >= ms`\n // stays false past the deadline)\n // - make remainingMs report values > the configured ms total\n // - silently wrap into pausedDurationMs accumulation downstream\n // (R1 sec C4.)\n if (state.status === \"paused\" && state.pausedAtMs !== null) {\n return Math.max(\n 0,\n state.pausedAtMs - state.startedAtMs - state.pausedDurationMs,\n );\n }\n return Math.max(0, nowMs - state.startedAtMs - state.pausedDurationMs);\n}\n\n/**\n * Compute remaining ms for a countdown timer at a given clock-now.\n * Returns 0 if the timer has hit zero or hasn't started.\n */\nexport function remainingMs(\n state: TimerFactState,\n nowMs: number,\n totalMs: number,\n): number {\n return Math.max(0, totalMs - elapsedMs(state, nowMs));\n}\n\n/**\n * Transition: start an idle (or reset) timer.\n *\n * No-op if already running, paused, or completed (use `reset()` first).\n */\nexport function startTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status === \"running\") return state;\n if (state.status === \"paused\") return state;\n return {\n ...state,\n startedAtMs: nowMs,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"running\",\n repeats: 0,\n };\n}\n\n/**\n * Transition: pause a running timer. Records the pause moment so a\n * later `resumeTimer()` can correctly extend pausedDurationMs.\n *\n * No-op if not running.\n */\nexport function pauseTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"running\") return state;\n return { ...state, pausedAtMs: nowMs, status: \"paused\" };\n}\n\n/**\n * Transition: resume a paused timer. Adds the time spent paused into\n * `pausedDurationMs` so elapsed/remaining math stays correct.\n *\n * No-op if not paused.\n */\nexport function resumeTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"paused\") return state;\n if (state.pausedAtMs === null) return state;\n // Clamp pausedFor at 0 — clock step-back between pause and resume\n // would otherwise produce a negative pausedDurationMs accumulation,\n // which propagates into elapsedMs (returns inflated values), which\n // prematurely completes countdowns. (R1 sec M1.)\n const pausedFor = Math.max(0, nowMs - state.pausedAtMs);\n return {\n ...state,\n pausedDurationMs: state.pausedDurationMs + pausedFor,\n pausedAtMs: null,\n status: \"running\",\n };\n}\n\n/**\n * Transition: reset a timer to idle. Loses all elapsed time + repeat\n * count. Equivalent to `initialTimerState()`.\n */\nexport function resetTimer(): TimerFactState {\n return initialTimerState();\n}\n\n/**\n * Transition: mark the timer completed. For countdown mode when\n * elapsed >= ms; for repeat mode when consumer wants to halt.\n */\nexport function completeTimer(state: TimerFactState): TimerFactState {\n return { ...state, status: \"completed\" };\n}\n\n/**\n * Transition: register a repeat firing. Increments `repeats` and\n * advances `startedAtMs` by `ms` so the next interval lands at the\n * intended boundary (drift-free).\n */\nexport function registerRepeat(\n state: TimerFactState,\n ms: number,\n): TimerFactState {\n if (state.startedAtMs === null) return state;\n // Defensible-illegal: registerRepeat from a paused state would\n // otherwise advance startedAtMs while leaving status === 'paused',\n // producing an inconsistent state (logically running by clock math\n // but reads as paused). No-op instead. (R2 sec m-R2-2.)\n if (state.status === \"paused\") return state;\n // Reset pausedDurationMs on each repeat so accumulated pause time\n // from prior intervals does not double-count into the next\n // interval's elapsed math. Without this reset, every repeat after a\n // pause would arithmetic-drift the next deadline by the cumulative\n // pause window. (R1 sec M9.)\n return {\n ...state,\n startedAtMs: state.startedAtMs + ms,\n pausedDurationMs: 0,\n pausedAtMs: null,\n repeats: state.repeats + 1,\n };\n}\n\n/**\n * Higher-level helper: given a timer state, total ms, and the current\n * clock, return whether the timer should transition to 'completed' (for\n * countdown mode) or fire a repeat (for repeat mode).\n *\n * Pure — does not mutate state. Returns a structured signal the consumer\n * applies via `completeTimer` / `registerRepeat`.\n */\nexport function tickTimer(\n state: TimerFactState,\n nowMs: number,\n opts: TimerFactOpts,\n): { kind: \"no-op\" } | { kind: \"complete\" } | { kind: \"repeat\" } {\n if (state.status !== \"running\") return { kind: \"no-op\" };\n const elapsed = elapsedMs(state, nowMs);\n\n if (opts.mode === \"up\") {\n // 'up' never completes; consumer reads elapsedMs directly.\n return { kind: \"no-op\" };\n }\n\n if (opts.mode === \"repeat\") {\n if (elapsed >= opts.ms) return { kind: \"repeat\" };\n return { kind: \"no-op\" };\n }\n\n // 'down' (default)\n if (elapsed >= opts.ms) return { kind: \"complete\" };\n return { kind: \"no-op\" };\n}\n\n/**\n * Bundle of helpers for one timer in one module — convenience for\n * callers who want a single import. Each method takes the current\n * state and clock-now, returns the next state. No mutation.\n *\n * @example\n * ```ts\n * import {\n * createSystem,\n * t,\n * realClock,\n * timerOps,\n * initialTimerState,\n * type TimerFactState,\n * } from '@directive-run/core';\n *\n * const clock = realClock();\n * const ops = timerOps({ ms: 60_000, mode: 'down' });\n *\n * createModule('countdown', {\n * schema: { facts: { state: t.object<TimerFactState>() }, events: { START: {} } },\n * init: (f) => { f.state = initialTimerState(); },\n * events: {\n * START: (f) => { f.state = ops.start(f.state, clock.now()); },\n * },\n * });\n *\n * // In the consumer (React, Node, edge), tick periodically:\n * setInterval(() => {\n * const signal = ops.tick(f.state, clock.now());\n * if (signal.kind === 'complete') {\n * sys.dispatch({ type: 'TIMEOUT' });\n * }\n * }, 100);\n * ```\n */\nexport function timerOps(opts: TimerFactOpts) {\n return {\n initial: initialTimerState,\n start: startTimer,\n pause: pauseTimer,\n resume: resumeTimer,\n reset: resetTimer,\n complete: completeTimer,\n registerRepeat: (state: TimerFactState) => registerRepeat(state, opts.ms),\n tick: (state: TimerFactState, nowMs: number) => tickTimer(state, nowMs, opts),\n elapsedMs,\n remainingMs: (state: TimerFactState, nowMs: number) =>\n remainingMs(state, nowMs, opts.ms),\n };\n}\n","/**\n * @directive-run/core\n *\n * Constraint-driven runtime for TypeScript.\n *\n * Also available:\n * - `@directive-run/core/internals` – Manager factories, engine, tracking, and internal types\n * - `@directive-run/core/plugins` – Logging, devtools, persistence, observability, circuit breaker\n * - `@directive-run/core/testing` – Mock resolvers, fake timers, assertion helpers\n * - `@directive-run/core/migration` – Redux/Zustand/XState migration scaffolding\n * - `@directive-run/core/adapter-utils` – Shared framework adapter utilities\n * - `@directive-run/core/worker` – Web Worker support\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Core Types — what 90% of users need\n// ============================================================================\n\nexport type {\n // Schema\n Schema,\n SchemaType,\n InferSchemaType,\n // Module Schema (consolidated)\n ModuleSchema,\n InferFacts,\n InferDerivations,\n InferSelectorState,\n InferEvents,\n InferRequirements,\n InferRequirementTypes,\n // Facts\n Facts,\n FactsSnapshot,\n // Requirements\n Requirement,\n RequirementWithId,\n // Constraints + Resolvers (config types)\n RetryPolicy,\n BatchConfig,\n // Plugins\n Plugin,\n Snapshot,\n // Errors\n ErrorBoundaryConfig,\n // Module\n ModuleDef,\n ModuleHooks,\n // System\n System,\n SystemConfig,\n SystemInspection,\n SystemSnapshot,\n MetaAccessor,\n MetaMatch,\n ObservationEvent,\n // Trace\n TraceEntry,\n TraceOption,\n // History\n HistoryOption,\n HistoryAPI,\n HistoryState,\n // Composition (Namespaced Multi-Module)\n ModulesMap,\n NamespacedSystem,\n CreateSystemOptionsNamed,\n // Single Module\n CreateSystemOptionsSingle,\n SingleModuleSystem,\n // Type Guards\n SystemMode,\n AnySystem,\n // Cross-Module Dependencies\n CrossModuleDeps,\n // Dynamic Definitions\n DynamicConstraintDef,\n DynamicEffectDef,\n DynamicResolverDef,\n // Definition Meta\n DefinitionMeta,\n DerivationDefWithMeta,\n // Distributable Snapshots\n DistributableSnapshot,\n DistributableSnapshotOptions,\n} from \"./core/types.js\";\n\n// ============================================================================\n// Core Classes\n// ============================================================================\n\nexport { DirectiveError } from \"./core/types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/**\n * Schema type builders for defining fact types.\n *\n * @example\n * ```ts\n * import { t } from '@directive-run/core';\n *\n * const schema = {\n * facts: {\n * count: t.number().min(0).default(0),\n * name: t.string(),\n * status: t.enum(\"idle\", \"loading\", \"error\"),\n * user: t.object<User>().nullable(),\n * },\n * derivations: { doubled: t.number() },\n * events: { increment: {} },\n * requirements: { FETCH_USER: {} },\n * };\n * ```\n */\nexport {\n t,\n type Branded,\n type ExtendedSchemaType,\n type ChainableSchemaType,\n} from \"./core/schema-builders.js\";\n\n// ============================================================================\n// Module & System\n// ============================================================================\n\nexport {\n createModule,\n createModuleFactory,\n type ModuleConfig,\n type ModuleConfigWithDeps,\n} from \"./core/module.js\";\nexport { createSystem } from \"./core/system.js\";\nexport { createSystemWithStatus } from \"./utils/system-with-status.js\";\n\n// Helper factory functions for typed constraint/resolver definitions\nexport {\n typedConstraint,\n typedResolver,\n} from \"./core/types.js\";\n\n// ============================================================================\n// Requirements Helpers\n// ============================================================================\n\nexport {\n req,\n forType,\n isRequirementType,\n generateRequirementId,\n RequirementSet,\n} from \"./core/requirements.js\";\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport {\n isSingleModuleSystem,\n isNamespacedSystem,\n} from \"./core/types/composition.js\";\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Backoff strategy constants for retry policies.\n *\n * @example\n * ```ts\n * import { Backoff } from '@directive-run/core';\n *\n * retry: { attempts: 3, backoff: Backoff.Exponential, initialDelay: 100 }\n * ```\n */\nexport const Backoff = {\n /** No delay between retries */\n None: \"none\",\n /** Linear delay increase (initialDelay * attempt) */\n Linear: \"linear\",\n /** Exponential delay increase (initialDelay * 2^attempt) */\n Exponential: \"exponential\",\n} as const;\n\n// ============================================================================\n// Requirement Status Utilities\n// ============================================================================\n\nexport {\n createRequirementStatusPlugin,\n createStatusHook,\n type RequirementTypeStatus,\n} from \"./utils/requirement-status.js\";\n\n// ============================================================================\n// Snapshot Utilities\n// ============================================================================\n\nexport {\n shallowEqual,\n isSnapshotExpired,\n validateSnapshot,\n diffSnapshots,\n signSnapshot,\n verifySnapshotSignature,\n isSignedSnapshot,\n type DistributableSnapshotLike,\n type SnapshotDiff,\n type SnapshotDiffEntry,\n type SignedSnapshot,\n} from \"./utils/utils.js\";\n\n// ============================================================================\n// Clock + Timer (RFC 0001 v0.1)\n// ============================================================================\n\nexport {\n type SignalClock,\n realClock,\n virtualClock,\n defaultClock,\n} from \"./core/clock.js\";\n\nexport {\n type TimerFactState,\n type TimerFactOpts,\n initialTimerState,\n elapsedMs,\n remainingMs,\n startTimer,\n pauseTimer,\n resumeTimer,\n resetTimer,\n completeTimer,\n registerRepeat,\n tickTimer,\n timerOps,\n} from \"./core/timer.js\";\n\n// ============================================================================\n// Lower-level APIs — use \"@directive-run/core/internals\" for these\n// ============================================================================\n// Manager factories, engine, tracking, and internal types are available at:\n// import { createEngine, createFacts, withTracking } from \"@directive-run/core/internals\"\n//\n// Internal types (FactsStore, FactChange, DerivationState, ConstraintState,\n// DerivationsDef, ConstraintsDef, ResolversDef, EventsDef, ReconcileResult,\n// RecoveryStrategy, ErrorSource, etc.) are also in internals.\n\n// Migration utilities available via \"@directive-run/core/migration\" subpath export.\n"]}
1
+ {"version":3,"sources":["../src/core/schema-builders.ts","../src/core/module.ts","../src/utils/requirement-status.ts","../src/utils/system-with-status.ts","../src/core/clock.ts","../src/core/timer.ts","../src/index.ts"],"names":["createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","value","v","intermediate","desc","predicate","message","newRefinements","m","unionImpl","types","typeNames","schemaType","t","createChainableString","fm","n","regex","createChainableNumber","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","i","validator","createChainableObject","shapeSchema","key","schemaT","keys","k","values","dev_true_default","valueSet","innerType","innerTypeName","valueType","valueTypeName","val","uuidRegex","emailRegex","validateModuleId","id","validateKeyAlignment","implKeys","schemaKeys","implLabel","schemaLabel","missingImplMessage","validateSnapshotEvents","snapshotEvents","schemaEvents","schemaEventKeys","eventName","validateResolverRequirements","resolvers","requirements","requirementTypes","resolverName","resolver","resolverDef","validateModuleConfig","config","createModule","crossModuleDeps","createModuleFactory","name","createRequirementStatusPlugin","state","notify","listener","getOrCreateSet","map","type","set","getStatus","pendingSet","inflightSet","failedSet","lastError","getAllStatus","allTypes","result","subscribe","reset","req","_resolver","error","createStatusHook","statusPlugin","createSystemWithStatus","options","allPlugins","createSystem","realClock","cb","ms","handle","virtualClock","initialMs","nowMs","nextId","queue","entry","targetMs","ready","e","a","b","next","defaultClock","initialTimerState","elapsedMs","remainingMs","totalMs","startTimer","pauseTimer","resumeTimer","pausedFor","resetTimer","completeTimer","registerRepeat","tickTimer","opts","elapsed","timerOps","Backoff"],"mappings":"4vBAuCA,SAASA,EACPC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CACAC,EACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACuB,CACvB,OAAO,CACL,KAAA,C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ZC,CAAAA,EAAWD,EAAK,EAAA,CAAW,CAAE,IAAA,CAAM,QAAS,EACzC,CAAE,IAAA,CAAM,OAAQ,CAAA,CAIrBC,GAAWD,CAAAA,CAAK,EAAA,CAAW,CAAE,IAAA,CAAM,UAAW,CAAA,CAC3C,CAAE,IAAA,CAAM,OAAQ,CACzB,CAsCO,SAASE,EAAAA,CAASF,CAAAA,CAAqB,CAC5C,OAAO,CACL,OAAA,CAASZ,CAAAA,CACT,MAAOI,CAAAA,CACP,KAAA,CAAOC,EACP,MAAA,CAAQC,CAAAA,CACR,MAAOE,CAAAA,CACP,QAAA,CAAUC,CAAAA,CACV,cAAA,CAAiBpD,GAA0BqD,CAAAA,CAAerD,CAAAA,CAAOuD,CAAAA,CAAK,EAAE,EACxE,IAAA,CAAM,CAACvD,CAAAA,CAAuBgC,CAAAA,GAC5BsB,EAAUtD,CAAAA,CAAOgC,CAAAA,CAAOuB,CAAI,CAAA,CAC9B,UAAAX,CAAAA,CACA,WAAA,CAAa,CAAC5C,CAAAA,CAAuBgC,IACnCa,CAAAA,CAAY7C,CAAAA,CAAOgC,CAAAA,CAAOuB,CAAAA,CAAK,EAAE,CACrC,CACF,CCjGO,IAAMG,GAAU,CAErB,IAAA,CAAM,OAEN,MAAA,CAAQ,QAAA,CAER,YAAa,aACf","file":"index.js","sourcesContent":["/**\n * Schema Type Builders\n *\n * Provides type-safe schema definitions with optional runtime validation.\n * Used to define fact types, derivation types, event payload types, etc.\n *\n * This module has no dependency on the facts store or tracking system.\n */\n\nimport isDevelopment from \"#is-development\";\nimport type { SchemaType } from \"./types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/** Brand symbol for branded types */\ndeclare const Brand: unique symbol;\n\n/** Branded type - adds a unique brand to a base type */\nexport type Branded<T, B extends string> = T & { readonly [Brand]: B };\n\n/** Extended SchemaType with type name for better error messages */\nexport interface ExtendedSchemaType<T> extends SchemaType<T> {\n readonly _typeName?: string;\n readonly _default?: T | (() => T);\n readonly _transform?: (value: unknown) => T;\n readonly _description?: string;\n readonly _refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>;\n /** Mutable - set by array validators to indicate which element failed */\n _lastFailedIndex?: number;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n readonly _meta?: import(\"./types/meta.js\").DefinitionMeta;\n}\n\n/** Create a schema type builder with optional type name */\nfunction createSchemaType<T>(\n validators: Array<(v: T) => boolean> = [],\n typeName?: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n meta?: import(\"./types/meta.js\").DefinitionMeta,\n): ExtendedSchemaType<T> {\n return {\n _type: undefined as unknown as T,\n _validators: validators,\n _typeName: typeName,\n _default: defaultValue,\n _transform: transform,\n _description: description,\n _refinements: refinements,\n _meta: meta,\n validate(fn: (value: T) => boolean) {\n return createSchemaType(\n [...validators, fn],\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n meta,\n );\n },\n };\n}\n\n/** Chainable schema type with all common methods */\nexport interface ChainableSchemaType<T> extends ExtendedSchemaType<T> {\n default(value: T | (() => T)): ChainableSchemaType<T>;\n transform<U>(fn: (value: T) => U): ChainableSchemaType<U>;\n brand<B extends string>(): ChainableSchemaType<Branded<T, B>>;\n describe(description: string): ChainableSchemaType<T>;\n refine(\n predicate: (value: T) => boolean,\n message: string,\n ): ChainableSchemaType<T>;\n nullable(): ChainableSchemaType<T | null>;\n optional(): ChainableSchemaType<T | undefined>;\n /** Attach metadata for debugging and devtools. */\n meta(meta: import(\"./types/meta.js\").DefinitionMeta): ChainableSchemaType<T>;\n}\n\n/** Create a chainable schema type with common methods */\nfunction createChainableType<T>(\n validators: Array<(v: T) => boolean>,\n typeName: string,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{ predicate: (value: T) => boolean; message: string }>,\n fieldMeta?: import(\"./types/meta.js\").DefinitionMeta,\n): ChainableSchemaType<T> {\n const base = createSchemaType<T>(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n return {\n ...base,\n default(value: T | (() => T)) {\n return createChainableType(\n validators,\n typeName,\n value,\n transform,\n description,\n refinements,\n fieldMeta,\n );\n },\n transform<U>(fn: (value: T) => U) {\n const newTransform = (v: unknown) => {\n const intermediate = transform ? transform(v) : (v as T);\n return fn(intermediate);\n };\n return createChainableType<U>(\n [],\n typeName,\n undefined,\n newTransform as (v: unknown) => U,\n description,\n undefined,\n fieldMeta,\n );\n },\n brand<B extends string>() {\n return createChainableType<Branded<T, B>>(\n validators as Array<(v: Branded<T, B>) => boolean>,\n `Branded<${typeName}>`,\n defaultValue as Branded<T, B> | (() => Branded<T, B>),\n transform as (value: unknown) => Branded<T, B>,\n description,\n refinements as Array<{\n predicate: (value: Branded<T, B>) => boolean;\n message: string;\n }>,\n fieldMeta,\n );\n },\n describe(desc: string) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n desc,\n refinements,\n fieldMeta,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [...(refinements ?? []), { predicate, message }];\n return createChainableType(\n [...validators, predicate],\n typeName,\n defaultValue,\n transform,\n description,\n newRefinements,\n fieldMeta,\n );\n },\n nullable() {\n return createChainableType<T | null>(\n [\n (v): v is T | null =>\n v === null || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | null`,\n defaultValue as (T | null) | (() => T | null),\n transform as (value: unknown) => T | null,\n description,\n undefined,\n fieldMeta,\n );\n },\n optional() {\n return createChainableType<T | undefined>(\n [\n (v): v is T | undefined =>\n v === undefined || validators.every((fn) => fn(v as T)),\n ],\n `${typeName} | undefined`,\n defaultValue as (T | undefined) | (() => T | undefined),\n transform as (value: unknown) => T | undefined,\n description,\n undefined,\n fieldMeta,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableType(\n validators,\n typeName,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n}\n\n/**\n * Two-form union schema constructor.\n *\n * Hoisted out of the `t` object literal because the overload-cast pattern\n * (`(impl) as { ovl1; ovl2 }`) inside an object literal triggers a TS\n * declaration-emit \"implicitly has type any\" cycle. Annotating the const\n * with the explicit overload type breaks the cycle so DTS can emit `t`'s\n * shape without recursing through the runtime expression.\n *\n * @internal\n */\ntype UnionFn = {\n <T = unknown>(): ChainableSchemaType<T>;\n <T extends SchemaType<unknown>[]>(\n ...types: T\n ): ChainableSchemaType<T[number] extends SchemaType<infer U> ? U : never>;\n};\n\nconst unionImpl: UnionFn = (<T extends SchemaType<unknown>[]>(...types: T) => {\n if (types.length === 0) {\n return createChainableType<unknown>([], \"union\");\n }\n type UnionType = T[number] extends SchemaType<infer U> ? U : never;\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<UnionType>(\n [\n (v): v is UnionType =>\n types.some((schemaType) => schemaType._validators.every((fn) => fn(v))),\n ],\n typeNames.join(\" | \"),\n );\n}) as UnionFn;\n\n/**\n * Schema type builders for defining fact types.\n *\n * @remarks\n * Each builder returns a chainable {@link ExtendedSchemaType} with validation\n * methods (`.min()`, `.max()`, `.pattern()`, etc.) and dev-mode runtime\n * type checking. Validators are tree-shaken in production builds.\n *\n * @example\n * ```typescript\n * const module = createModule(\"example\", {\n * schema: {\n * name: t.string(),\n * age: t.number().min(0).max(150),\n * active: t.boolean(),\n * tags: t.array<string>().of(t.string()),\n * user: t.object<{ id: string; email: string }>(),\n * },\n * });\n * ```\n *\n * @public\n */\nexport const t = {\n /**\n * Create a string schema type.\n *\n * @example\n * ```typescript\n * // Basic string\n * schema: { name: t.string() }\n *\n * // String literal union (for type safety)\n * schema: { phase: t.string<\"red\" | \"green\" | \"yellow\">() }\n *\n * // With custom validation\n * schema: { email: t.string().validate(s => s.includes(\"@\")) }\n *\n * // With transform\n * schema: { trimmed: t.string().transform(s => s.trim()) }\n *\n * // With brand\n * schema: { userId: t.string().brand<\"UserId\">() }\n * ```\n */\n string<T extends string = string>() {\n type ChainableString = ChainableSchemaType<T> & {\n minLength(n: number): ChainableString;\n maxLength(n: number): ChainableString;\n pattern(regex: RegExp): ChainableString;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableString;\n };\n\n const createChainableString = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n transform?: (value: unknown) => T,\n description?: string,\n refinements?: Array<{\n predicate: (value: T) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableString => {\n const chainable = createChainableType<T>(\n validators,\n \"string\",\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n return {\n ...chainable,\n minLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length >= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n maxLength(n: number) {\n return createChainableString(\n [...validators, (v) => (v as string).length <= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n pattern(regex: RegExp) {\n return createChainableString(\n [...validators, (v) => regex.test(v as string)],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableString(\n validators,\n value,\n transform,\n description,\n refinements,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableString(\n validators,\n defaultValue,\n transform,\n desc,\n refinements,\n fm,\n );\n },\n refine(predicate: (value: T) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableString(\n [...validators, predicate],\n defaultValue,\n transform,\n description,\n newRefinements,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableString(\n validators,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n };\n\n return createChainableString([(v): v is T => typeof v === \"string\"]);\n },\n\n /**\n * Create a number schema type with optional min/max constraints.\n *\n * @example\n * ```typescript\n * // Basic number\n * schema: { count: t.number() }\n *\n * // With range constraints\n * schema: { age: t.number().min(0).max(150) }\n *\n * // With custom validation\n * schema: { even: t.number().validate(n => n % 2 === 0) }\n *\n * // With default\n * schema: { count: t.number().default(0) }\n *\n * // With transform (from string)\n * schema: { age: t.number().transform(v => parseInt(String(v), 10)) }\n * ```\n */\n number() {\n type ChainableNumber = ChainableSchemaType<number> & {\n min(n: number): ChainableNumber;\n max(n: number): ChainableNumber;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableNumber;\n };\n\n const createChainableNumber = (\n validators: Array<(v: number) => boolean>,\n defaultValue?: number | (() => number),\n transform?: (value: unknown) => number,\n description?: string,\n refinements?: Array<{\n predicate: (value: number) => boolean;\n message: string;\n }>,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableNumber => {\n const chainable = createChainableType<number>(\n validators,\n \"number\",\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n return {\n ...chainable,\n min(n: number) {\n return createChainableNumber(\n [...validators, (v) => v >= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n max(n: number) {\n return createChainableNumber(\n [...validators, (v) => v <= n],\n defaultValue,\n transform,\n description,\n refinements,\n fm,\n );\n },\n default(value: number | (() => number)) {\n return createChainableNumber(\n validators,\n value,\n transform,\n description,\n refinements,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableNumber(\n validators,\n defaultValue,\n transform,\n desc,\n refinements,\n fm,\n );\n },\n refine(predicate: (value: number) => boolean, message: string) {\n const newRefinements = [\n ...(refinements ?? []),\n { predicate, message },\n ];\n return createChainableNumber(\n [...validators, predicate],\n defaultValue,\n transform,\n description,\n newRefinements,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableNumber(\n validators,\n defaultValue,\n transform,\n description,\n refinements,\n m,\n );\n },\n };\n };\n return createChainableNumber([(v) => typeof v === \"number\"]);\n },\n\n /**\n * Create a boolean schema type.\n *\n * @example\n * ```typescript\n * schema: {\n * active: t.boolean(),\n * verified: t.boolean().default(false),\n * }\n * ```\n */\n boolean() {\n return createChainableType<boolean>(\n [(v) => typeof v === \"boolean\"],\n \"boolean\",\n );\n },\n\n /**\n * Create an array schema type.\n * Can be used with or without element validation:\n * - `t.array<string>()` - Type-only, no element validation\n * - `t.array<string>().of(t.string())` - With element validation\n */\n array<T>() {\n type ChainableArray = ChainableSchemaType<T[]> & {\n of(elementType: SchemaType<T>): ChainableArray;\n nonEmpty(): ChainableArray;\n maxLength(n: number): ChainableArray;\n minLength(n: number): ChainableArray;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableArray;\n _lastFailedIndex?: number;\n };\n\n const createChainableArray = (\n validators: Array<(v: T[]) => boolean>,\n elementType?: SchemaType<T>,\n defaultValue?: T[] | (() => T[]),\n description?: string,\n indexRef?: { value: number },\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableArray => {\n const chainable = createChainableType<T[]>(\n validators,\n \"array\",\n defaultValue,\n undefined,\n description,\n undefined,\n fm,\n );\n // Use ref for storing failed index (shared with validator closure)\n const ref = indexRef ?? { value: -1 };\n const result: ChainableArray = {\n ...chainable,\n get _lastFailedIndex() {\n return ref.value;\n },\n set _lastFailedIndex(v: number) {\n ref.value = v;\n },\n of(et: SchemaType<T>) {\n const newRef = { value: -1 };\n return createChainableArray(\n [\n ...validators,\n (v) => {\n for (let i = 0; i < v.length; i++) {\n if (!et._validators.every((validator) => validator(v[i]))) {\n newRef.value = i;\n return false;\n }\n }\n return true;\n },\n ],\n et,\n defaultValue,\n description,\n newRef,\n fm,\n );\n },\n nonEmpty() {\n return createChainableArray(\n [...validators, (v) => v.length > 0],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n maxLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length <= n],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n minLength(n: number) {\n return createChainableArray(\n [...validators, (v) => v.length >= n],\n elementType,\n defaultValue,\n description,\n ref,\n fm,\n );\n },\n default(value: T[] | (() => T[])) {\n return createChainableArray(\n validators,\n elementType,\n value,\n description,\n ref,\n fm,\n );\n },\n describe(desc: string) {\n return createChainableArray(\n validators,\n elementType,\n defaultValue,\n desc,\n ref,\n fm,\n );\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableArray(\n validators,\n elementType,\n defaultValue,\n description,\n ref,\n m,\n );\n },\n };\n return result;\n };\n return createChainableArray([(v) => Array.isArray(v)]);\n },\n\n /**\n * Create an object schema type for any complex value.\n * Can be used with or without shape validation:\n * - `t.object<User>()` - Type-only, no property validation\n * - `t.object<User>().shape({ name: t.string(), age: t.number() })` - With property validation\n *\n * For arrays, prefer `t.array<T>()` which adds `Array.isArray` validation.\n */\n object<T>() {\n type ChainableObject = ChainableSchemaType<T> & {\n shape(schema: { [K in keyof T]?: SchemaType<T[K]> }): ChainableObject;\n nonNull(): ChainableObject;\n hasKeys(...keys: string[]): ChainableObject;\n meta(m: import(\"./types/meta.js\").DefinitionMeta): ChainableObject;\n };\n\n const createChainableObject = (\n validators: Array<(v: T) => boolean>,\n defaultValue?: T | (() => T),\n description?: string,\n fm?: import(\"./types/meta.js\").DefinitionMeta,\n ): ChainableObject => {\n const chainable = createChainableType<T>(\n validators,\n \"object\",\n defaultValue,\n undefined,\n description,\n undefined,\n fm,\n );\n return {\n ...chainable,\n shape(shapeSchema: { [K in keyof T]?: SchemaType<T[K]> }) {\n return createChainableObject(\n [\n ...validators,\n (v) => {\n for (const [key, schemaType] of Object.entries(shapeSchema)) {\n const value = (v as Record<string, unknown>)[key];\n const schemaT = schemaType as SchemaType<unknown>;\n if (\n schemaT &&\n !schemaT._validators.every((validator) => validator(value))\n ) {\n return false;\n }\n }\n return true;\n },\n ],\n defaultValue,\n description,\n fm,\n );\n },\n nonNull() {\n return createChainableObject(\n [...validators, (v) => v !== null && v !== undefined],\n defaultValue,\n description,\n fm,\n );\n },\n hasKeys(...keys: string[]) {\n return createChainableObject(\n [\n ...validators,\n (v) => keys.every((k) => k in (v as Record<string, unknown>)),\n ],\n defaultValue,\n description,\n fm,\n );\n },\n default(value: T | (() => T)) {\n return createChainableObject(validators, value, description, fm);\n },\n describe(desc: string) {\n return createChainableObject(validators, defaultValue, desc, fm);\n },\n meta(m: import(\"./types/meta.js\").DefinitionMeta) {\n return createChainableObject(\n validators,\n defaultValue,\n description,\n m,\n );\n },\n };\n };\n return createChainableObject([\n (v) => typeof v === \"object\" && v !== null && !Array.isArray(v),\n ]);\n },\n\n /**\n * Create an enum schema type for string literal unions.\n *\n * @example\n * ```typescript\n * // Define allowed values\n * schema: { status: t.enum(\"idle\", \"loading\", \"success\", \"error\") }\n *\n * // Type is inferred as \"idle\" | \"loading\" | \"success\" | \"error\"\n * ```\n */\n enum<T extends string>(...values: T[]) {\n if (isDevelopment && values.length === 0) {\n console.warn(\n \"[Directive] t.enum() called with no values - this will reject all strings\",\n );\n }\n const valueSet = new Set(values);\n return createChainableType<T>(\n [(v): v is T => typeof v === \"string\" && valueSet.has(v as T)],\n `enum(${values.join(\"|\")})`,\n );\n },\n\n /**\n * Create a literal schema type for exact value matching.\n *\n * @example\n * ```typescript\n * // Exact string match\n * schema: { type: t.literal(\"user\") }\n *\n * // Exact number match\n * schema: { version: t.literal(1) }\n *\n * // Exact boolean\n * schema: { enabled: t.literal(true) }\n * ```\n */\n literal<T extends string | number | boolean>(value: T) {\n return createChainableType<T>(\n [(v): v is T => v === value],\n `literal(${String(value)})`,\n );\n },\n\n /**\n * Create a nullable schema type (T | null).\n *\n * @example\n * ```typescript\n * // Nullable string\n * schema: { name: t.nullable(t.string()) }\n *\n * // Nullable object\n * schema: { user: t.nullable(t.object<User>()) }\n * ```\n */\n nullable<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | null>(\n [\n (v): v is T | null => {\n if (v === null) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | null`,\n ) as SchemaType<T | null>;\n },\n\n /**\n * Create an optional schema type (T | undefined).\n *\n * @example\n * ```typescript\n * // Optional string\n * schema: { nickname: t.optional(t.string()) }\n *\n * // Optional number\n * schema: { age: t.optional(t.number()) }\n * ```\n */\n optional<T>(innerType: SchemaType<T>) {\n const innerTypeName =\n (innerType as ExtendedSchemaType<T>)._typeName ?? \"unknown\";\n return createSchemaType<T | undefined>(\n [\n (v): v is T | undefined => {\n if (v === undefined) {\n return true;\n }\n return innerType._validators.every((validator) => validator(v as T));\n },\n ],\n `${innerTypeName} | undefined`,\n ) as SchemaType<T | undefined>;\n },\n\n /**\n * Create a union schema type.\n *\n * **Two forms:**\n * - `t.union(t.string(), t.number())` — variadic schema args; the runtime\n * validator checks that the value matches at least one inner schema.\n * - `t.union<string | number | boolean>()` — generic-only form with no\n * schema args; the runtime validator accepts ANY value (mirrors\n * {@link unknown} plus generic narrowing). Use this for polymorphic\n * payloads where the union is too dynamic to enumerate as inner schemas\n * (e.g. an `UPDATE_FIELD` event whose `value` may be `string | number |\n * boolean | Date`).\n *\n * Chainable methods (`.validate`, `.transform`, `.default`, `.describe`,\n * `.refine`, `.optional`, `.nullable`) work the same for both forms.\n *\n * @example\n * ```typescript\n * // Variadic — runtime validation against inner schemas\n * schema: { value: t.union(t.string(), t.number()) }\n *\n * // Generic-only — type-only narrowing, runtime accepts any value\n * schema: {\n * payload: t.union<string | number | boolean>(),\n * }\n *\n * // Add a custom predicate via .validate when you still want a runtime check\n * schema: {\n * strict: t.union<string | number>().validate(\n * (v) => typeof v === \"string\" || typeof v === \"number\",\n * ),\n * }\n * ```\n */\n union: unionImpl,\n\n /**\n * Create a record schema type for dynamic key-value maps.\n *\n * @example\n * ```typescript\n * // Record with string values\n * schema: { metadata: t.record(t.string()) }\n *\n * // Record with number values\n * schema: { scores: t.record(t.number()) }\n * ```\n */\n record<V>(valueType: SchemaType<V>) {\n const valueTypeName =\n (valueType as ExtendedSchemaType<V>)._typeName ?? \"unknown\";\n return createChainableType<Record<string, V>>(\n [\n (v): v is Record<string, V> => {\n if (typeof v !== \"object\" || v === null || Array.isArray(v))\n return false;\n return Object.values(v).every((val) =>\n valueType._validators.every((validator) => validator(val)),\n );\n },\n ],\n `Record<string, ${valueTypeName}>`,\n );\n },\n\n /**\n * Create a tuple schema type for fixed-length arrays with specific types.\n *\n * @example\n * ```typescript\n * // [string, number] tuple\n * schema: { coord: t.tuple(t.string(), t.number()) }\n *\n * // [x, y, z] coordinates\n * schema: { position: t.tuple(t.number(), t.number(), t.number()) }\n * ```\n */\n tuple<T extends SchemaType<unknown>[]>(...types: T) {\n if (isDevelopment && types.length === 0) {\n console.warn(\n \"[Directive] t.tuple() called with no types - this will only accept empty arrays\",\n );\n }\n type TupleType = {\n [K in keyof T]: T[K] extends SchemaType<infer U> ? U : never;\n };\n const typeNames = types.map(\n (schemaType) =>\n (schemaType as ExtendedSchemaType<unknown>)._typeName ?? \"unknown\",\n );\n return createChainableType<TupleType>(\n [\n (v): v is TupleType => {\n if (!Array.isArray(v) || v.length !== types.length) {\n return false;\n }\n return types.every((schemaType, i) =>\n schemaType._validators.every((validator) => validator(v[i])),\n );\n },\n ],\n `[${typeNames.join(\", \")}]`,\n );\n },\n\n /**\n * Create a date schema type.\n *\n * @example\n * ```typescript\n * schema: { createdAt: t.date() }\n * ```\n */\n date() {\n return createChainableType<Date>(\n [(v): v is Date => v instanceof Date && !Number.isNaN(v.getTime())],\n \"Date\",\n );\n },\n\n /**\n * Create a UUID schema type.\n *\n * @example\n * ```typescript\n * schema: { id: t.uuid() }\n * ```\n */\n uuid() {\n const uuidRegex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && uuidRegex.test(v)],\n \"uuid\",\n );\n },\n\n /**\n * Create an email schema type.\n *\n * @example\n * ```typescript\n * schema: { email: t.email() }\n * ```\n */\n email() {\n // Simple email regex - for comprehensive validation use Zod\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return createChainableType<string>(\n [(v): v is string => typeof v === \"string\" && emailRegex.test(v)],\n \"email\",\n );\n },\n\n /**\n * Create a URL schema type.\n *\n * @example\n * ```typescript\n * schema: { website: t.url() }\n * ```\n */\n url() {\n return createChainableType<string>(\n [\n (v): v is string => {\n if (typeof v !== \"string\") {\n return false;\n }\n try {\n new URL(v);\n return true;\n } catch {\n return false;\n }\n },\n ],\n \"url\",\n );\n },\n\n /**\n * Create a bigint schema type.\n *\n * @example\n * ```typescript\n * schema: { largeNumber: t.bigint() }\n * ```\n */\n bigint() {\n return createChainableType<bigint>(\n [(v): v is bigint => typeof v === \"bigint\"],\n \"bigint\",\n );\n },\n\n /**\n * Create an `any` schema type that accepts all values without validation.\n *\n * @example\n * ```typescript\n * schema: { payload: t.any() }\n * ```\n */\n // biome-ignore lint/suspicious/noExplicitAny: Intentional any type for schema builder\n any() {\n return createChainableType<any>([], \"any\");\n },\n\n /**\n * Create an `unknown` schema type that accepts all values without validation.\n * Prefer `t.unknown()` over `t.any()` for stricter downstream type checking.\n *\n * @example\n * ```typescript\n * schema: { data: t.unknown() }\n * ```\n */\n unknown() {\n return createChainableType<unknown>([], \"unknown\");\n },\n};\n","/**\n * Module - The declarative API for defining Directive modules\n *\n * Modules group related facts, constraints, resolvers, effects, and derivations.\n */\n\nimport isDevelopment from \"#is-development\";\nimport type {\n CrossModuleConstraintsDef,\n CrossModuleDeps,\n CrossModuleDerivationsDef,\n CrossModuleEffectsDef,\n DefinitionMeta,\n EffectsDef,\n Facts,\n ModuleDef,\n ModuleHooks,\n ModuleSchema,\n TypedConstraintsDef,\n TypedDerivationsDef,\n TypedEventsDef,\n TypedResolversDef,\n} from \"./types.js\";\n\n// ============================================================================\n// Module Configuration\n// ============================================================================\n\n/**\n * Module configuration with consolidated schema.\n *\n * derive and events are optional - omit them if your schema has empty derivations/events.\n */\nexport interface ModuleConfig<M extends ModuleSchema> {\n schema: M;\n init?: (facts: Facts<M[\"facts\"]>) => void;\n derive?: TypedDerivationsDef<M>;\n events?: TypedEventsDef<M>;\n effects?: EffectsDef<M[\"facts\"]>;\n constraints?: TypedConstraintsDef<M>;\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n/**\n * Module configuration with cross-module dependencies for type-safe access\n * to other modules' facts in effects and constraints.\n *\n * When crossModuleDeps is provided:\n * - Own module facts: `facts.self.*`\n * - Cross-module facts: `facts.{dep}.*`\n *\n * @example\n * ```typescript\n * import { authSchema } from './auth';\n * import { dataSchema } from './data';\n *\n * const uiModule = createModule(\"ui\", {\n * schema: uiSchema,\n * crossModuleDeps: { auth: authSchema, data: dataSchema },\n * effects: {\n * onAuthChange: {\n * run: (facts) => {\n * facts.self.notifications // ✅ own module via \"self\"\n * facts.auth.isAuthenticated // ✅ cross-module (namespaced)\n * facts.data.users // ✅ cross-module (namespaced)\n * }\n * }\n * },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * require: { type: \"FETCH_USERS\" },\n * }\n * }\n * });\n * ```\n */\nexport interface ModuleConfigWithDeps<\n M extends ModuleSchema,\n Deps extends CrossModuleDeps,\n> {\n schema: M;\n /**\n * Cross-module dependencies for type-safe access in derive/effects/constraints.\n *\n * **Access patterns by context:**\n * - `derive`, `effects`, `constraints`: Use `facts.self.*` for own module, `facts.{dep}.*` for cross-module\n * - `init`, `events`, `resolvers`: Use flat access (`facts.myFact`) - no cross-module access\n *\n * This separation ensures initialization and event handling stay scoped to own module,\n * while observers (derive/effects/constraints) can see across modules.\n *\n * @example\n * ```typescript\n * crossModuleDeps: { auth: authSchema },\n * init: (facts) => { facts.users = []; }, // flat access\n * derive: { count: (facts) => facts.self.users.length }, // facts.self.*\n * effects: { log: { run: (facts) => console.log(facts.auth.token) } }, // facts.{dep}.*\n * ```\n */\n crossModuleDeps: Deps;\n /** Initialize module facts. Uses flat access (`facts.myFact`) to ensure modules initialize independently. */\n init?: (facts: Facts<M[\"facts\"]>) => void;\n /** Derivations with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n derive?: CrossModuleDerivationsDef<M, Deps>;\n /** Event handlers. Uses flat access (`facts.myFact`) to keep mutations scoped to own module. */\n events?: TypedEventsDef<M>;\n /** Effects with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n effects?: CrossModuleEffectsDef<M, Deps>;\n /** Constraints with cross-module facts access (`facts.self.*` + `facts.{dep}.*`) */\n constraints?: CrossModuleConstraintsDef<M, Deps>;\n /** Resolvers. Uses flat access (`ctx.facts.myFact`) to keep async mutations scoped to own module. */\n resolvers?: TypedResolversDef<M>;\n hooks?: ModuleHooks<M>;\n /** Optional metadata for debugging and devtools (never read on hot path). */\n meta?: DefinitionMeta;\n /** History configuration — controls which events create snapshots for undo/redo. */\n history?: {\n /** Events that create history snapshots. Omit to snapshot all events. */\n snapshotEvents?: Array<\n keyof (M[\"events\"] extends Record<string, unknown>\n ? M[\"events\"]\n : Record<string, never>) &\n string\n >;\n };\n}\n\n// ============================================================================\n// Module Validation Helpers (dev-mode only)\n// ============================================================================\n\n/** Validate module ID follows naming conventions */\nfunction validateModuleId(id: string): void {\n if (!id || typeof id !== \"string\") {\n console.warn(\"[Directive] Module ID must be a non-empty string\");\n\n return;\n }\n if (!/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(id)) {\n console.warn(\n `[Directive] Module ID \"${id}\" should follow kebab-case convention (e.g., \"my-module\")`,\n );\n }\n}\n\n/** Warn when keys in `implKeys` are missing from `schemaKeys` and vice versa */\nfunction validateKeyAlignment(\n implKeys: Set<string>,\n schemaKeys: Set<string>,\n implLabel: string,\n schemaLabel: string,\n missingImplMessage: string,\n): void {\n for (const key of implKeys) {\n if (!schemaKeys.has(key)) {\n console.warn(\n `[Directive] ${implLabel} \"${key}\" not declared in ${schemaLabel}`,\n );\n }\n }\n for (const key of schemaKeys) {\n if (!implKeys.has(key)) {\n console.warn(\n `[Directive] ${schemaLabel}[\"${key}\"] ${missingImplMessage}`,\n );\n }\n }\n}\n\n/** Validate history.snapshotEvents reference valid event names */\nfunction validateSnapshotEvents(\n snapshotEvents: string[],\n schemaEvents: Record<string, unknown>,\n): void {\n if (snapshotEvents.length === 0) {\n console.warn(\n \"[Directive] history.snapshotEvents is an empty array — no events will create history snapshots. \" +\n \"Omit history.snapshotEvents entirely to snapshot all events, or list specific events.\",\n );\n }\n const schemaEventKeys = new Set(Object.keys(schemaEvents));\n for (const eventName of snapshotEvents) {\n if (!schemaEventKeys.has(eventName)) {\n console.warn(\n `[Directive] history.snapshotEvents entry \"${eventName}\" not declared in schema.events. ` +\n `Available events: ${[...schemaEventKeys].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/** Validate resolvers reference valid requirement types */\nfunction validateResolverRequirements(\n resolvers: Record<string, unknown>,\n requirements: Record<string, unknown>,\n): void {\n const requirementTypes = new Set(Object.keys(requirements));\n for (const [resolverName, resolver] of Object.entries(resolvers)) {\n const resolverDef = resolver as { requirement?: string };\n if (\n typeof resolverDef.requirement === \"string\" &&\n !requirementTypes.has(resolverDef.requirement)\n ) {\n console.warn(\n `[Directive] Resolver \"${resolverName}\" references unknown requirement type \"${resolverDef.requirement}\". ` +\n `Available types: ${[...requirementTypes].join(\", \") || \"(none)\"}`,\n );\n }\n }\n}\n\n/** Run all dev-mode validations for a module config */\nfunction validateModuleConfig<M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): void {\n validateModuleId(id);\n\n if (!config.schema) {\n console.warn(\"[Directive] Module schema is required\");\n } else if (!config.schema.facts) {\n console.warn(\"[Directive] Module schema.facts is required\");\n }\n\n validateKeyAlignment(\n new Set(Object.keys(config.derive ?? {})),\n new Set(Object.keys(config.schema?.derivations ?? {})),\n \"Derivation\",\n \"schema.derivations\",\n \"has no matching implementation in derive\",\n );\n\n validateKeyAlignment(\n new Set(Object.keys(config.events ?? {})),\n new Set(Object.keys(config.schema?.events ?? {})),\n \"Event\",\n \"schema.events\",\n \"has no matching handler in events\",\n );\n\n if (config.history?.snapshotEvents) {\n validateSnapshotEvents(\n config.history.snapshotEvents as string[],\n config.schema?.events ?? {},\n );\n }\n\n if (config.resolvers && config.schema?.requirements) {\n validateResolverRequirements(\n config.resolvers as Record<string, unknown>,\n config.schema.requirements,\n );\n }\n}\n\n// ============================================================================\n// createModule\n// ============================================================================\n\n/**\n * Create a module definition with full type inference.\n *\n * The consolidated schema provides:\n * - Derivation composition (`derived.otherDerivation` is typed)\n * - Event dispatch (`system.dispatch({ type: \"...\" })` has autocomplete)\n * - Resolver requirements (`req.payload` is typed based on requirement type)\n *\n * @param id - Unique module identifier (kebab-case recommended)\n * @param config - Module configuration including schema, init, derive, constraints, resolvers, etc.\n * @returns A frozen module definition ready for use with `createSystem`\n *\n * @example\n * ```ts\n * const trafficLight = createModule(\"traffic-light\", {\n * schema: {\n * facts: {\n * phase: t.string<\"red\" | \"green\" | \"yellow\">(),\n * elapsed: t.number(),\n * },\n * derivations: {\n * isRed: t.boolean(),\n * timeRemaining: t.number(),\n * },\n * events: {\n * tick: {},\n * setPhase: { phase: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * requirements: {\n * TRANSITION: { to: t.string<\"red\" | \"green\" | \"yellow\">() },\n * },\n * },\n * init: (facts) => {\n * facts.phase = \"red\";\n * facts.elapsed = 0;\n * },\n * derive: {\n * isRed: (facts) => facts.phase === \"red\",\n * timeRemaining: (facts, derived) => {\n * // derived.isRed is typed as boolean!\n * return derived.isRed ? 30 - facts.elapsed : 0;\n * },\n * },\n * events: {\n * tick: (facts) => { facts.elapsed += 1; },\n * setPhase: (facts, { phase }) => { facts.phase = phase; }, // phase is typed!\n * },\n * constraints: {\n * shouldTransition: {\n * when: (facts) => facts.phase === \"red\" && facts.elapsed > 30,\n * require: { type: \"TRANSITION\", to: \"green\" },\n * },\n * },\n * resolvers: {\n * transition: {\n * requirement: \"TRANSITION\",\n * resolve: async (req, ctx) => {\n * ctx.facts.phase = req.to; // req.to is typed!\n * ctx.facts.elapsed = 0;\n * },\n * },\n * },\n * hooks: {\n * // Optional: observe resolver failures owned by this module.\n * // Fires AFTER retries are exhausted and the engine has handled the error\n * // (error boundary, plugin emit, retry decision). Use it as a side-channel\n * // observer for module-local logging/telemetry — not for recovery.\n * onResolverError: (error, requirement, ctx) => {\n * console.warn(`[traffic-light] resolver failed for ${requirement.type}`, error);\n * },\n * },\n * });\n * ```\n *\n * @example With cross-module dependencies\n * ```ts\n * import { authSchema } from './auth';\n *\n * const dataModule = createModule(\"data\", {\n * schema: dataSchema,\n * crossModuleDeps: { auth: authSchema },\n * constraints: {\n * fetchWhenAuth: {\n * when: (facts) => {\n * // facts.self.* for own module, facts.auth.* for cross-module\n * return facts.auth.isAuthenticated && facts.self.users.length === 0;\n * },\n * require: { type: \"FETCH_USERS\" },\n * },\n * },\n * derive: {\n * canFetch: (facts) => facts.auth.isAuthenticated && facts.self.users.length === 0,\n * },\n * });\n * ```\n *\n * @public\n */\n// Overload 1: With crossModuleDeps\nexport function createModule<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(id: string, config: ModuleConfigWithDeps<M, Deps>): ModuleDef<M>;\n\n// Overload 2: Without crossModuleDeps (original signature)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M>,\n): ModuleDef<M>;\n\n// Overload 3: Union (used by createModuleFactory)\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfigWithDeps<M, CrossModuleDeps> | ModuleConfig<M>,\n): ModuleDef<M>;\n\n/** @internal Implementation overload — see public overloads above. */\nexport function createModule<const M extends ModuleSchema>(\n id: string,\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): ModuleDef<M> {\n if (isDevelopment) {\n validateModuleConfig(id, config);\n }\n\n // Extract crossModuleDeps if present (for runtime proxy creation)\n const crossModuleDeps =\n \"crossModuleDeps\" in config ? config.crossModuleDeps : undefined;\n\n return {\n id,\n schema: config.schema,\n init: config.init,\n // Cast to TypedDerivationsDef for ModuleDef compatibility (runtime handles both types)\n derive: (config.derive ?? {}) as TypedDerivationsDef<M>,\n events: config.events ?? ({} as TypedEventsDef<M>),\n effects: config.effects as EffectsDef<M[\"facts\"]> | undefined,\n constraints: config.constraints as TypedConstraintsDef<M> | undefined,\n resolvers: config.resolvers,\n hooks: config.hooks,\n meta: config.meta,\n history: config.history,\n // Store crossModuleDeps for runtime proxy creation\n crossModuleDeps: crossModuleDeps as CrossModuleDeps | undefined,\n };\n}\n\n/**\n * Create a module factory that produces named instances from a single definition.\n * Useful for multi-instance UIs (tabs, panels, multi-tenant) where you need\n * isolated state from the same schema.\n *\n * @param config - Module configuration (same shape as `createModule` minus the `id`)\n * @returns A factory function that accepts a name and returns a `ModuleDef`\n *\n * @example\n * ```typescript\n * const chatRoom = createModuleFactory({\n * schema: {\n * facts: { messages: t.array<string>(), users: t.array<string>() },\n * derivations: { count: t.number() },\n * },\n * init: (facts) => { facts.messages = []; facts.users = []; },\n * derive: { count: (facts) => facts.messages.length },\n * });\n *\n * const system = createSystem({\n * modules: {\n * lobby: chatRoom(\"lobby\"),\n * support: chatRoom(\"support\"),\n * },\n * });\n * ```\n *\n * @public\n */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M>,\n): (name: string) => ModuleDef<M>;\nexport function createModuleFactory<\n const M extends ModuleSchema,\n const Deps extends CrossModuleDeps,\n>(config: ModuleConfigWithDeps<M, Deps>): (name: string) => ModuleDef<M>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createModuleFactory<const M extends ModuleSchema>(\n config: ModuleConfig<M> | ModuleConfigWithDeps<M, CrossModuleDeps>,\n): (name: string) => ModuleDef<M> {\n // Pass config directly — createModule's implementation overload handles both types.\n // Do NOT cast to ModuleConfig<M> which would strip crossModuleDeps.\n return (name: string) => createModule(name, config);\n}\n","/**\n * Requirement Status Utilities\n *\n * Provides reactive tracking of requirement status for UI feedback.\n */\n\nimport type { Plugin, RequirementWithId } from \"../core/types.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Status of a requirement type */\nexport interface RequirementTypeStatus {\n /** Number of pending (unmet) requirements of this type */\n pending: number;\n /** Number of inflight (being resolved) requirements of this type */\n inflight: number;\n /** Number of failed requirements of this type */\n failed: number;\n /** Whether any requirements of this type are loading (pending or inflight) */\n isLoading: boolean;\n /** Whether any requirements of this type have failed */\n hasError: boolean;\n /** Last error for this type (if any) */\n lastError: Error | null;\n}\n\n/** Status tracking state */\ninterface StatusState {\n pending: Map<string, Set<string>>; // type -> set of requirement IDs\n inflight: Map<string, Set<string>>; // type -> set of requirement IDs\n failed: Map<string, Set<string>>; // type -> set of requirement IDs\n errors: Map<string, Error>; // type -> last error\n listeners: Set<() => void>;\n}\n\n// ============================================================================\n// Requirement Status Plugin\n// ============================================================================\n\n/**\n * Create a plugin that tracks requirement status for reactive UI updates.\n *\n * @example\n * ```typescript\n * import { createRequirementStatusPlugin } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n *\n * const system = createSystem({\n * modules: [myModule],\n * plugins: [statusPlugin.plugin],\n * });\n *\n * // Get status for a requirement type\n * const status = statusPlugin.getStatus(\"FETCH_USER\");\n * console.log(status.isLoading, status.hasError);\n *\n * // Subscribe to status changes\n * const unsubscribe = statusPlugin.subscribe(() => {\n * console.log(\"Status changed:\", statusPlugin.getStatus(\"FETCH_USER\"));\n * });\n * ```\n */\nexport function createRequirementStatusPlugin(): {\n plugin: Plugin<never>;\n getStatus: (type: string) => RequirementTypeStatus;\n getAllStatus: () => Map<string, RequirementTypeStatus>;\n subscribe: (listener: () => void) => () => void;\n reset: () => void;\n} {\n const state: StatusState = {\n pending: new Map(),\n inflight: new Map(),\n failed: new Map(),\n errors: new Map(),\n listeners: new Set(),\n };\n\n /** Notify all listeners */\n function notify(): void {\n for (const listener of state.listeners) {\n listener();\n }\n }\n\n /** Get or create a set for a type in a map */\n function getOrCreateSet(\n map: Map<string, Set<string>>,\n type: string,\n ): Set<string> {\n let set = map.get(type);\n if (!set) {\n set = new Set();\n map.set(type, set);\n }\n return set;\n }\n\n /** Get status for a requirement type */\n function getStatus(type: string): RequirementTypeStatus {\n const pendingSet = state.pending.get(type) ?? new Set();\n const inflightSet = state.inflight.get(type) ?? new Set();\n const failedSet = state.failed.get(type) ?? new Set();\n const lastError = state.errors.get(type) ?? null;\n\n return {\n pending: pendingSet.size,\n inflight: inflightSet.size,\n failed: failedSet.size,\n isLoading: pendingSet.size > 0 || inflightSet.size > 0,\n hasError: failedSet.size > 0,\n lastError,\n };\n }\n\n /** Get status for all tracked types */\n function getAllStatus(): Map<string, RequirementTypeStatus> {\n const allTypes = new Set([\n ...state.pending.keys(),\n ...state.inflight.keys(),\n ...state.failed.keys(),\n ]);\n\n const result = new Map<string, RequirementTypeStatus>();\n for (const type of allTypes) {\n result.set(type, getStatus(type));\n }\n return result;\n }\n\n /** Subscribe to status changes */\n function subscribe(listener: () => void): () => void {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n }\n\n /** Reset all status */\n function reset(): void {\n state.pending.clear();\n state.inflight.clear();\n state.failed.clear();\n state.errors.clear();\n notify();\n }\n\n const plugin: Plugin<never> = {\n name: \"requirement-status\",\n\n onRequirementCreated(req: RequirementWithId) {\n const type = req.requirement.type;\n getOrCreateSet(state.pending, type).add(req.id);\n // Clear from failed when a new requirement is created\n state.failed.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverStart(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Move from pending to inflight\n state.pending.get(type)?.delete(req.id);\n getOrCreateSet(state.inflight, type).add(req.id);\n notify();\n },\n\n onResolverComplete(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from inflight\n state.inflight.get(type)?.delete(req.id);\n state.pending.get(type)?.delete(req.id);\n notify();\n },\n\n onResolverError(_resolver: string, req: RequirementWithId, error: unknown) {\n const type = req.requirement.type;\n // Move from inflight to failed\n state.inflight.get(type)?.delete(req.id);\n getOrCreateSet(state.failed, type).add(req.id);\n state.errors.set(\n type,\n error instanceof Error ? error : new Error(String(error)),\n );\n notify();\n },\n\n onResolverCancel(_resolver: string, req: RequirementWithId) {\n const type = req.requirement.type;\n // Remove from all tracking\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n\n onRequirementMet(req: RequirementWithId) {\n const type = req.requirement.type;\n // Clean up when requirement is met\n state.pending.get(type)?.delete(req.id);\n state.inflight.get(type)?.delete(req.id);\n notify();\n },\n };\n\n return {\n plugin,\n getStatus,\n getAllStatus,\n subscribe,\n reset,\n };\n}\n\n// ============================================================================\n// React Hook Helper (for use with React adapter)\n// ============================================================================\n\n/**\n * Create a hook factory for requirement status.\n * This is designed to be used with React's useSyncExternalStore.\n *\n * @example\n * ```typescript\n * import { useSyncExternalStore } from 'react';\n * import { createRequirementStatusPlugin, createStatusHook } from '@directive-run/core';\n *\n * const statusPlugin = createRequirementStatusPlugin();\n * const useRequirementStatus = createStatusHook(statusPlugin);\n *\n * function MyComponent() {\n * const status = useRequirementStatus(\"FETCH_USER\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error error={status.lastError} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createStatusHook(\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>,\n): (type: string) => RequirementTypeStatus {\n // This returns a function that can be used with useSyncExternalStore\n // The actual hook implementation would be in the React adapter\n return (type: string) => statusPlugin.getStatus(type);\n}\n","/**\n * System with Status Plugin Helper\n *\n * Convenience function for creating a system with status tracking enabled.\n */\n\nimport { createSystem } from \"../core/system.js\";\nimport type {\n ErrorBoundaryConfig,\n ModuleDef,\n ModuleSchema,\n Plugin,\n SingleModuleSystem,\n TraceOption,\n} from \"../core/types.js\";\nimport { createRequirementStatusPlugin } from \"./requirement-status.js\";\n\n/** Options for createSystemWithStatus */\nexport interface CreateSystemWithStatusOptions<M extends ModuleSchema> {\n /** The module to use for the system */\n module: ModuleDef<M>;\n /** Additional plugins to include alongside the status plugin */\n // biome-ignore lint/suspicious/noExplicitAny: Plugin generic contravariance issues\n plugins?: Plugin<any>[];\n /** Trace: per-run reconciliation changelog */\n trace?: TraceOption;\n /** Error boundary configuration */\n errorBoundary?: ErrorBoundaryConfig;\n /** Tick interval in milliseconds */\n tickMs?: number;\n /** Enable zero-config mode */\n zeroConfig?: boolean;\n /** Initial facts to set on the system */\n // biome-ignore lint/suspicious/noExplicitAny: Facts type varies by module\n initialFacts?: Record<string, any>;\n}\n\n/** Return type for createSystemWithStatus */\nexport interface SystemWithStatus<M extends ModuleSchema> {\n /**\n * The Directive system instance.\n * This is a SingleModuleSystem - use system.facts, system.dispatch(), etc.\n */\n system: SingleModuleSystem<M>;\n /** The status plugin for use with useRequirementStatus hooks */\n statusPlugin: ReturnType<typeof createRequirementStatusPlugin>;\n}\n\n/**\n * Create a Directive system with a status plugin pre-configured.\n *\n * This is a convenience wrapper around `createSystem` and `createRequirementStatusPlugin`\n * that handles the wiring automatically. The status plugin is added to the system's\n * plugins array so it receives lifecycle events.\n *\n * @param options - System configuration options\n * @returns An object containing both the system and the statusPlugin\n *\n * @example\n * ```tsx\n * import { createSystemWithStatus } from '@directive-run/core';\n * import { useRequirementStatus, useFact } from '@directive-run/react';\n *\n * // Simple setup - no provider needed\n * const { system, statusPlugin } = createSystemWithStatus({\n * module: myModule,\n * });\n * system.start();\n *\n * function App() {\n * const data = useFact(system, \"data\");\n * return <LoadingIndicator />;\n * }\n *\n * function LoadingIndicator() {\n * const status = useRequirementStatus(statusPlugin, \"FETCH_DATA\");\n * if (status.isLoading) return <Spinner />;\n * if (status.hasError) return <Error message={status.lastError?.message} />;\n * return <Content />;\n * }\n * ```\n */\nexport function createSystemWithStatus<M extends ModuleSchema>(\n options: CreateSystemWithStatusOptions<M>,\n): SystemWithStatus<M> {\n // Create the status plugin\n const statusPlugin = createRequirementStatusPlugin();\n\n // Add the plugin to the options\n const existingPlugins = options.plugins ?? [];\n\n // Create the system with the status plugin included\n // Use type assertion to bypass overload resolution issues\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const allPlugins = [...existingPlugins, statusPlugin.plugin] as Plugin<any>[];\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n const system = createSystem({\n module: options.module,\n plugins: allPlugins,\n trace: options.trace,\n errorBoundary: options.errorBoundary,\n tickMs: options.tickMs,\n zeroConfig: options.zeroConfig,\n initialFacts: options.initialFacts,\n // biome-ignore lint/suspicious/noExplicitAny: Required for overload compatibility\n } as any);\n\n return {\n // The system returned by createSystem with a single module is a SingleModuleSystem\n system: system as SingleModuleSystem<M>,\n statusPlugin,\n };\n}\n","/**\n * SignalClock — injectable clock source for declarative timers (RFC 0001).\n *\n * The clock interface decouples Directive's timer primitives from any\n * single time source. Production uses `realClock()`. Tests use\n * `virtualClock()` which advances synchronously via `clock.advanceBy()`.\n * Replay / dehydrate scenarios use a clock seeded from the recorded\n * stream.\n *\n * Auto-detection: `defaultClock()` returns `virtualClock()` when running\n * under Vitest (process.env.VITEST === 'true'), otherwise `realClock()`.\n * Consumers can pass an explicit clock to `createSystem({ clock })` to\n * override.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n/**\n * Stable interface for any time source.\n */\nexport interface SignalClock {\n /** Current time, in milliseconds since the Unix epoch. */\n now(): number;\n /**\n * Schedule a callback to fire after `ms` milliseconds. Returns a\n * cancellation function. Implementations may queue callbacks or fire\n * them on a tick boundary; the only contract is \"fires no earlier\n * than `ms` from now.\"\n */\n setTimeout(cb: () => void, ms: number): () => void;\n /**\n * (Test-only.) Synchronously advance the clock by `ms` milliseconds,\n * firing all scheduled callbacks whose deadlines fall within the\n * advanced window. Real clocks throw if called.\n */\n advanceBy?(ms: number): void;\n}\n\n/**\n * Production clock — wraps `Date.now()` and `globalThis.setTimeout`.\n * No mocking, no virtualization.\n */\nexport function realClock(): SignalClock {\n return {\n now: () => Date.now(),\n setTimeout: (cb, ms) => {\n const handle = globalThis.setTimeout(cb, ms);\n return () => globalThis.clearTimeout(handle);\n },\n };\n}\n\n/**\n * Virtual clock — advances only when `advanceBy(ms)` is called. All\n * scheduled callbacks fire synchronously in order of their deadlines.\n *\n * Two scheduled callbacks at the same deadline fire in registration order.\n * Cancellation is O(1).\n */\nexport function virtualClock(initialMs = 0): SignalClock {\n let nowMs = initialMs;\n let nextId = 0;\n interface Scheduled {\n id: number;\n deadlineMs: number;\n cb: () => void;\n canceled: boolean;\n }\n const queue: Scheduled[] = [];\n\n return {\n now: () => nowMs,\n setTimeout: (cb, ms) => {\n const entry: Scheduled = {\n id: nextId++,\n deadlineMs: nowMs + ms,\n cb,\n canceled: false,\n };\n queue.push(entry);\n return () => {\n entry.canceled = true;\n };\n },\n advanceBy: (ms) => {\n const targetMs = nowMs + ms;\n // Fire all callbacks whose deadlines fall in [nowMs, targetMs].\n // Sort live entries by deadline + registration order so ties\n // resolve deterministically.\n while (true) {\n const ready = queue\n .filter((e) => !e.canceled && e.deadlineMs <= targetMs)\n .sort((a, b) =>\n a.deadlineMs !== b.deadlineMs\n ? a.deadlineMs - b.deadlineMs\n : a.id - b.id,\n );\n if (ready.length === 0) break;\n const next = ready[0]!;\n // Advance \"now\" monotonically — never let a callback that\n // schedules another callback in the past pull `nowMs`\n // backward. Without this clamp, `setTimeout(cb2, -5)` from\n // inside a callback would make `clock.now()` return a smaller\n // value mid-advance, breaking elapsedMs (negative results)\n // and replay determinism. (R1 sec C3.)\n nowMs = Math.max(nowMs, next.deadlineMs);\n next.canceled = true;\n next.cb();\n }\n // Final advance — even if no callbacks fired in [nowMs, targetMs],\n // wall clock still moves forward.\n nowMs = Math.max(nowMs, targetMs);\n },\n };\n}\n\n/**\n * Returns `realClock()` always.\n *\n * Earlier drafts auto-detected vitest (`process.env.VITEST === 'true'`)\n * and returned a `virtualClock()` in that environment. AE review\n * flagged this as a footgun: tests that legitimately need real time\n * (sleep-based debounce checks, real-`setTimeout`-bound integration\n * fixtures) silently received a virtual clock that never advanced\n * unless the test author called `advanceBy()`, producing apparent\n * deadlocks indistinguishable from genuine bugs. Auto-detection is\n * therefore opt-in.\n *\n * Use {@link virtualClock} explicitly in tests:\n *\n * ```ts\n * const clock = virtualClock(0);\n * const sys = createSystem({ module, clock });\n * clock.advanceBy(1_000);\n * ```\n */\nexport function defaultClock(): SignalClock {\n return realClock();\n}\n","/**\n * Timer fact — a runtime container that advances over time on a\n * SignalClock (RFC 0001 v0.1).\n *\n * Produced by `createTimerFact(clock, opts)`. Holds the durable state\n * (startedAtMs, pausedDurationMs, status) and exposes a control surface\n * (start, pause, resume, reset) plus reactive reads (elapsedMs,\n * remainingMs, status).\n *\n * v0.1 SCOPE: timer is a \"thick fact\" — a single object you store in a\n * regular Directive fact (e.g. `t.object<TimerFactState>()`). The\n * engine doesn't auto-tick it; the consumer is responsible for calling\n * `timer.tick()` when they want elapsedMs / remainingMs to update.\n * Typical wiring: a setInterval in the consumer that calls `timer.tick()`\n * and dispatches an event when status changes.\n *\n * v0.2 (deferred): true `t.timer({ms})` schema integration where the\n * engine subscribes to the clock and writes the fact deltas itself,\n * eliminating the consumer-side tick wiring.\n *\n * @see ../../docs/rfcs/0001-t-timer.md\n */\n\n// SignalClock is the canonical time source for timer ops; consumers\n// pass `clock.now()` into the helpers below. Re-exported by index.ts\n// alongside this module so they can `import { realClock, timerOps,\n// initialTimerState } from \"@directive-run/core\"` together.\n\n/**\n * Persistent timer state — JSON-roundtrippable, suitable for storing\n * inside a Directive fact.\n */\nexport interface TimerFactState {\n /** Unix-ms when the timer last started or resumed. null = not running. */\n startedAtMs: number | null;\n /** Total ms accumulated while paused. */\n pausedDurationMs: number;\n /** ms when the timer was paused, if currently paused. null otherwise. */\n pausedAtMs: number | null;\n /**\n * - 'idle': not yet started, or reset.\n * - 'running': currently counting.\n * - 'paused': paused; pausedAtMs is set.\n * - 'completed': hit the deadline (countdown mode only).\n */\n status: \"idle\" | \"running\" | \"paused\" | \"completed\";\n /** Number of times the timer has fired (repeat mode only). */\n repeats: number;\n}\n\nexport interface TimerFactOpts {\n /** Duration in ms. Countdown mode counts this down; up mode counts up to ∞. */\n ms: number;\n /**\n * - 'down' (default): counts down from `ms` to 0; status → 'completed' at 0.\n * - 'up': counts elapsed time; never completes.\n * - 'repeat': fires every `ms`; increments `repeats`; status stays 'running'.\n */\n mode?: \"down\" | \"up\" | \"repeat\";\n}\n\n/**\n * Initial state for a newly-created timer. Pass this to your Directive\n * `init()` to seed the fact.\n */\nexport function initialTimerState(): TimerFactState {\n return {\n startedAtMs: null,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"idle\",\n repeats: 0,\n };\n}\n\n/**\n * Compute elapsed ms for a given timer state at a given clock-now.\n * Pure function — no side effects, no reads beyond its inputs.\n *\n * @example\n * ```ts\n * const elapsed = elapsedMs(facts.countdown, clock.now());\n * if (elapsed >= 60_000) {\n * facts.countdown = { ...facts.countdown, status: 'completed' };\n * }\n * ```\n */\nexport function elapsedMs(state: TimerFactState, nowMs: number): number {\n if (state.startedAtMs === null) return 0;\n // Clamp at 0 — a clock step-back (NTP correction, virtual-clock\n // re-entrancy, replay seeded from older snapshot) would otherwise\n // produce negative elapsed values that:\n // - make tickTimer never report 'complete' (because `elapsed >= ms`\n // stays false past the deadline)\n // - make remainingMs report values > the configured ms total\n // - silently wrap into pausedDurationMs accumulation downstream\n // (R1 sec C4.)\n if (state.status === \"paused\" && state.pausedAtMs !== null) {\n return Math.max(\n 0,\n state.pausedAtMs - state.startedAtMs - state.pausedDurationMs,\n );\n }\n return Math.max(0, nowMs - state.startedAtMs - state.pausedDurationMs);\n}\n\n/**\n * Compute remaining ms for a countdown timer at a given clock-now.\n * Returns 0 if the timer has hit zero or hasn't started.\n */\nexport function remainingMs(\n state: TimerFactState,\n nowMs: number,\n totalMs: number,\n): number {\n return Math.max(0, totalMs - elapsedMs(state, nowMs));\n}\n\n/**\n * Transition: start an idle (or reset) timer.\n *\n * No-op if already running, paused, or completed (use `reset()` first).\n */\nexport function startTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status === \"running\") return state;\n if (state.status === \"paused\") return state;\n return {\n ...state,\n startedAtMs: nowMs,\n pausedDurationMs: 0,\n pausedAtMs: null,\n status: \"running\",\n repeats: 0,\n };\n}\n\n/**\n * Transition: pause a running timer. Records the pause moment so a\n * later `resumeTimer()` can correctly extend pausedDurationMs.\n *\n * No-op if not running.\n */\nexport function pauseTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"running\") return state;\n return { ...state, pausedAtMs: nowMs, status: \"paused\" };\n}\n\n/**\n * Transition: resume a paused timer. Adds the time spent paused into\n * `pausedDurationMs` so elapsed/remaining math stays correct.\n *\n * No-op if not paused.\n */\nexport function resumeTimer(\n state: TimerFactState,\n nowMs: number,\n): TimerFactState {\n if (state.status !== \"paused\") return state;\n if (state.pausedAtMs === null) return state;\n // Clamp pausedFor at 0 — clock step-back between pause and resume\n // would otherwise produce a negative pausedDurationMs accumulation,\n // which propagates into elapsedMs (returns inflated values), which\n // prematurely completes countdowns. (R1 sec M1.)\n const pausedFor = Math.max(0, nowMs - state.pausedAtMs);\n return {\n ...state,\n pausedDurationMs: state.pausedDurationMs + pausedFor,\n pausedAtMs: null,\n status: \"running\",\n };\n}\n\n/**\n * Transition: reset a timer to idle. Loses all elapsed time + repeat\n * count. Equivalent to `initialTimerState()`.\n */\nexport function resetTimer(): TimerFactState {\n return initialTimerState();\n}\n\n/**\n * Transition: mark the timer completed. For countdown mode when\n * elapsed reaches `ms`; for repeat mode when consumer wants to halt.\n */\nexport function completeTimer(state: TimerFactState): TimerFactState {\n return { ...state, status: \"completed\" };\n}\n\n/**\n * Transition: register a repeat firing. Increments `repeats` and\n * advances `startedAtMs` by `ms` so the next interval lands at the\n * intended boundary (drift-free).\n */\nexport function registerRepeat(\n state: TimerFactState,\n ms: number,\n): TimerFactState {\n if (state.startedAtMs === null) return state;\n // Defensible-illegal: registerRepeat from a paused state would\n // otherwise advance startedAtMs while leaving status === 'paused',\n // producing an inconsistent state (logically running by clock math\n // but reads as paused). No-op instead. (R2 sec m-R2-2.)\n if (state.status === \"paused\") return state;\n // Reset pausedDurationMs on each repeat so accumulated pause time\n // from prior intervals does not double-count into the next\n // interval's elapsed math. Without this reset, every repeat after a\n // pause would arithmetic-drift the next deadline by the cumulative\n // pause window. (R1 sec M9.)\n return {\n ...state,\n startedAtMs: state.startedAtMs + ms,\n pausedDurationMs: 0,\n pausedAtMs: null,\n repeats: state.repeats + 1,\n };\n}\n\n/**\n * Higher-level helper: given a timer state, total ms, and the current\n * clock, return whether the timer should transition to 'completed' (for\n * countdown mode) or fire a repeat (for repeat mode).\n *\n * Pure — does not mutate state. Returns a structured signal the consumer\n * applies via `completeTimer` / `registerRepeat`.\n */\nexport function tickTimer(\n state: TimerFactState,\n nowMs: number,\n opts: TimerFactOpts,\n): { kind: \"no-op\" } | { kind: \"complete\" } | { kind: \"repeat\" } {\n if (state.status !== \"running\") return { kind: \"no-op\" };\n const elapsed = elapsedMs(state, nowMs);\n\n if (opts.mode === \"up\") {\n // 'up' never completes; consumer reads elapsedMs directly.\n return { kind: \"no-op\" };\n }\n\n if (opts.mode === \"repeat\") {\n if (elapsed >= opts.ms) return { kind: \"repeat\" };\n return { kind: \"no-op\" };\n }\n\n // 'down' (default)\n if (elapsed >= opts.ms) return { kind: \"complete\" };\n return { kind: \"no-op\" };\n}\n\n/**\n * Bundle of helpers for one timer in one module — convenience for\n * callers who want a single import. Each method takes the current\n * state and clock-now, returns the next state. No mutation.\n *\n * @example\n * ```ts\n * import {\n * createSystem,\n * t,\n * realClock,\n * timerOps,\n * initialTimerState,\n * type TimerFactState,\n * } from '@directive-run/core';\n *\n * const clock = realClock();\n * const ops = timerOps({ ms: 60_000, mode: 'down' });\n *\n * createModule('countdown', {\n * schema: { facts: { state: t.object<TimerFactState>() }, events: { START: {} } },\n * init: (f) => { f.state = initialTimerState(); },\n * events: {\n * START: (f) => { f.state = ops.start(f.state, clock.now()); },\n * },\n * });\n *\n * // In the consumer (React, Node, edge), tick periodically:\n * setInterval(() => {\n * const signal = ops.tick(f.state, clock.now());\n * if (signal.kind === 'complete') {\n * sys.dispatch({ type: 'TIMEOUT' });\n * }\n * }, 100);\n * ```\n */\nexport function timerOps(opts: TimerFactOpts) {\n return {\n initial: initialTimerState,\n start: startTimer,\n pause: pauseTimer,\n resume: resumeTimer,\n reset: resetTimer,\n complete: completeTimer,\n registerRepeat: (state: TimerFactState) => registerRepeat(state, opts.ms),\n tick: (state: TimerFactState, nowMs: number) =>\n tickTimer(state, nowMs, opts),\n elapsedMs,\n remainingMs: (state: TimerFactState, nowMs: number) =>\n remainingMs(state, nowMs, opts.ms),\n };\n}\n","/**\n * @directive-run/core\n *\n * Constraint-driven runtime for TypeScript.\n *\n * Also available:\n * - `@directive-run/core/internals` – Manager factories, engine, tracking, and internal types\n * - `@directive-run/core/plugins` – Logging, devtools, persistence, observability, circuit breaker\n * - `@directive-run/core/testing` – Mock resolvers, fake timers, assertion helpers\n * - `@directive-run/core/migration` – Redux/Zustand/XState migration scaffolding\n * - `@directive-run/core/adapter-utils` – Shared framework adapter utilities\n * - `@directive-run/core/worker` – Web Worker support\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Core Types — what 90% of users need\n// ============================================================================\n\nexport type {\n // Schema\n Schema,\n SchemaType,\n InferSchemaType,\n // Module Schema (consolidated)\n ModuleSchema,\n InferFacts,\n InferDerivations,\n InferSelectorState,\n InferEvents,\n InferRequirements,\n InferRequirementTypes,\n // Facts\n Facts,\n FactsSnapshot,\n // Requirements\n Requirement,\n RequirementWithId,\n // Constraints + Resolvers (config types)\n RetryPolicy,\n BatchConfig,\n // Plugins\n Plugin,\n Snapshot,\n // Errors\n ErrorBoundaryConfig,\n // Module\n ModuleDef,\n ModuleHooks,\n // System\n System,\n SystemConfig,\n SystemInspection,\n SystemSnapshot,\n MetaAccessor,\n MetaMatch,\n ObservationEvent,\n // Trace\n TraceEntry,\n TraceOption,\n // History\n HistoryOption,\n HistoryAPI,\n HistoryState,\n // Composition (Namespaced Multi-Module)\n ModulesMap,\n NamespacedSystem,\n CreateSystemOptionsNamed,\n // Single Module\n CreateSystemOptionsSingle,\n SingleModuleSystem,\n // Type Guards\n SystemMode,\n AnySystem,\n // Cross-Module Dependencies\n CrossModuleDeps,\n // Dynamic Definitions\n DynamicConstraintDef,\n DynamicEffectDef,\n DynamicResolverDef,\n // Definition Meta\n DefinitionMeta,\n DerivationDefWithMeta,\n // Data-configuration predicates and templates\n FactPredicate,\n FactTemplate,\n KeySelector,\n PatchSpec,\n PayloadRef,\n PatchValue,\n OperatorObject,\n PredicateObject,\n PredicateClause,\n PredicateCombinator,\n PredicateCombinatorKey,\n PredicateOp,\n ClauseResult,\n // Distributable Snapshots\n DistributableSnapshot,\n DistributableSnapshotOptions,\n} from \"./core/types.js\";\n\n// Predicate / template runtime\nexport {\n applyPatch,\n memoizePredicate,\n evaluateKeySelector,\n evaluatePredicate,\n evaluatePredicateExplained,\n evaluateTemplate,\n extractDeps,\n extractTemplateKeys,\n isPredicate,\n isTemplate,\n} from \"./core/predicate.js\";\n\n// ============================================================================\n// Core Classes\n// ============================================================================\n\nexport { DirectiveError } from \"./core/types.js\";\n\n// ============================================================================\n// Schema Type Builders\n// ============================================================================\n\n/**\n * Schema type builders for defining fact types.\n *\n * @example\n * ```ts\n * import { t } from '@directive-run/core';\n *\n * const schema = {\n * facts: {\n * count: t.number().min(0).default(0),\n * name: t.string(),\n * status: t.enum(\"idle\", \"loading\", \"error\"),\n * user: t.object<User>().nullable(),\n * },\n * derivations: { doubled: t.number() },\n * events: { increment: {} },\n * requirements: { FETCH_USER: {} },\n * };\n * ```\n */\nexport {\n t,\n type Branded,\n type ExtendedSchemaType,\n type ChainableSchemaType,\n} from \"./core/schema-builders.js\";\n\n// ============================================================================\n// Module & System\n// ============================================================================\n\nexport {\n createModule,\n createModuleFactory,\n type ModuleConfig,\n type ModuleConfigWithDeps,\n} from \"./core/module.js\";\nexport { createSystem } from \"./core/system.js\";\nexport { createSystemWithStatus } from \"./utils/system-with-status.js\";\n\n// Helper factory functions for typed constraint/resolver definitions\nexport {\n typedConstraint,\n typedResolver,\n} from \"./core/types.js\";\n\n// ============================================================================\n// Requirements Helpers\n// ============================================================================\n\nexport {\n req,\n forType,\n isRequirementType,\n generateRequirementId,\n RequirementSet,\n} from \"./core/requirements.js\";\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport {\n isSingleModuleSystem,\n isNamespacedSystem,\n} from \"./core/types/composition.js\";\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Backoff strategy constants for retry policies.\n *\n * @example\n * ```ts\n * import { Backoff } from '@directive-run/core';\n *\n * retry: { attempts: 3, backoff: Backoff.Exponential, initialDelay: 100 }\n * ```\n */\nexport const Backoff = {\n /** No delay between retries */\n None: \"none\",\n /** Linear delay increase (initialDelay * attempt) */\n Linear: \"linear\",\n /** Exponential delay increase (initialDelay * 2^attempt) */\n Exponential: \"exponential\",\n} as const;\n\n// ============================================================================\n// Requirement Status Utilities\n// ============================================================================\n\nexport {\n createRequirementStatusPlugin,\n createStatusHook,\n type RequirementTypeStatus,\n} from \"./utils/requirement-status.js\";\n\n// ============================================================================\n// Snapshot Utilities\n// ============================================================================\n\nexport {\n shallowEqual,\n isSnapshotExpired,\n validateSnapshot,\n diffSnapshots,\n signSnapshot,\n verifySnapshotSignature,\n isSignedSnapshot,\n type DistributableSnapshotLike,\n type SnapshotDiff,\n type SnapshotDiffEntry,\n type SignedSnapshot,\n} from \"./utils/utils.js\";\n\n// ============================================================================\n// Clock + Timer (RFC 0001 v0.1)\n// ============================================================================\n\nexport {\n type SignalClock,\n realClock,\n virtualClock,\n defaultClock,\n} from \"./core/clock.js\";\n\nexport {\n type TimerFactState,\n type TimerFactOpts,\n initialTimerState,\n elapsedMs,\n remainingMs,\n startTimer,\n pauseTimer,\n resumeTimer,\n resetTimer,\n completeTimer,\n registerRepeat,\n tickTimer,\n timerOps,\n} from \"./core/timer.js\";\n\n// ============================================================================\n// Lower-level APIs — use \"@directive-run/core/internals\" for these\n// ============================================================================\n// Manager factories, engine, tracking, and internal types are available at:\n// import { createEngine, createFacts, withTracking } from \"@directive-run/core/internals\"\n//\n// Internal types (FactsStore, FactChange, DerivationState, ConstraintState,\n// DerivationsDef, ConstraintsDef, ResolversDef, EventsDef, ReconcileResult,\n// RecoveryStrategy, ErrorSource, etc.) are also in internals.\n\n// Migration utilities available via \"@directive-run/core/migration\" subpath export.\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkTUS5WDVE_cjs=require('./chunk-TUS5WDVE.cjs'),chunkDDUARSUH_cjs=require('./chunk-DDUARSUH.cjs'),chunkBEJ6ICA7_cjs=require('./chunk-BEJ6ICA7.cjs');Object.defineProperty(exports,"createConstraintFactory",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.c}});Object.defineProperty(exports,"createConstraintsManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.p}});Object.defineProperty(exports,"createDerivationsManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.q}});Object.defineProperty(exports,"createDisabledHistory",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.j}});Object.defineProperty(exports,"createEffectsManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.r}});Object.defineProperty(exports,"createEngine",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.z}});Object.defineProperty(exports,"createErrorBoundaryManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.t}});Object.defineProperty(exports,"createFacts",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.w}});Object.defineProperty(exports,"createFactsProxy",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.v}});Object.defineProperty(exports,"createFactsStore",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.u}});Object.defineProperty(exports,"createHistoryManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.i}});Object.defineProperty(exports,"createPluginManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.x}});Object.defineProperty(exports,"createResolverFactory",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.d}});Object.defineProperty(exports,"createResolversManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.y}});Object.defineProperty(exports,"createRetryLaterManager",{enumerable:true,get:function(){return chunkTUS5WDVE_cjs.s}});Object.defineProperty(exports,"getCurrentDeps",{enumerable:true,get:function(){return chunkDDUARSUH_cjs.g}});Object.defineProperty(exports,"isTracking",{enumerable:true,get:function(){return chunkDDUARSUH_cjs.h}});Object.defineProperty(exports,"trackAccess",{enumerable:true,get:function(){return chunkDDUARSUH_cjs.k}});Object.defineProperty(exports,"withTracking",{enumerable:true,get:function(){return chunkDDUARSUH_cjs.i}});Object.defineProperty(exports,"withoutTracking",{enumerable:true,get:function(){return chunkDDUARSUH_cjs.j}});Object.defineProperty(exports,"safeStringify",{enumerable:true,get:function(){return chunkBEJ6ICA7_cjs.l}});//# sourceMappingURL=internals.cjs.map
1
+ 'use strict';var chunkPGUTGWUI_cjs=require('./chunk-PGUTGWUI.cjs'),chunkS3CFYDIB_cjs=require('./chunk-S3CFYDIB.cjs'),chunkZHS3EW2Z_cjs=require('./chunk-ZHS3EW2Z.cjs');Object.defineProperty(exports,"createConstraintFactory",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.m}});Object.defineProperty(exports,"createConstraintsManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.z}});Object.defineProperty(exports,"createDerivationsManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.A}});Object.defineProperty(exports,"createDisabledHistory",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.t}});Object.defineProperty(exports,"createEffectsManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.B}});Object.defineProperty(exports,"createEngine",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.J}});Object.defineProperty(exports,"createErrorBoundaryManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.D}});Object.defineProperty(exports,"createFacts",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.G}});Object.defineProperty(exports,"createFactsProxy",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.F}});Object.defineProperty(exports,"createFactsStore",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.E}});Object.defineProperty(exports,"createHistoryManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.s}});Object.defineProperty(exports,"createPluginManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.H}});Object.defineProperty(exports,"createResolverFactory",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.n}});Object.defineProperty(exports,"createResolversManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.I}});Object.defineProperty(exports,"createRetryLaterManager",{enumerable:true,get:function(){return chunkPGUTGWUI_cjs.C}});Object.defineProperty(exports,"getCurrentDeps",{enumerable:true,get:function(){return chunkS3CFYDIB_cjs.g}});Object.defineProperty(exports,"isTracking",{enumerable:true,get:function(){return chunkS3CFYDIB_cjs.h}});Object.defineProperty(exports,"trackAccess",{enumerable:true,get:function(){return chunkS3CFYDIB_cjs.k}});Object.defineProperty(exports,"withTracking",{enumerable:true,get:function(){return chunkS3CFYDIB_cjs.i}});Object.defineProperty(exports,"withoutTracking",{enumerable:true,get:function(){return chunkS3CFYDIB_cjs.j}});Object.defineProperty(exports,"safeStringify",{enumerable:true,get:function(){return chunkZHS3EW2Z_cjs.l}});//# sourceMappingURL=internals.cjs.map
2
2
  //# sourceMappingURL=internals.cjs.map