@directive-run/core 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-utils.cjs +1 -1
- package/dist/adapter-utils.cjs.map +1 -1
- package/dist/adapter-utils.js +1 -1
- package/dist/adapter-utils.js.map +1 -1
- package/dist/chunk-2HKKISIL.js +3 -0
- package/dist/chunk-2HKKISIL.js.map +1 -0
- package/dist/chunk-4KFEHIIX.cjs +3 -0
- package/dist/chunk-4KFEHIIX.cjs.map +1 -0
- package/dist/chunk-KKHSUZA5.cjs +2 -0
- package/dist/chunk-KKHSUZA5.cjs.map +1 -0
- package/dist/chunk-L76IJROE.cjs +16 -0
- package/dist/chunk-L76IJROE.cjs.map +1 -0
- package/dist/chunk-LN4YQDLL.js +2 -0
- package/dist/chunk-LN4YQDLL.js.map +1 -0
- package/dist/chunk-WIMO6TQ3.js +16 -0
- package/dist/chunk-WIMO6TQ3.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.d.cts +1 -1
- package/dist/internals.d.ts +1 -1
- package/dist/internals.js +1 -1
- package/dist/system-4J3B25OD.cjs +2 -0
- package/dist/{system-6JXMY66X.cjs.map → system-4J3B25OD.cjs.map} +1 -1
- package/dist/system-5OAYXJIG.js +2 -0
- package/dist/{system-I534ZO6E.js.map → system-5OAYXJIG.js.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +4 -0
- package/dist/testing.d.ts +4 -0
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.js +1 -1
- package/package.json +7 -1
- package/dist/chunk-B2LVGKNZ.js +0 -3
- package/dist/chunk-B2LVGKNZ.js.map +0 -1
- package/dist/chunk-DB5Z7EOG.js +0 -16
- package/dist/chunk-DB5Z7EOG.js.map +0 -1
- package/dist/chunk-GSXCAMNZ.js +0 -2
- package/dist/chunk-GSXCAMNZ.js.map +0 -1
- package/dist/chunk-NZ6EK6W5.cjs +0 -3
- package/dist/chunk-NZ6EK6W5.cjs.map +0 -1
- package/dist/chunk-UBI6S2N3.cjs +0 -16
- package/dist/chunk-UBI6S2N3.cjs.map +0 -1
- package/dist/chunk-WFIJ6OST.cjs +0 -2
- package/dist/chunk-WFIJ6OST.cjs.map +0 -1
- package/dist/system-6JXMY66X.cjs +0 -2
- package/dist/system-I534ZO6E.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/index.ts"],"names":["createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","value","v","intermediate","desc","predicate","message","newRefinements","m","t","createChainableString","fm","n","regex","createChainableNumber","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","i","validator","createChainableObject","shapeSchema","key","schemaType","schemaT","keys","k","values","valueSet","innerType","innerTypeName","types","typeNames","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","Backoff"],"mappings":"shBAsCA,SAASA,CAAAA,CACPC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CACAC,CAAAA,CACAC,CAA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AAa,CAAC,GALID,CAAAA,CAAQ,OAAA,EAAW,EAAC,CAKJF,CAAAA,CAAa,MAAM,CAAA,CAa3D,OAAO,CAEL,MAAA,CAbaI,CAAAA,CAAa,CAC1B,MAAA,CAAQF,CAAAA,CAAQ,MAAA,CAChB,OAAA,CAASC,CAAAA,CACT,KAAA,CAAOD,CAAAA,CAAQ,KAAA,CACf,aAAA,CAAeA,CAAAA,CAAQ,aAAA,CACvB,MAAA,CAAQA,CAAAA,CAAQ,MAAA,CAChB,UAAA,CAAYA,CAAAA,CAAQ,WACpB,YAAA,CAAcA,CAAAA,CAAQ,YAExB,CAAQ,CAAA,CAKN,YAAA,CAAAF,CACF,CACF,CCoEO,IAAMK,CAAAA,CAAU,CAErB,IAAA,CAAM,MAAA,CAEN,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 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 * 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 (process.env.NODE_ENV !== \"production\" && 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 * @example\n * ```typescript\n * // String or number\n * schema: { value: t.union(t.string(), t.number()) }\n *\n * // Multiple types\n * schema: { data: t.union(t.string(), t.number(), t.boolean()) }\n * ```\n */\n union<T extends SchemaType<unknown>[]>(...types: T) {\n if (process.env.NODE_ENV !== \"production\" && types.length === 0) {\n console.warn(\n \"[Directive] t.union() called with no types - this will reject all values\",\n );\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 },\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 (process.env.NODE_ENV !== \"production\" && 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 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 * });\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 (process.env.NODE_ENV !== \"production\") {\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 * @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// 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/index.ts"],"names":["createSchemaType","validators","typeName","defaultValue","transform","description","refinements","meta","fn","createChainableType","fieldMeta","value","v","intermediate","desc","predicate","message","newRefinements","m","t","createChainableString","fm","n","regex","createChainableNumber","createChainableArray","elementType","indexRef","chainable","ref","et","newRef","i","validator","createChainableObject","shapeSchema","key","schemaType","schemaT","keys","k","values","dev_true_default","valueSet","innerType","innerTypeName","types","typeNames","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","Backoff"],"mappings":"8hBAuCA,SAASA,CAAAA,CACPC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACuB,CACvB,OAAO,CACL,KAAA,CAAO,MAAA,CACP,WAAA,CAAaN,CAAAA,CACb,SAAA,CAAWC,CAAAA,CACX,QAAA,CAAUC,CAAAA,CACV,UAAA,CAAYC,CAAAA,CACZ,YAAA,CAAcC,CAAAA,CACd,YAAA,CAAcC,CAAAA,CACd,KAAA,CAAOC,EACP,QAAA,CAASC,CAAAA,CAA2B,CAClC,OAAOR,CAAAA,CACL,CAAC,GAAGC,CAAAA,CAAYO,CAAE,CAAA,CAClBN,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CACF,CACF,CACF,CACF,CAqBA,SAASE,CAAAA,CACPR,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAI,CAAAA,CACwB,CAUxB,OAAO,CACL,GAVWV,CAAAA,CACXC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAI,CACF,CAAA,CAGE,OAAA,CAAQC,CAAAA,CAAsB,CAC5B,OAAOF,CAAAA,CACLR,CAAAA,CACAC,CAAAA,CACAS,CA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I,CAAA,EAAG,MAAA,CAAOY,EAAI,EAAE,CAAA,CACvChB,CAAAA,GACF,CACF,CAAA,CAIE,SAAA,CAAAM,CAAAA,CACA,YAAA,CAAAK,CAAAA,CACA,SAAA,CAAAG,CAAAA,CACA,KAAA,CAAAC,CACF,CACF,CA0BO,SAASI,CAAAA,CACdC,CAAAA,CACyC,CAGzC,OAAQhB,CAAAA,EAAiBgB,CAAAA,CAAa,SAAA,CAAUhB,CAAI,CACtD,CChKO,SAASiB,CAAAA,CACdC,CAAAA,CACqB,CAErB,IAAMF,CAAAA,CAAetB,CAAAA,EAA8B,CAQ7CyB,CAAAA,CAAa,CAAC,GALID,CAAAA,CAAQ,OAAA,EAAW,EAAC,CAKJF,CAAAA,CAAa,MAAM,CAAA,CAa3D,OAAO,CAEL,MAAA,CAbaI,CAAAA,CAAa,CAC1B,MAAA,CAAQF,CAAAA,CAAQ,MAAA,CAChB,OAAA,CAASC,CAAAA,CACT,KAAA,CAAOD,CAAAA,CAAQ,KAAA,CACf,aAAA,CAAeA,CAAAA,CAAQ,aAAA,CACvB,MAAA,CAAQA,CAAAA,CAAQ,MAAA,CAChB,UAAA,CAAYA,CAAAA,CAAQ,WACpB,YAAA,CAAcA,CAAAA,CAAQ,YAExB,CAAQ,CAAA,CAKN,YAAA,CAAAF,CACF,CACF,CCoEO,IAAMK,EAAAA,CAAU,CAErB,IAAA,CAAM,MAAA,CAEN,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 * 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 * @example\n * ```typescript\n * // String or number\n * schema: { value: t.union(t.string(), t.number()) }\n *\n * // Multiple types\n * schema: { data: t.union(t.string(), t.number(), t.boolean()) }\n * ```\n */\n union<T extends SchemaType<unknown>[]>(...types: T) {\n if (isDevelopment && types.length === 0) {\n console.warn(\n \"[Directive] t.union() called with no types - this will reject all values\",\n );\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 },\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 * });\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 * @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// 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"]}
|
package/dist/internals.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk4KFEHIIX_cjs=require('./chunk-4KFEHIIX.cjs'),chunkKKHSUZA5_cjs=require('./chunk-KKHSUZA5.cjs'),chunkBEJ6ICA7_cjs=require('./chunk-BEJ6ICA7.cjs');Object.defineProperty(exports,"createConstraintFactory",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.c}});Object.defineProperty(exports,"createConstraintsManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.p}});Object.defineProperty(exports,"createDerivationsManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.q}});Object.defineProperty(exports,"createDisabledHistory",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.j}});Object.defineProperty(exports,"createEffectsManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.r}});Object.defineProperty(exports,"createEngine",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.z}});Object.defineProperty(exports,"createErrorBoundaryManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.t}});Object.defineProperty(exports,"createFacts",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.w}});Object.defineProperty(exports,"createFactsProxy",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.v}});Object.defineProperty(exports,"createFactsStore",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.u}});Object.defineProperty(exports,"createHistoryManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.i}});Object.defineProperty(exports,"createPluginManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.x}});Object.defineProperty(exports,"createResolverFactory",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.d}});Object.defineProperty(exports,"createResolversManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.y}});Object.defineProperty(exports,"createRetryLaterManager",{enumerable:true,get:function(){return chunk4KFEHIIX_cjs.s}});Object.defineProperty(exports,"getCurrentDeps",{enumerable:true,get:function(){return chunkKKHSUZA5_cjs.g}});Object.defineProperty(exports,"isTracking",{enumerable:true,get:function(){return chunkKKHSUZA5_cjs.h}});Object.defineProperty(exports,"trackAccess",{enumerable:true,get:function(){return chunkKKHSUZA5_cjs.k}});Object.defineProperty(exports,"withTracking",{enumerable:true,get:function(){return chunkKKHSUZA5_cjs.i}});Object.defineProperty(exports,"withoutTracking",{enumerable:true,get:function(){return chunkKKHSUZA5_cjs.j}});Object.defineProperty(exports,"safeStringify",{enumerable:true,get:function(){return chunkBEJ6ICA7_cjs.l}});//# sourceMappingURL=internals.cjs.map
|
|
2
2
|
//# sourceMappingURL=internals.cjs.map
|
package/dist/internals.d.cts
CHANGED
|
@@ -18,7 +18,7 @@ export { g as safeStringify } from './utils-BnQajqPu.cjs';
|
|
|
18
18
|
/** Options for creating a facts store */
|
|
19
19
|
interface CreateFactsStoreOptions<S extends Schema> {
|
|
20
20
|
schema: S;
|
|
21
|
-
/** Validate values against schema (default:
|
|
21
|
+
/** Validate values against schema (default: true in development, false in production) */
|
|
22
22
|
validate?: boolean;
|
|
23
23
|
/** Throw on unknown schema keys (default: true in dev mode) */
|
|
24
24
|
strictKeys?: boolean;
|
package/dist/internals.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export { g as safeStringify } from './utils-BnQajqPu.js';
|
|
|
18
18
|
/** Options for creating a facts store */
|
|
19
19
|
interface CreateFactsStoreOptions<S extends Schema> {
|
|
20
20
|
schema: S;
|
|
21
|
-
/** Validate values against schema (default:
|
|
21
|
+
/** Validate values against schema (default: true in development, false in production) */
|
|
22
22
|
validate?: boolean;
|
|
23
23
|
/** Throw on unknown schema keys (default: true in dev mode) */
|
|
24
24
|
strictKeys?: boolean;
|
package/dist/internals.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{c as createConstraintFactory,p as createConstraintsManager,q as createDerivationsManager,j as createDisabledHistory,r as createEffectsManager,z as createEngine,t as createErrorBoundaryManager,w as createFacts,v as createFactsProxy,u as createFactsStore,i as createHistoryManager,x as createPluginManager,d as createResolverFactory,y as createResolversManager,s as createRetryLaterManager}from'./chunk-
|
|
1
|
+
export{c as createConstraintFactory,p as createConstraintsManager,q as createDerivationsManager,j as createDisabledHistory,r as createEffectsManager,z as createEngine,t as createErrorBoundaryManager,w as createFacts,v as createFactsProxy,u as createFactsStore,i as createHistoryManager,x as createPluginManager,d as createResolverFactory,y as createResolversManager,s as createRetryLaterManager}from'./chunk-2HKKISIL.js';export{g as getCurrentDeps,h as isTracking,k as trackAccess,i as withTracking,j as withoutTracking}from'./chunk-LN4YQDLL.js';export{l as safeStringify}from'./chunk-4CMO5OVZ.js';//# sourceMappingURL=internals.js.map
|
|
2
2
|
//# sourceMappingURL=internals.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkL76IJROE_cjs=require('./chunk-L76IJROE.cjs');require('./chunk-4KFEHIIX.cjs'),require('./chunk-KKHSUZA5.cjs'),require('./chunk-BEJ6ICA7.cjs');Object.defineProperty(exports,"createSystem",{enumerable:true,get:function(){return chunkL76IJROE_cjs.a}});//# sourceMappingURL=system-4J3B25OD.cjs.map
|
|
2
|
+
//# sourceMappingURL=system-4J3B25OD.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"system-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"system-4J3B25OD.cjs"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"system-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"system-5OAYXJIG.js"}
|
package/dist/testing.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkL76IJROE_cjs=require('./chunk-L76IJROE.cjs');require('./chunk-4KFEHIIX.cjs'),require('./chunk-KKHSUZA5.cjs'),require('./chunk-BEJ6ICA7.cjs');async function R(){for(let t=0;t<10;t++)await Promise.resolve();}async function T(t,s,r={}){let{totalTime:o=5e3,stepSize:c=10,maxIterations:l=1e3}=r,m=0,u=0;for(;m<o&&u<l;){if(await R(),t.inspect().inflight.length===0){await R();return}s(c),m+=c,u++;}let v=t.inspect();if(v.inflight.length>0){let f=v.inflight.map(p=>p.resolverId).join(", ");throw new Error(`[Directive] settleWithFakeTimers did not settle after ${o}ms. ${v.inflight.length} resolvers still inflight: ${f}`)}}function D(){let t=0,s=[];return {async advance(r){let o=t+r;for(;s.length>0&&s[0].time<=o;){let c=s.shift();t=c.time,c.callback(),await Promise.resolve();}t=o;},async next(){if(s.length===0)return;let r=s.shift();t=r.time,r.callback(),await Promise.resolve();},async runAll(){for(;s.length>0;)await this.next();},now(){return t},reset(){t=0,s.length=0;}}}function b(t){let s=typeof t=="string"?{requirement:(o=>o.type===t)}:t,r=s.calls??[];return {requirement:s.requirement??(o=>true),async resolve(o,c){if(r.push(o),s.delay&&await new Promise(l=>setTimeout(l,s.delay)),s.error)throw typeof s.error=="string"?new Error(s.error):s.error;s.resolve&&await s.resolve(o,c);}}}function C(t){let s=[],r=[];return {...{get calls(){return s},get pending(){return r},resolve(l){let m=r.shift();m&&m.resolve(l);},reject(l){let m=r.shift();m&&m.reject(l);},resolveAll(l){for(;r.length>0;)this.resolve(l);},rejectAll(l){for(;r.length>0;)this.reject(l);},reset(){s.length=0,r.length=0;}},handler:(l,m)=>(s.push(l),new Promise((u,v)=>{r.push({requirement:l,resolve:f=>u(f),reject:v});}))}}function E(t){return "module"in t?x(t):M(t)}function x(t){let s=[],r=new Map,o=[],c=[],l={};if(t.mocks?.resolvers)for(let[i,e]of Object.entries(t.mocks.resolvers)){let n=[];r.set(i,n),l[i]=b({...e,calls:n});}let m={...t.module,resolvers:{...t.module.resolvers,...l}},v=chunkL76IJROE_cjs.a({...t,module:m,plugins:[{name:"__test-tracking__",onFactSet:(i,e,n)=>{c.push({key:i,fullKey:i,namespace:void 0,previousValue:n,newValue:e,timestamp:Date.now()});},onRequirementCreated:i=>{o.push(i);}},...t.plugins??[]]}),f=v.dispatch.bind(v);return v.dispatch=i=>{s.push(i),f(i);},{...v,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(i=5e3){let e=Date.now(),n=async()=>{await new Promise(d=>setTimeout(d,0));let a=v.inspect();if(a.inflight.length>0){if(Date.now()-e>i){let d=a.inflight.map(g=>g.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${i}ms. ${a.inflight.length} resolvers still inflight: ${d}`)}return await new Promise(d=>setTimeout(d,10)),n()}};return n()},assertRequirement(i){if(!o.some(n=>n.requirement.type===i))throw new Error(`[Directive] Expected requirement of type "${i}" but none found`)},assertResolverCalled(i,e){let n=r.get(i)??[];if(e!==void 0){if(n.length!==e)throw new Error(`[Directive] Expected resolver "${i}" to be called ${e} times but was called ${n.length} times`)}else if(n.length===0)throw new Error(`[Directive] Expected resolver "${i}" to be called but it was not`)},assertFactSet(i,e){let n=c.filter(a=>a.key===i);if(n.length===0)throw new Error(`[Directive] Expected fact "${i}" to be set but it was not`);if(e!==void 0&&!n.some(d=>d.newValue===e)){let d=n.map(g=>JSON.stringify(g.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${i}" to be set to ${JSON.stringify(e)} but got: ${d}`)}},assertFactChanges(i,e){let n=c.filter(a=>a.key===i);if(n.length!==e)throw new Error(`[Directive] Expected fact "${i}" to change ${e} times but it changed ${n.length} times`)}}}function M(t){let s=[],r=new Map,o=[],c=[],l={};if(t.mocks?.resolvers)for(let[e,n]of Object.entries(t.mocks.resolvers)){let a=[];r.set(e,a),l[e]=b({...n,calls:a});}let m={};for(let[e,n]of Object.entries(t.modules))m[e]={...n,resolvers:{...n.resolvers,...l}};let u=new Set(Object.keys(t.modules)),f=chunkL76IJROE_cjs.a({...t,modules:m,plugins:[{name:"__test-tracking__",onFactSet:(e,n,a)=>{let g=e.indexOf("::"),y,h;if(g>0){let w=e.substring(0,g);u.has(w)?(y=w,h=e.substring(g+2)):h=e;}else h=e;c.push({key:h,fullKey:e,namespace:y,previousValue:a,newValue:n,timestamp:Date.now()});},onRequirementCreated:e=>{o.push(e);}},...t.plugins??[]]}),p=f.dispatch.bind(f);return f.dispatch=e=>{s.push(e),p(e);},{...f,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(e=5e3){let n=Date.now(),a=async()=>{await new Promise(g=>setTimeout(g,0));let d=f.inspect();if(d.inflight.length>0){if(Date.now()-n>e){let g=d.inflight.map(y=>y.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${e}ms. ${d.inflight.length} resolvers still inflight: ${g}`)}return await new Promise(g=>setTimeout(g,10)),a()}};return a()},assertRequirement(e){if(!o.some(a=>a.requirement.type===e))throw new Error(`[Directive] Expected requirement of type "${e}" but none found`)},assertResolverCalled(e,n){let a=r.get(e)??[];if(n!==void 0){if(a.length!==n)throw new Error(`[Directive] Expected resolver "${e}" to be called ${n} times but was called ${a.length} times`)}else if(a.length===0)throw new Error(`[Directive] Expected resolver "${e}" to be called but it was not`)},assertFactSet(e,n){let a=c.filter(d=>d.key===e);if(a.length===0)throw new Error(`[Directive] Expected fact "${e}" to be set but it was not`);if(n!==void 0&&!a.some(g=>g.newValue===n)){let g=a.map(y=>JSON.stringify(y.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${e}" to be set to ${JSON.stringify(n)} but got: ${g}`)}},assertFactChanges(e,n){let a=c.filter(d=>d.key===e);if(a.length!==n)throw new Error(`[Directive] Expected fact "${e}" to change ${n} times but it changed ${a.length} times`)}}}function O(t,s,r){if(!k(t,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to be dynamic, but it is not.`)}function $(t,s,r){if(k(t,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to NOT be dynamic, but it is.`)}function k(t,s,r){switch(s){case "constraint":return t.constraints.isDynamic(r);case "resolver":return t.resolvers.isDynamic(r);case "derivation":return t.derive.isDynamic(r);case "effect":return t.effects.isDynamic(r)}}function P(t){let s=new Set,r=new Set,o=new Set,c=new Set,l=null;return {async run(m){l=t.observe(u=>{switch(u.type){case "constraint.evaluate":u.active&&s.add(u.id);break;case "resolver.start":r.add(u.resolver);break;case "effect.run":o.add(u.id);break;case "derivation.compute":c.add(u.id);break}});try{await m();}finally{l?.(),l=null;}},report(){let m=t.inspect(),u=new Set(m.constraints.map(i=>i.id)),v=new Set(m.resolverDefs.map(i=>i.id)),f=new Set;for(let i of u)s.has(i)||f.add(i);let p=new Set;for(let i of v)r.has(i)||p.add(i);return {constraintsHit:s,constraintsMissed:f,resolversRun:r,resolversMissed:p,effectsRun:o,derivationsComputed:c,constraintCoverage:u.size===0?1:s.size/u.size,resolverCoverage:v.size===0?1:r.size/v.size,effectCoverage:m.effects.length===0?1:o.size/m.effects.length,derivationCoverage:m.derivations.length===0?1:c.size/m.derivations.length}}}}function F(t){let s=[],r=t.observe(o=>s.push(o));return {events:s,ofType(o){return s.filter(c=>c.type===o)},clear(){s.length=0;},dispose(){r();}}}exports.assertDynamic=O;exports.assertNotDynamic=$;exports.createCoverageTracker=P;exports.createFakeTimers=D;exports.createMockResolver=b;exports.createTestObserver=F;exports.createTestSystem=E;exports.flushMicrotasks=R;exports.mockResolver=C;exports.settleWithFakeTimers=T;//# sourceMappingURL=testing.cjs.map
|
|
2
2
|
//# sourceMappingURL=testing.cjs.map
|