Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@zag-js/core

Package Overview
Dependencies
Maintainers
1
Versions
902
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@zag-js/core - npm Package Compare versions

Comparing version 0.0.0-dev-20220413091534 to 0.0.0-dev-20220413174154

dist/action-utils.d.ts.map

1

dist/action-utils.d.ts

@@ -7,1 +7,2 @@ import { StateMachine as S } from "./types";

export declare function determineActionsFn<TContext, TState extends S.StateSchema, TEvent extends S.EventObject>(values: S.Actions<TContext, TState, TEvent> | undefined, guardMap: S.GuardMap<TContext, TEvent> | undefined): (context: TContext, event: TEvent) => string | S.ExpressionWithMeta<TContext, TState, TEvent, void> | S.Action<TContext, TState, TEvent>[];
//# sourceMappingURL=action-utils.d.ts.map
import { StateMachine as S } from "./types";
export declare function createProxy<TContext, TState extends S.StateSchema, TEvent extends S.EventObject>(config: S.MachineConfig<TContext, TState, TEvent>): S.State<TContext, TState, TEvent>;
//# sourceMappingURL=create-proxy.d.ts.map

@@ -11,1 +11,2 @@ import { StateMachine as S } from "./types";

export declare function determineDelayFn<TContext, TEvent extends S.EventObject>(delay: S.Delay<TContext, TEvent> | undefined, delaysMap: S.DelayMap<TContext, TEvent> | undefined): (context: TContext, event: TEvent) => number;
//# sourceMappingURL=delay-utils.d.ts.map

@@ -21,1 +21,2 @@ import { StateMachine as S } from "./types";

export {};
//# sourceMappingURL=guard-utils.d.ts.map

@@ -7,1 +7,2 @@ export { proxy, ref, snapshot, subscribe } from "valtio/vanilla";

export type { StateMachine } from "./types";
//# sourceMappingURL=index.d.ts.map

@@ -1,2 +0,853 @@

