@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.
Files changed (99) hide show
  1. package/README.md +236 -105
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.cjs.map +4 -4
  4. package/dist/index.d.cts +5 -4
  5. package/dist/index.d.ts +5 -4
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +4 -4
  8. package/dist/journey-builder/index.d.cts +5 -0
  9. package/dist/journey-builder/index.d.ts +5 -0
  10. package/dist/journey-builder/types.d.cts +126 -0
  11. package/dist/journey-builder/types.d.ts +126 -0
  12. package/dist/journey-machine/async-state.d.cts +12 -0
  13. package/dist/journey-machine/async-state.d.ts +12 -0
  14. package/dist/journey-machine/computed.d.cts +2 -0
  15. package/dist/journey-machine/computed.d.ts +2 -0
  16. package/dist/journey-machine/controls.d.cts +17 -0
  17. package/dist/journey-machine/controls.d.ts +17 -0
  18. package/dist/journey-machine/helpers.d.cts +52 -0
  19. package/dist/journey-machine/helpers.d.ts +52 -0
  20. package/dist/journey-machine/index.d.cts +3 -0
  21. package/dist/journey-machine/index.d.ts +3 -0
  22. package/dist/journey-machine/navigation.d.cts +32 -0
  23. package/dist/journey-machine/navigation.d.ts +32 -0
  24. package/dist/journey-machine/plugin-controller.d.cts +15 -0
  25. package/dist/journey-machine/plugin-controller.d.ts +15 -0
  26. package/dist/journey-machine/resolve-journey-definition.d.cts +2 -0
  27. package/dist/journey-machine/resolve-journey-definition.d.ts +2 -0
  28. package/dist/journey-machine/runtime.d.cts +33 -0
  29. package/dist/journey-machine/runtime.d.ts +33 -0
  30. package/dist/journey-machine/send.d.cts +9 -0
  31. package/dist/journey-machine/send.d.ts +9 -0
  32. package/dist/plugins/analytics/index.cjs +2 -0
  33. package/dist/plugins/analytics/index.cjs.map +7 -0
  34. package/dist/plugins/analytics/index.d.cts +25 -0
  35. package/dist/plugins/analytics/index.d.ts +25 -0
  36. package/dist/plugins/analytics/index.js +2 -0
  37. package/dist/plugins/analytics/index.js.map +7 -0
  38. package/dist/plugins/autosave/index.cjs +2 -0
  39. package/dist/plugins/autosave/index.cjs.map +7 -0
  40. package/dist/plugins/autosave/index.d.cts +17 -0
  41. package/dist/plugins/autosave/index.d.ts +17 -0
  42. package/dist/plugins/autosave/index.js +2 -0
  43. package/dist/plugins/autosave/index.js.map +7 -0
  44. package/dist/plugins/diagnostics/diagnostics.d.cts +3 -0
  45. package/dist/plugins/diagnostics/diagnostics.d.ts +3 -0
  46. package/dist/plugins/diagnostics/index.cjs +2 -0
  47. package/dist/plugins/diagnostics/index.cjs.map +7 -0
  48. package/dist/plugins/diagnostics/index.d.cts +15 -0
  49. package/dist/plugins/diagnostics/index.d.ts +15 -0
  50. package/dist/plugins/diagnostics/index.js +2 -0
  51. package/dist/plugins/diagnostics/index.js.map +7 -0
  52. package/dist/plugins/execution-paths/execution-paths.d.cts +6 -0
  53. package/dist/plugins/execution-paths/execution-paths.d.ts +6 -0
  54. package/dist/plugins/execution-paths/index.cjs +2 -0
  55. package/dist/plugins/execution-paths/index.cjs.map +7 -0
  56. package/dist/plugins/execution-paths/index.d.cts +18 -0
  57. package/dist/plugins/execution-paths/index.d.ts +18 -0
  58. package/dist/plugins/execution-paths/index.js +2 -0
  59. package/dist/plugins/execution-paths/index.js.map +7 -0
  60. package/dist/plugins/persistence/controller.d.cts +17 -0
  61. package/dist/plugins/persistence/controller.d.ts +17 -0
  62. package/dist/plugins/persistence/index.cjs +2 -0
  63. package/dist/plugins/persistence/index.cjs.map +7 -0
  64. package/dist/plugins/persistence/index.d.cts +12 -0
  65. package/dist/plugins/persistence/index.d.ts +12 -0
  66. package/dist/plugins/persistence/index.js +2 -0
  67. package/dist/plugins/persistence/index.js.map +7 -0
  68. package/dist/plugins/replay/index.cjs +2 -0
  69. package/dist/plugins/replay/index.cjs.map +7 -0
  70. package/dist/plugins/replay/index.d.cts +27 -0
  71. package/dist/plugins/replay/index.d.ts +27 -0
  72. package/dist/plugins/replay/index.js +2 -0
  73. package/dist/plugins/replay/index.js.map +7 -0
  74. package/dist/types/analytics.types.d.cts +33 -0
  75. package/dist/types/analytics.types.d.ts +33 -0
  76. package/dist/types/autosave.types.d.cts +23 -0
  77. package/dist/types/autosave.types.d.ts +23 -0
  78. package/dist/types/diagnostics.types.d.cts +38 -0
  79. package/dist/types/diagnostics.types.d.ts +38 -0
  80. package/dist/types/index.d.cts +9 -0
  81. package/dist/types/index.d.ts +9 -4
  82. package/dist/types/journey.types.d.cts +191 -0
  83. package/dist/types/journey.types.d.ts +140 -167
  84. package/dist/types/machine.types.d.cts +104 -0
  85. package/dist/types/machine.types.d.ts +104 -0
  86. package/dist/types/observation.types.d.cts +83 -0
  87. package/dist/types/observation.types.d.ts +83 -0
  88. package/dist/types/persistence.types.d.cts +34 -0
  89. package/dist/types/persistence.types.d.ts +13 -20
  90. package/dist/types/replay.types.d.cts +35 -0
  91. package/dist/types/replay.types.d.ts +35 -0
  92. package/dist/types/transitions.types.d.cts +122 -0
  93. package/dist/types/transitions.types.d.ts +100 -57
  94. package/package.json +92 -2
  95. package/dist/machine-helpers.d.ts +0 -23
  96. package/dist/machine.d.ts +0 -11
  97. package/dist/persistence.d.ts +0 -17
  98. package/dist/transitions.d.ts +0 -62
  99. package/dist/types.d.ts +0 -1
