@doeixd/machine 0.0.8 → 0.0.9

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.
@@ -1,5 +1,5 @@
1
- "use strict";var I=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var ot=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},it=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of nt(t))!rt.call(e,o)&&o!==n&&I(e,o,{get:()=>t[o],enumerable:!(r=tt(t,o))||r.enumerable});return e};var at=e=>it(I({},"__esModule",{value:!0}),e);var vt={};ot(vt,{BoundMachine:()=>W,META_KEY:()=>xe,MachineBase:()=>T,MultiMachineBase:()=>J,RUNTIME_META:()=>P,action:()=>me,bindTransitions:()=>ae,branch:()=>Ge,call:()=>Qe,chain:()=>De,combine:()=>Le,combineFactories:()=>Tt,compose:()=>Be,composeTyped:()=>j,createAsyncMachine:()=>Ct,createCustomMiddleware:()=>$e,createEnsemble:()=>dt,createEvent:()=>Je,createFetchMachine:()=>ht,createFlow:()=>ue,createMachine:()=>E,createMachineBuilder:()=>Et,createMachineFactory:()=>mt,createMiddleware:()=>w,createMiddlewareRegistry:()=>We,createMultiMachine:()=>Mt,createMutableMachine:()=>ft,createParallelMachine:()=>ee,createPipeline:()=>_e,createRunner:()=>Pe,delegateToChild:()=>xt,describe:()=>he,extendTransitions:()=>bt,extractFromInstance:()=>Fe,extractFunctionMetadata:()=>U,extractMachine:()=>D,extractMachines:()=>Ee,extractStateNode:()=>K,generateChart:()=>V,generateStatechart:()=>Se,guard:()=>z,guarded:()=>ge,hasState:()=>Ft,inDevelopment:()=>He,invoke:()=>Ce,isConditionalMiddleware:()=>Ve,isMiddlewareFn:()=>ie,isState:()=>Ue,logState:()=>Xe,matchMachine:()=>St,mergeContext:()=>qe,metadata:()=>be,next:()=>Rt,overrideTransitions:()=>wt,pipeTransitions:()=>Ye,run:()=>L,runAsync:()=>Me,runMachine:()=>Pt,runSequence:()=>de,runWithDebug:()=>ye,runWithEnsemble:()=>yt,runWithRunner:()=>ut,setContext:()=>v,step:()=>ce,stepAsync:()=>fe,toggle:()=>pt,transitionTo:()=>pe,when:()=>_,whenContext:()=>Ie,whenGuard:()=>we,withAnalytics:()=>Ae,withDebugging:()=>Ke,withErrorReporting:()=>ke,withHistory:()=>ne,withLogging:()=>ve,withPerformanceMonitoring:()=>Ne,withPermissions:()=>je,withRetry:()=>ze,withSnapshot:()=>re,withTimeTravel:()=>oe,withValidation:()=>Oe,yieldMachine:()=>le});module.exports=at(vt);function L(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=n.next(r);if(i)return o;r=o}}function ce(e){return function*(){return yield e}()}function le(e){return e}function de(e,t){return t.reduce((n,r)=>L(r,n),e)}function ue(e){return e}function ye(e,t,n=(r,o)=>{console.log(`Step ${r}:`,o.context)}){let r=e(t),o=t,i=0;for(n(i,o);;){let{value:a,done:s}=r.next(o);if(s)return console.log("Final:",a),a;o=a,i++,n(i,o)}}async function Me(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=await n.next(r);if(i)return o;r=o}}async function*fe(e){return yield e}var xe=Symbol("MachineMeta"),P=Symbol("__machine_runtime_meta__");function R(e,t){let n=e[P]||{},r={...n,...t};t.guards&&n.guards?r.guards=[...t.guards,...n.guards]:t.guards&&(r.guards=[...t.guards]),t.actions&&n.actions?r.actions=[...t.actions,...n.actions]:t.actions&&(r.actions=[...t.actions]),Object.defineProperty(e,P,{value:r,enumerable:!1,writable:!1,configurable:!0})}function pe(e,t){return R(t,{target:e.name||e.toString()}),t}function he(e,t){return R(t,{description:e}),t}function ge(e,t){return R(t,{guards:[e]}),t}function Ce(e,t){return R(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function me(e,t){return R(t,{actions:[e]}),t}function z(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=async function(...c){let d=typeof this=="object"&&"context"in this,u=d?this.context:this;if(await Promise.resolve(e(u,...c))){let y=d?this.context:this;return t.apply(y,c)}else if(r==="throw"){let y=o||"Guard condition failed";throw new Error(y)}else if(r==="ignore"){if(d)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(d)return r.apply(this,c);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),R(s,{description:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}function we(e){return{do(t){let n=z(e,t);return n.else=function(r){return z(e,t,{onFail:r})},n}}}function be(e,t){return t}var g=require("ts-morph");function Te(e){return g.Node.isIdentifier(e)?e.getText():g.Node.isTypeOfExpression(e)?e.getExpression().getText():"unknown"}function $(e){if(!g.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(g.Node.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();o&&(g.Node.isStringLiteral(o)||g.Node.isNumericLiteral(o)?t[r]=o.getLiteralValue():o.getText()==="true"||o.getText()==="false"?t[r]=o.getText()==="true":g.Node.isIdentifier(o)?t[r]=o.getText():g.Node.isObjectLiteralExpression(o)?t[r]=$(o):g.Node.isArrayLiteralExpression(o)&&(t[r]=o.getElements().map(i=>g.Node.isObjectLiteralExpression(i)?$(i):i.getText())))}return t}function st(e){if(!g.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(g.Node.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();if(!o)continue;r==="onDone"||r==="onError"?t[r]=Te(o):g.Node.isStringLiteral(o)?t[r]=o.getLiteralValue():g.Node.isIdentifier(o)&&(t[r]=o.getText())}return t}function B(e,t=!1){if(!g.Node.isCallExpression(e))return null;let n=e.getExpression(),r=g.Node.isIdentifier(n)?n.getText():null;if(!r)return null;let o={},i=e.getArguments();switch(r){case"transitionTo":i[0]&&(o.target=Te(i[0]));break;case"describe":if(i[0]&&g.Node.isStringLiteral(i[0])&&(o.description=i[0].getLiteralValue()),i[1]&&g.Node.isCallExpression(i[1])){let a=B(i[1],t);a&&Object.assign(o,a)}break;case"guarded":if(i[0]){let a=$(i[0]);Object.keys(a).length>0&&(o.guards=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=B(i[1],t);a&&Object.assign(o,a)}break;case"invoke":if(i[0]){let a=st(i[0]);Object.keys(a).length>0&&(o.invoke=a)}break;case"action":if(i[0]){let a=$(i[0]);Object.keys(a).length>0&&(o.actions=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=B(i[1],t);a&&Object.assign(o,a)}break;default:return null}return Object.keys(o).length>0?o:null}function ct(e,t=!1){if(!g.Node.isPropertyDeclaration(e))return t&&console.error(" ⚠️ Not a property declaration"),null;let n=e.getInitializer();if(!n)return t&&console.error(" ⚠️ No initializer"),null;if(!g.Node.isCallExpression(n))return t&&console.error(" ⚠️ Initializer is not a call expression"),null;let r=B(n,t);return r&&t&&console.error(" ✅ Extracted metadata:",JSON.stringify(r,null,2)),r}function G(e,t=!1){let n={on:{}},r=e.getDeclarations()[0];if(!r||!g.Node.isClassDeclaration(r))return t&&console.error(`⚠️ Warning: Could not get class declaration for ${e.getName()}`),n;let o=e.getName();t&&console.error(` Analyzing state: ${o}`);for(let i of r.getInstanceMembers()){let a=i.getName();t&&console.error(` Checking member: ${a}`);let s=ct(i,t);if(!s)continue;t&&console.error(` Found transition: ${a}`);let{invoke:c,actions:d,guards:u,...x}=s;if(c&&(n.invoke||(n.invoke=[]),n.invoke.push({src:c.src,onDone:{target:c.onDone},onError:{target:c.onError},description:c.description}),t&&console.error(` → Invoke: ${c.src}`)),x.target){let y={target:x.target};x.description&&(y.description=x.description),u&&(y.cond=u.map(f=>f.name).join(" && "),t&&console.error(` → Guard: ${y.cond}`)),d&&d.length>0&&(y.actions=d.map(f=>f.name),t&&console.error(` → Actions: ${y.actions.join(", ")}`)),n.on[a]=y,t&&console.error(` → Target: ${x.target}`)}}return n}function lt(e,t,n,r,o=!1){let i=G(t,o);if(r){o&&console.error(` 👪 Analyzing children for state: ${e}`),i.initial=r.initialState,i.states={};for(let a of r.classes){let s=n.getClass(a);if(s){let c=s.getSymbolOrThrow();i.states[a]=G(c,o)}else console.warn(`⚠️ Warning: Child class '${a}' not found.`)}}return i}function D(e,t,n=!1){n&&(console.error(`
2
- 🔍 Analyzing machine: ${e.id}`),console.error(` Source: ${e.input}`));let r=t.getSourceFile(e.input);if(!r)throw new Error(`Source file not found: ${e.input}`);if(e.parallel){n&&console.error(" ⏹️ Parallel machine detected. Analyzing regions.");let i={id:e.id,type:"parallel",states:{}};e.description&&(i.description=e.description);for(let a of e.parallel.regions){n&&console.error(` 📍 Analyzing region: ${a.name}`);let s={};for(let c of a.classes){let d=r.getClass(c);if(d){let u=d.getSymbolOrThrow();s[c]=G(u,n)}else console.warn(`⚠️ Warning: Class '${c}' not found for region '${a.name}'.`)}i.states[a.name]={initial:a.initialState,states:s}}return n&&console.error(` ✅ Extracted ${e.parallel.regions.length} parallel regions`),i}if(!e.initialState||!e.classes)throw new Error(`Machine config for '${e.id}' must have either 'parallel' or 'initialState'/'classes'.`);let o={id:e.id,initial:e.initialState,states:{}};e.description&&(o.description=e.description);for(let i of e.classes){let a=r.getClass(i);if(!a){console.warn(`⚠️ Warning: Class '${i}' not found in '${e.input}'. Skipping.`);continue}let s=a.getSymbolOrThrow(),c=i===e.initialState&&e.children,d=lt(i,s,r,c?e.children:void 0,n);o.states[i]=d}return n&&console.error(` ✅ Extracted ${e.classes.length} states`),o}function Ee(e){var o;let t=(o=e.verbose)!=null?o:!1;t&&(console.error(`
1
+ "use strict";var I=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},st=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ot(t))!it.call(e,o)&&o!==n&&I(e,o,{get:()=>t[o],enumerable:!(r=rt(t,o))||r.enumerable});return e};var ct=e=>st(I({},"__esModule",{value:!0}),e);var jt={};at(jt,{ADVANCED_CONFIG_EXAMPLES:()=>yt,BoundMachine:()=>G,META_KEY:()=>he,MachineBase:()=>T,MultiMachineBase:()=>q,RUNTIME_META:()=>R,action:()=>we,bindTransitions:()=>se,branch:()=>Ue,call:()=>et,chain:()=>Ke,combine:()=>Ve,combineFactories:()=>Ft,compose:()=>_e,composeTyped:()=>N,createAsyncMachine:()=>bt,createCustomMiddleware:()=>De,createEnsemble:()=>ft,createEvent:()=>Ye,createFetchMachine:()=>mt,createFlow:()=>ye,createMachine:()=>E,createMachineBuilder:()=>Pt,createMachineFactory:()=>Tt,createMiddleware:()=>w,createMiddlewareRegistry:()=>He,createMultiMachine:()=>ht,createMutableMachine:()=>pt,createParallelMachine:()=>te,createPipeline:()=>Ge,createRunner:()=>ve,delegateToChild:()=>gt,describe:()=>ge,extendTransitions:()=>St,extractFromInstance:()=>Re,extractFunctionMetadata:()=>J,extractMachine:()=>D,extractMachines:()=>Fe,extractStateNode:()=>K,generateChart:()=>U,generateStatechart:()=>Pe,guard:()=>$,guardAsync:()=>_,guarded:()=>Ce,hasState:()=>vt,inDevelopment:()=>Ie,invoke:()=>me,isConditionalMiddleware:()=>Je,isMiddlewareFn:()=>ae,isState:()=>qe,logState:()=>Ze,matchMachine:()=>Rt,mergeContext:()=>Xe,metadata:()=>Ee,next:()=>Ot,overrideTransitions:()=>Et,pipeTransitions:()=>Qe,run:()=>L,runAsync:()=>Me,runMachine:()=>At,runSequence:()=>ue,runWithDebug:()=>fe,runWithEnsemble:()=>xt,runWithRunner:()=>Mt,setContext:()=>O,step:()=>le,stepAsync:()=>xe,toggle:()=>Ct,transitionTo:()=>pe,when:()=>W,whenContext:()=>Le,whenGuard:()=>be,whenGuardAsync:()=>Te,withAnalytics:()=>je,withDebugging:()=>We,withErrorReporting:()=>ze,withHistory:()=>re,withLogging:()=>Oe,withPerformanceMonitoring:()=>Be,withPermissions:()=>Ne,withRetry:()=>$e,withSnapshot:()=>oe,withTimeTravel:()=>ie,withValidation:()=>ke,yieldMachine:()=>de});module.exports=ct(jt);function L(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=n.next(r);if(i)return o;r=o}}function le(e){return function*(){return yield e}()}function de(e){return e}function ue(e,t){return t.reduce((n,r)=>L(r,n),e)}function ye(e){return e}function fe(e,t,n=(r,o)=>{console.log(`Step ${r}:`,o.context)}){let r=e(t),o=t,i=0;for(n(i,o);;){let{value:a,done:s}=r.next(o);if(s)return console.log("Final:",a),a;o=a,i++,n(i,o)}}async function Me(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=await n.next(r);if(i)return o;r=o}}async function*xe(e){return yield e}var he=Symbol("MachineMeta"),R=Symbol("__machine_runtime_meta__");function S(e,t){let n=e[R]||{},r={...n,...t};t.guards&&n.guards?r.guards=[...t.guards,...n.guards]:t.guards&&(r.guards=[...t.guards]),t.actions&&n.actions?r.actions=[...t.actions,...n.actions]:t.actions&&(r.actions=[...t.actions]),Object.defineProperty(e,R,{value:r,enumerable:!1,writable:!1,configurable:!0})}function pe(e,t){return S(t,{target:e.name||e.toString()}),t}function ge(e,t){return S(t,{description:e}),t}function Ce(e,t){return S(t,{guards:[e]}),t}function me(e,t){return S(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function we(e,t){return S(t,{actions:[e]}),t}function $(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=function(...c){let l=typeof this=="object"&&"context"in this,u=l?this.context:this;if(e(u,...c)){let y=l?this.context:this;return t.apply(y,c)}else if(r==="throw"){let y=o||"Guard condition failed";throw new Error(y)}else if(r==="ignore"){if(l)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(l)return r.apply(this,c);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),S(s,{description:i||"Synchronous guarded transition",guards:[{name:"runtime_guard",description:i||"Synchronous condition check"}]}),s}function _(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=async function(...c){let l=typeof this=="object"&&"context"in this,u=l?this.context:this;if(await Promise.resolve(e(u,...c))){let y=l?this.context:this;return t.apply(y,c)}else if(r==="throw"){let y=o||"Guard condition failed";throw new Error(y)}else if(r==="ignore"){if(l)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(l)return r.apply(this,c);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),S(s,{description:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}function be(e){return{do(t){let n=$(e,t);return n.else=function(r){return $(e,t,{onFail:r})},n}}}function Te(e){return{do(t){let n=_(e,t);return n.else=function(r){return _(e,t,{onFail:r})},n}}}function Ee(e,t){return t}var g=require("ts-morph");function Se(e){return g.Node.isIdentifier(e)?e.getText():g.Node.isTypeOfExpression(e)?e.getExpression().getText():"unknown"}function A(e){if(!g.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(g.Node.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();o&&(g.Node.isStringLiteral(o)||g.Node.isNumericLiteral(o)?t[r]=o.getLiteralValue():o.getText()==="true"||o.getText()==="false"?t[r]=o.getText()==="true":g.Node.isIdentifier(o)?t[r]=o.getText():g.Node.isObjectLiteralExpression(o)?t[r]=A(o):g.Node.isArrayLiteralExpression(o)&&(t[r]=o.getElements().map(i=>g.Node.isObjectLiteralExpression(i)?A(i):i.getText())))}return t}function lt(e){if(!g.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(g.Node.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();if(!o)continue;r==="onDone"||r==="onError"?t[r]=Se(o):g.Node.isStringLiteral(o)?t[r]=o.getLiteralValue():g.Node.isIdentifier(o)&&(t[r]=o.getText())}return t}function v(e,t=!1){if(!g.Node.isCallExpression(e))return null;let n=e.getExpression(),r=g.Node.isIdentifier(n)?n.getText():null;if(!r)return null;let o={},i=e.getArguments();switch(r){case"transitionTo":i[0]&&(o.target=Se(i[0]));break;case"describe":if(i[0]&&g.Node.isStringLiteral(i[0])&&(o.description=i[0].getLiteralValue()),i[1]&&g.Node.isCallExpression(i[1])){let a=v(i[1],t);a&&Object.assign(o,a)}break;case"guarded":if(i[0]){let a=A(i[0]);Object.keys(a).length>0&&(o.guards=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=v(i[1],t);a&&Object.assign(o,a)}break;case"invoke":if(i[0]){let a=lt(i[0]);Object.keys(a).length>0&&(o.invoke=a)}break;case"action":if(i[0]){let a=A(i[0]);Object.keys(a).length>0&&(o.actions=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=v(i[1],t);a&&Object.assign(o,a)}break;case"guard":if(i[2]){let a=A(i[2]);a.description&&(o.description=a.description)}if(o.guards=[{name:"runtime_guard",description:o.description||"Synchronous condition check"}],i[1]&&g.Node.isCallExpression(i[1])){let a=v(i[1],t);a&&Object.assign(o,a)}break;case"guardAsync":if(i[2]){let a=A(i[2]);a.description&&(o.description=a.description)}if(o.guards=[{name:"runtime_guard_async",description:o.description||"Asynchronous condition check"}],i[1]&&g.Node.isCallExpression(i[1])){let a=v(i[1],t);a&&Object.assign(o,a)}break;default:return null}return Object.keys(o).length>0?o:null}function dt(e,t=!1){if(!g.Node.isPropertyDeclaration(e))return t&&console.error(" ⚠️ Not a property declaration"),null;let n=e.getInitializer();if(!n)return t&&console.error(" ⚠️ No initializer"),null;if(!g.Node.isCallExpression(n))return t&&console.error(" ⚠️ Initializer is not a call expression"),null;let r=v(n,t);return r&&t&&console.error(" ✅ Extracted metadata:",JSON.stringify(r,null,2)),r}function V(e,t=!1){let n={on:{}},r=e.getDeclarations()[0];if(!r||!g.Node.isClassDeclaration(r))return t&&console.error(`⚠️ Warning: Could not get class declaration for ${e.getName()}`),n;let o=e.getName();t&&console.error(` Analyzing state: ${o}`);for(let i of r.getInstanceMembers()){let a=i.getName();t&&console.error(` Checking member: ${a}`);let s=dt(i,t);if(!s)continue;t&&console.error(` Found transition: ${a}`);let{invoke:c,actions:l,guards:u,...M}=s;if(c&&(n.invoke||(n.invoke=[]),n.invoke.push({src:c.src,onDone:{target:c.onDone},onError:{target:c.onError},description:c.description}),t&&console.error(` → Invoke: ${c.src}`)),M.target){let y={target:M.target};M.description&&(y.description=M.description),u&&(y.cond=u.map(x=>x.name).join(" && "),t&&console.error(` → Guard: ${y.cond}`)),l&&l.length>0&&(y.actions=l.map(x=>x.name),t&&console.error(` → Actions: ${y.actions.join(", ")}`)),n.on[a]=y,t&&console.error(` → Target: ${M.target}`)}}return n}function ut(e,t,n,r,o=!1){let i=V(t,o);if(r){o&&console.error(` 👪 Analyzing children for state: ${e}`),i.initial=r.initialState,i.states={};for(let a of r.classes){let s=n.getClass(a);if(s){let c=s.getSymbolOrThrow();i.states[a]=V(c,o)}else console.warn(`⚠️ Warning: Child class '${a}' not found.`)}}return i}function D(e,t,n=!1){n&&(console.error(`
2
+ 🔍 Analyzing machine: ${e.id}`),console.error(` Source: ${e.input}`));let r=t.getSourceFile(e.input);if(!r)throw new Error(`Source file not found: ${e.input}`);if(e.parallel){n&&console.error(" ⏹️ Parallel machine detected. Analyzing regions.");let i={id:e.id,type:"parallel",states:{}};e.description&&(i.description=e.description);for(let a of e.parallel.regions){n&&console.error(` 📍 Analyzing region: ${a.name}`);let s={};for(let c of a.classes){let l=r.getClass(c);if(l){let u=l.getSymbolOrThrow();s[c]=V(u,n)}else console.warn(`⚠️ Warning: Class '${c}' not found for region '${a.name}'.`)}i.states[a.name]={initial:a.initialState,states:s}}return n&&console.error(` ✅ Extracted ${e.parallel.regions.length} parallel regions`),i}if(!e.initialState||!e.classes)throw new Error(`Machine config for '${e.id}' must have either 'parallel' or 'initialState'/'classes'.`);let o={id:e.id,initial:e.initialState,states:{}};e.description&&(o.description=e.description);for(let i of e.classes){let a=r.getClass(i);if(!a){console.warn(`⚠️ Warning: Class '${i}' not found in '${e.input}'. Skipping.`);continue}let s=a.getSymbolOrThrow(),c=i===e.initialState&&e.children,l=ut(i,s,r,c?e.children:void 0,n);o.states[i]=l}return n&&console.error(` ✅ Extracted ${e.classes.length} states`),o}function Fe(e){var o;let t=(o=e.verbose)!=null?o:!1;t&&(console.error(`
3
3
  📊 Starting statechart extraction`),console.error(` Machines to extract: ${e.machines.length}`));let n=new g.Project;n.addSourceFilesAtPaths("src/**/*.ts"),n.addSourceFilesAtPaths("examples/**/*.ts");let r=[];for(let i of e.machines)try{let a=D(i,n,t);r.push(a)}catch(a){console.error(`❌ Error extracting machine '${i.id}':`,a),t||console.error(" Run with --verbose for more details")}return t&&console.error(`
4
- ✅ Extraction complete: ${r.length}/${e.machines.length} machines extracted`),r}function V(){let e={input:"examples/authMachine.ts",classes:["LoggedOutMachine","LoggingInMachine","LoggedInMachine","SessionExpiredMachine","ErrorMachine"],id:"auth",initialState:"LoggedOutMachine",description:"Authentication state machine"};console.error("🔍 Using legacy generateChart function"),console.error(`⚠️ Consider using extractMachines() with a config file instead
5
- `);let t=new g.Project;t.addSourceFilesAtPaths("src/**/*.ts"),t.addSourceFilesAtPaths("examples/**/*.ts");try{let n=D(e,t,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}require.main===module&&V();function U(e){return typeof e!="function"?null:e[P]||null}function K(e){let t={on:{}},n=[];for(let r in e){let o=e[r];if(typeof o!="function")continue;let i=U(o);if(i){if(i.invoke&&n.push({src:i.invoke.src,onDone:{target:i.invoke.onDone},onError:{target:i.invoke.onError},description:i.invoke.description}),i.target){let a={target:i.target};i.description&&(a.description=i.description),i.guards&&i.guards.length>0&&(a.cond=i.guards.map(s=>s.name).join(" && ")),i.actions&&i.actions.length>0&&(a.actions=i.actions.map(s=>s.name)),t.on[r]=a}else if(i.guards&&i.guards.length>0){let a={target:"GuardedTransition",cond:i.guards.map(s=>s.name).join(" && ")};i.description&&(a.description=i.description),t.on[r]=a}}}return n.length>0&&(t.invoke=n),t}function Se(e,t){let n={id:t.id,initial:t.initial,states:{}};t.description&&(n.description=t.description);for(let[r,o]of Object.entries(e))n.states[r]=K(o);return n}function Fe(e,t){let n=t.stateName||e.constructor.name||"State";return{id:t.id,initial:n,states:{[n]:K(e)}}}function Pe(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:o,...i}=e,a=new Proxy({},{get(s,c){let d=n[c];if(typeof d=="function")return(...u)=>{let x=d.apply(n.context,u),y=Object.assign({context:x.context},i);return r(y),y}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function dt(e,t,n){let r=()=>{let i=e.getContext(),a=n(i),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(i)},o=new Proxy({},{get(i,a){let s=r(),c=s[a];if(typeof c!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...d)=>c.apply(s.context,d)}});return{get context(){return e.getContext()},get state(){return r()},actions:o}}function ut(e,t){let n=Pe(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function yt(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var J=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function Mt(e,t){let n=new e(t);return new Proxy({},{get(r,o){let i=t.getContext();if(o in i)return i[o];let a=n[o];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(r,o,i){let a=t.getContext();if(o in a){let s={...a,[o]:i};return t.setContext(s),!0}return!1},has(r,o){let i=t.getContext();return o in i||typeof n[o]=="function"},ownKeys(r){let o=t.getContext(),i=Object.keys(o),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...i,...a]))},getOwnPropertyDescriptor(r,o){let i=t.getContext();if(o in i||typeof n[o]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function ft(e,t,n){let r=()=>{let o=n(e),i=t[o];if(!i)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(o)}".`);return i(e)};return new Proxy(e,{get(o,i,a){if(i in o)return o[i];let s=r(),c=s[i];if(typeof c=="function")return(...d)=>{let u=c.apply(s.context,d);if(typeof u!="object"||u===null){console.warn(`[MutableMachine] Transition "${String(i)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(o).forEach(x=>delete o[x]),Object.assign(o,u)}},set(o,i,a,s){return o[i]=a,!0},has(o,i){let a=r();return i in o||typeof a[i]=="function"}})}function xt(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return v(this,{...this.context,child:r})}return this}}function pt(e){return function(){return typeof this.context[e]!="boolean"&&console.warn(`[toggle primitive] Property '${String(e)}' is not a boolean. Toggling may have unexpected results.`),v(this,{...this.context,[e]:!this.context[e]})}}var q=class extends T{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},S=class extends T{constructor(n,r,o){super({status:"loading",abortController:new AbortController,attempts:o});this.config=n;this.params=r;this.succeed=n=>{var r,o;return(o=(r=this.config).onSuccess)==null||o.call(r,n),new X(this.config,{status:"success",data:n})};this.fail=n=>{var o,i,a;let r=(o=this.config.maxRetries)!=null?o:3;return this.context.attempts<r?new Y(this.config,this.params,n,this.context.attempts):((a=(i=this.config).onError)==null||a.call(i,n),new Q(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new Z(this.config));this.execute()}async execute(){}},Y=class extends T{constructor(n,r,o,i){super({status:"retrying",error:o,attempts:i});this.config=n;this.params=r;this.retry=n=>new S(this.config,n!=null?n:this.params,this.context.attempts+1)}},X=class extends T{constructor(n,r){super(r);this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},Q=class extends T{constructor(n,r){super(r);this.config=n;this.retry=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},Z=class extends T{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}};function ht(e){return new q(e)}function ee(e,t){let n={...e.context,...t.context},r={...e},o={...t};delete r.context,delete o.context;let i={};for(let a in r){let s=r[a];i[a]=(...c)=>{let d=s.apply(e.context,c);return ee(d,t)}}for(let a in o){let s=o[a];i[a]=(...c)=>{let d=s.apply(t.context,c);return ee(e,d)}}return{context:n,...i}}var Re=Symbol("CANCEL");function w(e,t,n={}){let{mode:r="auto",exclude:o=["context"]}=n,i={};for(let a in e){if(!Object.prototype.hasOwnProperty.call(e,a))continue;let s=e[a];if(a==="context"){i.context=s;continue}if(o.includes(a)){i[a]=s;continue}if(typeof s!="function"||a.startsWith("_")){i[a]=s;continue}i[a]=gt(a,s,e,t,r)}return i}function gt(e,t,n,r,o){return function(...a){let s=n.context,c={transitionName:e,context:s,args:a},d=()=>{try{if(r.before){let f=r.before(c);if(f===Re)return n;if(f instanceof Promise)throw new Error(`Middleware mode is 'sync' but before hook returned Promise for transition: ${e}`)}let y=t.call(this,...a);if(y instanceof Promise)return u(y,s);if(r.after){let f={transitionName:e,prevContext:s,nextContext:y.context,args:a};if(r.after(f)instanceof Promise)throw new Error(`Middleware mode is 'sync' but after hook returned Promise for transition: ${e}`)}return y}catch(y){if(r.error){let f={transitionName:e,context:s,args:a,error:y},l=r.error(f);if(l instanceof Promise)throw l.catch(()=>{}),y;if(l&&typeof l=="object"&&"context"in l)return l}throw y}},u=async(y,f)=>{try{let l=await y;if(r.after){let h={transitionName:e,prevContext:f,nextContext:l.context,args:a};await r.after(h)}return l}catch(l){if(r.error){let h={transitionName:e,context:f,args:a,error:l},M=await r.error(h);if(M&&typeof M=="object"&&"context"in M)return M}throw l}},x=async()=>{try{if(r.before&&await r.before(c)===Re)return n;let y=await t.call(this,...a);if(r.after){let f={transitionName:e,prevContext:s,nextContext:y.context,args:a};await r.after(f)}return y}catch(y){if(r.error){let f={transitionName:e,context:s,args:a,error:y},l=await r.error(f);if(l&&typeof l=="object"&&"context"in l)return l}throw y}};return o==="async"?x():d()}}function ve(e,t={}){let{logger:n=console.log,includeContext:r=!0,includeArgs:o=!0}=t;return w(e,{before:({transitionName:i,args:a})=>{let s=o&&a.length>0?` ${JSON.stringify(a)}`:"";n(`→ ${i}${s}`)},after:({transitionName:i,nextContext:a})=>{let s=r?` ${JSON.stringify(a)}`:"";n(`✓ ${i}${s}`)}})}function Ae(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!0}=n;return w(e,{after:async({transitionName:a,prevContext:s,nextContext:c,args:d})=>{let u={transition:a,to:c};o&&(u.from=s),i&&d.length>0&&(u.args=d),await t(`${r}.${a}`,u)}},{mode:"async"})}function Oe(e,t,n){return w(e,{before:r=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(i===!1)throw new Error(`Validation failed for transition: ${r.transitionName}`)});if(o===!1)throw new Error(`Validation failed for transition: ${r.transitionName}`)}},{mode:"auto",...n})}function je(e,t,n){return w(e,{before:r=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(!i)throw new Error(`Unauthorized transition: ${r.transitionName}`)});if(!o)throw new Error(`Unauthorized transition: ${r.transitionName}`)}},{mode:"auto",...n})}function ke(e,t,n={}){let{includeContext:r=!0,includeArgs:o=!0,mode:i}=n;return w(e,{error:async({transitionName:a,context:s,args:c,error:d})=>{let u={transition:a};r&&(u.context=s),o&&c.length>0&&(u.args=c),await Promise.resolve(t(d,u))}},{mode:i})}function Ne(e,t){let n=new Map;return w(e,{before:({transitionName:r})=>{n.set(r,performance.now())},after:({transitionName:r,nextContext:o})=>{let i=n.get(r);if(i){let a=performance.now()-i;n.delete(r);let s=t({transitionName:r,duration:a,context:o});if(s instanceof Promise)return s}}},{mode:"auto"})}function ze(e,t={}){let{maxRetries:n=3,delay:r=1e3,backoffMultiplier:o=1,shouldRetry:i=()=>!0,onRetry:a}=t,s={};for(let c in e){if(!Object.prototype.hasOwnProperty.call(e,c))continue;let d=e[c];if(c==="context"||typeof d!="function"){s[c]=d;continue}s[c]=async function(...x){let y;for(let f=0;f<=n;f++)try{return await d.call(this,...x)}catch(l){if(y=l,f===n||!i(y))break;a==null||a(f+1,y);let h=r*Math.pow(o,f);await new Promise(M=>setTimeout(M,h))}throw y}}return s}function ne(e,t={}){let{maxSize:n,serializer:r,filter:o,onEntry:i,_isRewrap:a=!1}=t,s=[],c=0,d=w(e,{before:({transitionName:u,args:x})=>{if(o&&!o(u,x))return;let y={id:`entry-${c++}`,transitionName:u,args:[...x],timestamp:Date.now()};if(r)try{y.serializedArgs=r.serialize(x)}catch(f){console.error("Failed to serialize history args:",f)}s.push(y),n&&s.length>n&&s.shift(),i==null||i(y)}},{exclude:["context","history","clearHistory"]});if(!a)for(let u in d){if(!Object.prototype.hasOwnProperty.call(d,u))continue;let x=d[u];if(typeof x=="function"&&!u.startsWith("_")&&u!=="context"&&!["history","clearHistory"].includes(u)){let y=x;d[u]=function(...f){let l=y.apply(this,f);if(l&&typeof l=="object"&&"context"in l&&!("history"in l)){let h=w(l,{before:({transitionName:M,args:C})=>{if(o&&!o(M,C))return;let p={id:`entry-${c++}`,transitionName:M,args:[...C],timestamp:Date.now()};if(r)try{p.serializedArgs=r.serialize(C)}catch(b){console.error("Failed to serialize history args:",b)}s.push(p),n&&s.length>n&&s.shift(),i==null||i(p)}},{exclude:["context","history","clearHistory"]});return Object.assign(h,{history:s,clearHistory:()=>{s.length=0,c=0}})}return l}}}return Object.assign(d,{history:s,clearHistory:()=>{s.length=0,c=0}})}function re(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:o,onlyIfChanged:i=!1,filter:a,onSnapshot:s,_extraExclusions:c=[],_isRewrap:d=!1}=t,u=[],x=0,y=w(e,{after:({transitionName:l,prevContext:h,nextContext:M})=>{if(a&&!a(l)||i&&!(JSON.stringify(h)!==JSON.stringify(M)))return;let C={id:`snapshot-${x++}`,transitionName:l,before:{...h},after:{...M},timestamp:Date.now()};if(r)try{C.serializedBefore=r.serialize(h),C.serializedAfter=r.serialize(M)}catch(p){console.error("Failed to serialize snapshot:",p)}if(o)try{C.diff=o(h,M)}catch(p){console.error("Failed to capture snapshot:",p)}u.push(C),n&&u.length>n&&u.shift(),s==null||s(C)}},{exclude:["context","snapshots","clearSnapshots","restoreSnapshot",...c]}),f=l=>{let{context:h,...M}=e;return{context:l,...M}};if(!d)for(let l in y){if(!Object.prototype.hasOwnProperty.call(y,l))continue;let h=y[l];if(typeof h=="function"&&!l.startsWith("_")&&l!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(l)){let M=h;y[l]=function(...C){let p=M.apply(this,C);if(p&&typeof p=="object"&&"context"in p&&!("snapshots"in p)){for(let m in p){if(!Object.prototype.hasOwnProperty.call(p,m))continue;let A=p[m];if(typeof A=="function"&&!m.startsWith("_")&&m!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(m)){let Ze=A;p[m]=function(...et){let k=p.context,O=Ze.apply(this,et);if(O&&typeof O=="object"&&"context"in O){let N=O.context;if(!(a&&!a(m))){let se=!0;if(i&&(se=JSON.stringify(k)!==JSON.stringify(N)),se){let F={id:`snapshot-${x++}`,transitionName:m,before:{...k},after:{...N},timestamp:Date.now()};if(r)try{F.serializedBefore=r.serialize(k),F.serializedAfter=r.serialize(N)}catch(H){console.error("Failed to serialize snapshot:",H)}if(o)try{F.diff=o(k,N)}catch(H){console.error("Failed to capture snapshot:",H)}u.push(F),n&&u.length>n&&u.shift(),s==null||s(F)}}}return O}}}let b=Object.assign(p,{snapshots:u,clearSnapshots:()=>{u.length=0,x=0},restoreSnapshot:f});return e.history&&(b.history=e.history,b.clearHistory=e.clearHistory),b}return p}}}return Object.assign(y,{snapshots:u,clearSnapshots:()=>{u.length=0,x=0},restoreSnapshot:f})}function oe(e,t={}){let{maxSize:n,serializer:r,onRecord:o}=t,i=[],a=[],s=0,c=0,d=(l,h)=>{let M={id:`entry-${s++}`,transitionName:l,args:[...h],timestamp:Date.now()};if(r)try{M.serializedArgs=r.serialize(h)}catch(C){console.error("Failed to serialize history args:",C)}i.push(M),n&&i.length>n&&i.shift(),o==null||o("history",M)},u=(l,h,M)=>{let C={id:`snapshot-${c++}`,transitionName:l,before:{...h},after:{...M},timestamp:Date.now()};if(r)try{C.serializedBefore=r.serialize(h),C.serializedAfter=r.serialize(M)}catch(p){console.error("Failed to serialize snapshot:",p)}a.push(C),n&&a.length>n&&a.shift(),o==null||o("snapshot",C)},x=l=>{let{context:h,...M}=e;return Object.assign({context:l},l,M)},y=(l=0)=>{if(l<0||l>=a.length)throw new Error(`Invalid snapshot index: ${l}`);let h=x(a[l].before),M=a[l],C=i.findIndex(p=>p.transitionName===M.transitionName&&p.timestamp===M.timestamp);if(C===-1)throw new Error("Could not find matching history entry for snapshot");for(let p=C;p<i.length;p++){let b=i[p],m=h[b.transitionName];if(typeof m=="function")try{h=m.apply(h.context,b.args)}catch(A){throw console.error(`Replay failed at step ${p}:`,A),A}}return h},f=l=>{let h={...l};for(let M in l){if(!Object.prototype.hasOwnProperty.call(l,M))continue;let C=l[M];typeof C=="function"&&!M.startsWith("_")&&M!=="context"&&!["history","snapshots","clearHistory","clearSnapshots","clearTimeTravel","restoreSnapshot","replayFrom"].includes(M)&&(h[M]=function(...p){d(M,p);let b=h.context,m=C.apply(this,p);return m&&typeof m=="object"&&"context"in m&&u(M,b,m.context),m&&typeof m=="object"&&"context"in m?f(m):m})}return Object.assign(h,{history:i,snapshots:a,clearHistory:()=>{i.length=0,s=0},clearSnapshots:()=>{a.length=0,c=0},clearTimeTravel:()=>{i.length=0,a.length=0,s=0,c=0},restoreSnapshot:x,replayFrom:y})};return f(e)}function Be(e,...t){return t.reduce((n,r)=>r(n),e)}function $e(e,t){return n=>w(n,e,t)}function j(e,...t){return t.reduce((n,r)=>r(n),e)}function De(e){return new te(e)}var te=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function Ke(e){return oe(re(ne(e)))}function _e(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(o,...i)=>{let a=o,s=[];for(let c=0;c<i.length;c++){let d=i[c];try{if("middleware"in d&&"when"in d){if(!d.when(a))continue;a=d.middleware(a)}else a=d(a)}catch(u){let x=u instanceof Error?u:new Error(String(u));if(s.push({error:x,middlewareIndex:c}),n&&console.error(`Middleware pipeline error at index ${c}:`,x),r==null||r(x,`middleware-${c}`),!t)break}}return{machine:a,errors:s,success:s.length===0}}}function We(){let e=new Map;return{register(t,n,r,o){if(e.has(t))throw new Error(`Middleware '${t}' is already registered`);return e.set(t,{name:t,middleware:n,description:r,priority:o}),this},unregister(t){return e.delete(t)},has(t){return e.has(t)},get(t){return e.get(t)},list(){return Array.from(e.values()).sort((t,n)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})},apply(t,n){let r=n.map(o=>{let i=e.get(o);if(!i)throw new Error(`Middleware '${o}' is not registered`);return i}).sort((o,i)=>{var a,s;return((a=o.priority)!=null?a:0)-((s=i.priority)!=null?s:0)});return j(t,...r.map(o=>o.middleware))},applyAll(t){let n=this.list();return j(t,...n.map(r=>r.middleware))}}}function _(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function He(e){return _(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function Ie(e,t,n){return _(n,r=>r.context[e]===t)}function Le(...e){return t=>j(t,...e)}function Ge(e,t){return n=>{for(let[r,o]of e)if(r(n))return o(n);return t?t(n):n}}function ie(e){return typeof e=="function"&&e.length===1}function Ve(e){return e!==null&&"middleware"in e&&"when"in e&&ie(e.middleware)&&typeof e.when=="function"}function Ue(e,t){return e instanceof t}function Je(e,...t){return{type:e,args:t}}function qe(e,t){return v(e,n=>({...n,...t}))}async function Ye(e,...t){let n=e;for(let r of t)n=await r(n);return n}function Xe(e,t){return t?console.log(t,e.context):console.log(e.context),e}function Qe(e,t,...n){return e.apply(t,n)}function ae(e){return new Proxy(e,{get(t,n){let r=t[n];return typeof r=="function"?function(...o){let i=r.apply(t.context,o);return i&&typeof i=="object"&&"context"in i?ae(i):i}:r}})}var W=class e{constructor(t){return this.wrappedMachine=t,new Proxy(this,{get:(n,r)=>{if(r==="wrappedMachine")return Reflect.get(n,r);if(r==="context")return this.wrappedMachine.context;let o=this.wrappedMachine[r];return typeof o=="function"?(...i)=>{let a=o.apply(this.wrappedMachine.context,i);return a&&typeof a=="object"&&"context"in a?new e(a):a}:o}})}};function E(e,t){let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function Ct(e,t){return Object.assign({context:e},t)}function mt(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...o){let i=r(this,...o);return E(i,t)}]));return n=>E(n,t)}}function v(e,t){let{context:n,...r}=e,o=typeof t=="function"?t(n):t;return E(o,r)}function wt(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function bt(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function Tt(e,t){return(...n)=>{let r=e(...n),o=t(),i={...r.context,...o.context},{context:a,...s}=r,{context:c,...d}=o,u={...s,...d};return E(i,u)}}function Et(e){let{context:t,...n}=e;return r=>E(r,n)}function St(e,t,n){let r=e.context[t],o=n[r];if(!o)throw new Error(`No handler found for state: ${String(r)}`);return o(e.context)}function Ft(e,t,n){return e.context[t]===n}function Pt(e,t){let n=e,r=null;async function o(i){r&&(r.abort(),r=null);let a=n[i.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(i.type)}' on current state.`);let s=new AbortController;r=s;try{let d=await a.apply(n.context,[...i.args,{signal:s.signal}]);return s.signal.aborted||(n=d,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:o,stop:()=>{r&&(r.abort(),r=null)}}}var T=class{constructor(t){this.context=t}};function Rt(e,t){let{context:n,...r}=e;return E(t(n),r)}
4
+ ✅ Extraction complete: ${r.length}/${e.machines.length} machines extracted`),r}function U(){let e={input:"examples/authMachine.ts",classes:["LoggedOutMachine","LoggingInMachine","LoggedInMachine","SessionExpiredMachine","ErrorMachine"],id:"auth",initialState:"LoggedOutMachine",description:"Authentication state machine"};console.error("🔍 Using legacy generateChart function"),console.error(`⚠️ Consider using extractMachines() with a config file instead
5
+ `);let t=new g.Project;t.addSourceFilesAtPaths("src/**/*.ts"),t.addSourceFilesAtPaths("examples/**/*.ts");try{let n=D(e,t,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}var yt={hierarchical:{input:"examples/dashboardMachine.ts",id:"dashboard",classes:["DashboardMachine","LoggedOutMachine"],initialState:"DashboardMachine",children:{contextProperty:"child",initialState:"ViewingChildMachine",classes:["ViewingChildMachine","EditingChildMachine"]}},parallel:{input:"examples/editorMachine.ts",id:"editor",parallel:{regions:[{name:"fontWeight",initialState:"NormalWeight",classes:["NormalWeight","BoldWeight"]},{name:"textDecoration",initialState:"NoDecoration",classes:["NoDecoration","UnderlineState"]}]}}};require.main===module&&U();function J(e){return typeof e!="function"?null:e[R]||null}function K(e){let t={on:{}},n=[];for(let r in e){let o=e[r];if(typeof o!="function")continue;let i=J(o);if(i){if(i.invoke&&n.push({src:i.invoke.src,onDone:{target:i.invoke.onDone},onError:{target:i.invoke.onError},description:i.invoke.description}),i.target){let a={target:i.target};i.description&&(a.description=i.description),i.guards&&i.guards.length>0&&(a.cond=i.guards.map(s=>s.name).join(" && ")),i.actions&&i.actions.length>0&&(a.actions=i.actions.map(s=>s.name)),t.on[r]=a}else if(i.guards&&i.guards.length>0){let a={target:"GuardedTransition",cond:i.guards.map(s=>s.name).join(" && ")};i.description&&(a.description=i.description),t.on[r]=a}}}return n.length>0&&(t.invoke=n),t}function Pe(e,t){let n={id:t.id,initial:t.initial,states:{}};t.description&&(n.description=t.description);for(let[r,o]of Object.entries(e))n.states[r]=K(o);return n}function Re(e,t){let n=t.stateName||e.constructor.name||"State";return{id:t.id,initial:n,states:{[n]:K(e)}}}function ve(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:o,...i}=e,a=new Proxy({},{get(s,c){let l=n[c];if(typeof l=="function")return(...u)=>{let M=l.apply(n.context,u),y=Object.assign({context:M.context},i);return r(y),y}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function ft(e,t,n){let r=()=>{let i=e.getContext(),a=n(i),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(i)},o=new Proxy({},{get(i,a){let s=r(),c=s[a];if(typeof c!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...l)=>c.apply(s.context,l)}});return{get context(){return e.getContext()},get state(){return r()},actions:o}}function Mt(e,t){let n=ve(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function xt(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var q=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function ht(e,t){let n=new e(t);return new Proxy({},{get(r,o){let i=t.getContext();if(o in i)return i[o];let a=n[o];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(r,o,i){let a=t.getContext();if(o in a){let s={...a,[o]:i};return t.setContext(s),!0}return!1},has(r,o){let i=t.getContext();return o in i||typeof n[o]=="function"},ownKeys(r){let o=t.getContext(),i=Object.keys(o),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...i,...a]))},getOwnPropertyDescriptor(r,o){let i=t.getContext();if(o in i||typeof n[o]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function pt(e,t,n){let r=()=>{let o=n(e),i=t[o];if(!i)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(o)}".`);return i(e)};return new Proxy(e,{get(o,i,a){if(i in o)return o[i];let s=r(),c=s[i];if(typeof c=="function")return(...l)=>{let u=c.apply(s.context,l);if(typeof u!="object"||u===null){console.warn(`[MutableMachine] Transition "${String(i)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(o).forEach(M=>delete o[M]),Object.assign(o,u)}},set(o,i,a,s){return o[i]=a,!0},has(o,i){let a=r();return i in o||typeof a[i]=="function"}})}function gt(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return O(this,{...this.context,child:r})}return this}}function Ct(e){return function(){return typeof this.context[e]!="boolean"&&console.warn(`[toggle primitive] Property '${String(e)}' is not a boolean. Toggling may have unexpected results.`),O(this,{...this.context,[e]:!this.context[e]})}}var Y=class extends T{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new F(this.config,n!=null?n:this.config.initialParams,1)}},F=class extends T{constructor(n,r,o){super({status:"loading",abortController:new AbortController,attempts:o});this.config=n;this.params=r;this.succeed=n=>{var r,o;return(o=(r=this.config).onSuccess)==null||o.call(r,n),new Q(this.config,{status:"success",data:n})};this.fail=n=>{var o,i,a;let r=(o=this.config.maxRetries)!=null?o:3;return this.context.attempts<r?new X(this.config,this.params,n,this.context.attempts):((a=(i=this.config).onError)==null||a.call(i,n),new Z(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new ee(this.config));this.execute()}async execute(){}},X=class extends T{constructor(n,r,o,i){super({status:"retrying",error:o,attempts:i});this.config=n;this.params=r;this.retry=n=>new F(this.config,n!=null?n:this.params,this.context.attempts+1)}},Q=class extends T{constructor(n,r){super(r);this.config=n;this.refetch=n=>new F(this.config,n!=null?n:this.config.initialParams,1)}},Z=class extends T{constructor(n,r){super(r);this.config=n;this.retry=n=>new F(this.config,n!=null?n:this.config.initialParams,1)}},ee=class extends T{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new F(this.config,n!=null?n:this.config.initialParams,1)}};function mt(e){return new Y(e)}function te(e,t){let n={...e.context,...t.context},r={...e},o={...t};delete r.context,delete o.context;let i={};for(let a in r){let s=r[a];i[a]=(...c)=>{let l=s.apply(e.context,c);return te(l,t)}}for(let a in o){let s=o[a];i[a]=(...c)=>{let l=s.apply(t.context,c);return te(e,l)}}return{context:n,...i}}var Ae=Symbol("CANCEL");function w(e,t,n={}){let{mode:r="auto",exclude:o=["context"]}=n,i={};for(let a in e){if(!Object.prototype.hasOwnProperty.call(e,a))continue;let s=e[a];if(a==="context"){i.context=s;continue}if(o.includes(a)){i[a]=s;continue}if(typeof s!="function"||a.startsWith("_")){i[a]=s;continue}i[a]=wt(a,s,e,t,r)}return i}function wt(e,t,n,r,o){return function(...a){let s=n.context,c={transitionName:e,context:s,args:a},l=()=>{try{if(r.before){let x=r.before(c);if(x===Ae)return n;if(x instanceof Promise)throw new Error(`Middleware mode is 'sync' but before hook returned Promise for transition: ${e}`)}let y=t.call(this,...a);if(y instanceof Promise)return u(y,s);if(r.after){let x={transitionName:e,prevContext:s,nextContext:y.context,args:a};if(r.after(x)instanceof Promise)throw new Error(`Middleware mode is 'sync' but after hook returned Promise for transition: ${e}`)}return y}catch(y){if(r.error){let x={transitionName:e,context:s,args:a,error:y},d=r.error(x);if(d instanceof Promise)throw d.catch(()=>{}),y;if(d&&typeof d=="object"&&"context"in d)return d}throw y}},u=async(y,x)=>{try{let d=await y;if(r.after){let p={transitionName:e,prevContext:x,nextContext:d.context,args:a};await r.after(p)}return d}catch(d){if(r.error){let p={transitionName:e,context:x,args:a,error:d},f=await r.error(p);if(f&&typeof f=="object"&&"context"in f)return f}throw d}},M=async()=>{try{if(r.before&&await r.before(c)===Ae)return n;let y=await t.call(this,...a);if(r.after){let x={transitionName:e,prevContext:s,nextContext:y.context,args:a};await r.after(x)}return y}catch(y){if(r.error){let x={transitionName:e,context:s,args:a,error:y},d=await r.error(x);if(d&&typeof d=="object"&&"context"in d)return d}throw y}};return o==="async"?M():l()}}function Oe(e,t={}){let{logger:n=console.log,includeContext:r=!0,includeArgs:o=!0}=t;return w(e,{before:({transitionName:i,args:a})=>{let s=o&&a.length>0?` ${JSON.stringify(a)}`:"";n(`→ ${i}${s}`)},after:({transitionName:i,nextContext:a})=>{let s=r?` ${JSON.stringify(a)}`:"";n(`✓ ${i}${s}`)}})}function je(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!0}=n;return w(e,{after:async({transitionName:a,prevContext:s,nextContext:c,args:l})=>{let u={transition:a,to:c};o&&(u.from=s),i&&l.length>0&&(u.args=l),await t(`${r}.${a}`,u)}},{mode:"async"})}function ke(e,t,n){return w(e,{before:r=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(i===!1)throw new Error(`Validation failed for transition: ${r.transitionName}`)});if(o===!1)throw new Error(`Validation failed for transition: ${r.transitionName}`)}},{mode:"auto",...n})}function Ne(e,t,n){return w(e,{before:r=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(!i)throw new Error(`Unauthorized transition: ${r.transitionName}`)});if(!o)throw new Error(`Unauthorized transition: ${r.transitionName}`)}},{mode:"auto",...n})}function ze(e,t,n={}){let{includeContext:r=!0,includeArgs:o=!0,mode:i}=n;return w(e,{error:async({transitionName:a,context:s,args:c,error:l})=>{let u={transition:a};r&&(u.context=s),o&&c.length>0&&(u.args=c),await Promise.resolve(t(l,u))}},{mode:i})}function Be(e,t){let n=new Map;return w(e,{before:({transitionName:r})=>{n.set(r,performance.now())},after:({transitionName:r,nextContext:o})=>{let i=n.get(r);if(i){let a=performance.now()-i;n.delete(r);let s=t({transitionName:r,duration:a,context:o});if(s instanceof Promise)return s}}},{mode:"auto"})}function $e(e,t={}){let{maxRetries:n=3,delay:r=1e3,backoffMultiplier:o=1,shouldRetry:i=()=>!0,onRetry:a}=t,s={};for(let c in e){if(!Object.prototype.hasOwnProperty.call(e,c))continue;let l=e[c];if(c==="context"||typeof l!="function"){s[c]=l;continue}s[c]=async function(...M){let y;for(let x=0;x<=n;x++)try{return await l.call(this,...M)}catch(d){if(y=d,x===n||!i(y))break;a==null||a(x+1,y);let p=r*Math.pow(o,x);await new Promise(f=>setTimeout(f,p))}throw y}}return s}function re(e,t={}){let{maxSize:n,serializer:r,filter:o,onEntry:i,_isRewrap:a=!1}=t,s=[],c=0,l=w(e,{before:({transitionName:u,args:M})=>{if(o&&!o(u,M))return;let y={id:`entry-${c++}`,transitionName:u,args:[...M],timestamp:Date.now()};if(r)try{y.serializedArgs=r.serialize(M)}catch(x){console.error("Failed to serialize history args:",x)}s.push(y),n&&s.length>n&&s.shift(),i==null||i(y)}},{exclude:["context","history","clearHistory"]});if(!a)for(let u in l){if(!Object.prototype.hasOwnProperty.call(l,u))continue;let M=l[u];if(typeof M=="function"&&!u.startsWith("_")&&u!=="context"&&!["history","clearHistory"].includes(u)){let y=M;l[u]=function(...x){let d=y.apply(this,x);if(d&&typeof d=="object"&&"context"in d&&!("history"in d)){let p=w(d,{before:({transitionName:f,args:C})=>{if(o&&!o(f,C))return;let h={id:`entry-${c++}`,transitionName:f,args:[...C],timestamp:Date.now()};if(r)try{h.serializedArgs=r.serialize(C)}catch(b){console.error("Failed to serialize history args:",b)}s.push(h),n&&s.length>n&&s.shift(),i==null||i(h)}},{exclude:["context","history","clearHistory"]});return Object.assign(p,{history:s,clearHistory:()=>{s.length=0,c=0}})}return d}}}return Object.assign(l,{history:s,clearHistory:()=>{s.length=0,c=0}})}function oe(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:o,onlyIfChanged:i=!1,filter:a,onSnapshot:s,_extraExclusions:c=[],_isRewrap:l=!1}=t,u=[],M=0,y=w(e,{after:({transitionName:d,prevContext:p,nextContext:f})=>{if(a&&!a(d)||i&&!(JSON.stringify(p)!==JSON.stringify(f)))return;let C={id:`snapshot-${M++}`,transitionName:d,before:{...p},after:{...f},timestamp:Date.now()};if(r)try{C.serializedBefore=r.serialize(p),C.serializedAfter=r.serialize(f)}catch(h){console.error("Failed to serialize snapshot:",h)}if(o)try{C.diff=o(p,f)}catch(h){console.error("Failed to capture snapshot:",h)}u.push(C),n&&u.length>n&&u.shift(),s==null||s(C)}},{exclude:["context","snapshots","clearSnapshots","restoreSnapshot",...c]}),x=d=>{let{context:p,...f}=e;return{context:d,...f}};if(!l)for(let d in y){if(!Object.prototype.hasOwnProperty.call(y,d))continue;let p=y[d];if(typeof p=="function"&&!d.startsWith("_")&&d!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(d)){let f=p;y[d]=function(...C){let h=f.apply(this,C);if(h&&typeof h=="object"&&"context"in h&&!("snapshots"in h)){for(let m in h){if(!Object.prototype.hasOwnProperty.call(h,m))continue;let j=h[m];if(typeof j=="function"&&!m.startsWith("_")&&m!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(m)){let tt=j;h[m]=function(...nt){let z=h.context,k=tt.apply(this,nt);if(k&&typeof k=="object"&&"context"in k){let B=k.context;if(!(a&&!a(m))){let ce=!0;if(i&&(ce=JSON.stringify(z)!==JSON.stringify(B)),ce){let P={id:`snapshot-${M++}`,transitionName:m,before:{...z},after:{...B},timestamp:Date.now()};if(r)try{P.serializedBefore=r.serialize(z),P.serializedAfter=r.serialize(B)}catch(H){console.error("Failed to serialize snapshot:",H)}if(o)try{P.diff=o(z,B)}catch(H){console.error("Failed to capture snapshot:",H)}u.push(P),n&&u.length>n&&u.shift(),s==null||s(P)}}}return k}}}let b=Object.assign(h,{snapshots:u,clearSnapshots:()=>{u.length=0,M=0},restoreSnapshot:x});return e.history&&(b.history=e.history,b.clearHistory=e.clearHistory),b}return h}}}return Object.assign(y,{snapshots:u,clearSnapshots:()=>{u.length=0,M=0},restoreSnapshot:x})}function ie(e,t={}){let{maxSize:n,serializer:r,onRecord:o}=t,i=[],a=[],s=0,c=0,l=(d,p)=>{let f={id:`entry-${s++}`,transitionName:d,args:[...p],timestamp:Date.now()};if(r)try{f.serializedArgs=r.serialize(p)}catch(C){console.error("Failed to serialize history args:",C)}i.push(f),n&&i.length>n&&i.shift(),o==null||o("history",f)},u=(d,p,f)=>{let C={id:`snapshot-${c++}`,transitionName:d,before:{...p},after:{...f},timestamp:Date.now()};if(r)try{C.serializedBefore=r.serialize(p),C.serializedAfter=r.serialize(f)}catch(h){console.error("Failed to serialize snapshot:",h)}a.push(C),n&&a.length>n&&a.shift(),o==null||o("snapshot",C)},M=d=>{let{context:p,...f}=e;return Object.assign({context:d},d,f)},y=(d=0)=>{if(d<0||d>=a.length)throw new Error(`Invalid snapshot index: ${d}`);let p=M(a[d].before),f=a[d],C=i.findIndex(h=>h.transitionName===f.transitionName&&h.timestamp===f.timestamp);if(C===-1)throw new Error("Could not find matching history entry for snapshot");for(let h=C;h<i.length;h++){let b=i[h],m=p[b.transitionName];if(typeof m=="function")try{p=m.apply(p.context,b.args)}catch(j){throw console.error(`Replay failed at step ${h}:`,j),j}}return p},x=d=>{let p={...d};for(let f in d){if(!Object.prototype.hasOwnProperty.call(d,f))continue;let C=d[f];typeof C=="function"&&!f.startsWith("_")&&f!=="context"&&!["history","snapshots","clearHistory","clearSnapshots","clearTimeTravel","restoreSnapshot","replayFrom"].includes(f)&&(p[f]=function(...h){l(f,h);let b=p.context,m=C.apply(this,h);return m&&typeof m=="object"&&"context"in m&&u(f,b,m.context),m&&typeof m=="object"&&"context"in m?x(m):m})}return Object.assign(p,{history:i,snapshots:a,clearHistory:()=>{i.length=0,s=0},clearSnapshots:()=>{a.length=0,c=0},clearTimeTravel:()=>{i.length=0,a.length=0,s=0,c=0},restoreSnapshot:M,replayFrom:y})};return x(e)}function _e(e,...t){return t.reduce((n,r)=>r(n),e)}function De(e,t){return n=>w(n,e,t)}function N(e,...t){return t.reduce((n,r)=>r(n),e)}function Ke(e){return new ne(e)}var ne=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function We(e){return ie(oe(re(e)))}function Ge(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(o,...i)=>{let a=o,s=[];for(let c=0;c<i.length;c++){let l=i[c];try{if("middleware"in l&&"when"in l){if(!l.when(a))continue;a=l.middleware(a)}else a=l(a)}catch(u){let M=u instanceof Error?u:new Error(String(u));if(s.push({error:M,middlewareIndex:c}),n&&console.error(`Middleware pipeline error at index ${c}:`,M),r==null||r(M,`middleware-${c}`),!t)break}}return{machine:a,errors:s,success:s.length===0}}}function He(){let e=new Map;return{register(t,n,r,o){if(e.has(t))throw new Error(`Middleware '${t}' is already registered`);return e.set(t,{name:t,middleware:n,description:r,priority:o}),this},unregister(t){return e.delete(t)},has(t){return e.has(t)},get(t){return e.get(t)},list(){return Array.from(e.values()).sort((t,n)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})},apply(t,n){let r=n.map(o=>{let i=e.get(o);if(!i)throw new Error(`Middleware '${o}' is not registered`);return i}).sort((o,i)=>{var a,s;return((a=o.priority)!=null?a:0)-((s=i.priority)!=null?s:0)});return N(t,...r.map(o=>o.middleware))},applyAll(t){let n=this.list();return N(t,...n.map(r=>r.middleware))}}}function W(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function Ie(e){return W(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function Le(e,t,n){return W(n,r=>r.context[e]===t)}function Ve(...e){return t=>N(t,...e)}function Ue(e,t){return n=>{for(let[r,o]of e)if(r(n))return o(n);return t?t(n):n}}function ae(e){return typeof e=="function"&&e.length===1}function Je(e){return e!==null&&"middleware"in e&&"when"in e&&ae(e.middleware)&&typeof e.when=="function"}function qe(e,t){return e instanceof t}function Ye(e,...t){return{type:e,args:t}}function Xe(e,t){return O(e,n=>({...n,...t}))}async function Qe(e,...t){let n=e;for(let r of t)n=await r(n);return n}function Ze(e,t){return t?console.log(t,e.context):console.log(e.context),e}function et(e,t,...n){return e.apply(t,n)}function se(e){return new Proxy(e,{get(t,n){let r=t[n];return typeof r=="function"?function(...o){let i=r.apply(t.context,o);return i&&typeof i=="object"&&"context"in i?se(i):i}:r}})}var G=class e{constructor(t){return this.wrappedMachine=t,new Proxy(this,{get:(n,r)=>{if(r==="wrappedMachine")return Reflect.get(n,r);if(r==="context")return this.wrappedMachine.context;let o=this.wrappedMachine[r];return typeof o=="function"?(...i)=>{let a=o.apply(this.wrappedMachine.context,i);return a&&typeof a=="object"&&"context"in a?new e(a):a}:o}})}};function E(e,t){let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function bt(e,t){return Object.assign({context:e},t)}function Tt(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...o){let i=r(this,...o);return E(i,t)}]));return n=>E(n,t)}}function O(e,t){let{context:n,...r}=e,o=typeof t=="function"?t(n):t;return E(o,r)}function Et(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function St(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function Ft(e,t){return(...n)=>{let r=e(...n),o=t(),i={...r.context,...o.context},{context:a,...s}=r,{context:c,...l}=o,u={...s,...l};return E(i,u)}}function Pt(e){let{context:t,...n}=e;return r=>E(r,n)}function Rt(e,t,n){let r=e.context[t],o=n[r];if(!o)throw new Error(`No handler found for state: ${String(r)}`);return o(e.context)}function vt(e,t,n){return e.context[t]===n}function At(e,t){let n=e,r=null;async function o(i){r&&(r.abort(),r=null);let a=n[i.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(i.type)}' on current state.`);let s=new AbortController;r=s;try{let l=await a.apply(n.context,[...i.args,{signal:s.signal}]);return s.signal.aborted||(n=l,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:o,stop:()=>{r&&(r.abort(),r=null)}}}var T=class{constructor(t){this.context=t}};function Ot(e,t){let{context:n,...r}=e;return E(t(n),r)}
@@ -128,6 +128,47 @@ function action(action2, transition) {
128
128
  return transition;
129
129
  }
130
130
  function guard(condition, transition, options = {}) {
131
+ const { onFail = "throw", errorMessage, description } = options;
132
+ const fullOptions = { ...options, onFail, errorMessage, description };
133
+ const guardedTransition = function(...args) {
134
+ const isMachine = typeof this === "object" && "context" in this;
135
+ const ctx = isMachine ? this.context : this;
136
+ const conditionResult = condition(ctx, ...args);
137
+ if (conditionResult) {
138
+ const contextForTransition = isMachine ? this.context : this;
139
+ return transition.apply(contextForTransition, args);
140
+ } else {
141
+ if (onFail === "throw") {
142
+ const message = errorMessage || "Guard condition failed";
143
+ throw new Error(message);
144
+ } else if (onFail === "ignore") {
145
+ if (isMachine) {
146
+ return this;
147
+ } else {
148
+ throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.');
149
+ }
150
+ } else if (typeof onFail === "function") {
151
+ if (isMachine) {
152
+ return onFail.apply(this, args);
153
+ } else {
154
+ throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.");
155
+ }
156
+ } else {
157
+ return onFail;
158
+ }
159
+ }
160
+ };
161
+ Object.defineProperty(guardedTransition, "__guard", { value: true, enumerable: false });
162
+ Object.defineProperty(guardedTransition, "condition", { value: condition, enumerable: false });
163
+ Object.defineProperty(guardedTransition, "transition", { value: transition, enumerable: false });
164
+ Object.defineProperty(guardedTransition, "options", { value: fullOptions, enumerable: false });
165
+ attachRuntimeMeta(guardedTransition, {
166
+ description: description || "Synchronous guarded transition",
167
+ guards: [{ name: "runtime_guard", description: description || "Synchronous condition check" }]
168
+ });
169
+ return guardedTransition;
170
+ }
171
+ function guardAsync(condition, transition, options = {}) {
131
172
  const { onFail = "throw", errorMessage, description } = options;
132
173
  const fullOptions = { ...options, onFail, errorMessage, description };
133
174
  const guardedTransition = async function(...args) {
@@ -183,6 +224,21 @@ function whenGuard(condition) {
183
224
  }
184
225
  };
185
226
  }
227
+ function whenGuardAsync(condition) {
228
+ return {
229
+ /**
230
+ * Define the transition to execute when the condition passes.
231
+ * Returns a guarded transition that can optionally have an else clause.
232
+ */
233
+ do(transition) {
234
+ const guarded2 = guardAsync(condition, transition);
235
+ guarded2.else = function(fallback) {
236
+ return guardAsync(condition, transition, { onFail: fallback });
237
+ };
238
+ return guarded2;
239
+ }
240
+ };
241
+ }
186
242
  function metadata(_meta, value) {
187
243
  return value;
188
244
  }
@@ -316,6 +372,36 @@ function extractFromCallExpression(call2, verbose = false) {
316
372
  }
317
373
  }
318
374
  break;
375
+ case "guard":
376
+ if (args[2]) {
377
+ const options = parseObjectLiteral(args[2]);
378
+ if (options.description) {
379
+ metadata2.description = options.description;
380
+ }
381
+ }
382
+ metadata2.guards = [{ name: "runtime_guard", description: metadata2.description || "Synchronous condition check" }];
383
+ if (args[1] && Node.isCallExpression(args[1])) {
384
+ const nested = extractFromCallExpression(args[1], verbose);
385
+ if (nested) {
386
+ Object.assign(metadata2, nested);
387
+ }
388
+ }
389
+ break;
390
+ case "guardAsync":
391
+ if (args[2]) {
392
+ const options = parseObjectLiteral(args[2]);
393
+ if (options.description) {
394
+ metadata2.description = options.description;
395
+ }
396
+ }
397
+ metadata2.guards = [{ name: "runtime_guard_async", description: metadata2.description || "Asynchronous condition check" }];
398
+ if (args[1] && Node.isCallExpression(args[1])) {
399
+ const nested = extractFromCallExpression(args[1], verbose);
400
+ if (nested) {
401
+ Object.assign(metadata2, nested);
402
+ }
403
+ }
404
+ break;
319
405
  default:
320
406
  return null;
321
407
  }
@@ -557,6 +643,37 @@ function generateChart() {
557
643
  process.exit(1);
558
644
  }
559
645
  }
646
+ var ADVANCED_CONFIG_EXAMPLES = {
647
+ hierarchical: {
648
+ input: "examples/dashboardMachine.ts",
649
+ id: "dashboard",
650
+ classes: ["DashboardMachine", "LoggedOutMachine"],
651
+ initialState: "DashboardMachine",
652
+ children: {
653
+ contextProperty: "child",
654
+ initialState: "ViewingChildMachine",
655
+ classes: ["ViewingChildMachine", "EditingChildMachine"]
656
+ }
657
+ },
658
+ parallel: {
659
+ input: "examples/editorMachine.ts",
660
+ id: "editor",
661
+ parallel: {
662
+ regions: [
663
+ {
664
+ name: "fontWeight",
665
+ initialState: "NormalWeight",
666
+ classes: ["NormalWeight", "BoldWeight"]
667
+ },
668
+ {
669
+ name: "textDecoration",
670
+ initialState: "NoDecoration",
671
+ classes: ["NoDecoration", "UnderlineState"]
672
+ }
673
+ ]
674
+ }
675
+ }
676
+ };
560
677
  if (__require.main === module) {
561
678
  generateChart();
562
679
  }
@@ -2040,6 +2157,7 @@ function next(m, update) {
2040
2157
  return createMachine(update(context), transitions);
2041
2158
  }
2042
2159
  export {
2160
+ ADVANCED_CONFIG_EXAMPLES,
2043
2161
  BoundMachine,
2044
2162
  META_KEY,
2045
2163
  MachineBase,
@@ -2081,6 +2199,7 @@ export {
2081
2199
  generateChart,
2082
2200
  generateStatechart,
2083
2201
  guard,
2202
+ guardAsync,
2084
2203
  guarded,
2085
2204
  hasState,
2086
2205
  inDevelopment,
@@ -2110,6 +2229,7 @@ export {
2110
2229
  when,
2111
2230
  whenContext,
2112
2231
  whenGuard,
2232
+ whenGuardAsync,
2113
2233
  withAnalytics,
2114
2234
  withDebugging,
2115
2235
  withErrorReporting,