@directive-run/core 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +153 -9
- package/dist/adapter-utils.d.cts +1 -1
- package/dist/adapter-utils.d.ts +1 -1
- package/dist/index.cjs +16 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -39
- package/dist/index.d.ts +18 -39
- package/dist/index.js +16 -16
- package/dist/index.js.map +1 -1
- package/dist/migration.cjs +12 -12
- package/dist/migration.cjs.map +1 -1
- package/dist/migration.js +12 -12
- package/dist/migration.js.map +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.d.cts +103 -23
- package/dist/plugins/index.d.ts +103 -23
- package/dist/plugins/index.js +2 -2
- package/dist/plugins/index.js.map +1 -1
- package/dist/{plugins-CcwEXXMS.d.cts → plugins-DZljh9NJ.d.cts} +135 -3
- package/dist/{plugins-CcwEXXMS.d.ts → plugins-DZljh9NJ.d.ts} +135 -3
- package/dist/testing.cjs +3 -3
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +3 -3
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +1 -1
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +3 -3
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/migration.cjs
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
'use strict';function m(e){let t={},s={},i={};for(let[n,
|
|
1
|
+
'use strict';function m(e){let t={},s={},i={};for(let[n,c]of Object.entries(e.initialState))t[n]=p(c);for(let n of Object.keys(e.reducers))n.includes("By")||n.includes("Set")||n.includes("With")?(s[n]={payload:"t.object()"},i[n]=`(facts, { payload }) => {
|
|
2
2
|
// TODO: Implement ${n}
|
|
3
3
|
}`):(s[n]={},i[n]=`(facts) => {
|
|
4
4
|
// TODO: Implement ${n}
|
|
5
|
-
}`);let
|
|
6
|
-
${Object.entries(e.initialState).map(([n,
|
|
5
|
+
}`);let a=`(facts) => {
|
|
6
|
+
${Object.entries(e.initialState).map(([n,c])=>` facts.${n} = ${JSON.stringify(c)};`).join(`
|
|
7
7
|
`)}
|
|
8
|
-
}`;return {name:e.name,facts:t,derivations:{},events:s,requirements:{},initCode:
|
|
8
|
+
}`;return {name:e.name,facts:t,derivations:{},events:s,requirements:{},initCode:a,deriveCode:{},eventsCode:i}}function h(e){let t={},s={},i={};for(let[n,c]of Object.entries(e.state))t[n]=p(c);for(let n of Object.keys(e.actions))s[n]={},i[n]=`(facts) => {
|
|
9
9
|
// TODO: Implement ${n}
|
|
10
|
-
}`;let
|
|
11
|
-
${Object.entries(e.state).map(([n,
|
|
10
|
+
}`;let a=`(facts) => {
|
|
11
|
+
${Object.entries(e.state).map(([n,c])=>` facts.${n} = ${JSON.stringify(c)};`).join(`
|
|
12
12
|
`)}
|
|
13
|
-
}`;return {name:"store",facts:t,derivations:{},events:s,requirements:{},initCode:
|
|
13
|
+
}`;return {name:"store",facts:t,derivations:{},events:s,requirements:{},initCode:a,deriveCode:{},eventsCode:i}}function C(e){let t={state:`t.string<${Object.keys(e.states).map(r=>`'${r}'`).join(" | ")}>()`},s={},i={},f={},a={};if(e.context)for(let[r,o]of Object.entries(e.context))t[r]=p(o);for(let r of Object.keys(e.states)){let o=`is${l(r)}`;s[o]="t.boolean()",i[o]=`(facts) => facts.state === '${r}'`;}let n=new Map;for(let[r,o]of Object.entries(e.states))if(o.on)for(let[d,u]of Object.entries(o.on)){n.has(d)||n.set(d,new Map);let g=typeof u=="string"?u:u.target;n.get(d).set(r,g);}for(let[r,o]of n)if(f[r]={},o.size===1){let d=[...o.entries()][0],u=d?d[1]:"unknown";a[r]=`(facts) => {
|
|
14
14
|
facts.state = '${u}';
|
|
15
15
|
}`;}else {let d=[...o.entries()].map(([u,g])=>` case '${u}': facts.state = '${g}'; break;`).join(`
|
|
16
|
-
`);
|
|
16
|
+
`);a[r]=`(facts) => {
|
|
17
17
|
switch (facts.state) {
|
|
18
18
|
${d}
|
|
19
19
|
}
|
|
20
|
-
}`;}let
|
|
21
|
-
${
|
|
20
|
+
}`;}let c=[` facts.state = '${e.initial}';`];if(e.context)for(let[r,o]of Object.entries(e.context))c.push(` facts.${r} = ${JSON.stringify(o)};`);let v=`(facts) => {
|
|
21
|
+
${c.join(`
|
|
22
22
|
`)}
|
|
23
|
-
}`;return {name:e.id,facts:t,derivations:s,events:f,requirements:{},initCode:v,deriveCode:i,eventsCode:
|
|
24
|
-
`)}function p(e){if(e===null)return "t.
|
|
23
|
+
}`;return {name:e.id,facts:t,derivations:s,events:f,requirements:{},initCode:v,deriveCode:i,eventsCode:a}}function y(e){let t=["import { createModule, t } from '@directive-run/core';","",`const ${e.name}Module = createModule('${e.name}', {`," schema: {"," facts: {"];for(let[s,i]of Object.entries(e.facts))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" derivations: {");for(let[s,i]of Object.entries(e.derivations))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" events: {");for(let[s,i]of Object.entries(e.events)){let f=Object.entries(i).map(([a,n])=>`${a}: ${n}`).join(", ");t.push(` ${s}: { ${f} },`);}if(t.push(" },"),t.push(" requirements: {},"),t.push(" },"),t.push(` init: ${e.initCode},`),Object.keys(e.deriveCode).length>0){t.push(" derive: {");for(let[s,i]of Object.entries(e.deriveCode))t.push(` ${s}: ${i},`);t.push(" },");}t.push(" events: {");for(let[s,i]of Object.entries(e.eventsCode))t.push(` ${s}: ${i},`);return t.push(" },"),t.push("});"),t.push(""),t.push(`export { ${e.name}Module };`),t.join(`
|
|
24
|
+
`)}function p(e){if(e===null)return "t.object().nullable()";if(e===void 0)return "t.object().optional()";switch(typeof e){case "number":return "t.number()";case "string":return "t.string()";case "boolean":return "t.boolean()";case "object":return Array.isArray(e)?"t.array(t.object())":"t.object()";default:return "t.object()"}}function l(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $(e){let t=["[ ] Install directive: pnpm add directive","[ ] Create module file(s) for your state","[ ] Define schema with facts, derivations, events","[ ] Implement init function for initial state","[ ] Implement event handlers","[ ] Update imports in consuming code","[ ] Test the new implementation","[ ] Remove old state management code"];return [...{redux:["[ ] Convert reducers to event handlers","[ ] Convert selectors to derivations","[ ] Convert thunks to constraints + resolvers","[ ] Update useSelector to useDerived","[ ] Update useDispatch to system.dispatch"],zustand:["[ ] Convert store state to facts","[ ] Convert store actions to events","[ ] Convert computed getters to derivations","[ ] Update useStore hooks to useDirective hooks"],xstate:["[ ] Convert machine states to a 'state' fact","[ ] Convert state checks to derivations (isActive, etc.)","[ ] Convert events to Directive events","[ ] Convert guards to constraint 'when' conditions","[ ] Convert services/actors to constraints + resolvers","[ ] Update useMachine to useDirective hooks"]}[e]??[],...t]}exports.analyzeReduxSlice=m;exports.analyzeXStateMachine=C;exports.analyzeZustandStore=h;exports.generateMigrationChecklist=$;exports.generateModuleCode=y;//# sourceMappingURL=migration.cjs.map
|
|
25
25
|
//# sourceMappingURL=migration.cjs.map
|
package/dist/migration.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/migration.ts"],"names":["analyzeReduxSlice","config","facts","events","eventsCode","key","value","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","s","derivations","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","eventName","target","targetState","transitions","firstEntry","toState","cases","from","to","initLines","generateModuleCode","structure","lines","type","schema","schemaStr","k","v","code","str","generateMigrationChecklist","source","common"],"mappings":"aAmEO,SAASA,CAAAA,CAAkBC,CAAAA,CAAoD,CACrF,IAAMC,CAAAA,CAAgC,EAAC,CACjCC,CAAAA,CAAiD,EAAC,CAClDC,CAAAA,CAAqC,EAAC,CAG5C,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,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K,QAAA,CACJ,OAAO,YAAA,CACR,KAAK,QAAA,CACJ,OAAO,aACR,KAAK,SAAA,CACJ,OAAO,aAAA,CACR,KAAK,QAAA,CACJ,OAAI,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,CACf,kBAAA,CAED,YAAA,CACR,QACC,OAAO,SACT,CACD,CAKA,SAASY,CAAAA,CAAWsB,CAAAA,CAAqB,CACxC,OAAOA,CAAAA,CAAI,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,GAAgBA,CAAAA,CAAI,KAAA,CAAM,CAAC,CACjD,CASO,SAASC,EACfC,CAAAA,CACW,CACX,IAAMC,CAAAA,CAAS,CACd,2CAAA,CACA,2CACA,mDAAA,CACA,+CAAA,CACA,8BAAA,CACA,sCAAA,CACA,iCAAA,CACA,sCACD,CAAA,CA2BA,OAAO,CAAC,GAzByC,CAChD,KAAA,CAAO,CACN,wCAAA,CACA,uCACA,+CAAA,CACA,sCAAA,CACA,2CACD,CAAA,CACA,OAAA,CAAS,CACR,kCAAA,CACA,qCAAA,CACA,6CAAA,CACA,iDACD,CAAA,CACA,MAAA,CAAQ,CACP,8CAAA,CACA,2DACA,wCAAA,CACA,oDAAA,CACA,wDAAA,CACA,6CACD,CACD,CAAA,CAEgCD,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGC,CAAM,CAC/B","file":"migration.cjs","sourcesContent":["/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.any()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.any().nullable()\";\n\tif (value === undefined) return \"t.any().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.any())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.any()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/migration.ts"],"names":["analyzeReduxSlice","config","facts","events","eventsCode","key","value","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","s","derivations","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","eventName","target","targetState","transitions","firstEntry","toState","cases","from","to","initLines","generateModuleCode","structure","lines","type","schema","schemaStr","k","v","code","str","generateMigrationChecklist","source","common"],"mappings":"aAmEO,SAASA,CAAAA,CAAkBC,CAAAA,CAAoD,CACrF,IAAMC,CAAAA,CAAgC,EAAC,CACjCC,CAAAA,CAAiD,EAAC,CAClDC,CAAAA,CAAqC,EAAC,CAG5C,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQL,CAAAA,CAAO,YAAY,CAAA,CAC5DC,CAAAA,C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AAK,SAAA,CACJ,OAAO,aAAA,CACR,KAAK,QAAA,CACJ,OAAI,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,CACf,qBAAA,CAED,YAAA,CACR,QACC,OAAO,YACT,CACD,CAKA,SAASY,CAAAA,CAAWsB,CAAAA,CAAqB,CACxC,OAAOA,CAAAA,CAAI,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,GAAgBA,CAAAA,CAAI,KAAA,CAAM,CAAC,CACjD,CASO,SAASC,EACfC,CAAAA,CACW,CACX,IAAMC,CAAAA,CAAS,CACd,2CAAA,CACA,2CACA,mDAAA,CACA,+CAAA,CACA,8BAAA,CACA,sCAAA,CACA,iCAAA,CACA,sCACD,CAAA,CA2BA,OAAO,CAAC,GAzByC,CAChD,KAAA,CAAO,CACN,wCAAA,CACA,uCACA,+CAAA,CACA,sCAAA,CACA,2CACD,CAAA,CACA,OAAA,CAAS,CACR,kCAAA,CACA,qCAAA,CACA,6CAAA,CACA,iDACD,CAAA,CACA,MAAA,CAAQ,CACP,8CAAA,CACA,2DACA,wCAAA,CACA,oDAAA,CACA,wDAAA,CACA,6CACD,CACD,CAAA,CAEgCD,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGC,CAAM,CAC/B","file":"migration.cjs","sourcesContent":["/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.object()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.object().nullable()\";\n\tif (value === undefined) return \"t.object().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.object())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.object()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n"]}
|
package/dist/migration.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
function m(e){let t={},s={},i={};for(let[n,
|
|
1
|
+
function m(e){let t={},s={},i={};for(let[n,c]of Object.entries(e.initialState))t[n]=p(c);for(let n of Object.keys(e.reducers))n.includes("By")||n.includes("Set")||n.includes("With")?(s[n]={payload:"t.object()"},i[n]=`(facts, { payload }) => {
|
|
2
2
|
// TODO: Implement ${n}
|
|
3
3
|
}`):(s[n]={},i[n]=`(facts) => {
|
|
4
4
|
// TODO: Implement ${n}
|
|
5
|
-
}`);let
|
|
6
|
-
${Object.entries(e.initialState).map(([n,
|
|
5
|
+
}`);let a=`(facts) => {
|
|
6
|
+
${Object.entries(e.initialState).map(([n,c])=>` facts.${n} = ${JSON.stringify(c)};`).join(`
|
|
7
7
|
`)}
|
|
8
|
-
}`;return {name:e.name,facts:t,derivations:{},events:s,requirements:{},initCode:
|
|
8
|
+
}`;return {name:e.name,facts:t,derivations:{},events:s,requirements:{},initCode:a,deriveCode:{},eventsCode:i}}function h(e){let t={},s={},i={};for(let[n,c]of Object.entries(e.state))t[n]=p(c);for(let n of Object.keys(e.actions))s[n]={},i[n]=`(facts) => {
|
|
9
9
|
// TODO: Implement ${n}
|
|
10
|
-
}`;let
|
|
11
|
-
${Object.entries(e.state).map(([n,
|
|
10
|
+
}`;let a=`(facts) => {
|
|
11
|
+
${Object.entries(e.state).map(([n,c])=>` facts.${n} = ${JSON.stringify(c)};`).join(`
|
|
12
12
|
`)}
|
|
13
|
-
}`;return {name:"store",facts:t,derivations:{},events:s,requirements:{},initCode:
|
|
13
|
+
}`;return {name:"store",facts:t,derivations:{},events:s,requirements:{},initCode:a,deriveCode:{},eventsCode:i}}function C(e){let t={state:`t.string<${Object.keys(e.states).map(r=>`'${r}'`).join(" | ")}>()`},s={},i={},f={},a={};if(e.context)for(let[r,o]of Object.entries(e.context))t[r]=p(o);for(let r of Object.keys(e.states)){let o=`is${l(r)}`;s[o]="t.boolean()",i[o]=`(facts) => facts.state === '${r}'`;}let n=new Map;for(let[r,o]of Object.entries(e.states))if(o.on)for(let[d,u]of Object.entries(o.on)){n.has(d)||n.set(d,new Map);let g=typeof u=="string"?u:u.target;n.get(d).set(r,g);}for(let[r,o]of n)if(f[r]={},o.size===1){let d=[...o.entries()][0],u=d?d[1]:"unknown";a[r]=`(facts) => {
|
|
14
14
|
facts.state = '${u}';
|
|
15
15
|
}`;}else {let d=[...o.entries()].map(([u,g])=>` case '${u}': facts.state = '${g}'; break;`).join(`
|
|
16
|
-
`);
|
|
16
|
+
`);a[r]=`(facts) => {
|
|
17
17
|
switch (facts.state) {
|
|
18
18
|
${d}
|
|
19
19
|
}
|
|
20
|
-
}`;}let
|
|
21
|
-
${
|
|
20
|
+
}`;}let c=[` facts.state = '${e.initial}';`];if(e.context)for(let[r,o]of Object.entries(e.context))c.push(` facts.${r} = ${JSON.stringify(o)};`);let v=`(facts) => {
|
|
21
|
+
${c.join(`
|
|
22
22
|
`)}
|
|
23
|
-
}`;return {name:e.id,facts:t,derivations:s,events:f,requirements:{},initCode:v,deriveCode:i,eventsCode:
|
|
24
|
-
`)}function p(e){if(e===null)return "t.
|
|
23
|
+
}`;return {name:e.id,facts:t,derivations:s,events:f,requirements:{},initCode:v,deriveCode:i,eventsCode:a}}function y(e){let t=["import { createModule, t } from '@directive-run/core';","",`const ${e.name}Module = createModule('${e.name}', {`," schema: {"," facts: {"];for(let[s,i]of Object.entries(e.facts))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" derivations: {");for(let[s,i]of Object.entries(e.derivations))t.push(` ${s}: ${i},`);t.push(" },"),t.push(" events: {");for(let[s,i]of Object.entries(e.events)){let f=Object.entries(i).map(([a,n])=>`${a}: ${n}`).join(", ");t.push(` ${s}: { ${f} },`);}if(t.push(" },"),t.push(" requirements: {},"),t.push(" },"),t.push(` init: ${e.initCode},`),Object.keys(e.deriveCode).length>0){t.push(" derive: {");for(let[s,i]of Object.entries(e.deriveCode))t.push(` ${s}: ${i},`);t.push(" },");}t.push(" events: {");for(let[s,i]of Object.entries(e.eventsCode))t.push(` ${s}: ${i},`);return t.push(" },"),t.push("});"),t.push(""),t.push(`export { ${e.name}Module };`),t.join(`
|
|
24
|
+
`)}function p(e){if(e===null)return "t.object().nullable()";if(e===void 0)return "t.object().optional()";switch(typeof e){case "number":return "t.number()";case "string":return "t.string()";case "boolean":return "t.boolean()";case "object":return Array.isArray(e)?"t.array(t.object())":"t.object()";default:return "t.object()"}}function l(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $(e){let t=["[ ] Install directive: pnpm add directive","[ ] Create module file(s) for your state","[ ] Define schema with facts, derivations, events","[ ] Implement init function for initial state","[ ] Implement event handlers","[ ] Update imports in consuming code","[ ] Test the new implementation","[ ] Remove old state management code"];return [...{redux:["[ ] Convert reducers to event handlers","[ ] Convert selectors to derivations","[ ] Convert thunks to constraints + resolvers","[ ] Update useSelector to useDerived","[ ] Update useDispatch to system.dispatch"],zustand:["[ ] Convert store state to facts","[ ] Convert store actions to events","[ ] Convert computed getters to derivations","[ ] Update useStore hooks to useDirective hooks"],xstate:["[ ] Convert machine states to a 'state' fact","[ ] Convert state checks to derivations (isActive, etc.)","[ ] Convert events to Directive events","[ ] Convert guards to constraint 'when' conditions","[ ] Convert services/actors to constraints + resolvers","[ ] Update useMachine to useDirective hooks"]}[e]??[],...t]}export{m as analyzeReduxSlice,C as analyzeXStateMachine,h as analyzeZustandStore,$ as generateMigrationChecklist,y as generateModuleCode};//# sourceMappingURL=migration.js.map
|
|
25
25
|
//# sourceMappingURL=migration.js.map
|
package/dist/migration.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/migration.ts"],"names":["analyzeReduxSlice","config","facts","events","eventsCode","key","value","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","s","derivations","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","eventName","target","targetState","transitions","firstEntry","toState","cases","from","to","initLines","generateModuleCode","structure","lines","type","schema","schemaStr","k","v","code","str","generateMigrationChecklist","source","common"],"mappings":"AAmEO,SAASA,CAAAA,CAAkBC,CAAAA,CAAoD,CACrF,IAAMC,CAAAA,CAAgC,EAAC,CACjCC,CAAAA,CAAiD,EAAC,CAClDC,CAAAA,CAAqC,EAAC,CAG5C,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQL,CAAAA,CAAO,YAAY,CAAA,CAC5DC,CAAAA,CAAMG,CAAG,CAAA,CAAIE,CAAAA,CAAgBD,CAAK,EAInC,IAAA,IAAWE,CAAAA,IAAe,MAAA,CAAO,IAAA,CAAKP,CAAAA,CAAO,QAAQ,CAAA,CAEjCO,CAAAA,CAAY,QAAA,CAAS,IAAI,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,KAAK,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,MAAM,CAAA,EAE1GL,CAA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AM,CAAC,CACjD,CASO,SAASC,EACfC,CAAAA,CACW,CACX,IAAMC,CAAAA,CAAS,CACd,2CAAA,CACA,2CACA,mDAAA,CACA,+CAAA,CACA,8BAAA,CACA,sCAAA,CACA,iCAAA,CACA,sCACD,CAAA,CA2BA,OAAO,CAAC,GAzByC,CAChD,KAAA,CAAO,CACN,wCAAA,CACA,uCACA,+CAAA,CACA,sCAAA,CACA,2CACD,CAAA,CACA,OAAA,CAAS,CACR,kCAAA,CACA,qCAAA,CACA,6CAAA,CACA,iDACD,CAAA,CACA,MAAA,CAAQ,CACP,8CAAA,CACA,2DACA,wCAAA,CACA,oDAAA,CACA,wDAAA,CACA,6CACD,CACD,CAAA,CAEgCD,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGC,CAAM,CAC/B","file":"migration.js","sourcesContent":["/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.any()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.any().nullable()\";\n\tif (value === undefined) return \"t.any().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.any())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.any()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/migration.ts"],"names":["analyzeReduxSlice","config","facts","events","eventsCode","key","value","inferTypeString","reducerName","initCode","analyzeZustandStore","actionName","analyzeXStateMachine","s","derivations","deriveCode","stateName","derivationName","capitalize","eventTransitions","stateConfig","eventName","target","targetState","transitions","firstEntry","toState","cases","from","to","initLines","generateModuleCode","structure","lines","type","schema","schemaStr","k","v","code","str","generateMigrationChecklist","source","common"],"mappings":"AAmEO,SAASA,CAAAA,CAAkBC,CAAAA,CAAoD,CACrF,IAAMC,CAAAA,CAAgC,EAAC,CACjCC,CAAAA,CAAiD,EAAC,CAClDC,CAAAA,CAAqC,EAAC,CAG5C,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQL,CAAAA,CAAO,YAAY,CAAA,CAC5DC,CAAAA,CAAMG,CAAG,CAAA,CAAIE,CAAAA,CAAgBD,CAAK,EAInC,IAAA,IAAWE,CAAAA,IAAe,MAAA,CAAO,IAAA,CAAKP,CAAAA,CAAO,QAAQ,CAAA,CAEjCO,CAAAA,CAAY,QAAA,CAAS,IAAI,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,KAAK,CAAA,EAAKA,CAAAA,CAAY,QAAA,CAAS,MAAM,CAAA,EAE1GL,CAAAA,CAAOK,CAAW,CAAA,CAAI,CAAE,OAAA,CAAS,YAAa,CAAA,CAC9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CAAS,CACd,2CAAA,CACA,2CACA,mDAAA,CACA,+CAAA,CACA,8BAAA,CACA,sCAAA,CACA,iCAAA,CACA,sCACD,CAAA,CA2BA,OAAO,CAAC,GAzByC,CAChD,KAAA,CAAO,CACN,wCAAA,CACA,uCACA,+CAAA,CACA,sCAAA,CACA,2CACD,CAAA,CACA,OAAA,CAAS,CACR,kCAAA,CACA,qCAAA,CACA,6CAAA,CACA,iDACD,CAAA,CACA,MAAA,CAAQ,CACP,8CAAA,CACA,2DACA,wCAAA,CACA,oDAAA,CACA,wDAAA,CACA,6CACD,CACD,CAAA,CAEgCD,CAAM,CAAA,EAAK,EAAC,CACvB,GAAGC,CAAM,CAC/B","file":"migration.js","sourcesContent":["/**\n * Migration Utilities for Directive\n *\n * Helpers for migrating from Redux, Zustand, or XState to Directive.\n * These utilities help you understand your existing state management\n * and generate equivalent Directive module structures.\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Redux slice configuration (simplified) */\nexport interface ReduxSliceConfig {\n\tname: string;\n\tinitialState: Record<string, unknown>;\n\treducers: Record<string, (state: unknown, action?: { payload?: unknown }) => void>;\n}\n\n/** Zustand store configuration (simplified) */\nexport interface ZustandStoreConfig {\n\tstate: Record<string, unknown>;\n\tactions: Record<string, (...args: unknown[]) => void>;\n}\n\n/** XState machine configuration (simplified) */\nexport interface XStateMachineConfig {\n\tid: string;\n\tinitial: string;\n\tstates: Record<string, { on?: Record<string, string | { target: string }> }>;\n\tcontext?: Record<string, unknown>;\n}\n\n/** Generated Directive module structure */\nexport interface DirectiveModuleStructure {\n\tname: string;\n\tfacts: Record<string, string>;\n\tderivations: Record<string, string>;\n\tevents: Record<string, Record<string, string>>;\n\trequirements: Record<string, unknown>;\n\tinitCode: string;\n\tderiveCode: Record<string, string>;\n\teventsCode: Record<string, string>;\n}\n\n// ============================================================================\n// Redux Migration\n// ============================================================================\n\n/**\n * Analyze a Redux slice and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const reduxConfig = {\n * name: 'counter',\n * initialState: { value: 0, status: 'idle' },\n * reducers: {\n * increment: (state) => { state.value += 1; },\n * decrement: (state) => { state.value -= 1; },\n * },\n * };\n *\n * const structure = analyzeReduxSlice(reduxConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeReduxSlice(config: ReduxSliceConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze initial state to generate facts\n\tfor (const [key, value] of Object.entries(config.initialState)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze reducers to generate events\n\tfor (const reducerName of Object.keys(config.reducers)) {\n\t\t// Simple heuristic: if reducer name suggests payload, add it\n\t\tconst hasPayload = reducerName.includes(\"By\") || reducerName.includes(\"Set\") || reducerName.includes(\"With\");\n\t\tif (hasPayload) {\n\t\t\tevents[reducerName] = { payload: \"t.object()\" };\n\t\t\teventsCode[reducerName] = `(facts, { payload }) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t} else {\n\t\t\tevents[reducerName] = {};\n\t\t\teventsCode[reducerName] = `(facts) => {\\n // TODO: Implement ${reducerName}\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.initialState)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: config.name,\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Zustand Migration\n// ============================================================================\n\n/**\n * Analyze a Zustand store and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const zustandConfig = {\n * state: { count: 0, loading: false },\n * actions: {\n * increment: () => {},\n * decrement: () => {},\n * setLoading: (loading: boolean) => {},\n * },\n * };\n *\n * const structure = analyzeZustandStore(zustandConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeZustandStore(config: ZustandStoreConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Analyze state\n\tfor (const [key, value] of Object.entries(config.state)) {\n\t\tfacts[key] = inferTypeString(value);\n\t}\n\n\t// Analyze actions\n\tfor (const actionName of Object.keys(config.actions)) {\n\t\tevents[actionName] = {};\n\t\teventsCode[actionName] = `(facts) => {\\n // TODO: Implement ${actionName}\\n }`;\n\t}\n\n\t// Generate init code\n\tconst initLines = Object.entries(config.state)\n\t\t.map(([key, value]) => ` facts.${key} = ${JSON.stringify(value)};`)\n\t\t.join(\"\\n\");\n\tconst initCode = `(facts) => {\\n${initLines}\\n }`;\n\n\treturn {\n\t\tname: \"store\",\n\t\tfacts,\n\t\tderivations: {},\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode: {},\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// XState Migration\n// ============================================================================\n\n/**\n * Analyze an XState machine and generate a Directive module structure.\n *\n * @example\n * ```typescript\n * const xstateConfig = {\n * id: 'toggle',\n * initial: 'inactive',\n * states: {\n * inactive: { on: { TOGGLE: 'active' } },\n * active: { on: { TOGGLE: 'inactive' } },\n * },\n * };\n *\n * const structure = analyzeXStateMachine(xstateConfig);\n * console.log(generateModuleCode(structure));\n * ```\n */\nexport function analyzeXStateMachine(config: XStateMachineConfig): DirectiveModuleStructure {\n\tconst facts: Record<string, string> = {\n\t\tstate: `t.string<${Object.keys(config.states).map(s => `'${s}'`).join(\" | \")}>()`,\n\t};\n\tconst derivations: Record<string, string> = {};\n\tconst deriveCode: Record<string, string> = {};\n\tconst events: Record<string, Record<string, string>> = {};\n\tconst eventsCode: Record<string, string> = {};\n\n\t// Add context to facts\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tfacts[key] = inferTypeString(value);\n\t\t}\n\t}\n\n\t// Generate state derivations (isActive, isInactive, etc.)\n\tfor (const stateName of Object.keys(config.states)) {\n\t\tconst derivationName = `is${capitalize(stateName)}`;\n\t\tderivations[derivationName] = \"t.boolean()\";\n\t\tderiveCode[derivationName] = `(facts) => facts.state === '${stateName}'`;\n\t}\n\n\t// Collect all events and their transitions\n\tconst eventTransitions = new Map<string, Map<string, string>>();\n\tfor (const [stateName, stateConfig] of Object.entries(config.states)) {\n\t\tif (!stateConfig.on) continue;\n\t\tfor (const [eventName, target] of Object.entries(stateConfig.on)) {\n\t\t\tif (!eventTransitions.has(eventName)) {\n\t\t\t\teventTransitions.set(eventName, new Map());\n\t\t\t}\n\t\t\tconst targetState = typeof target === \"string\" ? target : target.target;\n\t\t\teventTransitions.get(eventName)!.set(stateName, targetState);\n\t\t}\n\t}\n\n\t// Generate events and handlers\n\tfor (const [eventName, transitions] of eventTransitions) {\n\t\tevents[eventName] = {};\n\n\t\tif (transitions.size === 1) {\n\t\t\tconst firstEntry = [...transitions.entries()][0];\n\t\t\tconst toState = firstEntry ? firstEntry[1] : \"unknown\";\n\t\t\teventsCode[eventName] = `(facts) => {\\n facts.state = '${toState}';\\n }`;\n\t\t} else {\n\t\t\tconst cases = [...transitions.entries()]\n\t\t\t\t.map(([from, to]) => ` case '${from}': facts.state = '${to}'; break;`)\n\t\t\t\t.join(\"\\n\");\n\t\t\teventsCode[eventName] = `(facts) => {\\n switch (facts.state) {\\n${cases}\\n }\\n }`;\n\t\t}\n\t}\n\n\t// Generate init code\n\tconst initLines = [` facts.state = '${config.initial}';`];\n\tif (config.context) {\n\t\tfor (const [key, value] of Object.entries(config.context)) {\n\t\t\tinitLines.push(` facts.${key} = ${JSON.stringify(value)};`);\n\t\t}\n\t}\n\tconst initCode = `(facts) => {\\n${initLines.join(\"\\n\")}\\n }`;\n\n\treturn {\n\t\tname: config.id,\n\t\tfacts,\n\t\tderivations,\n\t\tevents,\n\t\trequirements: {},\n\t\tinitCode,\n\t\tderiveCode,\n\t\teventsCode,\n\t};\n}\n\n// ============================================================================\n// Code Generation\n// ============================================================================\n\n/**\n * Generate Directive module code from a structure.\n */\nexport function generateModuleCode(structure: DirectiveModuleStructure): string {\n\tconst lines: string[] = [\n\t\t`import { createModule, t } from '@directive-run/core';`,\n\t\t``,\n\t\t`const ${structure.name}Module = createModule('${structure.name}', {`,\n\t\t` schema: {`,\n\t\t` facts: {`,\n\t];\n\n\t// Facts\n\tfor (const [key, type] of Object.entries(structure.facts)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Derivations\n\tlines.push(` derivations: {`);\n\tfor (const [key, type] of Object.entries(structure.derivations)) {\n\t\tlines.push(` ${key}: ${type},`);\n\t}\n\tlines.push(` },`);\n\n\t// Events\n\tlines.push(` events: {`);\n\tfor (const [key, schema] of Object.entries(structure.events)) {\n\t\tconst schemaStr = Object.entries(schema)\n\t\t\t.map(([k, v]) => `${k}: ${v}`)\n\t\t\t.join(\", \");\n\t\tlines.push(` ${key}: { ${schemaStr} },`);\n\t}\n\tlines.push(` },`);\n\n\t// Requirements\n\tlines.push(` requirements: {},`);\n\tlines.push(` },`);\n\n\t// Init\n\tlines.push(` init: ${structure.initCode},`);\n\n\t// Derive\n\tif (Object.keys(structure.deriveCode).length > 0) {\n\t\tlines.push(` derive: {`);\n\t\tfor (const [key, code] of Object.entries(structure.deriveCode)) {\n\t\t\tlines.push(` ${key}: ${code},`);\n\t\t}\n\t\tlines.push(` },`);\n\t}\n\n\t// Events handlers\n\tlines.push(` events: {`);\n\tfor (const [key, code] of Object.entries(structure.eventsCode)) {\n\t\tlines.push(` ${key}: ${code},`);\n\t}\n\tlines.push(` },`);\n\n\tlines.push(`});`);\n\tlines.push(``);\n\tlines.push(`export { ${structure.name}Module };`);\n\n\treturn lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Infer a t.* type string from a JavaScript value.\n */\nfunction inferTypeString(value: unknown): string {\n\tif (value === null) return \"t.object().nullable()\";\n\tif (value === undefined) return \"t.object().optional()\";\n\n\tswitch (typeof value) {\n\t\tcase \"number\":\n\t\t\treturn \"t.number()\";\n\t\tcase \"string\":\n\t\t\treturn \"t.string()\";\n\t\tcase \"boolean\":\n\t\t\treturn \"t.boolean()\";\n\t\tcase \"object\":\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn \"t.array(t.object())\";\n\t\t\t}\n\t\t\treturn \"t.object()\";\n\t\tdefault:\n\t\t\treturn \"t.object()\";\n\t}\n}\n\n/**\n * Capitalize first letter.\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// ============================================================================\n// Migration Checklist Generator\n// ============================================================================\n\n/**\n * Generate a migration checklist for a given state management pattern.\n */\nexport function generateMigrationChecklist(\n\tsource: \"redux\" | \"zustand\" | \"xstate\",\n): string[] {\n\tconst common = [\n\t\t\"[ ] Install directive: pnpm add directive\",\n\t\t\"[ ] Create module file(s) for your state\",\n\t\t\"[ ] Define schema with facts, derivations, events\",\n\t\t\"[ ] Implement init function for initial state\",\n\t\t\"[ ] Implement event handlers\",\n\t\t\"[ ] Update imports in consuming code\",\n\t\t\"[ ] Test the new implementation\",\n\t\t\"[ ] Remove old state management code\",\n\t];\n\n\tconst sourceSpecific: Record<string, string[]> = {\n\t\tredux: [\n\t\t\t\"[ ] Convert reducers to event handlers\",\n\t\t\t\"[ ] Convert selectors to derivations\",\n\t\t\t\"[ ] Convert thunks to constraints + resolvers\",\n\t\t\t\"[ ] Update useSelector to useDerived\",\n\t\t\t\"[ ] Update useDispatch to system.dispatch\",\n\t\t],\n\t\tzustand: [\n\t\t\t\"[ ] Convert store state to facts\",\n\t\t\t\"[ ] Convert store actions to events\",\n\t\t\t\"[ ] Convert computed getters to derivations\",\n\t\t\t\"[ ] Update useStore hooks to useDirective hooks\",\n\t\t],\n\t\txstate: [\n\t\t\t\"[ ] Convert machine states to a 'state' fact\",\n\t\t\t\"[ ] Convert state checks to derivations (isActive, etc.)\",\n\t\t\t\"[ ] Convert events to Directive events\",\n\t\t\t\"[ ] Convert guards to constraint 'when' conditions\",\n\t\t\t\"[ ] Convert services/actors to constraints + resolvers\",\n\t\t\t\"[ ] Update useMachine to useDirective hooks\",\n\t\t],\n\t};\n\n\tconst specific = sourceSpecific[source] ?? [];\n\treturn [...specific, ...common];\n}\n"]}
|
package/dist/plugins/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var U={debug:0,info:1,warn:2,error:3};function W(s={}){let{level:l="info",filter:a=()=>true,logger:o=console,prefix:c="[Directive]"}=s,i=U[l],t=(e,r,...f)=>{U[e]<i||a(r)&&o[e](`${c} ${r}`,...f);};return {name:"logging",onInit:()=>t("debug","init"),onStart:()=>t("info","start"),onStop:()=>t("info","stop"),onDestroy:()=>t("debug","destroy"),onFactSet:(e,r,f)=>{t("debug","fact.set",{key:e,value:r,prev:f});},onFactDelete:(e,r)=>{t("debug","fact.delete",{key:e,prev:r});},onFactsBatch:e=>{t("debug","facts.batch",{count:e.length,changes:e});},onDerivationCompute:(e,r,f)=>{t("debug","derivation.compute",{id:e,value:r,deps:f});},onDerivationInvalidate:e=>{t("debug","derivation.invalidate",{id:e});},onReconcileStart:()=>{t("debug","reconcile.start");},onReconcileEnd:e=>{t("debug","reconcile.end",{unmet:e.unmet.length,inflight:e.inflight.length,completed:e.completed.length,canceled:e.canceled.length});},onConstraintEvaluate:(e,r)=>{t("debug","constraint.evaluate",{id:e,active:r});},onConstraintError:(e,r)=>{t("error","constraint.error",{id:e,error:r});},onRequirementCreated:e=>{t("debug","requirement.created",{id:e.id,type:e.requirement.type});},onRequirementMet:(e,r)=>{t("info","requirement.met",{id:e.id,byResolver:r});},onRequirementCanceled:e=>{t("debug","requirement.canceled",{id:e.id});},onResolverStart:(e,r)=>{t("debug","resolver.start",{resolver:e,requirementId:r.id});},onResolverComplete:(e,r,f)=>{t("info","resolver.complete",{resolver:e,requirementId:r.id,duration:f});},onResolverError:(e,r,f)=>{t("error","resolver.error",{resolver:e,requirementId:r.id,error:f});},onResolverRetry:(e,r,f)=>{t("warn","resolver.retry",{resolver:e,requirementId:r.id,attempt:f});},onResolverCancel:(e,r)=>{t("debug","resolver.cancel",{resolver:e,requirementId:r.id});},onEffectRun:e=>{t("debug","effect.run",{id:e});},onEffectError:(e,r)=>{t("error","effect.error",{id:e,error:r});},onSnapshot:e=>{t("debug","timetravel.snapshot",{id:e.id,trigger:e.trigger});},onTimeTravel:(e,r)=>{t("info","timetravel.jump",{from:e,to:r});},onError:e=>{t("error","error",{source:e.source,sourceId:e.sourceId,message:e.message});},onErrorRecovery:(e,r)=>{t("warn","error.recovery",{source:e.source,sourceId:e.sourceId,strategy:r});}}}function J(){if(typeof window>"u")return {systems:new Map,getSystem:()=>null,getSystems:()=>[],inspect:()=>null,getEvents:()=>[]};if(!window.__DIRECTIVE__){let s=new Map;window.__DIRECTIVE__={systems:s,getSystem(l){return l?s.get(l)?.system??null:s.values().next().value?.system??null},getSystems(){return [...s.keys()]},inspect(l){return this.getSystem(l)?.inspect()??null},getEvents(l){return l?s.get(l)?.events??[]:s.values().next().value?.events??[]}};}return window.__DIRECTIVE__}function G(s={}){let{name:l="default",trace:a=false}=s,o=J(),c={system:null,events:[],maxEvents:1e3};o.systems.set(l,c);let i=(t,e)=>{a&&(c.events.push({timestamp:Date.now(),type:t,data:e}),c.events.length>c.maxEvents&&c.events.shift());};return {name:"devtools",onInit:t=>{c.system=t,i("init",{}),typeof window<"u"&&console.log(`%c[Directive Devtools]%c System "${l}" initialized. Access via window.__DIRECTIVE__`,"color: #7c3aed; font-weight: bold","color: inherit");},onStart:()=>i("start",{}),onStop:()=>i("stop",{}),onDestroy:()=>{i("destroy",{}),o.systems.delete(l);},onFactSet:(t,e,r)=>{i("fact.set",{key:t,value:e,prev:r});},onFactsBatch:t=>{i("facts.batch",{changes:t});},onReconcileStart:()=>{i("reconcile.start",{});},onReconcileEnd:t=>{i("reconcile.end",t);},onConstraintEvaluate:(t,e)=>{i("constraint.evaluate",{id:t,active:e});},onRequirementCreated:t=>{i("requirement.created",{id:t.id,type:t.requirement.type});},onRequirementMet:(t,e)=>{i("requirement.met",{id:t.id,byResolver:e});},onResolverStart:(t,e)=>{i("resolver.start",{resolver:t,requirementId:e.id});},onResolverComplete:(t,e,r)=>{i("resolver.complete",{resolver:t,requirementId:e.id,duration:r});},onResolverError:(t,e,r)=>{i("resolver.error",{resolver:t,requirementId:e.id,error:String(r)});},onSnapshot:t=>{i("timetravel.snapshot",{id:t.id,trigger:t.trigger});},onTimeTravel:(t,e)=>{i("timetravel.jump",{from:t,to:e});},onError:t=>{i("error",{source:t.source,sourceId:t.sourceId,message:t.message});}}}function j(s,l=50){let a=new Set(["__proto__","constructor","prototype"]),o=new WeakSet;function c(i,t){if(t>l)return false;if(i==null||typeof i!="object")return true;let e=i;if(o.has(e))return true;if(o.add(e),Array.isArray(e)){for(let r of e)if(!c(r,t+1))return o.delete(e),false;return o.delete(e),true}for(let r of Object.keys(e))if(a.has(r)||!c(e[r],t+1))return o.delete(e),false;return o.delete(e),true}return c(s,0)}function z(s){let{storage:l,key:a,include:o,exclude:c=[],debounce:i=100,onRestore:t,onSave:e,onError:r}=s,f=null,b=null,y=new Set,T=n=>c.includes(n)?false:o?o.includes(n):true,E=()=>{try{let n=l.getItem(a);if(!n)return null;let g=JSON.parse(n);return typeof g!="object"||g===null?null:j(g)?g:(r?.(new Error("Potential prototype pollution detected in stored data")),null)}catch(n){return r?.(n instanceof Error?n:new Error(String(n))),null}},D=()=>{if(b)try{let n={};for(let g of y)T(g)&&(n[g]=b.facts[g]);l.setItem(a,JSON.stringify(n)),e?.(n);}catch(n){r?.(n instanceof Error?n:new Error(String(n)));}},S=()=>{f&&clearTimeout(f),f=setTimeout(D,i);};return {name:"persistence",onInit:n=>{b=n;let g=E();g&&(b.facts.$store.batch(()=>{for(let[v,p]of Object.entries(g))T(v)&&(b.facts[v]=p,y.add(v));}),t?.(g));},onDestroy:()=>{f&&clearTimeout(f),D();},onFactSet:n=>{y.add(n),T(n)&&S();},onFactDelete:n=>{y.delete(n),T(n)&&S();},onFactsBatch:n=>{let g=false;for(let v of n)v.type==="set"?y.add(v.key):y.delete(v.key),T(v.key)&&(g=true);g&&S();}}}function K(s={}){let{onSlowConstraint:l,onSlowResolver:a,slowConstraintThresholdMs:o=16,slowResolverThresholdMs:c=1e3}=s,i=new Map,t=new Map,e=new Map,r={runs:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0},f=0,b=0,y=0;function T(n){let g=i.get(n);return g||(g={evaluations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastEvaluatedAt:0},i.set(n,g)),g}function E(n){let g=t.get(n);return g||(g={starts:0,completions:0,errors:0,retries:0,cancellations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastCompletedAt:0},t.set(n,g)),g}function D(n){let g=e.get(n);return g||(g={runs:0,errors:0,lastRunAt:0},e.set(n,g)),g}return {name:"performance",onStart(){f=Date.now();},onConstraintEvaluate(n,g){let v=performance.now(),p=T(n);if(p.evaluations++,p.lastEvaluatedAt=Date.now(),y>0){let h=v-y;p.totalDurationMs+=h;let A=p.evaluations;p.avgDurationMs=p.totalDurationMs/A,h>p.maxDurationMs&&(p.maxDurationMs=h),h>o&&l?.(n,h);}y=v;},onResolverStart(n,g){let v=E(n);v.starts++;},onResolverComplete(n,g,v){let p=E(n);p.completions++,p.totalDurationMs+=v,p.avgDurationMs=p.totalDurationMs/p.completions,v>p.maxDurationMs&&(p.maxDurationMs=v),p.lastCompletedAt=Date.now(),v>c&&a?.(n,v);},onResolverError(n,g,v){E(n).errors++;},onResolverRetry(n,g,v){E(n).retries++;},onResolverCancel(n,g){E(n).cancellations++;},onEffectRun(n){let g=D(n);g.runs++,g.lastRunAt=Date.now();},onEffectError(n,g){D(n).errors++;},onReconcileStart(){b=performance.now(),y=0;},onReconcileEnd(){let n=performance.now()-b;r.runs++,r.totalDurationMs+=n,r.avgDurationMs=r.totalDurationMs/r.runs,n>r.maxDurationMs&&(r.maxDurationMs=n);},getSnapshot(){let n={};for(let[p,h]of i)n[p]={...h};let g={};for(let[p,h]of t)g[p]={...h};let v={};for(let[p,h]of e)v[p]={...h};return {constraints:n,resolvers:g,effects:v,reconcile:{...r},uptime:f?Date.now()-f:0}},reset(){i.clear(),t.clear(),e.clear(),r.runs=0,r.totalDurationMs=0,r.avgDurationMs=0,r.maxDurationMs=0,y=0;}}}function F(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function H(s,l){if(s.length===0)return 0;let a=[...s].sort((c,i)=>c-i),o=Math.ceil(l/100*a.length)-1;return a[Math.max(0,o)]??0}function Q(s={}){let{serviceName:l="directive-agents",metrics:a={},tracing:o={},alerts:c=[],summaryMetrics:i={},events:t={}}=s,e={requests:i.requests??"agent.requests",errors:i.errors??"agent.errors",latency:i.latency??"agent.latency",tokens:i.tokens??"agent.tokens",cost:i.cost??"agent.cost"},{enabled:r=true,exportInterval:f,exporter:b,maxDataPoints:y=1e3}=a,{enabled:T=true,sampleRate:E=1,maxSpans:D=1e3,exporter:S}=o,n=Date.now(),g=new Map,v=new Map,p=[],h=[],A=new Map,w=new Map,_;f&&(b||S)&&(_=setInterval(async()=>{try{if(b&&r&&await b(Array.from(w.values())),S&&T){let u=p.splice(0,100);u.length>0&&await S(u);}}catch(u){console.error("[Directive Observability] Export error:",u);}},f));function L(u){if(!r)return;let d=`${u.name}:${JSON.stringify(Object.fromEntries(Object.entries(u.labels).sort()))}`,m=g.get(d);m||(m=[],g.set(d,m)),m.push(u),m.length>y&&m.shift(),B(u.name,m),t.onMetricRecorded?.(u),M(u.name);}function B(u,d){if(d.length===0)return;let m=d.map(C=>C.value),x=m.reduce((C,R)=>C+R,0),P=d[0],O=m[m.length-1],I={name:u,type:P.type,count:d.length,sum:x,min:Math.min(...m),max:Math.max(...m),avg:x/d.length,lastValue:O,lastUpdated:Date.now()};w.set(u,I);}function M(u){for(let d of c){if(d.metric!==u)continue;let m=w.get(u);if(!m)continue;let x=`${d.metric}:${d.threshold}`,P=A.get(x),O=d.cooldownMs??6e4;if(P&&Date.now()-P<O)continue;let I=d.operator??">",C=m.lastValue,R=d.threshold,N=false;switch(I){case ">":N=C>R;break;case "<":N=C<R;break;case ">=":N=C>=R;break;case "<=":N=C<=R;break;case "==":N=C===R;break}if(N){let V={alertId:F(),metric:u,currentValue:C,threshold:R,operator:I,action:d.action,timestamp:Date.now(),message:`Alert: ${u} ${I} ${R} (current: ${C})`};switch(h.push(V),h.length>1e3&&h.splice(0,h.length-1e3),A.set(x,Date.now()),t.onAlert?.(V),d.action){case "log":console.log(`[Observability] ${V.message}`);break;case "warn":console.warn(`[Observability] ${V.message}`);break;case "alert":console.error(`[Observability ALERT] ${V.message}`);break;case "callback":d.callback?.(m,R);break}}}}function k(u){let d=[];for(let[m,x]of g)if(m.startsWith(`${u}:`))for(let P of x)d.push(P.value);return d.length===0?{}:{p50:H(d,50),p90:H(d,90),p99:H(d,99)}}return {incrementCounter(u,d={},m=1){L({name:u,type:"counter",value:m,labels:d,timestamp:Date.now()});},setGauge(u,d,m={}){L({name:u,type:"gauge",value:d,labels:m,timestamp:Date.now()});},observeHistogram(u,d,m={}){L({name:u,type:"histogram",value:d,labels:m,timestamp:Date.now()});},startSpan(u,d){if(Math.random()>E)return {traceId:"sampled-out",spanId:"sampled-out",operationName:u,serviceName:l,startTime:Date.now(),status:"ok",tags:{},logs:[]};let m={traceId:d?v.get(d)?.traceId??F():F(),spanId:F(),parentSpanId:d,operationName:u,serviceName:l,startTime:Date.now(),status:"ok",tags:{},logs:[]};return T&&(v.set(m.spanId,m),t.onSpanStart?.(m)),m},endSpan(u,d="ok"){if(u==="sampled-out")return;let m=v.get(u);if(m){for(m.endTime=Date.now(),m.duration=m.endTime-m.startTime,m.status=d,v.delete(u),p.push(m);p.length>D;)p.shift();L({name:`${m.operationName}.latency`,type:"histogram",value:m.duration,labels:{},timestamp:Date.now()}),d==="error"&&L({name:`${m.operationName}.errors`,type:"counter",value:1,labels:{},timestamp:Date.now()}),t.onSpanEnd?.(m);}},addSpanLog(u,d,m="info"){if(u==="sampled-out")return;let x=v.get(u);x&&x.logs.push({timestamp:Date.now(),message:d,level:m});},addSpanTag(u,d,m){if(u==="sampled-out")return;let x=v.get(u);x&&(x.tags[d]=m);},getDashboard(){let u=w.get(e.requests),d=w.get(e.errors),m=w.get(e.latency),x=w.get(e.tokens),P=w.get(e.cost),O=u?.sum??0,I=d?.sum??0,C=O>0?I/O:0,R=m?k(e.latency):{};return {service:{name:l,uptime:Date.now()-n,startTime:n},metrics:Object.fromEntries(w),traces:[...p].slice(-100),alerts:[...h].slice(-50),summary:{totalRequests:O,totalErrors:I,errorRate:C,avgLatency:m?.avg??0,p99Latency:R.p99??0,activeSpans:v.size,totalTokens:x?.sum??0,totalCost:P?.sum??0}}},getMetric(u){let d=w.get(u);if(!d)return;let m=k(u);return {...d,...m}},getTraces(u=100){return [...p].slice(-u)},getAlerts(){return [...h]},export(){return {metrics:Array.from(w.values()),traces:[...p],alerts:[...h]}},clear(){g.clear(),w.clear(),v.clear(),p.length=0,h.length=0,A.clear();},async dispose(){_&&(clearInterval(_),_=void 0);try{b&&r&&w.size>0&&await b(Array.from(w.values())),S&&T&&p.length>0&&await S([...p]);}catch(u){console.error("[Directive Observability] Error flushing data during dispose:",u);}g.clear(),w.clear(),v.clear(),p.length=0,h.length=0,A.clear();},getHealthStatus(){let u=w.get(e.requests),d=w.get(e.errors),m=u?.sum??0,x=d?.sum??0,P=m>0?x/m:0,O=h.filter(I=>Date.now()-I.timestamp<3e5).length;return {healthy:P<.1&&O===0,uptime:Date.now()-n,errorRate:P,activeAlerts:O}}}}function X(s){return {trackRun(l,a){let o={agent:l};s.incrementCounter("agent.requests",o),a.success||s.incrementCounter("agent.errors",o),s.observeHistogram("agent.latency",a.latencyMs,o),a.inputTokens!==void 0&&(s.incrementCounter("agent.tokens.input",o,a.inputTokens),s.incrementCounter("agent.tokens",o,a.inputTokens)),a.outputTokens!==void 0&&(s.incrementCounter("agent.tokens.output",o,a.outputTokens),s.incrementCounter("agent.tokens",o,a.outputTokens)),a.cost!==void 0&&s.incrementCounter("agent.cost",o,a.cost),a.toolCalls!==void 0&&s.incrementCounter("agent.tool_calls",o,a.toolCalls);},trackGuardrail(l,a){let o={guardrail:l};s.incrementCounter("guardrail.checks",o),a.passed||s.incrementCounter("guardrail.failures",o),a.blocked&&s.incrementCounter("guardrail.blocks",o),s.observeHistogram("guardrail.latency",a.latencyMs,o);},trackApproval(l,a){let o={tool:l};s.incrementCounter("approval.requests",o),a.approved?s.incrementCounter("approval.approved",o):s.incrementCounter("approval.rejected",o),a.timedOut&&s.incrementCounter("approval.timeouts",o),s.observeHistogram("approval.wait_time",a.waitTimeMs,o);},trackHandoff(l,a,o){s.incrementCounter("handoff.count",{from:l,to:a}),s.observeHistogram("handoff.latency",o);}}}function Y(s){let l=[{key:"service.name",value:{stringValue:s.serviceName??"directive-agents"}}];if(s.serviceVersion&&l.push({key:"service.version",value:{stringValue:s.serviceVersion}}),s.resourceAttributes)for(let[a,o]of Object.entries(s.resourceAttributes))l.push({key:a,value:{stringValue:o}});return {attributes:l}}function $(s){return `${BigInt(s)*BigInt(1e6)}`}function Z(s){switch(s){case "counter":return "sum";case "gauge":return "gauge";case "histogram":return "histogram";default:return "gauge"}}function ee(s,l,a){let o=s.map(c=>{let i=c.lastUpdated-6e4,t=[{asInt:c.type==="counter"?c.sum:void 0,asDouble:c.type!=="counter"?c.lastValue:void 0,timeUnixNano:$(c.lastUpdated),startTimeUnixNano:$(i),attributes:[]}],e=Z(c.type),r={name:c.name,unit:""};return e==="sum"?r.sum={dataPoints:t,aggregationTemporality:2,isMonotonic:true}:e==="histogram"?r.histogram={dataPoints:[{count:c.count,sum:c.sum,min:c.min,max:c.max,timeUnixNano:$(c.lastUpdated),startTimeUnixNano:$(i),attributes:[]}],aggregationTemporality:2}:r.gauge={dataPoints:t},r});return {resourceMetrics:[{resource:l,scopeMetrics:[{scope:{name:"directive",version:a},metrics:o}]}]}}function te(s,l,a){let o=s.map(c=>{let i=c.logs.map(r=>({timeUnixNano:$(r.timestamp),name:r.level,attributes:[{key:"message",value:{stringValue:r.message}},{key:"level",value:{stringValue:r.level}}]})),t=Object.entries(c.tags).map(([r,f])=>({key:r,value:typeof f=="string"?{stringValue:f}:typeof f=="number"?{intValue:`${f}`}:{boolValue:f}})),e=c.status==="ok"?1:c.status==="error"?2:0;return {traceId:c.traceId.replace(/-/g,"").padEnd(32,"0").slice(0,32),spanId:c.spanId.replace(/-/g,"").padEnd(16,"0").slice(0,16),parentSpanId:c.parentSpanId?c.parentSpanId.replace(/-/g,"").padEnd(16,"0").slice(0,16):void 0,name:c.operationName,kind:1,startTimeUnixNano:$(c.startTime),endTimeUnixNano:c.endTime?$(c.endTime):$(c.startTime),attributes:t,events:i,status:{code:e}}});return {resourceSpans:[{resource:l,scopeSpans:[{scope:{name:"directive",version:a},spans:o}]}]}}function re(s){let{endpoint:l,headers:a={},scopeVersion:o="0.1.0",timeoutMs:c=1e4,fetch:i=globalThis.fetch,onError:t}=s;try{let f=new URL(l);if(f.protocol!=="http:"&&f.protocol!=="https:")throw new Error("Only http: and https: protocols are supported")}catch(f){throw new Error(`[Directive OTLP] Invalid endpoint URL "${l}": ${f instanceof Error?f.message:String(f)}`)}if(/\/v1\/(metrics|traces)/.test(l)&&console.warn(`[Directive OTLP] Endpoint "${l}" already contains a /v1/metrics or /v1/traces path. The exporter will append /v1/metrics or /v1/traces automatically. Use the base URL (e.g., "http://localhost:4318") instead.`),c<=0||!Number.isFinite(c))throw new Error(`[Directive OTLP] timeoutMs must be > 0, got ${c}`);let e=Y(s);async function r(f,b,y){let T=`${l.replace(/\/$/,"")}${f}`,E=new AbortController,D=setTimeout(()=>E.abort(),c);try{let S=await i(T,{method:"POST",headers:{"Content-Type":"application/json",...a},body:JSON.stringify(b),signal:E.signal});if(!S.ok)throw new Error(`OTLP export failed: ${S.status} ${S.statusText}`)}catch(S){let n=S instanceof Error?S:new Error(String(S));t?t(n,y):console.error(`[Directive OTLP] Export ${y} error:`,n.message);}finally{clearTimeout(D);}}return {async exportMetrics(f){if(f.length===0)return;let b=ee(f,e,o);await r("/v1/metrics",b,"metrics");},async exportTraces(f){if(f.length===0)return;let b=te(f,e,o);await r("/v1/traces",b,"traces");}}}var q=class extends Error{code="CIRCUIT_OPEN";retryAfterMs;state;constructor(l,a,o="OPEN",c){let i=c?`[Directive CircuitBreaker] Circuit "${l}" is ${o}. ${c}`:`[Directive CircuitBreaker] Circuit "${l}" is ${o}. Request rejected. Try again in ${Math.ceil(a/1e3)}s.`;super(i),this.name="CircuitBreakerOpenError",this.retryAfterMs=a,this.state=o;}};function ne(s={}){let{failureThreshold:l=5,recoveryTimeMs:a=3e4,halfOpenMaxRequests:o=3,failureWindowMs:c=6e4,observability:i,metricPrefix:t="circuit_breaker",name:e="default",isFailure:r=()=>true,onStateChange:f}=s;if(l<1||!Number.isFinite(l))throw new Error(`[Directive CircuitBreaker] failureThreshold must be >= 1, got ${l}`);if(a<=0||!Number.isFinite(a))throw new Error(`[Directive CircuitBreaker] recoveryTimeMs must be > 0, got ${a}`);if(o<1||!Number.isFinite(o))throw new Error(`[Directive CircuitBreaker] halfOpenMaxRequests must be >= 1, got ${o}`);if(c<=0||!Number.isFinite(c))throw new Error(`[Directive CircuitBreaker] failureWindowMs must be > 0, got ${c}`);let b="CLOSED",y=[],T=0,E=0,D=Date.now(),S=0,n=0,g=0,v=0,p=0,h=null,A=null;function w(M){if(b===M)return;let k=b;b=M,D=Date.now(),M==="OPEN"&&(S=Date.now()),M==="HALF_OPEN"&&(T=0,E=0),f?.(k,M),i&&i.incrementCounter(`${t}.state_change`,{name:e,from:k,to:M});}function _(){let M=Date.now()-c;return y=y.filter(k=>k>M),y.length}function L(){v++,A=Date.now(),i&&i.incrementCounter(`${t}.success`,{name:e}),b==="HALF_OPEN"&&(E++,E>=o&&(w("CLOSED"),y=[]));}function B(M){if(!r(M)){L();return}g++,h=Date.now(),y.push(Date.now());let k=l*2;if(y.length>k&&(y=y.slice(-k)),i&&i.incrementCounter(`${t}.failure`,{name:e}),b==="HALF_OPEN"){w("OPEN");return}b==="CLOSED"&&_()>=l&&w("OPEN");}return {async execute(M){if(n++,i&&i.incrementCounter(`${t}.requests`,{name:e}),b==="OPEN")if(Date.now()-S>=a)w("HALF_OPEN");else throw p++,i&&i.incrementCounter(`${t}.rejected`,{name:e}),new q(e,a-(Date.now()-S));if(b==="HALF_OPEN"){if(T>=o)throw p++,new q(e,a,"HALF_OPEN",`Max trial requests (${o}) reached.`);T++;}let k=Date.now();try{let u=await M();return L(),i&&i.observeHistogram(`${t}.latency`,Date.now()-k,{name:e}),u}catch(u){let d=u instanceof Error?u:new Error(String(u));throw B(d),i&&i.observeHistogram(`${t}.latency`,Date.now()-k,{name:e}),u}},getState(){return b==="OPEN"&&Date.now()-S>=a&&w("HALF_OPEN"),b},getStats(){return {state:this.getState(),totalRequests:n,totalFailures:g,totalSuccesses:v,totalRejected:p,recentFailures:_(),lastFailureTime:h,lastSuccessTime:A,lastStateChange:D}},forceState(M){w(M);},reset(){let M=b;b="CLOSED",y=[],T=0,E=0,D=Date.now(),S=0,n=0,g=0,v=0,p=0,h=null,A=null,M!=="CLOSED"&&f?.(M,"CLOSED");},isAllowed(){return b==="CLOSED"?true:b==="OPEN"?Date.now()-S>=a:T<o}}}
|
|
2
|
-
exports.CircuitBreakerOpenError=
|
|
1
|
+
'use strict';var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var De={debug:0,info:1,warn:2,error:3};function Ke(e={}){let{level:s="info",filter:o=()=>true,logger:r=console,prefix:a="[Directive]"}=e,d=De[s],c=(n,i,...l)=>{De[n]<d||o(i)&&r[n](`${a} ${i}`,...l);};return {name:"logging",onInit:()=>c("debug","init"),onStart:()=>c("info","start"),onStop:()=>c("info","stop"),onDestroy:()=>c("debug","destroy"),onFactSet:(n,i,l)=>{c("debug","fact.set",{key:n,value:i,prev:l});},onFactDelete:(n,i)=>{c("debug","fact.delete",{key:n,prev:i});},onFactsBatch:n=>{c("debug","facts.batch",{count:n.length,changes:n});},onDerivationCompute:(n,i,l)=>{c("debug","derivation.compute",{id:n,value:i,deps:l});},onDerivationInvalidate:n=>{c("debug","derivation.invalidate",{id:n});},onReconcileStart:()=>{c("debug","reconcile.start");},onReconcileEnd:n=>{c("debug","reconcile.end",{unmet:n.unmet.length,inflight:n.inflight.length,completed:n.completed.length,canceled:n.canceled.length});},onConstraintEvaluate:(n,i)=>{c("debug","constraint.evaluate",{id:n,active:i});},onConstraintError:(n,i)=>{c("error","constraint.error",{id:n,error:i});},onRequirementCreated:n=>{c("debug","requirement.created",{id:n.id,type:n.requirement.type});},onRequirementMet:(n,i)=>{c("info","requirement.met",{id:n.id,byResolver:i});},onRequirementCanceled:n=>{c("debug","requirement.canceled",{id:n.id});},onResolverStart:(n,i)=>{c("debug","resolver.start",{resolver:n,requirementId:i.id});},onResolverComplete:(n,i,l)=>{c("info","resolver.complete",{resolver:n,requirementId:i.id,duration:l});},onResolverError:(n,i,l)=>{c("error","resolver.error",{resolver:n,requirementId:i.id,error:l});},onResolverRetry:(n,i,l)=>{c("warn","resolver.retry",{resolver:n,requirementId:i.id,attempt:l});},onResolverCancel:(n,i)=>{c("debug","resolver.cancel",{resolver:n,requirementId:i.id});},onEffectRun:n=>{c("debug","effect.run",{id:n});},onEffectError:(n,i)=>{c("error","effect.error",{id:n,error:i});},onSnapshot:n=>{c("debug","timetravel.snapshot",{id:n.id,trigger:n.trigger});},onTimeTravel:(n,i)=>{c("info","timetravel.jump",{from:n,to:i});},onError:n=>{c("error","error",{source:n.source,sourceId:n.sourceId,message:n.message});},onErrorRecovery:(n,i)=>{c("warn","error.recovery",{source:n.source,sourceId:n.sourceId,strategy:i});}}}var ie=class{constructor(s){this.capacity=s;this.buf=new Array(s);}buf;head=0;_size=0;get size(){return this._size}push(s){this.buf[this.head]=s,this.head=(this.head+1)%this.capacity,this._size<this.capacity&&this._size++;}toArray(){return this._size===0?[]:this._size<this.capacity?this.buf.slice(0,this._size):[...this.buf.slice(this.head),...this.buf.slice(0,this.head)]}clear(){this.buf=new Array(this.capacity),this.head=0,this._size=0;}};function le(){try{if(typeof process<"u"&&process.env?.NODE_ENV==="production")return !1}catch{}try{if(typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&undefined?.MODE==="production")return !1}catch{}return true}function ge(e){try{if(e===void 0)return "undefined";if(e===null)return "null";if(typeof e=="bigint")return String(e)+"n";if(typeof e=="symbol")return String(e);if(typeof e=="object"){let s=JSON.stringify(e,(o,r)=>typeof r=="bigint"?String(r)+"n":typeof r=="symbol"?String(r):r);return s.length>120?s.slice(0,117)+"...":s}return String(e)}catch{return "<error>"}}function K(e,s){return e.length<=s?e:e.slice(0,s-3)+"..."}function te(e){try{return e.inspect()}catch{return null}}function Re(e){try{return e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e))}catch{return null}}function ke(e){return e===void 0?1e3:!Number.isFinite(e)||e<1?(le()&&console.warn(`[directive:devtools] Invalid maxEvents value (${e}), using default 1000`),1e3):Math.floor(e)}function Le(){return {reconcileCount:0,reconcileTotalMs:0,resolverStats:new Map,effectRunCount:0,effectErrorCount:0,lastReconcileStartMs:0}}var Je=200,ne=340,re=16,oe=80,fe=2,be=["#8b9aff","#4ade80","#fbbf24","#c084fc","#f472b6","#22d3ee"];function Oe(){return {entries:new ie(Je),inflight:new Map}}function Pe(){return {derivationDeps:new Map,activeConstraints:new Set,recentlyChangedFacts:new Set,recentlyComputedDerivations:new Set,recentlyActiveConstraints:new Set,animationTimer:null}}var Ie=1e4,_e=100;function $e(){return {isRecording:false,recordedEvents:[],snapshots:[]}}var Ne=50,ye=200,b={bg:"#1a1a2e",text:"#e0e0e0",accent:"#8b9aff",muted:"#b0b0d0",border:"#333",rowBorder:"#2a2a4a",green:"#4ade80",yellow:"#fbbf24",red:"#f87171",closeBtn:"#aaa",font:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},V={nodeW:90,nodeH:16,nodeGap:6,startY:16,colGap:20,fontSize:10,labelMaxChars:11};function Be(e,s,o,r){let a=false,d={position:"fixed",zIndex:"99999",...s.includes("bottom")?{bottom:"12px"}:{top:"12px"},...s.includes("right")?{right:"12px"}:{left:"12px"}},c=document.createElement("style");c.textContent=`[data-directive-devtools] summary:focus-visible{outline:2px solid ${b.accent};outline-offset:2px;border-radius:2px}[data-directive-devtools] button:focus-visible{outline:2px solid ${b.accent};outline-offset:2px}`,document.head.appendChild(c);let n=document.createElement("button");n.setAttribute("aria-label","Open Directive DevTools"),n.setAttribute("aria-expanded",String(o)),n.title="Ctrl+Shift+D to toggle",Object.assign(n.style,{...d,background:b.bg,color:b.text,border:`1px solid ${b.border}`,borderRadius:"6px",padding:"10px 14px",minWidth:"44px",minHeight:"44px",cursor:"pointer",fontFamily:b.font,fontSize:"12px",display:o?"none":"block"}),n.textContent="Directive";let i=document.createElement("div");i.setAttribute("role","region"),i.setAttribute("aria-label","Directive DevTools"),i.setAttribute("data-directive-devtools",""),i.tabIndex=-1,Object.assign(i.style,{...d,background:b.bg,color:b.text,border:`1px solid ${b.border}`,borderRadius:"8px",padding:"12px",fontFamily:b.font,fontSize:"11px",maxWidth:"min(380px, calc(100vw - 24px))",maxHeight:"min(500px, calc(100vh - 24px))",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.5)",display:o?"block":"none"});let l=document.createElement("div");Object.assign(l.style,{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"});let g=document.createElement("strong");g.style.color=b.accent,g.textContent=e==="default"?"Directive DevTools":`DevTools (${e})`;let h=document.createElement("button");h.setAttribute("aria-label","Close DevTools"),Object.assign(h.style,{background:"none",border:"none",color:b.closeBtn,cursor:"pointer",fontSize:"16px",padding:"8px 12px",minWidth:"44px",minHeight:"44px",lineHeight:"1",display:"flex",alignItems:"center",justifyContent:"center"}),h.textContent="\xD7",l.appendChild(g),l.appendChild(h),i.appendChild(l);let k=document.createElement("div");k.style.marginBottom="6px",k.setAttribute("aria-live","polite");let _=document.createElement("span");_.style.color=b.green,_.textContent="Settled",k.appendChild(_),i.appendChild(k);let C=document.createElement("div");Object.assign(C.style,{display:"none",marginBottom:"8px",padding:"4px 8px",background:"#252545",borderRadius:"4px",alignItems:"center",gap:"6px"});let T=document.createElement("button");Object.assign(T.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:b.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),T.textContent="\u25C0 Undo",T.disabled=true;let u=document.createElement("button");Object.assign(u.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:b.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),u.textContent="Redo \u25B6",u.disabled=true;let f=document.createElement("span");f.style.color=b.muted,f.style.fontSize="10px",C.appendChild(T),C.appendChild(u),C.appendChild(f),i.appendChild(C);function A(q,X){let U=document.createElement("details");X&&(U.open=true),U.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${q} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",U.appendChild(Y);let Q=document.createElement("table");Object.assign(Q.style,{width:"100%",borderCollapse:"collapse",fontSize:"11px"});let Te=document.createElement("thead"),Me=document.createElement("tr");for(let Ye of ["Key","Value"]){let ce=document.createElement("th");ce.scope="col",Object.assign(ce.style,{textAlign:"left",padding:"2px 4px",color:b.accent}),ce.textContent=Ye,Me.appendChild(ce);}Te.appendChild(Me),Q.appendChild(Te);let Ae=document.createElement("tbody");return Q.appendChild(Ae),U.appendChild(Q),{details:U,tbody:Ae,countSpan:ee}}function w(q,X){let U=document.createElement("details");U.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:X,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${q} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",U.appendChild(Y);let Q=document.createElement("ul");return Object.assign(Q.style,{margin:"0",paddingLeft:"16px"}),U.appendChild(Q),{details:U,list:Q,countSpan:ee}}let L=A("Facts",true);i.appendChild(L.details);let B=A("Derivations",false);i.appendChild(B.details);let D=w("Inflight",b.yellow);i.appendChild(D.details);let j=w("Unmet",b.red);i.appendChild(j.details);let O=document.createElement("details");O.style.marginBottom="4px";let H=document.createElement("summary");Object.assign(H.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),H.textContent="Performance",O.appendChild(H);let P=document.createElement("div");P.style.fontSize="10px",P.style.color=b.muted,P.textContent="No data yet",O.appendChild(P),i.appendChild(O);let N=document.createElement("details");N.style.marginBottom="4px";let S=document.createElement("summary");Object.assign(S.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),S.textContent="Dependency Graph",N.appendChild(S);let x=document.createElementNS("http://www.w3.org/2000/svg","svg");x.setAttribute("width","100%"),x.setAttribute("height","120"),x.setAttribute("role","img"),x.setAttribute("aria-label","System dependency graph"),x.style.display="block",x.setAttribute("viewBox","0 0 460 120"),x.setAttribute("preserveAspectRatio","xMinYMin meet"),N.appendChild(x),i.appendChild(N);let E=document.createElement("details");E.style.marginBottom="4px";let $=document.createElement("summary");Object.assign($.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),$.textContent="Timeline",E.appendChild($);let I=document.createElementNS("http://www.w3.org/2000/svg","svg");I.setAttribute("width","100%"),I.setAttribute("height","60"),I.setAttribute("role","img"),I.setAttribute("aria-label","Resolver execution timeline"),I.style.display="block",I.setAttribute("viewBox",`0 0 ${ne} 60`),I.setAttribute("preserveAspectRatio","xMinYMin meet");let m=document.createElementNS("http://www.w3.org/2000/svg","text");m.setAttribute("x",String(ne/2)),m.setAttribute("y","30"),m.setAttribute("text-anchor","middle"),m.setAttribute("fill",b.muted),m.setAttribute("font-size","10"),m.setAttribute("font-family",b.font),m.textContent="No resolver activity yet",I.appendChild(m),E.appendChild(I),i.appendChild(E);let v,y,t,p;if(r){let q=document.createElement("details");q.style.marginBottom="4px";let X=document.createElement("summary");Object.assign(X.style,{cursor:"pointer",color:b.accent,marginBottom:"4px"}),t=document.createElement("span"),t.textContent="0",X.textContent="Events (",X.appendChild(t),X.appendChild(document.createTextNode(")")),q.appendChild(X),y=document.createElement("div"),Object.assign(y.style,{maxHeight:"150px",overflow:"auto",fontSize:"10px"}),y.setAttribute("role","log"),y.setAttribute("aria-live","polite"),y.tabIndex=0;let U=document.createElement("div");U.style.color=b.muted,U.style.padding="4px",U.textContent="Waiting for events...",U.className="dt-events-empty",y.appendChild(U),q.appendChild(y),i.appendChild(q),v=q,p=document.createElement("div");}else v=document.createElement("details"),y=document.createElement("div"),t=document.createElement("span"),p=document.createElement("div"),p.style.fontSize="10px",p.style.color=b.muted,p.style.marginTop="4px",p.style.fontStyle="italic",p.textContent="Enable trace: true for event log",i.appendChild(p);let M=document.createElement("div");Object.assign(M.style,{display:"flex",gap:"6px",marginTop:"6px"});let R=document.createElement("button");Object.assign(R.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:b.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),R.textContent="\u23FA Record";let z=document.createElement("button");Object.assign(z.style,{background:"none",border:`1px solid ${b.border}`,color:b.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:b.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),z.textContent="\u2913 Export",M.appendChild(R),M.appendChild(z),i.appendChild(M),i.addEventListener("wheel",q=>{let X=i,U=X.scrollTop===0&&q.deltaY<0,Y=X.scrollTop+X.clientHeight>=X.scrollHeight&&q.deltaY>0;(U||Y)&&q.preventDefault();},{passive:false});let F=o,W=new Set;function G(){F=true,i.style.display="block",n.style.display="none",n.setAttribute("aria-expanded","true"),h.focus();}function J(){F=false,i.style.display="none",n.style.display="block",n.setAttribute("aria-expanded","false"),n.focus();}n.addEventListener("click",G),h.addEventListener("click",J);function we(q){q.key==="Escape"&&F&&J();}i.addEventListener("keydown",we);function Ce(q){q.key==="d"&&q.shiftKey&&(q.ctrlKey||q.metaKey)&&(q.preventDefault(),F?J():G());}document.addEventListener("keydown",Ce);function pe(){a||(document.body.appendChild(n),document.body.appendChild(i));}document.body?pe():document.addEventListener("DOMContentLoaded",pe,{once:true});function Xe(){a=true,n.removeEventListener("click",G),h.removeEventListener("click",J),i.removeEventListener("keydown",we),document.removeEventListener("keydown",Ce),document.removeEventListener("DOMContentLoaded",pe);for(let q of W)clearTimeout(q);W.clear(),n.remove(),i.remove(),c.remove();}return {refs:{container:i,toggleBtn:n,titleEl:g,statusEl:_,factsBody:L.tbody,factsCount:L.countSpan,derivBody:B.tbody,derivCount:B.countSpan,derivSection:B.details,inflightList:D.list,inflightSection:D.details,inflightCount:D.countSpan,unmetList:j.list,unmetSection:j.details,unmetCount:j.countSpan,perfSection:O,perfBody:P,timeTravelSection:C,timeTravelLabel:f,undoBtn:T,redoBtn:u,flowSection:N,flowSvg:x,timelineSection:E,timelineSvg:I,eventsSection:v,eventsList:y,eventsCount:t,traceHint:p,recordBtn:R,exportBtn:z},destroy:Xe,isOpen:()=>F,flashTimers:W}}function se(e,s,o,r,a,d){let c=ge(r),n=e.get(o);if(n){let i=n.cells;if(i[1]&&(i[1].textContent=c,a&&d)){let l=i[1];l.style.background="rgba(139, 154, 255, 0.25)";let g=setTimeout(()=>{l.style.background="",d.delete(g);},300);d.add(g);}}else {n=document.createElement("tr"),n.style.borderBottom=`1px solid ${b.rowBorder}`;let i=document.createElement("td");Object.assign(i.style,{padding:"2px 4px",color:b.muted}),i.textContent=o;let l=document.createElement("td");l.style.padding="2px 4px",l.textContent=c,n.appendChild(i),n.appendChild(l),s.appendChild(n),e.set(o,n);}}function He(e,s){let o=e.get(s);o&&(o.remove(),e.delete(s));}function ue(e,s,o){if(e.inflightList.replaceChildren(),e.inflightCount.textContent=String(s.length),s.length>0)for(let r of s){let a=document.createElement("li");a.style.fontSize="11px",a.textContent=`${r.resolverId} (${r.id})`,e.inflightList.appendChild(a);}else {let r=document.createElement("li");r.style.fontSize="10px",r.style.color=b.muted,r.textContent="None",e.inflightList.appendChild(r);}if(e.unmetList.replaceChildren(),e.unmetCount.textContent=String(o.length),o.length>0)for(let r of o){let a=document.createElement("li");a.style.fontSize="11px",a.textContent=`${r.requirement.type} from ${r.fromConstraint}`,e.unmetList.appendChild(a);}else {let r=document.createElement("li");r.style.fontSize="10px",r.style.color=b.muted,r.textContent="None",e.unmetList.appendChild(r);}}function de(e,s,o){let r=s===0&&o===0;e.statusEl.style.color=r?b.green:b.yellow,e.statusEl.textContent=r?"Settled":"Working...",e.toggleBtn.textContent=r?"Directive":"Directive...",e.toggleBtn.setAttribute("aria-label",`Open Directive DevTools${r?"":" (system working)"}`);}function ve(e,s,o,r){let a=Object.keys(o.derive);if(e.derivCount.textContent=String(a.length),a.length===0){s.clear(),e.derivBody.replaceChildren();let c=document.createElement("tr"),n=document.createElement("td");n.colSpan=2,n.style.color=b.muted,n.style.fontSize="10px",n.textContent="No derivations defined",c.appendChild(n),e.derivBody.appendChild(c);return}let d=new Set(a);for(let[c,n]of s)d.has(c)||(n.remove(),s.delete(c));for(let c of a){let n;try{n=ge(o.read(c));}catch{n="<error>";}se(s,e.derivBody,c,n,true,r);}}function je(e,s,o,r){let a=e.eventsList.querySelector(".dt-events-empty");a&&a.remove();let d=document.createElement("div");Object.assign(d.style,{padding:"2px 4px",borderBottom:`1px solid ${b.rowBorder}`,fontFamily:"inherit"});let c=new Date,n=`${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}:${String(c.getSeconds()).padStart(2,"0")}.${String(c.getMilliseconds()).padStart(3,"0")}`,i;try{let k=JSON.stringify(o);i=K(k,60);}catch{i="{}";}let l=document.createElement("span");l.style.color=b.closeBtn,l.textContent=n;let g=document.createElement("span");g.style.color=b.accent,g.textContent=` ${s} `;let h=document.createElement("span");for(h.style.color=b.muted,h.textContent=i,d.appendChild(l),d.appendChild(g),d.appendChild(h),e.eventsList.prepend(d);e.eventsList.childElementCount>Ne;)e.eventsList.lastElementChild?.remove();e.eventsCount.textContent=String(r);}function Ve(e,s){e.perfBody.replaceChildren();let o=s.reconcileCount>0?(s.reconcileTotalMs/s.reconcileCount).toFixed(1):"\u2014",r=[`Reconciles: ${s.reconcileCount} (avg ${o}ms)`,`Effects: ${s.effectRunCount} run, ${s.effectErrorCount} errors`];for(let a of r){let d=document.createElement("div");d.style.marginBottom="2px",d.textContent=a,e.perfBody.appendChild(d);}if(s.resolverStats.size>0){let a=document.createElement("div");a.style.marginTop="4px",a.style.marginBottom="2px",a.style.color=b.accent,a.textContent="Resolvers:",e.perfBody.appendChild(a);let d=[...s.resolverStats.entries()].sort((c,n)=>n[1].totalMs-c[1].totalMs);for(let[c,n]of d){let i=n.count>0?(n.totalMs/n.count).toFixed(1):"0",l=document.createElement("div");l.style.paddingLeft="8px",l.textContent=`${c}: ${n.count}x, avg ${i}ms${n.errors>0?`, ${n.errors} err`:""}`,n.errors>0&&(l.style.color=b.red),e.perfBody.appendChild(l);}}}function he(e,s){let o=s.debug;if(!o){e.timeTravelSection.style.display="none";return}e.timeTravelSection.style.display="flex";let r=o.currentIndex,a=o.snapshots.length;e.timeTravelLabel.textContent=a>0?`${r+1} / ${a}`:"0 snapshots";let d=r>0,c=r<a-1;e.undoBtn.disabled=!d,e.undoBtn.style.opacity=d?"1":"0.4",e.redoBtn.disabled=!c,e.redoBtn.style.opacity=c?"1":"0.4";}function Fe(e,s){e.undoBtn.addEventListener("click",()=>{s.debug&&s.debug.currentIndex>0&&s.debug.goBack(1);}),e.redoBtn.addEventListener("click",()=>{s.debug&&s.debug.currentIndex<s.debug.snapshots.length-1&&s.debug.goForward(1);});}var Se=new WeakMap;function Qe(e,s,o,r,a,d){return [e.join(","),s.join(","),o.map(c=>`${c.id}:${c.active}`).join(","),[...r.entries()].map(([c,n])=>`${c}:${n.status}:${n.type}`).join(","),a.join(","),d.join(",")].join("|")}function Ze(e,s,o,r,a){for(let d of o){let c=e.nodes.get(`0:${d}`);if(!c)continue;let n=s.recentlyChangedFacts.has(d);c.rect.setAttribute("fill",n?b.text+"33":"none"),c.rect.setAttribute("stroke-width",n?"2":"1");}for(let d of r){let c=e.nodes.get(`1:${d}`);if(!c)continue;let n=s.recentlyComputedDerivations.has(d);c.rect.setAttribute("fill",n?b.accent+"33":"none"),c.rect.setAttribute("stroke-width",n?"2":"1");}for(let d of a){let c=e.nodes.get(`2:${d}`);if(!c)continue;let n=s.recentlyActiveConstraints.has(d),i=c.rect.getAttribute("stroke")??b.muted;c.rect.setAttribute("fill",n?i+"33":"none"),c.rect.setAttribute("stroke-width",n?"2":"1");}}function xe(e,s,o){let r=te(s);if(!r)return;let a;try{a=Object.keys(s.facts.$store.toObject());}catch{a=[];}let d=Object.keys(s.derive),c=r.constraints,n=r.unmet,i=r.inflight,l=Object.keys(r.resolvers),g=new Map;for(let m of n)g.set(m.id,{type:m.requirement.type,fromConstraint:m.fromConstraint,status:"unmet"});for(let m of i)g.set(m.id,{type:m.resolverId,fromConstraint:"",status:"inflight"});if(a.length===0&&d.length===0&&c.length===0&&l.length===0){Se.delete(e.flowSvg),e.flowSvg.replaceChildren(),e.flowSvg.setAttribute("viewBox","0 0 460 40");let m=document.createElementNS("http://www.w3.org/2000/svg","text");m.setAttribute("x","230"),m.setAttribute("y","24"),m.setAttribute("text-anchor","middle"),m.setAttribute("fill",b.muted),m.setAttribute("font-size","10"),m.setAttribute("font-family",b.font),m.textContent="No system topology",e.flowSvg.appendChild(m);return}let h=i.map(m=>m.resolverId).sort(),k=Qe(a,d,c,g,l,h),_=Se.get(e.flowSvg);if(_&&_.fingerprint===k){Ze(_,o,a,d,c.map(m=>m.id));return}let C=V.nodeW+V.colGap,T=[5,5+C,5+C*2,5+C*3,5+C*4],u=T[4]+V.nodeW+5;function f(m){let v=V.startY+12;return m.map(y=>{let t={...y,y:v};return v+=V.nodeH+V.nodeGap,t})}let A=f(a.map(m=>({id:m,label:K(m,V.labelMaxChars)}))),w=f(d.map(m=>({id:m,label:K(m,V.labelMaxChars)}))),L=f(c.map(m=>({id:m.id,label:K(m.id,V.labelMaxChars),active:m.active,priority:m.priority}))),B=f([...g.entries()].map(([m,v])=>({id:m,type:v.type,fromConstraint:v.fromConstraint,status:v.status}))),D=f(l.map(m=>({id:m,label:K(m,V.labelMaxChars)}))),j=Math.max(A.length,w.length,L.length,B.length,D.length,1),O=V.startY+12+j*(V.nodeH+V.nodeGap)+8;e.flowSvg.replaceChildren(),e.flowSvg.setAttribute("viewBox",`0 0 ${u} ${O}`),e.flowSvg.setAttribute("aria-label",`Dependency graph: ${a.length} facts, ${d.length} derivations, ${c.length} constraints, ${g.size} requirements, ${l.length} resolvers`);let H=["Facts","Derivations","Constraints","Reqs","Resolvers"];for(let[m,v]of H.entries()){let y=document.createElementNS("http://www.w3.org/2000/svg","text");y.setAttribute("x",String(T[m]??0)),y.setAttribute("y","10"),y.setAttribute("fill",b.accent),y.setAttribute("font-size",String(V.fontSize)),y.setAttribute("font-family",b.font),y.textContent=v,e.flowSvg.appendChild(y);}let P={fingerprint:k,nodes:new Map};function N(m,v,y,t,p,M,R,z){let F=document.createElementNS("http://www.w3.org/2000/svg","g"),W=document.createElementNS("http://www.w3.org/2000/svg","rect");W.setAttribute("x",String(v)),W.setAttribute("y",String(y-6)),W.setAttribute("width",String(V.nodeW)),W.setAttribute("height",String(V.nodeH)),W.setAttribute("rx","3"),W.setAttribute("fill",z?M+"33":"none"),W.setAttribute("stroke",M),W.setAttribute("stroke-width",z?"2":"1"),W.setAttribute("opacity",R?"0.35":"1"),F.appendChild(W);let G=document.createElementNS("http://www.w3.org/2000/svg","text");return G.setAttribute("x",String(v+4)),G.setAttribute("y",String(y+4)),G.setAttribute("fill",M),G.setAttribute("font-size",String(V.fontSize)),G.setAttribute("font-family",b.font),G.setAttribute("opacity",R?"0.35":"1"),G.textContent=p,F.appendChild(G),e.flowSvg.appendChild(F),P.nodes.set(`${m}:${t}`,{g:F,rect:W,text:G}),{midX:v+V.nodeW/2,midY:y}}function S(m,v,y,t,p,M){let R=document.createElementNS("http://www.w3.org/2000/svg","line");R.setAttribute("x1",String(m)),R.setAttribute("y1",String(v)),R.setAttribute("x2",String(y)),R.setAttribute("y2",String(t)),R.setAttribute("stroke",p),R.setAttribute("stroke-width","1"),R.setAttribute("stroke-dasharray","3,2"),R.setAttribute("opacity","0.7"),e.flowSvg.appendChild(R);}let x=new Map,E=new Map,$=new Map,I=new Map;for(let m of A){let v=o.recentlyChangedFacts.has(m.id),y=N(0,T[0],m.y,m.id,m.label,b.text,false,v);x.set(m.id,y);}for(let m of w){let v=o.recentlyComputedDerivations.has(m.id),y=N(1,T[1],m.y,m.id,m.label,b.accent,false,v);E.set(m.id,y);}for(let m of L){let v=o.recentlyActiveConstraints.has(m.id),y=N(2,T[2],m.y,m.id,m.label,m.active?b.yellow:b.muted,!m.active,v);$.set(m.id,y);}for(let m of B){let v=m.status==="unmet"?b.red:b.yellow,y=N(3,T[3],m.y,m.id,K(m.type,V.labelMaxChars),v,false,false);I.set(m.id,y);}for(let m of D){let v=i.some(y=>y.resolverId===m.id);N(4,T[4],m.y,m.id,m.label,v?b.green:b.muted,!v,false);}for(let m of w){let v=o.derivationDeps.get(m.id),y=E.get(m.id);if(v&&y)for(let t of v){let p=x.get(t);p&&S(p.midX+V.nodeW/2,p.midY,y.midX-V.nodeW/2,y.midY,b.accent);}}for(let m of B){let v=$.get(m.fromConstraint),y=I.get(m.id);v&&y&&S(v.midX+V.nodeW/2,v.midY,y.midX-V.nodeW/2,y.midY,b.muted);}for(let m of i){let v=I.get(m.id);if(v){let y=D.find(t=>t.id===m.resolverId);y&&S(v.midX+V.nodeW/2,v.midY,T[4],y.y,b.green);}}Se.set(e.flowSvg,P);}function qe(e){e.animationTimer&&clearTimeout(e.animationTimer),e.animationTimer=setTimeout(()=>{e.recentlyChangedFacts.clear(),e.recentlyComputedDerivations.clear(),e.recentlyActiveConstraints.clear(),e.animationTimer=null;},600);}function ze(e,s){let o=s.entries.toArray();if(o.length===0)return;e.timelineSvg.replaceChildren();let r=1/0,a=-1/0;for(let C of o)C.startMs<r&&(r=C.startMs),C.endMs>a&&(a=C.endMs);let d=performance.now();for(let C of s.inflight.values())C<r&&(r=C),d>a&&(a=d);let c=a-r||1,n=ne-oe-10,i=[],l=new Set;for(let C of o)l.has(C.resolver)||(l.add(C.resolver),i.push(C.resolver));for(let C of s.inflight.keys())l.has(C)||(l.add(C),i.push(C));let h=i.slice(-12),k=re*h.length+20;e.timelineSvg.setAttribute("viewBox",`0 0 ${ne} ${k}`),e.timelineSvg.setAttribute("height",String(Math.min(k,200)));let _=5;for(let C=0;C<=_;C++){let T=oe+n*C/_,u=c*C/_,f=document.createElementNS("http://www.w3.org/2000/svg","text");f.setAttribute("x",String(T)),f.setAttribute("y","8"),f.setAttribute("fill",b.muted),f.setAttribute("font-size","6"),f.setAttribute("font-family",b.font),f.setAttribute("text-anchor","middle"),f.textContent=u<1e3?`${u.toFixed(0)}ms`:`${(u/1e3).toFixed(1)}s`,e.timelineSvg.appendChild(f);let A=document.createElementNS("http://www.w3.org/2000/svg","line");A.setAttribute("x1",String(T)),A.setAttribute("y1","10"),A.setAttribute("x2",String(T)),A.setAttribute("y2",String(k)),A.setAttribute("stroke",b.border),A.setAttribute("stroke-width","0.5"),e.timelineSvg.appendChild(A);}for(let C=0;C<h.length;C++){let T=h[C],u=12+C*re,f=C%be.length,A=be[f],w=document.createElementNS("http://www.w3.org/2000/svg","text");w.setAttribute("x",String(oe-4)),w.setAttribute("y",String(u+re/2+3)),w.setAttribute("fill",b.muted),w.setAttribute("font-size","7"),w.setAttribute("font-family",b.font),w.setAttribute("text-anchor","end"),w.textContent=K(T,12),e.timelineSvg.appendChild(w);let L=o.filter(D=>D.resolver===T);for(let D of L){let j=oe+(D.startMs-r)/c*n,O=Math.max((D.endMs-D.startMs)/c*n,fe),H=document.createElementNS("http://www.w3.org/2000/svg","rect");H.setAttribute("x",String(j)),H.setAttribute("y",String(u+2)),H.setAttribute("width",String(O)),H.setAttribute("height",String(re-4)),H.setAttribute("rx","2"),H.setAttribute("fill",D.error?b.red:A),H.setAttribute("opacity","0.8");let P=document.createElementNS("http://www.w3.org/2000/svg","title"),N=D.endMs-D.startMs;P.textContent=`${T}: ${N.toFixed(1)}ms${D.error?" (error)":""}`,H.appendChild(P),e.timelineSvg.appendChild(H);}let B=s.inflight.get(T);if(B!==void 0){let D=oe+(B-r)/c*n,j=Math.max((d-B)/c*n,fe),O=document.createElementNS("http://www.w3.org/2000/svg","rect");O.setAttribute("x",String(D)),O.setAttribute("y",String(u+2)),O.setAttribute("width",String(j)),O.setAttribute("height",String(re-4)),O.setAttribute("rx","2"),O.setAttribute("fill",A),O.setAttribute("opacity","0.4"),O.setAttribute("stroke",A),O.setAttribute("stroke-width","1"),O.setAttribute("stroke-dasharray","3,2");let H=document.createElementNS("http://www.w3.org/2000/svg","title");H.textContent=`${T}: inflight ${(d-B).toFixed(0)}ms`,O.appendChild(H),e.timelineSvg.appendChild(O);}}e.timelineSvg.setAttribute("aria-label",`Timeline: ${o.length} resolver executions across ${h.length} resolvers`);}function et(){if(typeof window>"u")return {systems:new Map,getSystem:()=>null,getSystems:()=>[],inspect:()=>null,getEvents:()=>[],explain:()=>null,exportSession:()=>null,importSession:()=>false,clearEvents:()=>{},subscribe:()=>()=>{}};if(!window.__DIRECTIVE__){let e=new Map,s={systems:e,getSystem(o){return o?e.get(o)?.system??null:e.values().next().value?.system??null},getSystems(){return [...e.keys()]},inspect(o){let r=this.getSystem(o),a=o?e.get(o):e.values().next().value,d=r?.inspect()??null;return d&&a&&(d.resolverStats=a.resolverStats?Object.fromEntries(a.resolverStats):{}),d},getEvents(o){return o?e.get(o)?.events.toArray()??[]:e.values().next().value?.events.toArray()??[]},explain(o,r){return this.getSystem(r)?.explain(o)??null},subscribe(o,r){let a=r?e.get(r):e.values().next().value;if(!a){let d=false,n=setInterval(()=>{let l=r?e.get(r):e.values().next().value;l&&!d&&(d=true,l.subscribers.add(o));},100),i=setTimeout(()=>clearInterval(n),1e4);return ()=>{clearInterval(n),clearTimeout(i);for(let l of e.values())l.subscribers.delete(o);}}return a.subscribers.add(o),()=>{a.subscribers.delete(o);}},exportSession(o){let r=o?e.get(o):e.values().next().value;return r?JSON.stringify({version:1,name:o??e.keys().next().value??"default",exportedAt:Date.now(),events:r.events.toArray()}):null},importSession(o,r){try{if(o.length>10*1024*1024)return !1;let a=JSON.parse(o);if(!a||typeof a!="object"||Array.isArray(a)||!Array.isArray(a.events))return !1;let d=r?e.get(r):e.values().next().value;if(!d)return !1;let c=d.maxEvents,n=a.events,i=n.length>c?n.length-c:0;d.events.clear();for(let l=i;l<n.length;l++){let g=n[l];g&&typeof g=="object"&&!Array.isArray(g)&&typeof g.timestamp=="number"&&typeof g.type=="string"&&g.type!=="__proto__"&&g.type!=="constructor"&&g.type!=="prototype"&&d.events.push({timestamp:g.timestamp,type:g.type,data:g.data??null});}return !0}catch{return false}},clearEvents(o){let r=o?e.get(o):e.values().next().value;r&&r.events.clear();}};return Object.defineProperty(window,"__DIRECTIVE__",{value:s,writable:false,configurable:le(),enumerable:true}),s}return window.__DIRECTIVE__}function tt(e={}){let{name:s="default",trace:o=false,maxEvents:r,panel:a=false,position:d="bottom-right",defaultOpen:c=false}=e,n=ke(r),i=et(),l={system:null,events:new ie(n),maxEvents:n,subscribers:new Set,resolverStats:new Map};i.systems.set(s,l);let g=(t,p)=>{let M={timestamp:Date.now(),type:t,data:p};o&&l.events.push(M);for(let R of l.subscribers)try{R(M);}catch{}},h=null,k=new Map,_=new Map,C=Le(),T=Pe(),u=$e(),f=Oe(),A=a&&typeof window<"u"&&typeof document<"u"&&le(),w=null,L=0,B=1,D=2,j=4,O=8,H=16,P=32,N=64,S=128,x=new Map,E=new Set,$=null;function I(t){L|=t,w===null&&typeof requestAnimationFrame<"u"&&(w=requestAnimationFrame(m));}function m(){if(w=null,!h||!l.system){L=0;return}let t=h.refs,p=l.system,M=L;if(L=0,M&B){for(let R of E)He(k,R);E.clear();for(let[R,{value:z,flash:F}]of x)se(k,t.factsBody,R,z,F,h.flashTimers);x.clear(),t.factsCount.textContent=String(k.size);}if(M&D&&ve(t,_,p,h.flashTimers),M&O)if($)de(t,$.inflight.length,$.unmet.length);else {let R=te(p);R&&de(t,R.inflight.length,R.unmet.length);}if(M&j)if($)ue(t,$.inflight,$.unmet);else {let R=te(p);R&&ue(t,R.inflight,R.unmet);}M&H&&Ve(t,C),M&P&&xe(t,p,T),M&N&&he(t,p),M&S&&ze(t,f);}function v(t,p){h&&o&&je(h.refs,t,p,l.events.size);}function y(t,p){u.isRecording&&u.recordedEvents.length<Ie&&u.recordedEvents.push({timestamp:Date.now(),type:t,data:Re(p)});}return {name:"devtools",onInit:t=>{if(l.system=t,g("init",{}),typeof window<"u"&&console.log(`%c[Directive Devtools]%c System "${s}" initialized. Access via window.__DIRECTIVE__`,"color: #7c3aed; font-weight: bold","color: inherit"),A){let p=l.system;h=Be(s,d,c,o);let M=h.refs;try{let z=p.facts.$store.toObject();for(let[F,W]of Object.entries(z))se(k,M.factsBody,F,W,!1);M.factsCount.textContent=String(Object.keys(z).length);}catch{}ve(M,_,p);let R=te(p);R&&(de(M,R.inflight.length,R.unmet.length),ue(M,R.inflight,R.unmet)),he(M,p),Fe(M,p),xe(M,p,T),M.recordBtn.addEventListener("click",()=>{if(u.isRecording=!u.isRecording,M.recordBtn.textContent=u.isRecording?"\u23F9 Stop":"\u23FA Record",M.recordBtn.style.color=u.isRecording?b.red:b.text,u.isRecording){u.recordedEvents=[],u.snapshots=[];try{u.snapshots.push({timestamp:Date.now(),facts:p.facts.$store.toObject()});}catch{}}}),M.exportBtn.addEventListener("click",()=>{let z=u.recordedEvents.length>0?u.recordedEvents:l.events.toArray(),F=JSON.stringify({version:1,name:s,exportedAt:Date.now(),events:z,snapshots:u.snapshots},null,2),W=new Blob([F],{type:"application/json"}),G=URL.createObjectURL(W),J=document.createElement("a");J.href=G,J.download=`directive-session-${s}-${Date.now()}.json`,J.click(),URL.revokeObjectURL(G);});}},onStart:t=>{g("start",{}),v("start",{}),y("start",{});},onStop:t=>{g("stop",{}),v("stop",{}),y("stop",{});},onDestroy:t=>{g("destroy",{}),i.systems.delete(s),w!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(w),w=null),T.animationTimer&&clearTimeout(T.animationTimer),h&&(h.destroy(),h=null,k.clear(),_.clear());},onFactSet:(t,p,M)=>{g("fact.set",{key:t,value:p,prev:M}),y("fact.set",{key:t,value:p,prev:M}),T.recentlyChangedFacts.add(t),h&&l.system&&(x.set(t,{value:p,flash:true}),E.delete(t),I(B),v("fact.set",{key:t,value:p}));},onFactDelete:(t,p)=>{g("fact.delete",{key:t,prev:p}),y("fact.delete",{key:t,prev:p}),h&&(E.add(t),x.delete(t),I(B),v("fact.delete",{key:t}));},onFactsBatch:t=>{if(g("facts.batch",{changes:t}),y("facts.batch",{count:t.length}),h&&l.system){for(let p of t)p.type==="delete"?(E.add(p.key),x.delete(p.key)):(T.recentlyChangedFacts.add(p.key),x.set(p.key,{value:p.value,flash:true}),E.delete(p.key));I(B),v("facts.batch",{count:t.length});}},onDerivationCompute:(t,p,M)=>{g("derivation.compute",{id:t,value:p,deps:M}),y("derivation.compute",{id:t,deps:M}),T.derivationDeps.set(t,M),T.recentlyComputedDerivations.add(t),v("derivation.compute",{id:t,deps:M});},onDerivationInvalidate:t=>{g("derivation.invalidate",{id:t}),v("derivation.invalidate",{id:t});},onReconcileStart:t=>{g("reconcile.start",{}),C.lastReconcileStartMs=performance.now(),v("reconcile.start",{}),y("reconcile.start",{});},onReconcileEnd:t=>{if(g("reconcile.end",t),y("reconcile.end",{unmet:t.unmet.length,inflight:t.inflight.length,completed:t.completed.length}),C.lastReconcileStartMs>0){let p=performance.now()-C.lastReconcileStartMs;C.reconcileCount++,C.reconcileTotalMs+=p,C.lastReconcileStartMs=0;}if(u.isRecording&&l.system&&u.snapshots.length<_e)try{u.snapshots.push({timestamp:Date.now(),facts:l.system.facts.$store.toObject()});}catch{}h&&l.system&&($=t,qe(T),I(D|O|j|H|P|N),v("reconcile.end",{unmet:t.unmet.length,inflight:t.inflight.length}));},onConstraintEvaluate:(t,p)=>{g("constraint.evaluate",{id:t,active:p}),y("constraint.evaluate",{id:t,active:p}),p?(T.activeConstraints.add(t),T.recentlyActiveConstraints.add(t)):T.activeConstraints.delete(t),v("constraint.evaluate",{id:t,active:p});},onConstraintError:(t,p)=>{g("constraint.error",{id:t,error:String(p)}),v("constraint.error",{id:t,error:String(p)});},onRequirementCreated:t=>{g("requirement.created",{id:t.id,type:t.requirement.type}),y("requirement.created",{id:t.id,type:t.requirement.type}),v("requirement.created",{id:t.id,type:t.requirement.type});},onRequirementMet:(t,p)=>{g("requirement.met",{id:t.id,byResolver:p}),y("requirement.met",{id:t.id,byResolver:p}),v("requirement.met",{id:t.id,byResolver:p});},onRequirementCanceled:t=>{g("requirement.canceled",{id:t.id}),y("requirement.canceled",{id:t.id}),v("requirement.canceled",{id:t.id});},onResolverStart:(t,p)=>{g("resolver.start",{resolver:t,requirementId:p.id}),y("resolver.start",{resolver:t,requirementId:p.id}),f.inflight.set(t,performance.now()),h&&l.system&&(I(j|O|S),v("resolver.start",{resolver:t,requirementId:p.id}));},onResolverComplete:(t,p,M)=>{g("resolver.complete",{resolver:t,requirementId:p.id,duration:M}),y("resolver.complete",{resolver:t,requirementId:p.id,duration:M});let R=l.resolverStats.get(t)??{count:0,totalMs:0,errors:0};if(R.count++,R.totalMs+=M,l.resolverStats.set(t,R),l.resolverStats.size>ye){let F=l.resolverStats.keys().next().value;F!==void 0&&l.resolverStats.delete(F);}C.resolverStats.set(t,{...R});let z=f.inflight.get(t);f.inflight.delete(t),z!==void 0&&f.entries.push({resolver:t,startMs:z,endMs:performance.now(),error:false}),h&&l.system&&(I(j|O|H|S),v("resolver.complete",{resolver:t,duration:M}));},onResolverError:(t,p,M)=>{g("resolver.error",{resolver:t,requirementId:p.id,error:String(M)}),y("resolver.error",{resolver:t,requirementId:p.id,error:String(M)});let R=l.resolverStats.get(t)??{count:0,totalMs:0,errors:0};if(R.errors++,l.resolverStats.set(t,R),l.resolverStats.size>ye){let F=l.resolverStats.keys().next().value;F!==void 0&&l.resolverStats.delete(F);}C.resolverStats.set(t,{...R});let z=f.inflight.get(t);f.inflight.delete(t),z!==void 0&&f.entries.push({resolver:t,startMs:z,endMs:performance.now(),error:true}),h&&l.system&&(I(j|O|H|S),v("resolver.error",{resolver:t,error:String(M)}));},onResolverRetry:(t,p,M)=>{g("resolver.retry",{resolver:t,requirementId:p.id,attempt:M}),y("resolver.retry",{resolver:t,requirementId:p.id,attempt:M}),v("resolver.retry",{resolver:t,attempt:M});},onResolverCancel:(t,p)=>{g("resolver.cancel",{resolver:t,requirementId:p.id}),y("resolver.cancel",{resolver:t,requirementId:p.id}),f.inflight.delete(t),v("resolver.cancel",{resolver:t});},onEffectRun:t=>{g("effect.run",{id:t}),y("effect.run",{id:t}),C.effectRunCount++,v("effect.run",{id:t});},onEffectError:(t,p)=>{g("effect.error",{id:t,error:String(p)}),C.effectErrorCount++,v("effect.error",{id:t,error:String(p)});},onSnapshot:t=>{g("timetravel.snapshot",{id:t.id,trigger:t.trigger}),h&&l.system&&I(N),v("timetravel.snapshot",{id:t.id,trigger:t.trigger});},onTimeTravel:(t,p)=>{if(g("timetravel.jump",{from:t,to:p}),y("timetravel.jump",{from:t,to:p}),h&&l.system){let M=l.system;try{let R=M.facts.$store.toObject();k.clear(),h.refs.factsBody.replaceChildren();for(let[z,F]of Object.entries(R))se(k,h.refs.factsBody,z,F,!1);h.refs.factsCount.textContent=String(Object.keys(R).length);}catch{}_.clear(),T.derivationDeps.clear(),h.refs.derivBody.replaceChildren(),$=null,I(D|O|j|P|N),v("timetravel.jump",{from:t,to:p});}},onError:t=>{g("error",{source:t.source,sourceId:t.sourceId,message:t.message}),y("error",{source:t.source,message:t.message}),v("error",{source:t.source,message:t.message});},onErrorRecovery:(t,p)=>{g("error.recovery",{source:t.source,sourceId:t.sourceId,strategy:p}),v("error.recovery",{source:t.source,strategy:p});},onRunComplete:t=>{g("run.complete",{id:t.id,status:t.status,facts:t.factChanges.length,constraints:t.constraintsHit.length,requirements:t.requirementsAdded.length,resolvers:t.resolversStarted.length,effects:t.effectsRun.length}),v("run.complete",{id:t.id});}}}var Ue="directive-devtools-event",We=new Set(["__proto__","constructor","prototype"]),nt=Math.random().toString(36).slice(2,8);function rt(){if(typeof window<"u"){let e=`__DIRECTIVE_BRIDGE_ID_${nt}__`,s=window,o=s[e]??0;return s[e]=o+1,o+1}return 1}function ot(e){let s=false;for(let r of We)if(r in e){s=true;break}if(!s)return e;let o=Object.create(null);for(let[r,a]of Object.entries(e))We.has(r)||(o[r]=a);return o}function it(e){if(!(typeof window>"u"))try{let s=ot(e),o={id:rt(),timestamp:Date.now(),snapshotId:null,...s};window.dispatchEvent(new CustomEvent(Ue,{detail:o}));}catch{}}function Ge(e,s=50){let o=new Set(["__proto__","constructor","prototype"]),r=new WeakSet;function a(d,c){if(c>s)return false;if(d==null||typeof d!="object")return true;let n=d;if(r.has(n))return true;if(r.add(n),Array.isArray(n)){for(let i of n)if(!a(i,c+1))return r.delete(n),false;return r.delete(n),true}for(let i of Object.keys(n))if(o.has(i)||!a(n[i],c+1))return r.delete(n),false;return r.delete(n),true}return a(e,0)}function st(e){let{storage:s,key:o,include:r,exclude:a=[],debounce:d=100,onRestore:c,onSave:n,onError:i}=e,l=null,g=null,h=new Set,k=u=>a.includes(u)?false:r?r.includes(u):true,_=()=>{try{let u=s.getItem(o);if(!u)return null;let f=JSON.parse(u);return typeof f!="object"||f===null?null:Ge(f)?f:(i?.(new Error("Potential prototype pollution detected in stored data")),null)}catch(u){return i?.(u instanceof Error?u:new Error(String(u))),null}},C=()=>{if(g)try{let u={};for(let f of h)k(f)&&(u[f]=g.facts[f]);s.setItem(o,JSON.stringify(u)),n?.(u);}catch(u){i?.(u instanceof Error?u:new Error(String(u)));}},T=()=>{l&&clearTimeout(l),l=setTimeout(C,d);};return {name:"persistence",onInit:u=>{g=u;let f=_();f&&(g.facts.$store.batch(()=>{for(let[A,w]of Object.entries(f))k(A)&&(g.facts[A]=w,h.add(A));}),c?.(f));},onDestroy:()=>{l&&clearTimeout(l),C();},onFactSet:u=>{h.add(u),k(u)&&T();},onFactDelete:u=>{h.delete(u),k(u)&&T();},onFactsBatch:u=>{let f=false;for(let A of u)A.type==="set"?h.add(A.key):h.delete(A.key),k(A.key)&&(f=true);f&&T();}}}function at(e={}){let{onSlowConstraint:s,onSlowResolver:o,slowConstraintThresholdMs:r=16,slowResolverThresholdMs:a=1e3}=e,d=new Map,c=new Map,n=new Map,i={runs:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0},l=0,g=0,h=0;function k(u){let f=d.get(u);return f||(f={evaluations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastEvaluatedAt:0},d.set(u,f)),f}function _(u){let f=c.get(u);return f||(f={starts:0,completions:0,errors:0,retries:0,cancellations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastCompletedAt:0},c.set(u,f)),f}function C(u){let f=n.get(u);return f||(f={runs:0,errors:0,lastRunAt:0},n.set(u,f)),f}return {name:"performance",onStart(){l=Date.now();},onConstraintEvaluate(u,f){let A=performance.now(),w=k(u);if(w.evaluations++,w.lastEvaluatedAt=Date.now(),h>0){let L=A-h;w.totalDurationMs+=L;let B=w.evaluations;w.avgDurationMs=w.totalDurationMs/B,L>w.maxDurationMs&&(w.maxDurationMs=L),L>r&&s?.(u,L);}h=A;},onResolverStart(u,f){let A=_(u);A.starts++;},onResolverComplete(u,f,A){let w=_(u);w.completions++,w.totalDurationMs+=A,w.avgDurationMs=w.totalDurationMs/w.completions,A>w.maxDurationMs&&(w.maxDurationMs=A),w.lastCompletedAt=Date.now(),A>a&&o?.(u,A);},onResolverError(u,f,A){_(u).errors++;},onResolverRetry(u,f,A){_(u).retries++;},onResolverCancel(u,f){_(u).cancellations++;},onEffectRun(u){let f=C(u);f.runs++,f.lastRunAt=Date.now();},onEffectError(u,f){C(u).errors++;},onReconcileStart(){g=performance.now(),h=0;},onReconcileEnd(){let u=performance.now()-g;i.runs++,i.totalDurationMs+=u,i.avgDurationMs=i.totalDurationMs/i.runs,u>i.maxDurationMs&&(i.maxDurationMs=u);},getSnapshot(){let u={};for(let[w,L]of d)u[w]={...L};let f={};for(let[w,L]of c)f[w]={...L};let A={};for(let[w,L]of n)A[w]={...L};return {constraints:u,resolvers:f,effects:A,reconcile:{...i},uptime:l?Date.now()-l:0}},reset(){d.clear(),c.clear(),n.clear(),i.runs=0,i.totalDurationMs=0,i.avgDurationMs=0,i.maxDurationMs=0,h=0;}}}function me(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function Ee(e,s){if(e.length===0)return 0;let o=[...e].sort((a,d)=>a-d),r=Math.ceil(s/100*o.length)-1;return o[Math.max(0,r)]??0}function ct(e={}){let{serviceName:s="directive-agents",metrics:o={},tracing:r={},alerts:a=[],summaryMetrics:d={},events:c={}}=e,n={requests:d.requests??"agent.requests",errors:d.errors??"agent.errors",latency:d.latency??"agent.latency",tokens:d.tokens??"agent.tokens",cost:d.cost??"agent.cost"},{enabled:i=true,exportInterval:l,exporter:g,maxDataPoints:h=1e3}=o,{enabled:k=true,sampleRate:_=1,maxSpans:C=1e3,exporter:T}=r,u=Date.now(),f=new Map,A=new Map,w=[],L=[],B=new Map,D=new Map,j;l&&(g||T)&&(j=setInterval(async()=>{try{if(g&&i&&await g(Array.from(D.values())),T&&k){let S=w.splice(0,100);S.length>0&&await T(S);}}catch(S){console.error("[Directive Observability] Export error:",S);}},l));function O(S){if(!i)return;let x=`${S.name}:${JSON.stringify(Object.fromEntries(Object.entries(S.labels).sort()))}`,E=f.get(x);E||(E=[],f.set(x,E)),E.push(S),E.length>h&&E.shift(),H(S.name,E),c.onMetricRecorded?.(S),P(S.name);}function H(S,x){if(x.length===0)return;let E=x.map(y=>y.value),$=E.reduce((y,t)=>y+t,0),I=x[0],m=E[E.length-1],v={name:S,type:I.type,count:x.length,sum:$,min:Math.min(...E),max:Math.max(...E),avg:$/x.length,lastValue:m,lastUpdated:Date.now()};D.set(S,v);}function P(S){for(let x of a){if(x.metric!==S)continue;let E=D.get(S);if(!E)continue;let $=`${x.metric}:${x.threshold}`,I=B.get($),m=x.cooldownMs??6e4;if(I&&Date.now()-I<m)continue;let v=x.operator??">",y=E.lastValue,t=x.threshold,p=false;switch(v){case ">":p=y>t;break;case "<":p=y<t;break;case ">=":p=y>=t;break;case "<=":p=y<=t;break;case "==":p=y===t;break}if(p){let M={alertId:me(),metric:S,currentValue:y,threshold:t,operator:v,action:x.action,timestamp:Date.now(),message:`Alert: ${S} ${v} ${t} (current: ${y})`};switch(L.push(M),L.length>1e3&&L.splice(0,L.length-1e3),B.set($,Date.now()),c.onAlert?.(M),x.action){case "log":console.log(`[Observability] ${M.message}`);break;case "warn":console.warn(`[Observability] ${M.message}`);break;case "alert":console.error(`[Observability ALERT] ${M.message}`);break;case "callback":x.callback?.(E,t);break}}}}function N(S){let x=[];for(let[E,$]of f)if(E.startsWith(`${S}:`))for(let I of $)x.push(I.value);return x.length===0?{}:{p50:Ee(x,50),p90:Ee(x,90),p99:Ee(x,99)}}return {incrementCounter(S,x={},E=1){O({name:S,type:"counter",value:E,labels:x,timestamp:Date.now()});},setGauge(S,x,E={}){O({name:S,type:"gauge",value:x,labels:E,timestamp:Date.now()});},observeHistogram(S,x,E={}){O({name:S,type:"histogram",value:x,labels:E,timestamp:Date.now()});},startSpan(S,x){if(Math.random()>_)return {traceId:"sampled-out",spanId:"sampled-out",operationName:S,serviceName:s,startTime:Date.now(),status:"ok",tags:{},logs:[]};let E={traceId:x?A.get(x)?.traceId??me():me(),spanId:me(),parentSpanId:x,operationName:S,serviceName:s,startTime:Date.now(),status:"ok",tags:{},logs:[]};return k&&(A.set(E.spanId,E),c.onSpanStart?.(E)),E},endSpan(S,x="ok"){if(S==="sampled-out")return;let E=A.get(S);if(E){for(E.endTime=Date.now(),E.duration=E.endTime-E.startTime,E.status=x,A.delete(S),w.push(E);w.length>C;)w.shift();O({name:`${E.operationName}.latency`,type:"histogram",value:E.duration,labels:{},timestamp:Date.now()}),x==="error"&&O({name:`${E.operationName}.errors`,type:"counter",value:1,labels:{},timestamp:Date.now()}),c.onSpanEnd?.(E);}},addSpanLog(S,x,E="info"){if(S==="sampled-out")return;let $=A.get(S);$&&$.logs.push({timestamp:Date.now(),message:x,level:E});},addSpanTag(S,x,E){if(S==="sampled-out")return;let $=A.get(S);$&&($.tags[x]=E);},getDashboard(){let S=D.get(n.requests),x=D.get(n.errors),E=D.get(n.latency),$=D.get(n.tokens),I=D.get(n.cost),m=S?.sum??0,v=x?.sum??0,y=m>0?v/m:0,t=E?N(n.latency):{};return {service:{name:s,uptime:Date.now()-u,startTime:u},metrics:Object.fromEntries(D),traces:[...w].slice(-100),alerts:[...L].slice(-50),summary:{totalRequests:m,totalErrors:v,errorRate:y,avgLatency:E?.avg??0,p99Latency:t.p99??0,activeSpans:A.size,totalTokens:$?.sum??0,totalCost:I?.sum??0}}},getMetric(S){let x=D.get(S);if(!x)return;let E=N(S);return {...x,...E}},getTraces(S=100){return [...w].slice(-S)},getAlerts(){return [...L]},export(){return {metrics:Array.from(D.values()),traces:[...w],alerts:[...L]}},clear(){f.clear(),D.clear(),A.clear(),w.length=0,L.length=0,B.clear();},async dispose(){j&&(clearInterval(j),j=void 0);try{g&&i&&D.size>0&&await g(Array.from(D.values())),T&&k&&w.length>0&&await T([...w]);}catch(S){console.error("[Directive Observability] Error flushing data during dispose:",S);}f.clear(),D.clear(),A.clear(),w.length=0,L.length=0,B.clear();},getHealthStatus(){let S=D.get(n.requests),x=D.get(n.errors),E=S?.sum??0,$=x?.sum??0,I=E>0?$/E:0,m=L.filter(v=>Date.now()-v.timestamp<3e5).length;return {healthy:I<.1&&m===0,uptime:Date.now()-u,errorRate:I,activeAlerts:m}}}}function lt(e){return {trackRun(s,o){let r={agent:s};e.incrementCounter("agent.requests",r),o.success||e.incrementCounter("agent.errors",r),e.observeHistogram("agent.latency",o.latencyMs,r),o.inputTokens!==void 0&&(e.incrementCounter("agent.tokens.input",r,o.inputTokens),e.incrementCounter("agent.tokens",r,o.inputTokens)),o.outputTokens!==void 0&&(e.incrementCounter("agent.tokens.output",r,o.outputTokens),e.incrementCounter("agent.tokens",r,o.outputTokens)),o.cost!==void 0&&e.incrementCounter("agent.cost",r,o.cost),o.toolCalls!==void 0&&e.incrementCounter("agent.tool_calls",r,o.toolCalls);},trackGuardrail(s,o){let r={guardrail:s};e.incrementCounter("guardrail.checks",r),o.passed||e.incrementCounter("guardrail.failures",r),o.blocked&&e.incrementCounter("guardrail.blocks",r),e.observeHistogram("guardrail.latency",o.latencyMs,r);},trackApproval(s,o){let r={tool:s};e.incrementCounter("approval.requests",r),o.approved?e.incrementCounter("approval.approved",r):e.incrementCounter("approval.rejected",r),o.timedOut&&e.incrementCounter("approval.timeouts",r),e.observeHistogram("approval.wait_time",o.waitTimeMs,r);},trackHandoff(s,o,r){e.incrementCounter("handoff.count",{from:s,to:o}),e.observeHistogram("handoff.latency",r);}}}function ut(e){let s=[{key:"service.name",value:{stringValue:e.serviceName??"directive-agents"}}];if(e.serviceVersion&&s.push({key:"service.version",value:{stringValue:e.serviceVersion}}),e.resourceAttributes)for(let[o,r]of Object.entries(e.resourceAttributes))s.push({key:o,value:{stringValue:r}});return {attributes:s}}function Z(e){return `${BigInt(e)*BigInt(1e6)}`}function dt(e){switch(e){case "counter":return "sum";case "gauge":return "gauge";case "histogram":return "histogram";default:return "gauge"}}function mt(e,s,o){let r=e.map(a=>{let d=a.lastUpdated-6e4,c=[{asInt:a.type==="counter"?a.sum:void 0,asDouble:a.type!=="counter"?a.lastValue:void 0,timeUnixNano:Z(a.lastUpdated),startTimeUnixNano:Z(d),attributes:[]}],n=dt(a.type),i={name:a.name,unit:""};return n==="sum"?i.sum={dataPoints:c,aggregationTemporality:2,isMonotonic:true}:n==="histogram"?i.histogram={dataPoints:[{count:a.count,sum:a.sum,min:a.min,max:a.max,timeUnixNano:Z(a.lastUpdated),startTimeUnixNano:Z(d),attributes:[]}],aggregationTemporality:2}:i.gauge={dataPoints:c},i});return {resourceMetrics:[{resource:s,scopeMetrics:[{scope:{name:"directive",version:o},metrics:r}]}]}}function pt(e,s,o){let r=e.map(a=>{let d=a.logs.map(i=>({timeUnixNano:Z(i.timestamp),name:i.level,attributes:[{key:"message",value:{stringValue:i.message}},{key:"level",value:{stringValue:i.level}}]})),c=Object.entries(a.tags).map(([i,l])=>({key:i,value:typeof l=="string"?{stringValue:l}:typeof l=="number"?{intValue:`${l}`}:{boolValue:l}})),n=a.status==="ok"?1:a.status==="error"?2:0;return {traceId:a.traceId.replace(/-/g,"").padEnd(32,"0").slice(0,32),spanId:a.spanId.replace(/-/g,"").padEnd(16,"0").slice(0,16),parentSpanId:a.parentSpanId?a.parentSpanId.replace(/-/g,"").padEnd(16,"0").slice(0,16):void 0,name:a.operationName,kind:1,startTimeUnixNano:Z(a.startTime),endTimeUnixNano:a.endTime?Z(a.endTime):Z(a.startTime),attributes:c,events:d,status:{code:n}}});return {resourceSpans:[{resource:s,scopeSpans:[{scope:{name:"directive",version:o},spans:r}]}]}}function gt(e){let{endpoint:s,headers:o={},scopeVersion:r="0.1.0",timeoutMs:a=1e4,fetch:d=globalThis.fetch,onError:c}=e;try{let l=new URL(s);if(l.protocol!=="http:"&&l.protocol!=="https:")throw new Error("Only http: and https: protocols are supported")}catch(l){throw new Error(`[Directive OTLP] Invalid endpoint URL "${s}": ${l instanceof Error?l.message:String(l)}`)}if(/\/v1\/(metrics|traces)/.test(s)&&console.warn(`[Directive OTLP] Endpoint "${s}" already contains a /v1/metrics or /v1/traces path. The exporter will append /v1/metrics or /v1/traces automatically. Use the base URL (e.g., "http://localhost:4318") instead.`),a<=0||!Number.isFinite(a))throw new Error(`[Directive OTLP] timeoutMs must be > 0, got ${a}`);let n=ut(e);async function i(l,g,h){let k=`${s.replace(/\/$/,"")}${l}`,_=new AbortController,C=setTimeout(()=>_.abort(),a);try{let T=await d(k,{method:"POST",headers:{"Content-Type":"application/json",...o},body:JSON.stringify(g),signal:_.signal});if(!T.ok)throw new Error(`OTLP export failed: ${T.status} ${T.statusText}`)}catch(T){let u=T instanceof Error?T:new Error(String(T));c?c(u,h):console.error(`[Directive OTLP] Export ${h} error:`,u.message);}finally{clearTimeout(C);}}return {async exportMetrics(l){if(l.length===0)return;let g=mt(l,n,r);await i("/v1/metrics",g,"metrics");},async exportTraces(l){if(l.length===0)return;let g=pt(l,n,r);await i("/v1/traces",g,"traces");}}}var ae=class extends Error{code="CIRCUIT_OPEN";retryAfterMs;state;constructor(s,o,r="OPEN",a){let d=a?`[Directive CircuitBreaker] Circuit "${s}" is ${r}. ${a}`:`[Directive CircuitBreaker] Circuit "${s}" is ${r}. Request rejected. Try again in ${Math.ceil(o/1e3)}s.`;super(d),this.name="CircuitBreakerOpenError",this.retryAfterMs=o,this.state=r;}};function ft(e={}){let{failureThreshold:s=5,recoveryTimeMs:o=3e4,halfOpenMaxRequests:r=3,failureWindowMs:a=6e4,observability:d,metricPrefix:c="circuit_breaker",name:n="default",isFailure:i=()=>true,onStateChange:l}=e;if(s<1||!Number.isFinite(s))throw new Error(`[Directive CircuitBreaker] failureThreshold must be >= 1, got ${s}`);if(o<=0||!Number.isFinite(o))throw new Error(`[Directive CircuitBreaker] recoveryTimeMs must be > 0, got ${o}`);if(r<1||!Number.isFinite(r))throw new Error(`[Directive CircuitBreaker] halfOpenMaxRequests must be >= 1, got ${r}`);if(a<=0||!Number.isFinite(a))throw new Error(`[Directive CircuitBreaker] failureWindowMs must be > 0, got ${a}`);let g="CLOSED",h=[],k=0,_=0,C=Date.now(),T=0,u=0,f=0,A=0,w=0,L=null,B=null;function D(P){if(g===P)return;let N=g;g=P,C=Date.now(),P==="OPEN"&&(T=Date.now()),P==="HALF_OPEN"&&(k=0,_=0),l?.(N,P),d&&d.incrementCounter(`${c}.state_change`,{name:n,from:N,to:P});}function j(){let P=Date.now()-a;return h=h.filter(N=>N>P),h.length}function O(){A++,B=Date.now(),d&&d.incrementCounter(`${c}.success`,{name:n}),g==="HALF_OPEN"&&(_++,_>=r&&(D("CLOSED"),h=[]));}function H(P){if(!i(P)){O();return}f++,L=Date.now(),h.push(Date.now());let N=s*2;if(h.length>N&&(h=h.slice(-N)),d&&d.incrementCounter(`${c}.failure`,{name:n}),g==="HALF_OPEN"){D("OPEN");return}g==="CLOSED"&&j()>=s&&D("OPEN");}return {async execute(P){if(u++,d&&d.incrementCounter(`${c}.requests`,{name:n}),g==="OPEN")if(Date.now()-T>=o)D("HALF_OPEN");else throw w++,d&&d.incrementCounter(`${c}.rejected`,{name:n}),new ae(n,o-(Date.now()-T));if(g==="HALF_OPEN"){if(k>=r)throw w++,new ae(n,o,"HALF_OPEN",`Max trial requests (${r}) reached.`);k++;}let N=Date.now();try{let S=await P();return O(),d&&d.observeHistogram(`${c}.latency`,Date.now()-N,{name:n}),S}catch(S){let x=S instanceof Error?S:new Error(String(S));throw H(x),d&&d.observeHistogram(`${c}.latency`,Date.now()-N,{name:n}),S}},getState(){return g==="OPEN"&&Date.now()-T>=o&&D("HALF_OPEN"),g},getStats(){return {state:this.getState(),totalRequests:u,totalFailures:f,totalSuccesses:A,totalRejected:w,recentFailures:j(),lastFailureTime:L,lastSuccessTime:B,lastStateChange:C}},forceState(P){D(P);},reset(){let P=g;g="CLOSED",h=[],k=0,_=0,C=Date.now(),T=0,u=0,f=0,A=0,w=0,L=null,B=null,P!=="CLOSED"&&l?.(P,"CLOSED");},isAllowed(){return g==="CLOSED"?true:g==="OPEN"?Date.now()-T>=o:k<r}}}
|
|
2
|
+
exports.CircuitBreakerOpenError=ae;exports.DEVTOOLS_EVENT_NAME=Ue;exports.createAgentMetrics=lt;exports.createCircuitBreaker=ft;exports.createOTLPExporter=gt;exports.createObservability=ct;exports.devtoolsPlugin=tt;exports.emitDevToolsEvent=it;exports.loggingPlugin=Ke;exports.performancePlugin=at;exports.persistencePlugin=st;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|