@rxova/journey-core 0.6.3 → 0.7.0

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/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var I={RUNNING:"running",COMPLETE:"complete",TERMINATED:"terminated"},O="*",D={GO_TO_STEP_BY_ID:"goToStepById"},b={IDLE:"idle",EVALUATING_WHEN:"evaluating-when",RUNNING_EFFECT:"running-effect",ERROR:"error"};var B=(e,n,a)=>{if(!(n in e))throw new Error(a)},Q=e=>typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.trunc(e)),l=()=>Date.now(),oe=e=>[...new Set(e)],re=(e,n)=>Object.fromEntries(n.map(a=>[a,e[a]===!0])),L=(e,n)=>{let a=n??oe(e),y=Object.fromEntries(a.map(r=>[r,!1]));for(let r of e)y[r]=!0;return y},ae=(e,n)=>({...e,[n]:!0}),W=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function",F=()=>({phase:b.IDLE,eventType:null,transitionId:null,error:null}),G=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(a=>[a,F()]))}),K=e=>e.type===D.GO_TO_STEP_BY_ID&&"stepId"in e,z=e=>e==="COMPLETE"||e==="TERMINATED",X=(e,n)=>{let a=n;for(let[y,r]of e.entries()){if(!r||typeof r!="object")throw new Error(`Journey transition at index ${y} must be an object.`);if(typeof r.from!="string"||typeof r.event!="string")throw new Error(`Journey transition at index ${y} must define string "from" and "event".`);if(r.from!==O&&!(r.from in a))throw new Error(`Journey transition at index ${y} references unknown from step "${r.from}".`);if(r.event==="completeJourney"||r.event==="terminateJourney"){if("to"in r&&r.to!==void 0)throw new Error(`Journey transition at index ${y} with event "${r.event}" cannot define "to".`);continue}if(typeof r.to!="string")throw new Error(`Journey transition at index ${y} with event "${r.event}" must define string "to".`);if(!z(r.to)&&!(r.to in a))throw new Error(`Journey transition at index ${y} points to unknown step "${r.to}".`)}},M=(e,n,a)=>a?{transitioned:n,transitionId:a,snapshot:e}:{transitioned:n,snapshot:e},_=(e,n,a,y,r,S,u)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let t=Math.max(0,Math.min(Math.trunc(n),e.length-1)),J=e[t],x=Object.keys(S);return{status:y,currentStepId:J,history:{timeline:[...e],index:t},context:a,visited:u?re(u,x):L(e,x),stepMeta:{...S},async:r}},Z=async(e,n,a,y)=>{for(let r of e){let S=r.from===O||r.from===n.currentStepId,u=r.event===a.type;if(!S||!u)continue;if(!r.when)return r;let t=r.when({context:n.context,from:n.currentStepId,timeline:n.history.timeline,index:n.history.index,event:a}),J=W(t);J&&y?.onAsyncGuardStart?.(r);let x;try{x=await t}catch(f){throw J&&y?.onAsyncGuardError?.(r,f),f}if(J&&y?.onAsyncGuardSuccess?.(r),x)return r}return null},j=(e,n,a)=>{let y=e.history.timeline.slice(0,e.history.index+1),r=y;n!==e.currentStepId&&(r=[...y,n]);let S=r.length-1,u=ae(e.visited,n);return _(r,S,a,e.status,e.async,e.stepMeta,u)};var Y=e=>typeof e=="object"&&e!==null,ee=e=>e===I.RUNNING||e===I.COMPLETE||e===I.TERMINATED,pe=()=>{let e=globalThis.localStorage;return!e||typeof e.getItem!="function"||typeof e.setItem!="function"||typeof e.removeItem!="function"?null:e},se=e=>{if(!e)return null;let n=e.storage??pe();return n?{key:e.key,storage:n,version:e.version??1,clearOnReset:e.clearOnReset??!0,serialize:e.serialize??JSON.stringify,deserialize:e.deserialize??JSON.parse,...e.migrate?{migrate:e.migrate}:{},...e.onError?{onError:e.onError}:{}}:null},te=(e,n,a,y)=>{if(!Y(e))return null;let r=!1,S=Y(e.history)?e.history:null;S||(r=!0);let u=S?.timeline??e.timeline,t=Array.isArray(u)?u.filter(E=>typeof E=="string"&&E in n):[],J=typeof e.currentStepId=="string"&&e.currentStepId in n?e.currentStepId:typeof e.current=="string"&&e.current in n?e.current:null;if(t.length===0){if(!J)return null;t.push(J),r=!0}let x=t.length-1,f=S?.index??e.index;if(typeof f=="number"&&Number.isFinite(f))x=Math.max(0,Math.min(Math.trunc(f),t.length-1)),x!==f&&(r=!0);else if(J){let E=t.lastIndexOf(J);E>=0&&(x=E,r=!0)}let d=ee(e.status)?e.status:I.RUNNING;ee(e.status)||(r=!0);let s=Object.keys(n),m=e.visited,w=Y(m)?Object.fromEntries(s.map(E=>[E,m[E]===!0])):null,v=Array.isArray(m)?L(m.filter(E=>typeof E=="string"&&E in n),s):null,h=L(t,s);if(w){let E=m;h=w,s.some(g=>typeof E[g]!="boolean")&&(r=!0)}else v&&(h=v),r=!0;let P=Y(e.stepMeta)?e.stepMeta:null;P||(r=!0);let C=Object.fromEntries(Object.keys(n).map(E=>{let k=E,g=P?P[E]:void 0;return g===void 0?[k,y[k]]:[k,g]}));return{snapshot:{currentStepId:t[x],history:{timeline:t,index:x},context:"context"in e?e.context:a,status:d,visited:h,stepMeta:C},needsRewrite:r}},q=e=>{let{initial:n,context:a,stepMeta:y,steps:r,options:S}=e,u=se(S?.persistence),t=d=>{u?.onError?.(d)},J=d=>{if(u)try{let s={version:u.version,snapshot:{currentStepId:d.currentStepId,history:{timeline:[...d.history.timeline],index:d.history.index},context:d.context,status:d.status,visited:{...d.visited},stepMeta:{...d.stepMeta}}};u.storage.setItem(u.key,u.serialize(s))}catch(s){t(s)}},x=()=>{if(u)try{u.storage.removeItem(u.key)}catch(d){t(d)}},f=()=>{let d=_([n],0,a,I.RUNNING,G(r),y);if(!u)return d;try{let s=u.storage.getItem(u.key);if(!s)return d;let m=u.deserialize(s);if(!Y(m))return d;let w=m.version;if(typeof w!="number")return d;let v=null,h=!1;if(w===u.version){let C=te(m.snapshot,r,a,y);v=C?.snapshot??null,h=!!C?.needsRewrite}else if(u.migrate){let C=u.migrate(m.snapshot,w);v=te(C,r,a,y)?.snapshot??null,h=v!==null}if(!v)return d;let P=_(v.history.timeline,v.history.index,v.context,v.status,G(r),v.stepMeta,v.visited);return h&&J(P),P}catch(s){return t(s),d}};return{clearOnReset:u?.clearOnReset??!0,hydrateSnapshot:f,persistSnapshot:J,removePersistedSnapshot:x}};function ie(e,n){if(!e.steps||typeof e.steps!="object")throw new Error("Journey steps must be a record object.");if(!Array.isArray(e.transitions))throw new Error("Journey transitions must be an array.");B(e.steps,e.initial,`Journey initial step "${e.initial}" does not exist in steps registry.`),X(e.transitions,e.steps);let a=()=>{let o={};for(let p of Object.keys(e.steps))o[p]=e.steps[p].meta;return o},{clearOnReset:y,hydrateSnapshot:r,persistSnapshot:S,removePersistedSnapshot:u}=q({initial:e.initial,context:e.context,stepMeta:a(),steps:e.steps,...n?{options:n}:{}}),t=r();t={...t,async:G(e.steps)};let J=new Set,x=new Set,f=Promise.resolve(),d=()=>{for(let o of J)o()},s=o=>{for(let p of x)p(o)},m=o=>{let p=f.then(o,o);return f=p.then(()=>{},()=>{}),p},w=o=>o===b.EVALUATING_WHEN||o===b.RUNNING_EFFECT,v=(o,p)=>{let i=t.async.byStep[o]??F(),T=p(i);if(i.phase===T.phase&&i.eventType===T.eventType&&i.transitionId===T.transitionId&&i.error===T.error)return;let N={...t.async.byStep,[o]:T},R=Object.values(N).some(U=>w(U.phase));t={...t,async:{isLoading:R,byStep:N}},d()},h=(o,p,i,T)=>{v(o,()=>({phase:p,eventType:i,transitionId:T??null,error:null}))},P=o=>{v(o,()=>F())},C=(o,p,i,T)=>{v(o,()=>({phase:b.ERROR,eventType:p,transitionId:T??null,error:i}))},E=(o,p)=>{if(t.status!==I.RUNNING)return M(t,!1);let i=Q(o);if(t.history.index===0)return M(t,!1);let T=t.currentStepId,N=Math.max(0,t.history.index-i),R=t.history.index-N;return R<=0?M(t,!1):(s({type:"step.exit",stepId:T,timestamp:l()}),t=_(t.history.timeline,N,t.context,t.status,t.async,t.stepMeta,t.visited),S(t),d(),s({type:"navigation.previous",from:T,to:t.currentStepId,requestedSteps:i,appliedSteps:R,timestamp:l()}),s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,p))},k=o=>{if(t.status!==I.RUNNING)return M(t,!1);let p=t.history.timeline.length-1;if(t.history.index>=p)return M(t,!1);let i=t.currentStepId;return s({type:"step.exit",stepId:i,timestamp:l()}),t=_(t.history.timeline,p,t.context,t.status,t.async,t.stepMeta,t.visited),S(t),d(),s({type:"navigation.lastVisited",from:i,to:t.currentStepId,timestamp:l()}),s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,o)},g={getSnapshot:()=>t,subscribe:o=>(J.add(o),()=>{J.delete(o)}),subscribeEvent:o=>(x.add(o),()=>{x.delete(o)}),resetMachine:()=>(t=_([e.initial],0,e.context,I.RUNNING,G(e.steps),a()),y?u():S(t),d(),t),updateContext:o=>(t={...t,context:o(t.context)},S(t),d(),t),updateStepMetadata:(o,p)=>{if(!(o in e.steps))return t;let i=t.stepMeta[o],T=p(i);return Object.is(i,T)||(t={...t,stepMeta:{...t.stepMeta,[o]:T}},S(t),d(),s({type:"metadata.updated",stepId:o,previous:i,next:T,timestamp:l()})),t},clearStepError:o=>{let p=o??t.currentStepId;return p in e.steps&&P(p),t},goToPreviousStep:o=>m(async()=>E(o,"goToPreviousStep")),goToLastVisitedStep:()=>m(async()=>k("goToLastVisitedStep")),goToNextStep:()=>g.send({type:"goToNextStep"}),terminateJourney:o=>o===void 0?g.send({type:"terminateJourney"}):g.send({type:"terminateJourney",payload:o}),completeJourney:o=>o===void 0?g.send({type:"completeJourney"}):g.send({type:"completeJourney",payload:o}),send:o=>m(async()=>{if(t.status!==I.RUNNING)return M(t,!1);let p=t.currentStepId;if(K(o)){B(e.steps,o.stepId,`Cannot goToStepById unknown step "${o.stepId}".`),s({type:"transition.start",from:p,event:o,timestamp:l()}),P(p);let c=t.currentStepId,A=j(t,o.stepId,t.context);return A.currentStepId!==c&&s({type:"step.exit",stepId:c,timestamp:l()}),t=A,S(t),d(),s({type:"transition.success",from:p,to:t.currentStepId,eventType:D.GO_TO_STEP_BY_ID,transitionId:D.GO_TO_STEP_BY_ID,timestamp:l()}),A.currentStepId!==c&&s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,D.GO_TO_STEP_BY_ID)}let i=o;s({type:"transition.start",from:p,event:o,timestamp:l()});let T;try{T=await Z(e.transitions,t,i,{onAsyncGuardStart:c=>{h(p,b.EVALUATING_WHEN,i.type,c.id)},onAsyncGuardSuccess:()=>{P(p)},onAsyncGuardError:(c,A)=>{C(p,i.type,A,c.id)}})}catch(c){throw C(p,i.type,c),s({type:"transition.error",from:p,eventType:i.type,transitionId:null,error:c,timestamp:l()}),c}if(!T){if(o.type==="goToPreviousStep"||o.type==="back"){let c=E(1,o.type);return c.transitioned&&s({type:"transition.success",from:p,to:c.snapshot.currentStepId,eventType:o.type,transitionId:null,timestamp:l()}),c}return M(t,!1)}let N=t.context;if(T.effect){let c=T.effect({context:t.context,from:t.currentStepId,timeline:t.history.timeline,index:t.history.index,event:i});W(c)&&h(p,b.RUNNING_EFFECT,i.type,T.id);let A;try{A=await c}catch(H){throw C(p,i.type,H,T.id),s({type:"transition.error",from:p,eventType:i.type,transitionId:T.id??null,error:H,timestamp:l()}),H}A!==void 0&&(N=A)}P(p);let R=T.event==="completeJourney"?"COMPLETE":T.event==="terminateJourney"?"TERMINATED":T.to;if(z(R)){let c=t.history.timeline.slice(0,t.history.index+1);return t={...t,history:{timeline:c,index:c.length-1},context:N,status:R==="COMPLETE"?I.COMPLETE:I.TERMINATED},S(t),d(),s({type:"transition.success",from:p,to:R,eventType:i.type,transitionId:T.id??null,timestamp:l()}),s({type:R==="COMPLETE"?"journey.complete":"journey.close",stepId:t.currentStepId,timestamp:l()}),M(t,!0,T.id)}let U=R;B(e.steps,U,`Transition points to unknown step "${U}".`);let $=t.currentStepId;return $!==U&&s({type:"step.exit",stepId:$,timestamp:l()}),t=j(t,U,N),S(t),d(),s({type:"transition.success",from:p,to:t.currentStepId,eventType:i.type,transitionId:T.id??null,timestamp:l()}),$!==t.currentStepId&&s({type:"step.enter",stepId:t.currentStepId,timestamp:l()}),M(t,!0,T.id)})};return g}var ne=(e,n)=>n==="completeJourney"?{complete:(a={})=>({...a,from:e,event:n})}:n==="terminateJourney"?{terminate:(a={})=>({...a,from:e,event:n})}:{to:(a,y={})=>({...y,from:e,event:n,to:a}),choose:(...a)=>a.map(y=>({...y,from:e,event:n}))},V=(e,n,a={})=>({...a,from:e,event:n}),Te={from:e=>({on:n=>ne(e,n),toComplete:(n={})=>V(e,"completeJourney",n),toTerminate:(n={})=>V(e,"terminateJourney",n)}),any:()=>({on:e=>ne(O,e),toComplete:(e={})=>V(O,"completeJourney",e),toTerminate:(e={})=>V(O,"terminateJourney",e)}),when:e=>({to:(n,a={})=>({...a,to:n,when:e})}),otherwise:()=>({to:(e,n={})=>({...n,to:e})})},ye=(...e)=>e.flatMap(n=>Array.isArray(n)?[...n]:[n]);export{b as JOURNEY_ASYNC_PHASE,D as JOURNEY_EVENT,I as JOURNEY_STATUS,O as JOURNEY_WILDCARD,ie as createJourneyMachine,q as createPersistenceController,ye as createTransitions,Te as tx};
1
+ var f={RUNNING:"running",COMPLETE:"complete",TERMINATED:"terminated"},O="*",A={GO_TO_STEP_BY_ID:"goToStepById"},N={IDLE:"idle",EVALUATING_WHEN:"evaluating-when",RUNNING_EFFECT:"running-effect",ERROR:"error"};var Y=(e,r,i)=>{if(!(r in e))throw new Error(i)},ne=e=>typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.trunc(e)),J=()=>Date.now(),me=e=>[...new Set(e)],Me=(e,r)=>Object.fromEntries(r.map(i=>[i,e[i]===!0])),F=(e,r)=>{let i=r??me(e),d=Object.fromEntries(i.map(a=>[a,!1]));for(let a of e)d[a]=!0;return d},fe=(e,r)=>({...e,[r]:!0}),H=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function",L=()=>({phase:N.IDLE,eventType:null,transitionId:null,error:null}),U=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(i=>[i,L()]))}),W=e=>e.type===A.GO_TO_STEP_BY_ID&&"stepId"in e,z=e=>e==="COMPLETE"||e==="TERMINATED",oe=(e,r)=>{let i=r;for(let[d,a]of e.entries()){if(!a||typeof a!="object")throw new Error(`Journey transition at index ${d} must be an object.`);if(typeof a.from!="string"||typeof a.event!="string")throw new Error(`Journey transition at index ${d} must define string "from" and "event".`);if(a.from!==O&&!(a.from in i))throw new Error(`Journey transition at index ${d} references unknown from step "${a.from}".`);if(a.event==="completeJourney"||a.event==="terminateJourney"){if("to"in a&&a.to!==void 0)throw new Error(`Journey transition at index ${d} with event "${a.event}" cannot define "to".`);continue}if(typeof a.to!="string")throw new Error(`Journey transition at index ${d} with event "${a.event}" must define string "to".`);if(!z(a.to)&&!(a.to in i))throw new Error(`Journey transition at index ${d} points to unknown step "${a.to}".`)}},P=(e,r,i={})=>({transitioned:r,...i.transitionId!==void 0?{transitionId:i.transitionId}:{},..."error"in i?{error:i.error}:{},snapshot:e}),_=(e,r,i,d,a,c,y)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let t=Math.max(0,Math.min(Math.trunc(r),e.length-1)),m=e[t],M=Object.keys(c);return{status:d,currentStepId:m,history:{timeline:[...e],index:t},context:i,visited:y?Me(y,M):F(e,M),stepMeta:{...c},async:a}},re=async(e,r,i,d)=>{for(let a of e){let c=a.from===O||a.from===r.currentStepId,y=a.event===i.type;if(!c||!y)continue;if(!a.when)return a;let t=a.when({context:r.context,from:r.currentStepId,timeline:r.history.timeline,index:r.history.index,event:i}),m=H(t);m&&d?.onAsyncGuardStart?.(a);let M;try{M=await t}catch(C){throw m&&d?.onAsyncGuardError?.(a,C),C}if(m&&d?.onAsyncGuardSuccess?.(a),M)return a}return null},Q=(e,r,i)=>{let d=e.history.timeline.slice(0,e.history.index+1),a=d;r!==e.currentStepId&&(a=[...d,r]);let c=a.length-1,y=fe(e.visited,r);return _(a,c,i,e.status,e.async,e.stepMeta,y)};var G=e=>typeof e=="object"&&e!==null,ae=e=>e===f.RUNNING||e===f.COMPLETE||e===f.TERMINATED,Pe=()=>{let e=globalThis.localStorage;return!e||typeof e.getItem!="function"||typeof e.setItem!="function"||typeof e.removeItem!="function"?null:e},Ce=e=>{if(!e)return null;let r=e.storage;if(r==null)try{r=Pe()}catch(i){return e.onError?.(i),null}return r?{key:e.key,storage:r,version:e.version??1,clearOnReset:e.clearOnReset??!0,serialize:e.serialize??JSON.stringify,deserialize:e.deserialize??JSON.parse,...e.migrate?{migrate:e.migrate}:{},...e.onError?{onError:e.onError}:{}}:null},ge=(e,r,i)=>{let d=F(r,i);if(G(e)){let a=!1,c={...d};for(let y of i){let t=e[y];if(t===!0){c[y]=!0;continue}if(t===!1){d[y]&&(a=!0);continue}a=!0}return{visited:c,needsRewrite:a}}if(Array.isArray(e)){let a=F(e.filter(y=>typeof y=="string"&&i.includes(y)),i);return{visited:Object.fromEntries(i.map(y=>[y,d[y]||a[y]])),needsRewrite:!0}}return{visited:d,needsRewrite:!0}},se=(e,r,i,d)=>{if(!G(e))return null;let a=!1,c=G(e.history)?e.history:null;c||(a=!0);let y=c?.timeline??e.timeline,t=Array.isArray(y)?y.filter(x=>typeof x=="string"&&x in r):[],m=typeof e.currentStepId=="string"&&e.currentStepId in r?e.currentStepId:typeof e.current=="string"&&e.current in r?e.current:null;if(t.length===0){if(!m)return null;t.push(m),a=!0}let M=t.length-1,C=c?.index??e.index;if(typeof C=="number"&&Number.isFinite(C))M=Math.max(0,Math.min(Math.trunc(C),t.length-1)),M!==C&&(a=!0);else if(m){let x=t.lastIndexOf(m);x>=0&&(M=x,a=!0)}let S=ae(e.status)?e.status:f.RUNNING;ae(e.status)||(a=!0);let g=Object.keys(r),{visited:R,needsRewrite:I}=ge(e.visited,t,g);I&&(a=!0);let E=G(e.stepMeta)?e.stepMeta:null;E||(a=!0);let D=Object.fromEntries(Object.keys(r).map(x=>{let l=x,k=E?E[x]:void 0;return k===void 0?[l,d[l]]:[l,k]}));return{snapshot:{currentStepId:t[M],history:{timeline:t,index:M},context:"context"in e?e.context:i,status:S,visited:R,stepMeta:D},needsRewrite:a}},K=e=>{let{initial:r,context:i,stepMeta:d,steps:a,options:c}=e,y=Ce(c?.persistence),t=S=>{y?.onError?.(S)},m=S=>{if(y)try{let g={version:y.version,snapshot:{currentStepId:S.currentStepId,history:{timeline:[...S.history.timeline],index:S.history.index},context:S.context,status:S.status,visited:{...S.visited},stepMeta:{...S.stepMeta}}};y.storage.setItem(y.key,y.serialize(g))}catch(g){t(g)}},M=()=>{if(y)try{y.storage.removeItem(y.key)}catch(S){t(S)}},C=()=>{let S=_([r],0,i,f.RUNNING,U(a),d);if(!y)return S;try{let g=y.storage.getItem(y.key);if(!g)return S;let R=y.deserialize(g);if(!G(R))return S;let I=R.version;if(typeof I!="number")return S;let E=null,D=!1;if(I===y.version){let l=se(R.snapshot,a,i,d);E=l?.snapshot??null,D=!!l?.needsRewrite}else if(y.migrate){let l=y.migrate(R.snapshot,I);E=se(l,a,i,d)?.snapshot??null,D=E!==null}if(!E)return S;let x=_(E.history.timeline,E.history.index,E.context,E.status,U(a),E.stepMeta,E.visited);return D&&m(x),x}catch(g){return t(g),S}};return{clearOnReset:y?.clearOnReset??!0,hydrateSnapshot:C,persistSnapshot:m,removePersistedSnapshot:M}};function Re(e,r){if(!e.steps||typeof e.steps!="object")throw new Error("Journey steps must be a record object.");if(!Array.isArray(e.transitions))throw new Error("Journey transitions must be an array.");for(let n of Object.keys(e.steps))if(n==="*")throw new Error('Step id "*" is reserved as a wildcard and cannot be used as a step name.');Y(e.steps,e.initial,`Journey initial step "${e.initial}" does not exist in steps registry.`),oe(e.transitions,e.steps);let i=()=>{let n={};for(let o of Object.keys(e.steps))n[o]=e.steps[o].meta;return n},{clearOnReset:d,hydrateSnapshot:a,persistSnapshot:c,removePersistedSnapshot:y}=K({initial:e.initial,context:e.context,stepMeta:i(),steps:e.steps,...r?{options:r}:{}}),t=a();t={...t,async:U(e.steps)};let m=r?.completeOnNoNextStep??!0,M={type:"journey.start",stepId:t.currentStepId,timestamp:J()},C=new Set,S=new Set,g=Promise.resolve(),R=0,I=!1,E=n=>!I&&n===R,D=()=>{R+=1,g=Promise.resolve()},x=()=>{for(let n of C)n()},l=n=>{for(let o of S)o(n)},k=(n,o)=>{let s=R,p=async()=>E(s)?n(s):o(),T=v=>{g=v.then(()=>{},()=>{})},u=g.then(p,p);return T(u),u},Te=n=>n===N.EVALUATING_WHEN||n===N.RUNNING_EFFECT,j=(n,o,s)=>{if(s!==void 0&&!E(s))return;let p=t.async.byStep[n]??L(),T=o(p);if(p.phase===T.phase&&p.eventType===T.eventType&&p.transitionId===T.transitionId&&p.error===T.error)return;let u={...t.async.byStep,[n]:T},v=Object.values(u).some(b=>Te(b.phase));t={...t,async:{isLoading:v,byStep:u}},x()},X=(n,o,s,p,T)=>{j(n,()=>({phase:o,eventType:s,transitionId:p??null,error:null}),T)},B=(n,o)=>{j(n,()=>L(),o)},Z=(n,o,s,p,T)=>{j(n,()=>({phase:N.ERROR,eventType:o,transitionId:p??null,error:s}),T)},ee=(n,o)=>{if(t.status!==f.RUNNING)return P(t,!1);let s=ne(n);if(t.history.index===0)return P(t,!1);let p=t.currentStepId,T=Math.max(0,t.history.index-s),u=t.history.index-T;return u<=0?P(t,!1):(l({type:"step.exit",stepId:p,timestamp:J()}),t=_(t.history.timeline,T,t.context,t.status,t.async,t.stepMeta,t.visited),c(t),x(),l({type:"navigation.previous",from:p,to:t.currentStepId,requestedSteps:s,appliedSteps:u,timestamp:J()}),l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...o!==void 0?{transitionId:o}:{}}))},ye=n=>{if(t.status!==f.RUNNING)return P(t,!1);let o=t.history.timeline.length-1;if(t.history.index>=o)return P(t,!1);let s=t.currentStepId;return l({type:"step.exit",stepId:s,timestamp:J()}),t=_(t.history.timeline,o,t.context,t.status,t.async,t.stepMeta,t.visited),c(t),x(),l({type:"navigation.lastVisited",from:s,to:t.currentStepId,timestamp:J()}),l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...n!==void 0?{transitionId:n}:{}})},w=()=>P(t,!1),de=(n,o)=>P(t,!1,{...o!==void 0?{transitionId:o}:{},error:n}),$=(n,o,s,p,T)=>(Z(n,o,s,p??void 0,T),l({type:"transition.error",from:n,eventType:o,transitionId:p,error:s,timestamp:J()}),de(s,p??void 0)),ue=(n,o,s)=>{B(o,s);let p=t.currentStepId,T=Q(t,n,t.context);return T.currentStepId!==p&&l({type:"step.exit",stepId:p,timestamp:J()}),t=T,c(t),x(),l({type:"transition.success",from:o,to:t.currentStepId,eventType:A.GO_TO_STEP_BY_ID,transitionId:A.GO_TO_STEP_BY_ID,timestamp:J()}),T.currentStepId!==p&&l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{transitionId:A.GO_TO_STEP_BY_ID})},le=(n,o,s)=>{if(!W(n))return{transitionsToEvaluate:e.transitions,earlyResult:null};Y(e.steps,n.stepId,`Cannot goToStepById unknown step "${n.stepId}".`);let p=e.transitions.filter(T=>(T.from==="*"||T.from===o)&&T.event===A.GO_TO_STEP_BY_ID&&"to"in T&&T.to===n.stepId);return p.length===0?{transitionsToEvaluate:e.transitions,earlyResult:ue(n.stepId,o,s)}:{transitionsToEvaluate:p,earlyResult:null}},Se=async(n,o,s,p)=>{let T;try{T=await re(n,t,o,{onAsyncGuardStart:u=>{X(s,N.EVALUATING_WHEN,o.type,u.id,p)},onAsyncGuardSuccess:()=>{B(s,p)},onAsyncGuardError:(u,v)=>{Z(s,o.type,v,u.id,p)}})}catch(u){return E(p)?{transition:null,earlyResult:$(s,o.type,u,null,p)}:{transition:null,earlyResult:w()}}return{transition:T,earlyResult:null}},ce=(n,o)=>{if(W(n))return w();if(n.type==="goToPreviousStep"||n.type==="back"){let s=ee(1,n.type);return s.transitioned&&l({type:"transition.success",from:o,to:s.snapshot.currentStepId,eventType:n.type,transitionId:null,timestamp:J()}),s}return n.type==="goToNextStep"&&m&&!Je(o,"goToNextStep")?te(o,"COMPLETE",n,null,t.context):w()},Ee=async(n,o,s,p)=>{let T=t.context;if(!n.effect)return{nextContext:T,earlyResult:null};let u;try{u=n.effect({context:t.context,from:t.currentStepId,timeline:t.history.timeline,index:t.history.index,event:o})}catch(b){return E(p)?{nextContext:null,earlyResult:$(s,o.type,b,n.id??null,p)}:{nextContext:null,earlyResult:w()}}H(u)&&X(s,N.RUNNING_EFFECT,o.type,n.id,p);let v;try{v=await u}catch(b){return E(p)?{nextContext:null,earlyResult:$(s,o.type,b,n.id??null,p)}:{nextContext:null,earlyResult:w()}}return E(p)?(v!==void 0&&(T=v),{nextContext:T,earlyResult:null}):{nextContext:null,earlyResult:w()}},xe=n=>n.event==="completeJourney"?"COMPLETE":n.event==="terminateJourney"?"TERMINATED":n.to,Je=(n,o)=>e.transitions.some(s=>(s.from==="*"||s.from===n)&&s.event===o),te=(n,o,s,p,T)=>{let u=t.history.timeline.slice(0,t.history.index+1);return t={...t,history:{timeline:u,index:u.length-1},context:T,status:o==="COMPLETE"?f.COMPLETE:f.TERMINATED},c(t),x(),l({type:"transition.success",from:n,to:o,eventType:s.type,transitionId:p,timestamp:J()}),l({type:o==="COMPLETE"?"journey.complete":"journey.close",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...p!==null?{transitionId:p}:{}})},ve=(n,o,s,p,T)=>{Y(e.steps,o,`Transition points to unknown step "${o}".`);let u=t.currentStepId;return u!==o&&l({type:"step.exit",stepId:u,timestamp:J()}),t=Q(t,o,T),c(t),x(),l({type:"transition.success",from:n,to:t.currentStepId,eventType:s.type,transitionId:p.id??null,timestamp:J()}),u!==t.currentStepId&&l({type:"step.enter",stepId:t.currentStepId,timestamp:J()}),P(t,!0,{...p.id!==void 0?{transitionId:p.id}:{}})},Ie=async(n,o)=>{if(t.status!==f.RUNNING)return w();let s=t.currentStepId,p=n;l({type:"transition.start",from:s,event:n,timestamp:J()});let T=le(n,s,o);if(T.earlyResult)return T.earlyResult;let u=await Se(T.transitionsToEvaluate,p,s,o);if(u.earlyResult)return u.earlyResult;if(!E(o))return w();let{transition:v}=u;if(!v)return ce(n,s);let b=await Ee(v,p,s,o);if(b.earlyResult)return b.earlyResult;B(s,o);let q=xe(v);return z(q)?te(s,q,p,v.id??null,b.nextContext):ve(s,q,p,v,b.nextContext)},h={getSnapshot:()=>t,subscribe:n=>I?()=>{}:(C.add(n),()=>{C.delete(n)}),subscribeSelector:(n,o,s)=>{if(I)return()=>{};let p=s??Object.is,T=n(t);return h.subscribe(()=>{let u=n(t);if(p(T,u))return;let v=T;T=u,o(u,v)})},subscribeEvent:n=>{if(I)return()=>{};S.add(n);try{n(M)}catch(o){throw S.delete(n),o}return()=>{S.delete(n)}},subscribeStart:n=>h.subscribeEvent(o=>{o.type==="journey.start"&&n(o)}),subscribeComplete:n=>h.subscribeEvent(o=>{o.type==="journey.complete"&&n(o)}),subscribeTerminate:n=>h.subscribeEvent(o=>{o.type==="journey.close"&&n(o)}),resetMachine:()=>(I||(D(),t=_([e.initial],0,e.context,f.RUNNING,U(e.steps),i()),d?y():c(t),x()),t),updateContext:n=>(I||(t={...t,context:n(t.context)},c(t),x()),t),updateStepMetadata:(n,o)=>{if(I||!(n in e.steps))return t;let s=t.stepMeta[n],p=o(s);return Object.is(s,p)||(t={...t,stepMeta:{...t.stepMeta,[n]:p}},c(t),x(),l({type:"metadata.updated",stepId:n,previous:s,next:p,timestamp:J()})),t},clearStepError:n=>{if(I)return t;let o=n??t.currentStepId;return o in e.steps&&B(o),t},dispose:()=>{I||(I=!0,D(),C.clear(),S.clear())},goToPreviousStep:n=>k(async()=>ee(n,"goToPreviousStep"),()=>P(t,!1)),goToLastVisitedStep:()=>k(async()=>ye("goToLastVisitedStep"),()=>P(t,!1)),goToNextStep:()=>h.send({type:"goToNextStep"}),terminateJourney:n=>n===void 0?h.send({type:"terminateJourney"}):h.send({type:"terminateJourney",payload:n}),completeJourney:n=>n===void 0?h.send({type:"completeJourney"}):h.send({type:"completeJourney",payload:n}),send:n=>k(async o=>Ie(n,o),w)};return h}var pe=e=>({to:(r,i={})=>({...i,to:r,...e?{when:e}:{}})}),ie=(e,r)=>r==="completeJourney"?{complete:(i={})=>({...i,from:e,event:r})}:r==="terminateJourney"?{terminate:(i={})=>({...i,from:e,event:r})}:{to:(i,d={})=>({...d,from:e,event:r,to:i}),choose:(...i)=>i.map(d=>({...d,from:e,event:r})),when:i=>pe(i),otherwise:()=>pe()},V=(e,r,i={})=>({...i,from:e,event:r}),he={from:e=>({on:r=>ie(e,r),toComplete:(r={})=>V(e,"completeJourney",r),toTerminate:(r={})=>V(e,"terminateJourney",r)}),any:()=>({on:e=>ie(O,e),toComplete:(e={})=>V(O,"completeJourney",e),toTerminate:(e={})=>V(O,"terminateJourney",e)}),when:e=>({to:(r,i={})=>({...i,to:r,when:e})}),otherwise:()=>({to:(e,r={})=>({...r,to:e})})},be=(...e)=>e.flatMap(r=>Array.isArray(r)?[...r]:[r]);export{N as JOURNEY_ASYNC_PHASE,A as JOURNEY_EVENT,f as JOURNEY_STATUS,O as JOURNEY_WILDCARD,Re as createJourneyMachine,K as createPersistenceController,be as createTransitions,he as tx};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/types/journey.types.ts", "../src/machine-helpers.ts", "../src/persistence.ts", "../src/machine.ts", "../src/transitions.ts"],
4
- "sourcesContent": ["import type { JourneyPersistenceOptions } from \"./persistence.types\";\nimport type { JourneyTransition } from \"./transitions.types\";\n\n/** Terminal outcomes reached when a journey completes or is explicitly terminated. */\nexport type JourneyTerminal = \"COMPLETE\" | \"TERMINATED\";\n\n/** Runtime machine status constants. */\nexport const JOURNEY_STATUS = {\n RUNNING: \"running\",\n COMPLETE: \"complete\",\n TERMINATED: \"terminated\"\n} as const;\n\n/** Union of possible runtime machine statuses. */\nexport type JourneyStatus = (typeof JOURNEY_STATUS)[keyof typeof JOURNEY_STATUS];\n\n/** Wildcard step identifier used by transitions that match from any step. */\nexport const JOURNEY_WILDCARD = \"*\" as const;\n\n/** Built-in event constants that are part of core machine behavior. */\nexport const JOURNEY_EVENT = {\n GO_TO_STEP_BY_ID: \"goToStepById\"\n} as const;\n\n/** Machine event types that are always recognized by core. */\nexport type JourneyBuiltInEvent = (typeof JOURNEY_EVENT)[keyof typeof JOURNEY_EVENT];\n/** Event literal type for the built-in go-to-step command. */\nexport type JourneyGoToStepByIdEventType = typeof JOURNEY_EVENT.GO_TO_STEP_BY_ID;\n/** Wildcard origin marker for transitions. */\nexport type JourneyBuiltInFrom = typeof JOURNEY_WILDCARD;\n/** Default transition event names supported by machine convenience APIs. */\nexport type JourneyDefaultEventType =\n | \"goToNextStep\"\n | \"goToPreviousStep\"\n | \"terminateJourney\"\n | \"completeJourney\";\n\n/** Async lifecycle phases tracked per step while guards/effects run. */\nexport const JOURNEY_ASYNC_PHASE = {\n IDLE: \"idle\",\n EVALUATING_WHEN: \"evaluating-when\",\n RUNNING_EFFECT: \"running-effect\",\n ERROR: \"error\"\n} as const;\n\n/** Union of supported async lifecycle phases. */\nexport type JourneyAsyncPhase = (typeof JOURNEY_ASYNC_PHASE)[keyof typeof JOURNEY_ASYNC_PHASE];\n\n/** Async execution state for a single step. */\nexport type JourneyStepAsyncState = {\n phase: JourneyAsyncPhase;\n eventType: string | null;\n transitionId: string | null;\n error: unknown | null;\n};\n\n/** Aggregated async state for the machine, keyed by step id. */\nexport type JourneyAsyncState<TStepId extends string> = {\n isLoading: boolean;\n byStep: Record<TStepId, JourneyStepAsyncState>;\n};\n\n/** Minimal event shape used across runtime boundaries. */\nexport type JourneyBaseEvent = {\n type: string;\n payload?: unknown;\n};\n\n/** Optional event payload map by event type. */\nexport type JourneyEventPayloadMap<TEventType extends string> = Partial<\n Record<TEventType | JourneyBuiltInEvent, unknown>\n>;\n\n/** Resolves payload type for a specific event type from the provided payload map. */\nexport type JourneyPayloadFor<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TEvent extends TEventType | JourneyBuiltInEvent\n> = TEvent extends keyof TPayloadMap ? TPayloadMap[TEvent] : unknown;\n\n/** Event-type union accepted by machine `.send()`, including built-in convenience events. */\nexport type JourneyMachineEventType<TEventType extends string> =\n | TEventType\n | JourneyDefaultEventType;\n\n/** Payload map available to machine `.send()`, including built-in convenience events. */\nexport type JourneyMachinePayloadMap<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n> = TPayloadMap & JourneyEventPayloadMap<JourneyDefaultEventType>;\n\ntype JourneyPayloadForDefaultEvent<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TDefaultEvent extends JourneyDefaultEventType\n> = JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n TDefaultEvent\n>;\n\n/** Built-in direct-navigation event that targets a specific step id. */\nexport type JourneyGoToEvent<TStepId extends string, TPayload = unknown> = {\n type: JourneyGoToStepByIdEventType;\n stepId: TStepId;\n payload?: TPayload;\n};\n\n/** Event union available to transitions and guards for the declared event type set. */\nexport type JourneyEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> =\n | JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<TEventType, TPayloadMap, JourneyGoToStepByIdEventType>\n >\n | {\n [TType in TEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<TEventType, TPayloadMap, TType>;\n };\n }[TEventType];\n\ntype JourneyDefaultMachineEvent<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n> = {\n [TType in JourneyDefaultEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n TType\n >;\n };\n}[JourneyDefaultEventType];\n\ntype JourneyCustomMachineEvent<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n> = {\n [TType in TEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<TEventType, TPayloadMap, TType>;\n };\n}[TEventType];\n\n/** Event union accepted by `JourneyMachine.send`. */\nexport type JourneySendEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> =\n | JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n JourneyGoToStepByIdEventType\n >\n >\n | JourneyDefaultMachineEvent<TEventType, TPayloadMap>\n | JourneyCustomMachineEvent<TEventType, TPayloadMap>;\n\n/**\n * Step definition with optional metadata and optional typed extension fields.\n * Use `TStepExtra` to explicitly model additional per-step properties.\n */\nexport type JourneyStepDefinition<\n TStepMeta = unknown,\n TStepExtra extends object = Record<never, never>\n> = {\n meta?: TStepMeta;\n} & TStepExtra;\n\n/** Serializable runtime snapshot of the journey state. */\nexport type JourneySnapshot<TContext, TStepId extends string, TStepMeta = unknown> = {\n currentStepId: TStepId;\n history: {\n timeline: readonly TStepId[];\n index: number;\n };\n context: TContext;\n visited: Record<TStepId, boolean>;\n stepMeta: Record<TStepId, TStepMeta>;\n status: JourneyStatus;\n async: JourneyAsyncState<TStepId>;\n};\n\n/** Full machine definition used to create a journey machine instance. */\nexport type JourneyDefinition<\n TContext,\n TStepId extends string = string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown,\n TStepExtra extends object = Record<never, never>\n> = {\n initial: TStepId;\n context: TContext;\n steps: Record<TStepId, JourneyStepDefinition<TStepMeta, TStepExtra>>;\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[];\n};\n\n/** Optional machine features (for example, persistence configuration). */\nexport type JourneyMachineOptions<TContext, TStepId extends string, TStepMeta = unknown> = {\n persistence?: JourneyPersistenceOptions<TContext, TStepId, TStepMeta>;\n};\n\n/** Result returned from send/navigation APIs. */\nexport type JourneySendResult<TContext, TStepId extends string, TStepMeta = unknown> = {\n transitioned: boolean;\n transitionId?: string;\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;\n};\n\n/** Observation events emitted by the machine lifecycle/event stream. */\nexport type JourneyObservationEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n> =\n | {\n type: \"transition.start\";\n from: TStepId;\n event: JourneySendEvent<TStepId, TEventType, TPayloadMap>;\n timestamp: number;\n }\n | {\n type: \"transition.success\";\n from: TStepId;\n to: TStepId | JourneyTerminal;\n eventType: string;\n transitionId: string | null;\n timestamp: number;\n }\n | {\n type: \"transition.error\";\n from: TStepId;\n eventType: string;\n transitionId: string | null;\n error: unknown;\n timestamp: number;\n }\n | {\n type: \"step.exit\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"step.enter\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"journey.complete\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"journey.close\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"navigation.previous\";\n from: TStepId;\n to: TStepId;\n requestedSteps: number;\n appliedSteps: number;\n timestamp: number;\n }\n | {\n type: \"navigation.lastVisited\";\n from: TStepId;\n to: TStepId;\n timestamp: number;\n }\n | {\n type: \"metadata.updated\";\n stepId: TStepId;\n previous: TStepMeta;\n next: TStepMeta;\n timestamp: number;\n };\n\n/** Runtime machine API for reading snapshots, sending events, and controlling flow. */\nexport type JourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n> = {\n getSnapshot: () => JourneySnapshot<TContext, TStepId, TStepMeta>;\n send: (\n event: JourneySendEvent<TStepId, TEventType, TPayloadMap>\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToNextStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n terminateJourney: (\n payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, \"terminateJourney\">\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n completeJourney: (\n payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, \"completeJourney\">\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToPreviousStep: (steps?: number) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToLastVisitedStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n updateContext: (\n updater: (context: TContext) => TContext\n ) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n updateStepMetadata: (\n stepId: TStepId,\n updater: (metadata: TStepMeta) => TStepMeta\n ) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n clearStepError: (stepId?: TStepId) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n resetMachine: () => JourneySnapshot<TContext, TStepId, TStepMeta>;\n subscribe: (listener: () => void) => () => void;\n subscribeEvent: (\n listener: (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => void\n ) => () => void;\n};\n", "import { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_WILDCARD } from \"./types\";\nimport type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyEventPayloadMap,\n JourneyGoToEvent,\n JourneyGoToStepByIdEventType,\n JourneyMachineEventType,\n JourneyMachinePayloadMap,\n JourneyPayloadFor,\n JourneySendEvent,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransition\n} from \"./types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nexport const normalizeStepCount = (steps?: number): number => {\n if (typeof steps !== \"number\" || !Number.isFinite(steps)) {\n return 1;\n }\n return Math.max(1, Math.trunc(steps));\n};\n\nexport const now = (): number => Date.now();\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nconst normalizeVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n stepIds: readonly TStepId[]\n): Record<TStepId, boolean> =>\n Object.fromEntries(stepIds.map((stepId) => [stepId, visited[stepId] === true])) as Record<\n TStepId,\n boolean\n >;\n\nexport const buildVisitedFromTimeline = <TStepId extends string>(\n timeline: readonly TStepId[],\n stepIds?: readonly TStepId[]\n): Record<TStepId, boolean> => {\n const resolvedStepIds = stepIds ?? unique(timeline);\n const visited = Object.fromEntries(resolvedStepIds.map((stepId) => [stepId, false])) as Record<\n TStepId,\n boolean\n >;\n\n for (const stepId of timeline) {\n visited[stepId] = true;\n }\n\n return visited;\n};\n\nexport const appendVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n current: TStepId\n): Record<TStepId, boolean> => ({\n ...visited,\n [current]: true\n});\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: JOURNEY_ASYNC_PHASE.IDLE,\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToStepByIdEvent = <\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n event: JourneySendEvent<TStepId, TEventType, TPayloadMap>\n): event is JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n JourneyGoToStepByIdEventType\n >\n> => event.type === JOURNEY_EVENT.GO_TO_STEP_BY_ID && \"stepId\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal\n): target is JourneyTerminal => target === \"COMPLETE\" || target === \"TERMINATED\";\n\nexport const validateJourneyTransitions = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[],\n steps: Record<TStepId, unknown>\n) => {\n const stepRegistry = steps as Record<string, unknown>;\n\n for (const [index, transition] of transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (transition.from !== JOURNEY_WILDCARD && !(transition.from in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n if (transition.event === \"completeJourney\" || transition.event === \"terminateJourney\") {\n if (\"to\" in transition && transition.to !== undefined) {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" cannot define \"to\".`\n );\n }\n continue;\n }\n\n if (typeof transition.to !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" must define string \"to\".`\n );\n }\n\n if (!isTerminalTarget(transition.to) && !(transition.to in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n};\n\nexport const buildSendResult = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n transitioned: boolean,\n transitionId?: string\n): JourneySendResult<TContext, TStepId, TStepMeta> =>\n transitionId ? { transitioned, transitionId, snapshot } : { transitioned, snapshot };\n\nexport const buildSnapshot = <TContext, TStepId extends string, TStepMeta>(\n timeline: readonly TStepId[],\n index: number,\n context: TContext,\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n stepMeta: Record<TStepId, TStepMeta>,\n visited?: Record<TStepId, boolean>\n): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n if (timeline.length === 0) {\n throw new Error(\"Journey timeline cannot be empty.\");\n }\n const safeIndex = Math.max(0, Math.min(Math.trunc(index), timeline.length - 1));\n const currentStepId = timeline[safeIndex] as TStepId;\n const stepIds = Object.keys(stepMeta) as TStepId[];\n return {\n status,\n currentStepId,\n history: {\n timeline: [...timeline],\n index: safeIndex\n },\n context,\n visited: visited\n ? normalizeVisited(visited, stepIds)\n : buildVisitedFromTimeline(timeline, stepIds),\n stepMeta: { ...stepMeta },\n async: asyncState\n };\n};\n\nexport const selectTransition = async <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TStepMeta\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[],\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>,\n hooks?: {\n onAsyncGuardStart?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardSuccess?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardError?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>,\n error: unknown\n ) => void;\n }\n): Promise<JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> | null> => {\n for (const transition of transitions) {\n const fromMatches =\n transition.from === JOURNEY_WILDCARD || transition.from === snapshot.currentStepId;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n const guardResult = transition.when({\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event\n });\n const asyncGuard = isPromiseLike(guardResult);\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n }\n\n let allowed: boolean;\n try {\n allowed = await guardResult;\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n const baseTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n let nextTimeline = baseTimeline;\n if (nextCurrent !== snapshot.currentStepId) {\n nextTimeline = [...baseTimeline, nextCurrent];\n }\n\n const nextIndex = nextTimeline.length - 1;\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(\n nextTimeline,\n nextIndex,\n nextContext,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n visited\n );\n};\n", "import { JOURNEY_STATUS } from \"./types/journey.types\";\nimport type {\n JourneyPersistedSnapshot,\n JourneyPersistedState,\n JourneyStorage,\n ResolvedPersistence\n} from \"./types/persistence.types\";\nimport type { JourneyMachineOptions, JourneySnapshot, JourneyStatus } from \"./types/journey.types\";\nimport { buildInitialAsyncState, buildSnapshot, buildVisitedFromTimeline } from \"./machine-helpers\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isStatusValue = (value: unknown): value is JourneyStatus =>\n value === JOURNEY_STATUS.RUNNING ||\n value === JOURNEY_STATUS.COMPLETE ||\n value === JOURNEY_STATUS.TERMINATED;\n\nconst resolveDefaultStorage = (): JourneyStorage | null => {\n const localStorageCandidate = (globalThis as { localStorage?: Partial<JourneyStorage> })\n .localStorage;\n\n if (\n !localStorageCandidate ||\n typeof localStorageCandidate.getItem !== \"function\" ||\n typeof localStorageCandidate.setItem !== \"function\" ||\n typeof localStorageCandidate.removeItem !== \"function\"\n ) {\n return null;\n }\n\n return localStorageCandidate as JourneyStorage;\n};\n\nconst resolvePersistence = <TContext, TStepId extends string, TStepMeta>(\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>[\"persistence\"]\n): ResolvedPersistence<TContext, TStepId, TStepMeta> | null => {\n if (!options) {\n return null;\n }\n\n const storage = options.storage ?? resolveDefaultStorage();\n if (!storage) {\n return null;\n }\n\n return {\n key: options.key,\n storage,\n version: options.version ?? 1,\n clearOnReset: options.clearOnReset ?? true,\n serialize: options.serialize ?? JSON.stringify,\n deserialize: options.deserialize ?? JSON.parse,\n ...(options.migrate ? { migrate: options.migrate } : {}),\n ...(options.onError ? { onError: options.onError } : {})\n };\n};\n\nconst coercePersistedSnapshot = <TContext, TStepId extends string, TStepMeta>(\n value: unknown,\n steps: Record<TStepId, unknown>,\n fallbackContext: TContext,\n fallbackStepMeta: Record<TStepId, TStepMeta>\n): {\n snapshot: JourneyPersistedSnapshot<TContext, TStepId, TStepMeta>;\n needsRewrite: boolean;\n} | null => {\n if (!isRecord(value)) {\n return null;\n }\n\n let needsRewrite = false;\n\n const rawHistory = isRecord(value.history) ? value.history : null;\n if (!rawHistory) {\n needsRewrite = true;\n }\n\n const rawTimeline = rawHistory?.timeline ?? value.timeline;\n const timeline = Array.isArray(rawTimeline)\n ? (rawTimeline.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[])\n : [];\n\n const currentStepIdValue =\n typeof value.currentStepId === \"string\" && value.currentStepId in steps\n ? (value.currentStepId as TStepId)\n : typeof value.current === \"string\" && value.current in steps\n ? (value.current as TStepId)\n : null;\n\n if (timeline.length === 0) {\n if (!currentStepIdValue) {\n return null;\n }\n timeline.push(currentStepIdValue);\n needsRewrite = true;\n }\n\n let index = timeline.length - 1;\n const rawIndex = rawHistory?.index ?? value.index;\n if (typeof rawIndex === \"number\" && Number.isFinite(rawIndex)) {\n index = Math.max(0, Math.min(Math.trunc(rawIndex), timeline.length - 1));\n if (index !== rawIndex) {\n needsRewrite = true;\n }\n } else if (currentStepIdValue) {\n const inferredIndex = timeline.lastIndexOf(currentStepIdValue);\n if (inferredIndex >= 0) {\n index = inferredIndex;\n needsRewrite = true;\n }\n }\n\n const status = isStatusValue(value.status) ? value.status : JOURNEY_STATUS.RUNNING;\n if (!isStatusValue(value.status)) {\n needsRewrite = true;\n }\n\n const stepIds = Object.keys(steps) as TStepId[];\n const visitedSource = value.visited;\n const visitedFromRecord = isRecord(visitedSource)\n ? (Object.fromEntries(\n stepIds.map((stepId) => [stepId, visitedSource[stepId] === true])\n ) as Record<TStepId, boolean>)\n : null;\n const visitedFromArray = Array.isArray(visitedSource)\n ? buildVisitedFromTimeline(\n visitedSource.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[],\n stepIds\n )\n : null;\n\n let visited = buildVisitedFromTimeline(timeline, stepIds);\n if (visitedFromRecord) {\n const visitedRecord = visitedSource as Record<string, unknown>;\n visited = visitedFromRecord;\n const hasMissingOrInvalidStep = stepIds.some(\n (stepId) => typeof visitedRecord[stepId] !== \"boolean\"\n );\n if (hasMissingOrInvalidStep) {\n needsRewrite = true;\n }\n } else if (visitedFromArray) {\n visited = visitedFromArray;\n needsRewrite = true;\n } else {\n needsRewrite = true;\n }\n\n const rawStepMeta = isRecord(value.stepMeta) ? value.stepMeta : null;\n if (!rawStepMeta) {\n needsRewrite = true;\n }\n\n const stepMeta = Object.fromEntries(\n Object.keys(steps).map((stepId) => {\n const typedStepId = stepId as TStepId;\n const rawValue = rawStepMeta ? rawStepMeta[stepId] : undefined;\n if (rawValue === undefined) {\n return [typedStepId, fallbackStepMeta[typedStepId]];\n }\n return [typedStepId, rawValue as TStepMeta];\n })\n ) as Record<TStepId, TStepMeta>;\n\n return {\n snapshot: {\n currentStepId: timeline[index] as TStepId,\n history: {\n timeline,\n index\n },\n context: (\"context\" in value ? value.context : fallbackContext) as TContext,\n status,\n visited,\n stepMeta\n },\n needsRewrite\n };\n};\n\n/**\n * Creates a persistence controller for snapshots, including hydration,\n * serialization, and storage error handling.\n */\nexport const createPersistenceController = <TContext, TStepId extends string, TStepMeta>(args: {\n initial: TStepId;\n context: TContext;\n stepMeta: Record<TStepId, TStepMeta>;\n steps: Record<TStepId, unknown>;\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>;\n}) => {\n const { initial, context, stepMeta, steps, options } = args;\n const persistence = resolvePersistence(options?.persistence);\n\n const reportPersistenceError = (error: unknown) => {\n persistence?.onError?.(error);\n };\n\n const persistSnapshot = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n if (!persistence) {\n return;\n }\n\n try {\n const persistedState: JourneyPersistedState<TContext, TStepId, TStepMeta> = {\n version: persistence.version,\n snapshot: {\n currentStepId: snapshot.currentStepId,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: snapshot.context,\n status: snapshot.status,\n visited: { ...snapshot.visited },\n stepMeta: { ...snapshot.stepMeta }\n }\n };\n persistence.storage.setItem(persistence.key, persistence.serialize(persistedState));\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const removePersistedSnapshot = () => {\n if (!persistence) {\n return;\n }\n\n try {\n persistence.storage.removeItem(persistence.key);\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const hydrateSnapshot = (): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n const initialSnapshot = buildSnapshot(\n [initial],\n 0,\n context,\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(steps),\n stepMeta\n );\n if (!persistence) {\n return initialSnapshot;\n }\n\n try {\n const rawPersisted = persistence.storage.getItem(persistence.key);\n if (!rawPersisted) {\n return initialSnapshot;\n }\n\n const parsed = persistence.deserialize(rawPersisted);\n if (!isRecord(parsed)) {\n return initialSnapshot;\n }\n\n const persistedVersion = parsed.version;\n if (typeof persistedVersion !== \"number\") {\n return initialSnapshot;\n }\n\n let persistedSnapshot: JourneyPersistedSnapshot<TContext, TStepId, TStepMeta> | null = null;\n let shouldRewritePersisted = false;\n\n if (persistedVersion === persistence.version) {\n const coerced = coercePersistedSnapshot(parsed.snapshot, steps, context, stepMeta);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = Boolean(coerced?.needsRewrite);\n } else if (persistence.migrate) {\n const migrated = persistence.migrate(parsed.snapshot, persistedVersion);\n const coerced = coercePersistedSnapshot(migrated, steps, context, stepMeta);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = persistedSnapshot !== null;\n }\n\n if (!persistedSnapshot) {\n return initialSnapshot;\n }\n\n const hydratedSnapshot = buildSnapshot(\n persistedSnapshot.history.timeline,\n persistedSnapshot.history.index,\n persistedSnapshot.context,\n persistedSnapshot.status,\n buildInitialAsyncState(steps),\n persistedSnapshot.stepMeta,\n persistedSnapshot.visited\n );\n\n if (shouldRewritePersisted) {\n persistSnapshot(hydratedSnapshot);\n }\n\n return hydratedSnapshot;\n } catch (error) {\n reportPersistenceError(error);\n return initialSnapshot;\n }\n };\n\n return {\n clearOnReset: persistence?.clearOnReset ?? true,\n hydrateSnapshot,\n persistSnapshot,\n removePersistedSnapshot\n };\n};\n", "import { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_STATUS } from \"./types\";\nimport type {\n JourneyAsyncState,\n JourneyAsyncPhase,\n JourneyDefaultEventType,\n JourneyDefinition,\n JourneyEvent,\n JourneyEventPayloadMap,\n JourneyMachine,\n JourneyMachineOptions,\n JourneyObservationEvent,\n JourneySendResult,\n JourneyStepDefinition,\n JourneyTransition,\n JourneyTerminal\n} from \"./types\";\nimport {\n assertStepExists,\n buildIdleStepAsyncState,\n buildInitialAsyncState,\n buildSendResult,\n buildSnapshot,\n isGoToStepByIdEvent,\n isPromiseLike,\n isTerminalTarget,\n normalizeStepCount,\n now,\n selectTransition,\n transitionSnapshot,\n validateJourneyTransitions\n} from \"./machine-helpers\";\nimport { createPersistenceController } from \"./persistence\";\n\n/**\n * Creates a journey machine from a journey definition.\n * Validates steps/transitions, hydrates persisted state (if configured),\n * and returns an API for sending events and reading snapshots.\n */\nexport function createJourneyMachine<\n TContext,\n TStepMeta = unknown,\n TSteps extends Record<string, JourneyStepDefinition<TStepMeta>> = Record<\n string,\n JourneyStepDefinition<TStepMeta>\n >,\n TPayloadMap extends JourneyEventPayloadMap<JourneyDefaultEventType> = Record<never, never>\n>(\n journey: {\n initial: Extract<keyof TSteps, string>;\n context: TContext;\n steps: TSteps;\n transitions: readonly JourneyTransition<\n TContext,\n Extract<keyof TSteps, string>,\n JourneyDefaultEventType,\n TPayloadMap\n >[];\n },\n options?: JourneyMachineOptions<TContext, Extract<keyof TSteps, string>, TStepMeta>\n): JourneyMachine<\n TContext,\n Extract<keyof TSteps, string>,\n JourneyDefaultEventType,\n TPayloadMap,\n TStepMeta\n>;\n// eslint-disable-next-line no-redeclare\nexport function createJourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>\n): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>;\n// eslint-disable-next-line no-redeclare\nexport function createJourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>\n): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta> {\n if (!journey.steps || typeof journey.steps !== \"object\") {\n throw new Error(\"Journey steps must be a record object.\");\n }\n\n if (!Array.isArray(journey.transitions)) {\n throw new Error(\"Journey transitions must be an array.\");\n }\n\n assertStepExists(\n journey.steps,\n journey.initial,\n `Journey initial step \"${journey.initial}\" does not exist in steps registry.`\n );\n\n validateJourneyTransitions(journey.transitions, journey.steps);\n\n const buildStepMeta = (): Record<TStepId, TStepMeta> => {\n const stepMeta = {} as Record<TStepId, TStepMeta>;\n for (const stepId of Object.keys(journey.steps) as TStepId[]) {\n stepMeta[stepId] = journey.steps[stepId].meta as TStepMeta;\n }\n return stepMeta;\n };\n\n const { clearOnReset, hydrateSnapshot, persistSnapshot, removePersistedSnapshot } =\n createPersistenceController({\n initial: journey.initial,\n context: journey.context,\n stepMeta: buildStepMeta(),\n steps: journey.steps,\n ...(options ? { options } : {})\n });\n\n let snapshot = hydrateSnapshot();\n snapshot = {\n ...snapshot,\n async: buildInitialAsyncState(journey.steps)\n };\n\n const listeners = new Set<() => void>();\n const eventListeners = new Set<\n (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => void\n >();\n let actionQueue: Promise<void> = Promise.resolve();\n\n const notify = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n const emit = (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => {\n for (const listener of eventListeners) {\n listener(event);\n }\n };\n\n const queue = <T>(runner: () => Promise<T>): Promise<T> => {\n const resultPromise = actionQueue.then(runner, runner);\n actionQueue = resultPromise.then(\n () => undefined,\n () => undefined\n );\n return resultPromise;\n };\n\n const isAsyncLoadingPhase = (phase: JourneyAsyncPhase): boolean =>\n phase === JOURNEY_ASYNC_PHASE.EVALUATING_WHEN || phase === JOURNEY_ASYNC_PHASE.RUNNING_EFFECT;\n\n const updateStepAsync = (\n stepId: TStepId,\n updater: (\n current: JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => {\n const current = snapshot.async.byStep[stepId] ?? buildIdleStepAsyncState();\n const next = updater(current);\n if (\n current.phase === next.phase &&\n current.eventType === next.eventType &&\n current.transitionId === next.transitionId &&\n current.error === next.error\n ) {\n return;\n }\n\n const nextByStep = {\n ...snapshot.async.byStep,\n [stepId]: next\n };\n const isLoading = Object.values(nextByStep).some((state) => isAsyncLoadingPhase(state.phase));\n snapshot = {\n ...snapshot,\n async: {\n isLoading,\n byStep: nextByStep\n }\n };\n notify();\n };\n\n const setStepLoading = (\n stepId: TStepId,\n phase: JourneyAsyncPhase,\n eventType: string,\n transitionId?: string\n ) => {\n updateStepAsync(stepId, () => ({\n phase,\n eventType,\n transitionId: transitionId ?? null,\n error: null\n }));\n };\n\n const setStepIdle = (stepId: TStepId) => {\n updateStepAsync(stepId, () => buildIdleStepAsyncState());\n };\n\n const setStepError = (\n stepId: TStepId,\n eventType: string,\n error: unknown,\n transitionId?: string\n ) => {\n updateStepAsync(stepId, () => ({\n phase: JOURNEY_ASYNC_PHASE.ERROR,\n eventType,\n transitionId: transitionId ?? null,\n error\n }));\n };\n\n const applyPreviousNavigation = (\n requestedSteps?: number,\n transitionId?: string\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const steps = normalizeStepCount(requestedSteps);\n if (snapshot.history.index === 0) {\n return buildSendResult(snapshot, false);\n }\n\n const from = snapshot.currentStepId;\n const nextIndex = Math.max(0, snapshot.history.index - steps);\n const appliedSteps = snapshot.history.index - nextIndex;\n if (appliedSteps <= 0) {\n return buildSendResult(snapshot, false);\n }\n\n emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n snapshot = buildSnapshot(\n snapshot.history.timeline,\n nextIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n snapshot.visited\n );\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"navigation.previous\",\n from,\n to: snapshot.currentStepId,\n requestedSteps: steps,\n appliedSteps,\n timestamp: now()\n });\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n return buildSendResult(snapshot, true, transitionId);\n };\n\n const applyLastVisitedNavigation = (\n transitionId?: string\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const targetIndex = snapshot.history.timeline.length - 1;\n if (snapshot.history.index >= targetIndex) {\n return buildSendResult(snapshot, false);\n }\n\n const from = snapshot.currentStepId;\n emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n snapshot = buildSnapshot(\n snapshot.history.timeline,\n targetIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n snapshot.visited\n );\n persistSnapshot(snapshot);\n notify();\n\n emit({ type: \"navigation.lastVisited\", from, to: snapshot.currentStepId, timestamp: now() });\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n return buildSendResult(snapshot, true, transitionId);\n };\n\n const machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta> = {\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n subscribeEvent: (listener) => {\n eventListeners.add(listener);\n return () => {\n eventListeners.delete(listener);\n };\n },\n resetMachine: () => {\n snapshot = buildSnapshot(\n [journey.initial],\n 0,\n journey.context,\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(journey.steps),\n buildStepMeta()\n );\n if (clearOnReset) {\n removePersistedSnapshot();\n } else {\n persistSnapshot(snapshot);\n }\n notify();\n return snapshot;\n },\n updateContext: (updater) => {\n snapshot = {\n ...snapshot,\n context: updater(snapshot.context)\n };\n persistSnapshot(snapshot);\n notify();\n return snapshot;\n },\n updateStepMetadata: (stepId, updater) => {\n if (!(stepId in journey.steps)) {\n return snapshot;\n }\n\n const previousMeta = snapshot.stepMeta[stepId];\n const nextMeta = updater(previousMeta);\n if (Object.is(previousMeta, nextMeta)) {\n return snapshot;\n }\n\n snapshot = {\n ...snapshot,\n stepMeta: {\n ...snapshot.stepMeta,\n [stepId]: nextMeta\n }\n };\n persistSnapshot(snapshot);\n notify();\n emit({\n type: \"metadata.updated\",\n stepId,\n previous: previousMeta,\n next: nextMeta,\n timestamp: now()\n });\n return snapshot;\n },\n clearStepError: (stepId) => {\n const resolvedStep = stepId ?? snapshot.currentStepId;\n if (!(resolvedStep in journey.steps)) {\n return snapshot;\n }\n\n setStepIdle(resolvedStep);\n return snapshot;\n },\n goToPreviousStep: (steps) =>\n queue(async () => {\n const result = applyPreviousNavigation(steps, \"goToPreviousStep\");\n return result;\n }),\n goToLastVisitedStep: () =>\n queue(async () => {\n const result = applyLastVisitedNavigation(\"goToLastVisitedStep\");\n return result;\n }),\n goToNextStep: () => machine.send({ type: \"goToNextStep\" }),\n terminateJourney: (payload) =>\n payload === undefined\n ? machine.send({ type: \"terminateJourney\" })\n : machine.send({ type: \"terminateJourney\", payload }),\n completeJourney: (payload) =>\n payload === undefined\n ? machine.send({ type: \"completeJourney\" })\n : machine.send({ type: \"completeJourney\", payload }),\n send: (event) =>\n queue(async () => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const fromStep = snapshot.currentStepId;\n\n if (isGoToStepByIdEvent(event)) {\n assertStepExists(\n journey.steps,\n event.stepId,\n `Cannot goToStepById unknown step \"${event.stepId}\".`\n );\n emit({ type: \"transition.start\", from: fromStep, event, timestamp: now() });\n setStepIdle(fromStep);\n\n const beforeCurrent = snapshot.currentStepId;\n const nextSnapshot = transitionSnapshot(snapshot, event.stepId, snapshot.context);\n if (nextSnapshot.currentStepId !== beforeCurrent) {\n emit({ type: \"step.exit\", stepId: beforeCurrent, timestamp: now() });\n }\n\n snapshot = nextSnapshot;\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: snapshot.currentStepId,\n eventType: JOURNEY_EVENT.GO_TO_STEP_BY_ID,\n transitionId: JOURNEY_EVENT.GO_TO_STEP_BY_ID,\n timestamp: now()\n });\n\n if (nextSnapshot.currentStepId !== beforeCurrent) {\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n }\n\n return buildSendResult(snapshot, true, JOURNEY_EVENT.GO_TO_STEP_BY_ID);\n }\n\n const transitionEvent = event as JourneyEvent<TStepId, TEventType, TPayloadMap>;\n emit({ type: \"transition.start\", from: fromStep, event, timestamp: now() });\n\n let transition;\n try {\n transition = await selectTransition(journey.transitions, snapshot, transitionEvent, {\n onAsyncGuardStart: (currentTransition) => {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.EVALUATING_WHEN,\n transitionEvent.type,\n currentTransition.id\n );\n },\n onAsyncGuardSuccess: () => {\n setStepIdle(fromStep);\n },\n onAsyncGuardError: (currentTransition, error) => {\n setStepError(fromStep, transitionEvent.type, error, currentTransition.id);\n }\n });\n } catch (error) {\n setStepError(fromStep, transitionEvent.type, error);\n emit({\n type: \"transition.error\",\n from: fromStep,\n eventType: transitionEvent.type,\n transitionId: null,\n error,\n timestamp: now()\n });\n throw error;\n }\n\n if (!transition) {\n if (event.type === \"goToPreviousStep\" || event.type === \"back\") {\n const fallbackResult = applyPreviousNavigation(1, event.type);\n if (fallbackResult.transitioned) {\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: fallbackResult.snapshot.currentStepId,\n eventType: event.type,\n transitionId: null,\n timestamp: now()\n });\n }\n return fallbackResult;\n }\n\n return buildSendResult(snapshot, false);\n }\n\n let nextContext = snapshot.context;\n if (transition.effect) {\n const effectResultPromise = transition.effect({\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event: transitionEvent\n });\n if (isPromiseLike(effectResultPromise)) {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.RUNNING_EFFECT,\n transitionEvent.type,\n transition.id\n );\n }\n\n let effectResult: TContext | void;\n try {\n effectResult = await effectResultPromise;\n } catch (error) {\n setStepError(fromStep, transitionEvent.type, error, transition.id);\n emit({\n type: \"transition.error\",\n from: fromStep,\n eventType: transitionEvent.type,\n transitionId: transition.id ?? null,\n error,\n timestamp: now()\n });\n throw error;\n }\n\n if (effectResult !== undefined) {\n nextContext = effectResult;\n }\n }\n\n setStepIdle(fromStep);\n\n const target: TStepId | JourneyTerminal =\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : (transition.to as TStepId | JourneyTerminal);\n\n if (isTerminalTarget(target)) {\n const normalizedTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n snapshot = {\n ...snapshot,\n history: {\n timeline: normalizedTimeline,\n index: normalizedTimeline.length - 1\n },\n context: nextContext,\n status: target === \"COMPLETE\" ? JOURNEY_STATUS.COMPLETE : JOURNEY_STATUS.TERMINATED\n };\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: target,\n eventType: transitionEvent.type,\n transitionId: transition.id ?? null,\n timestamp: now()\n });\n emit({\n type: target === \"COMPLETE\" ? \"journey.complete\" : \"journey.close\",\n stepId: snapshot.currentStepId,\n timestamp: now()\n });\n\n return buildSendResult(snapshot, true, transition.id);\n }\n\n const resolvedTarget = target;\n\n assertStepExists(\n journey.steps,\n resolvedTarget,\n `Transition points to unknown step \"${resolvedTarget}\".`\n );\n\n const beforeCurrent = snapshot.currentStepId;\n if (beforeCurrent !== resolvedTarget) {\n emit({ type: \"step.exit\", stepId: beforeCurrent, timestamp: now() });\n }\n snapshot = transitionSnapshot(snapshot, resolvedTarget, nextContext);\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: snapshot.currentStepId,\n eventType: transitionEvent.type,\n transitionId: transition.id ?? null,\n timestamp: now()\n });\n if (beforeCurrent !== snapshot.currentStepId) {\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n }\n\n return buildSendResult(snapshot, true, transition.id);\n })\n };\n\n return machine;\n}\n", "import { JOURNEY_WILDCARD } from \"./types/journey.types\";\nimport type { JourneyEventPayloadMap } from \"./types/journey.types\";\nimport type {\n EventBuilder,\n JourneyEventTransition,\n JourneyTransition,\n JourneyTransitionArgs,\n JourneyTransitionTarget,\n TransitionBranch,\n TransitionConfig\n} from \"./types/transitions.types\";\n\nconst createEventBuilder = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n from: TStepId | typeof JOURNEY_WILDCARD,\n event: TEventType\n): EventBuilder<TContext, TStepId, TEventType, TPayloadMap> => {\n if (event === \"completeJourney\") {\n return {\n complete: (\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Extract<TEventType, \"completeJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n }\n\n if (event === \"terminateJourney\") {\n return {\n terminate: (\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Extract<TEventType, \"terminateJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n }\n\n return {\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Exclude<TEventType, \"completeJourney\" | \"terminateJourney\">,\n to\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>,\n choose: (\n ...branches: Array<TransitionBranch<TContext, TStepId, TEventType, TPayloadMap>>\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[] =>\n branches.map(\n (branch) =>\n ({\n ...branch,\n from,\n event: event as Exclude<TEventType, \"completeJourney\" | \"terminateJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n )\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n};\n\nconst buildTerminalTransition = <\n TContext,\n TStepId extends string,\n TEventType extends \"completeJourney\" | \"terminateJourney\"\n>(\n from: TStepId | typeof JOURNEY_WILDCARD,\n event: TEventType,\n config: TransitionConfig<TContext, TStepId, TEventType, Record<never, never>> = {}\n): JourneyEventTransition<TContext, TStepId, TEventType, Record<never, never>> =>\n ({\n ...config,\n from,\n event\n }) as JourneyEventTransition<TContext, TStepId, TEventType, Record<never, never>>;\n\n/**\n * Fluent helpers for building journey transitions with type-safe branches.\n */\nexport const tx = {\n from: <TStepId extends string, TContext = unknown>(from: TStepId) => ({\n on: <TEventType extends string>(event: TEventType) =>\n createEventBuilder<TContext, TStepId, TEventType, Record<never, never>>(from, event),\n toComplete: (\n config: TransitionConfig<TContext, TStepId, \"completeJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(from, \"completeJourney\", config),\n toTerminate: (\n config: TransitionConfig<TContext, TStepId, \"terminateJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(from, \"terminateJourney\", config)\n }),\n any: <TContext = unknown, TStepId extends string = string>() => ({\n on: <TEventType extends string>(event: TEventType) =>\n createEventBuilder<TContext, TStepId, TEventType, Record<never, never>>(\n JOURNEY_WILDCARD,\n event\n ),\n toComplete: (\n config: TransitionConfig<TContext, TStepId, \"completeJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(JOURNEY_WILDCARD, \"completeJourney\", config),\n toTerminate: (\n config: TransitionConfig<TContext, TStepId, \"terminateJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(JOURNEY_WILDCARD, \"terminateJourney\", config)\n }),\n when: <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n >(\n predicate: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => boolean | Promise<boolean>\n ) => ({\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): TransitionBranch<TContext, TStepId, TEventType, TPayloadMap> => ({\n ...config,\n to,\n when: predicate\n })\n }),\n otherwise: <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n >() => ({\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): TransitionBranch<TContext, TStepId, TEventType, TPayloadMap> => ({\n ...config,\n to\n })\n })\n};\n\n/**\n * Flattens transition items and transition arrays into a single transition list.\n */\nexport const createTransitions = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n ...items: Array<\n | JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n | readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[]\n >\n): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[] =>\n items.flatMap((item) => (Array.isArray(item) ? [...item] : [item]));\n"],
5
- "mappings": "AAOO,IAAMA,EAAiB,CAC5B,QAAS,UACT,SAAU,WACV,WAAY,YACd,EAMaC,EAAmB,IAGnBC,EAAgB,CAC3B,iBAAkB,cACpB,EAgBaC,EAAsB,CACjC,KAAM,OACN,gBAAiB,kBACjB,eAAgB,iBAChB,MAAO,OACT,ECxBO,IAAMC,EAAmB,CAC9BC,EACAC,EACAC,IACG,CACH,GAAI,EAAED,KAAUD,GACd,MAAM,IAAI,MAAME,CAAO,CAE3B,EAEaC,EAAsBH,GAC7B,OAAOA,GAAU,UAAY,CAAC,OAAO,SAASA,CAAK,EAC9C,EAEF,KAAK,IAAI,EAAG,KAAK,MAAMA,CAAK,CAAC,EAGzBI,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Exists", "steps", "stepId", "message", "normalizeStepCount", "now", "unique", "items", "normalizeVisited", "visited", "stepIds", "buildVisitedFromTimeline", "timeline", "resolvedStepIds", "appendVisited", "current", "isPromiseLike", "value", "buildIdleStepAsyncState", "JOURNEY_ASYNC_PHASE", "buildInitialAsyncState", "isGoToStepByIdEvent", "event", "JOURNEY_EVENT", "isTerminalTarget", "target", "validateJourneyTransitions", "transitions", "stepRegistry", "index", "transition", "JOURNEY_WILDCARD", "buildSendResult", "snapshot", "transitioned", "transitionId", "buildSnapshot", "context", "status", "asyncState", "stepMeta", "safeIndex", "currentStepId", "selectTransition", "hooks", "fromMatches", "eventMatches", "guardResult", "asyncGuard", "allowed", "error", "transitionSnapshot", "nextCurrent", "nextContext", "baseTimeline", "nextTimeline", "nextIndex", "isRecord", "value", "isStatusValue", "JOURNEY_STATUS", "resolveDefaultStorage", "localStorageCandidate", "resolvePersistence", "options", "storage", "coercePersistedSnapshot", "steps", "fallbackContext", "fallbackStepMeta", "needsRewrite", "rawHistory", "rawTimeline", "timeline", "step", "currentStepIdValue", "index", "rawIndex", "inferredIndex", "status", "stepIds", "visitedSource", "visitedFromRecord", "stepId", "visitedFromArray", "buildVisitedFromTimeline", "visited", "visitedRecord", "rawStepMeta", "stepMeta", "typedStepId", "rawValue", "createPersistenceController", "args", "initial", "context", "persistence", "reportPersistenceError", "error", "persistSnapshot", "snapshot", "persistedState", "removePersistedSnapshot", "hydrateSnapshot", "initialSnapshot", "buildSnapshot", "buildInitialAsyncState", "rawPersisted", "parsed", "persistedVersion", "persistedSnapshot", "shouldRewritePersisted", "coerced", "migrated", "hydratedSnapshot", "createJourneyMachine", "journey", "options", "assertStepExists", "validateJourneyTransitions", "buildStepMeta", "stepMeta", "stepId", "clearOnReset", "hydrateSnapshot", "persistSnapshot", "removePersistedSnapshot", "createPersistenceController", "snapshot", "buildInitialAsyncState", "listeners", "eventListeners", "actionQueue", "notify", "listener", "emit", "event", "queue", "runner", "resultPromise", "isAsyncLoadingPhase", "phase", "JOURNEY_ASYNC_PHASE", "updateStepAsync", "updater", "current", "buildIdleStepAsyncState", "next", "nextByStep", "isLoading", "state", "setStepLoading", "eventType", "transitionId", "setStepIdle", "setStepError", "error", "applyPreviousNavigation", "requestedSteps", "JOURNEY_STATUS", "buildSendResult", "steps", "normalizeStepCount", "from", "nextIndex", "appliedSteps", "now", "buildSnapshot", "applyLastVisitedNavigation", "targetIndex", "machine", "previousMeta", "nextMeta", "resolvedStep", "payload", "fromStep", "isGoToStepByIdEvent", "beforeCurrent", "nextSnapshot", "transitionSnapshot", "JOURNEY_EVENT", "transitionEvent", "transition", "selectTransition", "currentTransition", "fallbackResult", "nextContext", "effectResultPromise", "isPromiseLike", "effectResult", "target", "isTerminalTarget", "normalizedTimeline", "resolvedTarget", "createEventBuilder", "from", "event", "config", "to", "branches", "branch", "buildTerminalTransition", "tx", "JOURNEY_WILDCARD", "predicate", "createTransitions", "items", "item"]
4
+ "sourcesContent": ["import type { JourneyPersistenceOptions } from \"./persistence.types\";\nimport type { JourneyTransition } from \"./transitions.types\";\n\n/** Terminal outcomes reached when a journey completes or is explicitly terminated. */\nexport type JourneyTerminal = \"COMPLETE\" | \"TERMINATED\";\n\n/** Runtime machine status constants. */\nexport const JOURNEY_STATUS = {\n RUNNING: \"running\",\n COMPLETE: \"complete\",\n TERMINATED: \"terminated\"\n} as const;\n\n/** Union of possible runtime machine statuses. */\nexport type JourneyStatus = (typeof JOURNEY_STATUS)[keyof typeof JOURNEY_STATUS];\n\n/** Wildcard step identifier used by transitions that match from any step. */\nexport const JOURNEY_WILDCARD = \"*\" as const;\n\n/** Built-in event constants that are part of core machine behavior. */\nexport const JOURNEY_EVENT = {\n GO_TO_STEP_BY_ID: \"goToStepById\"\n} as const;\n\n/** Machine event types that are always recognized by core. */\nexport type JourneyBuiltInEvent = (typeof JOURNEY_EVENT)[keyof typeof JOURNEY_EVENT];\n/** Event literal type for the built-in go-to-step command. */\nexport type JourneyGoToStepByIdEventType = typeof JOURNEY_EVENT.GO_TO_STEP_BY_ID;\n/** Wildcard origin marker for transitions. */\nexport type JourneyBuiltInFrom = typeof JOURNEY_WILDCARD;\n/** Default transition event names supported by machine convenience APIs. */\nexport type JourneyDefaultEventType =\n | \"goToNextStep\"\n | \"goToPreviousStep\"\n | \"terminateJourney\"\n | \"completeJourney\";\n\n/** Async lifecycle phases tracked per step while guards/effects run. */\nexport const JOURNEY_ASYNC_PHASE = {\n IDLE: \"idle\",\n EVALUATING_WHEN: \"evaluating-when\",\n RUNNING_EFFECT: \"running-effect\",\n ERROR: \"error\"\n} as const;\n\n/** Union of supported async lifecycle phases. */\nexport type JourneyAsyncPhase = (typeof JOURNEY_ASYNC_PHASE)[keyof typeof JOURNEY_ASYNC_PHASE];\n\n/** Async execution state for a single step. */\nexport type JourneyStepAsyncState = {\n phase: JourneyAsyncPhase;\n eventType: string | null;\n transitionId: string | null;\n error: unknown | null;\n};\n\n/** Aggregated async state for the machine, keyed by step id. */\nexport type JourneyAsyncState<TStepId extends string> = {\n isLoading: boolean;\n byStep: Record<TStepId, JourneyStepAsyncState>;\n};\n\n/** Minimal event shape used across runtime boundaries. */\nexport type JourneyBaseEvent = {\n type: string;\n payload?: unknown;\n};\n\n/** Optional event payload map by event type. */\nexport type JourneyEventPayloadMap<TEventType extends string> = Partial<\n Record<TEventType | JourneyBuiltInEvent, unknown>\n>;\n\n/** Resolves payload type for a specific event type from the provided payload map. */\nexport type JourneyPayloadFor<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TEvent extends TEventType | JourneyBuiltInEvent\n> = TEvent extends keyof TPayloadMap ? TPayloadMap[TEvent] : unknown;\n\n/** Event-type union accepted by machine `.send()`, including built-in convenience events. */\nexport type JourneyMachineEventType<TEventType extends string> =\n | TEventType\n | JourneyDefaultEventType;\n\n/** Payload map available to machine `.send()`, including built-in convenience events. */\nexport type JourneyMachinePayloadMap<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n> = TPayloadMap & JourneyEventPayloadMap<JourneyDefaultEventType>;\n\ntype JourneyPayloadForDefaultEvent<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TDefaultEvent extends JourneyDefaultEventType\n> = JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n TDefaultEvent\n>;\n\n/** Built-in direct-navigation event that targets a specific step id. */\nexport type JourneyGoToEvent<TStepId extends string, TPayload = unknown> = {\n type: JourneyGoToStepByIdEventType;\n stepId: TStepId;\n payload?: TPayload;\n};\n\n/** Event union available to transitions and guards for the declared event type set. */\nexport type JourneyEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> =\n | JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<TEventType, TPayloadMap, JourneyGoToStepByIdEventType>\n >\n | {\n [TType in TEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<TEventType, TPayloadMap, TType>;\n };\n }[TEventType];\n\ntype JourneyDefaultMachineEvent<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n> = {\n [TType in JourneyDefaultEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n TType\n >;\n };\n}[JourneyDefaultEventType];\n\ntype JourneyCustomMachineEvent<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n> = {\n [TType in TEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<TEventType, TPayloadMap, TType>;\n };\n}[TEventType];\n\n/** Event union accepted by `JourneyMachine.send`. */\nexport type JourneySendEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> =\n | JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n JourneyGoToStepByIdEventType\n >\n >\n | JourneyDefaultMachineEvent<TEventType, TPayloadMap>\n | JourneyCustomMachineEvent<TEventType, TPayloadMap>;\n\n/**\n * Step definition with optional metadata and optional typed extension fields.\n * Use `TStepExtra` to explicitly model additional per-step properties.\n */\nexport type JourneyStepDefinition<\n TStepMeta = unknown,\n TStepExtra extends object = Record<never, never>\n> = {\n meta?: TStepMeta;\n} & TStepExtra;\n\n/** Serializable runtime snapshot of the journey state. */\nexport type JourneySnapshot<TContext, TStepId extends string, TStepMeta = unknown> = {\n currentStepId: TStepId;\n history: {\n timeline: readonly TStepId[];\n index: number;\n };\n context: TContext;\n visited: Record<TStepId, boolean>;\n stepMeta: Record<TStepId, TStepMeta>;\n status: JourneyStatus;\n async: JourneyAsyncState<TStepId>;\n};\n\n/** Selector function that derives a value from a machine snapshot. */\nexport type JourneySelector<\n TContext,\n TStepId extends string,\n TStepMeta = unknown,\n TSelected = unknown\n> = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => TSelected;\n\n/** Equality function used to compare selected values between snapshot updates. */\nexport type JourneyEqualityFn<TValue> = (previous: TValue, next: TValue) => boolean;\n\n/** Full machine definition used to create a journey machine instance. */\nexport type JourneyDefinition<\n TContext,\n TStepId extends string = string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown,\n TStepExtra extends object = Record<never, never>\n> = {\n initial: TStepId;\n context: TContext;\n steps: Record<TStepId, JourneyStepDefinition<TStepMeta, TStepExtra>>;\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[];\n};\n\n/** Optional machine features (for example, persistence configuration). */\nexport type JourneyMachineOptions<TContext, TStepId extends string, TStepMeta = unknown> = {\n persistence?: JourneyPersistenceOptions<TContext, TStepId, TStepMeta>;\n completeOnNoNextStep?: boolean;\n};\n\n/** Result returned from send/navigation APIs. */\nexport type JourneySendResult<TContext, TStepId extends string, TStepMeta = unknown> = {\n transitioned: boolean;\n transitionId?: string;\n error?: unknown;\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;\n};\n\n/** Observation events emitted by the machine lifecycle/event stream. */\nexport type JourneyObservationEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n> =\n | {\n type: \"journey.start\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"transition.start\";\n from: TStepId;\n event: JourneySendEvent<TStepId, TEventType, TPayloadMap>;\n timestamp: number;\n }\n | {\n type: \"transition.success\";\n from: TStepId;\n to: TStepId | JourneyTerminal;\n eventType: string;\n transitionId: string | null;\n timestamp: number;\n }\n | {\n type: \"transition.error\";\n from: TStepId;\n eventType: string;\n transitionId: string | null;\n error: unknown;\n timestamp: number;\n }\n | {\n type: \"step.exit\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"step.enter\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"journey.complete\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"journey.close\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"navigation.previous\";\n from: TStepId;\n to: TStepId;\n requestedSteps: number;\n appliedSteps: number;\n timestamp: number;\n }\n | {\n type: \"navigation.lastVisited\";\n from: TStepId;\n to: TStepId;\n timestamp: number;\n }\n | {\n type: \"metadata.updated\";\n stepId: TStepId;\n previous: TStepMeta;\n next: TStepMeta;\n timestamp: number;\n };\n\n/** Runtime machine API for reading snapshots, sending events, and controlling flow. */\nexport type JourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n> = {\n getSnapshot: () => JourneySnapshot<TContext, TStepId, TStepMeta>;\n send: (\n event: JourneySendEvent<TStepId, TEventType, TPayloadMap>\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToNextStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n terminateJourney: (\n payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, \"terminateJourney\">\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n completeJourney: (\n payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, \"completeJourney\">\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToPreviousStep: (steps?: number) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToLastVisitedStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n updateContext: (\n updater: (context: TContext) => TContext\n ) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n updateStepMetadata: (\n stepId: TStepId,\n updater: (metadata: TStepMeta) => TStepMeta\n ) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n clearStepError: (stepId?: TStepId) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n resetMachine: () => JourneySnapshot<TContext, TStepId, TStepMeta>;\n dispose: () => void;\n subscribe: (listener: () => void) => () => void;\n subscribeSelector: <TSelected>(\n selector: JourneySelector<TContext, TStepId, TStepMeta, TSelected>,\n listener: (next: TSelected, previous: TSelected) => void,\n equalityFn?: JourneyEqualityFn<TSelected>\n ) => () => void;\n subscribeEvent: (\n listener: (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => void\n ) => () => void;\n subscribeStart: (\n listener: (\n event: Extract<\n JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>,\n { type: \"journey.start\" }\n >\n ) => void\n ) => () => void;\n subscribeComplete: (\n listener: (\n event: Extract<\n JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>,\n { type: \"journey.complete\" }\n >\n ) => void\n ) => () => void;\n subscribeTerminate: (\n listener: (\n event: Extract<\n JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>,\n { type: \"journey.close\" }\n >\n ) => void\n ) => () => void;\n};\n", "import { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_WILDCARD } from \"./types\";\nimport type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyEventPayloadMap,\n JourneyGoToEvent,\n JourneyGoToStepByIdEventType,\n JourneyMachineEventType,\n JourneyMachinePayloadMap,\n JourneyPayloadFor,\n JourneySendEvent,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransitionArgs,\n JourneyTransition\n} from \"./types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nexport const normalizeStepCount = (steps?: number): number => {\n if (typeof steps !== \"number\" || !Number.isFinite(steps)) {\n return 1;\n }\n return Math.max(1, Math.trunc(steps));\n};\n\nexport const now = (): number => Date.now();\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nconst normalizeVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n stepIds: readonly TStepId[]\n): Record<TStepId, boolean> =>\n Object.fromEntries(stepIds.map((stepId) => [stepId, visited[stepId] === true])) as Record<\n TStepId,\n boolean\n >;\n\nexport const buildVisitedFromTimeline = <TStepId extends string>(\n timeline: readonly TStepId[],\n stepIds?: readonly TStepId[]\n): Record<TStepId, boolean> => {\n const resolvedStepIds = stepIds ?? unique(timeline);\n const visited = Object.fromEntries(resolvedStepIds.map((stepId) => [stepId, false])) as Record<\n TStepId,\n boolean\n >;\n\n for (const stepId of timeline) {\n visited[stepId] = true;\n }\n\n return visited;\n};\n\nexport const appendVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n current: TStepId\n): Record<TStepId, boolean> => ({\n ...visited,\n [current]: true\n});\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: JOURNEY_ASYNC_PHASE.IDLE,\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToStepByIdEvent = <\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n event: JourneySendEvent<TStepId, TEventType, TPayloadMap>\n): event is JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<\n JourneyMachineEventType<TEventType>,\n JourneyMachinePayloadMap<TEventType, TPayloadMap>,\n JourneyGoToStepByIdEventType\n >\n> => event.type === JOURNEY_EVENT.GO_TO_STEP_BY_ID && \"stepId\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal\n): target is JourneyTerminal => target === \"COMPLETE\" || target === \"TERMINATED\";\n\nexport const validateJourneyTransitions = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[],\n steps: Record<TStepId, unknown>\n) => {\n const stepRegistry = steps as Record<string, unknown>;\n\n for (const [index, transition] of transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (transition.from !== JOURNEY_WILDCARD && !(transition.from in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n if (transition.event === \"completeJourney\" || transition.event === \"terminateJourney\") {\n if (\"to\" in transition && transition.to !== undefined) {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" cannot define \"to\".`\n );\n }\n continue;\n }\n\n if (typeof transition.to !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" must define string \"to\".`\n );\n }\n\n if (!isTerminalTarget(transition.to) && !(transition.to in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n};\n\nexport const buildSendResult = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n transitioned: boolean,\n options: {\n transitionId?: string;\n error?: unknown;\n } = {}\n): JourneySendResult<TContext, TStepId, TStepMeta> => ({\n transitioned,\n ...(options.transitionId !== undefined ? { transitionId: options.transitionId } : {}),\n ...(\"error\" in options ? { error: options.error } : {}),\n snapshot\n});\n\nexport const buildSnapshot = <TContext, TStepId extends string, TStepMeta>(\n timeline: readonly TStepId[],\n index: number,\n context: TContext,\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n stepMeta: Record<TStepId, TStepMeta>,\n visited?: Record<TStepId, boolean>\n): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n if (timeline.length === 0) {\n throw new Error(\"Journey timeline cannot be empty.\");\n }\n const safeIndex = Math.max(0, Math.min(Math.trunc(index), timeline.length - 1));\n const currentStepId = timeline[safeIndex] as TStepId;\n const stepIds = Object.keys(stepMeta) as TStepId[];\n return {\n status,\n currentStepId,\n history: {\n timeline: [...timeline],\n index: safeIndex\n },\n context,\n visited: visited\n ? normalizeVisited(visited, stepIds)\n : buildVisitedFromTimeline(timeline, stepIds),\n stepMeta: { ...stepMeta },\n async: asyncState\n };\n};\n\nexport const selectTransition = async <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TStepMeta\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[],\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>,\n hooks?: {\n onAsyncGuardStart?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardSuccess?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardError?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>,\n error: unknown\n ) => void;\n }\n): Promise<JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> | null> => {\n for (const transition of transitions) {\n const fromMatches =\n transition.from === JOURNEY_WILDCARD || transition.from === snapshot.currentStepId;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n const guardResult = (\n transition.when as (\n args: JourneyTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => boolean | Promise<boolean>\n )({\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event\n });\n const asyncGuard = isPromiseLike(guardResult);\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n }\n\n let allowed: boolean;\n try {\n allowed = await guardResult;\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n const baseTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n let nextTimeline = baseTimeline;\n if (nextCurrent !== snapshot.currentStepId) {\n nextTimeline = [...baseTimeline, nextCurrent];\n }\n\n const nextIndex = nextTimeline.length - 1;\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(\n nextTimeline,\n nextIndex,\n nextContext,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n visited\n );\n};\n", "import { JOURNEY_STATUS } from \"./types/journey.types\";\nimport type {\n JourneyPersistedSnapshot,\n JourneyPersistedState,\n JourneyStorage,\n ResolvedPersistence\n} from \"./types/persistence.types\";\nimport type { JourneyMachineOptions, JourneySnapshot, JourneyStatus } from \"./types/journey.types\";\nimport { buildInitialAsyncState, buildSnapshot, buildVisitedFromTimeline } from \"./machine-helpers\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isStatusValue = (value: unknown): value is JourneyStatus =>\n value === JOURNEY_STATUS.RUNNING ||\n value === JOURNEY_STATUS.COMPLETE ||\n value === JOURNEY_STATUS.TERMINATED;\n\nconst resolveDefaultStorage = (): JourneyStorage | null => {\n const localStorageCandidate = (globalThis as { localStorage?: Partial<JourneyStorage> })\n .localStorage;\n\n if (\n !localStorageCandidate ||\n typeof localStorageCandidate.getItem !== \"function\" ||\n typeof localStorageCandidate.setItem !== \"function\" ||\n typeof localStorageCandidate.removeItem !== \"function\"\n ) {\n return null;\n }\n\n return localStorageCandidate as JourneyStorage;\n};\n\nconst resolvePersistence = <TContext, TStepId extends string, TStepMeta>(\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>[\"persistence\"]\n): ResolvedPersistence<TContext, TStepId, TStepMeta> | null => {\n if (!options) {\n return null;\n }\n\n let storage: JourneyStorage | null | undefined = options.storage;\n if (storage == null) {\n try {\n storage = resolveDefaultStorage();\n } catch (error) {\n options.onError?.(error);\n return null;\n }\n }\n\n if (!storage) {\n return null;\n }\n\n return {\n key: options.key,\n storage,\n version: options.version ?? 1,\n clearOnReset: options.clearOnReset ?? true,\n serialize: options.serialize ?? JSON.stringify,\n deserialize: options.deserialize ?? JSON.parse,\n ...(options.migrate ? { migrate: options.migrate } : {}),\n ...(options.onError ? { onError: options.onError } : {})\n };\n};\n\nconst resolveVisitedFromPersistence = <TStepId extends string>(\n visitedSource: unknown,\n timeline: readonly TStepId[],\n stepIds: readonly TStepId[]\n): {\n visited: Record<TStepId, boolean>;\n needsRewrite: boolean;\n} => {\n const visitedFromTimeline = buildVisitedFromTimeline(timeline, stepIds);\n\n if (isRecord(visitedSource)) {\n let needsRewrite = false;\n const visited = { ...visitedFromTimeline };\n\n for (const stepId of stepIds) {\n const persistedValue = visitedSource[stepId];\n\n if (persistedValue === true) {\n visited[stepId] = true;\n continue;\n }\n\n if (persistedValue === false) {\n if (visitedFromTimeline[stepId]) {\n needsRewrite = true;\n }\n continue;\n }\n\n needsRewrite = true;\n }\n\n return { visited, needsRewrite };\n }\n\n if (Array.isArray(visitedSource)) {\n const visitedFromArray = buildVisitedFromTimeline(\n visitedSource.filter(\n (step): step is TStepId => typeof step === \"string\" && stepIds.includes(step as TStepId)\n ) as TStepId[],\n stepIds\n );\n const visited = Object.fromEntries(\n stepIds.map((stepId) => [stepId, visitedFromTimeline[stepId] || visitedFromArray[stepId]])\n ) as Record<TStepId, boolean>;\n\n return { visited, needsRewrite: true };\n }\n\n return { visited: visitedFromTimeline, needsRewrite: true };\n};\n\nconst coercePersistedSnapshot = <TContext, TStepId extends string, TStepMeta>(\n value: unknown,\n steps: Record<TStepId, unknown>,\n fallbackContext: TContext,\n fallbackStepMeta: Record<TStepId, TStepMeta>\n): {\n snapshot: JourneyPersistedSnapshot<TContext, TStepId, TStepMeta>;\n needsRewrite: boolean;\n} | null => {\n if (!isRecord(value)) {\n return null;\n }\n\n let needsRewrite = false;\n\n const rawHistory = isRecord(value.history) ? value.history : null;\n if (!rawHistory) {\n needsRewrite = true;\n }\n\n const rawTimeline = rawHistory?.timeline ?? value.timeline;\n const timeline = Array.isArray(rawTimeline)\n ? (rawTimeline.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[])\n : [];\n\n const currentStepIdValue =\n typeof value.currentStepId === \"string\" && value.currentStepId in steps\n ? (value.currentStepId as TStepId)\n : typeof value.current === \"string\" && value.current in steps\n ? (value.current as TStepId)\n : null;\n\n if (timeline.length === 0) {\n if (!currentStepIdValue) {\n return null;\n }\n timeline.push(currentStepIdValue);\n needsRewrite = true;\n }\n\n let index = timeline.length - 1;\n const rawIndex = rawHistory?.index ?? value.index;\n if (typeof rawIndex === \"number\" && Number.isFinite(rawIndex)) {\n index = Math.max(0, Math.min(Math.trunc(rawIndex), timeline.length - 1));\n if (index !== rawIndex) {\n needsRewrite = true;\n }\n } else if (currentStepIdValue) {\n const inferredIndex = timeline.lastIndexOf(currentStepIdValue);\n if (inferredIndex >= 0) {\n index = inferredIndex;\n needsRewrite = true;\n }\n }\n\n const status = isStatusValue(value.status) ? value.status : JOURNEY_STATUS.RUNNING;\n if (!isStatusValue(value.status)) {\n needsRewrite = true;\n }\n\n const stepIds = Object.keys(steps) as TStepId[];\n const { visited, needsRewrite: visitedNeedsRewrite } = resolveVisitedFromPersistence(\n value.visited,\n timeline,\n stepIds\n );\n if (visitedNeedsRewrite) {\n needsRewrite = true;\n }\n\n const rawStepMeta = isRecord(value.stepMeta) ? value.stepMeta : null;\n if (!rawStepMeta) {\n needsRewrite = true;\n }\n\n const stepMeta = Object.fromEntries(\n Object.keys(steps).map((stepId) => {\n const typedStepId = stepId as TStepId;\n const rawValue = rawStepMeta ? rawStepMeta[stepId] : undefined;\n if (rawValue === undefined) {\n return [typedStepId, fallbackStepMeta[typedStepId]];\n }\n return [typedStepId, rawValue as TStepMeta];\n })\n ) as Record<TStepId, TStepMeta>;\n\n return {\n snapshot: {\n currentStepId: timeline[index] as TStepId,\n history: {\n timeline,\n index\n },\n context: (\"context\" in value ? value.context : fallbackContext) as TContext,\n status,\n visited,\n stepMeta\n },\n needsRewrite\n };\n};\n\n/**\n * Creates a persistence controller for snapshots, including hydration,\n * serialization, and storage error handling.\n */\nexport const createPersistenceController = <TContext, TStepId extends string, TStepMeta>(args: {\n initial: TStepId;\n context: TContext;\n stepMeta: Record<TStepId, TStepMeta>;\n steps: Record<TStepId, unknown>;\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>;\n}) => {\n const { initial, context, stepMeta, steps, options } = args;\n const persistence = resolvePersistence(options?.persistence);\n\n const reportPersistenceError = (error: unknown) => {\n persistence?.onError?.(error);\n };\n\n const persistSnapshot = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n if (!persistence) {\n return;\n }\n\n try {\n const persistedState: JourneyPersistedState<TContext, TStepId, TStepMeta> = {\n version: persistence.version,\n snapshot: {\n currentStepId: snapshot.currentStepId,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: snapshot.context,\n status: snapshot.status,\n visited: { ...snapshot.visited },\n stepMeta: { ...snapshot.stepMeta }\n }\n };\n persistence.storage.setItem(persistence.key, persistence.serialize(persistedState));\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const removePersistedSnapshot = () => {\n if (!persistence) {\n return;\n }\n\n try {\n persistence.storage.removeItem(persistence.key);\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const hydrateSnapshot = (): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n const initialSnapshot = buildSnapshot(\n [initial],\n 0,\n context,\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(steps),\n stepMeta\n );\n if (!persistence) {\n return initialSnapshot;\n }\n\n try {\n const rawPersisted = persistence.storage.getItem(persistence.key);\n if (!rawPersisted) {\n return initialSnapshot;\n }\n\n const parsed = persistence.deserialize(rawPersisted);\n if (!isRecord(parsed)) {\n return initialSnapshot;\n }\n\n const persistedVersion = parsed.version;\n if (typeof persistedVersion !== \"number\") {\n return initialSnapshot;\n }\n\n let persistedSnapshot: JourneyPersistedSnapshot<TContext, TStepId, TStepMeta> | null = null;\n let shouldRewritePersisted = false;\n\n if (persistedVersion === persistence.version) {\n const coerced = coercePersistedSnapshot(parsed.snapshot, steps, context, stepMeta);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = Boolean(coerced?.needsRewrite);\n } else if (persistence.migrate) {\n const migrated = persistence.migrate(parsed.snapshot, persistedVersion);\n const coerced = coercePersistedSnapshot(migrated, steps, context, stepMeta);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = persistedSnapshot !== null;\n }\n\n if (!persistedSnapshot) {\n return initialSnapshot;\n }\n\n const hydratedSnapshot = buildSnapshot(\n persistedSnapshot.history.timeline,\n persistedSnapshot.history.index,\n persistedSnapshot.context,\n persistedSnapshot.status,\n buildInitialAsyncState(steps),\n persistedSnapshot.stepMeta,\n persistedSnapshot.visited\n );\n\n if (shouldRewritePersisted) {\n persistSnapshot(hydratedSnapshot);\n }\n\n return hydratedSnapshot;\n } catch (error) {\n reportPersistenceError(error);\n return initialSnapshot;\n }\n };\n\n return {\n clearOnReset: persistence?.clearOnReset ?? true,\n hydrateSnapshot,\n persistSnapshot,\n removePersistedSnapshot\n };\n};\n", "import { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_STATUS } from \"./types\";\nimport type {\n JourneyEqualityFn,\n JourneyAsyncState,\n JourneyAsyncPhase,\n JourneyDefaultEventType,\n JourneyDefinition,\n JourneyEvent,\n JourneyEventPayloadMap,\n JourneyMachine,\n JourneyMachineOptions,\n JourneyObservationEvent,\n JourneySelector,\n JourneySendEvent,\n JourneySendResult,\n JourneyStepDefinition,\n JourneyTransitionArgs,\n JourneyTransition,\n JourneyTerminal\n} from \"./types\";\nimport {\n assertStepExists,\n buildIdleStepAsyncState,\n buildInitialAsyncState,\n buildSendResult,\n buildSnapshot,\n isGoToStepByIdEvent,\n isPromiseLike,\n isTerminalTarget,\n normalizeStepCount,\n now,\n selectTransition,\n transitionSnapshot,\n validateJourneyTransitions\n} from \"./machine-helpers\";\nimport { createPersistenceController } from \"./persistence\";\n\n/**\n * Creates a journey machine from a journey definition.\n * Validates steps/transitions, hydrates persisted state (if configured),\n * and returns an API for sending events and reading snapshots.\n */\nexport function createJourneyMachine<\n TContext,\n TStepMeta = unknown,\n TSteps extends Record<string, JourneyStepDefinition<TStepMeta>> = Record<\n string,\n JourneyStepDefinition<TStepMeta>\n >,\n TPayloadMap extends JourneyEventPayloadMap<JourneyDefaultEventType> = Record<never, never>\n>(\n journey: JourneyDefinition<\n TContext,\n Extract<keyof TSteps, string>,\n JourneyDefaultEventType,\n TPayloadMap,\n TStepMeta\n > & {\n steps: TSteps;\n transitions: readonly JourneyTransition<\n TContext,\n Extract<keyof TSteps, string>,\n JourneyDefaultEventType,\n TPayloadMap\n >[];\n },\n options?: JourneyMachineOptions<TContext, Extract<keyof TSteps, string>, TStepMeta>\n): JourneyMachine<\n TContext,\n Extract<keyof TSteps, string>,\n JourneyDefaultEventType,\n TPayloadMap,\n TStepMeta\n>;\n// eslint-disable-next-line no-redeclare\nexport function createJourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>\n): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>;\n// eslint-disable-next-line no-redeclare\nexport function createJourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>\n): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta> {\n if (!journey.steps || typeof journey.steps !== \"object\") {\n throw new Error(\"Journey steps must be a record object.\");\n }\n\n if (!Array.isArray(journey.transitions)) {\n throw new Error(\"Journey transitions must be an array.\");\n }\n\n for (const stepId of Object.keys(journey.steps)) {\n if (stepId === \"*\") {\n throw new Error('Step id \"*\" is reserved as a wildcard and cannot be used as a step name.');\n }\n }\n\n assertStepExists(\n journey.steps,\n journey.initial,\n `Journey initial step \"${journey.initial}\" does not exist in steps registry.`\n );\n\n validateJourneyTransitions(journey.transitions, journey.steps);\n\n const buildStepMeta = (): Record<TStepId, TStepMeta> => {\n const stepMeta = {} as Record<TStepId, TStepMeta>;\n for (const stepId of Object.keys(journey.steps) as TStepId[]) {\n stepMeta[stepId] = journey.steps[stepId].meta as TStepMeta;\n }\n return stepMeta;\n };\n\n const { clearOnReset, hydrateSnapshot, persistSnapshot, removePersistedSnapshot } =\n createPersistenceController({\n initial: journey.initial,\n context: journey.context,\n stepMeta: buildStepMeta(),\n steps: journey.steps,\n ...(options ? { options } : {})\n });\n\n let snapshot = hydrateSnapshot();\n snapshot = {\n ...snapshot,\n async: buildInitialAsyncState(journey.steps)\n };\n const completeOnNoNextStep = options?.completeOnNoNextStep ?? true;\n const startupEvent: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta> = {\n type: \"journey.start\",\n stepId: snapshot.currentStepId,\n timestamp: now()\n };\n\n const listeners = new Set<() => void>();\n const eventListeners = new Set<\n (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => void\n >();\n let actionQueue: Promise<void> = Promise.resolve();\n let lifecycleVersion = 0;\n let isDisposed = false;\n\n const isRunActive = (runVersion: number): boolean =>\n !isDisposed && runVersion === lifecycleVersion;\n\n const cancelInFlight = () => {\n lifecycleVersion += 1;\n actionQueue = Promise.resolve();\n };\n\n const notify = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n const emit = (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => {\n for (const listener of eventListeners) {\n listener(event);\n }\n };\n\n const queue = <T>(\n runner: (runVersion: number) => Promise<T>,\n onCanceled: () => T\n ): Promise<T> => {\n const runVersion = lifecycleVersion;\n const createQueuedRunner = async () => {\n if (!isRunActive(runVersion)) {\n return onCanceled();\n }\n return runner(runVersion);\n };\n\n const settleQueue = (resultPromise: Promise<T>) => {\n actionQueue = resultPromise.then(\n () => undefined,\n () => undefined\n );\n };\n\n const resultPromise = actionQueue.then(createQueuedRunner, createQueuedRunner);\n settleQueue(resultPromise);\n return resultPromise;\n };\n\n const isAsyncLoadingPhase = (phase: JourneyAsyncPhase): boolean =>\n phase === JOURNEY_ASYNC_PHASE.EVALUATING_WHEN || phase === JOURNEY_ASYNC_PHASE.RUNNING_EFFECT;\n\n const updateStepAsync = (\n stepId: TStepId,\n updater: (\n current: JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => JourneyAsyncState<TStepId>[\"byStep\"][TStepId],\n runVersion?: number\n ) => {\n if (runVersion !== undefined && !isRunActive(runVersion)) {\n return;\n }\n\n const current = snapshot.async.byStep[stepId] ?? buildIdleStepAsyncState();\n const next = updater(current);\n if (\n current.phase === next.phase &&\n current.eventType === next.eventType &&\n current.transitionId === next.transitionId &&\n current.error === next.error\n ) {\n return;\n }\n\n const nextByStep = {\n ...snapshot.async.byStep,\n [stepId]: next\n };\n const isLoading = Object.values(nextByStep).some((state) => isAsyncLoadingPhase(state.phase));\n snapshot = {\n ...snapshot,\n async: {\n isLoading,\n byStep: nextByStep\n }\n };\n notify();\n };\n\n const setStepLoading = (\n stepId: TStepId,\n phase: JourneyAsyncPhase,\n eventType: string,\n transitionId?: string,\n runVersion?: number\n ) => {\n updateStepAsync(\n stepId,\n () => ({\n phase,\n eventType,\n transitionId: transitionId ?? null,\n error: null\n }),\n runVersion\n );\n };\n\n const setStepIdle = (stepId: TStepId, runVersion?: number) => {\n updateStepAsync(stepId, () => buildIdleStepAsyncState(), runVersion);\n };\n\n const setStepError = (\n stepId: TStepId,\n eventType: string,\n error: unknown,\n transitionId?: string,\n runVersion?: number\n ) => {\n updateStepAsync(\n stepId,\n () => ({\n phase: JOURNEY_ASYNC_PHASE.ERROR,\n eventType,\n transitionId: transitionId ?? null,\n error\n }),\n runVersion\n );\n };\n\n const applyPreviousNavigation = (\n requestedSteps?: number,\n transitionId?: string\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const steps = normalizeStepCount(requestedSteps);\n if (snapshot.history.index === 0) {\n return buildSendResult(snapshot, false);\n }\n\n const from = snapshot.currentStepId;\n const nextIndex = Math.max(0, snapshot.history.index - steps);\n const appliedSteps = snapshot.history.index - nextIndex;\n if (appliedSteps <= 0) {\n return buildSendResult(snapshot, false);\n }\n\n emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n snapshot = buildSnapshot(\n snapshot.history.timeline,\n nextIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n snapshot.visited\n );\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"navigation.previous\",\n from,\n to: snapshot.currentStepId,\n requestedSteps: steps,\n appliedSteps,\n timestamp: now()\n });\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n return buildSendResult(snapshot, true, {\n ...(transitionId !== undefined ? { transitionId } : {})\n });\n };\n\n const applyLastVisitedNavigation = (\n transitionId?: string\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const targetIndex = snapshot.history.timeline.length - 1;\n if (snapshot.history.index >= targetIndex) {\n return buildSendResult(snapshot, false);\n }\n\n const from = snapshot.currentStepId;\n emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n snapshot = buildSnapshot(\n snapshot.history.timeline,\n targetIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n snapshot.visited\n );\n persistSnapshot(snapshot);\n notify();\n\n emit({ type: \"navigation.lastVisited\", from, to: snapshot.currentStepId, timestamp: now() });\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n return buildSendResult(snapshot, true, {\n ...(transitionId !== undefined ? { transitionId } : {})\n });\n };\n\n type RuntimeSendEvent = JourneySendEvent<TStepId, TEventType, TPayloadMap>;\n type RuntimeTransitionEvent = JourneyEvent<TStepId, TEventType, TPayloadMap>;\n type RuntimeTransition = JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>;\n\n const buildCanceledSendResult = (): JourneySendResult<TContext, TStepId, TStepMeta> =>\n buildSendResult(snapshot, false);\n\n const buildErroredSendResult = (\n error: unknown,\n transitionId?: string\n ): JourneySendResult<TContext, TStepId, TStepMeta> =>\n buildSendResult(snapshot, false, {\n ...(transitionId !== undefined ? { transitionId } : {}),\n error\n });\n\n const buildTransitionErrorResult = (\n fromStep: TStepId,\n eventType: string,\n error: unknown,\n transitionId: string | null,\n runVersion: number\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n setStepError(fromStep, eventType, error, transitionId ?? undefined, runVersion);\n emit({\n type: \"transition.error\",\n from: fromStep,\n eventType,\n transitionId,\n error,\n timestamp: now()\n });\n return buildErroredSendResult(error, transitionId ?? undefined);\n };\n\n const applyDirectGoToStepById = (\n stepId: TStepId,\n fromStep: TStepId,\n runVersion: number\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n setStepIdle(fromStep, runVersion);\n\n const beforeCurrent = snapshot.currentStepId;\n const nextSnapshot = transitionSnapshot(snapshot, stepId, snapshot.context);\n if (nextSnapshot.currentStepId !== beforeCurrent) {\n emit({ type: \"step.exit\", stepId: beforeCurrent, timestamp: now() });\n }\n\n snapshot = nextSnapshot;\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: snapshot.currentStepId,\n eventType: JOURNEY_EVENT.GO_TO_STEP_BY_ID,\n transitionId: JOURNEY_EVENT.GO_TO_STEP_BY_ID,\n timestamp: now()\n });\n\n if (nextSnapshot.currentStepId !== beforeCurrent) {\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n }\n\n return buildSendResult(snapshot, true, { transitionId: JOURNEY_EVENT.GO_TO_STEP_BY_ID });\n };\n\n const resolveTransitionsForSend = (\n event: RuntimeSendEvent,\n fromStep: TStepId,\n runVersion: number\n ): {\n transitionsToEvaluate: readonly RuntimeTransition[];\n earlyResult: JourneySendResult<TContext, TStepId, TStepMeta> | null;\n } => {\n if (!isGoToStepByIdEvent(event)) {\n return { transitionsToEvaluate: journey.transitions, earlyResult: null };\n }\n\n assertStepExists(\n journey.steps,\n event.stepId,\n `Cannot goToStepById unknown step \"${event.stepId}\".`\n );\n\n const goToStepTransitions = journey.transitions.filter((transition) => {\n const fromMatches = transition.from === \"*\" || transition.from === fromStep;\n return (\n fromMatches &&\n transition.event === JOURNEY_EVENT.GO_TO_STEP_BY_ID &&\n \"to\" in transition &&\n transition.to === event.stepId\n );\n });\n\n if (goToStepTransitions.length === 0) {\n return {\n transitionsToEvaluate: journey.transitions,\n earlyResult: applyDirectGoToStepById(event.stepId, fromStep, runVersion)\n };\n }\n\n return { transitionsToEvaluate: goToStepTransitions, earlyResult: null };\n };\n\n const selectTransitionForSend = async (\n transitionsToEvaluate: readonly RuntimeTransition[],\n transitionEvent: RuntimeTransitionEvent,\n fromStep: TStepId,\n runVersion: number\n ): Promise<\n | { transition: RuntimeTransition | null; earlyResult: null }\n | { transition: null; earlyResult: JourneySendResult<TContext, TStepId, TStepMeta> }\n > => {\n let transition;\n try {\n transition = await selectTransition(transitionsToEvaluate, snapshot, transitionEvent, {\n onAsyncGuardStart: (currentTransition) => {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.EVALUATING_WHEN,\n transitionEvent.type,\n currentTransition.id,\n runVersion\n );\n },\n onAsyncGuardSuccess: () => {\n setStepIdle(fromStep, runVersion);\n },\n onAsyncGuardError: (currentTransition, error) => {\n setStepError(fromStep, transitionEvent.type, error, currentTransition.id, runVersion);\n }\n });\n } catch (error) {\n if (!isRunActive(runVersion)) {\n return { transition: null, earlyResult: buildCanceledSendResult() };\n }\n\n return {\n transition: null,\n earlyResult: buildTransitionErrorResult(\n fromStep,\n transitionEvent.type,\n error,\n null,\n runVersion\n )\n };\n }\n\n return { transition, earlyResult: null };\n };\n\n const handleNoTransitionMatch = (\n event: RuntimeSendEvent,\n fromStep: TStepId\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n if (isGoToStepByIdEvent(event)) {\n return buildCanceledSendResult();\n }\n\n if (event.type === \"goToPreviousStep\" || event.type === \"back\") {\n const fallbackResult = applyPreviousNavigation(1, event.type);\n if (fallbackResult.transitioned) {\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: fallbackResult.snapshot.currentStepId,\n eventType: event.type,\n transitionId: null,\n timestamp: now()\n });\n }\n return fallbackResult;\n }\n\n if (\n event.type === \"goToNextStep\" &&\n completeOnNoNextStep &&\n !hasDeclaredTransitionForEvent(fromStep, \"goToNextStep\")\n ) {\n return commitTerminalTransition(fromStep, \"COMPLETE\", event, null, snapshot.context);\n }\n\n return buildCanceledSendResult();\n };\n\n const resolveNextContext = async (\n transition: RuntimeTransition,\n transitionEvent: RuntimeTransitionEvent,\n fromStep: TStepId,\n runVersion: number\n ): Promise<\n | { nextContext: TContext; earlyResult: null }\n | { nextContext: null; earlyResult: JourneySendResult<TContext, TStepId, TStepMeta> }\n > => {\n let nextContext = snapshot.context;\n if (!transition.effect) {\n return { nextContext, earlyResult: null };\n }\n\n let effectResultPromise: TContext | void | Promise<TContext | void>;\n try {\n effectResultPromise = (\n transition.effect as (\n args: JourneyTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => TContext | void | Promise<TContext | void>\n )({\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event: transitionEvent\n });\n } catch (error) {\n if (!isRunActive(runVersion)) {\n return { nextContext: null, earlyResult: buildCanceledSendResult() };\n }\n\n return {\n nextContext: null,\n earlyResult: buildTransitionErrorResult(\n fromStep,\n transitionEvent.type,\n error,\n transition.id ?? null,\n runVersion\n )\n };\n }\n\n if (isPromiseLike(effectResultPromise)) {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.RUNNING_EFFECT,\n transitionEvent.type,\n transition.id,\n runVersion\n );\n }\n\n let effectResult: TContext | void;\n try {\n effectResult = await effectResultPromise;\n } catch (error) {\n if (!isRunActive(runVersion)) {\n return { nextContext: null, earlyResult: buildCanceledSendResult() };\n }\n\n return {\n nextContext: null,\n earlyResult: buildTransitionErrorResult(\n fromStep,\n transitionEvent.type,\n error,\n transition.id ?? null,\n runVersion\n )\n };\n }\n\n if (!isRunActive(runVersion)) {\n return { nextContext: null, earlyResult: buildCanceledSendResult() };\n }\n\n if (effectResult !== undefined) {\n nextContext = effectResult;\n }\n\n return { nextContext, earlyResult: null };\n };\n\n const resolveTransitionTarget = (transition: RuntimeTransition): TStepId | JourneyTerminal =>\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : (transition.to as TStepId | JourneyTerminal);\n\n const hasDeclaredTransitionForEvent = (fromStep: TStepId, eventType: string): boolean =>\n journey.transitions.some((transition) => {\n const fromMatches = transition.from === \"*\" || transition.from === fromStep;\n return fromMatches && transition.event === eventType;\n });\n\n const commitTerminalTransition = (\n fromStep: TStepId,\n target: JourneyTerminal,\n transitionEvent: RuntimeSendEvent,\n transitionId: string | null,\n nextContext: TContext\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n const normalizedTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n snapshot = {\n ...snapshot,\n history: {\n timeline: normalizedTimeline,\n index: normalizedTimeline.length - 1\n },\n context: nextContext,\n status: target === \"COMPLETE\" ? JOURNEY_STATUS.COMPLETE : JOURNEY_STATUS.TERMINATED\n };\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: target,\n eventType: transitionEvent.type,\n transitionId,\n timestamp: now()\n });\n emit({\n type: target === \"COMPLETE\" ? \"journey.complete\" : \"journey.close\",\n stepId: snapshot.currentStepId,\n timestamp: now()\n });\n\n return buildSendResult(snapshot, true, {\n ...(transitionId !== null ? { transitionId } : {})\n });\n };\n\n const commitStepTransition = (\n fromStep: TStepId,\n target: TStepId,\n transitionEvent: RuntimeTransitionEvent,\n transition: RuntimeTransition,\n nextContext: TContext\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n assertStepExists(journey.steps, target, `Transition points to unknown step \"${target}\".`);\n\n const beforeCurrent = snapshot.currentStepId;\n if (beforeCurrent !== target) {\n emit({ type: \"step.exit\", stepId: beforeCurrent, timestamp: now() });\n }\n snapshot = transitionSnapshot(snapshot, target, nextContext);\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: snapshot.currentStepId,\n eventType: transitionEvent.type,\n transitionId: transition.id ?? null,\n timestamp: now()\n });\n if (beforeCurrent !== snapshot.currentStepId) {\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n }\n\n return buildSendResult(snapshot, true, {\n ...(transition.id !== undefined ? { transitionId: transition.id } : {})\n });\n };\n\n const executeSend = async (\n event: RuntimeSendEvent,\n runVersion: number\n ): Promise<JourneySendResult<TContext, TStepId, TStepMeta>> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildCanceledSendResult();\n }\n\n const fromStep = snapshot.currentStepId;\n const transitionEvent = event as RuntimeTransitionEvent;\n emit({ type: \"transition.start\", from: fromStep, event, timestamp: now() });\n\n const transitionResolution = resolveTransitionsForSend(event, fromStep, runVersion);\n if (transitionResolution.earlyResult) {\n return transitionResolution.earlyResult;\n }\n\n const selectionResolution = await selectTransitionForSend(\n transitionResolution.transitionsToEvaluate,\n transitionEvent,\n fromStep,\n runVersion\n );\n if (selectionResolution.earlyResult) {\n return selectionResolution.earlyResult;\n }\n\n if (!isRunActive(runVersion)) {\n return buildCanceledSendResult();\n }\n\n const { transition } = selectionResolution;\n if (!transition) {\n return handleNoTransitionMatch(event, fromStep);\n }\n\n const contextResolution = await resolveNextContext(\n transition,\n transitionEvent,\n fromStep,\n runVersion\n );\n if (contextResolution.earlyResult) {\n return contextResolution.earlyResult;\n }\n\n setStepIdle(fromStep, runVersion);\n\n const target = resolveTransitionTarget(transition);\n if (isTerminalTarget(target)) {\n return commitTerminalTransition(\n fromStep,\n target,\n transitionEvent,\n transition.id ?? null,\n contextResolution.nextContext\n );\n }\n\n return commitStepTransition(\n fromStep,\n target,\n transitionEvent,\n transition,\n contextResolution.nextContext\n );\n };\n\n const machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta> = {\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n if (isDisposed) {\n return () => undefined;\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n subscribeSelector: <TSelected>(\n selector: JourneySelector<TContext, TStepId, TStepMeta, TSelected>,\n listener: (next: TSelected, previous: TSelected) => void,\n equalityFn?: JourneyEqualityFn<TSelected>\n ) => {\n if (isDisposed) {\n return () => undefined;\n }\n\n const isEqual = equalityFn ?? Object.is;\n let selected = selector(snapshot);\n\n return machine.subscribe(() => {\n const nextSelected = selector(snapshot);\n if (isEqual(selected, nextSelected)) {\n return;\n }\n\n const previous = selected;\n selected = nextSelected;\n listener(nextSelected, previous);\n });\n },\n subscribeEvent: (listener) => {\n if (isDisposed) {\n return () => undefined;\n }\n eventListeners.add(listener);\n try {\n listener(startupEvent);\n } catch (error) {\n eventListeners.delete(listener);\n throw error;\n }\n return () => {\n eventListeners.delete(listener);\n };\n },\n subscribeStart: (listener) =>\n machine.subscribeEvent((event) => {\n if (event.type === \"journey.start\") {\n listener(event);\n }\n }),\n subscribeComplete: (listener) =>\n machine.subscribeEvent((event) => {\n if (event.type === \"journey.complete\") {\n listener(event);\n }\n }),\n subscribeTerminate: (listener) =>\n machine.subscribeEvent((event) => {\n if (event.type === \"journey.close\") {\n listener(event);\n }\n }),\n resetMachine: () => {\n if (isDisposed) {\n return snapshot;\n }\n\n cancelInFlight();\n snapshot = buildSnapshot(\n [journey.initial],\n 0,\n journey.context,\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(journey.steps),\n buildStepMeta()\n );\n if (clearOnReset) {\n removePersistedSnapshot();\n } else {\n persistSnapshot(snapshot);\n }\n notify();\n return snapshot;\n },\n updateContext: (updater) => {\n if (isDisposed) {\n return snapshot;\n }\n\n snapshot = {\n ...snapshot,\n context: updater(snapshot.context)\n };\n persistSnapshot(snapshot);\n notify();\n return snapshot;\n },\n updateStepMetadata: (stepId, updater) => {\n if (isDisposed) {\n return snapshot;\n }\n\n if (!(stepId in journey.steps)) {\n return snapshot;\n }\n\n const previousMeta = snapshot.stepMeta[stepId];\n const nextMeta = updater(previousMeta);\n if (Object.is(previousMeta, nextMeta)) {\n return snapshot;\n }\n\n snapshot = {\n ...snapshot,\n stepMeta: {\n ...snapshot.stepMeta,\n [stepId]: nextMeta\n }\n };\n persistSnapshot(snapshot);\n notify();\n emit({\n type: \"metadata.updated\",\n stepId,\n previous: previousMeta,\n next: nextMeta,\n timestamp: now()\n });\n return snapshot;\n },\n clearStepError: (stepId) => {\n if (isDisposed) {\n return snapshot;\n }\n\n const resolvedStep = stepId ?? snapshot.currentStepId;\n if (!(resolvedStep in journey.steps)) {\n return snapshot;\n }\n\n setStepIdle(resolvedStep);\n return snapshot;\n },\n dispose: () => {\n if (isDisposed) {\n return;\n }\n\n isDisposed = true;\n cancelInFlight();\n listeners.clear();\n eventListeners.clear();\n },\n goToPreviousStep: (steps) =>\n queue(\n async () => {\n const result = applyPreviousNavigation(steps, \"goToPreviousStep\");\n return result;\n },\n () => buildSendResult(snapshot, false)\n ),\n goToLastVisitedStep: () =>\n queue(\n async () => {\n const result = applyLastVisitedNavigation(\"goToLastVisitedStep\");\n return result;\n },\n () => buildSendResult(snapshot, false)\n ),\n goToNextStep: () => machine.send({ type: \"goToNextStep\" }),\n terminateJourney: (payload) =>\n payload === undefined\n ? machine.send({ type: \"terminateJourney\" })\n : machine.send({ type: \"terminateJourney\", payload }),\n completeJourney: (payload) =>\n payload === undefined\n ? machine.send({ type: \"completeJourney\" })\n : machine.send({ type: \"completeJourney\", payload }),\n send: (event) =>\n queue(async (runVersion) => executeSend(event, runVersion), buildCanceledSendResult)\n };\n\n return machine;\n}\n", "import { JOURNEY_WILDCARD } from \"./types/journey.types\";\nimport type { JourneyEventPayloadMap } from \"./types/journey.types\";\nimport type {\n EventBuilder,\n JourneyEventTransition,\n JourneyTransition,\n JourneySelectedTransitionArgs,\n JourneyTransitionTarget,\n TransitionBranch,\n TransitionBranchBuilder,\n TransitionConfig\n} from \"./types/transitions.types\";\n\ntype TransitionPayloadMap = Partial<Record<string, unknown>>;\ntype SelectedPayloadMap<\n TEventType extends string,\n TPayloadMap extends TransitionPayloadMap\n> = TPayloadMap & JourneyEventPayloadMap<TEventType>;\n\nconst createBranchBuilder = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n predicate?: (\n args: JourneySelectedTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => boolean | Promise<boolean>\n): TransitionBranchBuilder<TContext, TStepId, TEventType, TPayloadMap> => ({\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): TransitionBranch<TContext, TStepId, TEventType, TPayloadMap> => ({\n ...config,\n to,\n ...(predicate ? { when: predicate } : {})\n })\n});\n\nconst createEventBuilder = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n from: TStepId | typeof JOURNEY_WILDCARD,\n event: TEventType\n): EventBuilder<TContext, TStepId, TEventType, TPayloadMap> => {\n if (event === \"completeJourney\") {\n return {\n complete: (\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Extract<TEventType, \"completeJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n }\n\n if (event === \"terminateJourney\") {\n return {\n terminate: (\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Extract<TEventType, \"terminateJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n }\n\n return {\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Exclude<TEventType, \"completeJourney\" | \"terminateJourney\">,\n to\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>,\n choose: (\n ...branches: Array<TransitionBranch<TContext, TStepId, TEventType, TPayloadMap>>\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[] =>\n branches.map(\n (branch) =>\n ({\n ...branch,\n from,\n event: event as Exclude<TEventType, \"completeJourney\" | \"terminateJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ),\n when: (\n predicate: (\n args: JourneySelectedTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => boolean | Promise<boolean>\n ) => createBranchBuilder(predicate),\n otherwise: () => createBranchBuilder()\n } as unknown as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n};\n\nconst buildTerminalTransition = <\n TContext,\n TStepId extends string,\n TEventType extends \"completeJourney\" | \"terminateJourney\",\n TPayloadMap extends TransitionPayloadMap = Record<never, never>\n>(\n from: TStepId | typeof JOURNEY_WILDCARD,\n event: TEventType,\n config: TransitionConfig<\n TContext,\n TStepId,\n TEventType,\n SelectedPayloadMap<TEventType, TPayloadMap>\n > = {}\n): JourneyEventTransition<\n TContext,\n TStepId,\n TEventType,\n SelectedPayloadMap<TEventType, TPayloadMap>\n> =>\n ({\n ...config,\n from,\n event\n }) as JourneyEventTransition<\n TContext,\n TStepId,\n TEventType,\n SelectedPayloadMap<TEventType, TPayloadMap>\n >;\n\n/**\n * Fluent helpers for building journey transitions with type-safe branches.\n */\nexport const tx = {\n from: <\n TStepId extends string,\n TContext = unknown,\n TPayloadMap extends TransitionPayloadMap = Record<never, never>\n >(\n from: TStepId\n ) => ({\n on: <TEventType extends string>(event: TEventType) =>\n createEventBuilder<\n TContext,\n TStepId,\n TEventType,\n SelectedPayloadMap<TEventType, TPayloadMap>\n >(from, event),\n toComplete: (\n config: TransitionConfig<\n TContext,\n TStepId,\n \"completeJourney\",\n SelectedPayloadMap<\"completeJourney\", TPayloadMap>\n > = {}\n ) =>\n buildTerminalTransition<TContext, TStepId, \"completeJourney\", TPayloadMap>(\n from,\n \"completeJourney\",\n config\n ),\n toTerminate: (\n config: TransitionConfig<\n TContext,\n TStepId,\n \"terminateJourney\",\n SelectedPayloadMap<\"terminateJourney\", TPayloadMap>\n > = {}\n ) =>\n buildTerminalTransition<TContext, TStepId, \"terminateJourney\", TPayloadMap>(\n from,\n \"terminateJourney\",\n config\n )\n }),\n any: <\n TContext = unknown,\n TStepId extends string = string,\n TPayloadMap extends TransitionPayloadMap = Record<never, never>\n >() => ({\n on: <TEventType extends string>(event: TEventType) =>\n createEventBuilder<\n TContext,\n TStepId,\n TEventType,\n SelectedPayloadMap<TEventType, TPayloadMap>\n >(JOURNEY_WILDCARD, event),\n toComplete: (\n config: TransitionConfig<\n TContext,\n TStepId,\n \"completeJourney\",\n SelectedPayloadMap<\"completeJourney\", TPayloadMap>\n > = {}\n ) =>\n buildTerminalTransition<TContext, TStepId, \"completeJourney\", TPayloadMap>(\n JOURNEY_WILDCARD,\n \"completeJourney\",\n config\n ),\n toTerminate: (\n config: TransitionConfig<\n TContext,\n TStepId,\n \"terminateJourney\",\n SelectedPayloadMap<\"terminateJourney\", TPayloadMap>\n > = {}\n ) =>\n buildTerminalTransition<TContext, TStepId, \"terminateJourney\", TPayloadMap>(\n JOURNEY_WILDCARD,\n \"terminateJourney\",\n config\n )\n }),\n when: <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n >(\n predicate: (\n args: JourneySelectedTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => boolean | Promise<boolean>\n ) => ({\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): TransitionBranch<TContext, TStepId, TEventType, TPayloadMap> => ({\n ...config,\n to,\n when: predicate\n })\n }),\n otherwise: <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n >() => ({\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): TransitionBranch<TContext, TStepId, TEventType, TPayloadMap> => ({\n ...config,\n to\n })\n })\n};\n\n/**\n * Flattens transition items and transition arrays into a single transition list.\n */\nexport const createTransitions = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n ...items: Array<\n | JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n | readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[]\n >\n): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[] =>\n items.flatMap((item) => (Array.isArray(item) ? [...item] : [item]));\n"],
5
+ "mappings": "AAOO,IAAMA,EAAiB,CAC5B,QAAS,UACT,SAAU,WACV,WAAY,YACd,EAMaC,EAAmB,IAGnBC,EAAgB,CAC3B,iBAAkB,cACpB,EAgBaC,EAAsB,CACjC,KAAM,OACN,gBAAiB,kB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R,CACF,CACJ,GACA,KAMEF,IAGI,CACJ,GAAI,CACFC,EACAC,EAAuE,CAAC,KACN,CAClE,GAAGA,EACH,GAAAD,EACA,KAAMD,CACR,EACF,GACA,UAAW,KAKH,CACN,GAAI,CACFC,EACAC,EAAuE,CAAC,KACN,CAClE,GAAGA,EACH,GAAAD,CACF,EACF,EACF,EAKaU,GAAoB,IAM5BC,IAKHA,EAAM,QAASC,GAAU,MAAM,QAAQA,CAAI,EAAI,CAAC,GAAGA,CAAI,EAAI,CAACA,CAAI,CAAE",
6
+ "names": ["JOURNEY_STATUS", "JOURNEY_WILDCARD", "JOURNEY_EVENT", "JOURNEY_ASYNC_PHASE", "assertStepExists", "steps", "stepId", "message", "normalizeStepCount", "now", "unique", "items", "normalizeVisited", "visited", "stepIds", "buildVisitedFromTimeline", "timeline", "resolvedStepIds", "appendVisited", "current", "isPromiseLike", "value", "buildIdleStepAsyncState", "JOURNEY_ASYNC_PHASE", "buildInitialAsyncState", "isGoToStepByIdEvent", "event", "JOURNEY_EVENT", "isTerminalTarget", "target", "validateJourneyTransitions", "transitions", "stepRegistry", "index", "transition", "JOURNEY_WILDCARD", "buildSendResult", "snapshot", "transitioned", "options", "buildSnapshot", "context", "status", "asyncState", "stepMeta", "safeIndex", "currentStepId", "selectTransition", "hooks", "fromMatches", "eventMatches", "guardResult", "asyncGuard", "allowed", "error", "transitionSnapshot", "nextCurrent", "nextContext", "baseTimeline", "nextTimeline", "nextIndex", "isRecord", "value", "isStatusValue", "JOURNEY_STATUS", "resolveDefaultStorage", "localStorageCandidate", "resolvePersistence", "options", "storage", "error", "resolveVisitedFromPersistence", "visitedSource", "timeline", "stepIds", "visitedFromTimeline", "buildVisitedFromTimeline", "needsRewrite", "visited", "stepId", "persistedValue", "visitedFromArray", "step", "coercePersistedSnapshot", "steps", "fallbackContext", "fallbackStepMeta", "rawHistory", "rawTimeline", "currentStepIdValue", "index", "rawIndex", "inferredIndex", "status", "visitedNeedsRewrite", "rawStepMeta", "stepMeta", "typedStepId", "rawValue", "createPersistenceController", "args", "initial", "context", "persistence", "reportPersistenceError", "persistSnapshot", "snapshot", "persistedState", "removePersistedSnapshot", "hydrateSnapshot", "initialSnapshot", "buildSnapshot", "buildInitialAsyncState", "rawPersisted", "parsed", "persistedVersion", "persistedSnapshot", "shouldRewritePersisted", "coerced", "migrated", "hydratedSnapshot", "createJourneyMachine", "journey", "options", "stepId", "assertStepExists", "validateJourneyTransitions", "buildStepMeta", "stepMeta", "clearOnReset", "hydrateSnapshot", "persistSnapshot", "removePersistedSnapshot", "createPersistenceController", "snapshot", "buildInitialAsyncState", "completeOnNoNextStep", "startupEvent", "now", "listeners", "eventListeners", "actionQueue", "lifecycleVersion", "isDisposed", "isRunActive", "runVersion", "cancelInFlight", "notify", "listener", "emit", "event", "queue", "runner", "onCanceled", "createQueuedRunner", "settleQueue", "resultPromise", "isAsyncLoadingPhase", "phase", "JOURNEY_ASYNC_PHASE", "updateStepAsync", "updater", "current", "buildIdleStepAsyncState", "next", "nextByStep", "isLoading", "state", "setStepLoading", "eventType", "transitionId", "setStepIdle", "setStepError", "error", "applyPreviousNavigation", "requestedSteps", "JOURNEY_STATUS", "buildSendResult", "steps", "normalizeStepCount", "from", "nextIndex", "appliedSteps", "buildSnapshot", "applyLastVisitedNavigation", "targetIndex", "buildCanceledSendResult", "buildErroredSendResult", "buildTransitionErrorResult", "fromStep", "applyDirectGoToStepById", "beforeCurrent", "nextSnapshot", "transitionSnapshot", "JOURNEY_EVENT", "resolveTransitionsForSend", "isGoToStepByIdEvent", "goToStepTransitions", "transition", "selectTransitionForSend", "transitionsToEvaluate", "transitionEvent", "selectTransition", "currentTransition", "handleNoTransitionMatch", "fallbackResult", "hasDeclaredTransitionForEvent", "commitTerminalTransition", "resolveNextContext", "nextContext", "effectResultPromise", "isPromiseLike", "effectResult", "resolveTransitionTarget", "target", "normalizedTimeline", "commitStepTransition", "executeSend", "transitionResolution", "selectionResolution", "contextResolution", "isTerminalTarget", "machine", "selector", "equalityFn", "isEqual", "selected", "nextSelected", "previous", "previousMeta", "nextMeta", "resolvedStep", "payload", "createBranchBuilder", "predicate", "to", "config", "createEventBuilder", "from", "event", "branches", "branch", "buildTerminalTransition", "tx", "JOURNEY_WILDCARD", "createTransitions", "items", "item"]
7
7
  }
