@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.
- package/README.md +288 -272
- package/dist/cjs/development/index.js +1269 -16
- package/dist/cjs/development/index.js.map +4 -4
- package/dist/cjs/production/index.js +5 -5
- package/dist/esm/development/index.js +1269 -16
- package/dist/esm/development/index.js.map +4 -4
- package/dist/esm/production/index.js +5 -5
- package/dist/types/extract.d.ts +40 -4
- package/dist/types/extract.d.ts.map +1 -1
- package/dist/types/generators.d.ts +40 -9
- package/dist/types/generators.d.ts.map +1 -1
- package/dist/types/higher-order.d.ts +221 -0
- package/dist/types/higher-order.d.ts.map +1 -0
- package/dist/types/index.d.ts +65 -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 +105 -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 +313 -0
- package/dist/types/utils.d.ts.map +1 -0
- package/package.json +2 -2
- package/src/adapters.ts +407 -0
- package/src/extract.ts +180 -8
- package/src/generators.ts +25 -25
- package/src/higher-order.ts +364 -0
- package/src/index.ts +215 -9
- package/src/middleware.ts +2325 -0
- package/src/primitives.ts +194 -3
- package/src/runtime-extract.ts +15 -0
- package/src/utils.ts +386 -5
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
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 r=C(t,e,!0);console.log(JSON.stringify(r,null,2))}catch(r){console.error("❌ Error:",r),process.exit(1)}}require.main===module&&A();function k(t){return typeof t!="function"?null:t[M]||null}function m(t){let e={on:{}},r=[];for(let o in t){let n=t[o];if(typeof n!="function")continue;let i=k(n);if(i&&(i.invoke&&r.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)),e.on[o]=a}}return r.length>0&&(e.invoke=r),e}function z(t,e){let r={id:e.id,initial:e.initial,states:{}};e.description&&(r.description=e.description);for(let[o,n]of Object.entries(t))r.states[o]=m(n);return r}function B(t,e){let r=e.stateName||t.constructor.name||"State";return{id:e.id,initial:r,states:{[r]:m(t)}}}function U(t,e){let r=t,o=s=>{r=s,e==null||e(s)},{context:n,...i}=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},i);return o(d),d}}});return{get state(){return r},get context(){return r.context},actions:a,setState:o}}function ne(t,e,r){let o=()=>{let i=t.getContext(),a=r(i),s=e[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(i)},n=new Proxy({},{get(i,a){let s=o(),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 o()},actions:n}}function re(t,e){let r=U(e),o=t(r),n=o.next();for(;!n.done;)n=o.next();return n.value}function oe(t,e){let r=t(e),o=r.next();for(;!o.done;)o=r.next();return o.value}var S=class{constructor(e){this.store=e}get context(){return this.store.getContext()}setContext(e){this.store.setContext(e)}};function ie(t,e){let r=new t(e);return new Proxy({},{get(o,n){let i=e.getContext();if(n in i)return i[n];let a=r[n];if(typeof a=="function")return(...s)=>a.apply(r,s)},set(o,n,i){let a=e.getContext();if(n in a){let s={...a,[n]:i};return e.setContext(s),!0}return!1},has(o,n){let i=e.getContext();return n in i||typeof r[n]=="function"},ownKeys(o){let n=e.getContext(),i=Object.keys(n),a=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter(s=>s!=="constructor"&&typeof r[s]=="function");return Array.from(new Set([...i,...a]))},getOwnPropertyDescriptor(o,n){let i=e.getContext();if(n in i||typeof r[n]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function ae(t,e,r){let o=()=>{let n=r(t),i=e[n];if(!i)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(n)}".`);return i(t)};return new Proxy(t,{get(n,i,a){if(i in n)return n[i];let s=o(),u=s[i];if(typeof u=="function")return(...l)=>{let f=u.apply(s.context,l);if(typeof f!="object"||f===null){console.warn(`[MutableMachine] Transition "${String(i)}" 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,i,a,s){return n[i]=a,!0},has(n,i){let a=o();return i in n||typeof a[i]=="function"}})}function y(t,e){return Object.assign({context:t},e)}function se(t,e){return Object.assign({context:t},e)}function ce(){return t=>{let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,function(...n){let i=o(this,...n);return y(i,e)}]));return r=>y(r,e)}}function ue(t,e){let{context:r,...o}=t,n=typeof e=="function"?e(r):e;return y(n,o)}function le(t,e){let{context:r,...o}=t,n={...o,...e};return y(r,n)}function xe(t,e){let{context:r,...o}=t,n={...o,...e};return y(r,n)}function de(t){let{context:e,...r}=t;return o=>y(o,r)}function fe(t,e,r){let o=t.context[e],n=r[o];if(!n)throw new Error(`No handler found for state: ${String(o)}`);return n(t.context)}function ye(t,e,r){return t.context[e]===r}function Me(t,e){let r=t;async function o(n){let i=r[n.type];if(typeof i!="function")throw new Error(`[Machine] Unknown event type '${String(n.type)}' on current state.`);return r=await i.apply(r.context,n.args),e==null||e(r),r}return{get state(){return r.context},dispatch:o}}var j=class{constructor(e){this.context=e}};function ge(t,e){let{context:r,...o}=t;return y(e(r),o)}
|
|
1
|
+
"use strict";var I=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var ot=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},it=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of nt(t))!rt.call(e,o)&&o!==n&&I(e,o,{get:()=>t[o],enumerable:!(r=tt(t,o))||r.enumerable});return e};var at=e=>it(I({},"__esModule",{value:!0}),e);var vt={};ot(vt,{BoundMachine:()=>W,META_KEY:()=>xe,MachineBase:()=>T,MultiMachineBase:()=>J,RUNTIME_META:()=>P,action:()=>me,bindTransitions:()=>ae,branch:()=>Ge,call:()=>Qe,chain:()=>De,combine:()=>Le,combineFactories:()=>Tt,compose:()=>Be,composeTyped:()=>j,createAsyncMachine:()=>Ct,createCustomMiddleware:()=>$e,createEnsemble:()=>dt,createEvent:()=>Je,createFetchMachine:()=>ht,createFlow:()=>ue,createMachine:()=>E,createMachineBuilder:()=>Et,createMachineFactory:()=>mt,createMiddleware:()=>w,createMiddlewareRegistry:()=>We,createMultiMachine:()=>Mt,createMutableMachine:()=>ft,createParallelMachine:()=>ee,createPipeline:()=>_e,createRunner:()=>Pe,delegateToChild:()=>xt,describe:()=>he,extendTransitions:()=>bt,extractFromInstance:()=>Fe,extractFunctionMetadata:()=>U,extractMachine:()=>D,extractMachines:()=>Ee,extractStateNode:()=>K,generateChart:()=>V,generateStatechart:()=>Se,guard:()=>z,guarded:()=>ge,hasState:()=>Ft,inDevelopment:()=>He,invoke:()=>Ce,isConditionalMiddleware:()=>Ve,isMiddlewareFn:()=>ie,isState:()=>Ue,logState:()=>Xe,matchMachine:()=>St,mergeContext:()=>qe,metadata:()=>be,next:()=>Rt,overrideTransitions:()=>wt,pipeTransitions:()=>Ye,run:()=>L,runAsync:()=>Me,runMachine:()=>Pt,runSequence:()=>de,runWithDebug:()=>ye,runWithEnsemble:()=>yt,runWithRunner:()=>ut,setContext:()=>v,step:()=>ce,stepAsync:()=>fe,toggle:()=>pt,transitionTo:()=>pe,when:()=>_,whenContext:()=>Ie,whenGuard:()=>we,withAnalytics:()=>Ae,withDebugging:()=>Ke,withErrorReporting:()=>ke,withHistory:()=>ne,withLogging:()=>ve,withPerformanceMonitoring:()=>Ne,withPermissions:()=>je,withRetry:()=>ze,withSnapshot:()=>re,withTimeTravel:()=>oe,withValidation:()=>Oe,yieldMachine:()=>le});module.exports=at(vt);function L(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=n.next(r);if(i)return o;r=o}}function ce(e){return function*(){return yield e}()}function le(e){return e}function de(e,t){return t.reduce((n,r)=>L(r,n),e)}function ue(e){return e}function ye(e,t,n=(r,o)=>{console.log(`Step ${r}:`,o.context)}){let r=e(t),o=t,i=0;for(n(i,o);;){let{value:a,done:s}=r.next(o);if(s)return console.log("Final:",a),a;o=a,i++,n(i,o)}}async function Me(e,t){let n=e(t),r=t;for(;;){let{value:o,done:i}=await n.next(r);if(i)return o;r=o}}async function*fe(e){return yield e}var xe=Symbol("MachineMeta"),P=Symbol("__machine_runtime_meta__");function R(e,t){let n=e[P]||{},r={...n,...t};t.guards&&n.guards?r.guards=[...t.guards,...n.guards]:t.guards&&(r.guards=[...t.guards]),t.actions&&n.actions?r.actions=[...t.actions,...n.actions]:t.actions&&(r.actions=[...t.actions]),Object.defineProperty(e,P,{value:r,enumerable:!1,writable:!1,configurable:!0})}function pe(e,t){return R(t,{target:e.name||e.toString()}),t}function he(e,t){return R(t,{description:e}),t}function ge(e,t){return R(t,{guards:[e]}),t}function Ce(e,t){return R(t,{invoke:{src:e.src,onDone:e.onDone.name||e.onDone.toString(),onError:e.onError.name||e.onError.toString(),description:e.description}}),t}function me(e,t){return R(t,{actions:[e]}),t}function z(e,t,n={}){let{onFail:r="throw",errorMessage:o,description:i}=n,a={...n,onFail:r,errorMessage:o,description:i},s=async function(...c){let d=typeof this=="object"&&"context"in this,u=d?this.context:this;if(await Promise.resolve(e(u,...c))){let y=d?this.context:this;return t.apply(y,c)}else if(r==="throw"){let y=o||"Guard condition failed";throw new Error(y)}else if(r==="ignore"){if(d)return this;throw new Error('Cannot use "ignore" mode with context-only binding. Use full machine binding or provide fallback.')}else if(typeof r=="function"){if(d)return r.apply(this,c);throw new Error("Cannot use function fallback with context-only binding. Use full machine binding.")}else return r};return Object.defineProperty(s,"__guard",{value:!0,enumerable:!1}),Object.defineProperty(s,"condition",{value:e,enumerable:!1}),Object.defineProperty(s,"transition",{value:t,enumerable:!1}),Object.defineProperty(s,"options",{value:a,enumerable:!1}),R(s,{description:i||"Runtime guarded transition",guards:[{name:"runtime_guard",description:i||"Runtime condition check"}]}),s}function we(e){return{do(t){let n=z(e,t);return n.else=function(r){return z(e,t,{onFail:r})},n}}}function be(e,t){return t}var g=require("ts-morph");function Te(e){return g.Node.isIdentifier(e)?e.getText():g.Node.isTypeOfExpression(e)?e.getExpression().getText():"unknown"}function $(e){if(!g.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(g.Node.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();o&&(g.Node.isStringLiteral(o)||g.Node.isNumericLiteral(o)?t[r]=o.getLiteralValue():o.getText()==="true"||o.getText()==="false"?t[r]=o.getText()==="true":g.Node.isIdentifier(o)?t[r]=o.getText():g.Node.isObjectLiteralExpression(o)?t[r]=$(o):g.Node.isArrayLiteralExpression(o)&&(t[r]=o.getElements().map(i=>g.Node.isObjectLiteralExpression(i)?$(i):i.getText())))}return t}function st(e){if(!g.Node.isObjectLiteralExpression(e))return{};let t={};for(let n of e.getProperties())if(g.Node.isPropertyAssignment(n)){let r=n.getName(),o=n.getInitializer();if(!o)continue;r==="onDone"||r==="onError"?t[r]=Te(o):g.Node.isStringLiteral(o)?t[r]=o.getLiteralValue():g.Node.isIdentifier(o)&&(t[r]=o.getText())}return t}function B(e,t=!1){if(!g.Node.isCallExpression(e))return null;let n=e.getExpression(),r=g.Node.isIdentifier(n)?n.getText():null;if(!r)return null;let o={},i=e.getArguments();switch(r){case"transitionTo":i[0]&&(o.target=Te(i[0]));break;case"describe":if(i[0]&&g.Node.isStringLiteral(i[0])&&(o.description=i[0].getLiteralValue()),i[1]&&g.Node.isCallExpression(i[1])){let a=B(i[1],t);a&&Object.assign(o,a)}break;case"guarded":if(i[0]){let a=$(i[0]);Object.keys(a).length>0&&(o.guards=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=B(i[1],t);a&&Object.assign(o,a)}break;case"invoke":if(i[0]){let a=st(i[0]);Object.keys(a).length>0&&(o.invoke=a)}break;case"action":if(i[0]){let a=$(i[0]);Object.keys(a).length>0&&(o.actions=[a])}if(i[1]&&g.Node.isCallExpression(i[1])){let a=B(i[1],t);a&&Object.assign(o,a)}break;default:return null}return Object.keys(o).length>0?o:null}function ct(e,t=!1){if(!g.Node.isPropertyDeclaration(e))return t&&console.error(" ⚠️ Not a property declaration"),null;let n=e.getInitializer();if(!n)return t&&console.error(" ⚠️ No initializer"),null;if(!g.Node.isCallExpression(n))return t&&console.error(" ⚠️ Initializer is not a call expression"),null;let r=B(n,t);return r&&t&&console.error(" ✅ Extracted metadata:",JSON.stringify(r,null,2)),r}function G(e,t=!1){let n={on:{}},r=e.getDeclarations()[0];if(!r||!g.Node.isClassDeclaration(r))return t&&console.error(`⚠️ Warning: Could not get class declaration for ${e.getName()}`),n;let o=e.getName();t&&console.error(` Analyzing state: ${o}`);for(let i of r.getInstanceMembers()){let a=i.getName();t&&console.error(` Checking member: ${a}`);let s=ct(i,t);if(!s)continue;t&&console.error(` Found transition: ${a}`);let{invoke:c,actions:d,guards:u,...x}=s;if(c&&(n.invoke||(n.invoke=[]),n.invoke.push({src:c.src,onDone:{target:c.onDone},onError:{target:c.onError},description:c.description}),t&&console.error(` → Invoke: ${c.src}`)),x.target){let y={target:x.target};x.description&&(y.description=x.description),u&&(y.cond=u.map(f=>f.name).join(" && "),t&&console.error(` → Guard: ${y.cond}`)),d&&d.length>0&&(y.actions=d.map(f=>f.name),t&&console.error(` → Actions: ${y.actions.join(", ")}`)),n.on[a]=y,t&&console.error(` → Target: ${x.target}`)}}return n}function lt(e,t,n,r,o=!1){let i=G(t,o);if(r){o&&console.error(` 👪 Analyzing children for state: ${e}`),i.initial=r.initialState,i.states={};for(let a of r.classes){let s=n.getClass(a);if(s){let c=s.getSymbolOrThrow();i.states[a]=G(c,o)}else console.warn(`⚠️ Warning: Child class '${a}' not found.`)}}return i}function D(e,t,n=!1){n&&(console.error(`
|
|
2
|
+
🔍 Analyzing machine: ${e.id}`),console.error(` Source: ${e.input}`));let r=t.getSourceFile(e.input);if(!r)throw new Error(`Source file not found: ${e.input}`);if(e.parallel){n&&console.error(" ⏹️ Parallel machine detected. Analyzing regions.");let i={id:e.id,type:"parallel",states:{}};e.description&&(i.description=e.description);for(let a of e.parallel.regions){n&&console.error(` 📍 Analyzing region: ${a.name}`);let s={};for(let c of a.classes){let d=r.getClass(c);if(d){let u=d.getSymbolOrThrow();s[c]=G(u,n)}else console.warn(`⚠️ Warning: Class '${c}' not found for region '${a.name}'.`)}i.states[a.name]={initial:a.initialState,states:s}}return n&&console.error(` ✅ Extracted ${e.parallel.regions.length} parallel regions`),i}if(!e.initialState||!e.classes)throw new Error(`Machine config for '${e.id}' must have either 'parallel' or 'initialState'/'classes'.`);let o={id:e.id,initial:e.initialState,states:{}};e.description&&(o.description=e.description);for(let i of e.classes){let a=r.getClass(i);if(!a){console.warn(`⚠️ Warning: Class '${i}' not found in '${e.input}'. Skipping.`);continue}let s=a.getSymbolOrThrow(),c=i===e.initialState&&e.children,d=lt(i,s,r,c?e.children:void 0,n);o.states[i]=d}return n&&console.error(` ✅ Extracted ${e.classes.length} states`),o}function Ee(e){var o;let t=(o=e.verbose)!=null?o:!1;t&&(console.error(`
|
|
3
|
+
📊 Starting statechart extraction`),console.error(` Machines to extract: ${e.machines.length}`));let n=new g.Project;n.addSourceFilesAtPaths("src/**/*.ts"),n.addSourceFilesAtPaths("examples/**/*.ts");let r=[];for(let i of e.machines)try{let a=D(i,n,t);r.push(a)}catch(a){console.error(`❌ Error extracting machine '${i.id}':`,a),t||console.error(" Run with --verbose for more details")}return t&&console.error(`
|
|
4
|
+
✅ Extraction complete: ${r.length}/${e.machines.length} machines extracted`),r}function V(){let e={input:"examples/authMachine.ts",classes:["LoggedOutMachine","LoggingInMachine","LoggedInMachine","SessionExpiredMachine","ErrorMachine"],id:"auth",initialState:"LoggedOutMachine",description:"Authentication state machine"};console.error("🔍 Using legacy generateChart function"),console.error(`⚠️ Consider using extractMachines() with a config file instead
|
|
5
|
+
`);let t=new g.Project;t.addSourceFilesAtPaths("src/**/*.ts"),t.addSourceFilesAtPaths("examples/**/*.ts");try{let n=D(e,t,!0);console.log(JSON.stringify(n,null,2))}catch(n){console.error("❌ Error:",n),process.exit(1)}}require.main===module&&V();function U(e){return typeof e!="function"?null:e[P]||null}function K(e){let t={on:{}},n=[];for(let r in e){let o=e[r];if(typeof o!="function")continue;let i=U(o);if(i){if(i.invoke&&n.push({src:i.invoke.src,onDone:{target:i.invoke.onDone},onError:{target:i.invoke.onError},description:i.invoke.description}),i.target){let a={target:i.target};i.description&&(a.description=i.description),i.guards&&i.guards.length>0&&(a.cond=i.guards.map(s=>s.name).join(" && ")),i.actions&&i.actions.length>0&&(a.actions=i.actions.map(s=>s.name)),t.on[r]=a}else if(i.guards&&i.guards.length>0){let a={target:"GuardedTransition",cond:i.guards.map(s=>s.name).join(" && ")};i.description&&(a.description=i.description),t.on[r]=a}}}return n.length>0&&(t.invoke=n),t}function Se(e,t){let n={id:t.id,initial:t.initial,states:{}};t.description&&(n.description=t.description);for(let[r,o]of Object.entries(e))n.states[r]=K(o);return n}function Fe(e,t){let n=t.stateName||e.constructor.name||"State";return{id:t.id,initial:n,states:{[n]:K(e)}}}function Pe(e,t){let n=e,r=s=>{n=s,t==null||t(s)},{context:o,...i}=e,a=new Proxy({},{get(s,c){let d=n[c];if(typeof d=="function")return(...u)=>{let x=d.apply(n.context,u),y=Object.assign({context:x.context},i);return r(y),y}}});return{get state(){return n},get context(){return n.context},actions:a,setState:r}}function dt(e,t,n){let r=()=>{let i=e.getContext(),a=n(i),s=t[a];if(!s)throw new Error(`[Ensemble] Invalid state: No factory found for state "${String(a)}".`);return s(i)},o=new Proxy({},{get(i,a){let s=r(),c=s[a];if(typeof c!="function")throw new Error(`[Ensemble] Transition "${a}" is not valid in the current state.`);return(...d)=>c.apply(s.context,d)}});return{get context(){return e.getContext()},get state(){return r()},actions:o}}function ut(e,t){let n=Pe(t),r=e(n),o=r.next();for(;!o.done;)o=r.next();return o.value}function yt(e,t){let n=e(t),r=n.next();for(;!r.done;)r=n.next();return r.value}var J=class{constructor(t){this.store=t}get context(){return this.store.getContext()}setContext(t){this.store.setContext(t)}};function Mt(e,t){let n=new e(t);return new Proxy({},{get(r,o){let i=t.getContext();if(o in i)return i[o];let a=n[o];if(typeof a=="function")return(...s)=>a.apply(n,s)},set(r,o,i){let a=t.getContext();if(o in a){let s={...a,[o]:i};return t.setContext(s),!0}return!1},has(r,o){let i=t.getContext();return o in i||typeof n[o]=="function"},ownKeys(r){let o=t.getContext(),i=Object.keys(o),a=Object.getOwnPropertyNames(Object.getPrototypeOf(n)).filter(s=>s!=="constructor"&&typeof n[s]=="function");return Array.from(new Set([...i,...a]))},getOwnPropertyDescriptor(r,o){let i=t.getContext();if(o in i||typeof n[o]=="function")return{value:void 0,writable:!0,enumerable:!0,configurable:!0}}})}function ft(e,t,n){let r=()=>{let o=n(e),i=t[o];if(!i)throw new Error(`[MutableMachine] Invalid state: No factory for state "${String(o)}".`);return i(e)};return new Proxy(e,{get(o,i,a){if(i in o)return o[i];let s=r(),c=s[i];if(typeof c=="function")return(...d)=>{let u=c.apply(s.context,d);if(typeof u!="object"||u===null){console.warn(`[MutableMachine] Transition "${String(i)}" did not return a valid context object. State may be inconsistent.`);return}Object.keys(o).forEach(x=>delete o[x]),Object.assign(o,u)}},set(o,i,a,s){return o[i]=a,!0},has(o,i){let a=r();return i in o||typeof a[i]=="function"}})}function xt(e){return function(...t){let n=this.context.child;if(typeof n[e]=="function"){let r=n[e](...t);return v(this,{...this.context,child:r})}return this}}function pt(e){return function(){return typeof this.context[e]!="boolean"&&console.warn(`[toggle primitive] Property '${String(e)}' is not a boolean. Toggling may have unexpected results.`),v(this,{...this.context,[e]:!this.context[e]})}}var q=class extends T{constructor(n){super({status:"idle"});this.config=n;this.fetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},S=class extends T{constructor(n,r,o){super({status:"loading",abortController:new AbortController,attempts:o});this.config=n;this.params=r;this.succeed=n=>{var r,o;return(o=(r=this.config).onSuccess)==null||o.call(r,n),new X(this.config,{status:"success",data:n})};this.fail=n=>{var o,i,a;let r=(o=this.config.maxRetries)!=null?o:3;return this.context.attempts<r?new Y(this.config,this.params,n,this.context.attempts):((a=(i=this.config).onError)==null||a.call(i,n),new Q(this.config,{status:"error",error:n}))};this.cancel=()=>(this.context.abortController.abort(),new Z(this.config));this.execute()}async execute(){}},Y=class extends T{constructor(n,r,o,i){super({status:"retrying",error:o,attempts:i});this.config=n;this.params=r;this.retry=n=>new S(this.config,n!=null?n:this.params,this.context.attempts+1)}},X=class extends T{constructor(n,r){super(r);this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},Q=class extends T{constructor(n,r){super(r);this.config=n;this.retry=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}},Z=class extends T{constructor(n){super({status:"canceled"});this.config=n;this.refetch=n=>new S(this.config,n!=null?n:this.config.initialParams,1)}};function ht(e){return new q(e)}function ee(e,t){let n={...e.context,...t.context},r={...e},o={...t};delete r.context,delete o.context;let i={};for(let a in r){let s=r[a];i[a]=(...c)=>{let d=s.apply(e.context,c);return ee(d,t)}}for(let a in o){let s=o[a];i[a]=(...c)=>{let d=s.apply(t.context,c);return ee(e,d)}}return{context:n,...i}}var Re=Symbol("CANCEL");function w(e,t,n={}){let{mode:r="auto",exclude:o=["context"]}=n,i={};for(let a in e){if(!Object.prototype.hasOwnProperty.call(e,a))continue;let s=e[a];if(a==="context"){i.context=s;continue}if(o.includes(a)){i[a]=s;continue}if(typeof s!="function"||a.startsWith("_")){i[a]=s;continue}i[a]=gt(a,s,e,t,r)}return i}function gt(e,t,n,r,o){return function(...a){let s=n.context,c={transitionName:e,context:s,args:a},d=()=>{try{if(r.before){let f=r.before(c);if(f===Re)return n;if(f instanceof Promise)throw new Error(`Middleware mode is 'sync' but before hook returned Promise for transition: ${e}`)}let y=t.call(this,...a);if(y instanceof Promise)return u(y,s);if(r.after){let f={transitionName:e,prevContext:s,nextContext:y.context,args:a};if(r.after(f)instanceof Promise)throw new Error(`Middleware mode is 'sync' but after hook returned Promise for transition: ${e}`)}return y}catch(y){if(r.error){let f={transitionName:e,context:s,args:a,error:y},l=r.error(f);if(l instanceof Promise)throw l.catch(()=>{}),y;if(l&&typeof l=="object"&&"context"in l)return l}throw y}},u=async(y,f)=>{try{let l=await y;if(r.after){let h={transitionName:e,prevContext:f,nextContext:l.context,args:a};await r.after(h)}return l}catch(l){if(r.error){let h={transitionName:e,context:f,args:a,error:l},M=await r.error(h);if(M&&typeof M=="object"&&"context"in M)return M}throw l}},x=async()=>{try{if(r.before&&await r.before(c)===Re)return n;let y=await t.call(this,...a);if(r.after){let f={transitionName:e,prevContext:s,nextContext:y.context,args:a};await r.after(f)}return y}catch(y){if(r.error){let f={transitionName:e,context:s,args:a,error:y},l=await r.error(f);if(l&&typeof l=="object"&&"context"in l)return l}throw y}};return o==="async"?x():d()}}function ve(e,t={}){let{logger:n=console.log,includeContext:r=!0,includeArgs:o=!0}=t;return w(e,{before:({transitionName:i,args:a})=>{let s=o&&a.length>0?` ${JSON.stringify(a)}`:"";n(`→ ${i}${s}`)},after:({transitionName:i,nextContext:a})=>{let s=r?` ${JSON.stringify(a)}`:"";n(`✓ ${i}${s}`)}})}function Ae(e,t,n={}){let{eventPrefix:r="state_transition",includePrevContext:o=!1,includeArgs:i=!0}=n;return w(e,{after:async({transitionName:a,prevContext:s,nextContext:c,args:d})=>{let u={transition:a,to:c};o&&(u.from=s),i&&d.length>0&&(u.args=d),await t(`${r}.${a}`,u)}},{mode:"async"})}function Oe(e,t,n){return w(e,{before:r=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(i===!1)throw new Error(`Validation failed for transition: ${r.transitionName}`)});if(o===!1)throw new Error(`Validation failed for transition: ${r.transitionName}`)}},{mode:"auto",...n})}function je(e,t,n){return w(e,{before:r=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(!i)throw new Error(`Unauthorized transition: ${r.transitionName}`)});if(!o)throw new Error(`Unauthorized transition: ${r.transitionName}`)}},{mode:"auto",...n})}function ke(e,t,n={}){let{includeContext:r=!0,includeArgs:o=!0,mode:i}=n;return w(e,{error:async({transitionName:a,context:s,args:c,error:d})=>{let u={transition:a};r&&(u.context=s),o&&c.length>0&&(u.args=c),await Promise.resolve(t(d,u))}},{mode:i})}function Ne(e,t){let n=new Map;return w(e,{before:({transitionName:r})=>{n.set(r,performance.now())},after:({transitionName:r,nextContext:o})=>{let i=n.get(r);if(i){let a=performance.now()-i;n.delete(r);let s=t({transitionName:r,duration:a,context:o});if(s instanceof Promise)return s}}},{mode:"auto"})}function ze(e,t={}){let{maxRetries:n=3,delay:r=1e3,backoffMultiplier:o=1,shouldRetry:i=()=>!0,onRetry:a}=t,s={};for(let c in e){if(!Object.prototype.hasOwnProperty.call(e,c))continue;let d=e[c];if(c==="context"||typeof d!="function"){s[c]=d;continue}s[c]=async function(...x){let y;for(let f=0;f<=n;f++)try{return await d.call(this,...x)}catch(l){if(y=l,f===n||!i(y))break;a==null||a(f+1,y);let h=r*Math.pow(o,f);await new Promise(M=>setTimeout(M,h))}throw y}}return s}function ne(e,t={}){let{maxSize:n,serializer:r,filter:o,onEntry:i,_isRewrap:a=!1}=t,s=[],c=0,d=w(e,{before:({transitionName:u,args:x})=>{if(o&&!o(u,x))return;let y={id:`entry-${c++}`,transitionName:u,args:[...x],timestamp:Date.now()};if(r)try{y.serializedArgs=r.serialize(x)}catch(f){console.error("Failed to serialize history args:",f)}s.push(y),n&&s.length>n&&s.shift(),i==null||i(y)}},{exclude:["context","history","clearHistory"]});if(!a)for(let u in d){if(!Object.prototype.hasOwnProperty.call(d,u))continue;let x=d[u];if(typeof x=="function"&&!u.startsWith("_")&&u!=="context"&&!["history","clearHistory"].includes(u)){let y=x;d[u]=function(...f){let l=y.apply(this,f);if(l&&typeof l=="object"&&"context"in l&&!("history"in l)){let h=w(l,{before:({transitionName:M,args:C})=>{if(o&&!o(M,C))return;let p={id:`entry-${c++}`,transitionName:M,args:[...C],timestamp:Date.now()};if(r)try{p.serializedArgs=r.serialize(C)}catch(b){console.error("Failed to serialize history args:",b)}s.push(p),n&&s.length>n&&s.shift(),i==null||i(p)}},{exclude:["context","history","clearHistory"]});return Object.assign(h,{history:s,clearHistory:()=>{s.length=0,c=0}})}return l}}}return Object.assign(d,{history:s,clearHistory:()=>{s.length=0,c=0}})}function re(e,t={}){let{maxSize:n,serializer:r,captureSnapshot:o,onlyIfChanged:i=!1,filter:a,onSnapshot:s,_extraExclusions:c=[],_isRewrap:d=!1}=t,u=[],x=0,y=w(e,{after:({transitionName:l,prevContext:h,nextContext:M})=>{if(a&&!a(l)||i&&!(JSON.stringify(h)!==JSON.stringify(M)))return;let C={id:`snapshot-${x++}`,transitionName:l,before:{...h},after:{...M},timestamp:Date.now()};if(r)try{C.serializedBefore=r.serialize(h),C.serializedAfter=r.serialize(M)}catch(p){console.error("Failed to serialize snapshot:",p)}if(o)try{C.diff=o(h,M)}catch(p){console.error("Failed to capture snapshot:",p)}u.push(C),n&&u.length>n&&u.shift(),s==null||s(C)}},{exclude:["context","snapshots","clearSnapshots","restoreSnapshot",...c]}),f=l=>{let{context:h,...M}=e;return{context:l,...M}};if(!d)for(let l in y){if(!Object.prototype.hasOwnProperty.call(y,l))continue;let h=y[l];if(typeof h=="function"&&!l.startsWith("_")&&l!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(l)){let M=h;y[l]=function(...C){let p=M.apply(this,C);if(p&&typeof p=="object"&&"context"in p&&!("snapshots"in p)){for(let m in p){if(!Object.prototype.hasOwnProperty.call(p,m))continue;let A=p[m];if(typeof A=="function"&&!m.startsWith("_")&&m!=="context"&&!["snapshots","clearSnapshots","restoreSnapshot","history","clearHistory"].includes(m)){let Ze=A;p[m]=function(...et){let k=p.context,O=Ze.apply(this,et);if(O&&typeof O=="object"&&"context"in O){let N=O.context;if(!(a&&!a(m))){let se=!0;if(i&&(se=JSON.stringify(k)!==JSON.stringify(N)),se){let F={id:`snapshot-${x++}`,transitionName:m,before:{...k},after:{...N},timestamp:Date.now()};if(r)try{F.serializedBefore=r.serialize(k),F.serializedAfter=r.serialize(N)}catch(H){console.error("Failed to serialize snapshot:",H)}if(o)try{F.diff=o(k,N)}catch(H){console.error("Failed to capture snapshot:",H)}u.push(F),n&&u.length>n&&u.shift(),s==null||s(F)}}}return O}}}let b=Object.assign(p,{snapshots:u,clearSnapshots:()=>{u.length=0,x=0},restoreSnapshot:f});return e.history&&(b.history=e.history,b.clearHistory=e.clearHistory),b}return p}}}return Object.assign(y,{snapshots:u,clearSnapshots:()=>{u.length=0,x=0},restoreSnapshot:f})}function oe(e,t={}){let{maxSize:n,serializer:r,onRecord:o}=t,i=[],a=[],s=0,c=0,d=(l,h)=>{let M={id:`entry-${s++}`,transitionName:l,args:[...h],timestamp:Date.now()};if(r)try{M.serializedArgs=r.serialize(h)}catch(C){console.error("Failed to serialize history args:",C)}i.push(M),n&&i.length>n&&i.shift(),o==null||o("history",M)},u=(l,h,M)=>{let C={id:`snapshot-${c++}`,transitionName:l,before:{...h},after:{...M},timestamp:Date.now()};if(r)try{C.serializedBefore=r.serialize(h),C.serializedAfter=r.serialize(M)}catch(p){console.error("Failed to serialize snapshot:",p)}a.push(C),n&&a.length>n&&a.shift(),o==null||o("snapshot",C)},x=l=>{let{context:h,...M}=e;return Object.assign({context:l},l,M)},y=(l=0)=>{if(l<0||l>=a.length)throw new Error(`Invalid snapshot index: ${l}`);let h=x(a[l].before),M=a[l],C=i.findIndex(p=>p.transitionName===M.transitionName&&p.timestamp===M.timestamp);if(C===-1)throw new Error("Could not find matching history entry for snapshot");for(let p=C;p<i.length;p++){let b=i[p],m=h[b.transitionName];if(typeof m=="function")try{h=m.apply(h.context,b.args)}catch(A){throw console.error(`Replay failed at step ${p}:`,A),A}}return h},f=l=>{let h={...l};for(let M in l){if(!Object.prototype.hasOwnProperty.call(l,M))continue;let C=l[M];typeof C=="function"&&!M.startsWith("_")&&M!=="context"&&!["history","snapshots","clearHistory","clearSnapshots","clearTimeTravel","restoreSnapshot","replayFrom"].includes(M)&&(h[M]=function(...p){d(M,p);let b=h.context,m=C.apply(this,p);return m&&typeof m=="object"&&"context"in m&&u(M,b,m.context),m&&typeof m=="object"&&"context"in m?f(m):m})}return Object.assign(h,{history:i,snapshots:a,clearHistory:()=>{i.length=0,s=0},clearSnapshots:()=>{a.length=0,c=0},clearTimeTravel:()=>{i.length=0,a.length=0,s=0,c=0},restoreSnapshot:x,replayFrom:y})};return f(e)}function Be(e,...t){return t.reduce((n,r)=>r(n),e)}function $e(e,t){return n=>w(n,e,t)}function j(e,...t){return t.reduce((n,r)=>r(n),e)}function De(e){return new te(e)}var te=class e{constructor(t){this.machine=t}with(t){let n=t(this.machine);return new e(n)}build(){return this.machine}};function Ke(e){return oe(re(ne(e)))}function _e(e={}){let{continueOnError:t=!1,logErrors:n=!0,onError:r}=e;return(o,...i)=>{let a=o,s=[];for(let c=0;c<i.length;c++){let d=i[c];try{if("middleware"in d&&"when"in d){if(!d.when(a))continue;a=d.middleware(a)}else a=d(a)}catch(u){let x=u instanceof Error?u:new Error(String(u));if(s.push({error:x,middlewareIndex:c}),n&&console.error(`Middleware pipeline error at index ${c}:`,x),r==null||r(x,`middleware-${c}`),!t)break}}return{machine:a,errors:s,success:s.length===0}}}function We(){let e=new Map;return{register(t,n,r,o){if(e.has(t))throw new Error(`Middleware '${t}' is already registered`);return e.set(t,{name:t,middleware:n,description:r,priority:o}),this},unregister(t){return e.delete(t)},has(t){return e.has(t)},get(t){return e.get(t)},list(){return Array.from(e.values()).sort((t,n)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})},apply(t,n){let r=n.map(o=>{let i=e.get(o);if(!i)throw new Error(`Middleware '${o}' is not registered`);return i}).sort((o,i)=>{var a,s;return((a=o.priority)!=null?a:0)-((s=i.priority)!=null?s:0)});return j(t,...r.map(o=>o.middleware))},applyAll(t){let n=this.list();return j(t,...n.map(r=>r.middleware))}}}function _(e,t){let n=function(r){return t(r)?e(r):r};return n.middleware=e,n.when=t,n}function He(e){return _(e,()=>typeof process!="undefined"?!1:typeof window!="undefined"?!window.location.hostname.includes("production"):!1)}function Ie(e,t,n){return _(n,r=>r.context[e]===t)}function Le(...e){return t=>j(t,...e)}function Ge(e,t){return n=>{for(let[r,o]of e)if(r(n))return o(n);return t?t(n):n}}function ie(e){return typeof e=="function"&&e.length===1}function Ve(e){return e!==null&&"middleware"in e&&"when"in e&&ie(e.middleware)&&typeof e.when=="function"}function Ue(e,t){return e instanceof t}function Je(e,...t){return{type:e,args:t}}function qe(e,t){return v(e,n=>({...n,...t}))}async function Ye(e,...t){let n=e;for(let r of t)n=await r(n);return n}function Xe(e,t){return t?console.log(t,e.context):console.log(e.context),e}function Qe(e,t,...n){return e.apply(t,n)}function ae(e){return new Proxy(e,{get(t,n){let r=t[n];return typeof r=="function"?function(...o){let i=r.apply(t.context,o);return i&&typeof i=="object"&&"context"in i?ae(i):i}:r}})}var W=class e{constructor(t){return this.wrappedMachine=t,new Proxy(this,{get:(n,r)=>{if(r==="wrappedMachine")return Reflect.get(n,r);if(r==="context")return this.wrappedMachine.context;let o=this.wrappedMachine[r];return typeof o=="function"?(...i)=>{let a=o.apply(this.wrappedMachine.context,i);return a&&typeof a=="object"&&"context"in a?new e(a):a}:o}})}};function E(e,t){let n="context"in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!=="context")):t;return Object.assign({context:e},n)}function Ct(e,t){return Object.assign({context:e},t)}function mt(){return e=>{let t=Object.fromEntries(Object.entries(e).map(([n,r])=>[n,function(...o){let i=r(this,...o);return E(i,t)}]));return n=>E(n,t)}}function v(e,t){let{context:n,...r}=e,o=typeof t=="function"?t(n):t;return E(o,r)}function wt(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function bt(e,t){let{context:n,...r}=e,o={...r,...t};return E(n,o)}function Tt(e,t){return(...n)=>{let r=e(...n),o=t(),i={...r.context,...o.context},{context:a,...s}=r,{context:c,...d}=o,u={...s,...d};return E(i,u)}}function Et(e){let{context:t,...n}=e;return r=>E(r,n)}function St(e,t,n){let r=e.context[t],o=n[r];if(!o)throw new Error(`No handler found for state: ${String(r)}`);return o(e.context)}function Ft(e,t,n){return e.context[t]===n}function Pt(e,t){let n=e,r=null;async function o(i){r&&(r.abort(),r=null);let a=n[i.type];if(typeof a!="function")throw new Error(`[Machine] Unknown event type '${String(i.type)}' on current state.`);let s=new AbortController;r=s;try{let d=await a.apply(n.context,[...i.args,{signal:s.signal}]);return s.signal.aborted||(n=d,t==null||t(n)),n}finally{r===s&&(r=null)}}return{get state(){return n.context},dispatch:o,stop:()=>{r&&(r.abort(),r=null)}}}var T=class{constructor(t){this.context=t}};function Rt(e,t){let{context:n,...r}=e;return E(t(n),r)}
|