@doeixd/machine 0.0.7 → 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.
- package/README.md +130 -272
- package/dist/cjs/development/index.js +1121 -18
- package/dist/cjs/development/index.js.map +4 -4
- package/dist/cjs/production/index.js +5 -5
- package/dist/esm/development/index.js +1121 -18
- package/dist/esm/development/index.js.map +4 -4
- package/dist/esm/production/index.js +5 -5
- package/dist/types/extract.d.ts.map +1 -1
- package/dist/types/index.d.ts +64 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/middleware.d.ts +1048 -0
- package/dist/types/middleware.d.ts.map +1 -0
- package/dist/types/primitives.d.ts +205 -3
- package/dist/types/primitives.d.ts.map +1 -1
- package/dist/types/runtime-extract.d.ts.map +1 -1
- package/dist/types/utils.d.ts +111 -6
- package/dist/types/utils.d.ts.map +1 -1
- package/package.json +10 -7
- package/scripts/extract-statechart.ts +351 -0
- package/src/adapters.ts +407 -0
- package/src/extract.ts +60 -20
- package/src/index.ts +201 -8
- package/src/middleware.ts +2325 -0
- package/src/primitives.ts +454 -3
- package/src/runtime-extract.ts +15 -0
- package/src/utils.ts +221 -6
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var de=(t,e)=>{for(var n in e)w(t,n,{get:e[n],enumerable:!0})},Me=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xe(e))!ye.call(t,r)&&r!==n&&w(t,r,{get:()=>e[r],enumerable:!(i=ue(e,r))||i.enumerable});return t};var fe=t=>Me(w({},"__esModule",{value:!0}),t);var De={};de(De,{BoundMachine:()=>S,META_KEY:()=>U,MachineBase:()=>y,MultiMachineBase:()=>v,RUNTIME_META:()=>h,action:()=>H,bindTransitions:()=>L,call:()=>le,createAsyncMachine:()=>ke,createEnsemble:()=>Ce,createEvent:()=>oe,createFetchMachine:()=>we,createFlow:()=>G,createMachine:()=>f,createMachineBuilder:()=>ve,createMachineFactory:()=>Fe,createMultiMachine:()=>Ee,createMutableMachine:()=>be,createParallelMachine:()=>$,createRunner:()=>re,delegateToChild:()=>Se,describe:()=>J,extendTransitions:()=>Re,extractFromInstance:()=>ne,extractFunctionMetadata:()=>R,extractMachine:()=>E,extractMachines:()=>ee,extractStateNode:()=>b,generateChart:()=>P,generateStatechart:()=>te,guarded:()=>Y,hasState:()=>je,invoke:()=>X,isState:()=>ie,logState:()=>ce,matchMachine:()=>Ne,mergeContext:()=>ae,metadata:()=>Q,next:()=>Ke,overrideTransitions:()=>Pe,pipeTransitions:()=>se,run:()=>k,runAsync:()=>V,runMachine:()=>Oe,runSequence:()=>W,runWithDebug:()=>B,runWithEnsemble:()=>me,runWithRunner:()=>Te,setContext:()=>p,step:()=>I,stepAsync:()=>z,toggle:()=>Ae,transitionTo:()=>q,yieldMachine:()=>_});module.exports=fe(De);function k(t,e){let n=t(e),i=e;for(;;){let{value:r,done:o}=n.next(i);if(o)return r;i=r}}function I(t){return function*(){return yield t}()}function _(t){return t}function W(t,e){return e.reduce((n,i)=>k(i,n),t)}function G(t){return t}function B(t,e,n=(i,r)=>{console.log(`Step ${i}:`,r.context)}){let i=t(e),r=e,o=0;for(n(o,r);;){let{value:a,done:s}=i.next(r);if(s)return console.log("Final:",a),a;r=a,o++,n(o,r)}}async function V(t,e){let n=t(e),i=e;for(;;){let{value:r,done:o}=await n.next(i);if(o)return r;i=r}}async function*z(t){return yield t}var U=Symbol("MachineMeta"),h=Symbol("__machine_runtime_meta__");function C(t,e){let n=t[h]||{},i={...n,...e};e.guards&&n.guards?i.guards=[...e.guards,...n.guards]:e.guards&&(i.guards=[...e.guards]),e.actions&&n.actions?i.actions=[...e.actions,...n.actions]:e.actions&&(i.actions=[...e.actions]),Object.defineProperty(t,h,{value:i,enumerable:!1,writable:!1,configurable:!0})}function q(t,e){return C(e,{target:t.name||t.toString()}),e}function J(t,e){return C(e,{description:t}),e}function Y(t,e){return C(e,{guards:[t]}),e}function X(t,e){return C(e,{invoke:{src:t.src,onDone:t.onDone.name||t.onDone.toString(),onError:t.onError.name||t.onError.toString(),description:t.description}}),e}function H(t,e){return C(e,{actions:[t]}),e}function Q(t,e){return e}var c=require("ts-morph");function Z(t){return c.Node.isIdentifier(t)?t.getText():c.Node.isTypeOfExpression(t)?t.getExpression().getText():"unknown"}function m(t){if(!c.Node.isObjectLiteralExpression(t))return{};let e={};for(let n of t.getProperties())if(c.Node.isPropertyAssignment(n)){let i=n.getName(),r=n.getInitializer();r&&(c.Node.isStringLiteral(r)||c.Node.isNumericLiteral(r)?e[i]=r.getLiteralValue():r.getText()==="true"||r.getText()==="false"?e[i]=r.getText()==="true":c.Node.isIdentifier(r)?e[i]=r.getText():c.Node.isObjectLiteralExpression(r)?e[i]=m(r):c.Node.isArrayLiteralExpression(r)&&(e[i]=r.getElements().map(o=>c.Node.isObjectLiteralExpression(o)?m(o):o.getText())))}return e}function ge(t){if(!c.Node.isObjectLiteralExpression(t))return{};let e={};for(let n of t.getProperties())if(c.Node.isPropertyAssignment(n)){let i=n.getName(),r=n.getInitializer();if(!r)continue;i==="onDone"||i==="onError"?e[i]=Z(r):c.Node.isStringLiteral(r)?e[i]=r.getLiteralValue():c.Node.isIdentifier(r)&&(e[i]=r.getText())}return e}function T(t,e=!1){if(!c.Node.isCallExpression(t))return null;let n=t.getExpression(),i=c.Node.isIdentifier(n)?n.getText():null;if(!i)return null;let r={},o=t.getArguments();switch(i){case"transitionTo":o[0]&&(r.target=Z(o[0]));break;case"describe":if(o[0]&&c.Node.isStringLiteral(o[0])&&(r.description=o[0].getLiteralValue()),o[1]&&c.Node.isCallExpression(o[1])){let a=T(o[1],e);a&&Object.assign(r,a)}break;case"guarded":if(o[0]){let a=m(o[0]);Object.keys(a).length>0&&(r.guards=[a])}if(o[1]&&c.Node.isCallExpression(o[1])){let a=T(o[1],e);a&&Object.assign(r,a)}break;case"invoke":if(o[0]){let a=ge(o[0]);Object.keys(a).length>0&&(r.invoke=a)}break;case"action":if(o[0]){let a=m(o[0]);Object.keys(a).length>0&&(r.actions=[a])}if(o[1]&&c.Node.isCallExpression(o[1])){let a=T(o[1],e);a&&Object.assign(r,a)}break;default:return null}return Object.keys(r).length>0?r:null}function he(t,e=!1){if(!c.Node.isPropertyDeclaration(t))return e&&console.error(" ⚠️ Not a property declaration"),null;let n=t.getInitializer();if(!n)return e&&console.error(" ⚠️ No initializer"),null;if(!c.Node.isCallExpression(n))return e&&console.error(" ⚠️ Initializer is not a call expression"),null;let i=T(n,e);return i&&e&&console.error(" ✅ Extracted metadata:",JSON.stringify(i,null,2)),i}function F(t,e=!1){let n={on:{}},i=t.getDeclarations()[0];if(!i||!c.Node.isClassDeclaration(i))return e&&console.error(`⚠️ Warning: Could not get class declaration for ${t.getName()}`),n;let r=t.getName();e&&console.error(` Analyzing state: ${r}`);for(let o of i.getInstanceMembers()){let a=o.getName();e&&console.error(` Checking member: ${a}`);let s=he(o,e);if(!s)continue;e&&console.error(` Found transition: ${a}`);let{invoke:l,actions:u,guards:x,...d}=s;if(l&&(n.invoke||(n.invoke=[]),n.invoke.push({src:l.src,onDone:{target:l.onDone},onError:{target:l.onError},description:l.description}),e&&console.error(` → Invoke: ${l.src}`)),d.target){let M={target:d.target};d.description&&(M.description=d.description),x&&(M.cond=x.map(A=>A.name).join(" && "),e&&console.error(` → Guard: ${M.cond}`)),u&&u.length>0&&(M.actions=u.map(A=>A.name),e&&console.error(` → Actions: ${M.actions.join(", ")}`)),n.on[a]=M,e&&console.error(` → Target: ${d.target}`)}}return n}function pe(t,e,n,i,r=!1){let o=F(e,r);if(i){r&&console.error(` 👪 Analyzing children for state: ${t}`),o.initial=i.initialState,o.states={};for(let a of i.classes){let s=n.getClass(a);if(s){let l=s.getSymbolOrThrow();o.states[a]=F(l,r)}else console.warn(`⚠️ Warning: Child class '${a}' not found.`)}}return o}function E(t,e,n=!1){n&&(console.error(`
|
|
2
|
-
🔍 Analyzing machine: ${
|
|
3
|
-
📊 Starting statechart extraction`),console.error(` Machines to extract: ${
|
|
4
|
-
✅ Extraction complete: ${
|
|
5
|
-
`);let e=new c.Project;e.addSourceFilesAtPaths("src/**/*.ts"),e.addSourceFilesAtPaths("examples/**/*.ts");try{let n=E(t,e,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}require.main===module&&P();function R(t){return typeof t!="function"?null:t[h]||null}function b(t){let e={on:{}},n=[];for(let i in t){let r=t[i];if(typeof r!="function")continue;let o=R(r);if(o&&(o.invoke&&n.push({src:o.invoke.src,onDone:{target:o.invoke.onDone},onError:{target:o.invoke.onError},description:o.invoke.description}),o.target)){let a={target:o.target};o.description&&(a.description=o.description),o.guards&&o.guards.length>0&&(a.cond=o.guards.map(s=>s.name).join(" && ")),o.actions&&o.actions.length>0&&(a.actions=o.actions.map(s=>s.name)),e.on[i]=a}}return n.length>0&&(e.invoke=n),e}function te(t,e){let n={id:e.id,initial:e.initial,states:{}};e.description&&(n.description=e.description);for(let[i,r]of Object.entries(t))n.states[i]=b(r);return n}function ne(t,e){let n=e.stateName||t.constructor.name||"State";return{id:e.id,initial:n,states:{[n]:b(t)}}}function re(t,e){let n=t,i=s=>{n=s,e==null||e(s)},{context:r,...o}=t,a=new Proxy({},{get(s,l){let u=n[l];if(typeof u=="function")return(...x)=>{let d=u.apply(n.context,x),M=Object.assign({context:d.context},o);return i(M),M}}});return{get state(){return n},get context(){return n.context},actions:a,setState:i}}function Ce(t,e,n){let i=()=>{let o=t.getContext(),a=n(o),s=e[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(o)},r=new Proxy({},{get(o,a){let s=i(),l=s[a];if(typeof l!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...u)=>l.apply(s.context,u)}});return{get context(){return t.getContext()},get state(){return i()},actions:r}}function Te(t,e){let n=re(e),i=t(n),r=i.next();for(;!r.done;)r=i.next();return r.value}function me(t,e){let n=t(e),i=n.next();for(;!i.done;)i=n.next();return i.value}var v=class{constructor(e){this.store=e}get context(){return this.store.getContext()}setContext(e){this.store.setContext(e)}};function Ee(t,e){let n=new t(e);return new Proxy({},{get(i,r){let o=e.getContext();if(r in o)return o[r];let a=n[r];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(i,r,o){let a=e.getContext();if(r in a){let s={...a,[r]:o};return e.setContext(s),!0}return!1},has(i,r){let o=e.getContext();return r in o||typeof n[r]=="function"},ownKeys(i){let r=e.getContext(),o=Object.keys(r),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...o,...a]))},getOwnPropertyDescriptor(i,r){let o=e.getContext();if(r in o||typeof n[r]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function be(t,e,n){let i=()=>{let r=n(t),o=e[r];if(!o)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(r)}".`);return o(t)};return new Proxy(t,{get(r,o,a){if(o in r)return r[o];let s=i(),l=s[o];if(typeof l=="function")return(...u)=>{let x=l.apply(s.context,u);if(typeof x!="object"||x===null){console.warn(`[MutableMachine] Transition "${String(o)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(r).forEach(d=>delete r[d]),Object.assign(r,x)}},set(r,o,a,s){return r[o]=a,!0},has(r,o){let a=i();return o in r||typeof a[o]=="function"}})}function Se(t){return function(...e){let n=this.context.child;if(typeof n[t]=="function"){let i=n[t](...e);return p(this,{...this.context,child:i})}return this}}function Ae(t){return function(){return typeof this.context[t]!="boolean"&&console.warn(`[toggle primitive] Property '${String(t)}' is not a boolean. Toggling may have unexpected results.`),p(this,{...this.context,[t]:!this.context[t]})}}var N=class extends y{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new g(this.config,n!=null?n:this.config.initialParams,1)}},g=class extends y{constructor(n,i,r){super({status:"loading",abortController:new AbortController,attempts:r});this.config=n;this.params=i;this.succeed=n=>{var i,r;return(r=(i=this.config).onSuccess)==null||r.call(i,n),new O(this.config,{status:"success",data:n})};this.fail=n=>{var r,o,a;let i=(r=this.config.maxRetries)!=null?r:3;return this.context.attempts<i?new j(this.config,this.params,n,this.context.attempts):((a=(o=this.config).onError)==null||a.call(o,n),new K(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new D(this.config));this.execute()}async execute(){}},j=class extends y{constructor(n,i,r,o){super({status:"retrying",error:r,attempts:o});this.config=n;this.params=i;this.retry=n=>new g(this.config,n!=null?n:this.params,this.context.attempts+1)}},O=class extends y{constructor(n,i){super(i);this.config=n;this.refetch=n=>new g(this.config,n!=null?n:this.config.initialParams,1)}},K=class extends y{constructor(n,i){super(i);this.config=n;this.retry=n=>new g(this.config,n!=null?n:this.config.initialParams,1)}},D=class extends y{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new g(this.config,n!=null?n:this.config.initialParams,1)}};function we(t){return new N(t)}function $(t,e){let n={...t.context,...e.context},i={...t},r={...e};delete i.context,delete r.context;let o={};for(let a in i){let s=i[a];o[a]=(...l)=>{let u=s.apply(t.context,l);return $(u,e)}}for(let a in r){let s=r[a];o[a]=(...l)=>{let u=s.apply(e.context,l);return $(t,u)}}return{context:n,...o}}function ie(t,e){return t instanceof e}function oe(t,...e){return{type:t,args:e}}function ae(t,e){return p(t,n=>({...n,...e}))}async function se(t,...e){let n=t;for(let i of e)n=await i(n);return n}function ce(t,e){return e?console.log(e,t.context):console.log(t.context),t}function le(t,e,...n){return t.apply(e,n)}function L(t){return new Proxy(t,{get(e,n){let i=e[n];return typeof i=="function"?function(...r){let o=i.apply(e.context,r);return o&&typeof o=="object"&&"context"in o?L(o):o}:i}})}var S=class t{constructor(e){return this.wrappedMachine=e,new Proxy(this,{get:(n,i)=>{if(i==="wrappedMachine"||i==="context")return Reflect.get(n,i);let r=this.wrappedMachine[i];return typeof r=="function"?(...o)=>{let a=r.apply(this.wrappedMachine.context,o);return a&&typeof a=="object"&&"context"in a?new t(a):a}:r}})}get context(){return this.wrappedMachine.context}};function f(t,e){return Object.assign({context:t},e)}function ke(t,e){return Object.assign({context:t},e)}function Fe(){return t=>{let e=Object.fromEntries(Object.entries(t).map(([n,i])=>[n,function(...r){let o=i(this,...r);return f(o,e)}]));return n=>f(n,e)}}function p(t,e){let{context:n,...i}=t,r=typeof e=="function"?e(n):e;return f(r,i)}function Pe(t,e){let{context:n,...i}=t,r={...i,...e};return f(n,r)}function Re(t,e){let{context:n,...i}=t,r={...i,...e};return f(n,r)}function ve(t){let{context:e,...n}=t;return i=>f(i,n)}function Ne(t,e,n){let i=t.context[e],r=n[i];if(!r)throw new Error(`No handler found for state: ${String(i)}`);return r(t.context)}function je(t,e,n){return t.context[e]===n}function Oe(t,e){let n=t;async function i(r){let o=n[r.type];if(typeof o!="function")throw new Error(`[Machine] Unknown event type '${String(r.type)}' on current state.`);return n=await o.apply(n.context,r.args),e==null||e(n),n}return{get state(){return n.context},dispatch:i}}var y=class{constructor(e){this.context=e}};function Ke(t,e){let{context:n,...i}=t;return f(e(n),i)}
|
|
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
|
+
📊 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 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)}
|