@doeixd/machine 0.0.11 → 0.0.13
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 +23 -0
- package/dist/cjs/development/index.js +62 -0
- package/dist/cjs/development/index.js.map +4 -4
- package/dist/cjs/production/index.js +4 -4
- package/dist/esm/development/index.js +62 -0
- package/dist/esm/development/index.js.map +4 -4
- package/dist/esm/production/index.js +3 -3
- package/dist/types/functional-combinators.d.ts +173 -0
- package/dist/types/functional-combinators.d.ts.map +1 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/multi.d.ts +14 -0
- package/dist/types/multi.d.ts.map +1 -1
- package/dist/types/utils.d.ts +63 -0
- package/dist/types/utils.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/functional-combinators.ts +340 -0
- package/src/index.ts +13 -1
- package/src/multi.ts +36 -0
- package/src/utils.ts +74 -0
|
@@ -1,5 +1,5 @@
|
|
|
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=
|
|
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=
|
|
1
|
+
"use strict";var I=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var yt=Object.prototype.hasOwnProperty;var ft=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},Mt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ut(t))!yt.call(e,o)&&o!==n&&I(e,o,{get:()=>t[o],enumerable:!(r=dt(t,o))||r.enumerable});return e};var xt=e=>Mt(I({},"__esModule",{value:!0}),e);var _t={};ft(_t,{ADVANCED_CONFIG_EXAMPLES:()=>Ct,BoundMachine:()=>G,META_KEY:()=>Ce,MachineBase:()=>E,MultiMachineBase:()=>q,RUNTIME_META:()=>P,action:()=>Ee,bindTransitions:()=>se,branch:()=>Xe,call:()=>it,chain:()=>Ie,combine:()=>Ye,combineFactories:()=>Ot,compose:()=>Ge,composeTyped:()=>N,createAsyncMachine:()=>At,createCustomMiddleware:()=>He,createEnsemble:()=>ke,createEnsembleFactory:()=>mt,createEvent:()=>et,createFetchMachine:()=>Rt,createFlow:()=>xe,createFunctionalMachine:()=>le,createMachine:()=>w,createMachineBuilder:()=>kt,createMachineFactory:()=>vt,createMiddleware:()=>T,createMiddlewareRegistry:()=>Ue,createMultiMachine:()=>bt,createMutableMachine:()=>Et,createParallelMachine:()=>te,createPipeline:()=>Ve,createRunner:()=>Oe,createTransition:()=>ot,createTransitionExtender:()=>ce,createTransitionFactory:()=>at,delegateToChild:()=>Ft,describe:()=>we,extendTransitions:()=>de,extractFromInstance:()=>je,extractFunctionMetadata:()=>J,extractMachine:()=>K,extractMachines:()=>Ae,extractStateNode:()=>D,generateChart:()=>U,generateStatechart:()=>ve,guard:()=>$,guardAsync:()=>_,guarded:()=>Te,hasState:()=>zt,inDevelopment:()=>Je,invoke:()=>be,isConditionalMiddleware:()=>Qe,isMiddlewareFn:()=>ae,isState:()=>Ze,logState:()=>rt,matchMachine:()=>Nt,mergeContext:()=>tt,metadata:()=>Re,next:()=>$t,overrideTransitions:()=>jt,pipeTransitions:()=>nt,run:()=>L,runAsync:()=>pe,runMachine:()=>Bt,runSequence:()=>Me,runWithDebug:()=>he,runWithEnsemble:()=>Tt,runWithRunner:()=>wt,setContext:()=>j,state:()=>st,step:()=>ye,stepAsync:()=>ge,toggle:()=>St,transitionTo:()=>me,when:()=>W,whenContext:()=>qe,whenGuard:()=>Fe,whenGuardAsync:()=>Se,withAnalytics:()=>Be,withDebugging:()=>Le,withErrorReporting:()=>Ke,withHistory:()=>re,withLogging:()=>ze,withPerformanceMonitoring:()=>De,withPermissions:()=>_e,withRetry:()=>We,withSnapshot:()=>oe,withTimeTravel:()=>ie,withValidation:()=>$e,yieldMachine:()=>fe});module.exports=xt(_t);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 ye(e){return function*(){return yield e}()}function fe(e){return e}function Me(e,t){return t.reduce((n,r)=>L(r,n),e)}function xe(e){return e}function he(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 pe(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*ge(e){return yield e}var Ce=Symbol("MachineMeta"),P=Symbol("__machine_runtime_meta__");function F(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 me(e,t){return F(t,{target:e.name||e.toString()}),t}function we(e,t){return F(t,{description:e}),t}function Te(e,t){return F(t,{guards:[e]}),t}function be(e,t){return F(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function Ee(e,t){return F(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}),F(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}),F(s,{description:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}function Fe(e){return{do(t){let n=$(e,t);return n.else=function(r){return $(e,t,{onFail:r})},n}}}function Se(e){return{do(t){let n=_(e,t);return n.else=function(r){return _(e,t,{onFail:r})},n}}}function Re(e,t){return t}var g=require("ts-morph");function Pe(e){return g.Node.isIdentifier(e)?e.getText():g.Node.isTypeOfExpression(e)?e.getExpression().getText():"unknown"}function v(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]=v(o):g.Node.isArrayLiteralExpression(o)&&(t[r]=o.getElements().map(i=>g.Node.isObjectLiteralExpression(i)?v(i):i.getText())))}return t}function ht(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]=Pe(o):g.Node.isStringLiteral(o)?t[r]=o.getLiteralValue():g.Node.isIdentifier(o)&&(t[r]=o.getText())}return t}function A(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=Pe(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=A(i[1],t);a&&Object.assign(o,a)}break;case"guarded":if(i[0]){let a=v(i[0]);Object.keys(a).length>0&&(o.guards=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=A(i[1],t);a&&Object.assign(o,a)}break;case"invoke":if(i[0]){let a=ht(i[0]);Object.keys(a).length>0&&(o.invoke=a)}break;case"action":if(i[0]){let a=v(i[0]);Object.keys(a).length>0&&(o.actions=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=A(i[1],t);a&&Object.assign(o,a)}break;case"guard":if(i[2]){let a=v(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=A(i[1],t);a&&Object.assign(o,a)}break;case"guardAsync":if(i[2]){let a=v(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=A(i[1],t);a&&Object.assign(o,a)}break;default:return null}return Object.keys(o).length>0?o:null}function pt(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=A(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=pt(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 gt(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 K(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=gt(i,s,r,c?e.children:void 0,n);o.states[i]=l}return n&&console.error(` ✅ Extracted ${e.classes.length} states`),o}function Ae(e){var o;let t=(o=e.verbose)!=null?o:!1;t&&(console.error(`
|
|
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=K(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
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)}
|
|
5
|
+
`);let t=new g.Project;t.addSourceFilesAtPaths("src/**/*.ts"),t.addSourceFilesAtPaths("examples/**/*.ts");try{let n=K(e,t,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}var Ct={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[P]||null}function D(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 ve(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]=D(o);return n}function je(e,t){let n=t.stateName||e.constructor.name||"State";return{id:t.id,initial:n,states:{[n]:D(e)}}}function Oe(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 ke(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){return function(r){return ke(e,r,t)}}function wt(e,t){let n=Oe(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function Tt(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 bt(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 Et(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 Ft(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return j(this,{...this.context,child:r})}return this}}function St(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.`),j(this,{...this.context,[e]:!this.context[e]})}}var Y=class extends E{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 E{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 E{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)}},Q=class extends E{constructor(n,r){super(r);this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},Z=class extends E{constructor(n,r){super(r);this.config=n;this.retry=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},ee=class extends E{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}};function Rt(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 Ne=Symbol("CANCEL");function T(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]=Pt(a,s,e,t,r)}return i}function Pt(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===Ne)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)===Ne)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 ze(e,t={}){let{logger:n=console.log,includeContext:r=!0,includeArgs:o=!0}=t;return T(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 Be(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!0}=n;return T(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 $e(e,t,n){return T(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 _e(e,t,n){return T(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 T(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 De(e,t){let n=new Map;return T(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 We(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=T(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=T(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=T(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 O=h[m];if(typeof O=="function"&&!m.startsWith("_")&&m!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(m)){let ct=O;h[m]=function(...lt){let z=h.context,k=ct.apply(this,lt);if(k&&typeof k=="object"&&"context"in k){let B=k.context;if(!(a&&!a(m))){let ue=!0;if(i&&(ue=JSON.stringify(z)!==JSON.stringify(B)),ue){let R={id:`snapshot-${M++}`,transitionName:m,before:{...z},after:{...B},timestamp:Date.now()};if(r)try{R.serializedBefore=r.serialize(z),R.serializedAfter=r.serialize(B)}catch(H){console.error("Failed to serialize snapshot:",H)}if(o)try{R.diff=o(z,B)}catch(H){console.error("Failed to capture snapshot:",H)}u.push(R),n&&u.length>n&&u.shift(),s==null||s(R)}}}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(O){throw console.error(`Replay failed at step ${h}:`,O),O}}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 Ge(e,...t){return t.reduce((n,r)=>r(n),e)}function He(e,t){return n=>T(n,e,t)}function N(e,...t){return t.reduce((n,r)=>r(n),e)}function Ie(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 Le(e){return ie(oe(re(e)))}function Ve(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 Ue(){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 Je(e){return W(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function qe(e,t,n){return W(n,r=>r.context[e]===t)}function Ye(...e){return t=>N(t,...e)}function Xe(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 Qe(e){return e!==null&&"middleware"in e&&"when"in e&&ae(e.middleware)&&typeof e.when=="function"}function Ze(e,t){return e instanceof t}function et(e,...t){return{type:e,args:t}}function tt(e,t){return j(e,n=>({...n,...t}))}async function nt(e,...t){let n=e;for(let r of t)n=await r(n);return n}function rt(e,t){return t?console.log(t,e.context):console.log(e.context),e}function ot(e,t){return function(...n){let r=t(this.context,...n);return w(r,e())}}function it(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 at(){return function(t){return function(...n){let r=t(this.context,...n);return w(r,this)}}}function ce(e){return{machine:e,addTransition:function(t,n){let r=function(...i){let a=n(this.context,...i);return w(a,this)},o=de(e,{[t]:r});return ce(o)}}}function le(e){return function(n){let r={},o=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,function(...s){let c=a(this.context,...s);return w(c,r)}]));return Object.assign(r,o),w(e,r)}}function st(e,t){return t!==void 0?w(e,t):le(e)}function w(e,t){let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function At(e,t){return Object.assign({context:e},t)}function vt(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...o){let i=r(this,...o);return w(i,t)}]));return n=>w(n,t)}}function j(e,t){let{context:n,...r}=e,o=typeof t=="function"?t(n):t;return w(o,r)}function jt(e,t){let{context:n,...r}=e,o={...r,...t};return w(n,o)}function de(e,t){let{context:n,...r}=e,o={...r,...t};return w(n,o)}function Ot(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 w(i,u)}}function kt(e){let{context:t,...n}=e;return r=>w(r,n)}function Nt(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 zt(e,t,n){return e.context[t]===n}function Bt(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 E=class{constructor(t){this.context=t}};function $t(e,t){let{context:n,...r}=e;return w(t(n),r)}
|
|
@@ -832,6 +832,11 @@ function createEnsemble(store, factories, getDiscriminant) {
|
|
|
832
832
|
actions
|
|
833
833
|
};
|
|
834
834
|
}
|
|
835
|
+
function createEnsembleFactory(store, getDiscriminant) {
|
|
836
|
+
return function withFactories(factories) {
|
|
837
|
+
return createEnsemble(store, factories, getDiscriminant);
|
|
838
|
+
};
|
|
839
|
+
}
|
|
835
840
|
function runWithRunner(flow, initialMachine) {
|
|
836
841
|
const runner = createRunner(initialMachine);
|
|
837
842
|
const generator = flow(runner);
|
|
@@ -1981,6 +1986,12 @@ function logState(machine, label) {
|
|
|
1981
1986
|
}
|
|
1982
1987
|
return machine;
|
|
1983
1988
|
}
|
|
1989
|
+
function createTransition(getTransitions, transformer) {
|
|
1990
|
+
return function(...args) {
|
|
1991
|
+
const nextContext = transformer(this.context, ...args);
|
|
1992
|
+
return createMachine(nextContext, getTransitions());
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1984
1995
|
function call(fn, context, ...args) {
|
|
1985
1996
|
return fn.apply(context, args);
|
|
1986
1997
|
}
|
|
@@ -2028,6 +2039,51 @@ var BoundMachine = class _BoundMachine {
|
|
|
2028
2039
|
}
|
|
2029
2040
|
};
|
|
2030
2041
|
|
|
2042
|
+
// src/functional-combinators.ts
|
|
2043
|
+
function createTransitionFactory() {
|
|
2044
|
+
return function createTransition2(transformer) {
|
|
2045
|
+
return function(...args) {
|
|
2046
|
+
const nextContext = transformer(this.context, ...args);
|
|
2047
|
+
return createMachine(nextContext, this);
|
|
2048
|
+
};
|
|
2049
|
+
};
|
|
2050
|
+
}
|
|
2051
|
+
function createTransitionExtender(machine) {
|
|
2052
|
+
return {
|
|
2053
|
+
machine,
|
|
2054
|
+
addTransition: function(name, transformer) {
|
|
2055
|
+
const transitionFn = function(...args) {
|
|
2056
|
+
const nextContext = transformer(this.context, ...args);
|
|
2057
|
+
return createMachine(nextContext, this);
|
|
2058
|
+
};
|
|
2059
|
+
const newMachine = extendTransitions(machine, { [name]: transitionFn });
|
|
2060
|
+
return createTransitionExtender(newMachine);
|
|
2061
|
+
}
|
|
2062
|
+
};
|
|
2063
|
+
}
|
|
2064
|
+
function createFunctionalMachine(initialContext) {
|
|
2065
|
+
return function withTransitions(transformers) {
|
|
2066
|
+
const transitions = {};
|
|
2067
|
+
const machineTransitions = Object.fromEntries(
|
|
2068
|
+
Object.entries(transformers).map(([key, transformer]) => [
|
|
2069
|
+
key,
|
|
2070
|
+
function(...args) {
|
|
2071
|
+
const nextContext = transformer(this.context, ...args);
|
|
2072
|
+
return createMachine(nextContext, transitions);
|
|
2073
|
+
}
|
|
2074
|
+
])
|
|
2075
|
+
);
|
|
2076
|
+
Object.assign(transitions, machineTransitions);
|
|
2077
|
+
return createMachine(initialContext, transitions);
|
|
2078
|
+
};
|
|
2079
|
+
}
|
|
2080
|
+
function state(context, transitions) {
|
|
2081
|
+
if (transitions !== void 0) {
|
|
2082
|
+
return createMachine(context, transitions);
|
|
2083
|
+
}
|
|
2084
|
+
return createFunctionalMachine(context);
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2031
2087
|
// src/index.ts
|
|
2032
2088
|
function createMachine(context, fns) {
|
|
2033
2089
|
const transitions = "context" in fns ? Object.fromEntries(
|
|
@@ -2175,9 +2231,11 @@ export {
|
|
|
2175
2231
|
createAsyncMachine,
|
|
2176
2232
|
createCustomMiddleware,
|
|
2177
2233
|
createEnsemble,
|
|
2234
|
+
createEnsembleFactory,
|
|
2178
2235
|
createEvent,
|
|
2179
2236
|
createFetchMachine,
|
|
2180
2237
|
createFlow,
|
|
2238
|
+
createFunctionalMachine,
|
|
2181
2239
|
createMachine,
|
|
2182
2240
|
createMachineBuilder,
|
|
2183
2241
|
createMachineFactory,
|
|
@@ -2188,6 +2246,9 @@ export {
|
|
|
2188
2246
|
createParallelMachine,
|
|
2189
2247
|
createPipeline,
|
|
2190
2248
|
createRunner,
|
|
2249
|
+
createTransition,
|
|
2250
|
+
createTransitionExtender,
|
|
2251
|
+
createTransitionFactory,
|
|
2191
2252
|
delegateToChild,
|
|
2192
2253
|
describe,
|
|
2193
2254
|
extendTransitions,
|
|
@@ -2222,6 +2283,7 @@ export {
|
|
|
2222
2283
|
runWithEnsemble,
|
|
2223
2284
|
runWithRunner,
|
|
2224
2285
|
setContext,
|
|
2286
|
+
state,
|
|
2225
2287
|
step,
|
|
2226
2288
|
stepAsync,
|
|
2227
2289
|
toggle,
|