@rxova/journey-core 1.0.0-rc.2 → 1.0.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/README.md +182 -186
- package/dist/connectors/immer/immer.cjs +2 -0
- package/dist/connectors/immer/immer.cjs.map +7 -0
- package/dist/connectors/immer/immer.d.cts +11 -0
- package/dist/connectors/immer/immer.d.ts +11 -0
- package/dist/connectors/immer/immer.js +2 -0
- package/dist/connectors/immer/immer.js.map +7 -0
- package/dist/connectors/immer/immer.types.d.cts +9 -0
- package/dist/connectors/immer/immer.types.d.ts +9 -0
- package/dist/core/errors.d.cts +57 -0
- package/dist/core/errors.d.ts +57 -0
- package/dist/core/helpers.d.cts +46 -0
- package/dist/core/helpers.d.ts +46 -0
- package/dist/core/machine.d.cts +9 -0
- package/dist/core/machine.d.ts +9 -0
- package/dist/core/runtime.d.cts +115 -0
- package/dist/core/runtime.d.ts +115 -0
- package/dist/core/runtime.types.d.cts +112 -0
- package/dist/core/runtime.types.d.ts +112 -0
- package/dist/core/store.d.cts +31 -0
- package/dist/core/store.d.ts +31 -0
- package/dist/core/types.d.cts +481 -0
- package/dist/core/types.d.ts +481 -0
- package/dist/diagnostics/diagnostics.helpers.d.cts +17 -0
- package/dist/diagnostics/diagnostics.helpers.d.ts +17 -0
- package/dist/diagnostics/diagnostics.types.d.cts +22 -0
- package/dist/diagnostics/diagnostics.types.d.ts +22 -0
- package/dist/graph/bag.types.d.cts +91 -0
- package/dist/graph/bag.types.d.ts +91 -0
- package/dist/graph/graph.d.cts +63 -0
- package/dist/graph/graph.d.ts +63 -0
- package/dist/graph/graph.types.d.cts +212 -0
- package/dist/graph/graph.types.d.ts +212 -0
- package/dist/graph/work.d.cts +81 -0
- package/dist/graph/work.d.ts +81 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.cts +13 -5
- package/dist/index.d.ts +13 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/linear/linear.d.cts +33 -0
- package/dist/linear/linear.d.ts +33 -0
- package/dist/linear/linear.types.d.cts +28 -0
- package/dist/linear/linear.types.d.ts +28 -0
- package/dist/plugins/analytics/analytics.d.cts +8 -0
- package/dist/plugins/analytics/analytics.d.ts +8 -0
- package/dist/plugins/analytics/analytics.helpers.d.cts +2 -0
- package/dist/plugins/analytics/analytics.helpers.d.ts +2 -0
- package/dist/plugins/analytics/analytics.types.d.cts +27 -0
- package/dist/plugins/analytics/analytics.types.d.ts +27 -0
- package/dist/plugins/execution-paths/execution-paths.d.cts +7 -4
- package/dist/plugins/execution-paths/execution-paths.d.ts +7 -4
- package/dist/plugins/execution-paths/execution-paths.types.d.cts +21 -0
- package/dist/plugins/execution-paths/execution-paths.types.d.ts +21 -0
- package/dist/plugins/index.cjs +2 -0
- package/dist/plugins/index.cjs.map +7 -0
- package/dist/plugins/index.d.cts +19 -0
- package/dist/plugins/index.d.ts +19 -0
- package/dist/plugins/index.js +2 -0
- package/dist/plugins/index.js.map +7 -0
- package/dist/plugins/persistence/persistence.d.cts +16 -0
- package/dist/plugins/persistence/persistence.d.ts +16 -0
- package/dist/plugins/persistence/persistence.helpers.d.cts +34 -0
- package/dist/plugins/persistence/persistence.helpers.d.ts +34 -0
- package/dist/plugins/persistence/persistence.types.d.cts +63 -0
- package/dist/plugins/persistence/persistence.types.d.ts +63 -0
- package/dist/plugins/replay/replay.d.cts +7 -0
- package/dist/plugins/replay/replay.d.ts +7 -0
- package/dist/plugins/replay/replay.helpers.d.cts +22 -0
- package/dist/plugins/replay/replay.helpers.d.ts +22 -0
- package/dist/plugins/replay/replay.types.d.cts +28 -0
- package/dist/plugins/replay/replay.types.d.ts +28 -0
- package/package.json +78 -79
- package/dist/journey-builder/index.d.cts +0 -5
- package/dist/journey-builder/index.d.ts +0 -5
- package/dist/journey-builder/types.d.cts +0 -126
- package/dist/journey-builder/types.d.ts +0 -126
- package/dist/journey-machine/async-state.d.cts +0 -12
- package/dist/journey-machine/async-state.d.ts +0 -12
- package/dist/journey-machine/computed.d.cts +0 -2
- package/dist/journey-machine/computed.d.ts +0 -2
- package/dist/journey-machine/controls.d.cts +0 -17
- package/dist/journey-machine/controls.d.ts +0 -17
- package/dist/journey-machine/helpers.d.cts +0 -52
- package/dist/journey-machine/helpers.d.ts +0 -52
- package/dist/journey-machine/index.d.cts +0 -3
- package/dist/journey-machine/index.d.ts +0 -3
- package/dist/journey-machine/navigation.d.cts +0 -32
- package/dist/journey-machine/navigation.d.ts +0 -32
- package/dist/journey-machine/plugin-controller.d.cts +0 -15
- package/dist/journey-machine/plugin-controller.d.ts +0 -15
- package/dist/journey-machine/resolve-journey-definition.d.cts +0 -2
- package/dist/journey-machine/resolve-journey-definition.d.ts +0 -2
- package/dist/journey-machine/runtime.d.cts +0 -33
- package/dist/journey-machine/runtime.d.ts +0 -33
- package/dist/journey-machine/send.d.cts +0 -9
- package/dist/journey-machine/send.d.ts +0 -9
- package/dist/plugins/analytics/index.cjs +0 -2
- package/dist/plugins/analytics/index.cjs.map +0 -7
- package/dist/plugins/analytics/index.d.cts +0 -25
- package/dist/plugins/analytics/index.d.ts +0 -25
- package/dist/plugins/analytics/index.js +0 -2
- package/dist/plugins/analytics/index.js.map +0 -7
- package/dist/plugins/autosave/index.cjs +0 -2
- package/dist/plugins/autosave/index.cjs.map +0 -7
- package/dist/plugins/autosave/index.d.cts +0 -17
- package/dist/plugins/autosave/index.d.ts +0 -17
- package/dist/plugins/autosave/index.js +0 -2
- package/dist/plugins/autosave/index.js.map +0 -7
- package/dist/plugins/diagnostics/diagnostics.d.cts +0 -3
- package/dist/plugins/diagnostics/diagnostics.d.ts +0 -3
- package/dist/plugins/diagnostics/index.cjs +0 -2
- package/dist/plugins/diagnostics/index.cjs.map +0 -7
- package/dist/plugins/diagnostics/index.d.cts +0 -15
- package/dist/plugins/diagnostics/index.d.ts +0 -15
- package/dist/plugins/diagnostics/index.js +0 -2
- package/dist/plugins/diagnostics/index.js.map +0 -7
- package/dist/plugins/execution-paths/index.cjs +0 -2
- package/dist/plugins/execution-paths/index.cjs.map +0 -7
- package/dist/plugins/execution-paths/index.d.cts +0 -18
- package/dist/plugins/execution-paths/index.d.ts +0 -18
- package/dist/plugins/execution-paths/index.js +0 -2
- package/dist/plugins/execution-paths/index.js.map +0 -7
- package/dist/plugins/persistence/controller.d.cts +0 -17
- package/dist/plugins/persistence/controller.d.ts +0 -17
- package/dist/plugins/persistence/index.cjs +0 -2
- package/dist/plugins/persistence/index.cjs.map +0 -7
- package/dist/plugins/persistence/index.d.cts +0 -12
- package/dist/plugins/persistence/index.d.ts +0 -12
- package/dist/plugins/persistence/index.js +0 -2
- package/dist/plugins/persistence/index.js.map +0 -7
- package/dist/plugins/replay/index.cjs +0 -2
- package/dist/plugins/replay/index.cjs.map +0 -7
- package/dist/plugins/replay/index.d.cts +0 -27
- package/dist/plugins/replay/index.d.ts +0 -27
- package/dist/plugins/replay/index.js +0 -2
- package/dist/plugins/replay/index.js.map +0 -7
- package/dist/types/analytics.types.d.cts +0 -33
- package/dist/types/analytics.types.d.ts +0 -33
- package/dist/types/autosave.types.d.cts +0 -23
- package/dist/types/autosave.types.d.ts +0 -23
- package/dist/types/diagnostics.types.d.cts +0 -38
- package/dist/types/diagnostics.types.d.ts +0 -38
- package/dist/types/index.d.cts +0 -9
- package/dist/types/index.d.ts +0 -9
- package/dist/types/journey.types.d.cts +0 -191
- package/dist/types/journey.types.d.ts +0 -191
- package/dist/types/machine.types.d.cts +0 -104
- package/dist/types/machine.types.d.ts +0 -104
- package/dist/types/observation.types.d.cts +0 -83
- package/dist/types/observation.types.d.ts +0 -83
- package/dist/types/persistence.types.d.cts +0 -34
- package/dist/types/persistence.types.d.ts +0 -34
- package/dist/types/replay.types.d.cts +0 -35
- package/dist/types/replay.types.d.ts +0 -35
- package/dist/types/transitions.types.d.cts +0 -122
- package/dist/types/transitions.types.d.ts +0 -122
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export {
|
|
3
|
-
export {
|
|
4
|
-
export type {
|
|
5
|
-
export {
|
|
1
|
+
export { createLinearJourney, withLinearTypes } from "./linear/linear.js";
|
|
2
|
+
export type { CompletePayloadOf, JourneyTerminationPayloads, LinearJourneyDefinition, LinearJourneyMachine, LinearStepConfig, LinearStepIdOf, LinearStepInput, TerminatePayloadOf } from "./linear/linear.types.js";
|
|
3
|
+
export { createGraphJourney, withGraphTypes } from "./graph/graph.js";
|
|
4
|
+
export type { GraphHookArgs, GraphJourneyDefinition, GraphJourneyMachine, GraphJourneyOptions, GraphOnEntry, GraphStepConfig, GraphTransition, SendArgs, SendVerb, SendWork, SendWorkArgs, TransitionGuard } from "./graph/graph.types.js";
|
|
5
|
+
export { defineWork } from "./graph/work.js";
|
|
6
|
+
export type { WorkConfig } from "./graph/work.js";
|
|
7
|
+
export type { Bag, GraphDefinition, GraphStep, HandlersOf, MetaOf, ResultOf, ResultsOf } from "./graph/bag.types.js";
|
|
8
|
+
export { analyzeStructure } from "./diagnostics/diagnostics.helpers.js";
|
|
9
|
+
export type { DiagnosticsIssue, DiagnosticsResult } from "./diagnostics/diagnostics.types.js";
|
|
10
|
+
export { JourneyError, isJourneyError } from "./core/errors.js";
|
|
11
|
+
export type { JourneyErrorCode, JourneyErrorDetails } from "./core/errors.js";
|
|
12
|
+
export type { AnyJourneyPlugin, ContextUpdater, CurrentStepBase, GraphGuardState, GraphSnapshot, GraphTransitionSnapshot, JourneyControls, JourneyEventObject, JourneyEventPayload, JourneyEventPayloads, JourneyHistoryState, JourneyMachineBase, JourneyNavigation, JourneyOutcome, JourneyPersistOption, JourneyPlugin, JourneyRuntimeOptions, JourneySnapshot, JourneySnapshotBase, JourneyStatus, JourneyStructure, JourneySubscriptionEvent, JourneySubscriptions, LinearSnapshot, MachineState, NavigationFailureReason, NavigationDirection, NavigationResult, StepEnterDirection, NavigationWork, NavigationWorkArgs, OnEnterHook, OnLeaveHook, PluginApis, PluginHost, StepAsyncState, StepHookArgs, TransitionInfo, TransitionState, Unsubscribe } from "./core/types.js";
|
|
13
|
+
export type { JourneyStorage } from "./plugins/persistence/persistence.types.js";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export {
|
|
3
|
-
export {
|
|
4
|
-
export type {
|
|
5
|
-
export {
|
|
1
|
+
export { createLinearJourney, withLinearTypes } from "./linear/linear.js";
|
|
2
|
+
export type { CompletePayloadOf, JourneyTerminationPayloads, LinearJourneyDefinition, LinearJourneyMachine, LinearStepConfig, LinearStepIdOf, LinearStepInput, TerminatePayloadOf } from "./linear/linear.types.js";
|
|
3
|
+
export { createGraphJourney, withGraphTypes } from "./graph/graph.js";
|
|
4
|
+
export type { GraphHookArgs, GraphJourneyDefinition, GraphJourneyMachine, GraphJourneyOptions, GraphOnEntry, GraphStepConfig, GraphTransition, SendArgs, SendVerb, SendWork, SendWorkArgs, TransitionGuard } from "./graph/graph.types.js";
|
|
5
|
+
export { defineWork } from "./graph/work.js";
|
|
6
|
+
export type { WorkConfig } from "./graph/work.js";
|
|
7
|
+
export type { Bag, GraphDefinition, GraphStep, HandlersOf, MetaOf, ResultOf, ResultsOf } from "./graph/bag.types.js";
|
|
8
|
+
export { analyzeStructure } from "./diagnostics/diagnostics.helpers.js";
|
|
9
|
+
export type { DiagnosticsIssue, DiagnosticsResult } from "./diagnostics/diagnostics.types.js";
|
|
10
|
+
export { JourneyError, isJourneyError } from "./core/errors.js";
|
|
11
|
+
export type { JourneyErrorCode, JourneyErrorDetails } from "./core/errors.js";
|
|
12
|
+
export type { AnyJourneyPlugin, ContextUpdater, CurrentStepBase, GraphGuardState, GraphSnapshot, GraphTransitionSnapshot, JourneyControls, JourneyEventObject, JourneyEventPayload, JourneyEventPayloads, JourneyHistoryState, JourneyMachineBase, JourneyNavigation, JourneyOutcome, JourneyPersistOption, JourneyPlugin, JourneyRuntimeOptions, JourneySnapshot, JourneySnapshotBase, JourneyStatus, JourneyStructure, JourneySubscriptionEvent, JourneySubscriptions, LinearSnapshot, MachineState, NavigationFailureReason, NavigationDirection, NavigationResult, StepEnterDirection, NavigationWork, NavigationWorkArgs, OnEnterHook, OnLeaveHook, PluginApis, PluginHost, StepAsyncState, StepHookArgs, TransitionInfo, TransitionState, Unsubscribe } from "./core/types.js";
|
|
13
|
+
export type { JourneyStorage } from "./plugins/persistence/persistence.types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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};
|
|
1
|
+
var m=class extends Error{constructor(e,t,r={},s){super(`journey: ${t}`,s===void 0?void 0:{cause:s}),this.name="JourneyError",this.code=e,this.stepId=r.stepId,this.event=r.event,this.pluginName=r.pluginName}},re=n=>n instanceof m;var R=(n,e)=>`${n.length}:${n}${e}`,H=n=>n.label??`${n.event}[${n.index}] (${n.from} -> ${n.to})`,F=n=>n===null?null:{event:n.event,from:n.from,to:n.to,label:n.label??null,index:n.index},x=Object.freeze({isLoading:!1,isSuccess:!0,isError:!1,error:null}),A=Object.freeze({isLoading:!0,isSuccess:!1,isError:!1,error:null}),S=(n,e)=>Object.hasOwn(n,e);function j(n){console.error("[journey] subscriber threw:",n)}var E=(n,e)=>{let t=Object.keys(n);return t.length!==Object.keys(e).length?!1:t.every(r=>S(e,r)&&Object.is(n[r],e[r]))};function C(n){return{getSnapshot:()=>n.store.getSnapshot(),controls:{start:()=>n.start(),pause:()=>n.pause(),resume:()=>n.resume(),complete:e=>n.complete(e),terminate:e=>n.terminate(e),restart:()=>n.restart()},dispose:()=>n.dispose(),navigate:{goToStepById:e=>n.goToStepById(e),goToPreviousStep:e=>n.goToPreviousStep(e),goToNextStep:e=>n.goToNextStep(e),goToLastVisitedStep:()=>n.goToLastVisitedStep()},subscriptions:{subscribe:e=>n.store.subscribe(e),subscribeEvent:(e,t)=>n.store.subscribeEvent(e,t)},context:{update:e=>n.updateContext(e)},async:{clearError:()=>n.clearAsyncError()},plugins:n.pluginApis}}var D=()=>{let n=globalThis;if(typeof n.__DEV__=="boolean")return n.__DEV__;let e=n.process?.env?.NODE_ENV;return e===void 0||e==="development"},V=(n,e)=>{if(!(!D()||typeof console>"u")){if(e===void 0){console.warn(n);return}console.warn("%s",n,e)}};var N=class{constructor(e,t){this.listeners=new Set;this.eventListeners=new Map;this.disposed=!1;this.snapshot=e,this.onListenerError=t}report(e){if(!this.onListenerError){j(e);return}try{this.onListenerError(e)}catch(t){j(t)}}getSnapshot(){return this.snapshot}publish(e){if(!Object.is(this.snapshot,e)){this.snapshot=e;for(let t of[...this.listeners])try{t()}catch(r){this.report(r)}}}subscribe(e){return this.disposed?()=>{}:(this.listeners.add(e),()=>{this.listeners.delete(e)})}subscribeEvent(e,t){if(this.disposed)return()=>{};let r=this.eventListeners.get(e);return r||(r=new Set,this.eventListeners.set(e,r)),r.add(t),()=>{r.delete(t)}}emit(e,t){let r=this.eventListeners.get(e);if(r)for(let s of[...r])try{s(t)}catch(a){this.report(a)}}dispose(){this.disposed=!0,this.listeners.clear(),this.eventListeners.clear()}};var B=n=>typeof n=="object"&&n!==null&&D()?Object.freeze(n):n,se=Object.freeze({}),Y=Object.freeze({}),w=(n,e)=>e!=null&&E(n,e)?e:Object.freeze(n),I=(n,e,t=Object.is)=>e!==void 0&&e.length===n.length&&n.every((r,s)=>t(r,e[s]))?e:Object.freeze([...n]),ie=(n,e)=>n===void 0?"none":e?"passed":"failed",P=class{constructor(e){this.pluginApis={};this.status="idle";this.timeline=[];this.currentIndex=-1;this.outcome=null;this.visitCounts=new Map;this.entryAsync=x;this.pending=null;this.disposed=!1;this.restoreSeed=null;this.generation=0;this.raiseQueue=[];this.processingRaised=!1;this.lastPluginExtensions={};this.lastSnapshot=null;this.transitionListeners=new Set;this.disposeCallbacks=[];this.snapshotDerivers=new Map;this.config=e,this.frozenStepOrder=Object.freeze([...e.stepIds]),this.restoreSeed=e.restore??null,this.context=B(e.restore?e.restore.context:e.initialContext),this.store=new N(this.buildSnapshot(),e.onListenerError),this.setupPlugins(),this.store.publish(this.buildSnapshot()),e.autoStart&&this.start()}start(){return this.disposed||this.status!=="idle"?!1:(this.setStatus("running"),this.enterInitialStep(),!0)}pause(){return this.disposed||this.status!=="running"||this.pending?!1:(this.setStatus("paused"),!0)}resume(){return this.disposed||this.status!=="paused"?!1:(this.setStatus("running"),!0)}complete(e){return this.disposed||this.status!=="running"||this.pending?!1:(this.outcome=Object.freeze({type:"completed",payload:e}),this.setStatus("completed"),!0)}terminate(e){return this.disposed||this.status==="terminated"?!1:(this.generation+=1,this.pending=null,this.entryAsync=x,this.raiseQueue=[],this.outcome=Object.freeze({type:"terminated",payload:e}),this.setStatus("terminated"),!0)}restart(){return this.disposed||this.status!=="completed"&&this.status!=="terminated"?!1:(this.generation+=1,this.pending=null,this.raiseQueue=[],this.timeline=[],this.currentIndex=-1,this.context=B(this.config.initialContext),this.outcome=null,this.visitCounts=new Map,this.entryAsync=x,this.setStatus("running"),this.enterInitialStep(),!0)}dispose(){if(!this.disposed){this.disposed=!0,this.generation+=1,this.pending=null,this.raiseQueue=[];for(let e of this.disposeCallbacks.splice(0))try{e()}catch{}this.transitionListeners.clear(),this.store.dispose()}}updateContext(e){if(this.disposed)return;let t=this.context;this.context=B(e(t));let r=this.publish();this.store.emit("contextChange",{snapshot:r,previous:t,current:this.context})}clearAsyncError(){this.disposed||!this.entryAsync.isError||(this.entryAsync=x,this.publish())}goToStepById(e){let t=this.checkNavigable();if(t)return this.blocked(t,e);if(!S(this.config.steps,e))return this.blocked({ok:!1,reason:"invalid-target"},e);if(e===this.currentStepId())return this.blocked({ok:!1,reason:"no-op"},e);if(this.config.kind==="graph"){let r=this.config.transitions.find(s=>s.from===this.currentStepId()&&s.to===e&&this.isEnabled(s));return r?this.runNavigation(e,{kind:"append"},this.eventFor(r),r):this.blocked({ok:!1,reason:"invalid-target"},e)}return this.runNavigation(e,{kind:"append"},null,null)}goToPreviousStep(e=1){let t=this.checkNavigable();if(t)return this.blocked(t,null);if(this.currentIndex<=0)return this.blocked({ok:!1,reason:"out-of-bounds"},null);let r=Math.max(0,this.currentIndex-Math.max(1,Math.floor(e))),s=this.timeline[r];return this.runNavigation(s,{kind:"pointer",index:r},null,null,void 0,"backward")}goToNextStep(e){let t=this.checkNavigable();if(t)return this.blocked(t,null);if(this.currentIndex<this.timeline.length-1){let r=this.currentIndex+1,s=this.timeline[r];return this.runNavigation(s,{kind:"pointer",index:r},null,null,e,"forward")}if(this.config.kind==="linear"){let r=this.config.stepIds.indexOf(this.currentStepId()??""),s=this.config.stepIds[r+1];return s===void 0?this.blocked({ok:!1,reason:"out-of-bounds"},null):this.runNavigation(s,{kind:"append"},null,null,e,"forward")}return this.blocked({ok:!1,reason:"out-of-bounds"},null)}goToLastVisitedStep(){let e=this.checkNavigable();if(e)return this.blocked(e,null);let t=this.timeline.length-1;if(this.currentIndex>=t)return this.blocked({ok:!1,reason:"no-op"},null);let r=this.timeline[t];return this.runNavigation(r,{kind:"pointer",index:t},null,null)}goToStepByIndex(e){let t=Number.isInteger(e)?this.config.stepIds[e]:void 0;return t===void 0?this.blocked({ok:!1,reason:"invalid-target"},null):this.goToStepById(t)}send(e,t,r){let s=this.checkNavigable();if(s)return this.blocked(s,null);let a=t===void 0?{type:e}:{type:e,payload:t},u=this.currentStepId(),o=r??(u===null?void 0:this.config.eventWork?.[R(u,e)]);if(o)return this.sendWithWork(e,a,o);let i=this.resolveTransition(e);return i?this.runNavigation(i.to,{kind:"append"},a,i):this.blocked({ok:!1,reason:"no-enabled-transition"},null)}async sendWithWork(e,t,r){let s=this.generation,a=this.currentStepId();if(a===null)return this.blocked({ok:!1,reason:"not-running"},null);let u=this.context,o=!1,i;this.pending={phase:"working",from:a,to:null},this.entryAsync=A,this.publish();try{let d={snapshot:this.store.getSnapshot(),from:a,event:t,handlers:this.config.handlers};if(i=await this.withTimeout(Promise.resolve(r.run(d)),`send work(${r.label??`${e} from ${a}`})`,r.timeoutMs),!this.isCurrent(s))return this.staleResult();let c=r.commit?.({...d,result:i,updateContext:h=>{u=h(u),o=!0}});if(typeof c=="object"&&c!==null&&"then"in c)throw new m("async-commit","send work commit must be synchronous")}catch(d){if(!this.isCurrent(s))return this.staleResult();this.pending=null,this.entryAsync=Object.freeze({isLoading:!1,isSuccess:!1,isError:!0,error:d});let c=this.publish();return this.store.emit("error",{snapshot:c,error:d,phase:"work",stepId:a}),this.blocked({ok:!1,reason:"error",error:d},null)}if(!this.isCurrent(s))return this.staleResult();let l=this.resolveTransition(e,u,i);return l?this.commitAndSettle(a,l.to,{kind:"append"},t,l,s,u,o,"jump"):(this.pending=null,this.entryAsync=x,this.publish(),this.blocked({ok:!1,reason:"no-enabled-transition"},null))}setupPlugins(){let e={getSnapshot:()=>this.store.getSnapshot(),structure:Object.freeze({kind:this.config.kind,stepIds:Object.freeze([...this.config.stepIds]),initial:this.config.initial,transitions:Object.freeze(this.config.transitions.map(t=>Object.freeze({event:t.event,from:t.from,to:t.to,guarded:t.when!==void 0,label:t.label??null,index:t.index})))}),onTransition:t=>(this.transitionListeners.add(t),()=>this.transitionListeners.delete(t)),onNavigationBlocked:t=>this.store.subscribeEvent("navigationBlocked",t),onStatusChange:t=>this.store.subscribeEvent("statusChange",t),onContextChange:t=>this.store.subscribeEvent("contextChange",t),onError:t=>this.store.subscribeEvent("error",t),onDispose:t=>{this.disposeCallbacks.push(t)},reportError:t=>this.store.report(t)};try{for(let t of this.config.plugins){if(S(this.pluginApis,t.name))throw new m("duplicate-plugin-name",`duplicate plugin name "${t.name}"`,{pluginName:t.name});let r=t.setup(e);this.pluginApis[t.name]=r.api,r.deriveSnapshot&&this.snapshotDerivers.set(t.name,r.deriveSnapshot)}}catch(t){throw this.dispose(),t}}currentStepId(){return this.currentIndex>=0?this.timeline[this.currentIndex]:null}eventFor(e){return{type:e.event}}isEnabled(e,t=this.context,r){if(!e.when)return!0;try{return e.when({context:t,handlers:this.config.handlers,result:r})}catch{return!1}}resolveTransition(e,t=this.context,r){return this.config.transitions.find(s=>s.event===e&&s.from===this.currentStepId()&&this.isEnabled(s,t,r))}checkNavigable(){return this.disposed?{ok:!1,reason:"disposed"}:this.status!=="running"?{ok:!1,reason:"not-running"}:this.pending?{ok:!1,reason:"transitioning"}:null}setStatus(e){let t=this.status;this.status=e;let r=this.publish();this.store.emit("statusChange",{snapshot:r,previous:t,current:e}),this.refreshPluginSnapshot()}refreshPluginSnapshot(){this.snapshotDerivers.size>0&&this.publish()}blocked(e,t){if(e.reason!=="disposed"){let r={snapshot:this.store.getSnapshot(),reason:e.reason,from:this.currentStepId(),to:t};"error"in e&&(r.error=e.error),this.store.emit("navigationBlocked",r)}return Promise.resolve({...e,from:this.currentStepId(),to:t})}hookArgs(e,t,r,s){return{snapshot:this.store.getSnapshot(),from:e,to:t,event:r,transition:s,updateContext:a=>this.updateContext(a),raise:a=>{this.config.kind!=="graph"||this.disposed||this.raiseQueue.push(a)}}}async invokeEffect(e,t,r,s){if(!e)return null;try{return await this.withTimeout(Promise.resolve(e(t)),r,s),null}catch(a){return{error:a}}}withTimeout(e,t,r){let s=r??this.config.defaultTimeoutMs;return s===void 0?e:new Promise((a,u)=>{let o=setTimeout(()=>u(new Error(`journey: ${t} timed out after ${s}ms`)),s);e.then(i=>{clearTimeout(o),a(i)},i=>{clearTimeout(o),u(i)})})}async enterInitialStep(){let e=this.generation,t=this.restoreSeed;if(this.restoreSeed=null,t){let s=t.timeline[t.currentIndex];this.pending={phase:"entering",from:null,to:s},this.timeline=[...t.timeline],this.currentIndex=t.currentIndex;for(let a of t.timeline)this.visitCounts.set(a,(this.visitCounts.get(a)??0)+1);this.commitEntry(null,s,"jump"),await this.runEntryEffects(null,s,null,null,e);return}let r=this.config.startAt??this.config.initial;this.pending={phase:"entering",from:null,to:r},this.timeline=[r],this.currentIndex=0,this.commitEntry(null,r,"jump"),await this.runEntryEffects(null,r,null,null,e)}async runNavigation(e,t,r,s,a,u){let o=this.generation,i=this.currentStepId(),l=this.context,d=!1;if(a&&i!==null&&u){this.pending={phase:"working",from:i,to:e},this.entryAsync=A,this.publish();try{let c={snapshot:this.store.getSnapshot(),from:i,to:e,direction:u},h=await this.withTimeout(Promise.resolve(a.run(c)),`${u} navigation work(${i} -> ${e})`,a.timeoutMs);if(!this.isCurrent(o))return this.staleResult();let f=a.commit?.({...c,result:h,updateContext:y=>{l=y(l),d=!0}});if(typeof f=="object"&&f!==null&&"then"in f)throw new m("async-commit","navigation work commit must be synchronous")}catch(c){if(!this.isCurrent(o))return this.staleResult();this.pending=null,this.entryAsync=Object.freeze({isLoading:!1,isSuccess:!1,isError:!0,error:c});let h=this.publish();return this.store.emit("error",{snapshot:h,error:c,phase:"work",stepId:i}),this.blocked({ok:!1,reason:"error",error:c},e)}}return this.isCurrent(o)?this.commitAndSettle(i,e,t,r,s,o,l,d,u??"jump"):this.staleResult()}async commitAndSettle(e,t,r,s,a,u,o,i,l){let d=this.context;r.kind==="pointer"?this.currentIndex=r.index:(this.timeline=[...this.timeline.slice(0,this.currentIndex+1),t],this.currentIndex=this.timeline.length-1),i&&(this.context=B(o));let c=e===null?void 0:this.config.steps[e];return this.pending={phase:c?.onLeave?"leaving":"entering",from:e,to:t},this.commitEntry(e,t,l,i?{previous:d,current:o}:void 0,c?.onLeave!==void 0||a?.onTransition!==void 0),await this.runEntryEffects(e,t,s,a,u),{ok:!0,from:e,to:t}}commitEntry(e,t,r,s,a=!1){this.visitCounts.set(t,(this.visitCounts.get(t)??0)+1);let u=this.config.steps[t];this.entryAsync=a||u?.onEnter?A:x;let o=this.publish();s&&this.store.emit("contextChange",{snapshot:o,...s}),e!==null&&this.store.emit("stepLeave",{snapshot:o,from:e,to:t}),this.store.emit("stepEnter",{snapshot:o,from:e,to:t,direction:r})}async runEntryEffects(e,t,r,s,a){let u=e===null?void 0:this.config.steps[e],o=this.config.steps[t],i=F(s),l=[],d=await this.invokeEffect(u?.onLeave,this.hookArgs(e,t,r,i),`onLeave(${e??""})`);if(!this.isCurrent(a))return;d&&e!==null&&l.push({error:d.error,phase:"leave",stepId:e}),this.pending={phase:"entering",from:e,to:t},this.publish();let c=await this.invokeEffect(s?.onTransition,this.hookArgs(e,t,r,i),`onTransition(${s?H(s):r?.type??""})`,s?.timeoutMs);if(!this.isCurrent(a))return;c&&l.push({error:c.error,phase:"transition",stepId:t});let h=await this.invokeEffect(o?.onEnter,this.hookArgs(e,t,r,i),`onEnter(${t})`);if(!this.isCurrent(a))return;h&&l.push({error:h.error,phase:"enter",stepId:t}),this.entryAsync=l[0]?Object.freeze({isLoading:!1,isSuccess:!1,isError:!0,error:l[0].error}):x,this.pending=null;let f=this.publish();for(let y of l)this.store.emit("error",{snapshot:f,error:y.error,phase:y.phase,stepId:y.stepId});for(let y of[...this.transitionListeners])try{y({from:e,to:t,snapshot:f})}catch{}this.refreshPluginSnapshot(),this.processRaisedEvents(a)}async processRaisedEvents(e){if(this.processingRaised||!this.isCurrent(e))return;this.processingRaised=!0;let t=0;try{for(;this.raiseQueue.length>0&&this.isCurrent(e);){if(this.status!=="running"){this.raiseQueue=[];return}if(t+=1,t>25){this.raiseQueue=[],this.store.emit("error",{snapshot:this.store.getSnapshot(),error:new Error(`journey: raised-event cascade exceeded ${25} events; queue dropped`),phase:"raise",stepId:this.currentStepId()});return}let r=this.raiseQueue.shift();await this.send(r.type,r.payload)}}finally{this.processingRaised=!1}}isCurrent(e){return!this.disposed&&e===this.generation}staleResult(){let e=this.currentStepId();return this.disposed?{ok:!1,reason:"disposed",from:e,to:null}:{ok:!1,reason:"not-running",from:e,to:null}}publish(){let e=this.buildSnapshot();return this.store.publish(e),e}buildSnapshot(){let e=this.lastSnapshot,t=this.currentStepId(),r={},s=0;for(let h of this.config.stepIds){let f=(this.visitCounts.get(h)??0)>0;r[h]=f,f&&(s+=1)}let a=e?.history,u=a!=null&&E(a.visited,r)?a.visited:Object.freeze(r),o={status:this.status,context:this.context,transition:w({pending:this.pending!==null,phase:this.pending?.phase??null,from:this.pending?.from??null,to:this.pending?.to??null},e?.transition),history:w({timeline:I(this.timeline,a?.timeline),currentIndex:this.currentIndex,visited:u,canGoBack:this.currentIndex>0,canGoForward:this.currentIndex>=0&&this.currentIndex<this.timeline.length-1},a),machine:w({outcome:this.outcome},e?.machine)},i=t===null?null:{id:t,metadata:this.config.steps[t]?.metadata??se,isFirstTimeVisit:(this.visitCounts.get(t)??0)===1,async:this.entryAsync},l;if(this.config.kind==="linear"){let h=e?.type==="linear"?e:null,f=t===null?-1:this.config.stepIds.indexOf(t);l={...o,type:"linear",currentStep:i===null?null:w({...i,index:f,isFirstStep:f===0,isLastStep:f===this.config.stepIds.length-1},h?.currentStep),steps:w({totalSteps:this.config.stepIds.length,stepOrder:this.frozenStepOrder,visitedStepCount:s},h?.steps),plugins:Y}}else{let h=[],f=[],y=[],g=[],p=new Map,T=new Set,b=!1;if(t!==null)for(let v of this.config.transitions){if(v.from!==t)continue;b=!0,h.includes(v.event)||h.push(v.event);let J=p.get(v.event)??0;p.set(v.event,J+1);let O=this.isEnabled(v),U=O&&!T.has(v.event);U&&T.add(v.event),g.push(Object.freeze({event:v.event,to:v.to,priority:J,guard:ie(v.when,O),enabled:O,selected:U})),O&&(f.includes(v.event)||f.push(v.event),y.includes(v.to)||y.push(v.to))}let k=e?.type==="graph"?e:null;l={...o,type:"graph",currentStep:i===null?null:w({...i,isTerminal:!b},k?.currentStep),steps:w({totalSteps:this.config.stepIds.length,visitedStepCount:s},k?.steps),declaredEvents:I(h,k?.declaredEvents),availableEvents:I(f,k?.availableEvents),availableSteps:I(y,k?.availableSteps),outgoingTransitions:I(g,k?.outgoingTransitions,(v,J)=>E(v,J)),plugins:Y}}if(this.snapshotDerivers.size>0){let h={};for(let[y,g]of this.snapshotDerivers)try{h[y]=g(l,this.lastPluginExtensions[y])}catch(p){this.store.report(p),S(this.lastPluginExtensions,y)&&(h[y]=this.lastPluginExtensions[y])}this.lastPluginExtensions=h;let f=e?.plugins;l={...l,plugins:f!=null&&E(f,h)?f:Object.freeze(h)}}let d=Object.freeze(l),c=e!==null&&E(d,e)?e:d;return this.lastSnapshot=c,c}};var K=["context","transition","status"];function q(n){return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.trunc(n))}function X(n,e){return{status:n.status,context:n.context,timeline:n.history.timeline,currentIndex:n.history.currentIndex,savedAt:e}}var oe=new Set(["idle","running","paused","completed","terminated"]),ae=["__proto__","constructor","prototype"];function G(n,e=0){if(e>50||n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(r=>G(r,e+1));let t={};for(let[r,s]of Object.entries(n))ae.includes(r)||(t[r]=G(s,e+1));return t}function W(n){if(n===null)return null;let e;try{e=JSON.parse(n)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;return typeof t.status!="string"||!oe.has(t.status)||!Array.isArray(t.timeline)||!t.timeline.every(r=>typeof r=="string")||typeof t.currentIndex!="number"||!Number.isInteger(t.currentIndex)||typeof t.savedAt!="number"||!Number.isFinite(t.savedAt)?null:{status:t.status,context:G(t.context),timeline:t.timeline,currentIndex:t.currentIndex,savedAt:t.savedAt}}function $(n){if(n.storage)return n.storage;let e;try{e=globalThis.localStorage}catch(t){throw new m("storage-unavailable","localStorage access was blocked by the environment; pass persist.storage explicitly",{},t)}if(!e)throw new m("storage-unavailable","persist.storage is required when localStorage is unavailable");return e}function L(n,e){let t;try{t=$(n).getItem(n.key)}catch{return null}let r=W(t);if(!r||r.status!=="running"&&r.status!=="paused"||!Number.isInteger(r.currentIndex)||r.currentIndex<0||r.currentIndex>=r.timeline.length)return null;for(let s of r.timeline)if(typeof s!="string"||!e(s))return null;return r}var z={status:"idle",lastSavedAt:null,error:null};function ue(n){let e=n.now??Date.now,t=q(n.debounceMs),r=new Set(n.saveOn??K),s=0;return{name:"persistence",setup(a){s+=1,s>1&&V(`journey: persistence plugin instance shared by ${s} machines; they overwrite key "${n.key}". Create one per machine.`);let u=null,o=z,i=null,l=!1,d=p=>{u=p,o={status:"saved",lastSavedAt:p.savedAt,error:null}},c=p=>{o={...o,status:"error",error:p},a.reportError(p)},h=()=>{let p=X(a.getSnapshot(),e());o={...o,status:"saving"};let T;try{T=n.storage.setItem(n.key,JSON.stringify(p))}catch(b){throw o={...o,status:"error",error:b},b}if(T!==void 0)return T.then(()=>d(p),c);d(p)},f=()=>{i!==null&&(clearTimeout(i),i=null)},y=()=>{i=null;try{let p=h()}catch(p){c(p)}},g=p=>{if(!(l||!r.has(p))){if(t===0){h();return}f(),o={...o,status:"pending"},i=setTimeout(y,t)}};return a.onContextChange(()=>g("context")),a.onTransition(()=>g("transition")),a.onStatusChange(({current:p})=>{if(p==="terminated"&&n.clearOnTerminate){f(),u=null,o=z,n.storage.removeItem(n.key);return}g("status")}),a.onDispose(()=>{l=!0,f()}),{api:{inspectPersistedState:()=>u,getPersistenceState:()=>o,readPersisted:()=>W(n.storage.getItem(n.key)),clearPersisted:()=>{f(),u=null,o=z;try{n.storage.removeItem(n.key)}catch(p){c(p)}},flushPersisted:async()=>{f();try{await h()}catch(p){c(p)}}},deriveSnapshot:(p,T)=>T===o?T:o}}}}function M(n){return ue({key:n.key,storage:$(n)})}function Z(n,e={}){if(n.steps.length===0)throw new m("empty-definition","a linear journey needs at least one step");let t=[],r={};for(let o of n.steps){let i=typeof o=="string"?{id:o}:o;if(S(r,i.id))throw new m("duplicate-step-id",`duplicate step id "${i.id}"`,{stepId:i.id});t.push(i.id);let l={metadata:i.metadata??{}};i.onEnter&&(l.onEnter=i.onEnter),i.onLeave&&(l.onLeave=i.onLeave),r[i.id]=l}if(e.startAt!==void 0&&!S(r,e.startAt))throw new m("unknown-step",`startAt references unknown step "${e.startAt}"`,{stepId:e.startAt});let s=e.persist&&e.startAt===void 0?L(e.persist,o=>S(r,o)):null,a=new P({kind:"linear",stepIds:t,steps:r,initial:t[0],...e.startAt!==void 0?{startAt:e.startAt}:{},initialContext:n.context,...s?{restore:{context:s.context,timeline:s.timeline,currentIndex:s.currentIndex}}:{},transitions:[],handlers:void 0,autoStart:e.autoStart??!0,defaultTimeoutMs:e.defaultTimeoutMs,...e.onListenerError!==void 0?{onListenerError:e.onListenerError}:{},plugins:[...e.persist?[M(e.persist)]:[],...e.plugins??[]]}),u=C(a);return{...u,navigate:{...u.navigate,goToStepByIndex:o=>a.goToStepByIndex(o)}}}var le=()=>(n,e={})=>Z(n,e);var ee=(n,e,t)=>{if(typeof n!="string"||n.length===0)throw new m("invalid-label",`${e} must declare "label" as a non-empty string`,t);return n},te=(n,e,t)=>{if(typeof n!="number"||!Number.isFinite(n)||n<=0)throw new m("invalid-timeout",`${e} must declare "timeoutMs" as a finite number greater than 0`,t);return n};function _(n){let e=Object.keys(n.steps);if(e.length===0)throw new m("empty-definition","a graph journey needs at least one step");if(!e.includes(n.initial))throw new m("unknown-initial-step",`initial step "${n.initial}" is not a declared step`,{stepId:n.initial});let t={};for(let u of e){let o=n.steps[u],i={metadata:o.metadata??{}};o.onEnter&&(i.onEnter=o.onEnter),o.onLeave&&(i.onLeave=o.onLeave),t[u]=i}let r=[],s={},a=(u,o,i,l)=>{if(!e.includes(i.to))throw new m("dangling-transition",`transition "${u}" references unknown step "${i.to}"`,{event:u,stepId:i.to});let d=`transition "${u}"[${l}] on step "${o}"`,c={event:u,from:o,to:i.to,index:l};i.when&&(c.when=i.when),i.onTransition&&(c.onTransition=i.onTransition),i.label!==void 0&&(c.label=ee(i.label,d,{event:u,stepId:o})),i.timeoutMs!==void 0&&(c.timeoutMs=te(i.timeoutMs,d,{event:u,stepId:o})),r.push(c)};for(let u of e){let o=n.steps[u]?.on;if(o)for(let[i,l]of Object.entries(o)){if(l===void 0)continue;if(typeof l=="string"){a(i,u,{to:l},0);continue}if(Array.isArray(l)){l.forEach((f,y)=>a(i,u,f,y));continue}let d=l,c=`work on "${i}" on step "${u}"`,h={run:d.run};d.commit&&(h.commit=d.commit),d.label!==void 0&&(h.label=ee(d.label,c,{event:i,stepId:u})),d.timeoutMs!==void 0&&(h.timeoutMs=te(d.timeoutMs,c,{event:i,stepId:u})),s[R(u,i)]=h,d.candidates.forEach((f,y)=>a(i,u,f,y))}}return{stepIds:e,steps:t,transitions:r,eventWork:s}}function ne(n,e={}){let{stepIds:t,steps:r,transitions:s,eventWork:a}=_(n);if(e.startAt!==void 0&&!S(r,e.startAt))throw new m("unknown-step",`startAt references unknown step "${e.startAt}"`,{stepId:e.startAt});let u=e.persist&&e.startAt===void 0?L(e.persist,l=>S(r,l)):null,o=new P({kind:"graph",stepIds:t,steps:r,initial:n.initial,...e.startAt!==void 0?{startAt:e.startAt}:{},initialContext:n.context,...u?{restore:{context:u.context,timeline:u.timeline,currentIndex:u.currentIndex}}:{},transitions:s,...Object.keys(a).length>0?{eventWork:a}:{},handlers:e.handlers??n.handlers,autoStart:e.autoStart??!0,defaultTimeoutMs:e.defaultTimeoutMs,...e.onListenerError!==void 0?{onListenerError:e.onListenerError}:{},plugins:[...e.persist?[M(e.persist)]:[],...e.plugins??[]]});return{...C(o),send:(l,d)=>o.send(l,d)}}var pe=()=>(n,e={})=>ne(n,e);var de=()=>n=>n;function ce(n){let e=[],t=[...n.stepIds],r=new Set,s=new Set;n.transitions.forEach((g,p)=>{let T=`${g.from} ${g.event}`;if(s.has(T)){r.add(p),e.push({code:"shadowed-transition",severity:"warning",from:g.from,event:g.event,message:`Transition "${g.from}.${g.event}" is shadowed by an earlier unconditional candidate.`});return}g.guarded||s.add(T)});let a=n.transitions.filter((g,p)=>!r.has(p)),u=g=>a.filter(p=>p.from===g),o=new Set,i=[n.initial];for(;i.length>0;){let g=i.pop();if(!o.has(g)){o.add(g);for(let p of u(g))i.push(p.to)}}for(let g of t)o.has(g)||e.push({code:"unreachable-step",severity:"warning",stepId:g,message:`Step "${g}" is unreachable from the initial step "${n.initial}".`});let l=t.filter(g=>u(g).length===0),d=new Set,c=new Set,h=[],f=g=>{c.add(g),h.push(g);for(let p of u(g)){let T=h.indexOf(p.to);if(T>=0){let b=[...h.slice(T),p.to],k=b.join(" ");d.has(k)||(d.add(k),e.push({code:"cycle-detected",severity:"warning",from:p.from,event:p.event,steps:b,message:`Cycle detected: ${b.join(" -> ")}.`}));continue}c.has(p.to)||f(p.to)}h.pop()};f(n.initial);let y=l.some(g=>o.has(g));return y||e.push({code:"no-terminal-path",severity:"warning",stepId:n.initial,message:`No terminal step is reachable from the initial step "${n.initial}".`}),{issues:e,summary:{stepCount:t.length,reachableStepCount:o.size,unreachableStepCount:t.length-o.size,terminalStepIds:l,cycleCount:d.size,shadowedTransitionCount:r.size,terminalPathExists:y}}}function he(n){let{stepIds:e,transitions:t}=_(n),r={kind:"graph",stepIds:e,initial:n.initial,transitions:t.map(s=>({event:s.event,from:s.from,to:s.to,guarded:s.when!==void 0,label:s.label??null,index:s.index}))};return ce(r)}export{m as JourneyError,he as analyzeStructure,ne as createGraphJourney,Z as createLinearJourney,de as defineWork,re as isJourneyError,pe as withGraphTypes,le as withLinearTypes};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|