@@ -0,0 +1,33 @@
1
+ import type { JourneyEqualityFn, JourneyJsonObject, JourneyMachineSnapshotReason, JourneyObservationEvent, JourneySelector, JourneySnapshot } from "../types";
2
+ type SnapshotOptions = {
3
+ notify?: boolean;
4
+ reason?: JourneyMachineSnapshotReason;
5
+ };
6
+ export type JourneyMachineRuntime<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>> = {
7
+ getSnapshot: () => JourneySnapshot<TContext, TStepId>;
8
+ peekSnapshot: () => JourneySnapshot<TContext, TStepId>;
9
+ setSnapshot: (nextSnapshot: JourneySnapshot<TContext, TStepId>, options?: SnapshotOptions) => JourneySnapshot<TContext, TStepId>;
10
+ isDisposed: () => boolean;
11
+ isRunActive: (runVersion: number) => boolean;
12
+ cancelInFlight: () => void;
13
+ openLifecycle: (runVersion: number) => AbortController | null;
14
+ closeLifecycle: (controller: AbortController) => void;
15
+ queue: <T>(runner: (runVersion: number, signal: AbortSignal) => Promise<T>, onCanceled: () => T) => Promise<T>;
16
+ notify: () => void;
17
+ emit: (event: JourneyObservationEvent<TStepId, TEventMap>) => void;
18
+ subscribe: (listener: () => void) => () => void;
19
+ subscribeSelector: <TSelected>(selector: JourneySelector<TContext, TStepId, TSelected>, listener: (next: TSelected, previous: TSelected) => void, equalityFn?: JourneyEqualityFn<TSelected>) => () => void;
20
+ subscribeEvent: (listener: (event: JourneyObservationEvent<TStepId, TEventMap>) => void) => () => void;
21
+ dispose: () => void;
22
+ };
23
+ export declare const createJourneyMachineRuntime: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>>({ snapshot: initialSnapshot, onSnapshotChange, onDispose, onListenerError }: {
24
+ snapshot: JourneySnapshot<TContext, TStepId>;
25
+ onSnapshotChange?: (args: {
26
+ previousSnapshot: JourneySnapshot<TContext, TStepId>;
27
+ snapshot: JourneySnapshot<TContext, TStepId>;
28
+ reason: JourneyMachineSnapshotReason;
29
+ }) => void;
30
+ onDispose?: () => void;
31
+ onListenerError?: (error: unknown, context: "snapshot" | "event") => void;
32
+ }) => JourneyMachineRuntime<TContext, TStepId, TEventMap>;
33
+ export {};
@@ -0,0 +1,33 @@
1
+ import type { JourneyEqualityFn, JourneyJsonObject, JourneyMachineSnapshotReason, JourneyObservationEvent, JourneySelector, JourneySnapshot } from "../types";
2
+ type SnapshotOptions = {
3
+ notify?: boolean;
4
+ reason?: JourneyMachineSnapshotReason;
5
+ };
6
+ export type JourneyMachineRuntime<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>> = {
7
+ getSnapshot: () => JourneySnapshot<TContext, TStepId>;
8
+ peekSnapshot: () => JourneySnapshot<TContext, TStepId>;
9
+ setSnapshot: (nextSnapshot: JourneySnapshot<TContext, TStepId>, options?: SnapshotOptions) => JourneySnapshot<TContext, TStepId>;
10
+ isDisposed: () => boolean;
11
+ isRunActive: (runVersion: number) => boolean;
12
+ cancelInFlight: () => void;
13
+ openLifecycle: (runVersion: number) => AbortController | null;
14
+ closeLifecycle: (controller: AbortController) => void;
15
+ queue: <T>(runner: (runVersion: number, signal: AbortSignal) => Promise<T>, onCanceled: () => T) => Promise<T>;
16
+ notify: () => void;
17
+ emit: (event: JourneyObservationEvent<TStepId, TEventMap>) => void;
18
+ subscribe: (listener: () => void) => () => void;
19
+ subscribeSelector: <TSelected>(selector: JourneySelector<TContext, TStepId, TSelected>, listener: (next: TSelected, previous: TSelected) => void, equalityFn?: JourneyEqualityFn<TSelected>) => () => void;
20
+ subscribeEvent: (listener: (event: JourneyObservationEvent<TStepId, TEventMap>) => void) => () => void;
21
+ dispose: () => void;
22
+ };
23
+ export declare const createJourneyMachineRuntime: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>>({ snapshot: initialSnapshot, onSnapshotChange, onDispose, onListenerError }: {
24
+ snapshot: JourneySnapshot<TContext, TStepId>;
25
+ onSnapshotChange?: (args: {
26
+ previousSnapshot: JourneySnapshot<TContext, TStepId>;
27
+ snapshot: JourneySnapshot<TContext, TStepId>;
28
+ reason: JourneyMachineSnapshotReason;
29
+ }) => void;
30
+ onDispose?: () => void;
31
+ onListenerError?: (error: unknown, context: "snapshot" | "event") => void;
32
+ }) => JourneyMachineRuntime<TContext, TStepId, TEventMap>;
33
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { JourneyJsonObject, JourneyResolvedTransition, JourneySendEvent, JourneySendResult } from "../types";
2
+ import type { JourneyMachineAsyncStateController } from "./async-state";
3
+ import type { JourneyMachineNavigationController } from "./navigation";
4
+ import type { JourneyMachineRuntime } from "./runtime";
5
+ export type JourneyMachineSendController<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>> = {
6
+ executeSend: (event: JourneySendEvent<TStepId, TEventMap>, runVersion: number, signal: AbortSignal) => Promise<JourneySendResult<TContext, TStepId>>;
7
+ buildCanceledSendResult: (operation?: string) => JourneySendResult<TContext, TStepId>;
8
+ };
9
+ export declare const createJourneyMachineSendController: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, THandlers extends Record<string, unknown>>(runtime: JourneyMachineRuntime<TContext, TStepId, TEventMap>, asyncState: JourneyMachineAsyncStateController<TStepId>, navigation: JourneyMachineNavigationController<TContext, TStepId, TEventMap, THandlers>, headless: boolean, steps: Record<TStepId, unknown>, transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[], handlers: THandlers, requireExplicitCompletion: boolean, defaultTimeoutMs: number | undefined) => JourneyMachineSendController<TContext, TStepId, TEventMap>;
@@ -0,0 +1,9 @@
1
+ import type { JourneyJsonObject, JourneyResolvedTransition, JourneySendEvent, JourneySendResult } from "../types";
2
+ import type { JourneyMachineAsyncStateController } from "./async-state";
3
+ import type { JourneyMachineNavigationController } from "./navigation";
4
+ import type { JourneyMachineRuntime } from "./runtime";
5
+ export type JourneyMachineSendController<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>> = {
6
+ executeSend: (event: JourneySendEvent<TStepId, TEventMap>, runVersion: number, signal: AbortSignal) => Promise<JourneySendResult<TContext, TStepId>>;
7
+ buildCanceledSendResult: (operation?: string) => JourneySendResult<TContext, TStepId>;
8
+ };
9
+ export declare const createJourneyMachineSendController: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, THandlers extends Record<string, unknown>>(runtime: JourneyMachineRuntime<TContext, TStepId, TEventMap>, asyncState: JourneyMachineAsyncStateController<TStepId>, navigation: JourneyMachineNavigationController<TContext, TStepId, TEventMap, THandlers>, headless: boolean, steps: Record<TStepId, unknown>, transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[], handlers: THandlers, requireExplicitCompletion: boolean, defaultTimeoutMs: number | undefined) => JourneyMachineSendController<TContext, TStepId, TEventMap>;
@@ -0,0 +1,2 @@
1
+ "use strict";var m=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var b=(n,t)=>{for(var i in t)m(n,i,{get:t[i],enumerable:!0})},I=(n,t,i,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of S(t))!x.call(n,a)&&a!==i&&m(n,a,{get:()=>t[a],enumerable:!(c=f(t,a))||c.enumerable});return n};var J=n=>I(m({},"__esModule",{value:!0}),n);var g={};b(g,{createAnalyticsPlugin:()=>E});module.exports=J(g);var w=()=>{let n=globalThis;if(typeof n.__DEV__=="boolean")return n.__DEV__;let t=n.process?.env?.NODE_ENV;return t===void 0||t==="development"},l=(n,t)=>{if(!(!w()||typeof console>"u")){if(t===void 0){console.warn(n);return}console.warn(n,t)}};var h=({context:n})=>({context:n}),E=n=>{let t,i=null,c=null,a=(y,u)=>{try{n.track(u)}catch(r){if(n.onError){n.onError(r,y);return}l("Journey analytics track() threw without an onError handler.",r)}};return{name:"analytics",setup:()=>({augmentMachine:({machine:y})=>{let u=y,r=(s,e)=>{a(s,e)},p=s=>{if(!n.includeStepMeta)return{};let e=u.getStepMeta(s);return e===void 0?{}:{stepMeta:e}},T=({from:s,to:e})=>{if(!n.includeStepMeta)return{};let d=u.getStepMeta(s),o=e==="COMPLETE"||e==="TERMINATED"?void 0:u.getStepMeta(e);return{...d===void 0?{}:{fromStepMeta:d},...o===void 0?{}:{toStepMeta:o}}};return t=u.subscribeEvent(s=>{let e=s,d=u.getSnapshot(),o=h({context:d.context});switch(e.type){case"journey.start":i=e.timestamp,c=e.timestamp,r(e,{name:"journey_started",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...p(e.stepId),...o}});return;case"step.enter":c=e.timestamp,r(e,{name:"step_viewed",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...p(e.stepId),...o}});return;case"step.exit":r(e,{name:"step_exited",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...c===null?{}:{dwellMs:Math.max(0,e.timestamp-c)},...p(e.stepId),...o}});return;case"transition.start":r(e,{name:"transition_started",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,eventType:e.event.type,...o}});return;case"transition.success":r(e,{name:"transition_succeeded",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,to:e.to,eventType:e.eventType,transitionId:e.transitionId,...e.label!==void 0?{label:e.label}:{},...T({from:e.from,to:e.to}),...o}});return;case"transition.error":r(e,{name:"transition_failed",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,eventType:e.eventType,transitionId:e.transitionId,...e.label!==void 0?{label:e.label}:{},error:e.error,...o}});return;case"journey.completed":r(e,{name:"journey_completed",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...i===null?{}:{durationMs:Math.max(0,e.timestamp-i)},...p(e.stepId),...o}});return;case"journey.terminated":r(e,{name:"journey_terminated",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...i===null?{}:{durationMs:Math.max(0,e.timestamp-i)},...p(e.stepId),...o}});return;case"navigation.previous":r(e,{name:"navigation_previous",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,to:e.to,requestedSteps:e.requestedSteps,appliedSteps:e.appliedSteps,...T({from:e.from,to:e.to}),...o}});return;case"navigation.lastVisited":r(e,{name:"navigation_last_visited",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,to:e.to,...T({from:e.from,to:e.to}),...o}});return}}),{trackAnalyticsEvent:(s,e={})=>{let d={name:s,timestamp:Date.now(),...n.machineId?{machineId:n.machineId}:{},payload:e};return a(d,d),d}}},dispose:()=>{t?.()}})}};0&&(module.exports={createAnalyticsPlugin});
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/plugins/analytics/index.ts", "../../../src/journey-machine/helpers.ts"],
4
+ "sourcesContent": ["import { warnInDevelopment } from \"../../journey-machine/helpers\";\n\nimport type {\n JourneyAnalyticsPluginOptions,\n JourneyAnalyticsTrackedEvent,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin,\n JourneyObservationEvent,\n JourneyTerminal\n} from \"../../types\";\n\nconst buildBasePayload = <TContext extends JourneyJsonObject>({\n context\n}: {\n context: TContext;\n}) => ({ context });\n\nexport type JourneyAnalyticsMachineExtension<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TStepMeta\n> = {\n trackAnalyticsEvent: (\n name: string,\n payload?: Record<string, unknown>\n ) => JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>;\n};\n\nexport type JourneyAnalyticsMachine<\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 JourneyAnalyticsMachineExtension<TContext, TStepId, TStepMeta>;\n\n/** Creates a plugin that converts journey observation events into analytics envelopes. */\nexport const createAnalyticsPlugin = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown> = Record<never, never>,\n TStepMeta = unknown\n>(\n options: JourneyAnalyticsPluginOptions<TContext, TStepId, TEventMap, TStepMeta>\n) => {\n let unsubscribe: (() => void) | undefined;\n let startedAt: number | null = null;\n let activeStepEnteredAt: number | null = null;\n\n const trackSafely = (\n event:\n | JourneyObservationEvent<TStepId, TEventMap>\n | JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>,\n tracked: JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>\n ) => {\n try {\n options.track(tracked);\n } catch (error) {\n if (options.onError) {\n options.onError(error, event);\n return;\n }\n\n warnInDevelopment(\"Journey analytics track() threw without an onError handler.\", error);\n }\n };\n\n return {\n name: \"analytics\",\n setup: () => ({\n augmentMachine: ({ machine }) => {\n const typedMachine = machine as JourneyMachine<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n Record<string, unknown>\n >;\n\n const emitTracked = (\n sourceEvent: JourneyObservationEvent<TStepId, TEventMap>,\n tracked: JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>\n ) => {\n trackSafely(sourceEvent, tracked);\n };\n\n const buildStepMetaPayload = (stepId: TStepId) => {\n if (!options.includeStepMeta) {\n return {};\n }\n\n const stepMeta = typedMachine.getStepMeta(stepId) as TStepMeta | undefined;\n return stepMeta === undefined ? {} : { stepMeta };\n };\n\n const buildTransitionMetaPayload = ({\n from,\n to\n }: {\n from: TStepId;\n to: TStepId | JourneyTerminal;\n }) => {\n if (!options.includeStepMeta) {\n return {};\n }\n\n const fromStepMeta = typedMachine.getStepMeta(from) as TStepMeta | undefined;\n const toStepMeta =\n to === \"COMPLETE\" || to === \"TERMINATED\"\n ? undefined\n : (typedMachine.getStepMeta(to) as TStepMeta | undefined);\n\n return {\n ...(fromStepMeta === undefined ? {} : { fromStepMeta }),\n ...(toStepMeta === undefined ? {} : { toStepMeta })\n };\n };\n\n unsubscribe = typedMachine.subscribeEvent((event) => {\n const typedEvent = event as JourneyObservationEvent<TStepId, TEventMap>;\n const snapshot = typedMachine.getSnapshot();\n const basePayload = buildBasePayload({\n context: snapshot.context as TContext\n });\n\n switch (typedEvent.type) {\n case \"journey.start\":\n startedAt = typedEvent.timestamp;\n activeStepEnteredAt = typedEvent.timestamp;\n emitTracked(typedEvent, {\n name: \"journey_started\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"step.enter\":\n activeStepEnteredAt = typedEvent.timestamp;\n emitTracked(typedEvent, {\n name: \"step_viewed\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"step.exit\":\n emitTracked(typedEvent, {\n name: \"step_exited\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...(activeStepEnteredAt === null\n ? {}\n : { dwellMs: Math.max(0, typedEvent.timestamp - activeStepEnteredAt) }),\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"transition.start\":\n emitTracked(typedEvent, {\n name: \"transition_started\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n eventType: typedEvent.event.type,\n ...basePayload\n }\n });\n return;\n case \"transition.success\":\n emitTracked(typedEvent, {\n name: \"transition_succeeded\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n to: typedEvent.to,\n eventType: typedEvent.eventType,\n transitionId: typedEvent.transitionId,\n ...(typedEvent.label !== undefined ? { label: typedEvent.label } : {}),\n ...buildTransitionMetaPayload({\n from: typedEvent.from,\n to: typedEvent.to as TStepId | JourneyTerminal\n }),\n ...basePayload\n }\n });\n return;\n case \"transition.error\":\n emitTracked(typedEvent, {\n name: \"transition_failed\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n eventType: typedEvent.eventType,\n transitionId: typedEvent.transitionId,\n ...(typedEvent.label !== undefined ? { label: typedEvent.label } : {}),\n error: typedEvent.error,\n ...basePayload\n }\n });\n return;\n case \"journey.completed\":\n emitTracked(typedEvent, {\n name: \"journey_completed\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...(startedAt === null\n ? {}\n : { durationMs: Math.max(0, typedEvent.timestamp - startedAt) }),\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"journey.terminated\":\n emitTracked(typedEvent, {\n name: \"journey_terminated\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...(startedAt === null\n ? {}\n : { durationMs: Math.max(0, typedEvent.timestamp - startedAt) }),\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"navigation.previous\":\n emitTracked(typedEvent, {\n name: \"navigation_previous\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n to: typedEvent.to,\n requestedSteps: typedEvent.requestedSteps,\n appliedSteps: typedEvent.appliedSteps,\n ...buildTransitionMetaPayload({\n from: typedEvent.from,\n to: typedEvent.to\n }),\n ...basePayload\n }\n });\n return;\n case \"navigation.lastVisited\":\n emitTracked(typedEvent, {\n name: \"navigation_last_visited\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n to: typedEvent.to,\n ...buildTransitionMetaPayload({\n from: typedEvent.from,\n to: typedEvent.to\n }),\n ...basePayload\n }\n });\n return;\n }\n });\n\n return {\n trackAnalyticsEvent: (name: string, payload: Record<string, unknown> = {}) => {\n const tracked = {\n name,\n timestamp: Date.now(),\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload\n } satisfies JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>;\n trackSafely(tracked, tracked);\n return tracked;\n }\n };\n },\n dispose: () => {\n unsubscribe?.();\n }\n })\n } satisfies JourneyMachinePlugin;\n};\n\nexport type { JourneyAnalyticsPluginOptions, JourneyAnalyticsTrackedEvent } 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"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,2BAAAE,IAAA,eAAAC,EAAAH,GC0SO,IAAMI,EAA2B,IAAe,CACrD,IAAMC,EAAmB,WACzB,GAAI,OAAOA,EAAiB,SAAY,UACtC,OAAOA,EAAiB,QAG1B,IAAMC,EAAUD,EAAiB,SAAS,KAAK,SAC/C,O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AInB,IAAc,KACd,CAAC,EACD,CAAE,WAAY,KAAK,IAAI,EAAGmB,EAAW,UAAYnB,CAAS,CAAE,EAChE,GAAGW,EAAqBQ,EAAW,MAAM,EACzC,GAAGE,CACL,CACF,CAAC,EACD,OACF,IAAK,sBACHZ,EAAYU,EAAY,CACtB,KAAM,sBACN,UAAWA,EAAW,UACtB,GAAIrB,EAAQ,UAAY,CAAE,UAAWA,EAAQ,SAAU,EAAI,CAAC,EAC5D,QAAS,CACP,KAAMqB,EAAW,KACjB,GAAIA,EAAW,GACf,eAAgBA,EAAW,eAC3B,aAAcA,EAAW,aACzB,GAAGL,EAA2B,CAC5B,KAAMK,EAAW,KACjB,GAAIA,EAAW,EACjB,CAAC,EACD,GAAGE,CACL,CACF,CAAC,EACD,OACF,IAAK,yBACHZ,EAAYU,EAAY,CACtB,KAAM,0BACN,UAAWA,EAAW,UACtB,GAAIrB,EAAQ,UAAY,CAAE,UAAWA,EAAQ,SAAU,EAAI,CAAC,EAC5D,QAAS,CACP,KAAMqB,EAAW,KACjB,GAAIA,EAAW,GACf,GAAGL,EAA2B,CAC5B,KAAMK,EAAW,KACjB,GAAIA,EAAW,EACjB,CAAC,EACD,GAAGE,CACL,CACF,CAAC,EACD,MACJ,CACF,CAAC,EAEM,CACL,oBAAqB,CAACC,EAAcC,EAAmC,CAAC,IAAM,CAC5E,IAAMnB,EAAU,CACd,KAAAkB,EACA,UAAW,KAAK,IAAI,EACpB,GAAIxB,EAAQ,UAAY,CAAE,UAAWA,EAAQ,SAAU,EAAI,CAAC,EAC5D,QAAAyB,CACF,EACA,OAAArB,EAAYE,EAASA,CAAO,EACrBA,CACT,CACF,CACF,EACA,QAAS,IAAM,CACbL,IAAc,CAChB,CACF,EACF,CACF",
6
+ "names": ["analytics_exports", "__export", "createAnalyticsPlugin", "__toCommonJS", "isDevelopmentEnvironment", "diagnosticGlobal", "nodeEnv", "warnInDevelopment", "message", "detail", "buildBasePayload", "context", "createAnalyticsPlugin", "options", "unsubscribe", "startedAt", "activeStepEnteredAt", "trackSafely", "event", "tracked", "error", "warnInDevelopment", "machine", "typedMachine", "emitTracked", "sourceEvent", "buildStepMetaPayload", "stepId", "stepMeta", "buildTransitionMetaPayload", "from", "to", "fromStepMeta", "toStepMeta", "typedEvent", "snapshot", "basePayload", "name", "payload"]
7
+ }
@@ -0,0 +1,25 @@
1
+ import type { JourneyAnalyticsPluginOptions, JourneyAnalyticsTrackedEvent, JourneyJsonObject, JourneyMachine } from "../../types";
2
+ export type JourneyAnalyticsMachineExtension<TContext extends JourneyJsonObject, TStepId extends string, TStepMeta> = {
3
+ trackAnalyticsEvent: (name: string, payload?: Record<string, unknown>) => JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>;
4
+ };
5
+ export type JourneyAnalyticsMachine<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> & JourneyAnalyticsMachineExtension<TContext, TStepId, TStepMeta>;
6
+ /** Creates a plugin that converts journey observation events into analytics envelopes. */
7
+ export declare const createAnalyticsPlugin: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown>(options: JourneyAnalyticsPluginOptions<TContext, TStepId, TEventMap, TStepMeta>) => {
8
+ name: string;
9
+ setup: <TContext_1 extends JourneyJsonObject, TStepId_1 extends string, TEventMap_1 extends Record<string, unknown> = Record<never, never>, TStepMeta_1 = unknown, THandlers extends Record<string, unknown> = Record<never, never>>() => {
10
+ augmentMachine: ({ machine }: {
11
+ machine: JourneyMachine<TContext_1, TStepId_1, TEventMap_1, TStepMeta_1, THandlers>;
12
+ journey: import("../..").JourneyDefinition<TContext_1, TStepId_1, TEventMap_1, TStepMeta_1, THandlers>;
13
+ resolvedJourney: import("../../types").JourneyResolvedDefinition<TContext_1, TStepId_1, TEventMap_1, TStepMeta_1, THandlers>;
14
+ }) => {
15
+ trackAnalyticsEvent: (name: string, payload?: Record<string, unknown>) => {
16
+ payload: Record<string, unknown>;
17
+ machineId?: string;
18
+ name: string;
19
+ timestamp: number;
20
+ };
21
+ };
22
+ dispose: () => void;
23
+ };
24
+ };
25
+ export type { JourneyAnalyticsPluginOptions, JourneyAnalyticsTrackedEvent } from "../../types";
@@ -0,0 +1,25 @@
1
+ import type { JourneyAnalyticsPluginOptions, JourneyAnalyticsTrackedEvent, JourneyJsonObject, JourneyMachine } from "../../types";
2
+ export type JourneyAnalyticsMachineExtension<TContext extends JourneyJsonObject, TStepId extends string, TStepMeta> = {
3
+ trackAnalyticsEvent: (name: string, payload?: Record<string, unknown>) => JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>;
4
+ };
5
+ export type JourneyAnalyticsMachine<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> & JourneyAnalyticsMachineExtension<TContext, TStepId, TStepMeta>;
6
+ /** Creates a plugin that converts journey observation events into analytics envelopes. */
7
+ export declare const createAnalyticsPlugin: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown>(options: JourneyAnalyticsPluginOptions<TContext, TStepId, TEventMap, TStepMeta>) => {
8
+ name: string;
9
+ setup: <TContext_1 extends JourneyJsonObject, TStepId_1 extends string, TEventMap_1 extends Record<string, unknown> = Record<never, never>, TStepMeta_1 = unknown, THandlers extends Record<string, unknown> = Record<never, never>>() => {
10
+ augmentMachine: ({ machine }: {
11
+ machine: JourneyMachine<TContext_1, TStepId_1, TEventMap_1, TStepMeta_1, THandlers>;
12
+ journey: import("../..").JourneyDefinition<TContext_1, TStepId_1, TEventMap_1, TStepMeta_1, THandlers>;
13
+ resolvedJourney: import("../../types").JourneyResolvedDefinition<TContext_1, TStepId_1, TEventMap_1, TStepMeta_1, THandlers>;
14
+ }) => {
15
+ trackAnalyticsEvent: (name: string, payload?: Record<string, unknown>) => {
16
+ payload: Record<string, unknown>;
17
+ machineId?: string;
18
+ name: string;
19
+ timestamp: number;
20
+ };
21
+ };
22
+ dispose: () => void;
23
+ };
24
+ };
25
+ export type { JourneyAnalyticsPluginOptions, JourneyAnalyticsTrackedEvent } from "../../types";
@@ -0,0 +1,2 @@
1
+ var l=()=>{let n=globalThis;if(typeof n.__DEV__=="boolean")return n.__DEV__;let i=n.process?.env?.NODE_ENV;return i===void 0||i==="development"},m=(n,i)=>{if(!(!l()||typeof console>"u")){if(i===void 0){console.warn(n);return}console.warn(n,i)}};var f=({context:n})=>({context:n}),b=n=>{let i,d=null,u=null,T=(p,a)=>{try{n.track(a)}catch(t){if(n.onError){n.onError(t,p);return}m("Journey analytics track() threw without an onError handler.",t)}};return{name:"analytics",setup:()=>({augmentMachine:({machine:p})=>{let a=p,t=(o,e)=>{T(o,e)},c=o=>{if(!n.includeStepMeta)return{};let e=a.getStepMeta(o);return e===void 0?{}:{stepMeta:e}},y=({from:o,to:e})=>{if(!n.includeStepMeta)return{};let s=a.getStepMeta(o),r=e==="COMPLETE"||e==="TERMINATED"?void 0:a.getStepMeta(e);return{...s===void 0?{}:{fromStepMeta:s},...r===void 0?{}:{toStepMeta:r}}};return i=a.subscribeEvent(o=>{let e=o,s=a.getSnapshot(),r=f({context:s.context});switch(e.type){case"journey.start":d=e.timestamp,u=e.timestamp,t(e,{name:"journey_started",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...c(e.stepId),...r}});return;case"step.enter":u=e.timestamp,t(e,{name:"step_viewed",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...c(e.stepId),...r}});return;case"step.exit":t(e,{name:"step_exited",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...u===null?{}:{dwellMs:Math.max(0,e.timestamp-u)},...c(e.stepId),...r}});return;case"transition.start":t(e,{name:"transition_started",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,eventType:e.event.type,...r}});return;case"transition.success":t(e,{name:"transition_succeeded",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,to:e.to,eventType:e.eventType,transitionId:e.transitionId,...e.label!==void 0?{label:e.label}:{},...y({from:e.from,to:e.to}),...r}});return;case"transition.error":t(e,{name:"transition_failed",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,eventType:e.eventType,transitionId:e.transitionId,...e.label!==void 0?{label:e.label}:{},error:e.error,...r}});return;case"journey.completed":t(e,{name:"journey_completed",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...d===null?{}:{durationMs:Math.max(0,e.timestamp-d)},...c(e.stepId),...r}});return;case"journey.terminated":t(e,{name:"journey_terminated",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{stepId:e.stepId,...d===null?{}:{durationMs:Math.max(0,e.timestamp-d)},...c(e.stepId),...r}});return;case"navigation.previous":t(e,{name:"navigation_previous",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,to:e.to,requestedSteps:e.requestedSteps,appliedSteps:e.appliedSteps,...y({from:e.from,to:e.to}),...r}});return;case"navigation.lastVisited":t(e,{name:"navigation_last_visited",timestamp:e.timestamp,...n.machineId?{machineId:n.machineId}:{},payload:{from:e.from,to:e.to,...y({from:e.from,to:e.to}),...r}});return}}),{trackAnalyticsEvent:(o,e={})=>{let s={name:o,timestamp:Date.now(),...n.machineId?{machineId:n.machineId}:{},payload:e};return T(s,s),s}}},dispose:()=>{i?.()}})}};export{b as createAnalyticsPlugin};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/journey-machine/helpers.ts", "../../../src/plugins/analytics/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 { warnInDevelopment } from \"../../journey-machine/helpers\";\n\nimport type {\n JourneyAnalyticsPluginOptions,\n JourneyAnalyticsTrackedEvent,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin,\n JourneyObservationEvent,\n JourneyTerminal\n} from \"../../types\";\n\nconst buildBasePayload = <TContext extends JourneyJsonObject>({\n context\n}: {\n context: TContext;\n}) => ({ context });\n\nexport type JourneyAnalyticsMachineExtension<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TStepMeta\n> = {\n trackAnalyticsEvent: (\n name: string,\n payload?: Record<string, unknown>\n ) => JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>;\n};\n\nexport type JourneyAnalyticsMachine<\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 JourneyAnalyticsMachineExtension<TContext, TStepId, TStepMeta>;\n\n/** Creates a plugin that converts journey observation events into analytics envelopes. */\nexport const createAnalyticsPlugin = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown> = Record<never, never>,\n TStepMeta = unknown\n>(\n options: JourneyAnalyticsPluginOptions<TContext, TStepId, TEventMap, TStepMeta>\n) => {\n let unsubscribe: (() => void) | undefined;\n let startedAt: number | null = null;\n let activeStepEnteredAt: number | null = null;\n\n const trackSafely = (\n event:\n | JourneyObservationEvent<TStepId, TEventMap>\n | JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>,\n tracked: JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>\n ) => {\n try {\n options.track(tracked);\n } catch (error) {\n if (options.onError) {\n options.onError(error, event);\n return;\n }\n\n warnInDevelopment(\"Journey analytics track() threw without an onError handler.\", error);\n }\n };\n\n return {\n name: \"analytics\",\n setup: () => ({\n augmentMachine: ({ machine }) => {\n const typedMachine = machine as JourneyMachine<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n Record<string, unknown>\n >;\n\n const emitTracked = (\n sourceEvent: JourneyObservationEvent<TStepId, TEventMap>,\n tracked: JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>\n ) => {\n trackSafely(sourceEvent, tracked);\n };\n\n const buildStepMetaPayload = (stepId: TStepId) => {\n if (!options.includeStepMeta) {\n return {};\n }\n\n const stepMeta = typedMachine.getStepMeta(stepId) as TStepMeta | undefined;\n return stepMeta === undefined ? {} : { stepMeta };\n };\n\n const buildTransitionMetaPayload = ({\n from,\n to\n }: {\n from: TStepId;\n to: TStepId | JourneyTerminal;\n }) => {\n if (!options.includeStepMeta) {\n return {};\n }\n\n const fromStepMeta = typedMachine.getStepMeta(from) as TStepMeta | undefined;\n const toStepMeta =\n to === \"COMPLETE\" || to === \"TERMINATED\"\n ? undefined\n : (typedMachine.getStepMeta(to) as TStepMeta | undefined);\n\n return {\n ...(fromStepMeta === undefined ? {} : { fromStepMeta }),\n ...(toStepMeta === undefined ? {} : { toStepMeta })\n };\n };\n\n unsubscribe = typedMachine.subscribeEvent((event) => {\n const typedEvent = event as JourneyObservationEvent<TStepId, TEventMap>;\n const snapshot = typedMachine.getSnapshot();\n const basePayload = buildBasePayload({\n context: snapshot.context as TContext\n });\n\n switch (typedEvent.type) {\n case \"journey.start\":\n startedAt = typedEvent.timestamp;\n activeStepEnteredAt = typedEvent.timestamp;\n emitTracked(typedEvent, {\n name: \"journey_started\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"step.enter\":\n activeStepEnteredAt = typedEvent.timestamp;\n emitTracked(typedEvent, {\n name: \"step_viewed\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"step.exit\":\n emitTracked(typedEvent, {\n name: \"step_exited\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...(activeStepEnteredAt === null\n ? {}\n : { dwellMs: Math.max(0, typedEvent.timestamp - activeStepEnteredAt) }),\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"transition.start\":\n emitTracked(typedEvent, {\n name: \"transition_started\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n eventType: typedEvent.event.type,\n ...basePayload\n }\n });\n return;\n case \"transition.success\":\n emitTracked(typedEvent, {\n name: \"transition_succeeded\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n to: typedEvent.to,\n eventType: typedEvent.eventType,\n transitionId: typedEvent.transitionId,\n ...(typedEvent.label !== undefined ? { label: typedEvent.label } : {}),\n ...buildTransitionMetaPayload({\n from: typedEvent.from,\n to: typedEvent.to as TStepId | JourneyTerminal\n }),\n ...basePayload\n }\n });\n return;\n case \"transition.error\":\n emitTracked(typedEvent, {\n name: \"transition_failed\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n eventType: typedEvent.eventType,\n transitionId: typedEvent.transitionId,\n ...(typedEvent.label !== undefined ? { label: typedEvent.label } : {}),\n error: typedEvent.error,\n ...basePayload\n }\n });\n return;\n case \"journey.completed\":\n emitTracked(typedEvent, {\n name: \"journey_completed\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...(startedAt === null\n ? {}\n : { durationMs: Math.max(0, typedEvent.timestamp - startedAt) }),\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"journey.terminated\":\n emitTracked(typedEvent, {\n name: \"journey_terminated\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n stepId: typedEvent.stepId,\n ...(startedAt === null\n ? {}\n : { durationMs: Math.max(0, typedEvent.timestamp - startedAt) }),\n ...buildStepMetaPayload(typedEvent.stepId),\n ...basePayload\n }\n });\n return;\n case \"navigation.previous\":\n emitTracked(typedEvent, {\n name: \"navigation_previous\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n to: typedEvent.to,\n requestedSteps: typedEvent.requestedSteps,\n appliedSteps: typedEvent.appliedSteps,\n ...buildTransitionMetaPayload({\n from: typedEvent.from,\n to: typedEvent.to\n }),\n ...basePayload\n }\n });\n return;\n case \"navigation.lastVisited\":\n emitTracked(typedEvent, {\n name: \"navigation_last_visited\",\n timestamp: typedEvent.timestamp,\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload: {\n from: typedEvent.from,\n to: typedEvent.to,\n ...buildTransitionMetaPayload({\n from: typedEvent.from,\n to: typedEvent.to\n }),\n ...basePayload\n }\n });\n return;\n }\n });\n\n return {\n trackAnalyticsEvent: (name: string, payload: Record<string, unknown> = {}) => {\n const tracked = {\n name,\n timestamp: Date.now(),\n ...(options.machineId ? { machineId: options.machineId } : {}),\n payload\n } satisfies JourneyAnalyticsTrackedEvent<TContext, TStepId, TStepMeta>;\n trackSafely(tracked, tracked);\n return tracked;\n }\n };\n },\n dispose: () => {\n unsubscribe?.();\n }\n })\n } satisfies JourneyMachinePlugin;\n};\n\nexport type { JourneyAnalyticsPluginOptions, JourneyAnalyticsTrackedEvent } from \"../../types\";\n"],
5
+ "mappings": "AA0SO,IAAMA,EAA2B,IAAe,CACrD,IAAMC,EAAmB,WACzB,GAAI,OAAOA,EAAiB,SAAY,UACtC,OAAOA,EAAiB,QAG1B,IAAMC,EAAUD,EAAiB,SAAS,KAAK,SAC/C,OAAOC,IAAY,QAAaA,IAAY,aAC9C,EAEaC,EAAoB,CAACC,EAAiBC,IAAqB,CACtE,GAAI,GAACL,EAAyB,GAAK,OAAO,QAAY,KAItD,IAAIK,IAAW,OAAW,CACxB,QAAQ,KAAKD,CAAO,EACpB,MACF,CAEA,QAAQ,KAAKA,EAASC,CAAM,EAC9B,ECnTA,IAAMC,EAAm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AAQ,UAAY,CAAE,UAAWA,EAAQ,SAAU,EAAI,CAAC,EAC5D,QAAS,CACP,KAAMqB,EAAW,KACjB,GAAIA,EAAW,GACf,eAAgBA,EAAW,eAC3B,aAAcA,EAAW,aACzB,GAAGL,EAA2B,CAC5B,KAAMK,EAAW,KACjB,GAAIA,EAAW,EACjB,CAAC,EACD,GAAGE,CACL,CACF,CAAC,EACD,OACF,IAAK,yBACHZ,EAAYU,EAAY,CACtB,KAAM,0BACN,UAAWA,EAAW,UACtB,GAAIrB,EAAQ,UAAY,CAAE,UAAWA,EAAQ,SAAU,EAAI,CAAC,EAC5D,QAAS,CACP,KAAMqB,EAAW,KACjB,GAAIA,EAAW,GACf,GAAGL,EAA2B,CAC5B,KAAMK,EAAW,KACjB,GAAIA,EAAW,EACjB,CAAC,EACD,GAAGE,CACL,CACF,CAAC,EACD,MACJ,CACF,CAAC,EAEM,CACL,oBAAqB,CAACC,EAAcC,EAAmC,CAAC,IAAM,CAC5E,IAAMnB,EAAU,CACd,KAAAkB,EACA,UAAW,KAAK,IAAI,EACpB,GAAIxB,EAAQ,UAAY,CAAE,UAAWA,EAAQ,SAAU,EAAI,CAAC,EAC5D,QAAAyB,CACF,EACA,OAAArB,EAAYE,EAASA,CAAO,EACrBA,CACT,CACF,CACF,EACA,QAAS,IAAM,CACbL,IAAc,CAChB,CACF,EACF,CACF",
6
+ "names": ["isDevelopmentEnvironment", "diagnosticGlobal", "nodeEnv", "warnInDevelopment", "message", "detail", "buildBasePayload", "context", "createAnalyticsPlugin", "options", "unsubscribe", "startedAt", "activeStepEnteredAt", "trackSafely", "event", "tracked", "error", "warnInDevelopment", "machine", "typedMachine", "emitTracked", "sourceEvent", "buildStepMetaPayload", "stepId", "stepMeta", "buildTransitionMetaPayload", "from", "to", "fromStepMeta", "toStepMeta", "typedEvent", "snapshot", "basePayload", "name", "payload"]
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var P=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var Q=(e,n)=>{for(var t in n)P(e,t,{get:n[t],enumerable:!0})},X=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of K(n))!U.call(e,r)&&r!==t&&P(e,r,{get:()=>n[r],enumerable:!(o=q(n,r))||o.enumerable});return e};var Y=e=>X(P({},"__esModule",{value:!0}),e);var ye={};Q(ye,{createAutosavePlugin:()=>le});module.exports=Y(ye);var x=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),J=e=>Array.isArray(e)?e.map(n=>J(n)):x(e)?Object.fromEntries(Object.entries(e).map(([n,t])=>[n,J(t)])):e,R=e=>{if(e===null)return"null";if(Array.isArray(e))return"array";if(typeof e=="object"){let n=e.constructor?.name;return n&&n!=="Object"?n:"object"}return typeof e};function C(e,n,t,o=[]){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return;let r=o.length===0?n:`${n}.${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 ${R(e)}.`);if(t.seen.has(e))throw new Error(`${r} must be JSON-serializable. Circular references are not supported.`);if(t.seen.add(e),Array.isArray(e)){for(let[s,i]of e.entries())C(i,n,t,[...o,String(s)]);return}if(!x(e))throw new Error(`${r} must be JSON-serializable. Received non-plain ${R(e)}.`);for(let[s,i]of Object.entries(e))C(i,n,t,[...o,s])}function g(e,n="Journey context"){return C(e,n,{seen:new WeakSet}),e}var Z=e=>J(g(e));var j=e=>[...new Set(e)],ee=(e,n)=>Object.fromEntries(n.map(t=>[t,e[t]===!0])),I=(e,n)=>{let t=n??j(e),o=Object.fromEntries(t.map(r=>[r,!1]));for(let r of e)o[r]=!0;return o};var ne=()=>{let e=globalThis;if(typeof e.__DEV__=="boolean")return e.__DEV__;let n=e.process?.env?.NODE_ENV;return n===void 0||n==="development"},M=(e,n)=>{if(!(!ne()||typeof console>"u")){if(n===void 0){console.warn(e);return}console.warn(e,n)}};var te=()=>({phase:"idle",eventType:null,transitionId:null,error:null}),$=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(t=>[t,te()]))});var E=(e,n,t,o,r,s)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let i=Math.max(0,Math.min(Math.trunc(n),e.length-1)),u=e[i],c=j(s?[...Object.keys(s),...e]:e);return{status:o,currentStepId:u,history:{timeline:[...e],index:i},context:Z(t),visited:s?ee(s,c):I(e,c),async:J(r)}};var k=e=>typeof e=="object"&&e!==null,V=e=>e==="idled"||e==="running"||e==="completed"||e==="terminated",re=(e,n)=>{if(typeof e!="string")throw new Error(`Persistence ${n} entries must be strings.`);let t=e.trim();if(!t)throw new Error(`Persistence ${n} entries must not be empty.`);if(t.includes("[")||t.includes("]")||t.includes("*")||t.startsWith(".")||t.endsWith(".")||t.includes(".."))throw new Error(`Persistence ${n} entry "${t}" must use exact dot-separated object keys.`);let o=t.split(".");if(o.some(r=>!r||r.trim()!==r||/^[0-9]+$/.test(r)))throw new Error(`Persistence ${n} entry "${t}" must use exact dot-separated object keys.`);return o},L=(e,n)=>{if(e===void 0)return null;if(!Array.isArray(e))throw new Error(`Persistence ${n} must be an array of dot-separated strings.`);let t=new Map;for(let o of e){let r=re(o,n);t.set(r.join("."),r)}return[...t.values()]},_=(e,n)=>n.length<=e.length&&n.every((t,o)=>e[o]===t),z=(e,n)=>e.some(t=>_(n,t)),oe=(e,n)=>e.some(t=>_(t,n)),F=(e,n,t,o=[])=>{if(z(t,o))return{value:void 0,changed:!0,included:!1};let r=n===null,s=r||z(n,o),i=r||oe(n,o);if(!s&&!i)return{value:void 0,changed:!0,included:!1};if(!x(e))return{value:e,changed:!s,included:s};let u=!1,c={};for(let[y,T]of Object.entries(e)){let p=F(T,n,t,[...o,y]);if(!p.included){u=!0;continue}c[y]=p.value,p.changed&&(u=!0)}return{value:c,changed:u||Object.keys(c).length!==Object.keys(e).length,included:!0}},N=(e,n)=>{if(x(e)&&x(n)){let t=new Map;for(let[o,r]of Object.entries(e))t.set(o,r);for(let[o,r]of Object.entries(n))t.set(o,N(e[o],r));return Object.fromEntries(t)}return n===void 0?e??null:n},se=(e,n)=>N(e,n),ie=()=>{let e=globalThis.localStorage;return!e||typeof e.getItem!="function"||typeof e.setItem!="function"||typeof e.removeItem!="function"?null:e},A=(e,n)=>{if(n){n(e);return}M("Journey persistence encountered an error without an onError handler.",e)},ae=e=>{if(!e)return null;let n=e.storage;if(n==null)try{n=ie()}catch(r){return A(r,e.onError),null}if(!n)return null;let t,o;try{let r=L(e.allowList,"allowList"),s=L(e.blockList,"blockList");t=r?r.map(i=>i.join(".")):void 0,o=s?s.map(i=>i.join(".")):[]}catch(r){return A(r,e.onError),null}return{key:e.key,storage:n,version:e.version??1,clearOnReset:e.clearOnReset??!0,...t?{allowList:t}:{},blockList:o,serialize:e.serialize??JSON.stringify,deserialize:e.deserialize??JSON.parse,...e.migrate?{migrate:e.migrate}:{},...e.onError?{onError:e.onError}:{}}},de=(e,n,t)=>{let o=I(n,t);if(k(e)){let r=!1,s={...o};for(let i of t){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=I(e.filter(i=>typeof i=="string"&&t.includes(i)),t);return{visited:Object.fromEntries(t.map(i=>[i,o[i]||r[i]])),needsRewrite:!0}}return{visited:o,needsRewrite:!0}},D=(e,n,t)=>{if(!k(e))return null;let o=!1,r=k(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 n):[],u=typeof e.currentStepId=="string"&&e.currentStepId in n?e.currentStepId:typeof e.current=="string"&&e.current in n?e.current:null;if(i.length===0){if(!u)return null;i.push(u),o=!0}let c=i.length-1,y=r?.index??e.index;if(typeof y=="number"&&Number.isFinite(y))c=Math.max(0,Math.min(Math.trunc(y),i.length-1)),c!==y&&(o=!0);else if(u){let a=i.lastIndexOf(u);a>=0&&(c=a,o=!0)}let T=V(e.status)?e.status:"idled";V(e.status)||(o=!0);let p=Object.keys(n),{visited:S,needsRewrite:m}=de(e.visited,i,p);return m&&(o=!0),{snapshot:{currentStepId:i[c],history:{timeline:i,index:c},context:g("context"in e?e.context:t,"Persisted journey context"),status:T,visited:S},needsRewrite:o}},H=e=>{let{initial:n,context:t,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(".")):[],c=a=>{A(a,s?.onError)},y=a=>{if(!s||i===null&&u.length===0)return{context:a,changed:!1};if(!x(a))return{context:a,changed:!1};let d=F(a,i,u);return{context:d.included&&x(d.value)?d.value:{},changed:d.changed}},T=a=>{if(s)try{let{context:d}=y(a.context),l={version:s.version,snapshot:{currentStepId:a.currentStepId,history:{timeline:[...a.history.timeline],index:a.history.index},context:d,status:a.status,visited:{...a.visited}}};s.storage.setItem(s.key,s.serialize(l))}catch(d){c(d)}},p=()=>{if(s)try{s.storage.removeItem(s.key)}catch(a){c(a)}},S=()=>E([n],0,t,"idled",$(o)),m=(a=S())=>{let d=E(a.history.timeline,a.history.index,a.context,a.status,a.async,a.visited);if(!s)return d;try{let l=s.storage.getItem(s.key);if(!l)return d;let h=s.deserialize(l);if(!k(h))return d;let b=h.version;if(typeof b!="number")return d;let f=null,v=!1;if(b===s.version){let w=D(h.snapshot,o,t);f=w?.snapshot??null,v=!!w?.needsRewrite}else if(s.migrate){let w=s.migrate(h.snapshot,b);f=D(w,o,t)?.snapshot??null,v=f!==null,f||c(new Error(`Journey persistence migrate() returned data that could not be coerced into a valid snapshot. Falling back to the initial snapshot (persisted version: ${b}, current version: ${s.version}).`))}if(!f)return d;let{context:G,changed:B}=y(f.context),W=se(d.context,G),O=E(f.history.timeline,f.history.index,g(W,"Hydrated journey context"),f.status==="running"?"idled":f.status,d.async,f.visited);return(v||B)&&T(O),O}catch(l){return c(l),d}};return{clearOnReset:s?.clearOnReset??!0,hydrateSnapshot:m,persistSnapshot:T,removePersistedSnapshot:p}};var ue=["context","navigation","reset","start","transition"],ce=e=>typeof e!="number"||!Number.isFinite(e)?300:Math.max(0,Math.trunc(e)),le=e=>{let n=ce(e.debounceMs),t=e.hydrate??!0,o=new Set(e.saveOn??ue),r={status:"idle"},s=null,i=null,u=!1;return{name:"autosave",__extension__:void 0,setup:(({resolvedJourney:y})=>{let T=e,p=H({initial:y.initial,context:y.context,steps:y.steps,options:{...T,onError:d=>{u=!0,r={status:"error",...r.lastSavedAt!==void 0?{lastSavedAt:r.lastSavedAt}:{},...r.pendingReason!==void 0?{pendingReason:r.pendingReason}:{},error:d},T.onError?.(d)}}}),S=()=>{s!==null&&(clearTimeout(s),s=null)},m=()=>{if(S(),!i)return;let d=i;if(i=null,u=!1,p.persistSnapshot(d.snapshot),u)return;let l=Date.now();r={status:"saved",lastSavedAt:l},T.onSaved?.({snapshot:d.snapshot,reason:d.reason,timestamp:l})},a=(d,l)=>{if(i={snapshot:d,reason:l},r={status:"pending",...r.lastSavedAt!==void 0?{lastSavedAt:r.lastSavedAt}:{},pendingReason:l},n===0){m();return}S(),s=setTimeout(()=>{m()},n)};return{hydrateSnapshot:d=>t?p.hydrateSnapshot(d):d,onSnapshotChange:({snapshot:d,reason:l})=>{if(l!=="async"){if(l==="reset"&&p.clearOnReset){S(),i=null,p.removePersistedSnapshot(),r={status:"idle"};return}o.has(l)&&a(d,l)}},augmentMachine:()=>({getAutosaveState:()=>({...r}),flushAutosave:async()=>{m()},clearAutosave:()=>{S(),i=null,p.removePersistedSnapshot(),r={status:"idle"}}}),dispose:()=>{S()}}})}};0&&(module.exports={createAutosavePlugin});
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/plugins/autosave/index.ts", "../../../src/journey-machine/helpers.ts", "../../../src/plugins/persistence/controller.ts"],
4
+ "sourcesContent": ["import { createPersistenceController } from \"../persistence/controller\";\n\nimport type {\n JourneyAutosavePluginOptions,\n JourneyAutosaveState,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin,\n JourneyMachineSnapshotReason,\n JourneySnapshot\n} from \"../../types\";\n\nconst DEFAULT_SAVE_REASONS = [\"context\", \"navigation\", \"reset\", \"start\", \"transition\"] as const;\n\nconst normalizeDebounceMs = (value: number | undefined) => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return 300;\n }\n\n return Math.max(0, Math.trunc(value));\n};\n\nexport type JourneyAutosaveMachineExtension = {\n getAutosaveState: () => JourneyAutosaveState;\n flushAutosave: () => Promise<void>;\n clearAutosave: () => void;\n};\n\nexport type JourneyAutosaveMachine<\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 JourneyAutosaveMachineExtension;\n\n/**\n * Creates a plugin that debounces snapshot persistence and exposes autosave\n * runtime state without requiring the persistence plugin as a public dependency.\n */\nexport const createAutosavePlugin = <TContext extends JourneyJsonObject, TStepId extends string>(\n options: JourneyAutosavePluginOptions<TContext, TStepId>\n) => {\n const debounceMs = normalizeDebounceMs(options.debounceMs);\n const hydrate = options.hydrate ?? true;\n const saveReasons = new Set(options.saveOn ?? DEFAULT_SAVE_REASONS);\n let autosaveState: JourneyAutosaveState = { status: \"idle\" };\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let pending: {\n snapshot: JourneySnapshot<JourneyJsonObject, string>;\n reason: JourneyMachineSnapshotReason;\n } | null = null;\n let lastSaveErrored = false;\n\n const setup = (({ resolvedJourney }) => {\n const resolvedOptions = options as unknown as JourneyAutosavePluginOptions<TContext, TStepId>;\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 ...resolvedOptions,\n onError: (error) => {\n lastSaveErrored = true;\n autosaveState = {\n status: \"error\",\n ...(autosaveState.lastSavedAt !== undefined\n ? { lastSavedAt: autosaveState.lastSavedAt }\n : {}),\n ...(autosaveState.pendingReason !== undefined\n ? { pendingReason: autosaveState.pendingReason }\n : {}),\n error\n };\n resolvedOptions.onError?.(error);\n }\n } as JourneyAutosavePluginOptions<TContext, TStepId>\n });\n\n const clearTimer = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n const commitPending = () => {\n clearTimer();\n if (!pending) {\n return;\n }\n\n const current = pending;\n pending = null;\n lastSaveErrored = false;\n controller.persistSnapshot(\n current.snapshot as unknown as Parameters<typeof controller.persistSnapshot>[0]\n );\n if (lastSaveErrored) {\n return;\n }\n\n const timestamp = Date.now();\n autosaveState = {\n status: \"saved\",\n lastSavedAt: timestamp\n };\n resolvedOptions.onSaved?.({\n snapshot: current.snapshot as unknown as JourneySnapshot<TContext, TStepId>,\n reason: current.reason,\n timestamp\n });\n };\n\n const scheduleSave = (\n snapshot: Parameters<typeof controller.persistSnapshot>[0],\n reason: JourneyMachineSnapshotReason\n ) => {\n pending = {\n snapshot: snapshot as unknown as JourneySnapshot<JourneyJsonObject, string>,\n reason\n };\n autosaveState = {\n status: \"pending\",\n ...(autosaveState.lastSavedAt !== undefined\n ? { lastSavedAt: autosaveState.lastSavedAt }\n : {}),\n pendingReason: reason\n };\n\n if (debounceMs === 0) {\n commitPending();\n return;\n }\n\n clearTimer();\n timeoutId = setTimeout(() => {\n commitPending();\n }, debounceMs);\n };\n\n return {\n hydrateSnapshot: (snapshot) =>\n hydrate\n ? (controller.hydrateSnapshot(snapshot as never) as unknown as typeof snapshot)\n : snapshot,\n onSnapshotChange: ({ snapshot, reason }) => {\n if (reason === \"async\") {\n return;\n }\n\n if (reason === \"reset\" && controller.clearOnReset) {\n clearTimer();\n pending = null;\n controller.removePersistedSnapshot();\n autosaveState = { status: \"idle\" };\n return;\n }\n\n if (!saveReasons.has(reason)) {\n return;\n }\n\n scheduleSave(\n snapshot as unknown as Parameters<typeof controller.persistSnapshot>[0],\n reason\n );\n },\n augmentMachine: () => ({\n getAutosaveState: () => ({ ...autosaveState }),\n flushAutosave: async () => {\n commitPending();\n },\n clearAutosave: () => {\n clearTimer();\n pending = null;\n controller.removePersistedSnapshot();\n autosaveState = { status: \"idle\" };\n }\n }),\n dispose: () => {\n clearTimer();\n }\n };\n }) as JourneyMachinePlugin[\"setup\"];\n\n return {\n name: \"autosave\",\n __extension__: undefined as unknown as JourneyAutosaveMachineExtension,\n setup\n } satisfies JourneyMachinePlugin;\n};\n\nexport type { JourneyAutosavePluginOptions, JourneyAutosaveState } 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,0BAAAE,KAAA,eAAAC,EAAAH,IC4BO,IAAMI,EAAiBC,GAC5B,OAAOA,GAAU,UACjBA,IAAU,MACV,CAAC,MAAM,QAAQA,CAAK,IACnB,OAAO,eAAeA,CAAK,IAAM,OAAO,WAAa,OAAO,eAAeA,CAAK,IAAM,MAEnFC,EAAsDD,GACtD,MAAM,QAAQA,CAAK,EACdA,EAAM,IAAKE,GAAUD,EAAuBC,CAAK,CAAC,EAGvDH,EAAcC,CAAK,EACd,OAAO,YACZ,OAAO,QAAQA,CAAK,EAAE,IAAI,CAAC,CAACG,EAAKC,CAAU,IAAM,CAC/CD,EACAF,EAAuBG,CAA8B,CACvD,CAAC,CACH,EAGKJ,EAOHK,EAAiBL,GAA2B,CAChD,GAAIA,IAAU,KACZ,MAAO,OAGT,GAAI,MAAM,QAAQA,CAAK,EACrB,MAAO,QAGT,GAAI,OAAOA,GAAU,SAAU,CAC7B,IAAMM,EAAmBN,EAA8C,aAAa,KACpF,OAAOM,GAAmBA,IAAoB,SAAWA,EAAkB,QAC7E,CAEA,OAAO,OAAON,CAChB,EAEA,SAASO,EACPP,EACAQ,EACAC,EACAC,EAA0B,CAAC,EACQ,CACnC,GACEV,IAAU,MACV,OAAOA,GAAU,UACjB,OAAOA,GAAU,UACjB,OAAOA,GAAU,UAEjB,OAGF,IA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jC,MACF,CAEKD,EAAY,IAAIgB,CAAM,GAI3BF,EACEC,EACAC,CACF,EACF,EACA,eAAgB,KAAO,CACrB,iBAAkB,KAAO,CAAE,GAAGf,CAAc,GAC5C,cAAe,SAAY,CACzBU,EAAc,CAChB,EACA,cAAe,IAAM,CACnBD,EAAW,EACXP,EAAU,KACVI,EAAW,wBAAwB,EACnCN,EAAgB,CAAE,OAAQ,MAAO,CACnC,CACF,GACA,QAAS,IAAM,CACbS,EAAW,CACb,CACF,CACF,EAMA,CACF",
6
+ "names": ["autosave_exports", "__export", "createAutosavePlugin", "__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", "DEFAULT_SAVE_REASONS", "normalizeDebounceMs", "value", "createAutosavePlugin", "options", "debounceMs", "hydrate", "saveReasons", "autosaveState", "timeoutId", "pending", "lastSaveErrored", "resolvedJourney", "resolvedOptions", "controller", "createPersistenceController", "error", "clearTimer", "commitPending", "current", "timestamp", "scheduleSave", "snapshot", "reason"]
7
+ }
@@ -0,0 +1,17 @@
1
+ import type { JourneyAutosavePluginOptions, JourneyAutosaveState, JourneyJsonObject, JourneyMachine } from "../../types";
2
+ export type JourneyAutosaveMachineExtension = {
3
+ getAutosaveState: () => JourneyAutosaveState;
4
+ flushAutosave: () => Promise<void>;
5
+ clearAutosave: () => void;
6
+ };
7
+ export type JourneyAutosaveMachine<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> & JourneyAutosaveMachineExtension;
8
+ /**
9
+ * Creates a plugin that debounces snapshot persistence and exposes autosave
10
+ * runtime state without requiring the persistence plugin as a public dependency.
11
+ */
12
+ export declare const createAutosavePlugin: <TContext extends JourneyJsonObject, TStepId extends string>(options: JourneyAutosavePluginOptions<TContext, TStepId>) => {
13
+ name: string;
14
+ __extension__: JourneyAutosaveMachineExtension;
15
+ 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>;
16
+ };
17
+ export type { JourneyAutosavePluginOptions, JourneyAutosaveState } from "../../types";
@@ -0,0 +1,17 @@
1
+ import type { JourneyAutosavePluginOptions, JourneyAutosaveState, JourneyJsonObject, JourneyMachine } from "../../types";
2
+ export type JourneyAutosaveMachineExtension = {
3
+ getAutosaveState: () => JourneyAutosaveState;
4
+ flushAutosave: () => Promise<void>;
5
+ clearAutosave: () => void;
6
+ };
7
+ export type JourneyAutosaveMachine<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> & JourneyAutosaveMachineExtension;
8
+ /**
9
+ * Creates a plugin that debounces snapshot persistence and exposes autosave
10
+ * runtime state without requiring the persistence plugin as a public dependency.
11
+ */
12
+ export declare const createAutosavePlugin: <TContext extends JourneyJsonObject, TStepId extends string>(options: JourneyAutosavePluginOptions<TContext, TStepId>) => {
13
+ name: string;
14
+ __extension__: JourneyAutosaveMachineExtension;
15
+ 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>;
16
+ };
17
+ export type { JourneyAutosavePluginOptions, JourneyAutosaveState } from "../../types";