@rxova/journey-core 0.7.0 → 1.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +236 -105
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/journey-builder/index.d.cts +5 -0
- package/dist/journey-builder/index.d.ts +5 -0
- package/dist/journey-builder/types.d.cts +126 -0
- package/dist/journey-builder/types.d.ts +126 -0
- package/dist/journey-machine/async-state.d.cts +12 -0
- package/dist/journey-machine/async-state.d.ts +12 -0
- package/dist/journey-machine/computed.d.cts +2 -0
- package/dist/journey-machine/computed.d.ts +2 -0
- package/dist/journey-machine/controls.d.cts +17 -0
- package/dist/journey-machine/controls.d.ts +17 -0
- package/dist/journey-machine/helpers.d.cts +52 -0
- package/dist/journey-machine/helpers.d.ts +52 -0
- package/dist/journey-machine/index.d.cts +3 -0
- package/dist/journey-machine/index.d.ts +3 -0
- package/dist/journey-machine/navigation.d.cts +32 -0
- package/dist/journey-machine/navigation.d.ts +32 -0
- package/dist/journey-machine/plugin-controller.d.cts +15 -0
- package/dist/journey-machine/plugin-controller.d.ts +15 -0
- package/dist/journey-machine/resolve-journey-definition.d.cts +2 -0
- package/dist/journey-machine/resolve-journey-definition.d.ts +2 -0
- package/dist/journey-machine/runtime.d.cts +33 -0
- package/dist/journey-machine/runtime.d.ts +33 -0
- package/dist/journey-machine/send.d.cts +9 -0
- package/dist/journey-machine/send.d.ts +9 -0
- package/dist/plugins/analytics/index.cjs +2 -0
- package/dist/plugins/analytics/index.cjs.map +7 -0
- package/dist/plugins/analytics/index.d.cts +25 -0
- package/dist/plugins/analytics/index.d.ts +25 -0
- package/dist/plugins/analytics/index.js +2 -0
- package/dist/plugins/analytics/index.js.map +7 -0
- package/dist/plugins/autosave/index.cjs +2 -0
- package/dist/plugins/autosave/index.cjs.map +7 -0
- package/dist/plugins/autosave/index.d.cts +17 -0
- package/dist/plugins/autosave/index.d.ts +17 -0
- package/dist/plugins/autosave/index.js +2 -0
- package/dist/plugins/autosave/index.js.map +7 -0
- package/dist/plugins/diagnostics/diagnostics.d.cts +3 -0
- package/dist/plugins/diagnostics/diagnostics.d.ts +3 -0
- package/dist/plugins/diagnostics/index.cjs +2 -0
- package/dist/plugins/diagnostics/index.cjs.map +7 -0
- package/dist/plugins/diagnostics/index.d.cts +15 -0
- package/dist/plugins/diagnostics/index.d.ts +15 -0
- package/dist/plugins/diagnostics/index.js +2 -0
- package/dist/plugins/diagnostics/index.js.map +7 -0
- package/dist/plugins/execution-paths/execution-paths.d.cts +6 -0
- package/dist/plugins/execution-paths/execution-paths.d.ts +6 -0
- package/dist/plugins/execution-paths/index.cjs +2 -0
- package/dist/plugins/execution-paths/index.cjs.map +7 -0
- package/dist/plugins/execution-paths/index.d.cts +18 -0
- package/dist/plugins/execution-paths/index.d.ts +18 -0
- package/dist/plugins/execution-paths/index.js +2 -0
- package/dist/plugins/execution-paths/index.js.map +7 -0
- package/dist/plugins/persistence/controller.d.cts +17 -0
- package/dist/plugins/persistence/controller.d.ts +17 -0
- package/dist/plugins/persistence/index.cjs +2 -0
- package/dist/plugins/persistence/index.cjs.map +7 -0
- package/dist/plugins/persistence/index.d.cts +12 -0
- package/dist/plugins/persistence/index.d.ts +12 -0
- package/dist/plugins/persistence/index.js +2 -0
- package/dist/plugins/persistence/index.js.map +7 -0
- package/dist/plugins/replay/index.cjs +2 -0
- package/dist/plugins/replay/index.cjs.map +7 -0
- package/dist/plugins/replay/index.d.cts +27 -0
- package/dist/plugins/replay/index.d.ts +27 -0
- package/dist/plugins/replay/index.js +2 -0
- package/dist/plugins/replay/index.js.map +7 -0
- package/dist/types/analytics.types.d.cts +33 -0
- package/dist/types/analytics.types.d.ts +33 -0
- package/dist/types/autosave.types.d.cts +23 -0
- package/dist/types/autosave.types.d.ts +23 -0
- package/dist/types/diagnostics.types.d.cts +38 -0
- package/dist/types/diagnostics.types.d.ts +38 -0
- package/dist/types/index.d.cts +9 -0
- package/dist/types/index.d.ts +9 -4
- package/dist/types/journey.types.d.cts +191 -0
- package/dist/types/journey.types.d.ts +140 -167
- package/dist/types/machine.types.d.cts +104 -0
- package/dist/types/machine.types.d.ts +104 -0
- package/dist/types/observation.types.d.cts +83 -0
- package/dist/types/observation.types.d.ts +83 -0
- package/dist/types/persistence.types.d.cts +34 -0
- package/dist/types/persistence.types.d.ts +13 -20
- package/dist/types/replay.types.d.cts +35 -0
- package/dist/types/replay.types.d.ts +35 -0
- package/dist/types/transitions.types.d.cts +122 -0
- package/dist/types/transitions.types.d.ts +100 -57
- package/package.json +92 -2
- package/dist/machine-helpers.d.ts +0 -23
- package/dist/machine.d.ts +0 -11
- package/dist/persistence.d.ts +0 -17
- package/dist/transitions.d.ts +0 -62
- package/dist/types.d.ts +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { createJourneyMachine } from "./machine";
|
|
2
|
-
export {
|
|
3
|
-
export {
|
|
4
|
-
export
|
|
1
|
+
export { createJourneyMachine } from "./journey-machine";
|
|
2
|
+
export { createJourneyBuilder } from "./journey-builder";
|
|
3
|
+
export { JourneyDisposedError } from "./journey-machine/helpers";
|
|
4
|
+
export type { JourneyBuilder, JourneyBuilderCustomEventKey, JourneyBuilderDefinition, JourneyBuilderDefinitionMetadata, JourneyBuilderGuard, JourneyBuilderOnEntry, JourneyBuilderTerminalCandidate, JourneyBuilderTerminalEntry, JourneyStepBuilder, JourneyToBuilder } from "./journey-builder";
|
|
5
|
+
export { type JourneyAnalyticsEventName, type JourneyAnalyticsEventPayload, type JourneyAnalyticsPluginOptions, type JourneyAnalyticsTrackedEvent, type JourneyAutosavePluginOptions, type JourneyAutosaveState, type JourneyAutosaveStatus, type JourneyComputed, type JourneyCompleteObservationEvent, type JourneyDiagnosticsIssue, type JourneyDiagnosticsIssueCode, type JourneyDiagnosticsIssueSeverity, type JourneyDiagnosticsOptions, type JourneyDiagnosticsResult, type JourneyDiagnosticsSummary, type JourneyDefaultEventType, type JourneyDefinition, type JourneyEqualityFn, type JourneyExecutionPathOptions, type JourneyExecutionPathsResult, type JourneyFullEventType, type JourneyJsonObject, type JourneyJsonValue, type JourneyLinearStep, type JourneyLifecycleErrorContext, type JourneyLifecycleErrorObservationEvent, type JourneyLifecycleErrorPhase, type JourneyLifecycleArgs, type JourneyMachine, type JourneyMachineOptions, type JourneyMachinePlugin, type JourneyMachineWithPlugins, type JourneyObservationEvent, type JourneyPayloadFor, type JourneyResolvedTransition, type JourneyResetObservationEvent, type JourneyReplayEntry, type JourneyReplayEventEntry, type JourneyReplayExportOptions, type JourneyReplayPluginOptions, type JourneyReplaySession, type JourneyReplaySnapshotEntry, type JourneySelector, type JourneySendEvent, type JourneySendResult, type JourneySnapshot, type JourneyStartObservationEvent, type JourneyStepAsyncState, type JourneyStepDefinition, type JourneyStepLifecycleCallback, type JourneyTerminateObservationEvent, type JourneyTransitionArgsForEvent, type JourneyTransitionUpdateContextArgsForEvent } from "./types";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { createJourneyMachine } from "./machine";
|
|
2
|
-
export {
|
|
3
|
-
export {
|
|
4
|
-
export
|
|
1
|
+
export { createJourneyMachine } from "./journey-machine";
|
|
2
|
+
export { createJourneyBuilder } from "./journey-builder";
|
|
3
|
+
export { JourneyDisposedError } from "./journey-machine/helpers";
|
|
4
|
+
export type { JourneyBuilder, JourneyBuilderCustomEventKey, JourneyBuilderDefinition, JourneyBuilderDefinitionMetadata, JourneyBuilderGuard, JourneyBuilderOnEntry, JourneyBuilderTerminalCandidate, JourneyBuilderTerminalEntry, JourneyStepBuilder, JourneyToBuilder } from "./journey-builder";
|
|
5
|
+
export { type JourneyAnalyticsEventName, type JourneyAnalyticsEventPayload, type JourneyAnalyticsPluginOptions, type JourneyAnalyticsTrackedEvent, type JourneyAutosavePluginOptions, type JourneyAutosaveState, type JourneyAutosaveStatus, type JourneyComputed, type JourneyCompleteObservationEvent, type JourneyDiagnosticsIssue, type JourneyDiagnosticsIssueCode, type JourneyDiagnosticsIssueSeverity, type JourneyDiagnosticsOptions, type JourneyDiagnosticsResult, type JourneyDiagnosticsSummary, type JourneyDefaultEventType, type JourneyDefinition, type JourneyEqualityFn, type JourneyExecutionPathOptions, type JourneyExecutionPathsResult, type JourneyFullEventType, type JourneyJsonObject, type JourneyJsonValue, type JourneyLinearStep, type JourneyLifecycleErrorContext, type JourneyLifecycleErrorObservationEvent, type JourneyLifecycleErrorPhase, type JourneyLifecycleArgs, type JourneyMachine, type JourneyMachineOptions, type JourneyMachinePlugin, type JourneyMachineWithPlugins, type JourneyObservationEvent, type JourneyPayloadFor, type JourneyResolvedTransition, type JourneyResetObservationEvent, type JourneyReplayEntry, type JourneyReplayEventEntry, type JourneyReplayExportOptions, type JourneyReplayPluginOptions, type JourneyReplaySession, type JourneyReplaySnapshotEntry, type JourneySelector, type JourneySendEvent, type JourneySendResult, type JourneySnapshot, type JourneyStartObservationEvent, type JourneyStepAsyncState, type JourneyStepDefinition, type JourneyStepLifecycleCallback, type JourneyTerminateObservationEvent, type JourneyTransitionArgsForEvent, type JourneyTransitionUpdateContextArgsForEvent } from "./types";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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};
|
|
1
|
+
var G=(e,t,o)=>{if(!(t in e))throw new Error(o)},Q=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),z=e=>Array.isArray(e)?e.map(t=>z(t)):Q(e)?Object.fromEntries(Object.entries(e).map(([t,o])=>[t,z(o)])):e,ue=e=>{if(e===null)return"null";if(Array.isArray(e))return"array";if(typeof e=="object"){let t=e.constructor?.name;return t&&t!=="Object"?t:"object"}return typeof e};function te(e,t,o,p=[]){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return;let a=p.length===0?t:`${t}.${p.join(".")}`;if(e===void 0)throw new Error(`${a} must be JSON-serializable. Received undefined.`);if(typeof e=="bigint"||typeof e=="symbol"||typeof e=="function")throw new Error(`${a} must be JSON-serializable. Received ${typeof e}.`);if(typeof e!="object")throw new Error(`${a} must be JSON-serializable. Received ${ue(e)}.`);if(o.seen.has(e))throw new Error(`${a} must be JSON-serializable. Circular references are not supported.`);if(o.seen.add(e),Array.isArray(e)){for(let[n,s]of e.entries())te(s,t,o,[...p,String(n)]);return}if(!Q(e))throw new Error(`${a} must be JSON-serializable. Received non-plain ${ue(e)}.`);for(let[n,s]of Object.entries(e))te(s,t,o,[...p,n])}function j(e,t="Journey context"){return te(e,t,{seen:new WeakSet}),e}var B=e=>z(j(e)),_=e=>Array.isArray(e)?e.map(t=>_(t)):e instanceof Date?new Date(e.getTime()):e instanceof Map?new Map([...e.entries()].map(([t,o])=>[_(t),_(o)])):e instanceof Set?new Set([...e].map(t=>_(t))):Q(e)?Object.fromEntries(Object.entries(e).map(([t,o])=>[t,_(o)])):e,se=e=>{if(typeof e!="object"&&typeof e!="function"||e===null)return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{return _(e)}else return _(e)},oe=e=>{if(!(typeof e!="object"||e===null||Object.isFrozen(e))){if(Array.isArray(e)){for(let t of e)oe(t);Object.freeze(e);return}if(Q(e)){for(let t of Object.values(e))oe(t);Object.freeze(e)}}},pe=e=>typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.trunc(e)),b=()=>Date.now(),le=e=>[...new Set(e)],ke=(e,t)=>Object.fromEntries(t.map(o=>[o,e[o]===!0])),Ae=(e,t)=>{let o=t??le(e),p=Object.fromEntries(o.map(a=>[a,!1]));for(let a of e)p[a]=!0;return p},Oe=(e,t)=>({...e,[t]:!0}),ie=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function",ye=e=>typeof e=="number"&&Number.isFinite(e),V=(e,t)=>{if(e!==void 0&&!ye(e))throw new Error(`${t} must define a finite numeric "timeoutMs" when provided.`)},re=class extends Error{constructor(o){super(o);this.name="JourneyTimeoutError"}},q=class extends Error{constructor(o){super(`Journey machine has been disposed; "${o}" can no longer be used.`);this.name="JourneyDisposedError";this.operation=o}},Te=()=>{let e=globalThis;if(typeof e.__DEV__=="boolean")return e.__DEV__;let t=e.process?.env?.NODE_ENV;return t===void 0||t==="development"},X=(e,t)=>{if(!(!Te()||typeof console>"u")){if(t===void 0){console.warn(e);return}console.warn(e,t)}},ce=(e,t)=>{if(!(!Te()||typeof console>"u")){if(t===void 0){console.error(e);return}console.error(e,t)}},Le=async(e,t,o)=>!ye(t)||t<=0?await e:await new Promise((p,a)=>{let n=setTimeout(()=>{a(o())},t);e.then(s=>{clearTimeout(n),p(s)},s=>{clearTimeout(n),a(s)})}),He=async(e,t)=>{if(t.aborted)throw t.reason;return await new Promise((o,p)=>{let a=()=>{t.removeEventListener("abort",a),p(t.reason)};t.addEventListener("abort",a,{once:!0}),e.then(n=>{t.removeEventListener("abort",a),o(n)},n=>{t.removeEventListener("abort",a),p(n)})})},Y=()=>({phase:"idle",eventType:null,transitionId:null,error:null}),Z=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(o=>[o,Y()]))}),ee=e=>e.type==="goToStepById"&&"stepId"in e,K=e=>e==="COMPLETE"||e==="TERMINATED",Se=e=>e.event==="completeJourney"?"COMPLETE":e.event==="terminateJourney"?"TERMINATED":e.to,fe=(e,t)=>{let o=t,p=new Set(["from","event","to","when","updateContext","onEnter","onLeave","id","label","timeoutMs"]);for(let[a,n]of e.entries()){if(!n||typeof n!="object")throw new Error(`Journey transition at index ${a} must be an object.`);for(let s of Object.keys(n))if(!p.has(s))throw new Error(`Journey transition at index ${a} contains unsupported field "${s}".`);if(typeof n.from!="string"||typeof n.event!="string")throw new Error(`Journey transition at index ${a} must define string "from" and "event".`);if(n.from!=="*"&&!(n.from in o))throw new Error(`Journey transition at index ${a} references unknown from step "${n.from}".`);if(V(n.timeoutMs,`Journey transition at index ${a}`),n.when!==void 0&&typeof n.when!="function")throw new Error(`Journey transition at index ${a} must define "when" as a function when provided.`);if(n.updateContext!==void 0&&typeof n.updateContext!="function")throw new Error(`Journey transition at index ${a} must define "updateContext" as a function when provided.`);if(n.onEnter!==void 0&&typeof n.onEnter!="function")throw new Error(`Journey transition at index ${a} must define "onEnter" as a function when provided.`);if(n.onLeave!==void 0&&typeof n.onLeave!="function")throw new Error(`Journey transition at index ${a} must define "onLeave" as a function when provided.`);if(n.id!==void 0&&typeof n.id!="string")throw new Error(`Journey transition at index ${a} must define "id" as a string when provided.`);if(n.label!==void 0&&typeof n.label!="string")throw new Error(`Journey transition at index ${a} must define "label" as a string when provided.`);if(n.event==="completeJourney"||n.event==="terminateJourney"){if("to"in n&&n.to!==void 0)throw new Error(`Journey transition at index ${a} with event "${n.event}" cannot define "to".`);continue}if(typeof n.to!="string")throw new Error(`Journey transition at index ${a} with event "${n.event}" must define string "to".`);if(!K(n.to)&&!(n.to in o))throw new Error(`Journey transition at index ${a} points to unknown step "${n.to}".`)}},k=(e,t,o={})=>({transitioned:t,...o.transitionId!==void 0?{transitionId:o.transitionId}:{},...o.label!==void 0?{label:o.label}:{},..."error"in o?{error:o.error}:{},snapshot:e}),D=(e,t,o,p,a,n)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let s=Math.max(0,Math.min(Math.trunc(t),e.length-1)),r=e[s],d=le(n?[...Object.keys(n),...e]:e);return{status:p,currentStepId:r,history:{timeline:[...e],index:s},context:B(o),visited:n?ke(n,d):Ae(e,d),async:z(a)}},H=e=>{let t={...e,history:{timeline:[...e.history.timeline],index:e.history.index},context:B(e.context),visited:{...e.visited},async:z(e.async)};return oe(t),t},Je=async(e,t,o,p,a,n,s)=>{for(let r of e){let d=r.from==="*"||r.from===t.currentStepId,l=r.event===o.type;if(!d||!l)continue;if(!r.when)return r;let y;if(p.aborted)throw p.reason;y=r.when({snapshot:t,context:t.context,from:t.currentStepId,timeline:t.history.timeline,index:t.history.index,event:o,signal:p,handlers:a});let i=ie(y),u=i?y:null,E;try{i?(n?.onAsyncGuardStart?.(r),E=await Le(He(u,p),r.timeoutMs??s,()=>new re(`Transition guard timed out after ${r.timeoutMs??s}ms (event: ${o.type}, transition: ${r.id??"<anonymous>"}).`))):E=y}catch(g){throw i&&n?.onAsyncGuardError?.(r,g),g}if(i&&n?.onAsyncGuardSuccess?.(r),E)return r}return null},xe=(e,t,o)=>{let p=e.history.timeline.slice(0,e.history.index+1),a=p;t!==e.currentStepId&&(a=[...p,t]);let n=a.length-1,s=Oe(e.visited,t);return D(a,n,o,e.status,e.async,s)};var me=({runtime:e})=>{let t=s=>s==="evaluating-when",o=s=>Object.values(s.byStep).reduce((r,d)=>r+(t(d.phase)?1:0),0),p=o(e.peekSnapshot().async),a=s=>{p=o(s)},n=(s,r,d)=>{if(d!==void 0&&!e.isRunActive(d))return;let l=e.peekSnapshot(),y=l.async.byStep[s]??Y(),i=r(y);if(y.phase===i.phase&&y.eventType===i.eventType&&y.transitionId===i.transitionId&&y.error===i.error)return;let u={...l.async.byStep,[s]:i},E=t(y.phase),g=t(i.phase),P=E===g?p:p+(g?1:-1);e.setSnapshot({...l,async:{isLoading:P>0,byStep:u}},{notify:!0,reason:"async"}),p=P};return{syncState:a,updateStepAsync:n,setStepLoading:(s,r,d,l,y)=>{n(s,()=>({phase:r,eventType:d,transitionId:l??null,error:null}),y)},setStepIdle:(s,r)=>{n(s,()=>Y(),r)},setStepError:(s,r,d,l,y)=>{n(s,()=>({phase:"error",eventType:r,transitionId:l??null,error:d}),y)}}};var Pe=e=>e.map(t=>typeof t=="string"?t:t.step),$e=e=>{let t=0;for(let o in e)e[o]&&(t+=1);return t},he=(e,t,o)=>{let p=e.transitions===void 0?"headless":Array.isArray(e.transitions)?"linear":"graph",a=p==="linear"?Pe(e.transitions):null;return()=>{let n=o(),s=n.history.index,r={activeStepId:n.currentStepId,activeStepIndex:s,visitedStepCount:$e(n.visited),isLoading:n.async.isLoading,isIdle:n.status==="idled",isRunning:n.status==="running",isComplete:n.status==="completed",isTerminated:n.status==="terminated",isInitialStep:n.currentStepId===t.initial};if(p==="linear"&&a!==null){let d=a.length,l=a.indexOf(n.currentStepId);return{...r,activeStepIndex:l===-1?s:l,mode:"linear",stepCount:d,journeyLength:d,isFirstStep:l===0,isLastStep:l===d-1,stepOrder:a}}return p==="graph"?{...r,mode:"graph"}:{...r,mode:"headless"}}};var ve=({runtime:e,asyncState:t,initial:o,initialContext:p,steps:a})=>{let n=r=>{X(`Journey machine has been disposed; "${r}" is a no-op.`)},s=()=>D([o],0,B(p),"idled",Z(a));return{startJourney:()=>e.isDisposed()?(n("startJourney"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let r=e.peekSnapshot();if(r.status!=="idled")return e.getSnapshot();let d=e.setSnapshot({...r,status:"running"},{notify:!0,reason:"start"});return e.emit({type:"journey.start",stepId:d.currentStepId,timestamp:b()}),e.getSnapshot()},()=>e.getSnapshot()),resetJourney:()=>e.isDisposed()?(n("resetJourney"),Promise.resolve(e.getSnapshot())):(e.cancelInFlight(),e.queue(async()=>{let r=e.setSnapshot(s(),{notify:!0,reason:"reset"});return e.emit({type:"journey.reset",stepId:r.currentStepId,timestamp:b()}),t.syncState(r.async),e.getSnapshot()},()=>e.getSnapshot())),updateContext:r=>e.isDisposed()?(n("updateContext"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let d=e.peekSnapshot(),l=j(r(B(d.context)));return e.setSnapshot({...d,context:l},{notify:!0,reason:"context"})},()=>e.getSnapshot()),clearStepError:r=>e.isDisposed()?(n("clearStepError"),Promise.resolve(e.getSnapshot())):e.queue(async()=>{let d=e.peekSnapshot(),l=r??d.currentStepId;return l in a&&t.setStepIdle(l),e.getSnapshot()},()=>e.getSnapshot()),dispose:()=>{e.dispose()}}};var Ee=({runtime:e,steps:t,transitions:o,scheduleLifecycle:p})=>({applyPreviousNavigation:(a,n,s=0)=>{let r=e.peekSnapshot();if(r.status!=="running")return k(e.getSnapshot(),!1);let d=pe(a);if(r.history.index===0)return k(e.getSnapshot(),!1);let l=r.currentStepId,y=Math.max(0,r.history.index-d),i=r.history.index-y;if(i<=0)return k(e.getSnapshot(),!1);e.emit({type:"step.exit",stepId:l,timestamp:b()});let u=e.setSnapshot(D(r.history.timeline,y,r.context,r.status,r.async,r.visited),{notify:!0,reason:"navigation"});return e.emit({type:"navigation.previous",from:l,to:u.currentStepId,requestedSteps:d,appliedSteps:i,timestamp:b()}),e.emit({type:"step.enter",stepId:u.currentStepId,timestamp:b()}),p({previousSnapshot:r,snapshot:u,from:l,to:u.currentStepId,event:{type:"goToPreviousStep"},transitionId:n??null,runVersion:s}),k(u,!0,{...n!==void 0?{transitionId:n}:{}})},applyLastVisitedNavigation:(a,n=0)=>{let s=e.peekSnapshot();if(s.status!=="running")return k(e.getSnapshot(),!1);let r=s.history.timeline.length-1;if(s.history.index>=r)return k(e.getSnapshot(),!1);let d=s.currentStepId;e.emit({type:"step.exit",stepId:d,timestamp:b()});let l=e.setSnapshot(D(s.history.timeline,r,s.context,s.status,s.async,s.visited),{notify:!0,reason:"navigation"});return e.emit({type:"navigation.lastVisited",from:d,to:l.currentStepId,timestamp:b()}),e.emit({type:"step.enter",stepId:l.currentStepId,timestamp:b()}),p({previousSnapshot:s,snapshot:l,from:d,to:l.currentStepId,event:{type:"goToLastVisitedStep"},transitionId:a??null,runVersion:n}),k(l,!0,{...a!==void 0?{transitionId:a}:{}})},hasDeclaredTransitionForEvent:(a,n)=>o.some(s=>(s.from==="*"||s.from===a)&&s.event===n),commitTerminalTransition:(a,n,s,r,d,l,y=0)=>{let i=e.peekSnapshot(),u=i.history.timeline.slice(0,i.history.index+1),E=e.setSnapshot({...i,history:{timeline:u,index:u.length-1},context:l,status:n==="COMPLETE"?"completed":"terminated"},{notify:!0,reason:"transition"});return e.emit({type:"transition.success",from:a,to:n,eventType:s.type,transitionId:r,...d?.label!==void 0?{label:d.label}:{},timestamp:b()}),e.emit({type:n==="COMPLETE"?"journey.completed":"journey.terminated",stepId:E.currentStepId,timestamp:b()}),p({previousSnapshot:i,snapshot:E,from:a,to:n,event:s,transitionId:r,...d?.label!==void 0?{label:d.label}:{},runVersion:y,...d!==void 0?{transition:d}:{}}),k(E,!0,{...r!==null?{transitionId:r}:{},...d?.label!==void 0?{label:d.label}:{}})},commitStepTransition:(a,n,s,r,d,l=0)=>{G(t,n,`Transition points to unknown step "${n}".`);let y=e.peekSnapshot(),i=y.currentStepId;i!==n&&e.emit({type:"step.exit",stepId:i,timestamp:b()});let u=e.setSnapshot(xe(y,n,d),{notify:!0,reason:"transition"});return e.emit({type:"transition.success",from:a,to:u.currentStepId,eventType:s.type,transitionId:r.id,...r.label!==void 0?{label:r.label}:{},timestamp:b()}),i!==u.currentStepId&&e.emit({type:"step.enter",stepId:u.currentStepId,timestamp:b()}),p({previousSnapshot:y,snapshot:u,from:a,to:u.currentStepId,event:s,transitionId:r.id,...r.label!==void 0?{label:r.label}:{},runVersion:l,transition:r}),k(u,!0,{transitionId:r.id,...r.label!==void 0?{label:r.label}:{}})}});var be=({plugins:e,setupContext:t})=>{let o=[];for(let p of e)try{o.push({name:p.name,hooks:p.setup(t)})}catch(a){for(let r of[...o].reverse())try{r.hooks.dispose?.()}catch{}let n=a instanceof Error?a.message:String(a),s=new Error(`Journey plugin "${p.name}" setup failed: ${n}`);throw Object.assign(s,{cause:a}),s}return{hydrateSnapshot:p=>o.reduce((a,n)=>n.hooks.hydrateSnapshot?.(a)??a,p),onSnapshotChange:({previousSnapshot:p,snapshot:a,reason:n})=>{let s;for(let r of o)try{let d=r.hooks.onSnapshotChange?.({previousSnapshot:p,snapshot:a,reason:n});ie(d)&&X(`Journey plugin "${r.name}" returned a Promise from onSnapshotChange. This hook must be synchronous; returning a Promise blocks the machine and the await is dropped.`)}catch(d){s??(s=d)}if(s!==void 0)throw s},extendMachine:p=>{let a=p,n=p,s=new Map;for(let r of o){let d=r.hooks.augmentMachine?.({machine:p,journey:t.journey,resolvedJourney:t.resolvedJourney});if(d)for(let[l,y]of Object.entries(d)){let i=s.get(l);if(i)throw new Error(`Journey plugin "${r.name}" cannot add "${l}" \u2014 already provided by plugin "${i}".`);if(l in a)throw new Error(`Journey plugin "${r.name}" cannot override machine property "${l}".`);s.set(l,r.name),n[l]=y}}return a},dispose:()=>{let p;for(let a of o)try{a.hooks.dispose?.()}catch(n){p??(p=n)}if(p!==void 0)throw p}}};var ge=({snapshot:e,onSnapshotChange:t,onDispose:o,onListenerError:p})=>{let a=H(e),n=H(a),s=new Set,r=new Set,d=Promise.resolve(),l=0,y=!1,i=null,u=new Set,E=p??((f,v)=>{ce(`Journey ${v} listener threw an error.`,f)}),g=()=>{for(let f of s)try{f()}catch(v){E(v,"snapshot")}},P=f=>{for(let v of r)try{v(f)}catch(C){E(C,"event")}},c=(f,v={})=>{let C=n,R=H(f),A=H(R);return t?.({previousSnapshot:H(C),snapshot:H(A),reason:v.reason??"transition"}),a=R,n=A,v.notify&&g(),A},S=f=>!y&&f===l,J=()=>{l+=1,i&&!i.signal.aborted&&i.abort(),i=null;for(let f of u)f.signal.aborted||f.abort();u.clear(),d=Promise.resolve()},x=f=>{if(!S(f))return null;let v=new AbortController;return S(f)?(u.add(v),v):(v.abort(),null)},h=f=>{u.delete(f)},T=(f,v)=>{let C=l,R=async()=>{if(!S(C))return v();let L=new AbortController;i=L;try{return S(C)?await f(C,L.signal):(L.abort(),v())}finally{i===L&&(i=null)}},A=d.then(R,R);return d=A.then(()=>{},()=>{}),A},m=f=>y?()=>{}:(s.add(f),()=>{s.delete(f)});return{getSnapshot:()=>n,peekSnapshot:()=>a,setSnapshot:c,isDisposed:()=>y,isRunActive:S,cancelInFlight:J,openLifecycle:x,closeLifecycle:h,queue:T,notify:g,emit:P,subscribe:m,subscribeSelector:(f,v,C)=>{if(y)return()=>{};let R=C??Object.is,A=f(n);return m(()=>{let L=f(n);if(R(A,L))return;let F=A;A=L,v(L,F)})},subscribeEvent:f=>y?()=>{}:(r.add(f),()=>{r.delete(f)}),dispose:()=>{y||(y=!0,J(),s.clear(),r.clear(),o?.())}}};var Ie=(e,t,o,p,a,n,s,r,d)=>{let l=(c="send")=>k(e.getSnapshot(),!1,{...e.isDisposed()?{error:new q(c)}:{}}),y=(c,S,J)=>k(e.getSnapshot(),!1,{...S!==void 0?{transitionId:S}:{},...J!==void 0?{label:J}:{},error:c}),i=(c,S,J,x,h,T,m=!1)=>(m||t.setStepError(c,S,J,x??void 0,T),e.emit({type:"transition.error",from:c,eventType:S,transitionId:x,...h!==void 0?{label:h}:{},error:J,timestamp:b()}),y(J,x??void 0,h)),u=(c,S)=>ee(c)?(G(a,c.stepId,`Cannot goToStepById unknown step "${c.stepId}".`),{transitionsToEvaluate:n.filter(J=>(J.from==="*"||J.from===S)&&J.event==="goToStepById"&&"to"in J&&J.to===c.stepId),earlyResult:null}):{transitionsToEvaluate:n,earlyResult:null},E=async(c,S,J,x,h)=>{let T,m=null,I,M=!1;try{T=await Je(c,H(e.peekSnapshot()),S,h,s,{onAsyncGuardStart:w=>{t.setStepLoading(J,"evaluating-when",S.type,w.id,x)},onAsyncGuardSuccess:()=>{t.setStepIdle(J,x)},onAsyncGuardError:(w,f)=>{m=w.id??null,I=w.label,M=!0,t.setStepError(J,S.type,f,w.id,x)}},d)}catch(w){return e.isRunActive(x)?{transition:null,earlyResult:i(J,S.type,w,m,I,x,M)}:{transition:null,earlyResult:l(S.type)}}return{transition:T,earlyResult:null}},g=(c,S,J)=>{if(ee(c))return l(c.type);if(c.type==="goToPreviousStep"){let x=o.applyPreviousNavigation(1,c.type,J);return x.transitioned&&e.emit({type:"transition.success",from:S,to:x.snapshot.currentStepId,eventType:c.type,transitionId:null,timestamp:b()}),x}return c.type==="goToNextStep"&&!r&&!o.hasDeclaredTransitionForEvent(S,"goToNextStep")||c.type==="completeJourney"&&!o.hasDeclaredTransitionForEvent(S,"completeJourney")?o.commitTerminalTransition(S,"COMPLETE",c,null,void 0,e.peekSnapshot().context,J):c.type==="terminateJourney"&&!o.hasDeclaredTransitionForEvent(S,"terminateJourney")?o.commitTerminalTransition(S,"TERMINATED",c,null,void 0,e.peekSnapshot().context,J):l(c.type)},P=(c,S,J,x)=>{let h=e.peekSnapshot();if(!c.updateContext)return{nextContext:h.context,earlyResult:null};try{let T=c.updateContext({snapshot:H(h),context:h.context,from:h.currentStepId,timeline:h.history.timeline,index:h.history.index,event:S});return{nextContext:j(T),earlyResult:null}}catch(T){return e.isRunActive(x)?{nextContext:null,earlyResult:i(J,S.type,T,c.id,c.label,x)}:{nextContext:null,earlyResult:l(S.type)}}};return{buildCanceledSendResult:l,executeSend:async(c,S,J)=>{if(e.peekSnapshot().status!=="running")return l(c.type);let x=e.peekSnapshot().currentStepId,h=c;if(e.emit({type:"transition.start",from:x,event:c,timestamp:b()}),p){if(ee(c))return o.commitStepTransition(x,c.stepId,h,{from:x,event:"goToStepById",to:c.stepId},e.peekSnapshot().context,S);if(c.type!=="completeJourney"&&c.type!=="terminateJourney"&&c.type!=="goToPreviousStep")return l(c.type)}let T=u(c,x);if(T.earlyResult)return T.earlyResult;let m=await E(T.transitionsToEvaluate,h,x,S,J);if(m.earlyResult)return m.earlyResult;if(!e.isRunActive(S))return l(c.type);let{transition:I}=m;if(!I)return g(c,x,S);t.setStepIdle(x,S);let M=P(I,h,x,S);if(M.earlyResult)return M.earlyResult;let w=Se(I);return K(w)?o.commitTerminalTransition(x,w,h,I.id??null,I,M.nextContext,S):o.commitStepTransition(x,w,h,I,M.nextContext,S)}}};var Ce=e=>{let t=2166136261;for(let o=0;o<e.length;o+=1)t^=e.charCodeAt(o),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},ae=e=>{let t=new Map,o=new Set;return e.map(p=>{let a=p.event==="completeJourney"?"COMPLETE":p.event==="terminateJourney"?"TERMINATED":String(p.to),n=JSON.stringify({from:p.from,event:p.event,target:a}),s=(t.get(n)??0)+1;t.set(n,s);let r=JSON.stringify({from:p.from,event:p.event,target:a,ordinal:s}),d=0,l=(()=>{let y=Ce(r);for(;o.has(y);)d+=1,y=Ce(`${r}:${d}`);return y})();return o.add(l),{...p,id:l,...p.label!==void 0?{label:p.label}:{}}})},we=e=>{let t=[],{transitions:o}=e;if(o===void 0)return{...e,transitions:ae(t)};if(Array.isArray(o)){if(o.length===0)throw new Error("Journey linear transitions must include the initial step as the first item.");let[n,...s]=o;if(typeof n!="string")throw new Error("Journey linear transitions at index 0 must be a step id string.");if(!(n in e.steps))throw new Error(`Journey linear transitions reference unknown step "${n}".`);let r=e.initial??n;if(e.initial!==void 0&&!o.map(i=>typeof i=="string"?i:i.step).includes(e.initial))throw new Error(`Journey initial step "${e.initial}" does not exist in linear transitions.`);let d=n,l=new Set([n]);for(let[y,i]of s.entries()){let u=y+1;if(typeof i=="string"){if(!(i in e.steps))throw new Error(`Journey linear transitions reference unknown step "${i}".`);if(l.has(i))throw new Error(`Journey linear transitions contain duplicate step "${i}" at index ${u}.`);l.add(i),t.push({from:d,event:"goToNextStep",to:i}),d=i;continue}if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`Journey linear transitions at index ${u} must be a step id string or step config object.`);let E=new Set(["step","label","updateContext","onEnter","onLeave","timeoutMs"]);for(let g of Object.keys(i))if(!E.has(g))throw new Error(`Journey linear transition object at index ${u} contains unsupported field "${g}". Allowed fields are "step", "label", "updateContext", "onEnter", "onLeave", and "timeoutMs".`);if(typeof i.step!="string")throw new Error(`Journey linear transition object at index ${u} must define string "step".`);if(!(i.step in e.steps))throw new Error(`Journey linear transitions reference unknown step "${i.step}".`);if(l.has(i.step))throw new Error(`Journey linear transitions contain duplicate step "${i.step}" at index ${u}.`);if(l.add(i.step),i.updateContext!==void 0&&typeof i.updateContext!="function")throw new Error(`Journey linear transition object at index ${u} must define "updateContext" as a function when provided.`);if(i.onEnter!==void 0&&typeof i.onEnter!="function")throw new Error(`Journey linear transition object at index ${u} must define "onEnter" as a function when provided.`);if(i.onLeave!==void 0&&typeof i.onLeave!="function")throw new Error(`Journey linear transition object at index ${u} must define "onLeave" as a function when provided.`);V(i.timeoutMs,`Journey linear transition object at index ${u}`),t.push({...i.label!==void 0?{label:i.label}:{},...i.timeoutMs!==void 0?{timeoutMs:i.timeoutMs}:{},...i.updateContext!==void 0?{updateContext:i.updateContext}:{},...i.onEnter!==void 0?{onEnter:i.onEnter}:{},...i.onLeave!==void 0?{onLeave:i.onLeave}:{},from:d,event:"goToNextStep",to:i.step}),d=i.step}return{...e,initial:r,transitions:ae(t)}}if(!o||typeof o!="object")throw new Error("Journey transitions must be an array or an object map when provided.");let p=o,a=[...Object.entries(p).filter(([n])=>n!=="global"),...p.global?[["global",p.global]]:[]];for(let[n,s]of a){if(n!=="global"&&!(n in e.steps))throw new Error(`Journey transitions reference unknown step "${n}".`);if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`Journey transitions for "${n}" must be an event map object.`);for(let[r,d]of Object.entries(s)){let l=r==="completeJourney"||r==="terminateJourney",y=l&&(d===!0||Array.isArray(d)&&d.length===0)?[{}]:d;if(!Array.isArray(y))throw new Error(`Journey transitions for "${n}.${r}" must be an array.`);for(let[i,u]of y.entries()){if(!u||typeof u!="object")throw new Error(`Journey transition at "${n}.${r}[${i}]" must be an object.`);let E=new Set(l?["when","updateContext","onEnter","onLeave","label","timeoutMs"]:["to","when","updateContext","onEnter","onLeave","label","timeoutMs"]);for(let g of Object.keys(u))if(!E.has(g))throw new Error(`Journey transition at "${n}.${r}[${i}]" contains unsupported field "${g}".`);if(!l&&typeof u.to!="string")throw new Error(`Journey transition at "${n}.${r}[${i}]" must define string "to".`);if(u.when!==void 0&&typeof u.when!="function")throw new Error(`Journey transition at "${n}.${r}[${i}]" must define "when" as a function when provided.`);if(u.updateContext!==void 0&&typeof u.updateContext!="function")throw new Error(`Journey transition at "${n}.${r}[${i}]" must define "updateContext" as a function when provided.`);if(u.onEnter!==void 0&&typeof u.onEnter!="function")throw new Error(`Journey transition at "${n}.${r}[${i}]" must define "onEnter" as a function when provided.`);if(u.onLeave!==void 0&&typeof u.onLeave!="function")throw new Error(`Journey transition at "${n}.${r}[${i}]" must define "onLeave" as a function when provided.`);if(u.label!==void 0&&typeof u.label!="string")throw new Error(`Journey transition at "${n}.${r}[${i}]" must define "label" as a string when provided.`);V(u.timeoutMs,`Journey transition at "${n}.${r}[${i}]"`),t.push({...u,from:n==="global"?"*":n,event:r})}}}return{...e,transitions:ae(t)}};function je(e,t){if(!e.steps||typeof e.steps!="object")throw new Error("Journey steps must be a record object.");if(e.transitions!==void 0&&(e.transitions===null||typeof e.transitions!="object"&&!Array.isArray(e.transitions)))throw new Error("Journey transitions must be an array or an object map when provided.");for(let T of Object.keys(e.steps))if(T==="*"||T==="global"||T==="COMPLETE"||T==="TERMINATED")throw new Error(`Step id "${T}" is reserved and cannot be used as a step name.`);if(e.initial===void 0&&!Array.isArray(e.transitions))throw new Error('Journey "initial" is required for graph and headless definitions. For linear transitions, initial defaults to the first array element.');j(e.context);let o=we(e);G(o.steps,o.initial,`Journey initial step "${o.initial}" does not exist in steps registry.`),fe(o.transitions,o.steps);let p=t?.requireExplicitCompletion??!1;V(t?.defaultTimeoutMs,"Journey machine options");let a=t?.defaultTimeoutMs,n=B(o.context),s=Object.fromEntries(Object.keys(o.steps).map(T=>[T,se(o.steps[T].meta)])),r=()=>D([o.initial],0,B(n),"idled",Z(o.steps)),d=be({plugins:t?.plugins??[],setupContext:{journey:e,resolvedJourney:o,options:{requireExplicitCompletion:p,defaultTimeoutMs:a},buildInitialSnapshot:r}}),l=d.hydrateSnapshot(r());j(l.context,"Journey hydrated context");let y=t?.onListenerError,i=t?.onLifecycleError,u=ge({snapshot:l,onSnapshotChange:d.onSnapshotChange,onDispose:d.dispose,...y!==void 0?{onListenerError:y}:{}}),E=me({runtime:u}),g=()=>Promise.resolve(k(u.getSnapshot(),!1)),P=({previousSnapshot:T,snapshot:m,from:I,to:M,event:w,transitionId:f,label:v,runVersion:C,transition:R})=>{let A=o.steps[I],L=K(M)?null:o.steps[M],F=o.handlers??{},U=O=>!u.isRunActive(C)||u.isDisposed()?Promise.resolve(k(u.getSnapshot(),!1)):g(O),ne=u.openLifecycle(C);if(!ne)return;let{signal:$}=ne,W=(O,Re)=>{let de={phase:Re,from:I,to:M,eventType:w.type,transitionId:f,...v!==void 0?{label:v}:{}};u.emit({type:"lifecycle.error",...de,error:O,timestamp:b()}),i?.(O,de)};(async()=>{try{if(A?.onLeave)try{await A.onLeave({snapshot:T,context:T.context,from:I,to:M,event:w,transitionId:f,...v!==void 0?{label:v}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"step.onLeave");return}if(!u.isRunActive(C))return;if(R?.onLeave)try{await R.onLeave({snapshot:T,context:T.context,from:I,to:M,event:w,transitionId:f,...R.label!==void 0?{label:R.label}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"transition.onLeave");return}if(!u.isRunActive(C))return;if(L?.onEnter)try{await L.onEnter({snapshot:m,context:m.context,from:I,to:M,event:w,transitionId:f,...v!==void 0?{label:v}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"step.onEnter");return}if(!u.isRunActive(C))return;if(R?.onEnter)try{await R.onEnter({snapshot:m,context:m.context,from:I,to:M,event:w,transitionId:f,...R.label!==void 0?{label:R.label}:{},handlers:F,signal:$,dispatch:U})}catch(O){if($.aborted||!u.isRunActive(C))return;W(O,"transition.onEnter");return}}finally{u.closeLifecycle(ne)}})()},c=Ee({runtime:u,steps:o.steps,transitions:o.transitions,scheduleLifecycle:P}),S=Ie(u,E,c,e.transitions===void 0,o.steps,o.transitions,o.handlers??{},p,a),J=ve({runtime:u,asyncState:E,initial:o.initial,initialContext:n,steps:o.steps}),x=he(e,o,u.getSnapshot),h={getSnapshot:u.getSnapshot,getStepMeta:T=>se(s[T]),getComputed:x,startJourney:J.startJourney,subscribe:u.subscribe,subscribeSelector:u.subscribeSelector,subscribeEvent:u.subscribeEvent,subscribeStart:T=>u.subscribeEvent(m=>{m.type==="journey.start"&&T(m)}),subscribeReset:T=>u.subscribeEvent(m=>{m.type==="journey.reset"&&T(m)}),subscribeComplete:T=>u.subscribeEvent(m=>{m.type==="journey.completed"&&T(m)}),subscribeTerminate:T=>u.subscribeEvent(m=>{m.type==="journey.terminated"&&T(m)}),resetJourney:J.resetJourney,updateContext:J.updateContext,clearStepError:J.clearStepError,dispose:J.dispose,goToPreviousStep:T=>u.queue(async m=>c.applyPreviousNavigation(T,"goToPreviousStep",m),()=>S.buildCanceledSendResult("goToPreviousStep")),goToLastVisitedStep:()=>u.queue(async T=>c.applyLastVisitedNavigation("goToLastVisitedStep",T),()=>S.buildCanceledSendResult("goToLastVisitedStep")),goToNextStep:()=>h.send({type:"goToNextStep"}),goToStepById:T=>h.send({type:"goToStepById",stepId:T}),terminateJourney:T=>T===void 0?h.send({type:"terminateJourney"}):h.send({type:"terminateJourney",payload:T}),completeJourney:T=>T===void 0?h.send({type:"completeJourney"}):h.send({type:"completeJourney",payload:T}),send:T=>u.queue((m,I)=>S.executeSend(T,m,I),()=>S.buildCanceledSendResult(T.type))};return g=h.send,d.extendMachine(h)}function N(e){return{_candidate:e,when(t){return N({...e,_when:t})},updateContext(t){return N({...e,_updateContext:t})},onEnter(t){return N({...e,_onEnter:t})},onLeave(t){return N({...e,_onLeave:t})},label(t){return N({...e,_label:t})},timeoutMs(t){return N({...e,_timeoutMs:t})}}}function Me(e){let t={to:e._to};return e._when!==void 0&&(t.when=e._when),e._updateContext!==void 0&&(t.updateContext=e._updateContext),e._onEnter!==void 0&&(t.onEnter=e._onEnter),e._onLeave!==void 0&&(t.onLeave=e._onLeave),e._label!==void 0&&(t.label=e._label),e._timeoutMs!==void 0&&(t.timeoutMs=e._timeoutMs),t}function Be(e){let t={};return e.when!==void 0&&(t.when=e.when),e.updateContext!==void 0&&(t.updateContext=e.updateContext),e.onEnter!==void 0&&(t.onEnter=e.onEnter),e.onLeave!==void 0&&(t.onLeave=e.onLeave),e.label!==void 0&&(t.label=e.label),e.timeoutMs!==void 0&&(t.timeoutMs=e.timeoutMs),t}function De(){function e(n){return N({_to:n,_when:void 0,_updateContext:void 0,_onEnter:void 0,_onLeave:void 0,_label:void 0,_timeoutMs:void 0})}function t(n){return typeof n=="function"?n({to:e}):n}function o(n){return n===!0||n.length===0?n:n.map(s=>Be(s))}function p(n,s){return{id:n,_meta:s?.meta,_onEnter:s?.onEnter,_onLeave:s?.onLeave,_on:s?.on}}function a(n){let s={},r={};for(let d of n.steps)if(s[d.id]={...d._meta!==void 0?{meta:d._meta}:{},...d._onEnter!==void 0?{onEnter:d._onEnter}:{},...d._onLeave!==void 0?{onLeave:d._onLeave}:{}},d._on){let l={};for(let[y,i]of Object.entries(d._on)){if(!i)continue;if(y==="completeJourney"||y==="terminateJourney"){l[y]=o(i);continue}let u=t(i);l[y]=u.map(E=>Me(E._candidate))}r[d.id]=l}if(n.global){let d={};for(let[l,y]of Object.entries(n.global))y!==void 0&&(l==="completeJourney"||l==="terminateJourney"?d[l]=o(y):Array.isArray(y)&&(d[l]=y.map(i=>Me(i._candidate))));r.global=d}return{initial:n.initial,context:n.context,...n.handlers!==void 0?{handlers:n.handlers}:{},steps:s,transitions:r}}return{createStep:p,to:e,build:a}}export{q as JourneyDisposedError,De as createJourneyBuilder,je as createJourneyMachine};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|