var J=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var At=Object.prototype.hasOwnProperty;var wt=(e,t)=>{for(var n in t)J(e,n,{get:t[n],enumerable:!0})},jt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ot(t))!At.call(e,s)&&s!==n&&J(e,s,{get:()=>t[s],enumerable:!(i=Ct(t,s))||i.enumerable});return e};var Pt=e=>jt(J({},"__esModule",{value:!0}),e);var Ut={};wt(Ut,{Machine:()=>w,choose:()=>dt,createMachine:()=>Ht,guards:()=>pt,mergeProps:()=>gt,proxy:()=>j,ref:()=>L,snapshot:()=>N,subscribe:()=>P});module.exports=Pt(Ut);var Jt=Symbol(),$t=Symbol(),Dt=Symbol(),et=Object.getPrototypeOf,$=new WeakMap,Mt=e=>e&&($.has(e)?$.get(e):et(e)===Object.prototype||et(e)===Array.prototype);var nt=e=>Mt(e)&&e[Dt]||null,B=(e,t=!0)=>{$.set(e,t)};var V={},at=Symbol(),b=Symbol(),_=Symbol(),Lt=Symbol(),k=Symbol(),it=Symbol(),X=new WeakSet;function L(e){return X.add(e),e}var G=e=>typeof e=="object"&&e!==null,It=e=>G(e)&&!X.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer),st=new WeakMap,rt=1,ot=new WeakMap;function j(e={}){if(!G(e))throw new Error("object required");let t=st.get(e);if(t)return t;let n=rt,i=new Set,s=(l,a=++rt)=>{n!==a&&(n=a,i.forEach(u=>u(l,a)))},r=new Map,o=l=>{let a=r.get(l);return a||(a=(u,p)=>{let S=[...u];S[1]=[l,...S[1]],s(S,p)},r.set(l,a)),a},c=l=>{let a=r.get(l);return r.delete(l),a},h=(l,a)=>{let u=ot.get(a);if(u?.[0]===n)return u[1];let p=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return B(p,!0),ot.set(a,[n,p]),Reflect.ownKeys(l).forEach(S=>{let f=Reflect.get(l,S,a);if(X.has(f))B(f,!1),p[S]=f;else if(f instanceof Promise)if(k in f)p[S]=f[k];else{let W=f[it]||f;Object.defineProperty(p,S,{get(){if(k in f)return f[k];throw W}})}else f?.[b]?p[S]=f[_]:p[S]=f}),Object.freeze(p),p},d=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e)),y={get(l,a,u){return a===at?n:a===b?i:a===_?h(l,u):a===Lt?y:Reflect.get(l,a,u)},deleteProperty(l,a){let u=Reflect.get(l,a),p=u?.[b];p&&p.delete(c(a));let S=Reflect.deleteProperty(l,a);return S&&s(["delete",[a],u]),S},is:Object.is,canProxy:It,set(l,a,u,p){var S;let f=Reflect.get(l,a,p);if(this.is(f,u))return!0;let W=f?.[b];W&&W.delete(c(a)),G(u)&&(u=nt(u)||u);let x;return(S=Object.getOwnPropertyDescriptor(l,a))!=null&&S.set?x=u:u instanceof Promise?x=u.then(M=>(x[k]=M,s(["resolve",[a],M]),M)).catch(M=>{x[it]=M,s(["reject",[a],M])}):u?.[b]?(x=u,x[b].add(o(a))):this.canProxy(u)?(x=j(u),x[b].add(o(a))):x=u,Reflect.set(l,a,x,p),s(["set",[a],u,f]),!0}},T=new Proxy(d,y);return st.set(e,T),Reflect.ownKeys(e).forEach(l=>{let a=Object.getOwnPropertyDescriptor(e,l);a.get||a.set?Object.defineProperty(d,l,a):T[l]=e[l]}),T}function q(e){return G(e)?e[at]:void 0}function P(e,t,n){(V.env&&V.env.MODE)!=="production"&&!e?.[b]&&console.warn("Please use proxy object");let i,s=[],r=o=>{if(s.push(o),n){t(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,t(s.splice(0))}))};return e[b].add(r),()=>{e[b].delete(r)}}function N(e){return(V.env&&V.env.MODE)!=="production"&&!e?.[_]&&console.warn("Please use proxy object"),e[_]}function ct(e){for(;e.length>0;)e.pop();return e}var Z=(e,...t)=>{let n=typeof e=="function"?e(...t):e;return n??void 0},m=e=>e,Q=()=>{};var ut=(...e)=>(...t)=>{e.forEach(function(n){n?.(...t)})},ht=(()=>{let e=0;return()=>(e++,e.toString(36))})();var C=e=>Array.isArray(e);var O=e=>!(e==null||typeof e!="object"||C(e)),lt=e=>typeof e=="number"&&!Number.isNaN(e),v=e=>typeof e=="string",A=e=>typeof e=="function";function H(...e){let t=e.length===1?e[0]:e[1],n=e.length===2?e[0]:!0}function K(...e){let t=e.length===1?e[0]:e[1],n=e.length===2?e[0]:!0}function dt(e){return{predicate:t=>(n,i)=>{var s;return(s=e.find(r=>{var o;return r.guard=r.guard||(()=>!0),v(r.guard)?!!((o=t[r.guard])!=null&&o.call(t,n,i)):ft(r.guard)?r.guard.predicate(t!=null?t:{})(n,i):r.guard(n,i)}))==null?void 0:s.actions}}}function ft(e){return O(e)&&e.predicate!=null}function U(e,t){return(n,i)=>ft(e)?e.predicate(t!=null?t:{})(n,i):e}function kt(...e){return{predicate:t=>(n,i)=>e.map(s=>{var r;return v(s)?!!((r=t[s])!=null&&r.call(t,n,i)):A(s)?s(n,i):s.predicate(t)(n,i)}).some(Boolean)}}function Nt(...e){return{predicate:t=>(n,i)=>e.map(s=>{var r;return v(s)?!!((r=t[s])!=null&&r.call(t,n,i)):A(s)?s(n,i):s.predicate(t)(n,i)}).every(Boolean)}}function Rt(e){return{predicate:t=>(n,i)=>{var s;return v(e)?!((s=t[e])!=null&&s.call(t,n,i)):A(e)?!e(n,i):!e.predicate(t)(n,i)}}}var pt={or:kt,and:Nt,not:Rt};function Ft(e){return O(e)&&e.predicate!=null}var Wt=()=>!0;function z(e,t){return e=e!=null?e:Wt,(n,i)=>{if(v(e)){let s=t==null?void 0:t[e];return A(s)?s(n,i):s}return Ft(e)?e.predicate(t!=null?t:{})(n,i):e==null?void 0:e(n,i)}}function I(e){var t,n,i;if(Array.isArray(e)){for(n=Array(t=e.length);t--;)n[t]=(i=e[t])&&typeof i=="object"?I(i):i;return n}if(Object.prototype.toString.call(e)==="[object Object]"){n={};for(t in e)t==="__proto__"?Object.defineProperty(n,t,{value:I(e[t]),configurable:!0,enumerable:!0,writable:!0}):n[t]=(i=e[t])&&typeof i=="object"?I(i):i;return n}return e}function tt(e,t,n,i){return P(e,s=>{s.some(r=>r[1][0]===t)&&n(e[t])},i)}var se=Symbol();var D=new WeakMap,R=new WeakMap,vt=(e,t)=>{let n=D.get(e);n&&(n[0].forEach(i=>{let{d:s}=i;e!==s&&vt(s)}),++n[2],t&&n[3].add(t))},_t=(e,t)=>{let n=D.get(e);return n?.[2]?(n[3].add(t),!0):!1},Y=e=>{let t=D.get(e);t&&(--t[2],t[2]||(t[3].forEach(n=>n()),t[3].clear()),t[0].forEach(n=>{let{d:i}=n;e!==i&&Y(i)}))},Gt=e=>{let{s:t,d:n}=e,i=R.get(n);i||(i=[new Set],R.set(e.d,i)),i[0].add(e);let s=D.get(t);if(!s){let r=new Set,o=P(t,c=>{r.forEach(h=>{let{d,c:y,n:T,i:l}=h;t===d&&c.every(a=>a[1].length===1&&l.includes(a[1][0]))||h.p||(vt(t,y),T?Y(t):h.p=Promise.resolve().then(()=>{delete h.p,Y(t)}))})},!0);s=[r,o,0,new Set],D.set(t,s)}s[0].add(e)},St=e=>{let{s:t,d:n}=e,i=R.get(n);i?.[0].delete(e),i?.[0].size===0&&R.delete(n);let s=D.get(t);if(s){let[r,o]=s;r.delete(e),r.size||(o(),D.delete(t))}},Vt=e=>{let t=R.get(e);return t?Array.from(t[0]):[]};function Tt(e,t){let n=t?.proxy||j({}),i=!!t?.sync,s=Object.keys(e);return s.forEach(r=>{if(Object.getOwnPropertyDescriptor(n,r))throw new Error("object property already defined");let o=e[r],c=null,h=()=>{if(c&&(Array.from(c).map(([a])=>_t(a,h)).some(a=>a)||Array.from(c).every(([a,u])=>q(a)===u.v)))return;let d=new Map,T=o(a=>(d.set(a,{v:q(a)}),a)),l=()=>{d.forEach((a,u)=>{var p;let S=(p=c?.get(u))==null?void 0:p.s;if(S)a.s=S;else{let f={s:u,d:n,k:r,c:h,n:i,i:s};Gt(f),a.s=f}}),c?.forEach((a,u)=>{!d.has(u)&&a.s&&St(a.s)}),c=d};T instanceof Promise?T.finally(l):l(),n[r]=T};h()}),n}function yt(e,t){let n=t?.delete?new Set:null;Vt(e).forEach(i=>{let{k:s}=i;(!t?.keys||t.keys.includes(s))&&(St(i),n&&n.add(s))}),n&&n.forEach(i=>{delete e[i]})}function Et(e){var n;let t=j({value:"",previousValue:"",event:m({}),context:(n=e.context)!=null?n:m({}),done:!1,tags:[],hasTag(i){return this.tags.includes(i)},matches(...i){return i.includes(this.value)},can(i){return m(this).nextEvents.includes(i)},get nextEvents(){var r,o,c,h;let i=(c=(o=(r=e.states)==null?void 0:r[this.value])==null?void 0:o.on)!=null?c:{},s=(h=e==null?void 0:e.on)!=null?h:{};return Object.keys({...i,...s})},get changed(){return this.event.value==="machine.init"||!this.previousValue?!1:this.value!==this.previousValue}});return m(t)}function F(e,t){return(n,i)=>{if(lt(e))return e;if(A(e))return e(n,i);if(v(e)){let s=Number.parseFloat(e);if(!Number.isNaN(s))return s;if(t){let r=t==null?void 0:t[e];if(r==null){let o=`[machine] Cannot determine delay for ${e}. It doesn't exist in options.delays`;throw new Error(o)}return A(r)?r(n,i):r}}}}function E(e){return v(e)?{type:e}:e}function g(e){return e?C(e)?e:[e]:[]}function mt(e){return v(e)?{target:e}:e}function xt(e,t){return(n,i)=>g(e).map(mt).find(s=>{var c;let o=z(s.guard,t)(n,i);return(c=o!=null?o:s.target)!=null?c:s.actions})}function bt(e,t){let n=v(e)?mt(e):e,i=s=>(s.actions&&!s.target&&t&&(s.target=t),s);if(C(n))return n.map(i);if(O(n))return i(m(n))}var w=class{constructor(t,n){this.config=t;this.status="Not Started";this.type="machine";this.activityEvents=new Map;this.delayedEvents=new Map;this.stateListeners=new Set;this.eventListeners=new Set;this.doneListeners=new Set;this.contextWatchers=new Set;this.removeStateListener=Q;this.removeEventListener=Q;this.children=new Map;this.start=t=>{if(this.status==="Running")return this;this.status="Running";let n=E("machine.init");if(t){let r=O(t)?t:{context:this.config.context,value:t};this.setState(r.value),this.setContext(r.context)}let i={target:t?void 0:this.config.initial},s=this.getNextStateInfo(i,n);return s.target=m(s.target||i.target),this.initialState=s,this.performStateChangeEffects(s.target,s,n),this.removeStateListener=P(this.state,()=>{this.stateListeners.forEach(r=>{r(this.stateSnapshot)})},this.sync),this.removeEventListener=tt(this.state,"event",r=>{this.config.onEvent&&this.executeActions(this.config.onEvent,r);for(let o of this.eventListeners)o(r)}),this.setupContextWatchers(),this.executeActivities(E("machine.start"),g(this.config.activities),"machine.start"),this.executeActions(this.config.entry,E("machine.start")),this};this.setupContextWatchers=()=>{var t;for(let[n,i]of Object.entries((t=this.config.watch)!=null?t:{}))this.contextWatchers.add(tt(this.state.context,n,()=>{this.executeActions(i,this.state.event)}))};this.setupComputed=()=>{var i;let t=m((i=this.config.computed)!=null?i:{}),n=Object.fromEntries(Object.entries(t).map(([s,r])=>[s,o=>r(o(this.state.context))]));Tt(n,{proxy:this.state.context})};this.detachComputed=()=>{yt(this.state.context,{delete:!0})};this.stop=()=>{if(this.status!=="Stopped")return this.setState(null),this.setEvent("machine.stop"),this.config.context&&this.setContext(this.config.context),this.stopStateListeners(),this.stopChildren(),this.stopActivities(),this.stopDelayedEvents(),this.stopContextWatchers(),this.stopEventListeners(),this.detachComputed(),this.status="Stopped",this.executeActions(this.config.exit,E("machine.stop")),this};this.stopEventListeners=()=>{this.eventListeners.clear(),this.removeEventListener()};this.stopStateListeners=()=>{this.removeStateListener(),this.stateListeners.clear()};this.stopContextWatchers=()=>{this.contextWatchers.forEach(t=>t()),this.contextWatchers.clear()};this.stopDelayedEvents=()=>{this.delayedEvents.forEach(t=>{t.forEach(n=>n())}),this.delayedEvents.clear()};this.stopActivities=t=>{var n,i;t?((n=this.activityEvents.get(t))==null||n.forEach(s=>s()),(i=this.activityEvents.get(t))==null||i.clear(),this.activityEvents.delete(t)):(this.activityEvents.forEach(s=>{s.forEach(r=>r()),s.clear()}),this.activityEvents.clear())};this.sendChild=(t,n)=>{let i=E(t),s=Z(n,this.contextSnapshot),r=this.children.get(s);r||K(`[machine/send-child] Cannot send '${i.type}' event to unknown child`),r.send(i)};this.stopChild=t=>{this.children.has(t)||K("[machine/stop-child] Cannot stop unknown child"),this.children.get(t).stop(),this.children.delete(t)};this.removeChild=t=>{this.children.delete(t)};this.stopChildren=()=>{this.children.forEach(t=>t.stop()),this.children.clear()};this.setParent=t=>{this.parent=t};this.spawn=(t,n)=>{let i=Z(t);return n&&(i.id=n),i.type="machine.actor",i.setParent(this),this.children.set(i.id,m(i)),i.onDone(()=>{this.removeChild(i.id)}).start(),m(L(i))};this.addActivityCleanup=(t,n)=>{var i;!t||(this.activityEvents.has(t)?(i=this.activityEvents.get(t))==null||i.add(n):this.activityEvents.set(t,new Set([n])))};this.setState=t=>{this.state.previousValue=this.state.value,this.state.value=t;let n=this.getStateNode(t);t==null?ct(this.state.tags):this.state.tags=g(n==null?void 0:n.tags)};this.setContext=t=>{for(let n in t)this.state.context[n]=t[n]};this.withContext=t=>{this.detachComputed();let n={...this.config.context,...t};return new w({...this.config,context:n},this.options)};this.withOptions=t=>(this.detachComputed(),new w(this.config,{...this.options,...t}));this.setActions=t=>{this.actionMap={...this.actionMap,...t}};this.clone=()=>(this.detachComputed(),new w(this.config,this.options));this.getStateNode=t=>{var n;if(!!t)return(n=this.config.states)==null?void 0:n[t]};this.getNextStateInfo=(t,n)=>{var o;let i=this.determineTransition(t,n),s=(o=i==null?void 0:i.target)!=null?o:this.state.value,r=this.getStateNode(s);return{transition:i,stateNode:r,target:s}};this.getActionFromDelayedTransition=t=>{let n=E("machine.after"),s=F(t.delay,this.delayMap)(this.contextSnapshot,n),r;return{entry:()=>{r=globalThis.setTimeout(()=>{let o=this.state.value,c=this.getNextStateInfo(t,n);this.performStateChangeEffects(o,c,n)},s)},exit:()=>{globalThis.clearTimeout(r)}}};this.getDelayedEventActions=t=>{let n=this.getStateNode(t),i=E("machine.after");if(!n||!n.after)return;let s=[],r=[];if(C(n.after)){let o=this.determineTransition(n.after,i);if(!o)return;let c=this.getActionFromDelayedTransition(o);s.push(c.entry),r.push(c.exit)}else if(O(n.after))for(let o in n.after){let c=n.after[o],h={};if(C(c)){let y=this.determineTransition(c,i);y&&(h=y)}else v(c)?h={target:c,delay:o}:h={...c,delay:o};let d=this.getActionFromDelayedTransition(h);s.push(d.entry),r.push(d.exit)}return{entries:s,exits:r}};this.executeActions=(t,n)=>{var s;let i=U(t,this.guardMap)(this.contextSnapshot,n);for(let r of g(i)){let o=v(r)?(s=this.actionMap)==null?void 0:s[r]:r;H(v(r)&&!o,`[machine/exec-action] No implementation found for action: \`${r}\``),o==null||o(this.state.context,n,this.meta)}};this.executeActivities=(t,n,i)=>{var s;for(let r of n){let o=v(r)?(s=this.activityMap)==null?void 0:s[r]:r;if(!o){H(`[machine/exec-activity] No implementation found for activity: \`${r}\``);continue}let c=o(this.state.context,t,this.meta);c&&this.addActivityCleanup(i!=null?i:this.state.value,c)}};this.createEveryActivities=(t,n)=>{if(!t)return;let i=E("machine.every");if(C(t)){let s=g(t).find(h=>{let d=F(h.delay,this.delayMap);h.delay=d(this.contextSnapshot,i);let T=z(h.guard,this.guardMap)(this.contextSnapshot,i);return T!=null?T:h.delay});if(!s)return;let o=F(s.delay,this.delayMap)(this.contextSnapshot,i);n(()=>{let h=globalThis.setInterval(()=>{this.executeActions(s.actions,i)},o);return()=>{globalThis.clearInterval(h)}})}else for(let s in t){let r=t==null?void 0:t[s],c=F(s,this.delayMap)(this.contextSnapshot,i);n(()=>{let d=globalThis.setInterval(()=>{this.executeActions(r,i)},c);return()=>{globalThis.clearInterval(d)}})}};this.setEvent=t=>{this.state.event=L(E(t))};this.performExitEffects=(t,n)=>{let i=this.state.value,s=t?this.getStateNode(t):void 0;this.stopActivities(i);let r=U(s==null?void 0:s.exit,this.guardMap)(this.contextSnapshot,n),o=g(r),c=this.delayedEvents.get(i);c&&o.push(...c),this.executeActions(o,n),this.eventListeners.clear()};this.performEntryEffects=(t,n)=>{let i=this.getStateNode(t),s=g(i==null?void 0:i.activities);this.createEveryActivities(i==null?void 0:i.every,h=>{s.unshift(h)}),s.length>0&&this.executeActivities(n,s);let r=U(i==null?void 0:i.entry,this.guardMap)(this.contextSnapshot,n),o=g(r),c=this.getDelayedEventActions(t);(i==null?void 0:i.after)&&c&&(this.delayedEvents.set(t,c==null?void 0:c.exits),o.push(...c.entries)),this.executeActions(o,n),(i==null?void 0:i.type)==="final"&&(this.state.done=!0,this.doneListeners.forEach(h=>{h(this.stateSnapshot)}),this.stop())};this.performTransitionEffects=(t,n)=>{let i=this.determineTransition(t,n);this.executeActions(i==null?void 0:i.actions,n)};this.performStateChangeEffects=(t,n,i)=>{var r,o;this.setEvent(i),n.target=(o=(r=n.target)!=null?r:this.state.value)!=null?o:void 0;let s=n.target&&n.target!==this.state.value;s&&this.performExitEffects(t,i),this.performTransitionEffects(n==null?void 0:n.transition,i),this.setState(n.target),s&&this.performEntryEffects(n.target,i)};this.determineTransition=(t,n)=>{let i=xt(t,this.guardMap);return i==null?void 0:i(this.contextSnapshot,n)};this.sendParent=t=>{var i;this.parent||K("[machine/send-parent] Cannot send event to an unknown parent");let n=E(t);(i=this.parent)==null||i.send(n)};this.send=t=>{let n=E(t);this.transition(this.state.value,n)};this.transition=(t,n)=>{var h,d,y;let i=v(t)?this.getStateNode(t):t==null?void 0:t.stateNode,s=E(n);if(!i&&!this.config.on){let T=this.status==="Stopped"?"[machine/transition] Cannot transition a stopped machine":"[machine/transition] State does not have a definition";H(T);return}let r=(y=(h=i==null?void 0:i.on)==null?void 0:h[s.type])!=null?y:(d=this.config.on)==null?void 0:d[s.type],o=bt(r,this.state.value);if(!o)return;let c=this.getNextStateInfo(o,s);return this.performStateChangeEffects(this.state.value,c,s),c.stateNode};this.subscribe=t=>(this.stateListeners.add(t),this.status==="Running"&&t(this.stateSnapshot),()=>{this.stateListeners.delete(t)});this.onDone=t=>(this.doneListeners.add(t),this);this.onTransition=t=>(this.stateListeners.add(t),this.status==="Running"&&t(this.stateSnapshot),this);this.onEvent=t=>(t(this.state.event),this.eventListeners.add(t),this);var s,r,o,c,h,d,y,T,l,a,u;this.options=I(n),this.id=(s=t.id)!=null?s:`machine-${ht()}`,this.guardMap=(o=(r=this.options)==null?void 0:r.guards)!=null?o:{},this.actionMap=(h=(c=this.options)==null?void 0:c.actions)!=null?h:{},this.delayMap=(y=(d=this.options)==null?void 0:d.delays)!=null?y:{},this.activityMap=(l=(T=this.options)==null?void 0:T.activities)!=null?l:{},this.sync=(u=(a=this.options)==null?void 0:a.sync)!=null?u:!1,this.state=Et(I(t)),this.setupComputed();let i=E("machine.created");this.executeActions(t==null?void 0:t.created,i)}get stateSnapshot(){return m(N(this.state))}get contextSnapshot(){return this.stateSnapshot.context}get self(){let t=this;return{id:this.id,send:this.send.bind(this),sendParent:this.sendParent.bind(this),sendChild:this.sendChild.bind(this),stop:this.stop.bind(this),stopChild:this.stopChild.bind(this),spawn:this.spawn.bind(this),get state(){return t.stateSnapshot}}}get meta(){return{state:this.stateSnapshot,guards:this.guardMap,send:this.send.bind(this),listen:this.onEvent.bind(this),self:this.self,getState:()=>this.stateSnapshot}}},Ht=(e,t)=>new w(e,t);var Kt=(...e)=>e.map(t=>t==null?void 0:t.trim()).filter(Boolean).join(" ");function gt(...e){var n,i;let t={};for(let s of e){for(let r in t){if(/^on[A-Z]/.test(r)&&typeof t[r]=="function"&&typeof s[r]=="function"){t[r]=ut(t[r],s[r]);continue}if(r==="className"||r==="class"){t[r]=Kt(t[r],s[r]);continue}if(r==="style"){t[r]=Object.assign({},(n=t[r])!=null?n:{},(i=s[r])!=null?i:{});continue}t[r]=s[r]!==void 0?s[r]:t[r]}for(let r in s)t[r]===void 0&&(t[r]=s[r])}return t}
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
Machine: () => Machine,
choose: () => choose,
createMachine: () => createMachine,
guards: () => guards,
mergeProps: () => mergeProps,
proxy: () => import_vanilla3.proxy,
ref: () => import_vanilla3.ref,
snapshot: () => import_vanilla3.snapshot,
subscribe: () => import_vanilla3.subscribe
});
module.exports = __toCommonJS(src_exports);
var import_vanilla3 = require("valtio/vanilla");
// ../utilities/core/src/array.ts
function clear(v) {
while (v.length > 0)
v.pop();
return v;
}
// ../utilities/core/src/functions.ts
var runIfFn = (v, ...a) => {
const res = typeof v === "function" ? v(...a) : v;
return res != null ? res : void 0;
};
var cast = (v) => v;
var noop = () => {
};
var callAll = (...fns) => (...a) => {
fns.forEach(function(fn) {
fn == null ? void 0 : fn(...a);
});
};
var uuid = /* @__PURE__ */ (() => {
let id = 0;
return () => {
id++;
return id.toString(36);
};
})();
// ../utilities/core/src/guard.ts
var isArray = (v) => Array.isArray(v);
var isObject = (v) => !(v == null || typeof v !== "object" || isArray(v));
var isNumber = (v) => typeof v === "number" && !Number.isNaN(v);
var isString = (v) => typeof v === "string";
var isFunction = (v) => typeof v === "function";
// ../utilities/core/src/warning.ts
function warn(...a) {
const m = a.length === 1 ? a[0] : a[1];
const c = a.length === 2 ? a[0] : true;
if (c && void 0 !== "production") {
console.warn(m);
}
}
function invariant(...a) {
const m = a.length === 1 ? a[0] : a[1];
const c = a.length === 2 ? a[0] : true;
if (c && void 0 !== "production") {
throw new Error(m);
}
}
// src/action-utils.ts
function choose(actions) {
return {
predicate: (guardMap) => (ctx, event) => {
var _a;
return (_a = actions.find((def) => {
var _a2;
def.guard = def.guard || (() => true);
if (isString(def.guard)) {
return !!((_a2 = guardMap[def.guard]) == null ? void 0 : _a2.call(guardMap, ctx, event));
}
if (isGuardHelper(def.guard)) {
return def.guard.predicate(guardMap != null ? guardMap : {})(ctx, event);
}
return def.guard(ctx, event);
})) == null ? void 0 : _a.actions;
}
};
}
function isGuardHelper(value) {
return isObject(value) && value.predicate != null;
}
function determineActionsFn(values, guardMap) {
return (context, event) => {
if (isGuardHelper(values))
return values.predicate(guardMap != null ? guardMap : {})(context, event);
return values;
};
}
// src/guard-utils.ts
function or(...conditions) {
return {
predicate: (guards2) => (ctx, event) => conditions.map((condition) => {
var _a;
if (isString(condition)) {
return !!((_a = guards2[condition]) == null ? void 0 : _a.call(guards2, ctx, event));
}
if (isFunction(condition)) {
return condition(ctx, event);
}
return condition.predicate(guards2)(ctx, event);
}).some(Boolean)
};
}
function and(...conditions) {
return {
predicate: (guards2) => (ctx, event) => conditions.map((condition) => {
var _a;
if (isString(condition)) {
return !!((_a = guards2[condition]) == null ? void 0 : _a.call(guards2, ctx, event));
}
if (isFunction(condition)) {
return condition(ctx, event);
}
return condition.predicate(guards2)(ctx, event);
}).every(Boolean)
};
}
function not(condition) {
return {
predicate: (guardMap) => (ctx, event) => {
var _a;
if (isString(condition)) {
return !((_a = guardMap[condition]) == null ? void 0 : _a.call(guardMap, ctx, event));
}
if (isFunction(condition)) {
return !condition(ctx, event);
}
return !condition.predicate(guardMap)(ctx, event);
}
};
}
var guards = { or, and, not };
function isGuardHelper2(value) {
return isObject(value) && value.predicate != null;
}
var TruthyGuard = () => true;
function determineGuardFn(guard, guardMap) {
guard = guard != null ? guard : TruthyGuard;
return (context, event) => {
if (isString(guard)) {
const value = guardMap == null ? void 0 : guardMap[guard];
return isFunction(value) ? value(context, event) : value;
}
if (isGuardHelper2(guard)) {
return guard.predicate(guardMap != null ? guardMap : {})(context, event);
}
return guard == null ? void 0 : guard(context, event);
};
}
// ../../node_modules/klona/json/index.mjs
function klona(val) {
var k, out, tmp;
if (Array.isArray(val)) {
out = Array(k = val.length);
while (k--)
out[k] = (tmp = val[k]) && typeof tmp === "object" ? klona(tmp) : tmp;
return out;
}
if (Object.prototype.toString.call(val) === "[object Object]") {
out = {};
for (k in val) {
if (k === "__proto__") {
Object.defineProperty(out, k, {
value: klona(val[k]),
configurable: true,
enumerable: true,
writable: true
});
} else {
out[k] = (tmp = val[k]) && typeof tmp === "object" ? klona(tmp) : tmp;
}
}
return out;
}
return val;
}
// src/machine.ts
var import_utils9 = require("valtio/utils");
var import_vanilla2 = require("valtio/vanilla");
// src/create-proxy.ts
var import_vanilla = require("valtio/vanilla");
function createProxy(config) {
var _a;
const state = (0, import_vanilla.proxy)({
value: "",
previousValue: "",
event: cast({}),
context: (_a = config.context) != null ? _a : cast({}),
done: false,
tags: [],
hasTag(tag) {
return this.tags.includes(tag);
},
matches(...value) {
return value.includes(this.value);
},
can(event) {
return cast(this).nextEvents.includes(event);
},
get nextEvents() {
var _a2, _b, _c, _d;
const stateEvents = (_c = (_b = (_a2 = config.states) == null ? void 0 : _a2[this.value]) == null ? void 0 : _b["on"]) != null ? _c : {};
const globalEvents = (_d = config == null ? void 0 : config.on) != null ? _d : {};
return Object.keys(__spreadValues(__spreadValues({}, stateEvents), globalEvents));
},
get changed() {
if (this.event.value === "machine.init" /* Init */ || !this.previousValue)
return false;
return this.value !== this.previousValue;
}
});
return cast(state);
}
// src/delay-utils.ts
function determineDelayFn(delay, delaysMap) {
return (context, event) => {
if (isNumber(delay))
return delay;
if (isFunction(delay)) {
return delay(context, event);
}
if (isString(delay)) {
const value = Number.parseFloat(delay);
if (!Number.isNaN(value)) {
return value;
}
if (delaysMap) {
const valueOrFn = delaysMap == null ? void 0 : delaysMap[delay];
if (valueOrFn == null) {
const msg = `[machine] Cannot determine delay for ${delay}. It doesn't exist in options.delays`;
throw new Error(msg);
}
return isFunction(valueOrFn) ? valueOrFn(context, event) : valueOrFn;
}
}
};
}
// src/utils.ts
function toEvent(event) {
const obj = isString(event) ? { type: event } : event;
return obj;
}
function toArray(value) {
if (!value)
return [];
return isArray(value) ? value : [value];
}
// src/transition-utils.ts
function toTarget(target) {
return isString(target) ? { target } : target;
}
function determineTransitionFn(transitions, guardMap) {
return (context, event) => {
return toArray(transitions).map(toTarget).find((transition) => {
var _a;
const determineGuard = determineGuardFn(transition.guard, guardMap);
const guard = determineGuard(context, event);
return (_a = guard != null ? guard : transition.target) != null ? _a : transition.actions;
});
};
}
function toTransition(transition, current) {
const _transition = isString(transition) ? toTarget(transition) : transition;
const fn = (t) => {
const isTargetless = t.actions && !t.target;
if (isTargetless && current)
t.target = current;
return t;
};
if (isArray(_transition)) {
return _transition.map(fn);
}
if (isObject(_transition)) {
return fn(cast(_transition));
}
}
// src/machine.ts
var Machine = class {
constructor(config, options) {
this.config = config;
this.status = "Not Started" /* NotStarted */;
this.type = "machine" /* Machine */;
this.activityEvents = /* @__PURE__ */ new Map();
this.delayedEvents = /* @__PURE__ */ new Map();
this.stateListeners = /* @__PURE__ */ new Set();
this.eventListeners = /* @__PURE__ */ new Set();
this.doneListeners = /* @__PURE__ */ new Set();
this.contextWatchers = /* @__PURE__ */ new Set();
this.removeStateListener = noop;
this.removeEventListener = noop;
this.children = /* @__PURE__ */ new Map();
this.start = (init) => {
if (this.status === "Running" /* Running */) {
return this;
}
this.status = "Running" /* Running */;
const event = toEvent("machine.init" /* Init */);
if (init) {
const resolved = isObject(init) ? init : { context: this.config.context, value: init };
this.setState(resolved.value);
this.setContext(resolved.context);
}
const transition = {
target: !!init ? void 0 : this.config.initial
};
const info = this.getNextStateInfo(transition, event);
info.target = cast(info.target || transition.target);
this.initialState = info;
this.performStateChangeEffects(info.target, info, event);
this.removeStateListener = (0, import_vanilla2.subscribe)(this.state, () => {
this.stateListeners.forEach((listener) => {
listener(this.stateSnapshot);
});
}, this.sync);
this.removeEventListener = (0, import_utils9.subscribeKey)(this.state, "event", (value) => {
if (this.config.onEvent) {
this.executeActions(this.config.onEvent, value);
}
for (const listener of this.eventListeners) {
listener(value);
}
});
this.setupContextWatchers();
this.executeActivities(toEvent("machine.start" /* Start */), toArray(this.config.activities), "machine.start" /* Start */);
this.executeActions(this.config.entry, toEvent("machine.start" /* Start */));
return this;
};
this.setupContextWatchers = () => {
var _a;
for (const [key, fn] of Object.entries((_a = this.config.watch) != null ? _a : {})) {
this.contextWatchers.add((0, import_utils9.subscribeKey)(this.state.context, key, () => {
this.executeActions(fn, this.state.event);
}));
}
};
this.setupComputed = () => {
var _a;
const computed = cast((_a = this.config.computed) != null ? _a : {});
const deriveFns = Object.fromEntries(Object.entries(computed).map(([key, fn]) => [key, (get) => fn(get(this.state.context))]));
(0, import_utils9.derive)(deriveFns, { proxy: this.state.context });
};
this.detachComputed = () => {
(0, import_utils9.underive)(this.state.context, { delete: true });
};
this.stop = () => {
if (this.status === "Stopped" /* Stopped */)
return;
this.setState(null);
this.setEvent("machine.stop" /* Stop */);
if (this.config.context) {
this.setContext(this.config.context);
}
this.stopStateListeners();
this.stopChildren();
this.stopActivities();
this.stopDelayedEvents();
this.stopContextWatchers();
this.stopEventListeners();
this.detachComputed();
this.status = "Stopped" /* Stopped */;
this.executeActions(this.config.exit, toEvent("machine.stop" /* Stop */));
return this;
};
this.stopEventListeners = () => {
this.eventListeners.clear();
this.removeEventListener();
};
this.stopStateListeners = () => {
this.removeStateListener();
this.stateListeners.clear();
};
this.stopContextWatchers = () => {
this.contextWatchers.forEach((fn) => fn());
this.contextWatchers.clear();
};
this.stopDelayedEvents = () => {
this.delayedEvents.forEach((state) => {
state.forEach((stop) => stop());
});
this.delayedEvents.clear();
};
this.stopActivities = (state) => {
var _a, _b;
if (state) {
(_a = this.activityEvents.get(state)) == null ? void 0 : _a.forEach((stop) => stop());
(_b = this.activityEvents.get(state)) == null ? void 0 : _b.clear();
this.activityEvents.delete(state);
} else {
this.activityEvents.forEach((state2) => {
state2.forEach((stop) => stop());
state2.clear();
});
this.activityEvents.clear();
}
};
this.sendChild = (evt, to) => {
const event = toEvent(evt);
const id = runIfFn(to, this.contextSnapshot);
const child = this.children.get(id);
if (!child) {
invariant(`[machine/send-child] Cannot send '${event.type}' event to unknown child`);
}
child.send(event);
};
this.stopChild = (id) => {
if (!this.children.has(id)) {
invariant("[machine/stop-child] Cannot stop unknown child");
}
this.children.get(id).stop();
this.children.delete(id);
};
this.removeChild = (id) => {
this.children.delete(id);
};
this.stopChildren = () => {
this.children.forEach((child) => child.stop());
this.children.clear();
};
this.setParent = (parent) => {
this.parent = parent;
};
this.spawn = (src, id) => {
const actor = runIfFn(src);
if (id)
actor.id = id;
actor.type = "machine.actor" /* Actor */;
actor.setParent(this);
this.children.set(actor.id, cast(actor));
actor.onDone(() => {
this.removeChild(actor.id);
}).start();
return cast((0, import_vanilla2.ref)(actor));
};
this.addActivityCleanup = (state, cleanup) => {
var _a;
if (!state)
return;
if (!this.activityEvents.has(state)) {
this.activityEvents.set(state, /* @__PURE__ */ new Set([cleanup]));
} else {
(_a = this.activityEvents.get(state)) == null ? void 0 : _a.add(cleanup);
}
};
this.setState = (target) => {
this.state.previousValue = this.state.value;
this.state.value = target;
const stateNode = this.getStateNode(target);
if (target == null) {
clear(this.state.tags);
} else {
this.state.tags = toArray(stateNode == null ? void 0 : stateNode.tags);
}
};
this.setContext = (context) => {
for (const key in context) {
this.state.context[key] = context[key];
}
};
this.withContext = (context) => {
this.detachComputed();
const newContext = __spreadValues(__spreadValues({}, this.config.context), context);
return new Machine(__spreadProps(__spreadValues({}, this.config), { context: newContext }), this.options);
};
this.withOptions = (options) => {
this.detachComputed();
return new Machine(this.config, __spreadValues(__spreadValues({}, this.options), options));
};
this.setActions = (actions) => {
this.actionMap = __spreadValues(__spreadValues({}, this.actionMap), actions);
};
this.clone = () => {
this.detachComputed();
return new Machine(this.config, this.options);
};
this.getStateNode = (state) => {
var _a;
if (!state)
return;
return (_a = this.config.states) == null ? void 0 : _a[state];
};
this.getNextStateInfo = (transitions, event) => {
var _a;
const transition = this.determineTransition(transitions, event);
const target = (_a = transition == null ? void 0 : transition.target) != null ? _a : this.state.value;
const stateNode = this.getStateNode(target);
return {
transition,
stateNode,
target
};
};
this.getActionFromDelayedTransition = (transition) => {
const event = toEvent("machine.after" /* After */);
const determineDelay = determineDelayFn(transition.delay, this.delayMap);
const delay = determineDelay(this.contextSnapshot, event);
let id;
return {
entry: () => {
id = globalThis.setTimeout(() => {
const current = this.state.value;
const next = this.getNextStateInfo(transition, event);
this.performStateChangeEffects(current, next, event);
}, delay);
},
exit: () => {
globalThis.clearTimeout(id);
}
};
};
this.getDelayedEventActions = (state) => {
const stateNode = this.getStateNode(state);
const event = toEvent("machine.after" /* After */);
if (!stateNode || !stateNode.after)
return;
const entries = [];
const exits = [];
if (isArray(stateNode.after)) {
const transition = this.determineTransition(stateNode.after, event);
if (!transition)
return;
const actions = this.getActionFromDelayedTransition(transition);
entries.push(actions.entry);
exits.push(actions.exit);
} else if (isObject(stateNode.after)) {
for (const delay in stateNode.after) {
const transition = stateNode.after[delay];
let resolvedTransition = {};
if (isArray(transition)) {
const picked = this.determineTransition(transition, event);
if (picked)
resolvedTransition = picked;
} else if (isString(transition)) {
resolvedTransition = { target: transition, delay };
} else {
resolvedTransition = __spreadProps(__spreadValues({}, transition), { delay });
}
const actions = this.getActionFromDelayedTransition(resolvedTransition);
entries.push(actions.entry);
exits.push(actions.exit);
}
}
return { entries, exits };
};
this.executeActions = (actions, event) => {
var _a;
const _actions = determineActionsFn(actions, this.guardMap)(this.contextSnapshot, event);
for (const action of toArray(_actions)) {
const fn = isString(action) ? (_a = this.actionMap) == null ? void 0 : _a[action] : action;
warn(isString(action) && !fn, `[machine/exec-action] No implementation found for action: \`${action}\``);
fn == null ? void 0 : fn(this.state.context, event, this.meta);
}
};
this.executeActivities = (event, activities, state) => {
var _a;
for (const activity of activities) {
const fn = isString(activity) ? (_a = this.activityMap) == null ? void 0 : _a[activity] : activity;
if (!fn) {
warn(`[machine/exec-activity] No implementation found for activity: \`${activity}\``);
continue;
}
const cleanup = fn(this.state.context, event, this.meta);
if (cleanup) {
this.addActivityCleanup(state != null ? state : this.state.value, cleanup);
}
}
};
this.createEveryActivities = (every, callbackfn) => {
if (!every)
return;
const event = toEvent("machine.every" /* Every */);
if (isArray(every)) {
const picked = toArray(every).find((t) => {
const determineDelay2 = determineDelayFn(t.delay, this.delayMap);
t.delay = determineDelay2(this.contextSnapshot, event);
const determineGuard = determineGuardFn(t.guard, this.guardMap);
const guard = determineGuard(this.contextSnapshot, event);
return guard != null ? guard : t.delay;
});
if (!picked)
return;
const determineDelay = determineDelayFn(picked.delay, this.delayMap);
const delay = determineDelay(this.contextSnapshot, event);
const activity = () => {
const id = globalThis.setInterval(() => {
this.executeActions(picked.actions, event);
}, delay);
return () => {
globalThis.clearInterval(id);
};
};
callbackfn(activity);
} else {
for (const interval in every) {
const actions = every == null ? void 0 : every[interval];
const determineDelay = determineDelayFn(interval, this.delayMap);
const delay = determineDelay(this.contextSnapshot, event);
const activity = () => {
const id = globalThis.setInterval(() => {
this.executeActions(actions, event);
}, delay);
return () => {
globalThis.clearInterval(id);
};
};
callbackfn(activity);
}
}
};
this.setEvent = (event) => {
this.state.event = (0, import_vanilla2.ref)(toEvent(event));
};
this.performExitEffects = (current, event) => {
const currentState = this.state.value;
const stateNode = current ? this.getStateNode(current) : void 0;
this.stopActivities(currentState);
const _exit = determineActionsFn(stateNode == null ? void 0 : stateNode.exit, this.guardMap)(this.contextSnapshot, event);
const exitActions = toArray(_exit);
const afterExitActions = this.delayedEvents.get(currentState);
if (afterExitActions) {
exitActions.push(...afterExitActions);
}
this.executeActions(exitActions, event);
this.eventListeners.clear();
};
this.performEntryEffects = (next, event) => {
const stateNode = this.getStateNode(next);
const activities = toArray(stateNode == null ? void 0 : stateNode.activities);
this.createEveryActivities(stateNode == null ? void 0 : stateNode.every, (activity) => {
activities.unshift(activity);
});
if (activities.length > 0) {
this.executeActivities(event, activities);
}
const _entry = determineActionsFn(stateNode == null ? void 0 : stateNode.entry, this.guardMap)(this.contextSnapshot, event);
const entryActions = toArray(_entry);
const afterActions = this.getDelayedEventActions(next);
if ((stateNode == null ? void 0 : stateNode.after) && afterActions) {
this.delayedEvents.set(next, afterActions == null ? void 0 : afterActions.exits);
entryActions.push(...afterActions.entries);
}
this.executeActions(entryActions, event);
if ((stateNode == null ? void 0 : stateNode.type) === "final") {
this.state.done = true;
this.doneListeners.forEach((listener) => {
listener(this.stateSnapshot);
});
this.stop();
}
};
this.performTransitionEffects = (transition, event) => {
const t = this.determineTransition(transition, event);
this.executeActions(t == null ? void 0 : t.actions, event);
};
this.performStateChangeEffects = (current, next, event) => {
var _a, _b;
this.setEvent(event);
next.target = (_b = (_a = next.target) != null ? _a : this.state.value) != null ? _b : void 0;
const ok = next.target && next.target !== this.state.value;
if (ok) {
this.performExitEffects(current, event);
}
this.performTransitionEffects(next == null ? void 0 : next.transition, event);
this.setState(next.target);
if (ok) {
this.performEntryEffects(next.target, event);
}
};
this.determineTransition = (transition, event) => {
const fn = determineTransitionFn(transition, this.guardMap);
return fn == null ? void 0 : fn(this.contextSnapshot, event);
};
this.sendParent = (evt) => {
var _a;
if (!this.parent) {
invariant("[machine/send-parent] Cannot send event to an unknown parent");
}
const event = toEvent(evt);
(_a = this.parent) == null ? void 0 : _a.send(event);
};
this.send = (evt) => {
const event = toEvent(evt);
this.transition(this.state.value, event);
};
this.transition = (state, evt) => {
var _a, _b, _c;
const stateNode = isString(state) ? this.getStateNode(state) : state == null ? void 0 : state.stateNode;
const event = toEvent(evt);
if (!stateNode && !this.config.on) {
const msg = this.status === "Stopped" /* Stopped */ ? "[machine/transition] Cannot transition a stopped machine" : "[machine/transition] State does not have a definition";
warn(msg);
return;
}
const transitionConfig = (_c = (_a = stateNode == null ? void 0 : stateNode.on) == null ? void 0 : _a[event.type]) != null ? _c : (_b = this.config.on) == null ? void 0 : _b[event.type];
const transition = toTransition(transitionConfig, this.state.value);
if (!transition)
return;
const info = this.getNextStateInfo(transition, event);
this.performStateChangeEffects(this.state.value, info, event);
return info.stateNode;
};
this.subscribe = (listener) => {
this.stateListeners.add(listener);
if (this.status === "Running" /* Running */) {
listener(this.stateSnapshot);
}
return () => {
this.stateListeners.delete(listener);
};
};
this.onDone = (listener) => {
this.doneListeners.add(listener);
return this;
};
this.onTransition = (listener) => {
this.stateListeners.add(listener);
if (this.status === "Running" /* Running */) {
listener(this.stateSnapshot);
}
return this;
};
this.onEvent = (listener) => {
listener(this.state.event);
this.eventListeners.add(listener);
return this;
};
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
this.options = klona(options);
this.id = (_a = config.id) != null ? _a : `machine-${uuid()}`;
this.guardMap = (_c = (_b = this.options) == null ? void 0 : _b.guards) != null ? _c : {};
this.actionMap = (_e = (_d = this.options) == null ? void 0 : _d.actions) != null ? _e : {};
this.delayMap = (_g = (_f = this.options) == null ? void 0 : _f.delays) != null ? _g : {};
this.activityMap = (_i = (_h = this.options) == null ? void 0 : _h.activities) != null ? _i : {};
this.sync = (_k = (_j = this.options) == null ? void 0 : _j.sync) != null ? _k : false;
this.state = createProxy(klona(config));
this.setupComputed();
const event = toEvent("machine.created" /* Created */);
this.executeActions(config == null ? void 0 : config.created, event);
}
get stateSnapshot() {
return cast((0, import_vanilla2.snapshot)(this.state));
}
get contextSnapshot() {
return this.stateSnapshot.context;
}
get self() {
const _self = this;
return {
id: this.id,
send: this.send.bind(this),
sendParent: this.sendParent.bind(this),
sendChild: this.sendChild.bind(this),
stop: this.stop.bind(this),
stopChild: this.stopChild.bind(this),
spawn: this.spawn.bind(this),
get state() {
return _self.stateSnapshot;
}
};
}
get meta() {
return {
state: this.stateSnapshot,
guards: this.guardMap,
send: this.send.bind(this),
listen: this.onEvent.bind(this),
self: this.self,
getState: () => this.stateSnapshot
};
}
};
var createMachine = (config, options) => new Machine(config, options);
// src/merge-props.ts
var clsx = (...args) => args.map((str) => str == null ? void 0 : str.trim()).filter(Boolean).join(" ");
function mergeProps(...args) {
var _a, _b;
let result = {};
for (let props of args) {
for (let key in result) {
if (/^on[A-Z]/.test(key) && typeof result[key] === "function" && typeof props[key] === "function") {
result[key] = callAll(result[key], props[key]);
continue;
}
if (key === "className" || key === "class") {
result[key] = clsx(result[key], props[key]);
continue;
}
if (key === "style") {
result[key] = Object.assign({}, (_a = result[key]) != null ? _a : {}, (_b = props[key]) != null ? _b : {});
continue;
}
result[key] = props[key] !== void 0 ? props[key] : result[key];
}
for (let key in props) {
if (result[key] === void 0) {
result[key] = props[key];
}
}
}
return result;
}
//# sourceMappingURL=index.js.map

