@doeixd/machine 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- var b=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(e,r)=>(typeof require!="undefined"?require:e)[r]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function E(t,e){let r=t(e),i=e;for(;;){let{value:n,done:o}=r.next(i);if(o)return n;i=n}}function N(t){return function*(){return yield t}()}function v(t){return t}function R(t,e){return e.reduce((r,i)=>E(i,r),t)}function O(t){return t}function P(t,e,r=(i,n)=>{console.log(`Step ${i}:`,n.context)}){let i=t(e),n=e,o=0;for(r(o,n);;){let{value:a,done:s}=i.next(n);if(s)return console.log("Final:",a),a;n=a,o++,r(o,n)}}async function K(t,e){let r=t(e),i=e;for(;;){let{value:n,done:o}=await r.next(i);if(o)return n;i=n}}async function*$(t){return yield t}var D=Symbol("MachineMeta"),M=Symbol("__machine_runtime_meta__");function g(t,e){let r=t[M]||{},i={...r,...e};e.guards&&r.guards?i.guards=[...e.guards,...r.guards]:e.guards&&(i.guards=[...e.guards]),e.actions&&r.actions?i.actions=[...e.actions,...r.actions]:e.actions&&(i.actions=[...e.actions]),Object.defineProperty(t,M,{value:i,enumerable:!1,writable:!1,configurable:!0})}function L(t,e){return g(e,{target:t.name||t.toString()}),e}function I(t,e){return g(e,{description:t}),e}function _(t,e){return g(e,{guards:[t]}),e}function W(t,e){return g(e,{invoke:{src:t.src,onDone:t.onDone.name||t.onDone.toString(),onError:t.onError.name||t.onError.toString(),description:t.description}}),e}function G(t,e){return g(e,{actions:[t]}),e}function V(t,e){return e}import{Project as A,Node as c}from"ts-morph";function k(t){return c.isIdentifier(t)?t.getText():c.isTypeOfExpression(t)?t.getExpression().getText():"unknown"}function h(t){if(!c.isObjectLiteralExpression(t))return{};let e={};for(let r of t.getProperties())if(c.isPropertyAssignment(r)){let i=r.getName(),n=r.getInitializer();n&&(c.isStringLiteral(n)||c.isNumericLiteral(n)?e[i]=n.getLiteralValue():n.getText()==="true"||n.getText()==="false"?e[i]=n.getText()==="true":c.isIdentifier(n)?e[i]=n.getText():c.isObjectLiteralExpression(n)?e[i]=h(n):c.isArrayLiteralExpression(n)&&(e[i]=n.getElements().map(o=>c.isObjectLiteralExpression(o)?h(o):o.getText())))}return e}function z(t){if(!c.isObjectLiteralExpression(t))return{};let e={};for(let r of t.getProperties())if(c.isPropertyAssignment(r)){let i=r.getName(),n=r.getInitializer();if(!n)continue;i==="onDone"||i==="onError"?e[i]=k(n):c.isStringLiteral(n)?e[i]=n.getLiteralValue():c.isIdentifier(n)&&(e[i]=n.getText())}return e}function p(t,e=!1){if(!c.isCallExpression(t))return null;let r=t.getExpression(),i=c.isIdentifier(r)?r.getText():null;if(!i)return null;let n={},o=t.getArguments();switch(i){case"transitionTo":o[0]&&(n.target=k(o[0]));break;case"describe":if(o[0]&&c.isStringLiteral(o[0])&&(n.description=o[0].getLiteralValue()),o[1]&&c.isCallExpression(o[1])){let a=p(o[1],e);a&&Object.assign(n,a)}break;case"guarded":if(o[0]){let a=h(o[0]);Object.keys(a).length>0&&(n.guards=[a])}if(o[1]&&c.isCallExpression(o[1])){let a=p(o[1],e);a&&Object.assign(n,a)}break;case"invoke":if(o[0]){let a=z(o[0]);Object.keys(a).length>0&&(n.invoke=a)}break;case"action":if(o[0]){let a=h(o[0]);Object.keys(a).length>0&&(n.actions=[a])}if(o[1]&&c.isCallExpression(o[1])){let a=p(o[1],e);a&&Object.assign(n,a)}break;default:return null}return Object.keys(n).length>0?n:null}function B(t,e=!1){if(!c.isPropertyDeclaration(t))return e&&console.error(" ⚠️ Not a property declaration"),null;let r=t.getInitializer();if(!r)return e&&console.error(" ⚠️ No initializer"),null;if(!c.isCallExpression(r))return e&&console.error(" ⚠️ Initializer is not a call expression"),null;let i=p(r,e);return i&&e&&console.error(" ✅ Extracted metadata:",JSON.stringify(i,null,2)),i}function U(t,e=!1){let r={on:{}},i=t.getDeclarations()[0];if(!i||!c.isClassDeclaration(i))return e&&console.error(`⚠️ Warning: Could not get class declaration for ${t.getName()}`),r;let n=t.getName();e&&console.error(` Analyzing state: ${n}`);for(let o of i.getInstanceMembers()){let a=o.getName();e&&console.error(` Checking member: ${a}`);let s=B(o,e);if(!s)continue;e&&console.error(` Found transition: ${a}`);let{invoke:u,actions:l,guards:f,...x}=s;if(u&&(r.invoke||(r.invoke=[]),r.invoke.push({src:u.src,onDone:{target:u.onDone},onError:{target:u.onError},description:u.description}),e&&console.error(` → Invoke: ${u.src}`)),x.target){let d={target:x.target};x.description&&(d.description=x.description),f&&(d.cond=f.map(C=>C.name).join(" && "),e&&console.error(` → Guard: ${d.cond}`)),l&&l.length>0&&(d.actions=l.map(C=>C.name),e&&console.error(` → Actions: ${d.actions.join(", ")}`)),r.on[a]=d,e&&console.error(` → Target: ${x.target}`)}}return r}function m(t,e,r=!1){r&&(console.error(`
2
- 🔍 Analyzing machine: ${t.id}`),console.error(` Source: ${t.input}`));let i=e.getSourceFile(t.input);if(!i)throw new Error(`Source file not found: ${t.input}`);let n={id:t.id,initial:t.initialState,states:{}};t.description&&(n.description=t.description);for(let o of t.classes){let a=i.getClass(o);if(!a){console.warn(`⚠️ Warning: Class '${o}' not found in '${t.input}'. Skipping.`);continue}let s=a.getSymbolOrThrow(),u=U(s,r);n.states[o]=u}return r&&console.error(` ✅ Extracted ${t.classes.length} states`),n}function q(t){var n;let e=(n=t.verbose)!=null?n:!1;e&&(console.error(`
3
- 📊 Starting statechart extraction`),console.error(` Machines to extract: ${t.machines.length}`));let r=new A;r.addSourceFilesAtPaths("src/**/*.ts"),r.addSourceFilesAtPaths("examples/**/*.ts");let i=[];for(let o of t.machines)try{let a=m(o,r,e);i.push(a)}catch(a){console.error(`❌ Error extracting machine '${o.id}':`,a),e||console.error(" Run with --verbose for more details")}return e&&console.error(`
4
- ✅ Extraction complete: ${i.length}/${t.machines.length} machines extracted`),i}function S(){let t={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 e=new A;e.addSourceFilesAtPaths("src/**/*.ts"),e.addSourceFilesAtPaths("examples/**/*.ts");try{let r=m(t,e,!0);console.log(JSON.stringify(r,null,2))}catch(r){console.error("❌ Error:",r),process.exit(1)}}b.main===module&&S();function j(t){return typeof t!="function"?null:t[M]||null}function T(t){let e={on:{}},r=[];for(let i in t){let n=t[i];if(typeof n!="function")continue;let o=j(n);if(o&&(o.invoke&&r.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 r.length>0&&(e.invoke=r),e}function J(t,e){let r={id:e.id,initial:e.initial,states:{}};e.description&&(r.description=e.description);for(let[i,n]of Object.entries(t))r.states[i]=T(n);return r}function Y(t,e){let r=e.stateName||t.constructor.name||"State";return{id:e.id,initial:r,states:{[r]:T(t)}}}function H(t,e){let r=t,i=s=>{r=s,e==null||e(s)},{context:n,...o}=t,a=new Proxy({},{get(s,u){let l=r[u];if(typeof l=="function")return(...f)=>{let x=l.apply(r.context,f),d=Object.assign({context:x.context},o);return i(d),d}}});return{get state(){return r},get context(){return r.context},actions:a,setState:i}}function ae(t,e,r){let i=()=>{let o=t.getContext(),a=r(o),s=e[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(o)},n=new Proxy({},{get(o,a){let s=i(),u=s[a];if(typeof u!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...l)=>u.apply(s.context,l)}});return{get context(){return t.getContext()},get state(){return i()},actions:n}}function se(t,e){let r=H(e),i=t(r),n=i.next();for(;!n.done;)n=i.next();return n.value}function ce(t,e){let r=t(e),i=r.next();for(;!i.done;)i=r.next();return i.value}var F=class{constructor(e){this.store=e}get context(){return this.store.getContext()}setContext(e){this.store.setContext(e)}};function ue(t,e){let r=new t(e);return new Proxy({},{get(i,n){let o=e.getContext();if(n in o)return o[n];let a=r[n];if(typeof a=="function")return(...s)=>a.apply(r,s)},set(i,n,o){let a=e.getContext();if(n in a){let s={...a,[n]:o};return e.setContext(s),!0}return!1},has(i,n){let o=e.getContext();return n in o||typeof r[n]=="function"},ownKeys(i){let n=e.getContext(),o=Object.keys(n),a=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter(s=>s!=="constructor"&&typeof r[s]=="function");return Array.from(new Set([...o,...a]))},getOwnPropertyDescriptor(i,n){let o=e.getContext();if(n in o||typeof r[n]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function le(t,e,r){let i=()=>{let n=r(t),o=e[n];if(!o)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(n)}".`);return o(t)};return new Proxy(t,{get(n,o,a){if(o in n)return n[o];let s=i(),u=s[o];if(typeof u=="function")return(...l)=>{let f=u.apply(s.context,l);if(typeof f!="object"||f===null){console.warn(`[MutableMachine] Transition "${String(o)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(n).forEach(x=>delete n[x]),Object.assign(n,f)}},set(n,o,a,s){return n[o]=a,!0},has(n,o){let a=i();return o in n||typeof a[o]=="function"}})}function y(t,e){return Object.assign({context:t},e)}function de(t,e){return Object.assign({context:t},e)}function fe(){return t=>{let e=Object.fromEntries(Object.entries(t).map(([r,i])=>[r,function(...n){let o=i(this,...n);return y(o,e)}]));return r=>y(r,e)}}function ye(t,e){let{context:r,...i}=t,n=typeof e=="function"?e(r):e;return y(n,i)}function Me(t,e){let{context:r,...i}=t,n={...i,...e};return y(r,n)}function ge(t,e){let{context:r,...i}=t,n={...i,...e};return y(r,n)}function pe(t){let{context:e,...r}=t;return i=>y(i,r)}function he(t,e,r){let i=t.context[e],n=r[i];if(!n)throw new Error(`No handler found for state: ${String(i)}`);return n(t.context)}function Ce(t,e,r){return t.context[e]===r}function me(t,e){let r=t;async function i(n){let o=r[n.type];if(typeof o!="function")throw new Error(`[Machine] Unknown event type '${String(n.type)}' on current state.`);return r=await o.apply(r.context,n.args),e==null||e(r),r}return{get state(){return r.context},dispatch:i}}var w=class{constructor(e){this.context=e}};function Te(t,e){let{context:r,...i}=t;return y(e(r),i)}export{D as META_KEY,w as MachineBase,F as MultiMachineBase,M as RUNTIME_META,G as action,de as createAsyncMachine,ae as createEnsemble,O as createFlow,y as createMachine,pe as createMachineBuilder,fe as createMachineFactory,ue as createMultiMachine,le as createMutableMachine,H as createRunner,I as describe,ge as extendTransitions,Y as extractFromInstance,j as extractFunctionMetadata,m as extractMachine,q as extractMachines,T as extractStateNode,S as generateChart,J as generateStatechart,_ as guarded,Ce as hasState,W as invoke,he as matchMachine,V as metadata,Te as next,Me as overrideTransitions,E as run,K as runAsync,me as runMachine,R as runSequence,P as runWithDebug,ce as runWithEnsemble,se as runWithRunner,ye as setContext,N as step,$ as stepAsync,L as transitionTo,v as yieldMachine};
1
+ var X=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function Q(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=n.next(r);if(i)return o;r=o}}function Me(e){return function*(){return yield e}()}function fe(e){return e}function xe(e,t){return t.reduce((n,r)=>Q(r,n),e)}function pe(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 ge(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*Ce(e){return yield e}var me=Symbol("MachineMeta"),A=Symbol("__machine_runtime_meta__");function P(e,t){let n=e[A]||{},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,A,{value:r,enumerable:!1,writable:!1,configurable:!0})}function we(e,t){return P(t,{target:e.name||e.toString()}),t}function be(e,t){return P(t,{description:e}),t}function Te(e,t){return P(t,{guards:[e]}),t}function Ee(e,t){return P(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function Se(e,t){return P(t,{actions:[e]}),t}function D(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=async function(...c){let d=typeof this=="object"&&"context"in this,u=d?this.context:this;if(await Promise.resolve(e(u,...c))){let y=d?this.context:this;return t.apply(y,c)}else if(r==="throw"){let y=o||"Guard condition failed";throw new Error(y)}else if(r==="ignore"){if(d)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(d)return r.apply(this,c);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),P(s,{description:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}function Fe(e){return{do(t){let n=D(e,t);return n.else=function(r){return D(e,t,{onFail:r})},n}}}function Pe(e,t){return t}import{Project as Z,Node as C}from"ts-morph";function ee(e){return C.isIdentifier(e)?e.getText():C.isTypeOfExpression(e)?e.getExpression().getText():"unknown"}function z(e){if(!C.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(C.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();o&&(C.isStringLiteral(o)||C.isNumericLiteral(o)?t[r]=o.getLiteralValue():o.getText()==="true"||o.getText()==="false"?t[r]=o.getText()==="true":C.isIdentifier(o)?t[r]=o.getText():C.isObjectLiteralExpression(o)?t[r]=z(o):C.isArrayLiteralExpression(o)&&(t[r]=o.getElements().map(i=>C.isObjectLiteralExpression(i)?z(i):i.getText())))}return t}function Re(e){if(!C.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(C.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();if(!o)continue;r==="onDone"||r==="onError"?t[r]=ee(o):C.isStringLiteral(o)?t[r]=o.getLiteralValue():C.isIdentifier(o)&&(t[r]=o.getText())}return t}function N(e,t=!1){if(!C.isCallExpression(e))return null;let n=e.getExpression(),r=C.isIdentifier(n)?n.getText():null;if(!r)return null;let o={},i=e.getArguments();switch(r){case"transitionTo":i[0]&&(o.target=ee(i[0]));break;case"describe":if(i[0]&&C.isStringLiteral(i[0])&&(o.description=i[0].getLiteralValue()),i[1]&&C.isCallExpression(i[1])){let a=N(i[1],t);a&&Object.assign(o,a)}break;case"guarded":if(i[0]){let a=z(i[0]);Object.keys(a).length>0&&(o.guards=[a])}if(i[1]&&C.isCallExpression(i[1])){let a=N(i[1],t);a&&Object.assign(o,a)}break;case"invoke":if(i[0]){let a=Re(i[0]);Object.keys(a).length>0&&(o.invoke=a)}break;case"action":if(i[0]){let a=z(i[0]);Object.keys(a).length>0&&(o.actions=[a])}if(i[1]&&C.isCallExpression(i[1])){let a=N(i[1],t);a&&Object.assign(o,a)}break;default:return null}return Object.keys(o).length>0?o:null}function ve(e,t=!1){if(!C.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(!C.isCallExpression(n))return t&&console.error(" ⚠️ Initializer is not a call expression"),null;let r=N(n,t);return r&&t&&console.error(" ✅ Extracted metadata:",JSON.stringify(r,null,2)),r}function K(e,t=!1){let n={on:{}},r=e.getDeclarations()[0];if(!r||!C.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=ve(i,t);if(!s)continue;t&&console.error(` Found transition: ${a}`);let{invoke:c,actions:d,guards:u,...x}=s;if(c&&(n.invoke||(n.invoke=[]),n.invoke.push({src:c.src,onDone:{target:c.onDone},onError:{target:c.onError},description:c.description}),t&&console.error(` → Invoke: ${c.src}`)),x.target){let y={target:x.target};x.description&&(y.description=x.description),u&&(y.cond=u.map(f=>f.name).join(" && "),t&&console.error(` → Guard: ${y.cond}`)),d&&d.length>0&&(y.actions=d.map(f=>f.name),t&&console.error(` → Actions: ${y.actions.join(", ")}`)),n.on[a]=y,t&&console.error(` → Target: ${x.target}`)}}return n}function Ae(e,t,n,r,o=!1){let i=K(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]=K(c,o)}else console.warn(`⚠️ Warning: Child class '${a}' not found.`)}}return i}function _(e,t,n=!1){n&&(console.error(`
2
+ 🔍 Analyzing machine: ${e.id}`),console.error(` Source: ${e.input}`));let r=t.getSourceFile(e.input);if(!r)throw new Error(`Source file not found: ${e.input}`);if(e.parallel){n&&console.error(" ⏹️ Parallel machine detected. Analyzing regions.");let i={id:e.id,type:"parallel",states:{}};e.description&&(i.description=e.description);for(let a of e.parallel.regions){n&&console.error(` 📍 Analyzing region: ${a.name}`);let s={};for(let c of a.classes){let d=r.getClass(c);if(d){let u=d.getSymbolOrThrow();s[c]=K(u,n)}else console.warn(`⚠️ Warning: Class '${c}' not found for region '${a.name}'.`)}i.states[a.name]={initial:a.initialState,states:s}}return n&&console.error(` ✅ Extracted ${e.parallel.regions.length} parallel regions`),i}if(!e.initialState||!e.classes)throw new Error(`Machine config for '${e.id}' must have either 'parallel' or 'initialState'/'classes'.`);let o={id:e.id,initial:e.initialState,states:{}};e.description&&(o.description=e.description);for(let i of e.classes){let a=r.getClass(i);if(!a){console.warn(`⚠️ Warning: Class '${i}' not found in '${e.input}'. Skipping.`);continue}let s=a.getSymbolOrThrow(),c=i===e.initialState&&e.children,d=Ae(i,s,r,c?e.children:void 0,n);o.states[i]=d}return n&&console.error(` ✅ Extracted ${e.classes.length} states`),o}function Oe(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 Z;n.addSourceFilesAtPaths("src/**/*.ts"),n.addSourceFilesAtPaths("examples/**/*.ts");let r=[];for(let i of e.machines)try{let a=_(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 te(){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 Z;t.addSourceFilesAtPaths("src/**/*.ts"),t.addSourceFilesAtPaths("examples/**/*.ts");try{let n=_(e,t,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}X.main===module&&te();function ne(e){return typeof e!="function"?null:e[A]||null}function W(e){let t={on:{}},n=[];for(let r in e){let o=e[r];if(typeof o!="function")continue;let i=ne(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 je(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]=W(o);return n}function ke(e,t){let n=t.stateName||e.constructor.name||"State";return{id:t.id,initial:n,states:{[n]:W(e)}}}function Ne(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:o,...i}=e,a=new Proxy({},{get(s,c){let d=n[c];if(typeof d=="function")return(...u)=>{let x=d.apply(n.context,u),y=Object.assign({context:x.context},i);return r(y),y}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function xt(e,t,n){let r=()=>{let i=e.getContext(),a=n(i),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(i)},o=new Proxy({},{get(i,a){let s=r(),c=s[a];if(typeof c!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...d)=>c.apply(s.context,d)}});return{get context(){return e.getContext()},get state(){return r()},actions:o}}function pt(e,t){let n=Ne(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function ht(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var re=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function gt(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 Ct(e,t,n){let r=()=>{let o=n(e),i=t[o];if(!i)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(o)}".`);return i(e)};return new Proxy(e,{get(o,i,a){if(i in o)return o[i];let s=r(),c=s[i];if(typeof c=="function")return(...d)=>{let u=c.apply(s.context,d);if(typeof u!="object"||u===null){console.warn(`[MutableMachine] Transition "${String(i)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(o).forEach(x=>delete o[x]),Object.assign(o,u)}},set(o,i,a,s){return o[i]=a,!0},has(o,i){let a=r();return i in o||typeof a[i]=="function"}})}function St(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 Ft(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 H=class extends T{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},S=class extends T{constructor(n,r,o){super({status:"loading",abortController:new AbortController,attempts:o});this.config=n;this.params=r;this.succeed=n=>{var r,o;return(o=(r=this.config).onSuccess)==null||o.call(r,n),new L(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 I(this.config,this.params,n,this.context.attempts):((a=(i=this.config).onError)==null||a.call(i,n),new G(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new V(this.config));this.execute()}async execute(){}},I=class extends T{constructor(n,r,o,i){super({status:"retrying",error:o,attempts:i});this.config=n;this.params=r;this.retry=n=>new S(this.config,n!=null?n:this.params,this.context.attempts+1)}},L=class extends T{constructor(n,r){super(r);this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},G=class extends T{constructor(n,r){super(r);this.config=n;this.retry=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},V=class extends T{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}};function Pt(e){return new H(e)}function oe(e,t){let n={...e.context,...t.context},r={...e},o={...t};delete r.context,delete o.context;let i={};for(let a in r){let s=r[a];i[a]=(...c)=>{let d=s.apply(e.context,c);return oe(d,t)}}for(let a in o){let s=o[a];i[a]=(...c)=>{let d=s.apply(t.context,c);return oe(e,d)}}return{context:n,...i}}var ie=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]=ze(a,s,e,t,r)}return i}function ze(e,t,n,r,o){return function(...a){let s=n.context,c={transitionName:e,context:s,args:a},d=()=>{try{if(r.before){let f=r.before(c);if(f===ie)return n;if(f instanceof Promise)throw new Error(`Middleware mode is 'sync' but before hook returned Promise for transition: ${e}`)}let y=t.call(this,...a);if(y instanceof Promise)return u(y,s);if(r.after){let f={transitionName:e,prevContext:s,nextContext:y.context,args:a};if(r.after(f)instanceof Promise)throw new Error(`Middleware mode is 'sync' but after hook returned Promise for transition: ${e}`)}return y}catch(y){if(r.error){let f={transitionName:e,context:s,args:a,error:y},l=r.error(f);if(l instanceof Promise)throw l.catch(()=>{}),y;if(l&&typeof l=="object"&&"context"in l)return l}throw y}},u=async(y,f)=>{try{let l=await y;if(r.after){let h={transitionName:e,prevContext:f,nextContext:l.context,args:a};await r.after(h)}return l}catch(l){if(r.error){let h={transitionName:e,context:f,args:a,error:l},M=await r.error(h);if(M&&typeof M=="object"&&"context"in M)return M}throw l}},x=async()=>{try{if(r.before&&await r.before(c)===ie)return n;let y=await t.call(this,...a);if(r.after){let f={transitionName:e,prevContext:s,nextContext:y.context,args:a};await r.after(f)}return y}catch(y){if(r.error){let f={transitionName:e,context:s,args:a,error:y},l=await r.error(f);if(l&&typeof l=="object"&&"context"in l)return l}throw y}};return o==="async"?x():d()}}function Be(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 $e(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!0}=n;return w(e,{after:async({transitionName:a,prevContext:s,nextContext:c,args:d})=>{let u={transition:a,to:c};o&&(u.from=s),i&&d.length>0&&(u.args=d),await t(`${r}.${a}`,u)}},{mode:"async"})}function De(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 Ke(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 _e(e,t,n={}){let{includeContext:r=!0,includeArgs:o=!0,mode:i}=n;return w(e,{error:async({transitionName:a,context:s,args:c,error:d})=>{let u={transition:a};r&&(u.context=s),o&&c.length>0&&(u.args=c),await Promise.resolve(t(d,u))}},{mode:i})}function We(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 He(e,t={}){let{maxRetries:n=3,delay:r=1e3,backoffMultiplier:o=1,shouldRetry:i=()=>!0,onRetry:a}=t,s={};for(let c in e){if(!Object.prototype.hasOwnProperty.call(e,c))continue;let d=e[c];if(c==="context"||typeof d!="function"){s[c]=d;continue}s[c]=async function(...x){let y;for(let f=0;f<=n;f++)try{return await d.call(this,...x)}catch(l){if(y=l,f===n||!i(y))break;a==null||a(f+1,y);let h=r*Math.pow(o,f);await new Promise(M=>setTimeout(M,h))}throw y}}return s}function ae(e,t={}){let{maxSize:n,serializer:r,filter:o,onEntry:i,_isRewrap:a=!1}=t,s=[],c=0,d=w(e,{before:({transitionName:u,args:x})=>{if(o&&!o(u,x))return;let y={id:`entry-${c++}`,transitionName:u,args:[...x],timestamp:Date.now()};if(r)try{y.serializedArgs=r.serialize(x)}catch(f){console.error("Failed to serialize history args:",f)}s.push(y),n&&s.length>n&&s.shift(),i==null||i(y)}},{exclude:["context","history","clearHistory"]});if(!a)for(let u in d){if(!Object.prototype.hasOwnProperty.call(d,u))continue;let x=d[u];if(typeof x=="function"&&!u.startsWith("_")&&u!=="context"&&!["history","clearHistory"].includes(u)){let y=x;d[u]=function(...f){let l=y.apply(this,f);if(l&&typeof l=="object"&&"context"in l&&!("history"in l)){let h=w(l,{before:({transitionName:M,args:g})=>{if(o&&!o(M,g))return;let p={id:`entry-${c++}`,transitionName:M,args:[...g],timestamp:Date.now()};if(r)try{p.serializedArgs=r.serialize(g)}catch(b){console.error("Failed to serialize history args:",b)}s.push(p),n&&s.length>n&&s.shift(),i==null||i(p)}},{exclude:["context","history","clearHistory"]});return Object.assign(h,{history:s,clearHistory:()=>{s.length=0,c=0}})}return l}}}return Object.assign(d,{history:s,clearHistory:()=>{s.length=0,c=0}})}function se(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:o,onlyIfChanged:i=!1,filter:a,onSnapshot:s,_extraExclusions:c=[],_isRewrap:d=!1}=t,u=[],x=0,y=w(e,{after:({transitionName:l,prevContext:h,nextContext:M})=>{if(a&&!a(l)||i&&!(JSON.stringify(h)!==JSON.stringify(M)))return;let g={id:`snapshot-${x++}`,transitionName:l,before:{...h},after:{...M},timestamp:Date.now()};if(r)try{g.serializedBefore=r.serialize(h),g.serializedAfter=r.serialize(M)}catch(p){console.error("Failed to serialize snapshot:",p)}if(o)try{g.diff=o(h,M)}catch(p){console.error("Failed to capture snapshot:",p)}u.push(g),n&&u.length>n&&u.shift(),s==null||s(g)}},{exclude:["context","snapshots","clearSnapshots","restoreSnapshot",...c]}),f=l=>{let{context:h,...M}=e;return{context:l,...M}};if(!d)for(let l in y){if(!Object.prototype.hasOwnProperty.call(y,l))continue;let h=y[l];if(typeof h=="function"&&!l.startsWith("_")&&l!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(l)){let M=h;y[l]=function(...g){let p=M.apply(this,g);if(p&&typeof p=="object"&&"context"in p&&!("snapshots"in p)){for(let m in p){if(!Object.prototype.hasOwnProperty.call(p,m))continue;let R=p[m];if(typeof R=="function"&&!m.startsWith("_")&&m!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(m)){let ue=R;p[m]=function(...ye){let j=p.context,v=ue.apply(this,ye);if(v&&typeof v=="object"&&"context"in v){let k=v.context;if(!(a&&!a(m))){let Y=!0;if(i&&(Y=JSON.stringify(j)!==JSON.stringify(k)),Y){let F={id:`snapshot-${x++}`,transitionName:m,before:{...j},after:{...k},timestamp:Date.now()};if(r)try{F.serializedBefore=r.serialize(j),F.serializedAfter=r.serialize(k)}catch($){console.error("Failed to serialize snapshot:",$)}if(o)try{F.diff=o(j,k)}catch($){console.error("Failed to capture snapshot:",$)}u.push(F),n&&u.length>n&&u.shift(),s==null||s(F)}}}return v}}}let b=Object.assign(p,{snapshots:u,clearSnapshots:()=>{u.length=0,x=0},restoreSnapshot:f});return e.history&&(b.history=e.history,b.clearHistory=e.clearHistory),b}return p}}}return Object.assign(y,{snapshots:u,clearSnapshots:()=>{u.length=0,x=0},restoreSnapshot:f})}function ce(e,t={}){let{maxSize:n,serializer:r,onRecord:o}=t,i=[],a=[],s=0,c=0,d=(l,h)=>{let M={id:`entry-${s++}`,transitionName:l,args:[...h],timestamp:Date.now()};if(r)try{M.serializedArgs=r.serialize(h)}catch(g){console.error("Failed to serialize history args:",g)}i.push(M),n&&i.length>n&&i.shift(),o==null||o("history",M)},u=(l,h,M)=>{let g={id:`snapshot-${c++}`,transitionName:l,before:{...h},after:{...M},timestamp:Date.now()};if(r)try{g.serializedBefore=r.serialize(h),g.serializedAfter=r.serialize(M)}catch(p){console.error("Failed to serialize snapshot:",p)}a.push(g),n&&a.length>n&&a.shift(),o==null||o("snapshot",g)},x=l=>{let{context:h,...M}=e;return Object.assign({context:l},l,M)},y=(l=0)=>{if(l<0||l>=a.length)throw new Error(`Invalid snapshot index: ${l}`);let h=x(a[l].before),M=a[l],g=i.findIndex(p=>p.transitionName===M.transitionName&&p.timestamp===M.timestamp);if(g===-1)throw new Error("Could not find matching history entry for snapshot");for(let p=g;p<i.length;p++){let b=i[p],m=h[b.transitionName];if(typeof m=="function")try{h=m.apply(h.context,b.args)}catch(R){throw console.error(`Replay failed at step ${p}:`,R),R}}return h},f=l=>{let h={...l};for(let M in l){if(!Object.prototype.hasOwnProperty.call(l,M))continue;let g=l[M];typeof g=="function"&&!M.startsWith("_")&&M!=="context"&&!["history","snapshots","clearHistory","clearSnapshots","clearTimeTravel","restoreSnapshot","replayFrom"].includes(M)&&(h[M]=function(...p){d(M,p);let b=h.context,m=g.apply(this,p);return m&&typeof m=="object"&&"context"in m&&u(M,b,m.context),m&&typeof m=="object"&&"context"in m?f(m):m})}return Object.assign(h,{history:i,snapshots:a,clearHistory:()=>{i.length=0,s=0},clearSnapshots:()=>{a.length=0,c=0},clearTimeTravel:()=>{i.length=0,a.length=0,s=0,c=0},restoreSnapshot:x,replayFrom:y})};return f(e)}function Ie(e,...t){return t.reduce((n,r)=>r(n),e)}function Le(e,t){return n=>w(n,e,t)}function B(e,...t){return t.reduce((n,r)=>r(n),e)}function Ge(e){return new U(e)}var U=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function Ve(e){return ce(se(ae(e)))}function Ue(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(o,...i)=>{let a=o,s=[];for(let c=0;c<i.length;c++){let d=i[c];try{if("middleware"in d&&"when"in d){if(!d.when(a))continue;a=d.middleware(a)}else a=d(a)}catch(u){let x=u instanceof Error?u:new Error(String(u));if(s.push({error:x,middlewareIndex:c}),n&&console.error(`Middleware pipeline error at index ${c}:`,x),r==null||r(x,`middleware-${c}`),!t)break}}return{machine:a,errors:s,success:s.length===0}}}function Je(){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 B(t,...r.map(o=>o.middleware))},applyAll(t){let n=this.list();return B(t,...n.map(r=>r.middleware))}}}function J(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function qe(e){return J(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function Ye(e,t,n){return J(n,r=>r.context[e]===t)}function Xe(...e){return t=>B(t,...e)}function Qe(e,t){return n=>{for(let[r,o]of e)if(r(n))return o(n);return t?t(n):n}}function le(e){return typeof e=="function"&&e.length===1}function Ze(e){return e!==null&&"middleware"in e&&"when"in e&&le(e.middleware)&&typeof e.when=="function"}function et(e,t){return e instanceof t}function tt(e,...t){return{type:e,args:t}}function nt(e,t){return O(e,n=>({...n,...t}))}async function rt(e,...t){let n=e;for(let r of t)n=await r(n);return n}function ot(e,t){return t?console.log(t,e.context):console.log(e.context),e}function it(e,t,...n){return e.apply(t,n)}function de(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?de(i):i}:r}})}var q=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 Kt(e,t){return Object.assign({context:e},t)}function _t(){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 Wt(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function Ht(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function It(e,t){return(...n)=>{let r=e(...n),o=t(),i={...r.context,...o.context},{context:a,...s}=r,{context:c,...d}=o,u={...s,...d};return E(i,u)}}function Lt(e){let{context:t,...n}=e;return r=>E(r,n)}function Gt(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 Ut(e,t){let n=e,r=null;async function o(i){r&&(r.abort(),r=null);let a=n[i.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(i.type)}' on current state.`);let s=new AbortController;r=s;try{let d=await a.apply(n.context,[...i.args,{signal:s.signal}]);return s.signal.aborted||(n=d,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:o,stop:()=>{r&&(r.abort(),r=null)}}}var T=class{constructor(t){this.context=t}};function Jt(e,t){let{context:n,...r}=e;return E(t(n),r)}export{q as BoundMachine,me as META_KEY,T as MachineBase,re as MultiMachineBase,A as RUNTIME_META,Se as action,de as bindTransitions,Qe as branch,it as call,Ge as chain,Xe as combine,It as combineFactories,Ie as compose,B as composeTyped,Kt as createAsyncMachine,Le as createCustomMiddleware,xt as createEnsemble,tt as createEvent,Pt as createFetchMachine,pe as createFlow,E as createMachine,Lt as createMachineBuilder,_t as createMachineFactory,w as createMiddleware,Je as createMiddlewareRegistry,gt as createMultiMachine,Ct as createMutableMachine,oe as createParallelMachine,Ue as createPipeline,Ne as createRunner,St as delegateToChild,be as describe,Ht as extendTransitions,ke as extractFromInstance,ne as extractFunctionMetadata,_ as extractMachine,Oe as extractMachines,W as extractStateNode,te as generateChart,je as generateStatechart,D as guard,Te as guarded,Vt as hasState,qe as inDevelopment,Ee as invoke,Ze as isConditionalMiddleware,le as isMiddlewareFn,et as isState,ot as logState,Gt as matchMachine,nt as mergeContext,Pe as metadata,Jt as next,Wt as overrideTransitions,rt as pipeTransitions,Q as run,ge as runAsync,Ut as runMachine,xe as runSequence,he as runWithDebug,ht as runWithEnsemble,pt as runWithRunner,O as setContext,Me as step,Ce as stepAsync,Ft as toggle,we as transitionTo,J as when,Ye as whenContext,Fe as whenGuard,$e as withAnalytics,Ve as withDebugging,_e as withErrorReporting,ae as withHistory,Be as withLogging,We as withPerformanceMonitoring,Ke as withPermissions,He as withRetry,se as withSnapshot,ce as withTimeTravel,De as withValidation,fe as yieldMachine};
@@ -14,22 +14,50 @@
14
14
  * 3. Run the script from your project root: `npx ts-node ./scripts/extract-statechart.ts`
15
15
  */
16
16
  import { Project } from 'ts-morph';
17
+ /**
18
+ * Configuration for a parallel region
19
+ */
20
+ export interface ParallelRegionConfig {
21
+ /** A unique name for this region (e.g., 'fontStyle') */
22
+ name: string;
23
+ /** The initial state class for this region */
24
+ initialState: string;
25
+ /** All reachable state classes within this region */
26
+ classes: string[];
27
+ }
28
+ /**
29
+ * Configuration for child states in a hierarchical machine
30
+ */
31
+ export interface ChildStatesConfig {
32
+ /** The property in the parent's context that holds the child machine */
33
+ contextProperty: string;
34
+ /** An array of all possible child state class names */
35
+ classes: string[];
36
+ /** The initial child state */
37
+ initialState: string;
38
+ }
17
39
  /**
18
40
  * Configuration for a single machine to extract
19
41
  */
20
42
  export interface MachineConfig {
21
43
  /** Path to the source file containing the machine */
22
44
  input: string;
23
- /** Array of class names that represent states */
24
- classes: string[];
25
45
  /** Output file path (optional, defaults to stdout) */
26
46
  output?: string;
27
47
  /** Top-level ID for the statechart */
28
48
  id: string;
29
- /** Name of the class that represents the initial state */
30
- initialState: string;
31
49
  /** Optional description of the machine */
32
50
  description?: string;
51
+ /** Array of class names that represent states (for simple FSM) */
52
+ classes?: string[];
53
+ /** Name of the class that represents the initial state (for simple FSM) */
54
+ initialState?: string;
55
+ /** Configuration for parallel regions (mutually exclusive with initialState/classes) */
56
+ parallel?: {
57
+ regions: ParallelRegionConfig[];
58
+ };
59
+ /** Configuration for hierarchical/nested states */
60
+ children?: ChildStatesConfig;
33
61
  }
34
62
  /**
35
63
  * Global extraction configuration
@@ -68,4 +96,12 @@ export declare function extractMachines(config: ExtractionConfig): any[];
68
96
  * @deprecated Use extractMachine or extractMachines instead
69
97
  */
70
98
  export declare function generateChart(): void;
99
+ /**
100
+ * Example configuration demonstrating hierarchical and parallel machines.
101
+ * This is not used by default but serves as documentation.
102
+ */
103
+ export declare const ADVANCED_CONFIG_EXAMPLES: {
104
+ hierarchical: MachineConfig;
105
+ parallel: MachineConfig;
106
+ };
71
107
  //# sourceMappingURL=extract.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"extract.d.ts","sourceRoot":"","sources":["../../src/extract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAc,MAAM,UAAU,CAAC;AAM/C;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,qDAAqD;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,iDAAiD;IACjD,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,sDAAsD;IACtD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,EAAE,EAAE,MAAM,CAAC;IACX,0DAA0D;IAC1D,YAAY,EAAE,MAAM,CAAC;IACrB,0CAA0C;IAC1C,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,mCAAmC;IACnC,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,6CAA6C;IAC7C,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC;IACrC,mDAAmD;IACnD,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,sBAAsB;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAkYD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,aAAa,EACrB,OAAO,EAAE,OAAO,EAChB,OAAO,UAAQ,GACd,GAAG,CAqCL;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,gBAAgB,GAAG,GAAG,EAAE,CA+B/D;AAED;;;;GAIG;AACH,wBAAgB,aAAa,SAkC5B"}
1
+ {"version":3,"file":"extract.d.ts","sourceRoot":"","sources":["../../src/extract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,OAAO,EAAc,MAAM,UAAU,CAAC;AAM/C;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,wDAAwD;IACxD,IAAI,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AG,CAiGL;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,gBAAgB,GAAG,GAAG,EAAE,CA+B/D;AAED;;;;GAIG;AACH,wBAAgB,aAAa,SAkC5B;AAED;;;GAGG;AACH,eAAO,MAAM,wBAAwB;kBAW9B,aAAa;cAmBb,aAAa;CACnB,CAAC"}
@@ -25,7 +25,6 @@
25
25
  * }, initialMachine);
26
26
  * ```
27
27
  */
28
- import { Machine } from './index';
29
28
  /**
30
29
  * Runs a generator-based state machine flow to completion.
31
30
  *
@@ -115,7 +114,11 @@ import { Machine } from './index';
115
114
  * }, machine);
116
115
  * ```
117
116
  */
118
- export declare function run<C extends object, T>(flow: (m: Machine<C>) => Generator<Machine<C>, T, Machine<C>>, initial: Machine<C>): T;
117
+ export declare function run<C extends any = any, M extends {
118
+ context: C;
119
+ } & Record<string, any> = {
120
+ context: C;
121
+ }, T = any>(flow: (m: M) => Generator<M, T, M>, initial: M): T;
119
122
  /**
120
123
  * A helper function to yield a machine state and receive the next state back.
121
124
  *
@@ -169,7 +172,11 @@ export declare function run<C extends object, T>(flow: (m: Machine<C>) => Genera
169
172
  * }, machine);
170
173
  * ```
171
174
  */
172
- export declare function step<C extends object>(m: Machine<C>): Generator<Machine<C>, Machine<C>, Machine<C>>;
175
+ export declare function step<C extends any = any, M extends {
176
+ context: C;
177
+ } & Record<string, any> = {
178
+ context: C;
179
+ }>(m: M): Generator<M, M, M>;
173
180
  /**
174
181
  * Alternative to `step` that doesn't require `yield*`.
175
182
  * This is semantically identical but uses direct yielding.
@@ -189,7 +196,11 @@ export declare function step<C extends object>(m: Machine<C>): Generator<Machine
189
196
  * }, counter);
190
197
  * ```
191
198
  */
192
- export declare function yieldMachine<C extends object>(m: Machine<C>): Machine<C>;
199
+ export declare function yieldMachine<C extends any = any, M extends {
200
+ context: C;
201
+ } & Record<string, any> = {
202
+ context: C;
203
+ }>(m: M): M;
193
204
  /**
194
205
  * Runs multiple generator flows in sequence, passing the result of each to the next.
195
206
  *
@@ -216,7 +227,11 @@ export declare function yieldMachine<C extends object>(m: Machine<C>): Machine<C
216
227
  * console.log(result.context.count); // 6
217
228
  * ```
218
229
  */
219
- export declare function runSequence<C extends object>(initial: Machine<C>, flows: Array<(m: Machine<C>) => Generator<Machine<C>, Machine<C>, Machine<C>>>): Machine<C>;
230
+ export declare function runSequence<C extends any = any, M extends {
231
+ context: C;
232
+ } & Record<string, any> = {
233
+ context: C;
234
+ }>(initial: M, flows: Array<(m: M) => Generator<M, M, M>>): M;
220
235
  /**
221
236
  * Creates a reusable generator flow that can be composed into other flows.
222
237
  *
@@ -244,7 +259,11 @@ export declare function runSequence<C extends object>(initial: Machine<C>, flows
244
259
  * }, counter);
245
260
  * ```
246
261
  */
247
- export declare function createFlow<C extends object>(flow: (m: Machine<C>) => Generator<Machine<C>, Machine<C>, Machine<C>>): (m: Machine<C>) => Generator<Machine<C>, Machine<C>, Machine<C>>;
262
+ export declare function createFlow<C extends any = any, M extends {
263
+ context: C;
264
+ } & Record<string, any> = {
265
+ context: C;
266
+ }>(flow: (m: M) => Generator<M, M, M>): (m: M) => Generator<M, M, M>;
248
267
  /**
249
268
  * Runs a generator flow with debugging output at each step.
250
269
  *
@@ -272,7 +291,11 @@ export declare function createFlow<C extends object>(flow: (m: Machine<C>) => Ge
272
291
  * // Final: 6
273
292
  * ```
274
293
  */
275
- export declare function runWithDebug<C extends object, T>(flow: (m: Machine<C>) => Generator<Machine<C>, T, Machine<C>>, initial: Machine<C>, logger?: (step: number, machine: Machine<C>) => void): T;
294
+ export declare function runWithDebug<C extends any = any, M extends {
295
+ context: C;
296
+ } & Record<string, any> = {
297
+ context: C;
298
+ }, T = any>(flow: (m: M) => Generator<M, T, M>, initial: M, logger?: (step: number, machine: M) => void): T;
276
299
  /**
277
300
  * Async version of `run` for async state machines.
278
301
  *
@@ -294,7 +317,11 @@ export declare function runWithDebug<C extends object, T>(flow: (m: Machine<C>)
294
317
  * }, asyncMachine);
295
318
  * ```
296
319
  */
297
- export declare function runAsync<C extends object, T>(flow: (m: Machine<C>) => AsyncGenerator<Machine<C>, T, Machine<C>>, initial: Machine<C>): Promise<T>;
320
+ export declare function runAsync<C extends any = any, M extends {
321
+ context: C;
322
+ } & Record<string, any> = {
323
+ context: C;
324
+ }, T = any>(flow: (m: M) => AsyncGenerator<M, T, M>, initial: M): Promise<T>;
298
325
  /**
299
326
  * Async version of `step` for async generators.
300
327
  *
@@ -310,5 +337,9 @@ export declare function runAsync<C extends object, T>(flow: (m: Machine<C>) => A
310
337
  * }, machine);
311
338
  * ```
312
339
  */
313
- export declare function stepAsync<C extends object>(m: Machine<C>): AsyncGenerator<Machine<C>, Machine<C>, Machine<C>>;
340
+ export declare function stepAsync<C extends any = any, M extends {
341
+ context: C;
342
+ } & Record<string, any> = {
343
+ context: C;
344
+ }>(m: M): AsyncGenerator<M, M, M>;
314
345
  //# sourceMappingURL=generators.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"generators.d.ts","sourceRoot":"","sources":["../../src/generators.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwFG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EACrC,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,EAC7D,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAClB,CAAC,CAsBH;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,wBAAgB,IAAI,CAAC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,CAAC,GACT,OAAO,CAAC,CAAC,CAAC,CAaZ;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAuB,SAAS,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG,EAAE,CAAC,SAAS;IAAE,OAAO,EAAE,CAAC,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG;IAAE,OAAO,EAAE,CAAC,CAAA;CAAE,EACnH,CAAC,EAAE,CAAC,GACH,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAGzB"}
@@ -0,0 +1,221 @@
1
+ /**
2
+ * @file Higher-Level Abstractions for @doeixd/machine
3
+ * @description
4
+ * This module provides a collection of powerful, pre-built patterns and primitives
5
+ * on top of the core `@doeixd/machine` library. These utilities are designed to
6
+ * solve common, recurring problems in state management, such as data fetching,
7
+ * hierarchical state, and toggling boolean context properties.
8
+ *
9
+ * Think of this as the "standard library" of common machine patterns.
10
+ */
11
+ import { MachineBase, Machine, Transitions, Context } from './index';
12
+ /**
13
+ * A type utility to infer the child machine type from a parent.
14
+ */
15
+ type ChildMachine<P> = P extends MachineBase<{
16
+ child: infer C;
17
+ }> ? C : never;
18
+ /**
19
+ * Creates a transition method that delegates a call to a child machine.
20
+ *
21
+ * This is a higher-order function that reduces boilerplate when implementing
22
+ * hierarchical state machines. It generates a method for the parent machine that:
23
+ * 1. Checks if the specified action exists on the current child state.
24
+ * 2. If it exists, calls the action on the child.
25
+ * 3. Reconstructs the parent machine with the new child state returned by the action.
26
+ * 4. If the action doesn't exist on the child, it returns the parent machine unchanged.
27
+ *
28
+ * @template P - The parent machine type, which must have a `child` property in its context.
29
+ * @template K - The name of the action on the child machine to delegate to.
30
+ * @param actionName - The string name of the child's transition method.
31
+ * @param ...args - Any arguments to pass to the child's transition method.
32
+ * @returns The parent machine instance, with its `child` state potentially updated.
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * class Parent extends MachineBase<{ child: ChildMachine }> {
37
+ * // Instead of writing a manual delegation method...
38
+ * // save = () => {
39
+ * // if ('save' in this.context.child) {
40
+ * // const newChild = this.context.child.save();
41
+ * // return setContext(this, { child: newChild });
42
+ * // }
43
+ * // return this;
44
+ * // }
45
+ *
46
+ * // ...you can just use the primitive.
47
+ * save = delegateToChild('save');
48
+ * edit = delegateToChild('edit');
49
+ * }
50
+ * ```
51
+ */
52
+ export declare function delegateToChild<P extends MachineBase<{
53
+ child: MachineBase<any>;
54
+ }>, K extends keyof ChildMachine<P> & string>(actionName: K): (...args: ChildMachine<P>[K] extends (...a: infer A) => any ? A : never) => P;
55
+ /**
56
+ * Creates a transition method that toggles a boolean property within the machine's context.
57
+ *
58
+ * This is a simple utility to reduce boilerplate for managing boolean flags.
59
+ *
60
+ * @template M - The machine type.
61
+ * @template K - The key of the boolean property in the machine's context.
62
+ * @param prop - The string name of the context property to toggle.
63
+ * @returns A new machine instance with the toggled property.
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * class SettingsMachine extends MachineBase<{ notifications: boolean; darkMode: boolean }> {
68
+ * toggleNotifications = toggle('notifications');
69
+ * toggleDarkMode = toggle('darkMode');
70
+ * }
71
+ * ```
72
+ */
73
+ export declare function toggle<M extends MachineBase<any>, K extends keyof Context<M>>(prop: K): (this: M) => M;
74
+ /**
75
+ * A fully-featured, pre-built state machine for data fetching.
76
+ * It handles loading, success, error states, cancellation, and retry logic out of the box.
77
+ *
78
+ * This machine is highly customizable through its configuration options.
79
+ */
80
+ export type Fetcher<T, _E = Error> = (params: any) => Promise<T>;
81
+ export type OnSuccess<T> = (data: T) => void;
82
+ export type OnError<E> = (error: E) => void;
83
+ export interface FetchMachineConfig<T, E = Error> {
84
+ fetcher: Fetcher<T, E>;
85
+ initialParams?: any;
86
+ maxRetries?: number;
87
+ onSuccess?: OnSuccess<T>;
88
+ onError?: OnError<E>;
89
+ }
90
+ type IdleContext = {
91
+ status: 'idle';
92
+ };
93
+ type LoadingContext = {
94
+ status: 'loading';
95
+ abortController: AbortController;
96
+ attempts: number;
97
+ };
98
+ type RetryingContext = {
99
+ status: 'retrying';
100
+ error: any;
101
+ attempts: number;
102
+ };
103
+ type SuccessContext<T> = {
104
+ status: 'success';
105
+ data: T;
106
+ };
107
+ type ErrorContext<E> = {
108
+ status: 'error';
109
+ error: E;
110
+ };
111
+ type CanceledContext = {
112
+ status: 'canceled';
113
+ };
114
+ declare class IdleMachine<T, E> extends MachineBase<IdleContext> {
115
+ private config;
116
+ constructor(config: FetchMachineConfig<T, E>);
117
+ fetch: (params?: any) => LoadingMachine<T, E>;
118
+ }
119
+ declare class LoadingMachine<T, E> extends MachineBase<LoadingContext> {
120
+ private config;
121
+ private params;
122
+ constructor(config: FetchMachineConfig<T, E>, params: any, attempts: number);
123
+ private execute;
124
+ succeed: (data: T) => SuccessMachine<T, E>;
125
+ fail: (error: E) => RetryingMachine<T, E> | ErrorMachine<T, E>;
126
+ cancel: () => CanceledMachine<T, E>;
127
+ }
128
+ declare class RetryingMachine<T, E> extends MachineBase<RetryingContext> {
129
+ private config;
130
+ private params;
131
+ constructor(config: FetchMachineConfig<T, E>, params: any, error: E, attempts: number);
132
+ retry: (params?: any) => LoadingMachine<T, E>;
133
+ }
134
+ declare class SuccessMachine<T, E> extends MachineBase<SuccessContext<T>> {
135
+ private config;
136
+ constructor(config: FetchMachineConfig<T, E>, context: SuccessContext<T>);
137
+ refetch: (params?: any) => LoadingMachine<T, E>;
138
+ }
139
+ declare class ErrorMachine<T, E> extends MachineBase<ErrorContext<E>> {
140
+ private config;
141
+ constructor(config: FetchMachineConfig<T, E>, context: ErrorContext<E>);
142
+ retry: (params?: any) => LoadingMachine<T, E>;
143
+ }
144
+ declare class CanceledMachine<T, E> extends MachineBase<CanceledContext> {
145
+ private config;
146
+ constructor(config: FetchMachineConfig<T, E>);
147
+ refetch: (params?: any) => LoadingMachine<T, E>;
148
+ }
149
+ export type FetchMachine<T, E = Error> = IdleMachine<T, E> | LoadingMachine<T, E> | RetryingMachine<T, E> | SuccessMachine<T, E> | ErrorMachine<T, E> | CanceledMachine<T, E>;
150
+ /**
151
+ * Creates a pre-built, highly configurable async data-fetching machine.
152
+ *
153
+ * This factory function returns a state machine that handles the entire lifecycle
154
+ * of a data request, including loading, success, error, cancellation, and retries.
155
+ *
156
+ * @template T - The type of the data to be fetched.
157
+ * @template E - The type of the error.
158
+ * @param config - Configuration object.
159
+ * @param config.fetcher - An async function that takes params and returns the data.
160
+ * @param [config.maxRetries=3] - The number of times to retry on failure.
161
+ * @param [config.onSuccess] - Optional callback fired with the data on success.
162
+ * @param [config.onError] - Optional callback fired with the error on final failure.
163
+ * @returns An `IdleMachine` instance, ready to start fetching.
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * // 1. Define your data fetching logic
168
+ * async function fetchUser(id: number): Promise<{ id: number; name: string }> {
169
+ * const res = await fetch(`/api/users/${id}`);
170
+ * if (!res.ok) throw new Error('User not found');
171
+ * return res.json();
172
+ * }
173
+ *
174
+ * // 2. Create the machine
175
+ * const userMachine = createFetchMachine({
176
+ * fetcher: fetchUser,
177
+ * onSuccess: (user) => console.log(`Fetched: ${user.name}`),
178
+ * });
179
+ *
180
+ * // 3. Use it (e.g., in a React hook)
181
+ * // let machine = userMachine;
182
+ * // machine = await machine.fetch(123); // Transitions to Loading, then Success/Error
183
+ * ```
184
+ *
185
+ * @note This is a simplified example. For a real-world implementation, you would
186
+ * typically use this machine with a runner (like `runMachine` or `useMachine`) to
187
+ * manage the async transitions and state updates automatically.
188
+ */
189
+ export declare function createFetchMachine<T, E = Error>(config: FetchMachineConfig<T, E>): FetchMachine<T, E>;
190
+ /**
191
+ * The core type for a Parallel Machine.
192
+ * It combines two machines, M1 and M2, into a single, unified type.
193
+ * @template M1 - The first machine in the parallel composition.
194
+ * @template M2 - The second machine in the parallel composition.
195
+ */
196
+ export type ParallelMachine<M1 extends Machine<any>, M2 extends Machine<any>> = Machine<Context<M1> & Context<M2>> & {
197
+ [K in keyof Transitions<M1>]: Transitions<M1>[K] extends (...args: infer A) => infer R ? R extends Machine<any> ? (...args: A) => ParallelMachine<R, M2> : never : never;
198
+ } & {
199
+ [K in keyof Transitions<M2>]: Transitions<M2>[K] extends (...args: infer A) => infer R ? R extends Machine<any> ? (...args: A) => ParallelMachine<M1, R> : never : never;
200
+ };
201
+ /**
202
+ * Creates a parallel machine by composing two independent machines.
203
+ *
204
+ * This function takes two machines and merges them into a single machine entity.
205
+ * Transitions from either machine can be called, and they will only affect
206
+ * their respective part of the combined state.
207
+ *
208
+ * NOTE: This primitive assumes that the transition names between the two
209
+ * machines do not collide. If both machines have a transition named `next`,
210
+ * the behavior is undefined.
211
+ *
212
+ * @param m1 The first machine instance.
213
+ * @param m2 The second machine instance.
214
+ * @returns A new ParallelMachine instance.
215
+ */
216
+ export declare function createParallelMachine<M1 extends Machine<any>, M2 extends Machine<any>>(m1: M1, m2: M2): ParallelMachine<M1, M2>;
217
+ export type RemapTransitions<M extends Machine<any>, T> = {
218
+ [K in keyof Transitions<M>]: Transitions<M>[K] extends (...args: infer A) => any ? (...args: A) => T : never;
219
+ };
220
+ export {};
221
+ //# sourceMappingURL=higher-order.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"higher-order.d.ts","sourceRoot":"","sources":["../../src/higher-order.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,WAAW,EACX,OAAO,EACP,WAAW,EAGX,OAAO,EAER,MAAM,SAAS,CAAC;AAMjB;;GAEG;AACH,KAAK,YAAY,CAAC,CAAC,IAAI,CAAC,SAAS,WAAW,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC,CAAA;CAAE,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAE7E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,eAAe,CAC7B,CAAC,SAAS,WAAW,CAAC;IAAE,KAAK,EAAE,WAAW,CAAC,GAAG,CAAC,CAAA;CAAE,CAAC,EAClD,CAAC,SAAS,MAAM,YA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