@@ -10,7 +10,10 @@ export declare const buildInitialAsyncState: <TStepId extends string>(steps: Rec
10
10
  export declare const isGoToStepByIdEvent: <TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>(event: JourneySendEvent<TStepId, TEventType, TPayloadMap>) => event is JourneyGoToEvent<TStepId, JourneyPayloadFor<JourneyMachineEventType<TEventType>, JourneyMachinePayloadMap<TEventType, TPayloadMap>, JourneyGoToStepByIdEventType>>;
11
11
  export declare const isTerminalTarget: <TStepId extends string>(target: TStepId | JourneyTerminal) => target is JourneyTerminal;
12
12
  export declare const validateJourneyTransitions: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>(transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[], steps: Record<TStepId, unknown>) => void;
13
- export declare const buildSendResult: <TContext, TStepId extends string, TStepMeta>(snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>, transitioned: boolean, transitionId?: string) => JourneySendResult<TContext, TStepId, TStepMeta>;
13
+ export declare const buildSendResult: <TContext, TStepId extends string, TStepMeta>(snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>, transitioned: boolean, options?: {
14
+ transitionId?: string;
15
+ error?: unknown;
16
+ }) => JourneySendResult<TContext, TStepId, TStepMeta>;
14
17
  export declare const buildSnapshot: <TContext, TStepId extends string, TStepMeta>(timeline: readonly TStepId[], index: number, context: TContext, status: JourneyStatus, asyncState: JourneyAsyncState<TStepId>, stepMeta: Record<TStepId, TStepMeta>, visited?: Record<TStepId, boolean>) => JourneySnapshot<TContext, TStepId, TStepMeta>;
15
18
  export declare const selectTransition: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>, TStepMeta>(transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[], snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>, event: JourneyEvent<TStepId, TEventType, TPayloadMap>, hooks?: {
16
19
  onAsyncGuardStart?: (transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>) => void;
package/dist/machine.d.ts CHANGED
@@ -4,9 +4,7 @@ import type { JourneyDefaultEventType, JourneyDefinition, JourneyEventPayloadMap
4
4
  * Validates steps/transitions, hydrates persisted state (if configured),
5
5
  * and returns an API for sending events and reading snapshots.
6
6
  */
7
- export declare function createJourneyMachine<TContext, TStepMeta = unknown, TSteps extends Record<string, JourneyStepDefinition<TStepMeta>> = Record<string, JourneyStepDefinition<TStepMeta>>, TPayloadMap extends JourneyEventPayloadMap<JourneyDefaultEventType> = Record<never, never>>(journey: {
8
- initial: Extract<keyof TSteps, string>;
9
- context: TContext;
7
+ export declare function createJourneyMachine<TContext, TStepMeta = unknown, TSteps extends Record<string, JourneyStepDefinition<TStepMeta>> = Record<string, JourneyStepDefinition<TStepMeta>>, TPayloadMap extends JourneyEventPayloadMap<JourneyDefaultEventType> = Record<never, never>>(journey: JourneyDefinition<TContext, Extract<keyof TSteps, string>, JourneyDefaultEventType, TPayloadMap, TStepMeta> & {
10
8
  steps: TSteps;
11
9
  transitions: readonly JourneyTransition<TContext, Extract<keyof TSteps, string>, JourneyDefaultEventType, TPayloadMap>[];
12
10
  }, options?: JourneyMachineOptions<TContext, Extract<keyof TSteps, string>, TStepMeta>): JourneyMachine<TContext, Extract<keyof TSteps, string>, JourneyDefaultEventType, TPayloadMap, TStepMeta>;