@@ -123,1 +123,2 @@ import { Dict, MachineStatus, MachineType, StateMachine as S, Writable } from "./types";

export declare const createMachine: <TContext extends Dict<any>, TState extends S.StateSchema = S.StateSchema, TEvent extends S.EventObject = S.AnyEventObject>(config: S.MachineConfig<TContext, TState, TEvent>, options?: S.MachineOptions<TContext, TState, TEvent>) => Machine<TContext, TState, TEvent>;
//# sourceMappingURL=machine.d.ts.map

@@ -8,1 +8,2 @@ interface Props {

export {};
//# sourceMappingURL=merge-props.d.ts.map

@@ -15,1 +15,2 @@ import type { StateMachine as S } from "./types";

export declare function toTransition<TContext, TState extends S.StateSchema, TEvent extends S.EventObject>(transition: S.Transitions<TContext, TState, TEvent> | undefined, current?: TState["value"] | null): S.TransitionDefinition<TContext, TState, TEvent> | S.TransitionDefinition<TContext, TState, TEvent>[];
//# sourceMappingURL=transition-utils.d.ts.map

@@ -258,1 +258,2 @@ export declare type Dict<T = any> = Record<string, T>;

export {};
//# sourceMappingURL=types.d.ts.map
import type { StateMachine as S } from "./types";
export declare function toEvent<T extends S.EventObject>(event: S.Event<T>): T;
export declare function toArray<T>(value: T | T[] | undefined): T[];
//# sourceMappingURL=utils.d.ts.map

26

package.json
{
"name": "@zag-js/core",
"version": "0.0.0-dev-20220413091534",
"version": "0.0.0-dev-20220413174154",
"description": "A minimal implementation of xstate fsm for UI machines",

@@ -14,3 +14,3 @@ "keywords": [

"author": "Segun Adebayo <sage@adebayosegun.com>",
"homepage": "https://github.com/chakra-ui/core#readme",
"homepage": "https://github.com/chakra-ui/zag#readme",
"license": "MIT",

@@ -20,10 +20,16 @@ "main": "dist/index.js",

"types": "dist/index.d.ts",
"repository": "https://github.com/chakra-ui/core/tree/main/packages/machine",
"repository": "https://github.com/chakra-ui/zag/tree/main/packages/machine",
"sideEffects": false,
"files": [
"src",
"dist",
"package.json",
"README.md"
"dist/**/*"
],
"scripts": {
"build:fast": "zag build",
"start": "zag build --watch",
"build": "zag build --prod",
"test": "jest --config ../../jest.config.js --rootDir . --passWithNoTests",
"lint": "eslint src --ext .ts,.tsx",
"test:ci": "yarn test --ci --runInBand",
"test:watch": "yarn test --watch --updateSnapshot"
},
"publishConfig": {

@@ -33,9 +39,9 @@ "access": "public"

"bugs": {
"url": "https://github.com/chakra-ui/core/issues"
"url": "https://github.com/chakra-ui/zag/issues"
},
"dependencies": {
"@zag-js/utils": "^0.0.0-dev-20220413091534",
"@zag-js/utils": "^0.0.0-dev-20220413174154",
"klona": "^2.0.5",
"valtio": "^1.5.2"
}
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc