@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
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { JourneyDefinition, JourneyExecutionPathOptions, JourneyExecutionPathsResult, JourneyFullEventType, JourneyJsonObject, JourneyResolvedDefinition } from "../../types";
|
|
2
|
+
/**
|
|
3
|
+
* Enumerates structural execution paths from a resolved journey definition.
|
|
4
|
+
*/
|
|
5
|
+
export declare function getExecutionPaths<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>, options?: JourneyExecutionPathOptions): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
6
|
+
export declare function getExecutionPaths<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(journey: JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>, options?: JourneyExecutionPathOptions): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var E=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var k=(n,t)=>{for(var s in t)E(n,s,{get:t[s],enumerable:!0})},R=(n,t,s,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of $(t))!C.call(n,c)&&c!==s&&E(n,c,{get:()=>t[c],enumerable:!(a=M(t,c))||a.enumerable});return n};var O=n=>R(E({},"__esModule",{value:!0}),n);var A={};k(A,{createExecutionPathsPlugin:()=>j,getExecutionPaths:()=>w});module.exports=O(A);var P=n=>typeof n=="number"&&Number.isFinite(n),S=(n,t)=>{if(n!==void 0&&!P(n))throw new Error(`${t} must define a finite numeric "timeoutMs" when provided.`)};var b=n=>n.event==="completeJourney"?"COMPLETE":n.event==="terminateJourney"?"TERMINATED":n.to;var g=n=>{let t=2166136261;for(let s=0;s<n.length;s+=1)t^=n.charCodeAt(s),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},m=n=>{let t=new Map,s=new Set;return n.map(a=>{let c=a.event==="completeJourney"?"COMPLETE":a.event==="terminateJourney"?"TERMINATED":String(a.to),o=JSON.stringify({from:a.from,event:a.event,target:c}),u=(t.get(o)??0)+1;t.set(o,u);let i=JSON.stringify({from:a.from,event:a.event,target:c,ordinal:u}),p=0,d=(()=>{let T=g(i);for(;s.has(T);)p+=1,T=g(`${i}:${p}`);return T})();return s.add(d),{...a,id:d,...a.label!==void 0?{label:a.label}:{}}})},v=n=>{let t=[],{transitions:s}=n;if(s===void 0)return{...n,transitions:m(t)};if(Array.isArray(s)){if(s.length===0)throw new Error("Journey linear transitions must include the initial step as the first item.");let[o,...u]=s;if(typeof o!="string")throw new Error("Journey linear transitions at index 0 must be a step id string.");if(!(o in n.steps))throw new Error(`Journey linear transitions reference unknown step "${o}".`);let i=n.initial??o;if(n.initial!==void 0&&!s.map(e=>typeof e=="string"?e:e.step).includes(n.initial))throw new Error(`Journey initial step "${n.initial}" does not exist in linear transitions.`);let p=o,d=new Set([o]);for(let[T,e]of u.entries()){let r=T+1;if(typeof e=="string"){if(!(e in n.steps))throw new Error(`Journey linear transitions reference unknown step "${e}".`);if(d.has(e))throw new Error(`Journey linear transitions contain duplicate step "${e}" at index ${r}.`);d.add(e),t.push({from:p,event:"goToNextStep",to:e}),p=e;continue}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Journey linear transitions at index ${r} must be a step id string or step config object.`);let y=new Set(["step","label","updateContext","onEnter","onLeave","timeoutMs"]);for(let f of Object.keys(e))if(!y.has(f))throw new Error(`Journey linear transition object at index ${r} contains unsupported field "${f}". Allowed fields are "step", "label", "updateContext", "onEnter", "onLeave", and "timeoutMs".`);if(typeof e.step!="string")throw new Error(`Journey linear transition object at index ${r} must define string "step".`);if(!(e.step in n.steps))throw new Error(`Journey linear transitions reference unknown step "${e.step}".`);if(d.has(e.step))throw new Error(`Journey linear transitions contain duplicate step "${e.step}" at index ${r}.`);if(d.add(e.step),e.updateContext!==void 0&&typeof e.updateContext!="function")throw new Error(`Journey linear transition object at index ${r} must define "updateContext" as a function when provided.`);if(e.onEnter!==void 0&&typeof e.onEnter!="function")throw new Error(`Journey linear transition object at index ${r} must define "onEnter" as a function when provided.`);if(e.onLeave!==void 0&&typeof e.onLeave!="function")throw new Error(`Journey linear transition object at index ${r} must define "onLeave" as a function when provided.`);S(e.timeoutMs,`Journey linear transition object at index ${r}`),t.push({...e.label!==void 0?{label:e.label}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.updateContext!==void 0?{updateContext:e.updateContext}:{},...e.onEnter!==void 0?{onEnter:e.onEnter}:{},...e.onLeave!==void 0?{onLeave:e.onLeave}:{},from:p,event:"goToNextStep",to:e.step}),p=e.step}return{...n,initial:i,transitions:m(t)}}if(!s||typeof s!="object")throw new Error("Journey transitions must be an array or an object map when provided.");let a=s,c=[...Object.entries(a).filter(([o])=>o!=="global"),...a.global?[["global",a.global]]:[]];for(let[o,u]of c){if(o!=="global"&&!(o in n.steps))throw new Error(`Journey transitions reference unknown step "${o}".`);if(!u||typeof u!="object"||Array.isArray(u))throw new Error(`Journey transitions for "${o}" must be an event map object.`);for(let[i,p]of Object.entries(u)){let d=i==="completeJourney"||i==="terminateJourney",T=d&&(p===!0||Array.isArray(p)&&p.length===0)?[{}]:p;if(!Array.isArray(T))throw new Error(`Journey transitions for "${o}.${i}" must be an array.`);for(let[e,r]of T.entries()){if(!r||typeof r!="object")throw new Error(`Journey transition at "${o}.${i}[${e}]" must be an object.`);let y=new Set(d?["when","updateContext","onEnter","onLeave","label","timeoutMs"]:["to","when","updateContext","onEnter","onLeave","label","timeoutMs"]);for(let f of Object.keys(r))if(!y.has(f))throw new Error(`Journey transition at "${o}.${i}[${e}]" contains unsupported field "${f}".`);if(!d&&typeof r.to!="string")throw new Error(`Journey transition at "${o}.${i}[${e}]" must define string "to".`);if(r.when!==void 0&&typeof r.when!="function")throw new Error(`Journey transition at "${o}.${i}[${e}]" must define "when" as a function when provided.`);if(r.updateContext!==void 0&&typeof r.updateContext!="function")throw new Error(`Journey transition at "${o}.${i}[${e}]" must define "updateContext" as a function when provided.`);if(r.onEnter!==void 0&&typeof r.onEnter!="function")throw new Error(`Journey transition at "${o}.${i}[${e}]" must define "onEnter" as a function when provided.`);if(r.onLeave!==void 0&&typeof r.onLeave!="function")throw new Error(`Journey transition at "${o}.${i}[${e}]" must define "onLeave" as a function when provided.`);if(r.label!==void 0&&typeof r.label!="string")throw new Error(`Journey transition at "${o}.${i}[${e}]" must define "label" as a string when provided.`);S(r.timeoutMs,`Journey transition at "${o}.${i}[${e}]"`),t.push({...r,from:o==="global"?"*":o,event:i})}}}return{...n,transitions:m(t)}};var I=(n,t)=>typeof n!="number"||!Number.isFinite(n)?t:Math.max(1,Math.trunc(n));function w(n,t={}){let a=(e=>Array.isArray(e.transitions)&&(e.transitions.length===0||typeof e.transitions[0]=="object"&&e.transitions[0]!==null))(n)?n:v(n),c=I(t.maxDepth,5),o=I(t.maxPaths,10),u=[],i=!1,p=!1,d=e=>{if(u.length>=o){i=!0;return}u.push(e)},T=(e,r,y)=>{if(u.length>=o){i=!0;return}let f=a.transitions.filter(l=>l.from==="*"||l.from===e);if(f.length===0){d({steps:r,events:y,terminated:"final"});return}if(y.length>=c){d({steps:r,events:y,terminated:"depth"}),i=!0;return}for(let l of f){let J=[...y,l.event],x=b(l);if(x==="COMPLETE"||x==="TERMINATED"){d({steps:r,events:J,terminated:"final"});continue}let h=[...r,x];if(r.includes(x)){p=!0,d({steps:h,events:J,terminated:"cycle"});continue}if(T(x,h,J),u.length>=o){i=!0;return}}};return T(a.initial,[a.initial],[]),{paths:u,truncated:i,cyclesDetected:p}}var j=()=>({name:"execution-paths",setup:({resolvedJourney:n})=>({augmentMachine:()=>({getExecutionPaths:t=>w(n,t)})})});0&&(module.exports={createExecutionPathsPlugin,getExecutionPaths});
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/plugins/execution-paths/index.ts", "../../../src/journey-machine/helpers.ts", "../../../src/journey-machine/resolve-journey-definition.ts", "../../../src/plugins/execution-paths/execution-paths.ts"],
|
|
4
|
+
"sourcesContent": ["import { getExecutionPaths } from \"./execution-paths\";\n\nimport type {\n JourneyExecutionPathOptions,\n JourneyExecutionPathsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin\n} from \"../../types\";\n\nexport type JourneyExecutionPathsMachineExtension<\n TStepId extends string,\n TEventType extends string\n> = {\n getExecutionPaths: (\n options?: JourneyExecutionPathOptions\n ) => JourneyExecutionPathsResult<TStepId, TEventType>;\n};\n\nexport type JourneyExecutionPathsMachine<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown> = Record<never, never>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> &\n JourneyExecutionPathsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;\n\n/**\n * Creates a plugin that augments a machine with structural execution-path\n * enumeration without pulling graph code into the base entrypoint.\n */\nexport const createExecutionPathsPlugin = () =>\n ({\n name: \"execution-paths\",\n setup: ({ resolvedJourney }) => ({\n augmentMachine: () => ({\n getExecutionPaths: (options?: JourneyExecutionPathOptions) =>\n getExecutionPaths(resolvedJourney, options)\n })\n })\n }) satisfies JourneyMachinePlugin;\n\nexport { getExecutionPaths } from \"./execution-paths\";\n", "import type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyGoToEvent,\n JourneyJsonObject,\n JourneyJsonValue,\n JourneyPayloadFor,\n JourneyResolvedTransition,\n JourneySendEvent,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransition,\n JourneyTransitionArgs\n} from \"../types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n\nconst cloneSerializableValue = <T extends JourneyJsonValue>(value: T): T => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneSerializableValue(entry)) as T;\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneSerializableValue(entryValue as JourneyJsonValue)\n ])\n ) as T;\n }\n\n return value;\n};\n\ntype SerializableCheckState = {\n readonly seen: WeakSet<object>;\n};\n\nconst describeValue = (value: unknown): string => {\n if (value === null) {\n return \"null\";\n }\n\n if (Array.isArray(value)) {\n return \"array\";\n }\n\n if (typeof value === \"object\") {\n const constructorName = (value as { constructor?: { name?: string } }).constructor?.name;\n return constructorName && constructorName !== \"Object\" ? constructorName : \"object\";\n }\n\n return typeof value;\n};\n\nfunction assertSerializableValue(\n value: unknown,\n label: string,\n state: SerializableCheckState,\n path: readonly string[] = []\n): asserts value is JourneyJsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return;\n }\n\n const pathLabel = path.length === 0 ? label : `${label}.${path.join(\".\")}`;\n\n if (value === undefined) {\n throw new Error(`${pathLabel} must be JSON-serializable. Received undefined.`);\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\" || typeof value === \"function\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${typeof value}.`);\n }\n\n if (typeof value !== \"object\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${describeValue(value)}.`);\n }\n\n if (state.seen.has(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Circular references are not supported.`\n );\n }\n\n state.seen.add(value);\n\n if (Array.isArray(value)) {\n for (const [index, entryValue] of value.entries()) {\n assertSerializableValue(entryValue, label, state, [...path, String(index)]);\n }\n return;\n }\n\n if (!isPlainObject(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Received non-plain ${describeValue(value)}.`\n );\n }\n\n for (const [key, entryValue] of Object.entries(value)) {\n assertSerializableValue(entryValue, label, state, [...path, key]);\n }\n}\n\nexport function assertSerializableContext<TContext extends JourneyJsonObject>(\n context: TContext,\n label = \"Journey context\"\n): TContext {\n assertSerializableValue(context, label, { seen: new WeakSet() });\n return context;\n}\n\nexport const cloneContext = <TContext extends JourneyJsonObject>(context: TContext): TContext =>\n cloneSerializableValue(assertSerializableContext(context));\n\nconst cloneDefinitionValueFallback = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneDefinitionValueFallback(entry));\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n\n if (value instanceof Map) {\n return new Map(\n [...value.entries()].map(([key, entryValue]) => [\n cloneDefinitionValueFallback(key),\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n if (value instanceof Set) {\n return new Set([...value].map((entry) => cloneDefinitionValueFallback(entry)));\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n return value;\n};\n\nexport const cloneMetaValue = <T>(value: T): T => {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) {\n return value;\n }\n\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(value);\n } catch {\n return cloneDefinitionValueFallback(value) as T;\n }\n } else {\n return cloneDefinitionValueFallback(value) as T;\n }\n};\n\nconst freezeSnapshotValue = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n freezeSnapshotValue(item);\n }\n Object.freeze(value);\n return;\n }\n\n if (!isPlainObject(value)) {\n return;\n }\n\n for (const entryValue of Object.values(value)) {\n freezeSnapshotValue(entryValue);\n }\n Object.freeze(value);\n};\n\nexport const normalizeStepCount = (steps?: number): number => {\n if (typeof steps !== \"number\" || !Number.isFinite(steps)) {\n return 1;\n }\n return Math.max(1, Math.trunc(steps));\n};\n\nexport const now = (): number => Date.now();\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nconst normalizeVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n stepIds: readonly TStepId[]\n): Record<TStepId, boolean> =>\n Object.fromEntries(stepIds.map((stepId) => [stepId, visited[stepId] === true])) as Record<\n TStepId,\n boolean\n >;\n\nexport const buildVisitedFromTimeline = <TStepId extends string>(\n timeline: readonly TStepId[],\n stepIds?: readonly TStepId[]\n): Record<TStepId, boolean> => {\n const resolvedStepIds = stepIds ?? unique(timeline);\n const visited = Object.fromEntries(resolvedStepIds.map((stepId) => [stepId, false])) as Record<\n TStepId,\n boolean\n >;\n\n for (const stepId of timeline) {\n visited[stepId] = true;\n }\n\n return visited;\n};\n\nexport const appendVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n current: TStepId\n): Record<TStepId, boolean> => ({\n ...visited,\n [current]: true\n});\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value);\n\nexport const validateFiniteTimeout = (timeoutMs: unknown, label: string) => {\n if (timeoutMs !== undefined && !isFiniteNumber(timeoutMs)) {\n throw new Error(`${label} must define a finite numeric \"timeoutMs\" when provided.`);\n }\n};\n\nexport class JourneyTimeoutError extends Error {\n override name = \"JourneyTimeoutError\";\n\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class JourneyDisposedError extends Error {\n override name = \"JourneyDisposedError\";\n readonly operation: string;\n\n constructor(operation: string) {\n super(`Journey machine has been disposed; \"${operation}\" can no longer be used.`);\n this.operation = operation;\n }\n}\n\ntype DiagnosticGlobal = typeof globalThis & {\n __DEV__?: unknown;\n process?: {\n env?: {\n NODE_ENV?: string;\n };\n };\n};\n\nexport const isDevelopmentEnvironment = (): boolean => {\n const diagnosticGlobal = globalThis as DiagnosticGlobal;\n if (typeof diagnosticGlobal.__DEV__ === \"boolean\") {\n return diagnosticGlobal.__DEV__;\n }\n\n const nodeEnv = diagnosticGlobal.process?.env?.NODE_ENV;\n return nodeEnv === undefined || nodeEnv === \"development\";\n};\n\nexport const warnInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.warn(message);\n return;\n }\n\n console.warn(message, detail);\n};\n\nexport const errorInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.error(message);\n return;\n }\n\n console.error(message, detail);\n};\n\nexport const withTimeout = async <T>(\n promise: PromiseLike<T>,\n timeoutMs: number | undefined,\n buildError: () => Error\n): Promise<T> => {\n if (!isFiniteNumber(timeoutMs) || timeoutMs <= 0) {\n return await promise;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(buildError());\n }, timeoutMs);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n};\n\nexport const withAbortSignal = async <T>(\n promise: PromiseLike<T>,\n signal: AbortSignal\n): Promise<T> => {\n if (signal.aborted) {\n throw signal.reason;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(signal.reason);\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n};\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: \"idle\",\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToStepByIdEvent = <\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n>(\n event: JourneySendEvent<TStepId, TEventMap>\n): event is JourneyGoToEvent<TStepId, JourneyPayloadFor<TEventMap, \"goToStepById\">> =>\n event.type === \"goToStepById\" && \"stepId\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal\n): target is JourneyTerminal => target === \"COMPLETE\" || target === \"TERMINATED\";\n\nexport const resolveTransitionTarget = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transition: JourneyTransition<TContext, TStepId, TEventMap, THandlers>\n): TStepId | JourneyTerminal =>\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : (transition.to as TStepId | JourneyTerminal);\n\nexport const validateJourneyTransitions = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[],\n steps: Record<TStepId, unknown>\n) => {\n const stepRegistry = steps as Record<string, unknown>;\n const allowedKeys = new Set([\n \"from\",\n \"event\",\n \"to\",\n \"when\",\n \"updateContext\",\n \"onEnter\",\n \"onLeave\",\n \"id\",\n \"label\",\n \"timeoutMs\"\n ]);\n\n for (const [index, transition] of transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n for (const key of Object.keys(transition)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey transition at index ${index} contains unsupported field \"${key}\".`\n );\n }\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (transition.from !== \"*\" && !(transition.from in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n validateFiniteTimeout(transition.timeoutMs, `Journey transition at index ${index}`);\n\n if (transition.when !== undefined && typeof transition.when !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"when\" as a function when provided.`\n );\n }\n\n if (transition.updateContext !== undefined && typeof transition.updateContext !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (transition.onEnter !== undefined && typeof transition.onEnter !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (transition.onLeave !== undefined && typeof transition.onLeave !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onLeave\" as a function when provided.`\n );\n }\n\n if (transition.id !== undefined && typeof transition.id !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"id\" as a string when provided.`\n );\n }\n\n if (transition.label !== undefined && typeof transition.label !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"label\" as a string when provided.`\n );\n }\n\n if (transition.event === \"completeJourney\" || transition.event === \"terminateJourney\") {\n if (\"to\" in transition && transition.to !== undefined) {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" cannot define \"to\".`\n );\n }\n continue;\n }\n\n if (typeof transition.to !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" must define string \"to\".`\n );\n }\n\n if (!isTerminalTarget(transition.to) && !(transition.to in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n};\n\nexport const buildSendResult = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n transitioned: boolean,\n options: {\n transitionId?: string;\n label?: string;\n error?: unknown;\n } = {}\n): JourneySendResult<TContext, TStepId> => ({\n transitioned,\n ...(options.transitionId !== undefined ? { transitionId: options.transitionId } : {}),\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(\"error\" in options ? { error: options.error } : {}),\n snapshot\n});\n\nexport const buildSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n timeline: readonly TStepId[],\n index: number,\n context: TContext,\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n visited?: Record<TStepId, boolean>\n): JourneySnapshot<TContext, TStepId> => {\n if (timeline.length === 0) {\n throw new Error(\"Journey timeline cannot be empty.\");\n }\n\n const safeIndex = Math.max(0, Math.min(Math.trunc(index), timeline.length - 1));\n const currentStepId = timeline[safeIndex] as TStepId;\n const stepIds = unique(\n visited ? ([...(Object.keys(visited) as TStepId[]), ...timeline] as const) : timeline\n );\n\n return {\n status,\n currentStepId,\n history: {\n timeline: [...timeline],\n index: safeIndex\n },\n context: cloneContext(context),\n visited: visited\n ? normalizeVisited(visited, stepIds)\n : buildVisitedFromTimeline(timeline, stepIds),\n async: cloneSerializableValue(\n asyncState as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n};\n\nexport const stabilizeSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>\n): JourneySnapshot<TContext, TStepId> => {\n const stableSnapshot: JourneySnapshot<TContext, TStepId> = {\n ...snapshot,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: cloneContext(snapshot.context),\n visited: { ...snapshot.visited },\n async: cloneSerializableValue(\n snapshot.async as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n\n freezeSnapshotValue(stableSnapshot);\n return stableSnapshot;\n};\n\nexport const selectTransition = async <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>,\n TTransition extends {\n from: TStepId | \"*\";\n event: string;\n when?: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>;\n timeoutMs?: number;\n id?: string;\n label?: string;\n }\n>(\n transitions: readonly TTransition[],\n snapshot: JourneySnapshot<TContext, TStepId>,\n event: JourneyEvent<TStepId, TEventMap>,\n signal: AbortSignal,\n handlers: THandlers,\n hooks?: {\n onAsyncGuardStart?: (transition: TTransition) => void;\n onAsyncGuardSuccess?: (transition: TTransition) => void;\n onAsyncGuardError?: (transition: TTransition, error: unknown) => void;\n },\n defaultTimeoutMs?: number\n): Promise<TTransition | null> => {\n for (const transition of transitions) {\n const fromMatches = transition.from === \"*\" || transition.from === snapshot.currentStepId;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n let guardResult: boolean | Promise<boolean>;\n if (signal.aborted) {\n throw signal.reason;\n }\n\n guardResult = (\n transition.when as (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>\n )({\n snapshot,\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event,\n signal,\n handlers\n });\n\n const asyncGuard = isPromiseLike(guardResult);\n const asyncGuardPromise = asyncGuard ? (guardResult as PromiseLike<boolean>) : null;\n\n let allowed: boolean;\n try {\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n allowed = await withTimeout(\n withAbortSignal(asyncGuardPromise as PromiseLike<boolean>, signal),\n transition.timeoutMs ?? defaultTimeoutMs,\n () =>\n new JourneyTimeoutError(\n `Transition guard timed out after ${transition.timeoutMs ?? defaultTimeoutMs}ms (event: ${event.type}, transition: ${transition.id ?? \"<anonymous>\"}).`\n )\n );\n } else {\n allowed = guardResult as boolean;\n }\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId> => {\n const baseTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n let nextTimeline = baseTimeline;\n if (nextCurrent !== snapshot.currentStepId) {\n nextTimeline = [...baseTimeline, nextCurrent];\n }\n\n const nextIndex = nextTimeline.length - 1;\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(\n nextTimeline,\n nextIndex,\n nextContext,\n snapshot.status,\n snapshot.async,\n visited\n );\n};\n", "import { validateFiniteTimeout } from \"./helpers\";\n\nimport type {\n JourneyDefinition,\n JourneyJsonObject,\n JourneyResolvedDefinition,\n JourneyResolvedTransition,\n JourneyTransition,\n JourneyTransitionGraph\n} from \"../types\";\n\nconst hashTransitionDescriptor = (value: string) => {\n let hash = 2166136261;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n};\n\nconst buildResolvedTransitions = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventMap, THandlers>[]\n): JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[] => {\n const transitionRouteCounts = new Map<string, number>();\n const usedIds = new Set<string>();\n\n return transitions.map((transition) => {\n const target =\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : String(transition.to);\n const routeKey = JSON.stringify({\n from: transition.from,\n event: transition.event,\n target\n });\n const ordinal = (transitionRouteCounts.get(routeKey) ?? 0) + 1;\n transitionRouteCounts.set(routeKey, ordinal);\n\n const descriptor = JSON.stringify({\n from: transition.from,\n event: transition.event,\n target,\n ordinal\n });\n\n let suffix = 0;\n const id = (() => {\n let candidate = hashTransitionDescriptor(descriptor);\n while (usedIds.has(candidate)) {\n suffix += 1;\n candidate = hashTransitionDescriptor(`${descriptor}:${suffix}`);\n }\n return candidate;\n })();\n usedIds.add(id);\n\n return {\n ...transition,\n id,\n ...(transition.label !== undefined ? { label: transition.label } : {})\n } as JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>;\n });\n};\n\nexport const resolveJourneyDefinition = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>\n): JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers> => {\n type TEventType = string;\n const resolvedTransitions: JourneyTransition<TContext, TStepId, TEventMap, THandlers>[] = [];\n const { transitions } = journey;\n\n if (transitions === undefined) {\n return {\n ...journey,\n transitions: buildResolvedTransitions(resolvedTransitions)\n } as JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n }\n\n if (Array.isArray(transitions)) {\n if (transitions.length === 0) {\n throw new Error(\n \"Journey linear transitions must include the initial step as the first item.\"\n );\n }\n\n const [initialStep, ...linearEntries] = transitions;\n if (typeof initialStep !== \"string\") {\n throw new Error(\"Journey linear transitions at index 0 must be a step id string.\");\n }\n\n if (!(initialStep in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${initialStep}\".`);\n }\n\n // Resolve initial: use journey.initial if provided (start from middle), otherwise array[0]\n const resolvedInitial = (journey.initial ?? initialStep) as TStepId;\n\n if (journey.initial !== undefined) {\n const allStepIds = transitions.map((entry) =>\n typeof entry === \"string\" ? entry : entry.step\n );\n if (!allStepIds.includes(journey.initial)) {\n throw new Error(\n `Journey initial step \"${journey.initial}\" does not exist in linear transitions.`\n );\n }\n }\n\n let previousStep = initialStep as TStepId;\n const seenSteps = new Set<string>([initialStep]);\n for (const [offset, entry] of linearEntries.entries()) {\n const index = offset + 1;\n if (typeof entry === \"string\") {\n if (!(entry in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${entry}\".`);\n }\n\n if (seenSteps.has(entry)) {\n throw new Error(\n `Journey linear transitions contain duplicate step \"${entry}\" at index ${index}.`\n );\n }\n seenSteps.add(entry);\n\n resolvedTransitions.push({\n from: previousStep,\n event: \"goToNextStep\" as TEventType,\n to: entry as TStepId\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n previousStep = entry as TStepId;\n continue;\n }\n\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(\n `Journey linear transitions at index ${index} must be a step id string or step config object.`\n );\n }\n\n const allowedKeys = new Set([\n \"step\",\n \"label\",\n \"updateContext\",\n \"onEnter\",\n \"onLeave\",\n \"timeoutMs\"\n ]);\n for (const key of Object.keys(entry)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey linear transition object at index ${index} contains unsupported field \"${key}\". Allowed fields are \"step\", \"label\", \"updateContext\", \"onEnter\", \"onLeave\", and \"timeoutMs\".`\n );\n }\n }\n\n if (typeof entry.step !== \"string\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define string \"step\".`\n );\n }\n\n if (!(entry.step in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${entry.step}\".`);\n }\n\n if (seenSteps.has(entry.step)) {\n throw new Error(\n `Journey linear transitions contain duplicate step \"${entry.step}\" at index ${index}.`\n );\n }\n seenSteps.add(entry.step);\n\n if (entry.updateContext !== undefined && typeof entry.updateContext !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (entry.onEnter !== undefined && typeof entry.onEnter !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (entry.onLeave !== undefined && typeof entry.onLeave !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"onLeave\" as a function when provided.`\n );\n }\n\n validateFiniteTimeout(entry.timeoutMs, `Journey linear transition object at index ${index}`);\n\n resolvedTransitions.push({\n ...(entry.label !== undefined ? { label: entry.label } : {}),\n ...(entry.timeoutMs !== undefined ? { timeoutMs: entry.timeoutMs } : {}),\n ...(entry.updateContext !== undefined ? { updateContext: entry.updateContext } : {}),\n ...(entry.onEnter !== undefined ? { onEnter: entry.onEnter } : {}),\n ...(entry.onLeave !== undefined ? { onLeave: entry.onLeave } : {}),\n from: previousStep,\n event: \"goToNextStep\" as TEventType,\n to: entry.step as TStepId\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n previousStep = entry.step as TStepId;\n }\n\n return {\n ...journey,\n initial: resolvedInitial,\n transitions: buildResolvedTransitions(resolvedTransitions)\n };\n }\n\n if (!transitions || typeof transitions !== \"object\") {\n throw new Error(\"Journey transitions must be an array or an object map when provided.\");\n }\n\n const transitionGraph = transitions as JourneyTransitionGraph<\n TContext,\n TStepId,\n TEventMap,\n THandlers\n >;\n\n const orderedGraphEntries = [\n ...Object.entries(transitionGraph).filter(([fromKey]) => fromKey !== \"global\"),\n ...(transitionGraph.global ? ([[\"global\", transitionGraph.global]] as const) : [])\n ];\n\n for (const [fromKey, eventMap] of orderedGraphEntries) {\n if (fromKey !== \"global\" && !(fromKey in journey.steps)) {\n throw new Error(`Journey transitions reference unknown step \"${fromKey}\".`);\n }\n\n if (!eventMap || typeof eventMap !== \"object\" || Array.isArray(eventMap)) {\n throw new Error(`Journey transitions for \"${fromKey}\" must be an event map object.`);\n }\n\n for (const [event, rawEdges] of Object.entries(eventMap) as Array<\n [TEventType, (typeof eventMap)[TEventType] | true]\n >) {\n const isTerminal = event === \"completeJourney\" || event === \"terminateJourney\";\n const edges =\n isTerminal && (rawEdges === true || (Array.isArray(rawEdges) && rawEdges.length === 0))\n ? [{}]\n : rawEdges;\n\n if (!Array.isArray(edges)) {\n throw new Error(`Journey transitions for \"${fromKey}.${event}\" must be an array.`);\n }\n\n for (const [index, edge] of edges.entries()) {\n if (!edge || typeof edge !== \"object\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must be an object.`\n );\n }\n\n const allowedKeys = new Set(\n isTerminal\n ? [\"when\", \"updateContext\", \"onEnter\", \"onLeave\", \"label\", \"timeoutMs\"]\n : [\"to\", \"when\", \"updateContext\", \"onEnter\", \"onLeave\", \"label\", \"timeoutMs\"]\n );\n for (const key of Object.keys(edge)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" contains unsupported field \"${key}\".`\n );\n }\n }\n\n if (!isTerminal && typeof (edge as { to?: unknown }).to !== \"string\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define string \"to\".`\n );\n }\n\n if ((edge as { when?: unknown }).when !== undefined && typeof edge.when !== \"function\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"when\" as a function when provided.`\n );\n }\n\n if (\n (edge as { updateContext?: unknown }).updateContext !== undefined &&\n typeof edge.updateContext !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (\n (edge as { onEnter?: unknown }).onEnter !== undefined &&\n typeof edge.onEnter !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (\n (edge as { onLeave?: unknown }).onLeave !== undefined &&\n typeof edge.onLeave !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"onLeave\" as a function when provided.`\n );\n }\n\n if ((edge as { label?: unknown }).label !== undefined && typeof edge.label !== \"string\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"label\" as a string when provided.`\n );\n }\n\n validateFiniteTimeout(\n (edge as { timeoutMs?: unknown }).timeoutMs,\n `Journey transition at \"${fromKey}.${event}[${index}]\"`\n );\n\n resolvedTransitions.push({\n ...edge,\n from: (fromKey === \"global\" ? \"*\" : fromKey) as TStepId | \"*\",\n event\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n }\n }\n }\n\n return {\n ...journey,\n transitions: buildResolvedTransitions(resolvedTransitions)\n } as JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n};\n", "/* eslint-disable no-redeclare */\nimport { resolveTransitionTarget } from \"../../journey-machine/helpers\";\nimport { resolveJourneyDefinition } from \"../../journey-machine/resolve-journey-definition\";\n\nimport type {\n JourneyDefinition,\n JourneyExecutionPath,\n JourneyExecutionPathEventType,\n JourneyExecutionPathOptions,\n JourneyExecutionPathsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyResolvedDefinition\n} from \"../../types\";\n\nconst normalizeLimit = (value: number | undefined, fallback: number): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n\n return Math.max(1, Math.trunc(value));\n};\n\n/**\n * Enumerates structural execution paths from a resolved journey definition.\n */\nexport function getExecutionPaths<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n options?: JourneyExecutionPathOptions\n): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;\nexport function getExecutionPaths<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey: JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n options?: JourneyExecutionPathOptions\n): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;\nexport function getExecutionPaths<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey:\n | JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>\n | JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n options: JourneyExecutionPathOptions = {}\n): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>> {\n type TEventType = JourneyFullEventType<TEventMap>;\n const isResolvedJourneyDefinition = (\n value: typeof journey\n ): value is JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers> =>\n Array.isArray(value.transitions) &&\n (value.transitions.length === 0 ||\n (typeof value.transitions[0] === \"object\" && value.transitions[0] !== null));\n const resolvedJourney = isResolvedJourneyDefinition(journey)\n ? journey\n : resolveJourneyDefinition(journey);\n const maxDepth = normalizeLimit(options.maxDepth, 5);\n const maxPaths = normalizeLimit(options.maxPaths, 10);\n const paths: JourneyExecutionPath<TStepId, TEventType>[] = [];\n let truncated = false;\n let cyclesDetected = false;\n\n const pushPath = (path: JourneyExecutionPath<TStepId, TEventType>) => {\n if (paths.length >= maxPaths) {\n truncated = true;\n return;\n }\n\n paths.push(path);\n };\n\n const visit = (\n currentStepId: TStepId,\n steps: TStepId[],\n events: JourneyExecutionPathEventType<TEventType>[]\n ) => {\n if (paths.length >= maxPaths) {\n truncated = true;\n return;\n }\n\n const outgoing = resolvedJourney.transitions.filter(\n (transition) => transition.from === \"*\" || transition.from === currentStepId\n );\n\n if (outgoing.length === 0) {\n pushPath({ steps, events, terminated: \"final\" });\n return;\n }\n\n if (events.length >= maxDepth) {\n pushPath({ steps, events, terminated: \"depth\" });\n truncated = true;\n return;\n }\n\n for (const transition of outgoing) {\n const nextEvents = [...events, transition.event as JourneyExecutionPathEventType<TEventType>];\n const target = resolveTransitionTarget(transition);\n\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n pushPath({ steps, events: nextEvents, terminated: \"final\" });\n continue;\n }\n\n const nextSteps = [...steps, target];\n if (steps.includes(target)) {\n cyclesDetected = true;\n pushPath({ steps: nextSteps, events: nextEvents, terminated: \"cycle\" });\n continue;\n }\n\n visit(target, nextSteps, nextEvents);\n if (paths.length >= maxPaths) {\n truncated = true;\n return;\n }\n }\n };\n\n visit(resolvedJourney.initial, [resolvedJourney.initial], []);\n\n return {\n paths,\n truncated,\n cyclesDetected\n };\n}\n/* eslint-enable no-redeclare */\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAA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AAO,OAAAC,EAAQ,WAAY,OAAQ,CAAC,EAC/CP,EAAY,GACZ,MACF,CAEA,QAAWS,KAAcD,EAAU,CACjC,IAAME,EAAa,CAAC,GAAGH,EAAQE,EAAW,KAAkD,EACtFE,EAASC,EAAwBH,CAAU,EAEjD,GAAIE,IAAW,YAAcA,IAAW,aAAc,CACpDT,EAAS,CAAE,MAAAI,EAAO,OAAQI,EAAY,WAAY,OAAQ,CAAC,EAC3D,QACF,CAEA,IAAMG,EAAY,CAAC,GAAGP,EAAOK,CAAM,EACnC,GAAIL,EAAM,SAASK,CAAM,EAAG,CAC1BV,EAAiB,GACjBC,EAAS,CAAE,MAAOW,EAAW,OAAQH,EAAY,WAAY,OAAQ,CAAC,EACtE,QACF,CAGA,GADAN,EAAMO,EAAQE,EAAWH,CAAU,EAC/BX,EAAM,QAAUD,EAAU,CAC5BE,EAAY,GACZ,MACF,CACF,CACF,EAEA,OAAAI,EAAMT,EAAgB,QAAS,CAACA,EAAgB,OAAO,EAAG,CAAC,CAAC,EAErD,CACL,MAAAI,EACA,UAAAC,EACA,eAAAC,CACF,CACF,CH1GO,IAAMa,EAA6B,KACvC,CACC,KAAM,kBACN,MAAO,CAAC,CAAE,gBAAAC,CAAgB,KAAO,CAC/B,eAAgB,KAAO,CACrB,kBAAoBC,GAClBC,EAAkBF,EAAiBC,CAAO,CAC9C,EACF,EACF",
|
|
6
|
+
"names": ["execution_paths_exports", "__export", "createExecutionPathsPlugin", "getExecutionPaths", "__toCommonJS", "isFiniteNumber", "value", "validateFiniteTimeout", "timeoutMs", "label", "resolveTransitionTarget", "transition", "hashTransitionDescriptor", "value", "hash", "index", "buildResolvedTransitions", "transitions", "transitionRouteCounts", "usedIds", "transition", "target", "routeKey", "ordinal", "descriptor", "suffix", "id", "candidate", "resolveJourneyDefinition", "journey", "resolvedTransitions", "initialStep", "linearEntries", "resolvedInitial", "entry", "previousStep", "seenSteps", "offset", "allowedKeys", "key", "validateFiniteTimeout", "transitionGraph", "orderedGraphEntries", "fromKey", "eventMap", "event", "rawEdges", "isTerminal", "edges", "edge", "normalizeLimit", "value", "fallback", "getExecutionPaths", "journey", "options", "resolvedJourney", "resolveJourneyDefinition", "maxDepth", "maxPaths", "paths", "truncated", "cyclesDetected", "pushPath", "path", "visit", "currentStepId", "steps", "events", "outgoing", "transition", "nextEvents", "target", "resolveTransitionTarget", "nextSteps", "createExecutionPathsPlugin", "resolvedJourney", "options", "getExecutionPaths"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { JourneyExecutionPathOptions, JourneyExecutionPathsResult, JourneyFullEventType, JourneyJsonObject, JourneyMachine } from "../../types";
|
|
2
|
+
export type JourneyExecutionPathsMachineExtension<TStepId extends string, TEventType extends string> = {
|
|
3
|
+
getExecutionPaths: (options?: JourneyExecutionPathOptions) => JourneyExecutionPathsResult<TStepId, TEventType>;
|
|
4
|
+
};
|
|
5
|
+
export type JourneyExecutionPathsMachine<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> & JourneyExecutionPathsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;
|
|
6
|
+
/**
|
|
7
|
+
* Creates a plugin that augments a machine with structural execution-path
|
|
8
|
+
* enumeration without pulling graph code into the base entrypoint.
|
|
9
|
+
*/
|
|
10
|
+
export declare const createExecutionPathsPlugin: () => {
|
|
11
|
+
name: string;
|
|
12
|
+
setup: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>({ resolvedJourney }: import("../../types").JourneyMachinePluginSetupContext<TContext, TStepId, TEventMap, TStepMeta, THandlers>) => {
|
|
13
|
+
augmentMachine: () => {
|
|
14
|
+
getExecutionPaths: (options?: JourneyExecutionPathOptions) => JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
export { getExecutionPaths } from "./execution-paths";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { JourneyExecutionPathOptions, JourneyExecutionPathsResult, JourneyFullEventType, JourneyJsonObject, JourneyMachine } from "../../types";
|
|
2
|
+
export type JourneyExecutionPathsMachineExtension<TStepId extends string, TEventType extends string> = {
|
|
3
|
+
getExecutionPaths: (options?: JourneyExecutionPathOptions) => JourneyExecutionPathsResult<TStepId, TEventType>;
|
|
4
|
+
};
|
|
5
|
+
export type JourneyExecutionPathsMachine<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> & JourneyExecutionPathsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;
|
|
6
|
+
/**
|
|
7
|
+
* Creates a plugin that augments a machine with structural execution-path
|
|
8
|
+
* enumeration without pulling graph code into the base entrypoint.
|
|
9
|
+
*/
|
|
10
|
+
export declare const createExecutionPathsPlugin: () => {
|
|
11
|
+
name: string;
|
|
12
|
+
setup: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>({ resolvedJourney }: import("../../types").JourneyMachinePluginSetupContext<TContext, TStepId, TEventMap, TStepMeta, THandlers>) => {
|
|
13
|
+
augmentMachine: () => {
|
|
14
|
+
getExecutionPaths: (options?: JourneyExecutionPathOptions) => JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
export { getExecutionPaths } from "./execution-paths";
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var I=n=>typeof n=="number"&&Number.isFinite(n),J=(n,i)=>{if(n!==void 0&&!I(n))throw new Error(`${i} must define a finite numeric "timeoutMs" when provided.`)};var h=n=>n.event==="completeJourney"?"COMPLETE":n.event==="terminateJourney"?"TERMINATED":n.to;var b=n=>{let i=2166136261;for(let a=0;a<n.length;a+=1)i^=n.charCodeAt(a),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},E=n=>{let i=new Map,a=new Set;return n.map(s=>{let f=s.event==="completeJourney"?"COMPLETE":s.event==="terminateJourney"?"TERMINATED":String(s.to),t=JSON.stringify({from:s.from,event:s.event,target:f}),u=(i.get(t)??0)+1;i.set(t,u);let r=JSON.stringify({from:s.from,event:s.event,target:f,ordinal:u}),p=0,d=(()=>{let c=b(r);for(;a.has(c);)p+=1,c=b(`${r}:${p}`);return c})();return a.add(d),{...s,id:d,...s.label!==void 0?{label:s.label}:{}}})},g=n=>{let i=[],{transitions:a}=n;if(a===void 0)return{...n,transitions:E(i)};if(Array.isArray(a)){if(a.length===0)throw new Error("Journey linear transitions must include the initial step as the first item.");let[t,...u]=a;if(typeof t!="string")throw new Error("Journey linear transitions at index 0 must be a step id string.");if(!(t in n.steps))throw new Error(`Journey linear transitions reference unknown step "${t}".`);let r=n.initial??t;if(n.initial!==void 0&&!a.map(e=>typeof e=="string"?e:e.step).includes(n.initial))throw new Error(`Journey initial step "${n.initial}" does not exist in linear transitions.`);let p=t,d=new Set([t]);for(let[c,e]of u.entries()){let o=c+1;if(typeof e=="string"){if(!(e in n.steps))throw new Error(`Journey linear transitions reference unknown step "${e}".`);if(d.has(e))throw new Error(`Journey linear transitions contain duplicate step "${e}" at index ${o}.`);d.add(e),i.push({from:p,event:"goToNextStep",to:e}),p=e;continue}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Journey linear transitions at index ${o} must be a step id string or step config object.`);let T=new Set(["step","label","updateContext","onEnter","onLeave","timeoutMs"]);for(let y of Object.keys(e))if(!T.has(y))throw new Error(`Journey linear transition object at index ${o} contains unsupported field "${y}". Allowed fields are "step", "label", "updateContext", "onEnter", "onLeave", and "timeoutMs".`);if(typeof e.step!="string")throw new Error(`Journey linear transition object at index ${o} must define string "step".`);if(!(e.step in n.steps))throw new Error(`Journey linear transitions reference unknown step "${e.step}".`);if(d.has(e.step))throw new Error(`Journey linear transitions contain duplicate step "${e.step}" at index ${o}.`);if(d.add(e.step),e.updateContext!==void 0&&typeof e.updateContext!="function")throw new Error(`Journey linear transition object at index ${o} must define "updateContext" as a function when provided.`);if(e.onEnter!==void 0&&typeof e.onEnter!="function")throw new Error(`Journey linear transition object at index ${o} must define "onEnter" as a function when provided.`);if(e.onLeave!==void 0&&typeof e.onLeave!="function")throw new Error(`Journey linear transition object at index ${o} must define "onLeave" as a function when provided.`);J(e.timeoutMs,`Journey linear transition object at index ${o}`),i.push({...e.label!==void 0?{label:e.label}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.updateContext!==void 0?{updateContext:e.updateContext}:{},...e.onEnter!==void 0?{onEnter:e.onEnter}:{},...e.onLeave!==void 0?{onLeave:e.onLeave}:{},from:p,event:"goToNextStep",to:e.step}),p=e.step}return{...n,initial:r,transitions:E(i)}}if(!a||typeof a!="object")throw new Error("Journey transitions must be an array or an object map when provided.");let s=a,f=[...Object.entries(s).filter(([t])=>t!=="global"),...s.global?[["global",s.global]]:[]];for(let[t,u]of f){if(t!=="global"&&!(t in n.steps))throw new Error(`Journey transitions reference unknown step "${t}".`);if(!u||typeof u!="object"||Array.isArray(u))throw new Error(`Journey transitions for "${t}" must be an event map object.`);for(let[r,p]of Object.entries(u)){let d=r==="completeJourney"||r==="terminateJourney",c=d&&(p===!0||Array.isArray(p)&&p.length===0)?[{}]:p;if(!Array.isArray(c))throw new Error(`Journey transitions for "${t}.${r}" must be an array.`);for(let[e,o]of c.entries()){if(!o||typeof o!="object")throw new Error(`Journey transition at "${t}.${r}[${e}]" must be an object.`);let T=new Set(d?["when","updateContext","onEnter","onLeave","label","timeoutMs"]:["to","when","updateContext","onEnter","onLeave","label","timeoutMs"]);for(let y of Object.keys(o))if(!T.has(y))throw new Error(`Journey transition at "${t}.${r}[${e}]" contains unsupported field "${y}".`);if(!d&&typeof o.to!="string")throw new Error(`Journey transition at "${t}.${r}[${e}]" must define string "to".`);if(o.when!==void 0&&typeof o.when!="function")throw new Error(`Journey transition at "${t}.${r}[${e}]" must define "when" as a function when provided.`);if(o.updateContext!==void 0&&typeof o.updateContext!="function")throw new Error(`Journey transition at "${t}.${r}[${e}]" must define "updateContext" as a function when provided.`);if(o.onEnter!==void 0&&typeof o.onEnter!="function")throw new Error(`Journey transition at "${t}.${r}[${e}]" must define "onEnter" as a function when provided.`);if(o.onLeave!==void 0&&typeof o.onLeave!="function")throw new Error(`Journey transition at "${t}.${r}[${e}]" must define "onLeave" as a function when provided.`);if(o.label!==void 0&&typeof o.label!="string")throw new Error(`Journey transition at "${t}.${r}[${e}]" must define "label" as a string when provided.`);J(o.timeoutMs,`Journey transition at "${t}.${r}[${e}]"`),i.push({...o,from:t==="global"?"*":t,event:r})}}}return{...n,transitions:E(i)}};var v=(n,i)=>typeof n!="number"||!Number.isFinite(n)?i:Math.max(1,Math.trunc(n));function S(n,i={}){let s=(e=>Array.isArray(e.transitions)&&(e.transitions.length===0||typeof e.transitions[0]=="object"&&e.transitions[0]!==null))(n)?n:g(n),f=v(i.maxDepth,5),t=v(i.maxPaths,10),u=[],r=!1,p=!1,d=e=>{if(u.length>=t){r=!0;return}u.push(e)},c=(e,o,T)=>{if(u.length>=t){r=!0;return}let y=s.transitions.filter(l=>l.from==="*"||l.from===e);if(y.length===0){d({steps:o,events:T,terminated:"final"});return}if(T.length>=f){d({steps:o,events:T,terminated:"depth"}),r=!0;return}for(let l of y){let w=[...T,l.event],x=h(l);if(x==="COMPLETE"||x==="TERMINATED"){d({steps:o,events:w,terminated:"final"});continue}let m=[...o,x];if(o.includes(x)){p=!0,d({steps:m,events:w,terminated:"cycle"});continue}if(c(x,m,w),u.length>=t){r=!0;return}}};return c(s.initial,[s.initial],[]),{paths:u,truncated:r,cyclesDetected:p}}var j=()=>({name:"execution-paths",setup:({resolvedJourney:n})=>({augmentMachine:()=>({getExecutionPaths:i=>S(n,i)})})});export{j as createExecutionPathsPlugin,S as getExecutionPaths};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/journey-machine/helpers.ts", "../../../src/journey-machine/resolve-journey-definition.ts", "../../../src/plugins/execution-paths/execution-paths.ts", "../../../src/plugins/execution-paths/index.ts"],
|
|
4
|
+
"sourcesContent": ["import type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyGoToEvent,\n JourneyJsonObject,\n JourneyJsonValue,\n JourneyPayloadFor,\n JourneyResolvedTransition,\n JourneySendEvent,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransition,\n JourneyTransitionArgs\n} from \"../types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n\nconst cloneSerializableValue = <T extends JourneyJsonValue>(value: T): T => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneSerializableValue(entry)) as T;\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneSerializableValue(entryValue as JourneyJsonValue)\n ])\n ) as T;\n }\n\n return value;\n};\n\ntype SerializableCheckState = {\n readonly seen: WeakSet<object>;\n};\n\nconst describeValue = (value: unknown): string => {\n if (value === null) {\n return \"null\";\n }\n\n if (Array.isArray(value)) {\n return \"array\";\n }\n\n if (typeof value === \"object\") {\n const constructorName = (value as { constructor?: { name?: string } }).constructor?.name;\n return constructorName && constructorName !== \"Object\" ? constructorName : \"object\";\n }\n\n return typeof value;\n};\n\nfunction assertSerializableValue(\n value: unknown,\n label: string,\n state: SerializableCheckState,\n path: readonly string[] = []\n): asserts value is JourneyJsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return;\n }\n\n const pathLabel = path.length === 0 ? label : `${label}.${path.join(\".\")}`;\n\n if (value === undefined) {\n throw new Error(`${pathLabel} must be JSON-serializable. Received undefined.`);\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\" || typeof value === \"function\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${typeof value}.`);\n }\n\n if (typeof value !== \"object\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${describeValue(value)}.`);\n }\n\n if (state.seen.has(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Circular references are not supported.`\n );\n }\n\n state.seen.add(value);\n\n if (Array.isArray(value)) {\n for (const [index, entryValue] of value.entries()) {\n assertSerializableValue(entryValue, label, state, [...path, String(index)]);\n }\n return;\n }\n\n if (!isPlainObject(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Received non-plain ${describeValue(value)}.`\n );\n }\n\n for (const [key, entryValue] of Object.entries(value)) {\n assertSerializableValue(entryValue, label, state, [...path, key]);\n }\n}\n\nexport function assertSerializableContext<TContext extends JourneyJsonObject>(\n context: TContext,\n label = \"Journey context\"\n): TContext {\n assertSerializableValue(context, label, { seen: new WeakSet() });\n return context;\n}\n\nexport const cloneContext = <TContext extends JourneyJsonObject>(context: TContext): TContext =>\n cloneSerializableValue(assertSerializableContext(context));\n\nconst cloneDefinitionValueFallback = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneDefinitionValueFallback(entry));\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n\n if (value instanceof Map) {\n return new Map(\n [...value.entries()].map(([key, entryValue]) => [\n cloneDefinitionValueFallback(key),\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n if (value instanceof Set) {\n return new Set([...value].map((entry) => cloneDefinitionValueFallback(entry)));\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n return value;\n};\n\nexport const cloneMetaValue = <T>(value: T): T => {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) {\n return value;\n }\n\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(value);\n } catch {\n return cloneDefinitionValueFallback(value) as T;\n }\n } else {\n return cloneDefinitionValueFallback(value) as T;\n }\n};\n\nconst freezeSnapshotValue = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n freezeSnapshotValue(item);\n }\n Object.freeze(value);\n return;\n }\n\n if (!isPlainObject(value)) {\n return;\n }\n\n for (const entryValue of Object.values(value)) {\n freezeSnapshotValue(entryValue);\n }\n Object.freeze(value);\n};\n\nexport const normalizeStepCount = (steps?: number): number => {\n if (typeof steps !== \"number\" || !Number.isFinite(steps)) {\n return 1;\n }\n return Math.max(1, Math.trunc(steps));\n};\n\nexport const now = (): number => Date.now();\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nconst normalizeVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n stepIds: readonly TStepId[]\n): Record<TStepId, boolean> =>\n Object.fromEntries(stepIds.map((stepId) => [stepId, visited[stepId] === true])) as Record<\n TStepId,\n boolean\n >;\n\nexport const buildVisitedFromTimeline = <TStepId extends string>(\n timeline: readonly TStepId[],\n stepIds?: readonly TStepId[]\n): Record<TStepId, boolean> => {\n const resolvedStepIds = stepIds ?? unique(timeline);\n const visited = Object.fromEntries(resolvedStepIds.map((stepId) => [stepId, false])) as Record<\n TStepId,\n boolean\n >;\n\n for (const stepId of timeline) {\n visited[stepId] = true;\n }\n\n return visited;\n};\n\nexport const appendVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n current: TStepId\n): Record<TStepId, boolean> => ({\n ...visited,\n [current]: true\n});\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value);\n\nexport const validateFiniteTimeout = (timeoutMs: unknown, label: string) => {\n if (timeoutMs !== undefined && !isFiniteNumber(timeoutMs)) {\n throw new Error(`${label} must define a finite numeric \"timeoutMs\" when provided.`);\n }\n};\n\nexport class JourneyTimeoutError extends Error {\n override name = \"JourneyTimeoutError\";\n\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class JourneyDisposedError extends Error {\n override name = \"JourneyDisposedError\";\n readonly operation: string;\n\n constructor(operation: string) {\n super(`Journey machine has been disposed; \"${operation}\" can no longer be used.`);\n this.operation = operation;\n }\n}\n\ntype DiagnosticGlobal = typeof globalThis & {\n __DEV__?: unknown;\n process?: {\n env?: {\n NODE_ENV?: string;\n };\n };\n};\n\nexport const isDevelopmentEnvironment = (): boolean => {\n const diagnosticGlobal = globalThis as DiagnosticGlobal;\n if (typeof diagnosticGlobal.__DEV__ === \"boolean\") {\n return diagnosticGlobal.__DEV__;\n }\n\n const nodeEnv = diagnosticGlobal.process?.env?.NODE_ENV;\n return nodeEnv === undefined || nodeEnv === \"development\";\n};\n\nexport const warnInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.warn(message);\n return;\n }\n\n console.warn(message, detail);\n};\n\nexport const errorInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.error(message);\n return;\n }\n\n console.error(message, detail);\n};\n\nexport const withTimeout = async <T>(\n promise: PromiseLike<T>,\n timeoutMs: number | undefined,\n buildError: () => Error\n): Promise<T> => {\n if (!isFiniteNumber(timeoutMs) || timeoutMs <= 0) {\n return await promise;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(buildError());\n }, timeoutMs);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n};\n\nexport const withAbortSignal = async <T>(\n promise: PromiseLike<T>,\n signal: AbortSignal\n): Promise<T> => {\n if (signal.aborted) {\n throw signal.reason;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(signal.reason);\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n};\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: \"idle\",\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToStepByIdEvent = <\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n>(\n event: JourneySendEvent<TStepId, TEventMap>\n): event is JourneyGoToEvent<TStepId, JourneyPayloadFor<TEventMap, \"goToStepById\">> =>\n event.type === \"goToStepById\" && \"stepId\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal\n): target is JourneyTerminal => target === \"COMPLETE\" || target === \"TERMINATED\";\n\nexport const resolveTransitionTarget = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transition: JourneyTransition<TContext, TStepId, TEventMap, THandlers>\n): TStepId | JourneyTerminal =>\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : (transition.to as TStepId | JourneyTerminal);\n\nexport const validateJourneyTransitions = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[],\n steps: Record<TStepId, unknown>\n) => {\n const stepRegistry = steps as Record<string, unknown>;\n const allowedKeys = new Set([\n \"from\",\n \"event\",\n \"to\",\n \"when\",\n \"updateContext\",\n \"onEnter\",\n \"onLeave\",\n \"id\",\n \"label\",\n \"timeoutMs\"\n ]);\n\n for (const [index, transition] of transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n for (const key of Object.keys(transition)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey transition at index ${index} contains unsupported field \"${key}\".`\n );\n }\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (transition.from !== \"*\" && !(transition.from in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n validateFiniteTimeout(transition.timeoutMs, `Journey transition at index ${index}`);\n\n if (transition.when !== undefined && typeof transition.when !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"when\" as a function when provided.`\n );\n }\n\n if (transition.updateContext !== undefined && typeof transition.updateContext !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (transition.onEnter !== undefined && typeof transition.onEnter !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (transition.onLeave !== undefined && typeof transition.onLeave !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onLeave\" as a function when provided.`\n );\n }\n\n if (transition.id !== undefined && typeof transition.id !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"id\" as a string when provided.`\n );\n }\n\n if (transition.label !== undefined && typeof transition.label !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"label\" as a string when provided.`\n );\n }\n\n if (transition.event === \"completeJourney\" || transition.event === \"terminateJourney\") {\n if (\"to\" in transition && transition.to !== undefined) {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" cannot define \"to\".`\n );\n }\n continue;\n }\n\n if (typeof transition.to !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" must define string \"to\".`\n );\n }\n\n if (!isTerminalTarget(transition.to) && !(transition.to in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n};\n\nexport const buildSendResult = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n transitioned: boolean,\n options: {\n transitionId?: string;\n label?: string;\n error?: unknown;\n } = {}\n): JourneySendResult<TContext, TStepId> => ({\n transitioned,\n ...(options.transitionId !== undefined ? { transitionId: options.transitionId } : {}),\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(\"error\" in options ? { error: options.error } : {}),\n snapshot\n});\n\nexport const buildSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n timeline: readonly TStepId[],\n index: number,\n context: TContext,\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n visited?: Record<TStepId, boolean>\n): JourneySnapshot<TContext, TStepId> => {\n if (timeline.length === 0) {\n throw new Error(\"Journey timeline cannot be empty.\");\n }\n\n const safeIndex = Math.max(0, Math.min(Math.trunc(index), timeline.length - 1));\n const currentStepId = timeline[safeIndex] as TStepId;\n const stepIds = unique(\n visited ? ([...(Object.keys(visited) as TStepId[]), ...timeline] as const) : timeline\n );\n\n return {\n status,\n currentStepId,\n history: {\n timeline: [...timeline],\n index: safeIndex\n },\n context: cloneContext(context),\n visited: visited\n ? normalizeVisited(visited, stepIds)\n : buildVisitedFromTimeline(timeline, stepIds),\n async: cloneSerializableValue(\n asyncState as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n};\n\nexport const stabilizeSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>\n): JourneySnapshot<TContext, TStepId> => {\n const stableSnapshot: JourneySnapshot<TContext, TStepId> = {\n ...snapshot,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: cloneContext(snapshot.context),\n visited: { ...snapshot.visited },\n async: cloneSerializableValue(\n snapshot.async as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n\n freezeSnapshotValue(stableSnapshot);\n return stableSnapshot;\n};\n\nexport const selectTransition = async <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>,\n TTransition extends {\n from: TStepId | \"*\";\n event: string;\n when?: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>;\n timeoutMs?: number;\n id?: string;\n label?: string;\n }\n>(\n transitions: readonly TTransition[],\n snapshot: JourneySnapshot<TContext, TStepId>,\n event: JourneyEvent<TStepId, TEventMap>,\n signal: AbortSignal,\n handlers: THandlers,\n hooks?: {\n onAsyncGuardStart?: (transition: TTransition) => void;\n onAsyncGuardSuccess?: (transition: TTransition) => void;\n onAsyncGuardError?: (transition: TTransition, error: unknown) => void;\n },\n defaultTimeoutMs?: number\n): Promise<TTransition | null> => {\n for (const transition of transitions) {\n const fromMatches = transition.from === \"*\" || transition.from === snapshot.currentStepId;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n let guardResult: boolean | Promise<boolean>;\n if (signal.aborted) {\n throw signal.reason;\n }\n\n guardResult = (\n transition.when as (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>\n )({\n snapshot,\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event,\n signal,\n handlers\n });\n\n const asyncGuard = isPromiseLike(guardResult);\n const asyncGuardPromise = asyncGuard ? (guardResult as PromiseLike<boolean>) : null;\n\n let allowed: boolean;\n try {\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n allowed = await withTimeout(\n withAbortSignal(asyncGuardPromise as PromiseLike<boolean>, signal),\n transition.timeoutMs ?? defaultTimeoutMs,\n () =>\n new JourneyTimeoutError(\n `Transition guard timed out after ${transition.timeoutMs ?? defaultTimeoutMs}ms (event: ${event.type}, transition: ${transition.id ?? \"<anonymous>\"}).`\n )\n );\n } else {\n allowed = guardResult as boolean;\n }\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId> => {\n const baseTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n let nextTimeline = baseTimeline;\n if (nextCurrent !== snapshot.currentStepId) {\n nextTimeline = [...baseTimeline, nextCurrent];\n }\n\n const nextIndex = nextTimeline.length - 1;\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(\n nextTimeline,\n nextIndex,\n nextContext,\n snapshot.status,\n snapshot.async,\n visited\n );\n};\n", "import { validateFiniteTimeout } from \"./helpers\";\n\nimport type {\n JourneyDefinition,\n JourneyJsonObject,\n JourneyResolvedDefinition,\n JourneyResolvedTransition,\n JourneyTransition,\n JourneyTransitionGraph\n} from \"../types\";\n\nconst hashTransitionDescriptor = (value: string) => {\n let hash = 2166136261;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n};\n\nconst buildResolvedTransitions = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventMap, THandlers>[]\n): JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[] => {\n const transitionRouteCounts = new Map<string, number>();\n const usedIds = new Set<string>();\n\n return transitions.map((transition) => {\n const target =\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : String(transition.to);\n const routeKey = JSON.stringify({\n from: transition.from,\n event: transition.event,\n target\n });\n const ordinal = (transitionRouteCounts.get(routeKey) ?? 0) + 1;\n transitionRouteCounts.set(routeKey, ordinal);\n\n const descriptor = JSON.stringify({\n from: transition.from,\n event: transition.event,\n target,\n ordinal\n });\n\n let suffix = 0;\n const id = (() => {\n let candidate = hashTransitionDescriptor(descriptor);\n while (usedIds.has(candidate)) {\n suffix += 1;\n candidate = hashTransitionDescriptor(`${descriptor}:${suffix}`);\n }\n return candidate;\n })();\n usedIds.add(id);\n\n return {\n ...transition,\n id,\n ...(transition.label !== undefined ? { label: transition.label } : {})\n } as JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>;\n });\n};\n\nexport const resolveJourneyDefinition = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>\n): JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers> => {\n type TEventType = string;\n const resolvedTransitions: JourneyTransition<TContext, TStepId, TEventMap, THandlers>[] = [];\n const { transitions } = journey;\n\n if (transitions === undefined) {\n return {\n ...journey,\n transitions: buildResolvedTransitions(resolvedTransitions)\n } as JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n }\n\n if (Array.isArray(transitions)) {\n if (transitions.length === 0) {\n throw new Error(\n \"Journey linear transitions must include the initial step as the first item.\"\n );\n }\n\n const [initialStep, ...linearEntries] = transitions;\n if (typeof initialStep !== \"string\") {\n throw new Error(\"Journey linear transitions at index 0 must be a step id string.\");\n }\n\n if (!(initialStep in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${initialStep}\".`);\n }\n\n // Resolve initial: use journey.initial if provided (start from middle), otherwise array[0]\n const resolvedInitial = (journey.initial ?? initialStep) as TStepId;\n\n if (journey.initial !== undefined) {\n const allStepIds = transitions.map((entry) =>\n typeof entry === \"string\" ? entry : entry.step\n );\n if (!allStepIds.includes(journey.initial)) {\n throw new Error(\n `Journey initial step \"${journey.initial}\" does not exist in linear transitions.`\n );\n }\n }\n\n let previousStep = initialStep as TStepId;\n const seenSteps = new Set<string>([initialStep]);\n for (const [offset, entry] of linearEntries.entries()) {\n const index = offset + 1;\n if (typeof entry === \"string\") {\n if (!(entry in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${entry}\".`);\n }\n\n if (seenSteps.has(entry)) {\n throw new Error(\n `Journey linear transitions contain duplicate step \"${entry}\" at index ${index}.`\n );\n }\n seenSteps.add(entry);\n\n resolvedTransitions.push({\n from: previousStep,\n event: \"goToNextStep\" as TEventType,\n to: entry as TStepId\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n previousStep = entry as TStepId;\n continue;\n }\n\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(\n `Journey linear transitions at index ${index} must be a step id string or step config object.`\n );\n }\n\n const allowedKeys = new Set([\n \"step\",\n \"label\",\n \"updateContext\",\n \"onEnter\",\n \"onLeave\",\n \"timeoutMs\"\n ]);\n for (const key of Object.keys(entry)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey linear transition object at index ${index} contains unsupported field \"${key}\". Allowed fields are \"step\", \"label\", \"updateContext\", \"onEnter\", \"onLeave\", and \"timeoutMs\".`\n );\n }\n }\n\n if (typeof entry.step !== \"string\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define string \"step\".`\n );\n }\n\n if (!(entry.step in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${entry.step}\".`);\n }\n\n if (seenSteps.has(entry.step)) {\n throw new Error(\n `Journey linear transitions contain duplicate step \"${entry.step}\" at index ${index}.`\n );\n }\n seenSteps.add(entry.step);\n\n if (entry.updateContext !== undefined && typeof entry.updateContext !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (entry.onEnter !== undefined && typeof entry.onEnter !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (entry.onLeave !== undefined && typeof entry.onLeave !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"onLeave\" as a function when provided.`\n );\n }\n\n validateFiniteTimeout(entry.timeoutMs, `Journey linear transition object at index ${index}`);\n\n resolvedTransitions.push({\n ...(entry.label !== undefined ? { label: entry.label } : {}),\n ...(entry.timeoutMs !== undefined ? { timeoutMs: entry.timeoutMs } : {}),\n ...(entry.updateContext !== undefined ? { updateContext: entry.updateContext } : {}),\n ...(entry.onEnter !== undefined ? { onEnter: entry.onEnter } : {}),\n ...(entry.onLeave !== undefined ? { onLeave: entry.onLeave } : {}),\n from: previousStep,\n event: \"goToNextStep\" as TEventType,\n to: entry.step as TStepId\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n previousStep = entry.step as TStepId;\n }\n\n return {\n ...journey,\n initial: resolvedInitial,\n transitions: buildResolvedTransitions(resolvedTransitions)\n };\n }\n\n if (!transitions || typeof transitions !== \"object\") {\n throw new Error(\"Journey transitions must be an array or an object map when provided.\");\n }\n\n const transitionGraph = transitions as JourneyTransitionGraph<\n TContext,\n TStepId,\n TEventMap,\n THandlers\n >;\n\n const orderedGraphEntries = [\n ...Object.entries(transitionGraph).filter(([fromKey]) => fromKey !== \"global\"),\n ...(transitionGraph.global ? ([[\"global\", transitionGraph.global]] as const) : [])\n ];\n\n for (const [fromKey, eventMap] of orderedGraphEntries) {\n if (fromKey !== \"global\" && !(fromKey in journey.steps)) {\n throw new Error(`Journey transitions reference unknown step \"${fromKey}\".`);\n }\n\n if (!eventMap || typeof eventMap !== \"object\" || Array.isArray(eventMap)) {\n throw new Error(`Journey transitions for \"${fromKey}\" must be an event map object.`);\n }\n\n for (const [event, rawEdges] of Object.entries(eventMap) as Array<\n [TEventType, (typeof eventMap)[TEventType] | true]\n >) {\n const isTerminal = event === \"completeJourney\" || event === \"terminateJourney\";\n const edges =\n isTerminal && (rawEdges === true || (Array.isArray(rawEdges) && rawEdges.length === 0))\n ? [{}]\n : rawEdges;\n\n if (!Array.isArray(edges)) {\n throw new Error(`Journey transitions for \"${fromKey}.${event}\" must be an array.`);\n }\n\n for (const [index, edge] of edges.entries()) {\n if (!edge || typeof edge !== \"object\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must be an object.`\n );\n }\n\n const allowedKeys = new Set(\n isTerminal\n ? [\"when\", \"updateContext\", \"onEnter\", \"onLeave\", \"label\", \"timeoutMs\"]\n : [\"to\", \"when\", \"updateContext\", \"onEnter\", \"onLeave\", \"label\", \"timeoutMs\"]\n );\n for (const key of Object.keys(edge)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" contains unsupported field \"${key}\".`\n );\n }\n }\n\n if (!isTerminal && typeof (edge as { to?: unknown }).to !== \"string\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define string \"to\".`\n );\n }\n\n if ((edge as { when?: unknown }).when !== undefined && typeof edge.when !== \"function\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"when\" as a function when provided.`\n );\n }\n\n if (\n (edge as { updateContext?: unknown }).updateContext !== undefined &&\n typeof edge.updateContext !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (\n (edge as { onEnter?: unknown }).onEnter !== undefined &&\n typeof edge.onEnter !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (\n (edge as { onLeave?: unknown }).onLeave !== undefined &&\n typeof edge.onLeave !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"onLeave\" as a function when provided.`\n );\n }\n\n if ((edge as { label?: unknown }).label !== undefined && typeof edge.label !== \"string\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"label\" as a string when provided.`\n );\n }\n\n validateFiniteTimeout(\n (edge as { timeoutMs?: unknown }).timeoutMs,\n `Journey transition at \"${fromKey}.${event}[${index}]\"`\n );\n\n resolvedTransitions.push({\n ...edge,\n from: (fromKey === \"global\" ? \"*\" : fromKey) as TStepId | \"*\",\n event\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n }\n }\n }\n\n return {\n ...journey,\n transitions: buildResolvedTransitions(resolvedTransitions)\n } as JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n};\n", "/* eslint-disable no-redeclare */\nimport { resolveTransitionTarget } from \"../../journey-machine/helpers\";\nimport { resolveJourneyDefinition } from \"../../journey-machine/resolve-journey-definition\";\n\nimport type {\n JourneyDefinition,\n JourneyExecutionPath,\n JourneyExecutionPathEventType,\n JourneyExecutionPathOptions,\n JourneyExecutionPathsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyResolvedDefinition\n} from \"../../types\";\n\nconst normalizeLimit = (value: number | undefined, fallback: number): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n\n return Math.max(1, Math.trunc(value));\n};\n\n/**\n * Enumerates structural execution paths from a resolved journey definition.\n */\nexport function getExecutionPaths<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n options?: JourneyExecutionPathOptions\n): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;\nexport function getExecutionPaths<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey: JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n options?: JourneyExecutionPathOptions\n): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;\nexport function getExecutionPaths<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey:\n | JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>\n | JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n options: JourneyExecutionPathOptions = {}\n): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>> {\n type TEventType = JourneyFullEventType<TEventMap>;\n const isResolvedJourneyDefinition = (\n value: typeof journey\n ): value is JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers> =>\n Array.isArray(value.transitions) &&\n (value.transitions.length === 0 ||\n (typeof value.transitions[0] === \"object\" && value.transitions[0] !== null));\n const resolvedJourney = isResolvedJourneyDefinition(journey)\n ? journey\n : resolveJourneyDefinition(journey);\n const maxDepth = normalizeLimit(options.maxDepth, 5);\n const maxPaths = normalizeLimit(options.maxPaths, 10);\n const paths: JourneyExecutionPath<TStepId, TEventType>[] = [];\n let truncated = false;\n let cyclesDetected = false;\n\n const pushPath = (path: JourneyExecutionPath<TStepId, TEventType>) => {\n if (paths.length >= maxPaths) {\n truncated = true;\n return;\n }\n\n paths.push(path);\n };\n\n const visit = (\n currentStepId: TStepId,\n steps: TStepId[],\n events: JourneyExecutionPathEventType<TEventType>[]\n ) => {\n if (paths.length >= maxPaths) {\n truncated = true;\n return;\n }\n\n const outgoing = resolvedJourney.transitions.filter(\n (transition) => transition.from === \"*\" || transition.from === currentStepId\n );\n\n if (outgoing.length === 0) {\n pushPath({ steps, events, terminated: \"final\" });\n return;\n }\n\n if (events.length >= maxDepth) {\n pushPath({ steps, events, terminated: \"depth\" });\n truncated = true;\n return;\n }\n\n for (const transition of outgoing) {\n const nextEvents = [...events, transition.event as JourneyExecutionPathEventType<TEventType>];\n const target = resolveTransitionTarget(transition);\n\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n pushPath({ steps, events: nextEvents, terminated: \"final\" });\n continue;\n }\n\n const nextSteps = [...steps, target];\n if (steps.includes(target)) {\n cyclesDetected = true;\n pushPath({ steps: nextSteps, events: nextEvents, terminated: \"cycle\" });\n continue;\n }\n\n visit(target, nextSteps, nextEvents);\n if (paths.length >= maxPaths) {\n truncated = true;\n return;\n }\n }\n };\n\n visit(resolvedJourney.initial, [resolvedJourney.initial], []);\n\n return {\n paths,\n truncated,\n cyclesDetected\n };\n}\n/* eslint-enable no-redeclare */\n", "import { getExecutionPaths } from \"./execution-paths\";\n\nimport type {\n JourneyExecutionPathOptions,\n JourneyExecutionPathsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin\n} from \"../../types\";\n\nexport type JourneyExecutionPathsMachineExtension<\n TStepId extends string,\n TEventType extends string\n> = {\n getExecutionPaths: (\n options?: JourneyExecutionPathOptions\n ) => JourneyExecutionPathsResult<TStepId, TEventType>;\n};\n\nexport type JourneyExecutionPathsMachine<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown> = Record<never, never>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> &\n JourneyExecutionPathsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;\n\n/**\n * Creates a plugin that augments a machine with structural execution-path\n * enumeration without pulling graph code into the base entrypoint.\n */\nexport const createExecutionPathsPlugin = () =>\n ({\n name: \"execution-paths\",\n setup: ({ resolvedJourney }) => ({\n augmentMachine: () => ({\n getExecutionPaths: (options?: JourneyExecutionPathOptions) =>\n getExecutionPaths(resolvedJourney, options)\n })\n })\n }) satisfies JourneyMachinePlugin;\n\nexport { getExecutionPaths } from \"./execution-paths\";\n"],
|
|
5
|
+
"mappings": "AAsQA,IAAMA,EAAkBC,GACtB,OAAOA,GAAU,UAAY,OAAO,SAASA,CAAK,EAEvCC,EAAwB,CAACC,EAAoBC,IAAkB,CAC1E,GAAID,IAAc,QAAa,CAACH,EAAeG,CAAS,EACtD,MAAM,IAAI,MAAM,GAAGC,CAAK,0DAA0D,CAEtF,EAwJO,IAAMC,EAMXC,GAEAA,EAAW,QAAU,kBACjB,WACAA,EAAW,QAAU,mBACnB,aACCA,EAAW,GCtapB,IAAMC,EAA4BC,GAAkB,CAClD,IAAIC,EAAO,WACX,QAASC,EAAQ,EAAGA,EAAQF,EAAM,OAAQE,GAAS,EACjDD,GAAQD,EAAM,WAAWE,CAAK,EAC9BD,EAAO,KAAK,KAAKA,EAAM,QA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C5BE,EAAY,GACZ,MACF,CACF,CACF,EAEA,OAAAI,EAAMT,EAAgB,QAAS,CAACA,EAAgB,OAAO,EAAG,CAAC,CAAC,EAErD,CACL,MAAAI,EACA,UAAAC,EACA,eAAAC,CACF,CACF,CC1GO,IAAMa,EAA6B,KACvC,CACC,KAAM,kBACN,MAAO,CAAC,CAAE,gBAAAC,CAAgB,KAAO,CAC/B,eAAgB,KAAO,CACrB,kBAAoBC,GAClBC,EAAkBF,EAAiBC,CAAO,CAC9C,EACF,EACF",
|
|
6
|
+
"names": ["isFiniteNumber", "value", "validateFiniteTimeout", "timeoutMs", "label", "resolveTransitionTarget", "transition", "hashTransitionDescriptor", "value", "hash", "index", "buildResolvedTransitions", "transitions", "transitionRouteCounts", "usedIds", "transition", "target", "routeKey", "ordinal", "descriptor", "suffix", "id", "candidate", "resolveJourneyDefinition", "journey", "resolvedTransitions", "initialStep", "linearEntries", "resolvedInitial", "entry", "previousStep", "seenSteps", "offset", "allowedKeys", "key", "validateFiniteTimeout", "transitionGraph", "orderedGraphEntries", "fromKey", "eventMap", "event", "rawEdges", "isTerminal", "edges", "edge", "normalizeLimit", "value", "fallback", "getExecutionPaths", "journey", "options", "resolvedJourney", "resolveJourneyDefinition", "maxDepth", "maxPaths", "paths", "truncated", "cyclesDetected", "pushPath", "path", "visit", "currentStepId", "steps", "events", "outgoing", "transition", "nextEvents", "target", "resolveTransitionTarget", "nextSteps", "createExecutionPathsPlugin", "resolvedJourney", "options", "getExecutionPaths"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { JourneyPersistenceOptions } from "../../types/persistence.types";
|
|
2
|
+
import type { JourneyJsonObject, JourneySnapshot } from "../../types/journey.types";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a persistence controller for snapshots, including hydration,
|
|
5
|
+
* serialization, and storage error handling.
|
|
6
|
+
*/
|
|
7
|
+
export declare const createPersistenceController: <TContext extends JourneyJsonObject, TStepId extends string>(args: {
|
|
8
|
+
initial: TStepId;
|
|
9
|
+
context: TContext;
|
|
10
|
+
steps: Record<TStepId, unknown>;
|
|
11
|
+
options?: JourneyPersistenceOptions<TContext, TStepId>;
|
|
12
|
+
}) => {
|
|
13
|
+
clearOnReset: boolean;
|
|
14
|
+
hydrateSnapshot: (baseSnapshot?: JourneySnapshot<TContext, TStepId>) => JourneySnapshot<TContext, TStepId>;
|
|
15
|
+
persistSnapshot: (snapshot: JourneySnapshot<TContext, TStepId>) => void;
|
|
16
|
+
removePersistedSnapshot: () => void;
|
|
17
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { JourneyPersistenceOptions } from "../../types/persistence.types";
|
|
2
|
+
import type { JourneyJsonObject, JourneySnapshot } from "../../types/journey.types";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a persistence controller for snapshots, including hydration,
|
|
5
|
+
* serialization, and storage error handling.
|
|
6
|
+
*/
|
|
7
|
+
export declare const createPersistenceController: <TContext extends JourneyJsonObject, TStepId extends string>(args: {
|
|
8
|
+
initial: TStepId;
|
|
9
|
+
context: TContext;
|
|
10
|
+
steps: Record<TStepId, unknown>;
|
|
11
|
+
options?: JourneyPersistenceOptions<TContext, TStepId>;
|
|
12
|
+
}) => {
|
|
13
|
+
clearOnReset: boolean;
|
|
14
|
+
hydrateSnapshot: (baseSnapshot?: JourneySnapshot<TContext, TStepId>) => JourneySnapshot<TContext, TStepId>;
|
|
15
|
+
persistSnapshot: (snapshot: JourneySnapshot<TContext, TStepId>) => void;
|
|
16
|
+
removePersistedSnapshot: () => void;
|
|
17
|
+
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var C=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var U=(e,t)=>{for(var n in t)C(e,n,{get:t[n],enumerable:!0})},X=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of K(t))!Q.call(e,r)&&r!==n&&C(e,r,{get:()=>t[r],enumerable:!(o=q(t,r))||o.enumerable});return e};var Y=e=>X(C({},"__esModule",{value:!0}),e);var ue={};U(ue,{createPersistenceController:()=>R,createPersistencePlugin:()=>ce});module.exports=Y(ue);var p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),w=e=>Array.isArray(e)?e.map(t=>w(t)):p(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,w(n)])):e,v=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 O(e,t,n,o=[]){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return;let r=o.length===0?t:`${t}.${o.join(".")}`;if(e===void 0)throw new Error(`${r} must be JSON-serializable. Received undefined.`);if(typeof e=="bigint"||typeof e=="symbol"||typeof e=="function")throw new Error(`${r} must be JSON-serializable. Received ${typeof e}.`);if(typeof e!="object")throw new Error(`${r} must be JSON-serializable. Received ${v(e)}.`);if(n.seen.has(e))throw new Error(`${r} must be JSON-serializable. Circular references are not supported.`);if(n.seen.add(e),Array.isArray(e)){for(let[s,i]of e.entries())O(i,t,n,[...o,String(s)]);return}if(!p(e))throw new Error(`${r} must be JSON-serializable. Received non-plain ${v(e)}.`);for(let[s,i]of Object.entries(e))O(i,t,n,[...o,s])}function h(e,t="Journey context"){return O(e,t,{seen:new WeakSet}),e}var Z=e=>w(h(e));var $=e=>[...new Set(e)],ee=(e,t)=>Object.fromEntries(t.map(n=>[n,e[n]===!0])),J=(e,t)=>{let n=t??$(e),o=Object.fromEntries(n.map(r=>[r,!1]));for(let r of e)o[r]=!0;return o};var 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"},M=(e,t)=>{if(!(!te()||typeof console>"u")){if(t===void 0){console.warn(e);return}console.warn(e,t)}};var ne=()=>({phase:"idle",eventType:null,transitionId:null,error:null}),V=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(n=>[n,ne()]))});var g=(e,t,n,o,r,s)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let i=Math.max(0,Math.min(Math.trunc(t),e.length-1)),u=e[i],d=$(s?[...Object.keys(s),...e]:e);return{status:o,currentStepId:u,history:{timeline:[...e],index:i},context:Z(n),visited:s?ee(s,d):J(e,d),async:w(r)}};var I=e=>typeof e=="object"&&e!==null,L=e=>e==="idled"||e==="running"||e==="completed"||e==="terminated",re=(e,t)=>{if(typeof e!="string")throw new Error(`Persistence ${t} entries must be strings.`);let n=e.trim();if(!n)throw new Error(`Persistence ${t} entries must not be empty.`);if(n.includes("[")||n.includes("]")||n.includes("*")||n.startsWith(".")||n.endsWith(".")||n.includes(".."))throw new Error(`Persistence ${t} entry "${n}" must use exact dot-separated object keys.`);let o=n.split(".");if(o.some(r=>!r||r.trim()!==r||/^[0-9]+$/.test(r)))throw new Error(`Persistence ${t} entry "${n}" must use exact dot-separated object keys.`);return o},z=(e,t)=>{if(e===void 0)return null;if(!Array.isArray(e))throw new Error(`Persistence ${t} must be an array of dot-separated strings.`);let n=new Map;for(let o of e){let r=re(o,t);n.set(r.join("."),r)}return[...n.values()]},N=(e,t)=>t.length<=e.length&&t.every((n,o)=>e[o]===n),D=(e,t)=>e.some(n=>N(t,n)),oe=(e,t)=>e.some(n=>N(n,t)),G=(e,t,n,o=[])=>{if(D(n,o))return{value:void 0,changed:!0,included:!1};let r=t===null,s=r||D(t,o),i=r||oe(t,o);if(!s&&!i)return{value:void 0,changed:!0,included:!1};if(!p(e))return{value:e,changed:!s,included:s};let u=!1,d={};for(let[y,x]of Object.entries(e)){let f=G(x,t,n,[...o,y]);if(!f.included){u=!0;continue}d[y]=f.value,f.changed&&(u=!0)}return{value:d,changed:u||Object.keys(d).length!==Object.keys(e).length,included:!0}},_=(e,t)=>{if(p(e)&&p(t)){let n=new Map;for(let[o,r]of Object.entries(e))n.set(o,r);for(let[o,r]of Object.entries(t))n.set(o,_(e[o],r));return Object.fromEntries(n)}return t===void 0?e??null:t},se=(e,t)=>_(e,t),ie=()=>{let e=globalThis.localStorage;return!e||typeof e.getItem!="function"||typeof e.setItem!="function"||typeof e.removeItem!="function"?null:e},j=(e,t)=>{if(t){t(e);return}M("Journey persistence encountered an error without an onError handler.",e)},ae=e=>{if(!e)return null;let t=e.storage;if(t==null)try{t=ie()}catch(r){return j(r,e.onError),null}if(!t)return null;let n,o;try{let r=z(e.allowList,"allowList"),s=z(e.blockList,"blockList");n=r?r.map(i=>i.join(".")):void 0,o=s?s.map(i=>i.join(".")):[]}catch(r){return j(r,e.onError),null}return{key:e.key,storage:t,version:e.version??1,clearOnReset:e.clearOnReset??!0,...n?{allowList:n}:{},blockList:o,serialize:e.serialize??JSON.stringify,deserialize:e.deserialize??JSON.parse,...e.migrate?{migrate:e.migrate}:{},...e.onError?{onError:e.onError}:{}}},de=(e,t,n)=>{let o=J(t,n);if(I(e)){let r=!1,s={...o};for(let i of n){let u=e[i];if(u===!0){s[i]=!0;continue}if(u===!1){o[i]&&(r=!0);continue}r=!0}return{visited:s,needsRewrite:r}}if(Array.isArray(e)){let r=J(e.filter(i=>typeof i=="string"&&n.includes(i)),n);return{visited:Object.fromEntries(n.map(i=>[i,o[i]||r[i]])),needsRewrite:!0}}return{visited:o,needsRewrite:!0}},F=(e,t,n)=>{if(!I(e))return null;let o=!1,r=I(e.history)?e.history:null;r||(o=!0);let s=r?.timeline??e.timeline,i=Array.isArray(s)?s.filter(a=>typeof a=="string"&&a in t):[],u=typeof e.currentStepId=="string"&&e.currentStepId in t?e.currentStepId:typeof e.current=="string"&&e.current in t?e.current:null;if(i.length===0){if(!u)return null;i.push(u),o=!0}let d=i.length-1,y=r?.index??e.index;if(typeof y=="number"&&Number.isFinite(y))d=Math.max(0,Math.min(Math.trunc(y),i.length-1)),d!==y&&(o=!0);else if(u){let a=i.lastIndexOf(u);a>=0&&(d=a,o=!0)}let x=L(e.status)?e.status:"idled";L(e.status)||(o=!0);let f=Object.keys(t),{visited:E,needsRewrite:k}=de(e.visited,i,f);return k&&(o=!0),{snapshot:{currentStepId:i[d],history:{timeline:i,index:d},context:h("context"in e?e.context:n,"Persisted journey context"),status:x,visited:E},needsRewrite:o}},R=e=>{let{initial:t,context:n,steps:o,options:r}=e,s=ae(r),i=s?.allowList?s.allowList.map(a=>a.split(".")):null,u=s?s.blockList.map(a=>a.split(".")):[],d=a=>{j(a,s?.onError)},y=a=>{if(!s||i===null&&u.length===0)return{context:a,changed:!1};if(!p(a))return{context:a,changed:!1};let c=G(a,i,u);return{context:c.included&&p(c.value)?c.value:{},changed:c.changed}},x=a=>{if(s)try{let{context:c}=y(a.context),T={version:s.version,snapshot:{currentStepId:a.currentStepId,history:{timeline:[...a.history.timeline],index:a.history.index},context:c,status:a.status,visited:{...a.visited}}};s.storage.setItem(s.key,s.serialize(T))}catch(c){d(c)}},f=()=>{if(s)try{s.storage.removeItem(s.key)}catch(a){d(a)}},E=()=>g([t],0,n,"idled",V(o)),k=(a=E())=>{let c=g(a.history.timeline,a.history.index,a.context,a.status,a.async,a.visited);if(!s)return c;try{let T=s.storage.getItem(s.key);if(!T)return c;let S=s.deserialize(T);if(!I(S))return c;let m=S.version;if(typeof m!="number")return c;let l=null,P=!1;if(m===s.version){let b=F(S.snapshot,o,n);l=b?.snapshot??null,P=!!b?.needsRewrite}else if(s.migrate){let b=s.migrate(S.snapshot,m);l=F(b,o,n)?.snapshot??null,P=l!==null,l||d(new Error(`Journey persistence migrate() returned data that could not be coerced into a valid snapshot. Falling back to the initial snapshot (persisted version: ${m}, current version: ${s.version}).`))}if(!l)return c;let{context:H,changed:B}=y(l.context),W=se(c.context,H),A=g(l.history.timeline,l.history.index,h(W,"Hydrated journey context"),l.status==="running"?"idled":l.status,c.async,l.visited);return(P||B)&&x(A),A}catch(T){return d(T),c}};return{clearOnReset:s?.clearOnReset??!0,hydrateSnapshot:k,persistSnapshot:x,removePersistedSnapshot:f}};var ce=e=>({name:"persistence",setup:(({resolvedJourney:n})=>{let o=R({initial:n.initial,context:n.context,steps:n.steps,options:e});return{hydrateSnapshot:r=>o.hydrateSnapshot(r),onSnapshotChange:({snapshot:r,reason:s})=>{if(s!=="async"){if(s==="reset"&&o.clearOnReset){o.removePersistedSnapshot();return}o.persistSnapshot(r)}}}})});0&&(module.exports={createPersistenceController,createPersistencePlugin});
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/plugins/persistence/index.ts", "../../../src/journey-machine/helpers.ts", "../../../src/plugins/persistence/controller.ts"],
|
|
4
|
+
"sourcesContent": ["import { createPersistenceController } from \"./controller\";\n\nimport type {\n JourneyJsonObject,\n JourneyMachinePlugin,\n JourneyPersistenceOptions\n} from \"../../types\";\n\n/**\n * Creates a machine plugin that hydrates snapshots from storage and persists\n * state changes without pulling persistence code into the base entrypoint.\n */\nexport const createPersistencePlugin = <TContext extends JourneyJsonObject, TStepId extends string>(\n options: JourneyPersistenceOptions<TContext, TStepId>\n) => {\n const setup = (({ resolvedJourney }) => {\n const controller = createPersistenceController({\n initial: resolvedJourney.initial as unknown as TStepId,\n context: resolvedJourney.context as unknown as TContext,\n steps: resolvedJourney.steps as unknown as Record<TStepId, unknown>,\n options\n });\n\n return {\n hydrateSnapshot: (snapshot) => controller.hydrateSnapshot(snapshot as never),\n onSnapshotChange: ({ snapshot, reason }) => {\n if (reason === \"async\") {\n return;\n }\n\n if (reason === \"reset\" && controller.clearOnReset) {\n controller.removePersistedSnapshot();\n return;\n }\n\n controller.persistSnapshot(snapshot as never);\n }\n };\n }) as JourneyMachinePlugin[\"setup\"];\n\n return {\n name: \"persistence\",\n setup\n } satisfies JourneyMachinePlugin;\n};\n\nexport { createPersistenceController };\nexport type { JourneyPersistedState, JourneyPersistenceOptions, JourneyStorage } from \"../../types\";\n", "import type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyGoToEvent,\n JourneyJsonObject,\n JourneyJsonValue,\n JourneyPayloadFor,\n JourneyResolvedTransition,\n JourneySendEvent,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransition,\n JourneyTransitionArgs\n} from \"../types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n\nconst cloneSerializableValue = <T extends JourneyJsonValue>(value: T): T => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneSerializableValue(entry)) as T;\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneSerializableValue(entryValue as JourneyJsonValue)\n ])\n ) as T;\n }\n\n return value;\n};\n\ntype SerializableCheckState = {\n readonly seen: WeakSet<object>;\n};\n\nconst describeValue = (value: unknown): string => {\n if (value === null) {\n return \"null\";\n }\n\n if (Array.isArray(value)) {\n return \"array\";\n }\n\n if (typeof value === \"object\") {\n const constructorName = (value as { constructor?: { name?: string } }).constructor?.name;\n return constructorName && constructorName !== \"Object\" ? constructorName : \"object\";\n }\n\n return typeof value;\n};\n\nfunction assertSerializableValue(\n value: unknown,\n label: string,\n state: SerializableCheckState,\n path: readonly string[] = []\n): asserts value is JourneyJsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return;\n }\n\n const pathLabel = path.length === 0 ? label : `${label}.${path.join(\".\")}`;\n\n if (value === undefined) {\n throw new Error(`${pathLabel} must be JSON-serializable. Received undefined.`);\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\" || typeof value === \"function\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${typeof value}.`);\n }\n\n if (typeof value !== \"object\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${describeValue(value)}.`);\n }\n\n if (state.seen.has(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Circular references are not supported.`\n );\n }\n\n state.seen.add(value);\n\n if (Array.isArray(value)) {\n for (const [index, entryValue] of value.entries()) {\n assertSerializableValue(entryValue, label, state, [...path, String(index)]);\n }\n return;\n }\n\n if (!isPlainObject(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Received non-plain ${describeValue(value)}.`\n );\n }\n\n for (const [key, entryValue] of Object.entries(value)) {\n assertSerializableValue(entryValue, label, state, [...path, key]);\n }\n}\n\nexport function assertSerializableContext<TContext extends JourneyJsonObject>(\n context: TContext,\n label = \"Journey context\"\n): TContext {\n assertSerializableValue(context, label, { seen: new WeakSet() });\n return context;\n}\n\nexport const cloneContext = <TContext extends JourneyJsonObject>(context: TContext): TContext =>\n cloneSerializableValue(assertSerializableContext(context));\n\nconst cloneDefinitionValueFallback = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneDefinitionValueFallback(entry));\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n\n if (value instanceof Map) {\n return new Map(\n [...value.entries()].map(([key, entryValue]) => [\n cloneDefinitionValueFallback(key),\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n if (value instanceof Set) {\n return new Set([...value].map((entry) => cloneDefinitionValueFallback(entry)));\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n return value;\n};\n\nexport const cloneMetaValue = <T>(value: T): T => {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) {\n return value;\n }\n\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(value);\n } catch {\n return cloneDefinitionValueFallback(value) as T;\n }\n } else {\n return cloneDefinitionValueFallback(value) as T;\n }\n};\n\nconst freezeSnapshotValue = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n freezeSnapshotValue(item);\n }\n Object.freeze(value);\n return;\n }\n\n if (!isPlainObject(value)) {\n return;\n }\n\n for (const entryValue of Object.values(value)) {\n freezeSnapshotValue(entryValue);\n }\n Object.freeze(value);\n};\n\nexport const normalizeStepCount = (steps?: number): number => {\n if (typeof steps !== \"number\" || !Number.isFinite(steps)) {\n return 1;\n }\n return Math.max(1, Math.trunc(steps));\n};\n\nexport const now = (): number => Date.now();\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nconst normalizeVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n stepIds: readonly TStepId[]\n): Record<TStepId, boolean> =>\n Object.fromEntries(stepIds.map((stepId) => [stepId, visited[stepId] === true])) as Record<\n TStepId,\n boolean\n >;\n\nexport const buildVisitedFromTimeline = <TStepId extends string>(\n timeline: readonly TStepId[],\n stepIds?: readonly TStepId[]\n): Record<TStepId, boolean> => {\n const resolvedStepIds = stepIds ?? unique(timeline);\n const visited = Object.fromEntries(resolvedStepIds.map((stepId) => [stepId, false])) as Record<\n TStepId,\n boolean\n >;\n\n for (const stepId of timeline) {\n visited[stepId] = true;\n }\n\n return visited;\n};\n\nexport const appendVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n current: TStepId\n): Record<TStepId, boolean> => ({\n ...visited,\n [current]: true\n});\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value);\n\nexport const validateFiniteTimeout = (timeoutMs: unknown, label: string) => {\n if (timeoutMs !== undefined && !isFiniteNumber(timeoutMs)) {\n throw new Error(`${label} must define a finite numeric \"timeoutMs\" when provided.`);\n }\n};\n\nexport class JourneyTimeoutError extends Error {\n override name = \"JourneyTimeoutError\";\n\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class JourneyDisposedError extends Error {\n override name = \"JourneyDisposedError\";\n readonly operation: string;\n\n constructor(operation: string) {\n super(`Journey machine has been disposed; \"${operation}\" can no longer be used.`);\n this.operation = operation;\n }\n}\n\ntype DiagnosticGlobal = typeof globalThis & {\n __DEV__?: unknown;\n process?: {\n env?: {\n NODE_ENV?: string;\n };\n };\n};\n\nexport const isDevelopmentEnvironment = (): boolean => {\n const diagnosticGlobal = globalThis as DiagnosticGlobal;\n if (typeof diagnosticGlobal.__DEV__ === \"boolean\") {\n return diagnosticGlobal.__DEV__;\n }\n\n const nodeEnv = diagnosticGlobal.process?.env?.NODE_ENV;\n return nodeEnv === undefined || nodeEnv === \"development\";\n};\n\nexport const warnInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.warn(message);\n return;\n }\n\n console.warn(message, detail);\n};\n\nexport const errorInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.error(message);\n return;\n }\n\n console.error(message, detail);\n};\n\nexport const withTimeout = async <T>(\n promise: PromiseLike<T>,\n timeoutMs: number | undefined,\n buildError: () => Error\n): Promise<T> => {\n if (!isFiniteNumber(timeoutMs) || timeoutMs <= 0) {\n return await promise;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(buildError());\n }, timeoutMs);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n};\n\nexport const withAbortSignal = async <T>(\n promise: PromiseLike<T>,\n signal: AbortSignal\n): Promise<T> => {\n if (signal.aborted) {\n throw signal.reason;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(signal.reason);\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n};\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: \"idle\",\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToStepByIdEvent = <\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n>(\n event: JourneySendEvent<TStepId, TEventMap>\n): event is JourneyGoToEvent<TStepId, JourneyPayloadFor<TEventMap, \"goToStepById\">> =>\n event.type === \"goToStepById\" && \"stepId\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal\n): target is JourneyTerminal => target === \"COMPLETE\" || target === \"TERMINATED\";\n\nexport const resolveTransitionTarget = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transition: JourneyTransition<TContext, TStepId, TEventMap, THandlers>\n): TStepId | JourneyTerminal =>\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : (transition.to as TStepId | JourneyTerminal);\n\nexport const validateJourneyTransitions = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[],\n steps: Record<TStepId, unknown>\n) => {\n const stepRegistry = steps as Record<string, unknown>;\n const allowedKeys = new Set([\n \"from\",\n \"event\",\n \"to\",\n \"when\",\n \"updateContext\",\n \"onEnter\",\n \"onLeave\",\n \"id\",\n \"label\",\n \"timeoutMs\"\n ]);\n\n for (const [index, transition] of transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n for (const key of Object.keys(transition)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey transition at index ${index} contains unsupported field \"${key}\".`\n );\n }\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (transition.from !== \"*\" && !(transition.from in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n validateFiniteTimeout(transition.timeoutMs, `Journey transition at index ${index}`);\n\n if (transition.when !== undefined && typeof transition.when !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"when\" as a function when provided.`\n );\n }\n\n if (transition.updateContext !== undefined && typeof transition.updateContext !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (transition.onEnter !== undefined && typeof transition.onEnter !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (transition.onLeave !== undefined && typeof transition.onLeave !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onLeave\" as a function when provided.`\n );\n }\n\n if (transition.id !== undefined && typeof transition.id !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"id\" as a string when provided.`\n );\n }\n\n if (transition.label !== undefined && typeof transition.label !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"label\" as a string when provided.`\n );\n }\n\n if (transition.event === \"completeJourney\" || transition.event === \"terminateJourney\") {\n if (\"to\" in transition && transition.to !== undefined) {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" cannot define \"to\".`\n );\n }\n continue;\n }\n\n if (typeof transition.to !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" must define string \"to\".`\n );\n }\n\n if (!isTerminalTarget(transition.to) && !(transition.to in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n};\n\nexport const buildSendResult = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n transitioned: boolean,\n options: {\n transitionId?: string;\n label?: string;\n error?: unknown;\n } = {}\n): JourneySendResult<TContext, TStepId> => ({\n transitioned,\n ...(options.transitionId !== undefined ? { transitionId: options.transitionId } : {}),\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(\"error\" in options ? { error: options.error } : {}),\n snapshot\n});\n\nexport const buildSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n timeline: readonly TStepId[],\n index: number,\n context: TContext,\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n visited?: Record<TStepId, boolean>\n): JourneySnapshot<TContext, TStepId> => {\n if (timeline.length === 0) {\n throw new Error(\"Journey timeline cannot be empty.\");\n }\n\n const safeIndex = Math.max(0, Math.min(Math.trunc(index), timeline.length - 1));\n const currentStepId = timeline[safeIndex] as TStepId;\n const stepIds = unique(\n visited ? ([...(Object.keys(visited) as TStepId[]), ...timeline] as const) : timeline\n );\n\n return {\n status,\n currentStepId,\n history: {\n timeline: [...timeline],\n index: safeIndex\n },\n context: cloneContext(context),\n visited: visited\n ? normalizeVisited(visited, stepIds)\n : buildVisitedFromTimeline(timeline, stepIds),\n async: cloneSerializableValue(\n asyncState as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n};\n\nexport const stabilizeSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>\n): JourneySnapshot<TContext, TStepId> => {\n const stableSnapshot: JourneySnapshot<TContext, TStepId> = {\n ...snapshot,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: cloneContext(snapshot.context),\n visited: { ...snapshot.visited },\n async: cloneSerializableValue(\n snapshot.async as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n\n freezeSnapshotValue(stableSnapshot);\n return stableSnapshot;\n};\n\nexport const selectTransition = async <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>,\n TTransition extends {\n from: TStepId | \"*\";\n event: string;\n when?: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>;\n timeoutMs?: number;\n id?: string;\n label?: string;\n }\n>(\n transitions: readonly TTransition[],\n snapshot: JourneySnapshot<TContext, TStepId>,\n event: JourneyEvent<TStepId, TEventMap>,\n signal: AbortSignal,\n handlers: THandlers,\n hooks?: {\n onAsyncGuardStart?: (transition: TTransition) => void;\n onAsyncGuardSuccess?: (transition: TTransition) => void;\n onAsyncGuardError?: (transition: TTransition, error: unknown) => void;\n },\n defaultTimeoutMs?: number\n): Promise<TTransition | null> => {\n for (const transition of transitions) {\n const fromMatches = transition.from === \"*\" || transition.from === snapshot.currentStepId;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n let guardResult: boolean | Promise<boolean>;\n if (signal.aborted) {\n throw signal.reason;\n }\n\n guardResult = (\n transition.when as (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>\n )({\n snapshot,\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event,\n signal,\n handlers\n });\n\n const asyncGuard = isPromiseLike(guardResult);\n const asyncGuardPromise = asyncGuard ? (guardResult as PromiseLike<boolean>) : null;\n\n let allowed: boolean;\n try {\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n allowed = await withTimeout(\n withAbortSignal(asyncGuardPromise as PromiseLike<boolean>, signal),\n transition.timeoutMs ?? defaultTimeoutMs,\n () =>\n new JourneyTimeoutError(\n `Transition guard timed out after ${transition.timeoutMs ?? defaultTimeoutMs}ms (event: ${event.type}, transition: ${transition.id ?? \"<anonymous>\"}).`\n )\n );\n } else {\n allowed = guardResult as boolean;\n }\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId> => {\n const baseTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n let nextTimeline = baseTimeline;\n if (nextCurrent !== snapshot.currentStepId) {\n nextTimeline = [...baseTimeline, nextCurrent];\n }\n\n const nextIndex = nextTimeline.length - 1;\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(\n nextTimeline,\n nextIndex,\n nextContext,\n snapshot.status,\n snapshot.async,\n visited\n );\n};\n", "import type {\n JourneyPersistedState,\n JourneyPersistenceOptions,\n JourneyStorage,\n ResolvedPersistence\n} from \"../../types/persistence.types\";\nimport type {\n JourneyJsonValue,\n JourneyJsonObject,\n JourneySnapshot,\n JourneySnapshotStateBase,\n JourneyStatus\n} from \"../../types/journey.types\";\nimport {\n assertSerializableContext,\n buildInitialAsyncState,\n buildSnapshot,\n buildVisitedFromTimeline,\n isPlainObject,\n warnInDevelopment\n} from \"../../journey-machine/helpers\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isStatusValue = (value: unknown): value is JourneyStatus =>\n value === \"idled\" || value === \"running\" || value === \"completed\" || value === \"terminated\";\n\ntype PersistencePath = readonly string[];\n\nconst normalizePersistencePath = (\n path: unknown,\n optionName: \"allowList\" | \"blockList\"\n): PersistencePath => {\n if (typeof path !== \"string\") {\n throw new Error(`Persistence ${optionName} entries must be strings.`);\n }\n\n const trimmedPath = path.trim();\n if (!trimmedPath) {\n throw new Error(`Persistence ${optionName} entries must not be empty.`);\n }\n\n if (\n trimmedPath.includes(\"[\") ||\n trimmedPath.includes(\"]\") ||\n trimmedPath.includes(\"*\") ||\n trimmedPath.startsWith(\".\") ||\n trimmedPath.endsWith(\".\") ||\n trimmedPath.includes(\"..\")\n ) {\n throw new Error(\n `Persistence ${optionName} entry \"${trimmedPath}\" must use exact dot-separated object keys.`\n );\n }\n\n const segments = trimmedPath.split(\".\");\n if (\n segments.some((segment) => !segment || segment.trim() !== segment || /^[0-9]+$/.test(segment))\n ) {\n throw new Error(\n `Persistence ${optionName} entry \"${trimmedPath}\" must use exact dot-separated object keys.`\n );\n }\n\n return segments;\n};\n\nconst normalizePersistencePaths = (\n paths: unknown,\n optionName: \"allowList\" | \"blockList\"\n): readonly PersistencePath[] | null => {\n if (paths === undefined) {\n return null;\n }\n\n if (!Array.isArray(paths)) {\n throw new Error(`Persistence ${optionName} must be an array of dot-separated strings.`);\n }\n\n const normalized = new Map<string, PersistencePath>();\n for (const path of paths) {\n const resolvedPath = normalizePersistencePath(path, optionName);\n normalized.set(resolvedPath.join(\".\"), resolvedPath);\n }\n\n return [...normalized.values()];\n};\n\nconst pathStartsWith = (path: readonly string[], prefix: readonly string[]): boolean =>\n prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment);\n\nconst pathHasAncestorMatch = (\n candidates: readonly PersistencePath[],\n path: readonly string[]\n): boolean => candidates.some((candidate) => pathStartsWith(path, candidate));\n\nconst pathHasDescendantMatch = (\n candidates: readonly PersistencePath[],\n path: readonly string[]\n): boolean => candidates.some((candidate) => pathStartsWith(candidate, path));\n\nconst filterContextValue = (\n value: unknown,\n allowList: readonly PersistencePath[] | null,\n blockList: readonly PersistencePath[],\n path: readonly string[] = []\n): { value: unknown; changed: boolean; included: boolean } => {\n if (pathHasAncestorMatch(blockList, path)) {\n return { value: undefined, changed: true, included: false };\n }\n\n const allowAll = allowList === null;\n const pathIsAllowed = allowAll || pathHasAncestorMatch(allowList, path);\n const pathHasAllowedDescendants = allowAll || pathHasDescendantMatch(allowList, path);\n\n if (!pathIsAllowed && !pathHasAllowedDescendants) {\n return { value: undefined, changed: true, included: false };\n }\n\n if (!isPlainObject(value)) {\n return {\n value,\n changed: !pathIsAllowed,\n included: pathIsAllowed\n };\n }\n\n let changed = false;\n const nextValue: Record<string, unknown> = {};\n\n for (const [key, childValue] of Object.entries(value)) {\n const result = filterContextValue(childValue, allowList, blockList, [...path, key]);\n if (!result.included) {\n changed = true;\n continue;\n }\n\n nextValue[key] = result.value;\n if (result.changed) {\n changed = true;\n }\n }\n\n return {\n value: nextValue,\n changed: changed || Object.keys(nextValue).length !== Object.keys(value).length,\n included: true\n };\n};\n\nconst mergePersistedValue = (\n initialValue: JourneyJsonValue | undefined,\n persistedValue: unknown\n): JourneyJsonValue => {\n if (isPlainObject(initialValue) && isPlainObject(persistedValue)) {\n const mergedEntries = new Map<string, JourneyJsonValue>();\n\n for (const [key, value] of Object.entries(initialValue)) {\n mergedEntries.set(key, value as JourneyJsonValue);\n }\n\n for (const [key, value] of Object.entries(persistedValue)) {\n mergedEntries.set(\n key,\n mergePersistedValue(initialValue[key] as JourneyJsonValue | undefined, value)\n );\n }\n\n return Object.fromEntries(mergedEntries) as JourneyJsonValue;\n }\n\n return persistedValue === undefined\n ? (initialValue ?? null)\n : (persistedValue as JourneyJsonValue);\n};\n\nconst mergePersistedContext = <TContext extends JourneyJsonObject>(\n initialContext: TContext,\n persistedContext: unknown\n): TContext => mergePersistedValue(initialContext, persistedContext) as TContext;\n\nconst resolveDefaultStorage = (): JourneyStorage | null => {\n const localStorageCandidate = (globalThis as { localStorage?: Partial<JourneyStorage> })\n .localStorage;\n\n if (\n !localStorageCandidate ||\n typeof localStorageCandidate.getItem !== \"function\" ||\n typeof localStorageCandidate.setItem !== \"function\" ||\n typeof localStorageCandidate.removeItem !== \"function\"\n ) {\n return null;\n }\n\n return localStorageCandidate as JourneyStorage;\n};\n\nconst reportPersistenceError = (error: unknown, onError?: (error: unknown) => void) => {\n if (onError) {\n onError(error);\n return;\n }\n\n warnInDevelopment(\"Journey persistence encountered an error without an onError handler.\", error);\n};\n\nconst resolvePersistence = <TContext extends JourneyJsonObject, TStepId extends string>(\n options?: JourneyPersistenceOptions<TContext, TStepId>\n): ResolvedPersistence<TContext, TStepId> | null => {\n if (!options) {\n return null;\n }\n\n let storage: JourneyStorage | null | undefined = options.storage;\n if (storage == null) {\n try {\n storage = resolveDefaultStorage();\n } catch (error) {\n reportPersistenceError(error, options.onError);\n return null;\n }\n }\n\n if (!storage) {\n return null;\n }\n\n let allowList: readonly string[] | undefined;\n let blockList: readonly string[];\n\n try {\n const normalizedAllowList = normalizePersistencePaths(options.allowList, \"allowList\");\n const normalizedBlockList = normalizePersistencePaths(options.blockList, \"blockList\");\n\n allowList = normalizedAllowList ? normalizedAllowList.map((path) => path.join(\".\")) : undefined;\n blockList = normalizedBlockList ? normalizedBlockList.map((path) => path.join(\".\")) : [];\n } catch (error) {\n reportPersistenceError(error, options.onError);\n return null;\n }\n\n return {\n key: options.key,\n storage,\n version: options.version ?? 1,\n clearOnReset: options.clearOnReset ?? true,\n ...(allowList ? { allowList } : {}),\n blockList,\n serialize: options.serialize ?? JSON.stringify,\n deserialize: options.deserialize ?? JSON.parse,\n ...(options.migrate ? { migrate: options.migrate } : {}),\n ...(options.onError ? { onError: options.onError } : {})\n };\n};\n\nconst resolveVisitedFromPersistence = <TStepId extends string>(\n visitedSource: unknown,\n timeline: readonly TStepId[],\n stepIds: readonly TStepId[]\n): {\n visited: Record<TStepId, boolean>;\n needsRewrite: boolean;\n} => {\n const visitedFromTimeline = buildVisitedFromTimeline(timeline, stepIds);\n\n if (isRecord(visitedSource)) {\n let needsRewrite = false;\n const visited = { ...visitedFromTimeline };\n\n for (const stepId of stepIds) {\n const persistedValue = visitedSource[stepId];\n\n if (persistedValue === true) {\n visited[stepId] = true;\n continue;\n }\n\n if (persistedValue === false) {\n if (visitedFromTimeline[stepId]) {\n needsRewrite = true;\n }\n continue;\n }\n\n needsRewrite = true;\n }\n\n return { visited, needsRewrite };\n }\n\n if (Array.isArray(visitedSource)) {\n const visitedFromArray = buildVisitedFromTimeline(\n visitedSource.filter(\n (step): step is TStepId => typeof step === \"string\" && stepIds.includes(step as TStepId)\n ) as TStepId[],\n stepIds\n );\n const visited = Object.fromEntries(\n stepIds.map((stepId) => [stepId, visitedFromTimeline[stepId] || visitedFromArray[stepId]])\n ) as Record<TStepId, boolean>;\n\n return { visited, needsRewrite: true };\n }\n\n return { visited: visitedFromTimeline, needsRewrite: true };\n};\n\nconst coercePersistedSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n value: unknown,\n steps: Record<TStepId, unknown>,\n fallbackContext: TContext\n): {\n snapshot: JourneySnapshotStateBase<TContext, TStepId>;\n needsRewrite: boolean;\n} | null => {\n if (!isRecord(value)) {\n return null;\n }\n\n let needsRewrite = false;\n\n const rawHistory = isRecord(value.history) ? value.history : null;\n if (!rawHistory) {\n needsRewrite = true;\n }\n\n const rawTimeline = rawHistory?.timeline ?? value.timeline;\n const timeline = Array.isArray(rawTimeline)\n ? (rawTimeline.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[])\n : [];\n\n const currentStepIdValue =\n typeof value.currentStepId === \"string\" && value.currentStepId in steps\n ? (value.currentStepId as TStepId)\n : typeof value.current === \"string\" && value.current in steps\n ? (value.current as TStepId)\n : null;\n\n if (timeline.length === 0) {\n if (!currentStepIdValue) {\n return null;\n }\n timeline.push(currentStepIdValue);\n needsRewrite = true;\n }\n\n let index = timeline.length - 1;\n const rawIndex = rawHistory?.index ?? value.index;\n if (typeof rawIndex === \"number\" && Number.isFinite(rawIndex)) {\n index = Math.max(0, Math.min(Math.trunc(rawIndex), timeline.length - 1));\n if (index !== rawIndex) {\n needsRewrite = true;\n }\n } else if (currentStepIdValue) {\n const inferredIndex = timeline.lastIndexOf(currentStepIdValue);\n if (inferredIndex >= 0) {\n index = inferredIndex;\n needsRewrite = true;\n }\n }\n\n const status = isStatusValue(value.status) ? value.status : \"idled\";\n if (!isStatusValue(value.status)) {\n needsRewrite = true;\n }\n\n const stepIds = Object.keys(steps) as TStepId[];\n const { visited, needsRewrite: visitedNeedsRewrite } = resolveVisitedFromPersistence(\n value.visited,\n timeline,\n stepIds\n );\n if (visitedNeedsRewrite) {\n needsRewrite = true;\n }\n\n return {\n snapshot: {\n currentStepId: timeline[index] as TStepId,\n history: {\n timeline,\n index\n },\n context: assertSerializableContext(\n (\"context\" in value ? value.context : fallbackContext) as TContext,\n \"Persisted journey context\"\n ),\n status,\n visited\n },\n needsRewrite\n };\n};\n\n/**\n * Creates a persistence controller for snapshots, including hydration,\n * serialization, and storage error handling.\n */\nexport const createPersistenceController = <\n TContext extends JourneyJsonObject,\n TStepId extends string\n>(args: {\n initial: TStepId;\n context: TContext;\n steps: Record<TStepId, unknown>;\n options?: JourneyPersistenceOptions<TContext, TStepId>;\n}) => {\n const { initial, context, steps, options } = args;\n const persistence = resolvePersistence(options);\n const allowList = persistence?.allowList\n ? persistence.allowList.map((path) => path.split(\".\"))\n : null;\n const blockList = persistence ? persistence.blockList.map((path) => path.split(\".\")) : [];\n\n const reportResolvedPersistenceError = (error: unknown) => {\n reportPersistenceError(error, persistence?.onError);\n };\n\n const filterPersistedContext = (value: TContext): { context: TContext; changed: boolean } => {\n if (!persistence || (allowList === null && blockList.length === 0)) {\n return { context: value, changed: false };\n }\n\n if (!isPlainObject(value)) {\n return { context: value, changed: false };\n }\n\n const filtered = filterContextValue(value, allowList, blockList);\n const filteredContext =\n filtered.included && isPlainObject(filtered.value) ? filtered.value : {};\n\n return {\n context: filteredContext as TContext,\n changed: filtered.changed\n };\n };\n\n const persistSnapshot = (snapshot: JourneySnapshot<TContext, TStepId>) => {\n if (!persistence) {\n return;\n }\n\n try {\n const { context: persistedContext } = filterPersistedContext(snapshot.context);\n const persistedState: JourneyPersistedState<TContext, TStepId> = {\n version: persistence.version,\n snapshot: {\n currentStepId: snapshot.currentStepId,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: persistedContext,\n status: snapshot.status,\n visited: { ...snapshot.visited }\n }\n };\n persistence.storage.setItem(persistence.key, persistence.serialize(persistedState));\n } catch (error) {\n reportResolvedPersistenceError(error);\n }\n };\n\n const removePersistedSnapshot = () => {\n if (!persistence) {\n return;\n }\n\n try {\n persistence.storage.removeItem(persistence.key);\n } catch (error) {\n reportResolvedPersistenceError(error);\n }\n };\n\n const buildBaseSnapshot = () =>\n buildSnapshot([initial], 0, context, \"idled\", buildInitialAsyncState(steps));\n const hydrateSnapshot = (\n baseSnapshot: JourneySnapshot<TContext, TStepId> = buildBaseSnapshot()\n ): JourneySnapshot<TContext, TStepId> => {\n const resolvedBaseSnapshot = buildSnapshot(\n baseSnapshot.history.timeline,\n baseSnapshot.history.index,\n baseSnapshot.context,\n baseSnapshot.status,\n baseSnapshot.async,\n baseSnapshot.visited\n );\n if (!persistence) {\n return resolvedBaseSnapshot;\n }\n\n try {\n const rawPersisted = persistence.storage.getItem(persistence.key);\n if (!rawPersisted) {\n return resolvedBaseSnapshot;\n }\n\n const parsed = persistence.deserialize(rawPersisted);\n if (!isRecord(parsed)) {\n return resolvedBaseSnapshot;\n }\n\n const persistedVersion = parsed.version;\n if (typeof persistedVersion !== \"number\") {\n return resolvedBaseSnapshot;\n }\n\n let persistedSnapshot: JourneySnapshotStateBase<TContext, TStepId> | null = null;\n let shouldRewritePersisted = false;\n\n if (persistedVersion === persistence.version) {\n const coerced = coercePersistedSnapshot(parsed.snapshot, steps, context);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = Boolean(coerced?.needsRewrite);\n } else if (persistence.migrate) {\n const migrated = persistence.migrate(parsed.snapshot, persistedVersion);\n const coerced = coercePersistedSnapshot(migrated, steps, context);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = persistedSnapshot !== null;\n\n if (!persistedSnapshot) {\n reportResolvedPersistenceError(\n new Error(\n \"Journey persistence migrate() returned data that could not be coerced into a valid snapshot. \" +\n `Falling back to the initial snapshot (persisted version: ${persistedVersion}, current version: ${persistence.version}).`\n )\n );\n }\n }\n\n if (!persistedSnapshot) {\n return resolvedBaseSnapshot;\n }\n\n const { context: filteredContext, changed: contextWasFiltered } = filterPersistedContext(\n persistedSnapshot.context\n );\n const hydratedContext = mergePersistedContext(resolvedBaseSnapshot.context, filteredContext);\n\n const hydratedSnapshot = buildSnapshot(\n persistedSnapshot.history.timeline,\n persistedSnapshot.history.index,\n assertSerializableContext(hydratedContext, \"Hydrated journey context\"),\n persistedSnapshot.status === \"running\" ? \"idled\" : persistedSnapshot.status,\n resolvedBaseSnapshot.async,\n persistedSnapshot.visited\n );\n\n if (shouldRewritePersisted || contextWasFiltered) {\n persistSnapshot(hydratedSnapshot);\n }\n\n return hydratedSnapshot;\n } catch (error) {\n reportResolvedPersistenceError(error);\n return resolvedBaseSnapshot;\n }\n };\n\n return {\n clearOnReset: persistence?.clearOnReset ?? true,\n hydrateSnapshot,\n persistSnapshot,\n removePersistedSnapshot\n };\n};\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,iCAAAE,EAAA,4BAAAC,KAAA,eAAAC,EAAAJ,IC4BO,IAAMK,EAAiBC,GAC5B,OAAOA,GAAU,UACjBA,IAAU,MACV,CAAC,MAAM,QAAQA,CAAK,IACnB,OAAO,eAAeA,CAAK,IAAM,O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AC3C,gBAAAW,EACA,gBAAAP,EACA,wBAAAG,CACF,CACF,EF7iBO,IAAMkB,GACXC,IA2BO,CACL,KAAM,cACN,OA3Ba,CAAC,CAAE,gBAAAC,CAAgB,IAAM,CACtC,IAAMC,EAAaC,EAA4B,CAC7C,QAASF,EAAgB,QACzB,QAASA,EAAgB,QACzB,MAAOA,EAAgB,MACvB,QAAAD,CACF,CAAC,EAED,MAAO,CACL,gBAAkBI,GAAaF,EAAW,gBAAgBE,CAAiB,EAC3E,iBAAkB,CAAC,CAAE,SAAAA,EAAU,OAAAC,CAAO,IAAM,CAC1C,GAAIA,IAAW,QAIf,IAAIA,IAAW,SAAWH,EAAW,aAAc,CACjDA,EAAW,wBAAwB,EACnC,MACF,CAEAA,EAAW,gBAAgBE,CAAiB,EAC9C,CACF,CACF,EAKA",
|
|
6
|
+
"names": ["persistence_exports", "__export", "createPersistenceController", "createPersistencePlugin", "__toCommonJS", "isPlainObject", "value", "cloneSerializableValue", "entry", "key", "entryValue", "describeValue", "constructorName", "assertSerializableValue", "label", "state", "path", "pathLabel", "index", "assertSerializableContext", "context", "cloneContext", "unique", "items", "normalizeVisited", "visited", "stepIds", "stepId", "buildVisitedFromTimeline", "timeline", "resolvedStepIds", "isDevelopmentEnvironment", "diagnosticGlobal", "nodeEnv", "warnInDevelopment", "message", "detail", "buildIdleStepAsyncState", "buildInitialAsyncState", "steps", "stepId", "buildSnapshot", "timeline", "index", "context", "status", "asyncState", "visited", "safeIndex", "currentStepId", "stepIds", "unique", "cloneContext", "normalizeVisited", "buildVisitedFromTimeline", "cloneSerializableValue", "isRecord", "value", "isStatusValue", "normalizePersistencePath", "path", "optionName", "trimmedPath", "segments", "segment", "normalizePersistencePaths", "paths", "normalized", "resolvedPath", "pathStartsWith", "prefix", "index", "pathHasAncestorMatch", "candidates", "candidate", "pathHasDescendantMatch", "filterContextValue", "allowList", "blockList", "allowAll", "pathIsAllowed", "pathHasAllowedDescendants", "isPlainObject", "changed", "nextValue", "key", "childValue", "result", "mergePersistedValue", "initialValue", "persistedValue", "mergedEntries", "mergePersistedContext", "initialContext", "persistedContext", "resolveDefaultStorage", "localStorageCandidate", "reportPersistenceError", "error", "onError", "warnInDevelopment", "resolvePersistence", "options", "storage", "normalizedAllowList", "normalizedBlockList", "resolveVisitedFromPersistence", "visitedSource", "timeline", "stepIds", "visitedFromTimeline", "buildVisitedFromTimeline", "needsRewrite", "visited", "stepId", "visitedFromArray", "step", "coercePersistedSnapshot", "steps", "fallbackContext", "rawHistory", "rawTimeline", "currentStepIdValue", "rawIndex", "inferredIndex", "status", "visitedNeedsRewrite", "assertSerializableContext", "createPersistenceController", "args", "initial", "context", "persistence", "reportResolvedPersistenceError", "filterPersistedContext", "filtered", "persistSnapshot", "snapshot", "persistedState", "removePersistedSnapshot", "buildBaseSnapshot", "buildSnapshot", "buildInitialAsyncState", "hydrateSnapshot", "baseSnapshot", "resolvedBaseSnapshot", "rawPersisted", "parsed", "persistedVersion", "persistedSnapshot", "shouldRewritePersisted", "coerced", "migrated", "filteredContext", "contextWasFiltered", "hydratedContext", "hydratedSnapshot", "createPersistencePlugin", "options", "resolvedJourney", "controller", "createPersistenceController", "snapshot", "reason"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createPersistenceController } from "./controller";
|
|
2
|
+
import type { JourneyJsonObject, JourneyPersistenceOptions } from "../../types";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a machine plugin that hydrates snapshots from storage and persists
|
|
5
|
+
* state changes without pulling persistence code into the base entrypoint.
|
|
6
|
+
*/
|
|
7
|
+
export declare const createPersistencePlugin: <TContext extends JourneyJsonObject, TStepId extends string>(options: JourneyPersistenceOptions<TContext, TStepId>) => {
|
|
8
|
+
name: string;
|
|
9
|
+
setup: <TContext_1 extends JourneyJsonObject, TStepId_1 extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(context: import("../../types").JourneyMachinePluginSetupContext<TContext_1, TStepId_1, TEventMap, TStepMeta, THandlers>) => import("../../types").JourneyMachinePluginHooks<TContext_1, TStepId_1, TEventMap, TStepMeta, THandlers>;
|
|
10
|
+
};
|
|
11
|
+
export { createPersistenceController };
|
|
12
|
+
export type { JourneyPersistedState, JourneyPersistenceOptions, JourneyStorage } from "../../types";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createPersistenceController } from "./controller";
|
|
2
|
+
import type { JourneyJsonObject, JourneyPersistenceOptions } from "../../types";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a machine plugin that hydrates snapshots from storage and persists
|
|
5
|
+
* state changes without pulling persistence code into the base entrypoint.
|
|
6
|
+
*/
|
|
7
|
+
export declare const createPersistencePlugin: <TContext extends JourneyJsonObject, TStepId extends string>(options: JourneyPersistenceOptions<TContext, TStepId>) => {
|
|
8
|
+
name: string;
|
|
9
|
+
setup: <TContext_1 extends JourneyJsonObject, TStepId_1 extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(context: import("../../types").JourneyMachinePluginSetupContext<TContext_1, TStepId_1, TEventMap, TStepMeta, THandlers>) => import("../../types").JourneyMachinePluginHooks<TContext_1, TStepId_1, TEventMap, TStepMeta, THandlers>;
|
|
10
|
+
};
|
|
11
|
+
export { createPersistenceController };
|
|
12
|
+
export type { JourneyPersistedState, JourneyPersistenceOptions, JourneyStorage } from "../../types";
|