@rxova/journey-core 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -47
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/machine-helpers.d.ts +11 -13
- package/dist/machine.d.ts +8 -3
- package/dist/persistence.d.ts +6 -6
- package/dist/transitions.d.ts +21 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/journey.types.d.ts +150 -0
- package/dist/types/persistence.types.d.ts +41 -0
- package/dist/types/transitions.types.d.ts +47 -0
- package/dist/types.d.ts +1 -139
- package/package.json +4 -3
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/machine-helpers.d.ts.map +0 -1
- package/dist/machine.d.ts.map +0 -1
- package/dist/persistence.d.ts.map +0 -1
- package/dist/tsconfig.build.tsbuildinfo +0 -1
- package/dist/types.d.ts.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/types.ts", "../src/machine-helpers.ts", "../src/persistence.ts", "../src/machine.ts"],
|
|
4
|
-
"sourcesContent": ["export const JOURNEY_TERMINAL = {\n COMPLETE: \"COMPLETE\",\n CLOSE: \"CLOSE\"\n} as const;\n\nexport type JourneyTerminal = (typeof JOURNEY_TERMINAL)[keyof typeof JOURNEY_TERMINAL];\n\nexport const JOURNEY_STATUS = {\n RUNNING: \"running\",\n COMPLETE: \"complete\",\n CLOSED: \"closed\"\n} as const;\n\nexport type JourneyStatus = (typeof JOURNEY_STATUS)[keyof typeof JOURNEY_STATUS];\n\nexport const HISTORY_TARGET = \"__HISTORY__\" as const;\nexport const JOURNEY_WILDCARD = \"*\" as const;\n\nexport const JOURNEY_EVENT = {\n GO_TO: \"goTo\"\n} as const;\n\nexport type JourneyBuiltInEvent = (typeof JOURNEY_EVENT)[keyof typeof JOURNEY_EVENT];\nexport type JourneyBuiltInFrom = typeof JOURNEY_WILDCARD;\n\nexport const JOURNEY_ASYNC_PHASE = {\n IDLE: \"idle\",\n EVALUATING_WHEN: \"evaluating-when\",\n RUNNING_EFFECT: \"running-effect\",\n ERROR: \"error\"\n} as const;\n\nexport type JourneyAsyncPhase = (typeof JOURNEY_ASYNC_PHASE)[keyof typeof JOURNEY_ASYNC_PHASE];\n\nexport type JourneyStepAsyncState = {\n phase: JourneyAsyncPhase;\n eventType: string | null;\n transitionId: string | null;\n error: unknown | null;\n};\n\nexport type JourneyAsyncState<TStepId extends string> = {\n isLoading: boolean;\n byStep: Record<TStepId, JourneyStepAsyncState>;\n};\n\nexport type JourneyBaseEvent = {\n type: string;\n payload?: unknown;\n};\n\nexport type JourneyEventPayloadMap<TEventType extends string> = Partial<\n Record<TEventType | JourneyBuiltInEvent, unknown>\n>;\n\nexport type JourneyPayloadFor<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TEvent extends TEventType | JourneyBuiltInEvent\n> = TEvent extends keyof TPayloadMap ? TPayloadMap[TEvent] : unknown;\n\nexport type JourneyGoToEvent<TStepId extends string, TPayload = unknown> = {\n type: (typeof JOURNEY_EVENT)[\"GO_TO\"];\n to: TStepId;\n payload?: TPayload;\n};\n\nexport type JourneyEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> =\n | JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<TEventType, TPayloadMap, (typeof JOURNEY_EVENT)[\"GO_TO\"]>\n >\n | {\n [TType in TEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<TEventType, TPayloadMap, TType>;\n };\n }[TEventType];\n\nexport type JourneyTransitionArgs<\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> = {\n context: TContext;\n from: TStepId;\n history: readonly TStepId[];\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>;\n};\n\nexport type JourneyTransitionTarget<TStepId extends string> =\n | TStepId\n | JourneyTerminal\n | typeof HISTORY_TARGET;\n\nexport type JourneyTransition<\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> = {\n id?: string;\n from: TStepId | JourneyBuiltInFrom;\n event: TEventType | (typeof JOURNEY_EVENT)[\"GO_TO\"];\n to: JourneyTransitionTarget<TStepId>;\n when?: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => boolean | Promise<boolean>;\n effect?: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => TContext | void | Promise<TContext | void>;\n};\n\nexport type JourneySnapshot<TContext, TStepId extends string> = {\n current: TStepId;\n context: TContext;\n history: readonly TStepId[];\n visited: readonly TStepId[];\n status: JourneyStatus;\n async: JourneyAsyncState<TStepId>;\n};\n\nexport type JourneyPersistedSnapshot<TContext, TStepId extends string> = {\n current: TStepId;\n context: TContext;\n history: readonly TStepId[];\n status: JourneyStatus;\n visited: readonly TStepId[];\n};\n\nexport type JourneyPersistedState<TContext, TStepId extends string> = {\n version: number;\n snapshot: JourneyPersistedSnapshot<TContext, TStepId>;\n};\n\nexport type JourneyHistoryOverflowReason = \"auto\" | \"hydrate\" | \"manual\";\n\nexport type JourneyHistoryOverflow<TStepId extends string> = {\n previous: readonly TStepId[];\n next: readonly TStepId[];\n trimmed: readonly TStepId[];\n maxHistory: number | null;\n reason: JourneyHistoryOverflowReason;\n};\n\nexport type JourneyHistoryOptions<TStepId extends string> = {\n maxHistory?: number | null;\n onOverflow?: (info: JourneyHistoryOverflow<TStepId>) => void;\n};\n\nexport type JourneyStorage = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n};\n\nexport type JourneyPersistenceOptions<TContext, TStepId extends string> = {\n key: string;\n storage?: JourneyStorage;\n version?: number;\n clearOnReset?: boolean;\n serialize?: (value: JourneyPersistedState<TContext, TStepId>) => string;\n deserialize?: (value: string) => unknown;\n migrate?: (\n value: unknown,\n persistedVersion: number\n ) => JourneyPersistedSnapshot<TContext, TStepId>;\n onError?: (error: unknown) => void;\n};\n\nexport type JourneyDefinition<\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> = {\n initial: TStepId;\n context: TContext;\n steps: Record<TStepId, unknown>;\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[];\n};\n\nexport type JourneyMachineOptions<TContext, TStepId extends string> = {\n persistence?: JourneyPersistenceOptions<TContext, TStepId>;\n history?: JourneyHistoryOptions<TStepId>;\n};\n\nexport type JourneySendResult<TContext, TStepId extends string> = {\n transitioned: boolean;\n transitionId?: string;\n snapshot: JourneySnapshot<TContext, TStepId>;\n};\n\nexport type JourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> = {\n getSnapshot: () => JourneySnapshot<TContext, TStepId>;\n send: (\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>\n ) => Promise<JourneySendResult<TContext, TStepId>>;\n updateContext: (updater: (context: TContext) => TContext) => JourneySnapshot<TContext, TStepId>;\n clearStepError: (stepId?: TStepId) => JourneySnapshot<TContext, TStepId>;\n reset: () => JourneySnapshot<TContext, TStepId>;\n trimHistory: (maxHistory?: number | null) => JourneySnapshot<TContext, TStepId>;\n clearHistory: () => JourneySnapshot<TContext, TStepId>;\n subscribe: (listener: () => void) => () => void;\n};\n", "import { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_TERMINAL, JOURNEY_WILDCARD } from \"./types\";\nimport type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyEventPayloadMap,\n JourneyGoToEvent,\n JourneyPayloadFor,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransition\n} from \"./types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nexport const buildVisited = <TStepId extends string>(\n history: readonly TStepId[],\n current: TStepId\n): TStepId[] => unique([...history, current]);\n\nexport const appendVisited = <TStepId extends string>(\n visited: readonly TStepId[],\n current: TStepId\n): TStepId[] => (visited.includes(current) ? [...visited] : [...visited, current]);\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: JOURNEY_ASYNC_PHASE.IDLE,\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToEvent = <\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>\n): event is JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<TEventType, TPayloadMap, (typeof JOURNEY_EVENT)[\"GO_TO\"]>\n> => event.type === JOURNEY_EVENT.GO_TO && \"to\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal | \"__HISTORY__\"\n): target is JourneyTerminal =>\n target === JOURNEY_TERMINAL.COMPLETE || target === JOURNEY_TERMINAL.CLOSE;\n\nexport const buildSendResult = <TContext, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n transitioned: boolean,\n transitionId?: string\n): JourneySendResult<TContext, TStepId> =>\n transitionId ? { transitioned, transitionId, snapshot } : { transitioned, snapshot };\n\nexport const buildSnapshot = <TContext, TStepId extends string>(\n current: TStepId,\n context: TContext,\n history: readonly TStepId[],\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n visited?: readonly TStepId[]\n): JourneySnapshot<TContext, TStepId> => ({\n status,\n current,\n context,\n history,\n visited: visited ? [...visited] : buildVisited(history, current),\n async: asyncState\n});\n\nexport const resolveHistoryTarget = <TContext, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n steps: Record<TStepId, unknown>\n): { target: TStepId; history: TStepId[] } => {\n const cloned = [...snapshot.history];\n\n while (cloned.length > 0) {\n const candidate = cloned.pop();\n if (!candidate) {\n break;\n }\n if (candidate in steps) {\n return {\n target: candidate,\n history: cloned\n };\n }\n }\n\n return {\n target: snapshot.current,\n history: [...snapshot.history]\n };\n};\n\nexport const selectTransition = async <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[],\n snapshot: JourneySnapshot<TContext, TStepId>,\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>,\n hooks?: {\n onAsyncGuardStart?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardSuccess?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardError?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>,\n error: unknown\n ) => void;\n }\n): Promise<JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> | null> => {\n for (const transition of transitions) {\n const fromMatches =\n transition.from === JOURNEY_WILDCARD || transition.from === snapshot.current;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n const guardResult = transition.when({\n context: snapshot.context,\n from: snapshot.current,\n history: snapshot.history,\n event\n });\n const asyncGuard = isPromiseLike(guardResult);\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n }\n\n let allowed: boolean;\n try {\n allowed = await guardResult;\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId> => {\n const history =\n nextCurrent === snapshot.current\n ? [...snapshot.history]\n : [...snapshot.history, snapshot.current];\n\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(nextCurrent, nextContext, history, snapshot.status, snapshot.async, visited);\n};\n", "import { JOURNEY_STATUS } from \"./types\";\nimport type {\n JourneyMachineOptions,\n JourneyPersistedSnapshot,\n JourneyPersistedState,\n JourneyStatus,\n JourneySnapshot,\n JourneyStorage\n} from \"./types\";\nimport { buildInitialAsyncState, buildSnapshot, buildVisited } from \"./machine-helpers\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isStatusValue = (value: unknown): value is JourneyStatus =>\n value === JOURNEY_STATUS.RUNNING ||\n value === JOURNEY_STATUS.COMPLETE ||\n value === JOURNEY_STATUS.CLOSED;\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\ntype ResolvedPersistence<TContext, TStepId extends string> = {\n key: string;\n storage: JourneyStorage;\n version: number;\n clearOnReset: boolean;\n serialize: (value: JourneyPersistedState<TContext, TStepId>) => string;\n deserialize: (value: string) => unknown;\n migrate?: (\n value: unknown,\n persistedVersion: number\n ) => JourneyPersistedSnapshot<TContext, TStepId>;\n onError?: (error: unknown) => void;\n};\n\nconst resolvePersistence = <TContext, TStepId extends string>(\n options?: JourneyMachineOptions<TContext, TStepId>[\"persistence\"]\n): ResolvedPersistence<TContext, TStepId> | null => {\n if (!options) {\n return null;\n }\n\n const storage = options.storage ?? resolveDefaultStorage();\n if (!storage) {\n return null;\n }\n\n return {\n key: options.key,\n storage,\n version: options.version ?? 1,\n clearOnReset: options.clearOnReset ?? true,\n serialize: options.serialize ?? JSON.stringify,\n deserialize: options.deserialize ?? JSON.parse,\n ...(options.migrate ? { migrate: options.migrate } : {}),\n ...(options.onError ? { onError: options.onError } : {})\n };\n};\n\nconst coercePersistedSnapshot = <TContext, TStepId extends string>(\n value: unknown,\n steps: Record<TStepId, unknown>,\n fallbackContext: TContext\n): { snapshot: JourneyPersistedSnapshot<TContext, TStepId>; needsRewrite: boolean } | null => {\n if (!isRecord(value)) {\n return null;\n }\n\n const currentValue = value.current;\n if (typeof currentValue !== \"string\" || !(currentValue in steps)) {\n return null;\n }\n const current = currentValue as TStepId;\n\n const history = Array.isArray(value.history)\n ? (value.history.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[])\n : [];\n\n const status = isStatusValue(value.status) ? value.status : JOURNEY_STATUS.RUNNING;\n\n const visitedRaw = Array.isArray(value.visited)\n ? (value.visited.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[])\n : null;\n const visited = visitedRaw && visitedRaw.length > 0 ? visitedRaw : buildVisited(history, current);\n const needsRewrite = !visitedRaw || visitedRaw.length === 0;\n\n return {\n snapshot: {\n current,\n context: (\"context\" in value ? value.context : fallbackContext) as TContext,\n history,\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 = <TContext, TStepId extends string>(args: {\n initial: TStepId;\n context: TContext;\n steps: Record<TStepId, unknown>;\n options?: JourneyMachineOptions<TContext, TStepId>;\n}) => {\n const { initial, context, steps, options } = args;\n const persistence = resolvePersistence(options?.persistence);\n\n const reportPersistenceError = (error: unknown) => {\n persistence?.onError?.(error);\n };\n\n const persistSnapshot = (snapshot: JourneySnapshot<TContext, TStepId>) => {\n if (!persistence) {\n return;\n }\n\n try {\n const persistedState: JourneyPersistedState<TContext, TStepId> = {\n version: persistence.version,\n snapshot: {\n current: snapshot.current,\n context: snapshot.context,\n history: [...snapshot.history],\n status: snapshot.status,\n visited: [...snapshot.visited]\n }\n };\n persistence.storage.setItem(persistence.key, persistence.serialize(persistedState));\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const removePersistedSnapshot = () => {\n if (!persistence) {\n return;\n }\n\n try {\n persistence.storage.removeItem(persistence.key);\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const hydrateSnapshot = (): JourneySnapshot<TContext, TStepId> => {\n const initialSnapshot = buildSnapshot(\n initial,\n context,\n [],\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(steps)\n );\n if (!persistence) {\n return initialSnapshot;\n }\n\n try {\n const rawPersisted = persistence.storage.getItem(persistence.key);\n if (!rawPersisted) {\n return initialSnapshot;\n }\n\n const parsed = persistence.deserialize(rawPersisted);\n if (!isRecord(parsed)) {\n return initialSnapshot;\n }\n\n const persistedVersion = parsed.version;\n if (typeof persistedVersion !== \"number\") {\n return initialSnapshot;\n }\n\n let persistedSnapshot: JourneyPersistedSnapshot<TContext, TStepId> | 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\n if (!persistedSnapshot) {\n return initialSnapshot;\n }\n\n const hydratedSnapshot = buildSnapshot(\n persistedSnapshot.current,\n persistedSnapshot.context,\n persistedSnapshot.history,\n persistedSnapshot.status,\n buildInitialAsyncState(steps),\n persistedSnapshot.visited\n );\n\n if (shouldRewritePersisted) {\n persistSnapshot(hydratedSnapshot);\n }\n\n return hydratedSnapshot;\n } catch (error) {\n reportPersistenceError(error);\n return initialSnapshot;\n }\n };\n\n return {\n clearOnReset: persistence?.clearOnReset ?? true,\n hydrateSnapshot,\n persistSnapshot,\n removePersistedSnapshot\n };\n};\n", "import {\n JOURNEY_ASYNC_PHASE,\n JOURNEY_EVENT,\n JOURNEY_STATUS,\n JOURNEY_TERMINAL,\n JOURNEY_WILDCARD,\n HISTORY_TARGET\n} from \"./types\";\nimport type {\n JourneyAsyncState,\n JourneyAsyncPhase,\n JourneyEventPayloadMap,\n JourneyDefinition,\n JourneyHistoryOverflowReason,\n JourneyHistoryOptions,\n JourneyMachine,\n JourneyMachineOptions,\n JourneySendResult,\n JourneySnapshot\n} from \"./types\";\nimport {\n appendVisited,\n assertStepExists,\n buildIdleStepAsyncState,\n buildInitialAsyncState,\n buildSendResult,\n isGoToEvent,\n isPromiseLike,\n isTerminalTarget,\n resolveHistoryTarget,\n selectTransition,\n transitionSnapshot,\n buildSnapshot\n} from \"./machine-helpers\";\nimport { createPersistenceController } from \"./persistence\";\n\nconst DEFAULT_MAX_HISTORY = 50;\n\nconst resolveMaxHistory = (value: number | null | undefined): number | null => {\n if (value === null) {\n return null;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return Math.max(0, Math.trunc(value));\n }\n return DEFAULT_MAX_HISTORY;\n};\n\nconst applyHistoryLimit = <TStepId extends string>(\n history: readonly TStepId[],\n maxHistory: number | null\n): { next: TStepId[]; trimmed: TStepId[] } => {\n if (maxHistory === null || history.length <= maxHistory) {\n return { next: [...history], trimmed: [] };\n }\n\n const trimCount = history.length - maxHistory;\n return {\n next: history.slice(trimCount),\n trimmed: history.slice(0, trimCount)\n };\n};\n\n/**\n * Creates a journey machine from a journey definition.\n * Validates steps/transitions, hydrates persisted state (if configured),\n * and returns an API for sending events and reading snapshots.\n */\nexport const createJourneyMachine = <\n TContext,\n TStepId extends string,\n TEventType extends string = \"next\" | \"back\" | \"close\" | \"submit\",\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap>,\n options?: JourneyMachineOptions<TContext, TStepId>\n): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap> => {\n if (!journey.steps || typeof journey.steps !== \"object\") {\n throw new Error(\"Journey steps must be a record object.\");\n }\n\n if (!Array.isArray(journey.transitions)) {\n throw new Error(\"Journey transitions must be an array.\");\n }\n\n assertStepExists(\n journey.steps,\n journey.initial,\n `Journey initial step \"${journey.initial}\" does not exist in steps registry.`\n );\n\n for (const [index, transition] of journey.transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (\n transition.from !== JOURNEY_WILDCARD &&\n !((transition.from as string) in (journey.steps as Record<string, unknown>))\n ) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n if (\n transition.to !== HISTORY_TARGET &&\n !isTerminalTarget(transition.to) &&\n !((transition.to as string) in (journey.steps as Record<string, unknown>))\n ) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n\n const { clearOnReset, hydrateSnapshot, persistSnapshot, removePersistedSnapshot } =\n createPersistenceController({\n initial: journey.initial,\n context: journey.context,\n steps: journey.steps,\n ...(options ? { options } : {})\n });\n\n const historyOptions: JourneyHistoryOptions<TStepId> | undefined = options?.history;\n\n const runHistoryTrim = (\n nextSnapshot: JourneySnapshot<TContext, TStepId>,\n reason: JourneyHistoryOverflowReason,\n overrideMaxHistory?: number | null\n ): {\n snapshot: JourneySnapshot<TContext, TStepId>;\n trimmed: TStepId[];\n maxHistory: number | null;\n } => {\n const resolvedMaxHistory = resolveMaxHistory(overrideMaxHistory ?? historyOptions?.maxHistory);\n const { next, trimmed } = applyHistoryLimit(nextSnapshot.history, resolvedMaxHistory);\n if (trimmed.length === 0) {\n return {\n snapshot: nextSnapshot,\n trimmed,\n maxHistory: resolvedMaxHistory\n };\n }\n\n const rebuilt = buildSnapshot(\n nextSnapshot.current,\n nextSnapshot.context,\n next,\n nextSnapshot.status,\n nextSnapshot.async,\n nextSnapshot.visited\n );\n\n historyOptions?.onOverflow?.({\n previous: nextSnapshot.history,\n next,\n trimmed,\n maxHistory: resolvedMaxHistory,\n reason\n });\n\n return {\n snapshot: rebuilt,\n trimmed,\n maxHistory: resolvedMaxHistory\n };\n };\n\n let snapshot = hydrateSnapshot();\n const hydratedTrim = runHistoryTrim(snapshot, \"hydrate\");\n snapshot = hydratedTrim.snapshot;\n if (hydratedTrim.trimmed.length > 0) {\n persistSnapshot(snapshot);\n }\n const listeners = new Set<() => void>();\n let sendQueue: Promise<void> = Promise.resolve();\n snapshot = {\n ...snapshot,\n async: buildInitialAsyncState(journey.steps)\n };\n\n const notify = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n const isAsyncLoadingPhase = (phase: JourneyAsyncPhase): boolean =>\n phase === JOURNEY_ASYNC_PHASE.EVALUATING_WHEN || phase === JOURNEY_ASYNC_PHASE.RUNNING_EFFECT;\n\n const updateStepAsync = (\n stepId: TStepId,\n updater: (\n current: JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => {\n const current = snapshot.async.byStep[stepId] ?? buildIdleStepAsyncState();\n const next = updater(current);\n if (\n current.phase === next.phase &&\n current.eventType === next.eventType &&\n current.transitionId === next.transitionId &&\n current.error === next.error\n ) {\n return;\n }\n const nextByStep = {\n ...snapshot.async.byStep,\n [stepId]: next\n };\n const isLoading = Object.values(nextByStep).some((state) => isAsyncLoadingPhase(state.phase));\n snapshot = {\n ...snapshot,\n async: {\n isLoading,\n byStep: nextByStep\n }\n };\n notify();\n };\n\n const setStepLoading = (\n stepId: TStepId,\n phase: JourneyAsyncPhase,\n eventType: string,\n transitionId?: string\n ) => {\n updateStepAsync(stepId, () => ({\n phase,\n eventType,\n transitionId: transitionId ?? null,\n error: null\n }));\n };\n\n const setStepIdle = (stepId: TStepId) => {\n updateStepAsync(stepId, () => buildIdleStepAsyncState());\n };\n\n const setStepError = (\n stepId: TStepId,\n eventType: string,\n error: unknown,\n transitionId?: string\n ) => {\n updateStepAsync(stepId, () => ({\n phase: JOURNEY_ASYNC_PHASE.ERROR,\n eventType,\n transitionId: transitionId ?? null,\n error\n }));\n };\n\n return {\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reset: () => {\n snapshot = buildSnapshot(\n journey.initial,\n journey.context,\n [],\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(journey.steps)\n );\n if (clearOnReset) {\n removePersistedSnapshot();\n } else {\n persistSnapshot(snapshot);\n }\n notify();\n return snapshot;\n },\n updateContext: (updater) => {\n snapshot = {\n ...snapshot,\n context: updater(snapshot.context)\n };\n persistSnapshot(snapshot);\n notify();\n return snapshot;\n },\n clearStepError: (stepId) => {\n const resolvedStep = stepId ?? snapshot.current;\n if (!(resolvedStep in journey.steps)) {\n return snapshot;\n }\n\n setStepIdle(resolvedStep);\n return snapshot;\n },\n trimHistory: (maxHistory) => {\n const result = runHistoryTrim(snapshot, \"manual\", maxHistory);\n if (result.trimmed.length === 0) {\n return snapshot;\n }\n snapshot = result.snapshot;\n persistSnapshot(snapshot);\n notify();\n return snapshot;\n },\n clearHistory: () => {\n if (snapshot.history.length === 0) {\n return snapshot;\n }\n snapshot = buildSnapshot(\n snapshot.current,\n snapshot.context,\n [],\n snapshot.status,\n snapshot.async,\n snapshot.visited\n );\n persistSnapshot(snapshot);\n notify();\n return snapshot;\n },\n send: (event) => {\n const run = async (): Promise<JourneySendResult<TContext, TStepId>> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return { transitioned: false, snapshot };\n }\n\n const fromStep = snapshot.current;\n\n if (isGoToEvent(event)) {\n assertStepExists(journey.steps, event.to, `Cannot goTo unknown step \"${event.to}\".`);\n setStepIdle(fromStep);\n snapshot = transitionSnapshot(snapshot, event.to, snapshot.context);\n snapshot = runHistoryTrim(snapshot, \"auto\").snapshot;\n persistSnapshot(snapshot);\n notify();\n return buildSendResult(snapshot, true, JOURNEY_EVENT.GO_TO);\n }\n\n let transition;\n try {\n transition = await selectTransition(journey.transitions, snapshot, event, {\n onAsyncGuardStart: (currentTransition) => {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.EVALUATING_WHEN,\n event.type,\n currentTransition.id\n );\n },\n onAsyncGuardSuccess: () => {\n setStepIdle(fromStep);\n },\n onAsyncGuardError: (currentTransition, error) => {\n setStepError(fromStep, event.type, error, currentTransition.id);\n }\n });\n } catch (error) {\n setStepError(fromStep, event.type, error);\n throw error;\n }\n\n if (!transition) {\n return buildSendResult(snapshot, false);\n }\n\n let nextContext = snapshot.context;\n if (transition.effect) {\n const effectResultPromise = transition.effect({\n context: snapshot.context,\n from: snapshot.current,\n history: snapshot.history,\n event\n });\n if (isPromiseLike(effectResultPromise)) {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.RUNNING_EFFECT,\n event.type as string,\n transition.id\n );\n }\n\n let effectResult: TContext | void;\n try {\n effectResult = await effectResultPromise;\n } catch (error) {\n setStepError(fromStep, event.type, error, transition.id);\n throw error;\n }\n\n if (effectResult !== undefined) {\n nextContext = effectResult;\n }\n }\n\n setStepIdle(fromStep);\n\n if (isTerminalTarget(transition.to)) {\n snapshot = {\n ...snapshot,\n context: nextContext,\n status:\n transition.to === JOURNEY_TERMINAL.COMPLETE\n ? JOURNEY_STATUS.COMPLETE\n : JOURNEY_STATUS.CLOSED\n };\n snapshot = runHistoryTrim(snapshot, \"auto\").snapshot;\n persistSnapshot(snapshot);\n notify();\n return buildSendResult(snapshot, true, transition.id);\n }\n\n if (transition.to === HISTORY_TARGET) {\n const { target, history } = resolveHistoryTarget(snapshot, journey.steps);\n assertStepExists(journey.steps, target, `Transition points to unknown step \"${target}\".`);\n const visited = appendVisited(snapshot.visited, target);\n snapshot = buildSnapshot(\n target,\n nextContext,\n history,\n snapshot.status,\n snapshot.async,\n visited\n );\n snapshot = runHistoryTrim(snapshot, \"auto\").snapshot;\n persistSnapshot(snapshot);\n notify();\n return buildSendResult(snapshot, true, transition.id);\n }\n\n const resolvedTarget = transition.to;\n\n assertStepExists(\n journey.steps,\n resolvedTarget,\n `Transition points to unknown step \"${resolvedTarget}\".`\n );\n\n const nextSnapshot = transitionSnapshot(snapshot, resolvedTarget, nextContext);\n snapshot = runHistoryTrim(nextSnapshot, \"auto\").snapshot;\n persistSnapshot(snapshot);\n notify();\n\n return buildSendResult(snapshot, true, transition.id);\n };\n\n const resultPromise = sendQueue.then(run, run);\n sendQueue = resultPromise.then(\n () => undefined,\n () => undefined\n );\n return resultPromise;\n }\n };\n};\n"],
|
|
5
|
-
"mappings": "AAAO,IAAMA,EAAmB,CAC9B,SAAU,WACV,MAAO,OACT,EAIaC,EAAiB,CAC5B,QAAS,UACT,SAAU,WACV,OAAQ,QACV,EAIaC,EAAiB,cAC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["
|
|
3
|
+
"sources": ["../src/types/journey.types.ts", "../src/machine-helpers.ts", "../src/persistence.ts", "../src/machine.ts", "../src/transitions.ts"],
|
|
4
|
+
"sourcesContent": ["import type { JourneyPersistenceOptions } from \"./persistence.types\";\nimport type { JourneyTransition } from \"./transitions.types\";\n\nexport type JourneyTerminal = \"COMPLETE\" | \"TERMINATED\";\n\nexport const JOURNEY_STATUS = {\n RUNNING: \"running\",\n COMPLETE: \"complete\",\n TERMINATED: \"terminated\"\n} as const;\n\nexport type JourneyStatus = (typeof JOURNEY_STATUS)[keyof typeof JOURNEY_STATUS];\n\nexport const JOURNEY_WILDCARD = \"*\" as const;\n\nexport const JOURNEY_EVENT = {\n GO_TO_STEP_BY_ID: \"goToStepById\"\n} as const;\n\nexport type JourneyBuiltInEvent = (typeof JOURNEY_EVENT)[keyof typeof JOURNEY_EVENT];\nexport type JourneyBuiltInFrom = typeof JOURNEY_WILDCARD;\nexport type JourneyDefaultEventType =\n | \"goToNextStep\"\n | \"goToPreviousStep\"\n | \"terminateJourney\"\n | \"completeJourney\";\n\nexport const JOURNEY_ASYNC_PHASE = {\n IDLE: \"idle\",\n EVALUATING_WHEN: \"evaluating-when\",\n RUNNING_EFFECT: \"running-effect\",\n ERROR: \"error\"\n} as const;\n\nexport type JourneyAsyncPhase = (typeof JOURNEY_ASYNC_PHASE)[keyof typeof JOURNEY_ASYNC_PHASE];\n\nexport type JourneyStepAsyncState = {\n phase: JourneyAsyncPhase;\n eventType: string | null;\n transitionId: string | null;\n error: unknown | null;\n};\n\nexport type JourneyAsyncState<TStepId extends string> = {\n isLoading: boolean;\n byStep: Record<TStepId, JourneyStepAsyncState>;\n};\n\nexport type JourneyBaseEvent = {\n type: string;\n payload?: unknown;\n};\n\nexport type JourneyEventPayloadMap<TEventType extends string> = Partial<\n Record<TEventType | JourneyBuiltInEvent, unknown>\n>;\n\nexport type JourneyPayloadFor<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TEvent extends TEventType | JourneyBuiltInEvent\n> = TEvent extends keyof TPayloadMap ? TPayloadMap[TEvent] : unknown;\n\ntype JourneyPayloadForDefaultEvent<\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TDefaultEvent extends JourneyDefaultEventType\n> = JourneyPayloadFor<\n TEventType | TDefaultEvent,\n TPayloadMap & JourneyEventPayloadMap<TDefaultEvent>,\n TDefaultEvent\n>;\n\nexport type JourneyGoToEvent<TStepId extends string, TPayload = unknown> = {\n type: (typeof JOURNEY_EVENT)[\"GO_TO_STEP_BY_ID\"];\n stepId: TStepId;\n payload?: TPayload;\n};\n\nexport type JourneyEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>\n> =\n | JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<TEventType, TPayloadMap, (typeof JOURNEY_EVENT)[\"GO_TO_STEP_BY_ID\"]>\n >\n | {\n [TType in TEventType]: {\n type: TType;\n payload?: JourneyPayloadFor<TEventType, TPayloadMap, TType>;\n };\n }[TEventType];\n\nexport type JourneyStepDefinition<TStepMeta = unknown> = {\n meta?: TStepMeta;\n} & Record<string, unknown>;\n\nexport type JourneySnapshot<TContext, TStepId extends string, TStepMeta = unknown> = {\n currentStepId: TStepId;\n history: {\n timeline: readonly TStepId[];\n index: number;\n };\n context: TContext;\n visited: Record<TStepId, boolean>;\n stepMeta: Record<TStepId, TStepMeta>;\n status: JourneyStatus;\n async: JourneyAsyncState<TStepId>;\n};\n\nexport type JourneyDefinition<\n TContext,\n TStepId extends string = string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n> = {\n initial: TStepId;\n context: TContext;\n steps: Record<TStepId, JourneyStepDefinition<TStepMeta>>;\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[];\n};\n\nexport type JourneyMachineOptions<TContext, TStepId extends string, TStepMeta = unknown> = {\n persistence?: JourneyPersistenceOptions<TContext, TStepId, TStepMeta>;\n};\n\nexport type JourneySendResult<TContext, TStepId extends string, TStepMeta = unknown> = {\n transitioned: boolean;\n transitionId?: string;\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;\n};\n\nexport type JourneyObservationEvent<\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n> =\n | {\n type: \"transition.start\";\n from: TStepId;\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>;\n timestamp: number;\n }\n | {\n type: \"transition.success\";\n from: TStepId;\n to: TStepId | JourneyTerminal;\n eventType: string;\n transitionId: string | null;\n timestamp: number;\n }\n | {\n type: \"transition.error\";\n from: TStepId;\n eventType: string;\n transitionId: string | null;\n error: unknown;\n timestamp: number;\n }\n | {\n type: \"step.exit\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"step.enter\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"journey.complete\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"journey.close\";\n stepId: TStepId;\n timestamp: number;\n }\n | {\n type: \"navigation.previous\";\n from: TStepId;\n to: TStepId;\n requestedSteps: number;\n appliedSteps: number;\n timestamp: number;\n }\n | {\n type: \"navigation.lastVisited\";\n from: TStepId;\n to: TStepId;\n timestamp: number;\n }\n | {\n type: \"metadata.updated\";\n stepId: TStepId;\n previous: TStepMeta;\n next: TStepMeta;\n timestamp: number;\n };\n\nexport type JourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n> = {\n getSnapshot: () => JourneySnapshot<TContext, TStepId, TStepMeta>;\n send: (\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToNextStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n terminateJourney: (\n payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, \"terminateJourney\">\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n completeJourney: (\n payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, \"completeJourney\">\n ) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToPreviousStep: (steps?: number) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n goToLastVisitedStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;\n updateContext: (\n updater: (context: TContext) => TContext\n ) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n updateStepMetadata: (\n stepId: TStepId,\n updater: (metadata: TStepMeta) => TStepMeta\n ) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n clearStepError: (stepId?: TStepId) => JourneySnapshot<TContext, TStepId, TStepMeta>;\n resetMachine: () => JourneySnapshot<TContext, TStepId, TStepMeta>;\n subscribe: (listener: () => void) => () => void;\n subscribeEvent: (\n listener: (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => void\n ) => () => void;\n};\n", "import { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_WILDCARD } from \"./types\";\nimport type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyEventPayloadMap,\n JourneyGoToEvent,\n JourneyPayloadFor,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransition\n} from \"./types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nexport const normalizeStepCount = (steps?: number): number => {\n if (typeof steps !== \"number\" || !Number.isFinite(steps)) {\n return 1;\n }\n return Math.max(1, Math.trunc(steps));\n};\n\nexport const now = (): number => Date.now();\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nconst normalizeVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n stepIds: readonly TStepId[]\n): Record<TStepId, boolean> =>\n Object.fromEntries(stepIds.map((stepId) => [stepId, visited[stepId] === true])) as Record<\n TStepId,\n boolean\n >;\n\nexport const buildVisitedFromTimeline = <TStepId extends string>(\n timeline: readonly TStepId[],\n stepIds?: readonly TStepId[]\n): Record<TStepId, boolean> => {\n const resolvedStepIds = stepIds ?? unique(timeline);\n const visited = Object.fromEntries(resolvedStepIds.map((stepId) => [stepId, false])) as Record<\n TStepId,\n boolean\n >;\n\n for (const stepId of timeline) {\n visited[stepId] = true;\n }\n\n return visited;\n};\n\nexport const appendVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n current: TStepId\n): Record<TStepId, boolean> => ({\n ...visited,\n [current]: true\n});\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: JOURNEY_ASYNC_PHASE.IDLE,\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToStepByIdEvent = <\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>\n): event is JourneyGoToEvent<\n TStepId,\n JourneyPayloadFor<TEventType, TPayloadMap, (typeof JOURNEY_EVENT)[\"GO_TO_STEP_BY_ID\"]>\n> => event.type === JOURNEY_EVENT.GO_TO_STEP_BY_ID && \"stepId\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal\n): target is JourneyTerminal => target === \"COMPLETE\" || target === \"TERMINATED\";\n\nexport const validateJourneyTransitions = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[],\n steps: Record<TStepId, unknown>\n) => {\n const stepRegistry = steps as Record<string, unknown>;\n\n for (const [index, transition] of transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (transition.from !== JOURNEY_WILDCARD && !(transition.from in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n if (transition.event === \"completeJourney\" || transition.event === \"terminateJourney\") {\n if (\"to\" in transition && transition.to !== undefined) {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" cannot define \"to\".`\n );\n }\n continue;\n }\n\n if (typeof transition.to !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" must define string \"to\".`\n );\n }\n\n if (!isTerminalTarget(transition.to) && !(transition.to in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n};\n\nexport const buildSendResult = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n transitioned: boolean,\n transitionId?: string\n): JourneySendResult<TContext, TStepId, TStepMeta> =>\n transitionId ? { transitioned, transitionId, snapshot } : { transitioned, snapshot };\n\nexport const buildSnapshot = <TContext, TStepId extends string, TStepMeta>(\n timeline: readonly TStepId[],\n index: number,\n context: TContext,\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n stepMeta: Record<TStepId, TStepMeta>,\n visited?: Record<TStepId, boolean>\n): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n if (timeline.length === 0) {\n throw new Error(\"Journey timeline cannot be empty.\");\n }\n const safeIndex = Math.max(0, Math.min(Math.trunc(index), timeline.length - 1));\n const currentStepId = timeline[safeIndex] as TStepId;\n const stepIds = Object.keys(stepMeta) as TStepId[];\n return {\n status,\n currentStepId,\n history: {\n timeline: [...timeline],\n index: safeIndex\n },\n context,\n visited: visited\n ? normalizeVisited(visited, stepIds)\n : buildVisitedFromTimeline(timeline, stepIds),\n stepMeta: { ...stepMeta },\n async: asyncState\n };\n};\n\nexport const selectTransition = async <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TStepMeta\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[],\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n event: JourneyEvent<TStepId, TEventType, TPayloadMap>,\n hooks?: {\n onAsyncGuardStart?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardSuccess?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n ) => void;\n onAsyncGuardError?: (\n transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>,\n error: unknown\n ) => void;\n }\n): Promise<JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> | null> => {\n for (const transition of transitions) {\n const fromMatches =\n transition.from === JOURNEY_WILDCARD || transition.from === snapshot.currentStepId;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n const guardResult = transition.when({\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event\n });\n const asyncGuard = isPromiseLike(guardResult);\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n }\n\n let allowed: boolean;\n try {\n allowed = await guardResult;\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n const baseTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n let nextTimeline = baseTimeline;\n if (nextCurrent !== snapshot.currentStepId) {\n nextTimeline = [...baseTimeline, nextCurrent];\n }\n\n const nextIndex = nextTimeline.length - 1;\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(\n nextTimeline,\n nextIndex,\n nextContext,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n visited\n );\n};\n", "import { JOURNEY_STATUS } from \"./types/journey.types\";\nimport type {\n JourneyPersistedSnapshot,\n JourneyPersistedState,\n JourneyStorage,\n ResolvedPersistence\n} from \"./types/persistence.types\";\nimport type { JourneyMachineOptions, JourneySnapshot, JourneyStatus } from \"./types/journey.types\";\nimport { buildInitialAsyncState, buildSnapshot, buildVisitedFromTimeline } from \"./machine-helpers\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isStatusValue = (value: unknown): value is JourneyStatus =>\n value === JOURNEY_STATUS.RUNNING ||\n value === JOURNEY_STATUS.COMPLETE ||\n value === JOURNEY_STATUS.TERMINATED;\n\nconst resolveDefaultStorage = (): JourneyStorage | null => {\n const localStorageCandidate = (globalThis as { localStorage?: Partial<JourneyStorage> })\n .localStorage;\n\n if (\n !localStorageCandidate ||\n typeof localStorageCandidate.getItem !== \"function\" ||\n typeof localStorageCandidate.setItem !== \"function\" ||\n typeof localStorageCandidate.removeItem !== \"function\"\n ) {\n return null;\n }\n\n return localStorageCandidate as JourneyStorage;\n};\n\nconst resolvePersistence = <TContext, TStepId extends string, TStepMeta>(\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>[\"persistence\"]\n): ResolvedPersistence<TContext, TStepId, TStepMeta> | null => {\n if (!options) {\n return null;\n }\n\n const storage = options.storage ?? resolveDefaultStorage();\n if (!storage) {\n return null;\n }\n\n return {\n key: options.key,\n storage,\n version: options.version ?? 1,\n clearOnReset: options.clearOnReset ?? true,\n serialize: options.serialize ?? JSON.stringify,\n deserialize: options.deserialize ?? JSON.parse,\n ...(options.migrate ? { migrate: options.migrate } : {}),\n ...(options.onError ? { onError: options.onError } : {})\n };\n};\n\nconst coercePersistedSnapshot = <TContext, TStepId extends string, TStepMeta>(\n value: unknown,\n steps: Record<TStepId, unknown>,\n fallbackContext: TContext,\n fallbackStepMeta: Record<TStepId, TStepMeta>\n): {\n snapshot: JourneyPersistedSnapshot<TContext, TStepId, TStepMeta>;\n needsRewrite: boolean;\n} | null => {\n if (!isRecord(value)) {\n return null;\n }\n\n let needsRewrite = false;\n\n const rawHistory = isRecord(value.history) ? value.history : null;\n if (!rawHistory) {\n needsRewrite = true;\n }\n\n const rawTimeline = rawHistory?.timeline ?? value.timeline;\n const timeline = Array.isArray(rawTimeline)\n ? (rawTimeline.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[])\n : [];\n\n const currentStepIdValue =\n typeof value.currentStepId === \"string\" && value.currentStepId in steps\n ? (value.currentStepId as TStepId)\n : typeof value.current === \"string\" && value.current in steps\n ? (value.current as TStepId)\n : null;\n\n if (timeline.length === 0) {\n if (!currentStepIdValue) {\n return null;\n }\n timeline.push(currentStepIdValue);\n needsRewrite = true;\n }\n\n let index = timeline.length - 1;\n const rawIndex = rawHistory?.index ?? value.index;\n if (typeof rawIndex === \"number\" && Number.isFinite(rawIndex)) {\n index = Math.max(0, Math.min(Math.trunc(rawIndex), timeline.length - 1));\n if (index !== rawIndex) {\n needsRewrite = true;\n }\n } else if (currentStepIdValue) {\n const inferredIndex = timeline.lastIndexOf(currentStepIdValue);\n if (inferredIndex >= 0) {\n index = inferredIndex;\n needsRewrite = true;\n }\n }\n\n const status = isStatusValue(value.status) ? value.status : JOURNEY_STATUS.RUNNING;\n if (!isStatusValue(value.status)) {\n needsRewrite = true;\n }\n\n const stepIds = Object.keys(steps) as TStepId[];\n const visitedSource = value.visited;\n const visitedFromRecord = isRecord(visitedSource)\n ? (Object.fromEntries(\n stepIds.map((stepId) => [stepId, visitedSource[stepId] === true])\n ) as Record<TStepId, boolean>)\n : null;\n const visitedFromArray = Array.isArray(visitedSource)\n ? buildVisitedFromTimeline(\n visitedSource.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[],\n stepIds\n )\n : null;\n\n let visited = buildVisitedFromTimeline(timeline, stepIds);\n if (visitedFromRecord) {\n const visitedRecord = visitedSource as Record<string, unknown>;\n visited = visitedFromRecord;\n const hasMissingOrInvalidStep = stepIds.some(\n (stepId) => typeof visitedRecord[stepId] !== \"boolean\"\n );\n if (hasMissingOrInvalidStep) {\n needsRewrite = true;\n }\n } else if (visitedFromArray) {\n visited = visitedFromArray;\n needsRewrite = true;\n } else {\n needsRewrite = true;\n }\n\n const rawStepMeta = isRecord(value.stepMeta) ? value.stepMeta : null;\n if (!rawStepMeta) {\n needsRewrite = true;\n }\n\n const stepMeta = Object.fromEntries(\n Object.keys(steps).map((stepId) => {\n const typedStepId = stepId as TStepId;\n const rawValue = rawStepMeta ? rawStepMeta[stepId] : undefined;\n if (rawValue === undefined) {\n return [typedStepId, fallbackStepMeta[typedStepId]];\n }\n return [typedStepId, rawValue as TStepMeta];\n })\n ) as Record<TStepId, TStepMeta>;\n\n return {\n snapshot: {\n currentStepId: timeline[index] as TStepId,\n history: {\n timeline,\n index\n },\n context: (\"context\" in value ? value.context : fallbackContext) as TContext,\n status,\n visited,\n stepMeta\n },\n needsRewrite\n };\n};\n\n/**\n * Creates a persistence controller for snapshots, including hydration,\n * serialization, and storage error handling.\n */\nexport const createPersistenceController = <TContext, TStepId extends string, TStepMeta>(args: {\n initial: TStepId;\n context: TContext;\n stepMeta: Record<TStepId, TStepMeta>;\n steps: Record<TStepId, unknown>;\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>;\n}) => {\n const { initial, context, stepMeta, steps, options } = args;\n const persistence = resolvePersistence(options?.persistence);\n\n const reportPersistenceError = (error: unknown) => {\n persistence?.onError?.(error);\n };\n\n const persistSnapshot = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n if (!persistence) {\n return;\n }\n\n try {\n const persistedState: JourneyPersistedState<TContext, TStepId, TStepMeta> = {\n version: persistence.version,\n snapshot: {\n currentStepId: snapshot.currentStepId,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: snapshot.context,\n status: snapshot.status,\n visited: { ...snapshot.visited },\n stepMeta: { ...snapshot.stepMeta }\n }\n };\n persistence.storage.setItem(persistence.key, persistence.serialize(persistedState));\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const removePersistedSnapshot = () => {\n if (!persistence) {\n return;\n }\n\n try {\n persistence.storage.removeItem(persistence.key);\n } catch (error) {\n reportPersistenceError(error);\n }\n };\n\n const hydrateSnapshot = (): JourneySnapshot<TContext, TStepId, TStepMeta> => {\n const initialSnapshot = buildSnapshot(\n [initial],\n 0,\n context,\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(steps),\n stepMeta\n );\n if (!persistence) {\n return initialSnapshot;\n }\n\n try {\n const rawPersisted = persistence.storage.getItem(persistence.key);\n if (!rawPersisted) {\n return initialSnapshot;\n }\n\n const parsed = persistence.deserialize(rawPersisted);\n if (!isRecord(parsed)) {\n return initialSnapshot;\n }\n\n const persistedVersion = parsed.version;\n if (typeof persistedVersion !== \"number\") {\n return initialSnapshot;\n }\n\n let persistedSnapshot: JourneyPersistedSnapshot<TContext, TStepId, TStepMeta> | null = null;\n let shouldRewritePersisted = false;\n\n if (persistedVersion === persistence.version) {\n const coerced = coercePersistedSnapshot(parsed.snapshot, steps, context, stepMeta);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = Boolean(coerced?.needsRewrite);\n } else if (persistence.migrate) {\n const migrated = persistence.migrate(parsed.snapshot, persistedVersion);\n const coerced = coercePersistedSnapshot(migrated, steps, context, stepMeta);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = persistedSnapshot !== null;\n }\n\n if (!persistedSnapshot) {\n return initialSnapshot;\n }\n\n const hydratedSnapshot = buildSnapshot(\n persistedSnapshot.history.timeline,\n persistedSnapshot.history.index,\n persistedSnapshot.context,\n persistedSnapshot.status,\n buildInitialAsyncState(steps),\n persistedSnapshot.stepMeta,\n persistedSnapshot.visited\n );\n\n if (shouldRewritePersisted) {\n persistSnapshot(hydratedSnapshot);\n }\n\n return hydratedSnapshot;\n } catch (error) {\n reportPersistenceError(error);\n return initialSnapshot;\n }\n };\n\n return {\n clearOnReset: persistence?.clearOnReset ?? true,\n hydrateSnapshot,\n persistSnapshot,\n removePersistedSnapshot\n };\n};\n", "import { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_STATUS } from \"./types\";\nimport type {\n JourneyAsyncState,\n JourneyAsyncPhase,\n JourneyDefaultEventType,\n JourneyDefinition,\n JourneyEventPayloadMap,\n JourneyMachine,\n JourneyMachineOptions,\n JourneyObservationEvent,\n JourneySendResult,\n JourneyStepDefinition,\n JourneyTransition,\n JourneyTerminal\n} from \"./types\";\nimport {\n assertStepExists,\n buildIdleStepAsyncState,\n buildInitialAsyncState,\n buildSendResult,\n buildSnapshot,\n isGoToStepByIdEvent,\n isPromiseLike,\n isTerminalTarget,\n normalizeStepCount,\n now,\n selectTransition,\n transitionSnapshot,\n validateJourneyTransitions\n} from \"./machine-helpers\";\nimport { createPersistenceController } from \"./persistence\";\n\n/**\n * Creates a journey machine from a journey definition.\n * Validates steps/transitions, hydrates persisted state (if configured),\n * and returns an API for sending events and reading snapshots.\n */\nexport function createJourneyMachine<\n TContext,\n TStepMeta = unknown,\n TSteps extends Record<string, JourneyStepDefinition<TStepMeta>> = Record<\n string,\n JourneyStepDefinition<TStepMeta>\n >,\n TPayloadMap extends JourneyEventPayloadMap<JourneyDefaultEventType> = Record<never, never>\n>(\n journey: {\n initial: Extract<keyof TSteps, string>;\n context: TContext;\n steps: TSteps;\n transitions: readonly JourneyTransition<\n TContext,\n Extract<keyof TSteps, string>,\n JourneyDefaultEventType,\n TPayloadMap\n >[];\n },\n options?: JourneyMachineOptions<TContext, Extract<keyof TSteps, string>, TStepMeta>\n): JourneyMachine<\n TContext,\n Extract<keyof TSteps, string>,\n JourneyDefaultEventType,\n TPayloadMap,\n TStepMeta\n>;\n// eslint-disable-next-line no-redeclare\nexport function createJourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>\n): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>;\n// eslint-disable-next-line no-redeclare\nexport function createJourneyMachine<\n TContext,\n TStepId extends string,\n TEventType extends string = JourneyDefaultEventType,\n TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>,\n TStepMeta = unknown\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>\n): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta> {\n if (!journey.steps || typeof journey.steps !== \"object\") {\n throw new Error(\"Journey steps must be a record object.\");\n }\n\n if (!Array.isArray(journey.transitions)) {\n throw new Error(\"Journey transitions must be an array.\");\n }\n\n assertStepExists(\n journey.steps,\n journey.initial,\n `Journey initial step \"${journey.initial}\" does not exist in steps registry.`\n );\n\n validateJourneyTransitions(journey.transitions, journey.steps);\n\n const buildStepMeta = (): Record<TStepId, TStepMeta> =>\n Object.fromEntries(\n Object.entries(journey.steps).map(([stepId, definition]) => [\n stepId,\n (definition as JourneyStepDefinition<TStepMeta>).meta as TStepMeta\n ])\n ) as Record<TStepId, TStepMeta>;\n\n const { clearOnReset, hydrateSnapshot, persistSnapshot, removePersistedSnapshot } =\n createPersistenceController({\n initial: journey.initial,\n context: journey.context,\n stepMeta: buildStepMeta(),\n steps: journey.steps,\n ...(options ? { options } : {})\n });\n\n let snapshot = hydrateSnapshot();\n snapshot = {\n ...snapshot,\n async: buildInitialAsyncState(journey.steps)\n };\n\n const listeners = new Set<() => void>();\n const eventListeners = new Set<\n (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => void\n >();\n let actionQueue: Promise<void> = Promise.resolve();\n\n const notify = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n const emit = (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => {\n for (const listener of eventListeners) {\n listener(event);\n }\n };\n\n const queue = <T>(runner: () => Promise<T>): Promise<T> => {\n const resultPromise = actionQueue.then(runner, runner);\n actionQueue = resultPromise.then(\n () => undefined,\n () => undefined\n );\n return resultPromise;\n };\n\n const isAsyncLoadingPhase = (phase: JourneyAsyncPhase): boolean =>\n phase === JOURNEY_ASYNC_PHASE.EVALUATING_WHEN || phase === JOURNEY_ASYNC_PHASE.RUNNING_EFFECT;\n\n const updateStepAsync = (\n stepId: TStepId,\n updater: (\n current: JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => {\n const current = snapshot.async.byStep[stepId] ?? buildIdleStepAsyncState();\n const next = updater(current);\n if (\n current.phase === next.phase &&\n current.eventType === next.eventType &&\n current.transitionId === next.transitionId &&\n current.error === next.error\n ) {\n return;\n }\n\n const nextByStep = {\n ...snapshot.async.byStep,\n [stepId]: next\n };\n const isLoading = Object.values(nextByStep).some((state) => isAsyncLoadingPhase(state.phase));\n snapshot = {\n ...snapshot,\n async: {\n isLoading,\n byStep: nextByStep\n }\n };\n notify();\n };\n\n const setStepLoading = (\n stepId: TStepId,\n phase: JourneyAsyncPhase,\n eventType: string,\n transitionId?: string\n ) => {\n updateStepAsync(stepId, () => ({\n phase,\n eventType,\n transitionId: transitionId ?? null,\n error: null\n }));\n };\n\n const setStepIdle = (stepId: TStepId) => {\n updateStepAsync(stepId, () => buildIdleStepAsyncState());\n };\n\n const setStepError = (\n stepId: TStepId,\n eventType: string,\n error: unknown,\n transitionId?: string\n ) => {\n updateStepAsync(stepId, () => ({\n phase: JOURNEY_ASYNC_PHASE.ERROR,\n eventType,\n transitionId: transitionId ?? null,\n error\n }));\n };\n\n const applyPreviousNavigation = (\n requestedSteps?: number,\n transitionId?: string\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const steps = normalizeStepCount(requestedSteps);\n if (snapshot.history.index === 0) {\n return buildSendResult(snapshot, false);\n }\n\n const from = snapshot.currentStepId;\n const nextIndex = Math.max(0, snapshot.history.index - steps);\n const appliedSteps = snapshot.history.index - nextIndex;\n if (appliedSteps <= 0) {\n return buildSendResult(snapshot, false);\n }\n\n emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n snapshot = buildSnapshot(\n snapshot.history.timeline,\n nextIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n snapshot.visited\n );\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"navigation.previous\",\n from,\n to: snapshot.currentStepId,\n requestedSteps: steps,\n appliedSteps,\n timestamp: now()\n });\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n return buildSendResult(snapshot, true, transitionId);\n };\n\n const applyLastVisitedNavigation = (\n transitionId?: string\n ): JourneySendResult<TContext, TStepId, TStepMeta> => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const targetIndex = snapshot.history.timeline.length - 1;\n if (snapshot.history.index >= targetIndex) {\n return buildSendResult(snapshot, false);\n }\n\n const from = snapshot.currentStepId;\n emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n snapshot = buildSnapshot(\n snapshot.history.timeline,\n targetIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.stepMeta,\n snapshot.visited\n );\n persistSnapshot(snapshot);\n notify();\n\n emit({ type: \"navigation.lastVisited\", from, to: snapshot.currentStepId, timestamp: now() });\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n return buildSendResult(snapshot, true, transitionId);\n };\n\n const machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta> = {\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n subscribeEvent: (listener) => {\n eventListeners.add(listener);\n return () => {\n eventListeners.delete(listener);\n };\n },\n resetMachine: () => {\n snapshot = buildSnapshot(\n [journey.initial],\n 0,\n journey.context,\n JOURNEY_STATUS.RUNNING,\n buildInitialAsyncState(journey.steps),\n buildStepMeta()\n );\n if (clearOnReset) {\n removePersistedSnapshot();\n } else {\n persistSnapshot(snapshot);\n }\n notify();\n return snapshot;\n },\n updateContext: (updater) => {\n snapshot = {\n ...snapshot,\n context: updater(snapshot.context)\n };\n persistSnapshot(snapshot);\n notify();\n return snapshot;\n },\n updateStepMetadata: (stepId, updater) => {\n if (!(stepId in journey.steps)) {\n return snapshot;\n }\n\n const previousMeta = snapshot.stepMeta[stepId];\n const nextMeta = updater(previousMeta);\n if (Object.is(previousMeta, nextMeta)) {\n return snapshot;\n }\n\n snapshot = {\n ...snapshot,\n stepMeta: {\n ...snapshot.stepMeta,\n [stepId]: nextMeta\n }\n };\n persistSnapshot(snapshot);\n notify();\n emit({\n type: \"metadata.updated\",\n stepId,\n previous: previousMeta,\n next: nextMeta,\n timestamp: now()\n });\n return snapshot;\n },\n clearStepError: (stepId) => {\n const resolvedStep = stepId ?? snapshot.currentStepId;\n if (!(resolvedStep in journey.steps)) {\n return snapshot;\n }\n\n setStepIdle(resolvedStep);\n return snapshot;\n },\n goToPreviousStep: (steps) =>\n queue(async () => {\n const result = applyPreviousNavigation(steps, \"goToPreviousStep\");\n return result;\n }),\n goToLastVisitedStep: () =>\n queue(async () => {\n const result = applyLastVisitedNavigation(\"goToLastVisitedStep\");\n return result;\n }),\n goToNextStep: () =>\n machine.send({ type: \"goToNextStep\" } as Extract<\n Parameters<typeof machine.send>[0],\n { type: \"goToNextStep\" }\n >),\n terminateJourney: (payload) =>\n machine.send(\n (payload === undefined\n ? ({ type: \"terminateJourney\" } as unknown)\n : ({ type: \"terminateJourney\", payload } as unknown)) as Extract<\n Parameters<typeof machine.send>[0],\n { type: \"terminateJourney\" }\n >\n ),\n completeJourney: (payload) =>\n machine.send(\n (payload === undefined\n ? ({ type: \"completeJourney\" } as unknown)\n : ({ type: \"completeJourney\", payload } as unknown)) as Extract<\n Parameters<typeof machine.send>[0],\n { type: \"completeJourney\" }\n >\n ),\n send: (event) =>\n queue(async () => {\n if (snapshot.status !== JOURNEY_STATUS.RUNNING) {\n return buildSendResult(snapshot, false);\n }\n\n const fromStep = snapshot.currentStepId;\n\n if (isGoToStepByIdEvent(event)) {\n assertStepExists(\n journey.steps,\n event.stepId,\n `Cannot goToStepById unknown step \"${event.stepId}\".`\n );\n emit({ type: \"transition.start\", from: fromStep, event, timestamp: now() });\n setStepIdle(fromStep);\n\n const beforeCurrent = snapshot.currentStepId;\n const nextSnapshot = transitionSnapshot(snapshot, event.stepId, snapshot.context);\n if (nextSnapshot.currentStepId !== beforeCurrent) {\n emit({ type: \"step.exit\", stepId: beforeCurrent, timestamp: now() });\n }\n\n snapshot = nextSnapshot;\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: snapshot.currentStepId,\n eventType: JOURNEY_EVENT.GO_TO_STEP_BY_ID,\n transitionId: JOURNEY_EVENT.GO_TO_STEP_BY_ID,\n timestamp: now()\n });\n\n if (nextSnapshot.currentStepId !== beforeCurrent) {\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n }\n\n return buildSendResult(snapshot, true, JOURNEY_EVENT.GO_TO_STEP_BY_ID);\n }\n\n emit({ type: \"transition.start\", from: fromStep, event, timestamp: now() });\n\n let transition;\n try {\n transition = await selectTransition(journey.transitions, snapshot, event, {\n onAsyncGuardStart: (currentTransition) => {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.EVALUATING_WHEN,\n event.type,\n currentTransition.id\n );\n },\n onAsyncGuardSuccess: () => {\n setStepIdle(fromStep);\n },\n onAsyncGuardError: (currentTransition, error) => {\n setStepError(fromStep, event.type, error, currentTransition.id);\n }\n });\n } catch (error) {\n setStepError(fromStep, event.type, error);\n emit({\n type: \"transition.error\",\n from: fromStep,\n eventType: event.type,\n transitionId: null,\n error,\n timestamp: now()\n });\n throw error;\n }\n\n if (!transition) {\n if (event.type === \"goToPreviousStep\" || event.type === \"back\") {\n const fallbackResult = applyPreviousNavigation(1, event.type);\n if (fallbackResult.transitioned) {\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: fallbackResult.snapshot.currentStepId,\n eventType: event.type,\n transitionId: null,\n timestamp: now()\n });\n }\n return fallbackResult;\n }\n\n return buildSendResult(snapshot, false);\n }\n\n let nextContext = snapshot.context;\n if (transition.effect) {\n const effectResultPromise = transition.effect({\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event\n });\n if (isPromiseLike(effectResultPromise)) {\n setStepLoading(\n fromStep,\n JOURNEY_ASYNC_PHASE.RUNNING_EFFECT,\n event.type as string,\n transition.id\n );\n }\n\n let effectResult: TContext | void;\n try {\n effectResult = await effectResultPromise;\n } catch (error) {\n setStepError(fromStep, event.type, error, transition.id);\n emit({\n type: \"transition.error\",\n from: fromStep,\n eventType: event.type,\n transitionId: transition.id ?? null,\n error,\n timestamp: now()\n });\n throw error;\n }\n\n if (effectResult !== undefined) {\n nextContext = effectResult;\n }\n }\n\n setStepIdle(fromStep);\n\n const target: TStepId | JourneyTerminal =\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : (transition.to as TStepId | JourneyTerminal);\n\n if (isTerminalTarget(target)) {\n const normalizedTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n snapshot = {\n ...snapshot,\n history: {\n timeline: normalizedTimeline,\n index: normalizedTimeline.length - 1\n },\n context: nextContext,\n status: target === \"COMPLETE\" ? JOURNEY_STATUS.COMPLETE : JOURNEY_STATUS.TERMINATED\n };\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: target,\n eventType: event.type,\n transitionId: transition.id ?? null,\n timestamp: now()\n });\n emit({\n type: target === \"COMPLETE\" ? \"journey.complete\" : \"journey.close\",\n stepId: snapshot.currentStepId,\n timestamp: now()\n });\n\n return buildSendResult(snapshot, true, transition.id);\n }\n\n const resolvedTarget = target;\n\n assertStepExists(\n journey.steps,\n resolvedTarget,\n `Transition points to unknown step \"${resolvedTarget}\".`\n );\n\n const beforeCurrent = snapshot.currentStepId;\n if (beforeCurrent !== resolvedTarget) {\n emit({ type: \"step.exit\", stepId: beforeCurrent, timestamp: now() });\n }\n snapshot = transitionSnapshot(snapshot, resolvedTarget, nextContext);\n persistSnapshot(snapshot);\n notify();\n\n emit({\n type: \"transition.success\",\n from: fromStep,\n to: snapshot.currentStepId,\n eventType: event.type,\n transitionId: transition.id ?? null,\n timestamp: now()\n });\n if (beforeCurrent !== snapshot.currentStepId) {\n emit({ type: \"step.enter\", stepId: snapshot.currentStepId, timestamp: now() });\n }\n\n return buildSendResult(snapshot, true, transition.id);\n })\n };\n\n return machine;\n}\n", "import { JOURNEY_WILDCARD } from \"./types/journey.types\";\nimport type { JourneyEventPayloadMap } from \"./types/journey.types\";\nimport type {\n EventBuilder,\n JourneyEventTransition,\n JourneyTransition,\n JourneyTransitionArgs,\n JourneyTransitionTarget,\n TransitionBranch,\n TransitionConfig\n} from \"./types/transitions.types\";\n\nconst createEventBuilder = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n from: TStepId | typeof JOURNEY_WILDCARD,\n event: TEventType\n): EventBuilder<TContext, TStepId, TEventType, TPayloadMap> => {\n if (event === \"completeJourney\") {\n return {\n complete: (\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Extract<TEventType, \"completeJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n }\n\n if (event === \"terminateJourney\") {\n return {\n terminate: (\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Extract<TEventType, \"terminateJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n }\n\n return {\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> =>\n ({\n ...config,\n from,\n event: event as Exclude<TEventType, \"completeJourney\" | \"terminateJourney\">,\n to\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>,\n choose: (\n ...branches: Array<TransitionBranch<TContext, TStepId, TEventType, TPayloadMap>>\n ): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[] =>\n branches.map(\n (branch) =>\n ({\n ...branch,\n from,\n event: event as Exclude<TEventType, \"completeJourney\" | \"terminateJourney\">\n }) as JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n )\n } as EventBuilder<TContext, TStepId, TEventType, TPayloadMap>;\n};\n\nconst buildTerminalTransition = <\n TContext,\n TStepId extends string,\n TEventType extends \"completeJourney\" | \"terminateJourney\"\n>(\n from: TStepId | typeof JOURNEY_WILDCARD,\n event: TEventType,\n config: TransitionConfig<TContext, TStepId, TEventType, Record<never, never>> = {}\n): JourneyEventTransition<TContext, TStepId, TEventType, Record<never, never>> =>\n ({\n ...config,\n from,\n event\n }) as JourneyEventTransition<TContext, TStepId, TEventType, Record<never, never>>;\n\nexport const tx = {\n from: <TStepId extends string, TContext = unknown>(from: TStepId) => ({\n on: <TEventType extends string>(event: TEventType) =>\n createEventBuilder<TContext, TStepId, TEventType, Record<never, never>>(from, event),\n toComplete: (\n config: TransitionConfig<TContext, TStepId, \"completeJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(from, \"completeJourney\", config),\n toTerminate: (\n config: TransitionConfig<TContext, TStepId, \"terminateJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(from, \"terminateJourney\", config)\n }),\n any: <TContext = unknown, TStepId extends string = string>() => ({\n on: <TEventType extends string>(event: TEventType) =>\n createEventBuilder<TContext, TStepId, TEventType, Record<never, never>>(\n JOURNEY_WILDCARD,\n event\n ),\n toComplete: (\n config: TransitionConfig<TContext, TStepId, \"completeJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(JOURNEY_WILDCARD, \"completeJourney\", config),\n toTerminate: (\n config: TransitionConfig<TContext, TStepId, \"terminateJourney\", Record<never, never>> = {}\n ) => buildTerminalTransition(JOURNEY_WILDCARD, \"terminateJourney\", config)\n }),\n when: <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n >(\n predicate: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>\n ) => boolean | Promise<boolean>\n ) => ({\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): TransitionBranch<TContext, TStepId, TEventType, TPayloadMap> => ({\n ...config,\n to,\n when: predicate\n })\n }),\n otherwise: <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n >() => ({\n to: (\n to: JourneyTransitionTarget<TStepId>,\n config: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap> = {}\n ): TransitionBranch<TContext, TStepId, TEventType, TPayloadMap> => ({\n ...config,\n to\n })\n })\n};\n\nexport const createTransitions = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>\n>(\n ...items: Array<\n | JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>\n | readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[]\n >\n): JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[] =>\n items.flatMap((item) => (Array.isArray(item) ? [...item] : [item]));\n"],
|
|
5
|
+
"mappings": "AAKO,IAAMA,EAAiB,CAC5B,QAAS,UACT,SAAU,WACV,WAAY,YACd,EAIaC,EAAmB,IAEnBC,EAAgB,CAC3B,iBAAkB,cACpB,EAUaC,EAAsB,CACjC,KAAM,OACN,gBAAiB,kBACjB,eAAgB,iBAChB,MAAO,OACT,ECjBO,IAAMC,EAAmB,CAC9BC,EACAC,EACAC,IACG,CACH,GAAI,EAAED,KAAUD,GACd,MAAM,IAAI,MAAME,CAAO,CAE3B,EAEaC,EAAsBH,GAC7B,OAAOA,GAAU,UAAY,CAAC,OAAO,SAASA,CAAK,EAC9C,EAEF,KAAK,IAAI,EAAG,KAAK,MAAMA,CAAK,CAAC,EAGzBI,EAAM,IAAc,KAAK,IAAI,EAEpCC,GAAaC,GAA6B,CAAC,GAAG,IAAI,IAAIA,CAAK,C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AOC,EACP,GAAAE,CACF,GACF,OAAQ,IACHC,IAEHA,EAAS,IACNC,IACE,CACC,GAAGA,EACH,KAAAL,EACA,MAAOC,CACT,EACJ,CACJ,EAGIK,EAA0B,CAK9BN,EACAC,EACAC,EAAgF,CAAC,KAEhF,CACC,GAAGA,EACH,KAAAF,EACA,MAAAC,CACF,GAEWM,GAAK,CAChB,KAAmDP,IAAmB,CACpE,GAAgCC,GAC9BF,GAAwEC,EAAMC,CAAK,EACrF,WAAY,CACVC,EAAuF,CAAC,IACrFI,EAAwBN,EAAM,kBAAmBE,CAAM,EAC5D,YAAa,CACXA,EAAwF,CAAC,IACtFI,EAAwBN,EAAM,mBAAoBE,CAAM,CAC/D,GACA,IAAK,KAA4D,CAC/D,GAAgCD,GAC9BF,GACES,EACAP,CACF,EACF,WAAY,CACVC,EAAuF,CAAC,IACrFI,EAAwBE,EAAkB,kBAAmBN,CAAM,EACxE,YAAa,CACXA,EAAwF,CAAC,IACtFI,EAAwBE,EAAkB,mBAAoBN,CAAM,CAC3E,GACA,KAMEO,IAGI,CACJ,GAAI,CACFN,EACAD,EAAuE,CAAC,KACN,CAClE,GAAGA,EACH,GAAAC,EACA,KAAMM,CACR,EACF,GACA,UAAW,KAKH,CACN,GAAI,CACFN,EACAD,EAAuE,CAAC,KACN,CAClE,GAAGA,EACH,GAAAC,CACF,EACF,EACF,EAEaO,GAAoB,IAM5BC,IAKHA,EAAM,QAASC,GAAU,MAAM,QAAQA,CAAI,EAAI,CAAC,GAAGA,CAAI,EAAI,CAACA,CAAI,CAAE",
|
|
6
|
+
"names": ["JOURNEY_STATUS", "JOURNEY_WILDCARD", "JOURNEY_EVENT", "JOURNEY_ASYNC_PHASE", "assertStepExists", "steps", "stepId", "message", "normalizeStepCount", "now", "unique", "items", "normalizeVisited", "visited", "stepIds", "buildVisitedFromTimeline", "timeline", "resolvedStepIds", "appendVisited", "current", "isPromiseLike", "value", "buildIdleStepAsyncState", "JOURNEY_ASYNC_PHASE", "buildInitialAsyncState", "isGoToStepByIdEvent", "event", "JOURNEY_EVENT", "isTerminalTarget", "target", "validateJourneyTransitions", "transitions", "stepRegistry", "index", "transition", "JOURNEY_WILDCARD", "buildSendResult", "snapshot", "transitioned", "transitionId", "buildSnapshot", "context", "status", "asyncState", "stepMeta", "safeIndex", "currentStepId", "selectTransition", "hooks", "fromMatches", "eventMatches", "guardResult", "asyncGuard", "allowed", "error", "transitionSnapshot", "nextCurrent", "nextContext", "baseTimeline", "nextTimeline", "nextIndex", "isRecord", "value", "isStatusValue", "JOURNEY_STATUS", "resolveDefaultStorage", "localStorageCandidate", "resolvePersistence", "options", "storage", "coercePersistedSnapshot", "steps", "fallbackContext", "fallbackStepMeta", "needsRewrite", "rawHistory", "rawTimeline", "timeline", "step", "currentStepIdValue", "index", "rawIndex", "inferredIndex", "status", "stepIds", "visitedSource", "visitedFromRecord", "stepId", "visitedFromArray", "buildVisitedFromTimeline", "visited", "visitedRecord", "rawStepMeta", "stepMeta", "typedStepId", "rawValue", "createPersistenceController", "args", "initial", "context", "persistence", "reportPersistenceError", "error", "persistSnapshot", "snapshot", "persistedState", "removePersistedSnapshot", "hydrateSnapshot", "initialSnapshot", "buildSnapshot", "buildInitialAsyncState", "rawPersisted", "parsed", "persistedVersion", "persistedSnapshot", "shouldRewritePersisted", "coerced", "migrated", "hydratedSnapshot", "createJourneyMachine", "journey", "options", "assertStepExists", "validateJourneyTransitions", "buildStepMeta", "stepId", "definition", "clearOnReset", "hydrateSnapshot", "persistSnapshot", "removePersistedSnapshot", "createPersistenceController", "snapshot", "buildInitialAsyncState", "listeners", "eventListeners", "actionQueue", "notify", "listener", "emit", "event", "queue", "runner", "resultPromise", "isAsyncLoadingPhase", "phase", "JOURNEY_ASYNC_PHASE", "updateStepAsync", "updater", "current", "buildIdleStepAsyncState", "next", "nextByStep", "isLoading", "state", "setStepLoading", "eventType", "transitionId", "setStepIdle", "setStepError", "error", "applyPreviousNavigation", "requestedSteps", "JOURNEY_STATUS", "buildSendResult", "steps", "normalizeStepCount", "from", "nextIndex", "appliedSteps", "now", "buildSnapshot", "applyLastVisitedNavigation", "targetIndex", "machine", "previousMeta", "nextMeta", "resolvedStep", "payload", "fromStep", "isGoToStepByIdEvent", "beforeCurrent", "nextSnapshot", "transitionSnapshot", "JOURNEY_EVENT", "transition", "selectTransition", "currentTransition", "fallbackResult", "nextContext", "effectResultPromise", "isPromiseLike", "effectResult", "target", "isTerminalTarget", "normalizedTimeline", "resolvedTarget", "createEventBuilder", "from", "event", "config", "to", "branches", "branch", "buildTerminalTransition", "tx", "JOURNEY_WILDCARD", "predicate", "createTransitions", "items", "item"]
|
|
7
7
|
}
|
|
@@ -1,23 +1,21 @@
|
|
|
1
1
|
import { JOURNEY_EVENT } from "./types";
|
|
2
2
|
import type { JourneyAsyncState, JourneyEvent, JourneyEventPayloadMap, JourneyGoToEvent, JourneyPayloadFor, JourneySendResult, JourneySnapshot, JourneyStatus, JourneyStepAsyncState, JourneyTerminal, JourneyTransition } from "./types";
|
|
3
3
|
export declare const assertStepExists: <TStepId extends string>(steps: Record<TStepId, unknown>, stepId: TStepId, message: string) => void;
|
|
4
|
-
export declare const
|
|
5
|
-
export declare const
|
|
4
|
+
export declare const normalizeStepCount: (steps?: number) => number;
|
|
5
|
+
export declare const now: () => number;
|
|
6
|
+
export declare const buildVisitedFromTimeline: <TStepId extends string>(timeline: readonly TStepId[], stepIds?: readonly TStepId[]) => Record<TStepId, boolean>;
|
|
7
|
+
export declare const appendVisited: <TStepId extends string>(visited: Record<TStepId, boolean>, current: TStepId) => Record<TStepId, boolean>;
|
|
6
8
|
export declare const isPromiseLike: <T>(value: T | PromiseLike<T>) => value is PromiseLike<T>;
|
|
7
9
|
export declare const buildIdleStepAsyncState: () => JourneyStepAsyncState;
|
|
8
10
|
export declare const buildInitialAsyncState: <TStepId extends string>(steps: Record<TStepId, unknown>) => JourneyAsyncState<TStepId>;
|
|
9
|
-
export declare const
|
|
10
|
-
export declare const isTerminalTarget: <TStepId extends string>(target: TStepId | JourneyTerminal
|
|
11
|
-
export declare const
|
|
12
|
-
export declare const
|
|
13
|
-
export declare const
|
|
14
|
-
|
|
15
|
-
history: TStepId[];
|
|
16
|
-
};
|
|
17
|
-
export declare const selectTransition: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>(transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[], snapshot: JourneySnapshot<TContext, TStepId>, event: JourneyEvent<TStepId, TEventType, TPayloadMap>, hooks?: {
|
|
11
|
+
export declare const isGoToStepByIdEvent: <TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>(event: JourneyEvent<TStepId, TEventType, TPayloadMap>) => event is JourneyGoToEvent<TStepId, JourneyPayloadFor<TEventType, TPayloadMap, (typeof JOURNEY_EVENT)["GO_TO_STEP_BY_ID"]>>;
|
|
12
|
+
export declare const isTerminalTarget: <TStepId extends string>(target: TStepId | JourneyTerminal) => target is JourneyTerminal;
|
|
13
|
+
export declare const validateJourneyTransitions: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>(transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[], steps: Record<TStepId, unknown>) => void;
|
|
14
|
+
export declare const buildSendResult: <TContext, TStepId extends string, TStepMeta>(snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>, transitioned: boolean, transitionId?: string) => JourneySendResult<TContext, TStepId, TStepMeta>;
|
|
15
|
+
export declare const buildSnapshot: <TContext, TStepId extends string, TStepMeta>(timeline: readonly TStepId[], index: number, context: TContext, status: JourneyStatus, asyncState: JourneyAsyncState<TStepId>, stepMeta: Record<TStepId, TStepMeta>, visited?: Record<TStepId, boolean>) => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
16
|
+
export declare const selectTransition: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>, TStepMeta>(transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[], snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>, event: JourneyEvent<TStepId, TEventType, TPayloadMap>, hooks?: {
|
|
18
17
|
onAsyncGuardStart?: (transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>) => void;
|
|
19
18
|
onAsyncGuardSuccess?: (transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>) => void;
|
|
20
19
|
onAsyncGuardError?: (transition: JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>, error: unknown) => void;
|
|
21
20
|
}) => Promise<JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> | null>;
|
|
22
|
-
export declare const transitionSnapshot: <TContext, TStepId extends string>(snapshot: JourneySnapshot<TContext, TStepId>, nextCurrent: TStepId, nextContext: TContext) => JourneySnapshot<TContext, TStepId>;
|
|
23
|
-
//# sourceMappingURL=machine-helpers.d.ts.map
|
|
21
|
+
export declare const transitionSnapshot: <TContext, TStepId extends string, TStepMeta>(snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>, nextCurrent: TStepId, nextContext: TContext) => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
package/dist/machine.d.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JourneyDefaultEventType, JourneyDefinition, JourneyEventPayloadMap, JourneyMachine, JourneyMachineOptions, JourneyStepDefinition, JourneyTransition } from "./types";
|
|
2
2
|
/**
|
|
3
3
|
* Creates a journey machine from a journey definition.
|
|
4
4
|
* Validates steps/transitions, hydrates persisted state (if configured),
|
|
5
5
|
* and returns an API for sending events and reading snapshots.
|
|
6
6
|
*/
|
|
7
|
-
export declare
|
|
8
|
-
|
|
7
|
+
export declare function createJourneyMachine<TContext, TStepMeta = unknown, TSteps extends Record<string, JourneyStepDefinition<TStepMeta>> = Record<string, JourneyStepDefinition<TStepMeta>>, TPayloadMap extends JourneyEventPayloadMap<JourneyDefaultEventType> = Record<never, never>>(journey: {
|
|
8
|
+
initial: Extract<keyof TSteps, string>;
|
|
9
|
+
context: TContext;
|
|
10
|
+
steps: TSteps;
|
|
11
|
+
transitions: readonly JourneyTransition<TContext, Extract<keyof TSteps, string>, JourneyDefaultEventType, TPayloadMap>[];
|
|
12
|
+
}, options?: JourneyMachineOptions<TContext, Extract<keyof TSteps, string>, TStepMeta>): JourneyMachine<TContext, Extract<keyof TSteps, string>, JourneyDefaultEventType, TPayloadMap, TStepMeta>;
|
|
13
|
+
export declare function createJourneyMachine<TContext, TStepId extends string, TEventType extends string = JourneyDefaultEventType, TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>, TStepMeta = unknown>(journey: JourneyDefinition<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>, options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>): JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>;
|
package/dist/persistence.d.ts
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import type { JourneyMachineOptions, JourneySnapshot } from "./types";
|
|
1
|
+
import type { JourneyMachineOptions, JourneySnapshot } from "./types/journey.types";
|
|
2
2
|
/**
|
|
3
3
|
* Creates a persistence controller for snapshots, including hydration,
|
|
4
4
|
* serialization, and storage error handling.
|
|
5
5
|
*/
|
|
6
|
-
export declare const createPersistenceController: <TContext, TStepId extends string>(args: {
|
|
6
|
+
export declare const createPersistenceController: <TContext, TStepId extends string, TStepMeta>(args: {
|
|
7
7
|
initial: TStepId;
|
|
8
8
|
context: TContext;
|
|
9
|
+
stepMeta: Record<TStepId, TStepMeta>;
|
|
9
10
|
steps: Record<TStepId, unknown>;
|
|
10
|
-
options?: JourneyMachineOptions<TContext, TStepId>;
|
|
11
|
+
options?: JourneyMachineOptions<TContext, TStepId, TStepMeta>;
|
|
11
12
|
}) => {
|
|
12
13
|
clearOnReset: boolean;
|
|
13
|
-
hydrateSnapshot: () => JourneySnapshot<TContext, TStepId>;
|
|
14
|
-
persistSnapshot: (snapshot: JourneySnapshot<TContext, TStepId>) => void;
|
|
14
|
+
hydrateSnapshot: () => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
15
|
+
persistSnapshot: (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => void;
|
|
15
16
|
removePersistedSnapshot: () => void;
|
|
16
17
|
};
|
|
17
|
-
//# sourceMappingURL=persistence.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { JourneyEventPayloadMap } from "./types/journey.types";
|
|
2
|
+
import type { EventBuilder, JourneyEventTransition, JourneyTransition, JourneyTransitionArgs, JourneyTransitionTarget, TransitionBranch, TransitionConfig } from "./types/transitions.types";
|
|
3
|
+
export declare const tx: {
|
|
4
|
+
from: <TStepId extends string, TContext = unknown>(from: TStepId) => {
|
|
5
|
+
on: <TEventType extends string>(event: TEventType) => EventBuilder<TContext, TStepId, TEventType, Record<never, never>>;
|
|
6
|
+
toComplete: (config?: TransitionConfig<TContext, TStepId, "completeJourney", Record<never, never>>) => JourneyEventTransition<TContext, TStepId, "completeJourney", Record<never, never>>;
|
|
7
|
+
toTerminate: (config?: TransitionConfig<TContext, TStepId, "terminateJourney", Record<never, never>>) => JourneyEventTransition<TContext, TStepId, "terminateJourney", Record<never, never>>;
|
|
8
|
+
};
|
|
9
|
+
any: <TContext = unknown, TStepId extends string = string>() => {
|
|
10
|
+
on: <TEventType extends string>(event: TEventType) => EventBuilder<TContext, TStepId, TEventType, Record<never, never>>;
|
|
11
|
+
toComplete: (config?: TransitionConfig<TContext, TStepId, "completeJourney", Record<never, never>>) => JourneyEventTransition<TContext, TStepId, "completeJourney", Record<never, never>>;
|
|
12
|
+
toTerminate: (config?: TransitionConfig<TContext, TStepId, "terminateJourney", Record<never, never>>) => JourneyEventTransition<TContext, TStepId, "terminateJourney", Record<never, never>>;
|
|
13
|
+
};
|
|
14
|
+
when: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>(predicate: (args: JourneyTransitionArgs<TContext, TStepId, TEventType, TPayloadMap>) => boolean | Promise<boolean>) => {
|
|
15
|
+
to: (to: JourneyTransitionTarget<TStepId>, config?: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap>) => TransitionBranch<TContext, TStepId, TEventType, TPayloadMap>;
|
|
16
|
+
};
|
|
17
|
+
otherwise: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>() => {
|
|
18
|
+
to: (to: JourneyTransitionTarget<TStepId>, config?: TransitionConfig<TContext, TStepId, TEventType, TPayloadMap>) => TransitionBranch<TContext, TStepId, TEventType, TPayloadMap>;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
export declare const createTransitions: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>>(...items: Array<JourneyTransition<TContext, TStepId, TEventType, TPayloadMap> | readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[]>) => JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[];
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { JOURNEY_ASYNC_PHASE, JOURNEY_EVENT, JOURNEY_STATUS, JOURNEY_WILDCARD } from "./journey.types";
|
|
2
|
+
export type { JourneyAsyncPhase, JourneyAsyncState, JourneyBaseEvent, JourneyBuiltInEvent, JourneyBuiltInFrom, JourneyDefaultEventType, JourneyDefinition, JourneyEvent, JourneyEventPayloadMap, JourneyGoToEvent, JourneyMachine, JourneyMachineOptions, JourneyObservationEvent, JourneyPayloadFor, JourneySendResult, JourneySnapshot, JourneyStatus, JourneyStepAsyncState, JourneyStepDefinition, JourneyTerminal } from "./journey.types";
|
|
3
|
+
export type { JourneyEventTransition, JourneyGoToStepTransition, JourneyTransition, JourneyTransitionArgs, JourneyTransitionTarget } from "./transitions.types";
|
|
4
|
+
export type { JourneyPersistedSnapshot, JourneyPersistedState, JourneyPersistenceOptions, JourneyStorage } from "./persistence.types";
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { JourneyPersistenceOptions } from "./persistence.types";
|
|
2
|
+
import type { JourneyTransition } from "./transitions.types";
|
|
3
|
+
export type JourneyTerminal = "COMPLETE" | "TERMINATED";
|
|
4
|
+
export declare const JOURNEY_STATUS: {
|
|
5
|
+
readonly RUNNING: "running";
|
|
6
|
+
readonly COMPLETE: "complete";
|
|
7
|
+
readonly TERMINATED: "terminated";
|
|
8
|
+
};
|
|
9
|
+
export type JourneyStatus = (typeof JOURNEY_STATUS)[keyof typeof JOURNEY_STATUS];
|
|
10
|
+
export declare const JOURNEY_WILDCARD: "*";
|
|
11
|
+
export declare const JOURNEY_EVENT: {
|
|
12
|
+
readonly GO_TO_STEP_BY_ID: "goToStepById";
|
|
13
|
+
};
|
|
14
|
+
export type JourneyBuiltInEvent = (typeof JOURNEY_EVENT)[keyof typeof JOURNEY_EVENT];
|
|
15
|
+
export type JourneyBuiltInFrom = typeof JOURNEY_WILDCARD;
|
|
16
|
+
export type JourneyDefaultEventType = "goToNextStep" | "goToPreviousStep" | "terminateJourney" | "completeJourney";
|
|
17
|
+
export declare const JOURNEY_ASYNC_PHASE: {
|
|
18
|
+
readonly IDLE: "idle";
|
|
19
|
+
readonly EVALUATING_WHEN: "evaluating-when";
|
|
20
|
+
readonly RUNNING_EFFECT: "running-effect";
|
|
21
|
+
readonly ERROR: "error";
|
|
22
|
+
};
|
|
23
|
+
export type JourneyAsyncPhase = (typeof JOURNEY_ASYNC_PHASE)[keyof typeof JOURNEY_ASYNC_PHASE];
|
|
24
|
+
export type JourneyStepAsyncState = {
|
|
25
|
+
phase: JourneyAsyncPhase;
|
|
26
|
+
eventType: string | null;
|
|
27
|
+
transitionId: string | null;
|
|
28
|
+
error: unknown | null;
|
|
29
|
+
};
|
|
30
|
+
export type JourneyAsyncState<TStepId extends string> = {
|
|
31
|
+
isLoading: boolean;
|
|
32
|
+
byStep: Record<TStepId, JourneyStepAsyncState>;
|
|
33
|
+
};
|
|
34
|
+
export type JourneyBaseEvent = {
|
|
35
|
+
type: string;
|
|
36
|
+
payload?: unknown;
|
|
37
|
+
};
|
|
38
|
+
export type JourneyEventPayloadMap<TEventType extends string> = Partial<Record<TEventType | JourneyBuiltInEvent, unknown>>;
|
|
39
|
+
export type JourneyPayloadFor<TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>, TEvent extends TEventType | JourneyBuiltInEvent> = TEvent extends keyof TPayloadMap ? TPayloadMap[TEvent] : unknown;
|
|
40
|
+
type JourneyPayloadForDefaultEvent<TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>, TDefaultEvent extends JourneyDefaultEventType> = JourneyPayloadFor<TEventType | TDefaultEvent, TPayloadMap & JourneyEventPayloadMap<TDefaultEvent>, TDefaultEvent>;
|
|
41
|
+
export type JourneyGoToEvent<TStepId extends string, TPayload = unknown> = {
|
|
42
|
+
type: (typeof JOURNEY_EVENT)["GO_TO_STEP_BY_ID"];
|
|
43
|
+
stepId: TStepId;
|
|
44
|
+
payload?: TPayload;
|
|
45
|
+
};
|
|
46
|
+
export type JourneyEvent<TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>> = JourneyGoToEvent<TStepId, JourneyPayloadFor<TEventType, TPayloadMap, (typeof JOURNEY_EVENT)["GO_TO_STEP_BY_ID"]>> | {
|
|
47
|
+
[TType in TEventType]: {
|
|
48
|
+
type: TType;
|
|
49
|
+
payload?: JourneyPayloadFor<TEventType, TPayloadMap, TType>;
|
|
50
|
+
};
|
|
51
|
+
}[TEventType];
|
|
52
|
+
export type JourneyStepDefinition<TStepMeta = unknown> = {
|
|
53
|
+
meta?: TStepMeta;
|
|
54
|
+
} & Record<string, unknown>;
|
|
55
|
+
export type JourneySnapshot<TContext, TStepId extends string, TStepMeta = unknown> = {
|
|
56
|
+
currentStepId: TStepId;
|
|
57
|
+
history: {
|
|
58
|
+
timeline: readonly TStepId[];
|
|
59
|
+
index: number;
|
|
60
|
+
};
|
|
61
|
+
context: TContext;
|
|
62
|
+
visited: Record<TStepId, boolean>;
|
|
63
|
+
stepMeta: Record<TStepId, TStepMeta>;
|
|
64
|
+
status: JourneyStatus;
|
|
65
|
+
async: JourneyAsyncState<TStepId>;
|
|
66
|
+
};
|
|
67
|
+
export type JourneyDefinition<TContext, TStepId extends string = string, TEventType extends string = JourneyDefaultEventType, TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>, TStepMeta = unknown> = {
|
|
68
|
+
initial: TStepId;
|
|
69
|
+
context: TContext;
|
|
70
|
+
steps: Record<TStepId, JourneyStepDefinition<TStepMeta>>;
|
|
71
|
+
transitions: readonly JourneyTransition<TContext, TStepId, TEventType, TPayloadMap>[];
|
|
72
|
+
};
|
|
73
|
+
export type JourneyMachineOptions<TContext, TStepId extends string, TStepMeta = unknown> = {
|
|
74
|
+
persistence?: JourneyPersistenceOptions<TContext, TStepId, TStepMeta>;
|
|
75
|
+
};
|
|
76
|
+
export type JourneySendResult<TContext, TStepId extends string, TStepMeta = unknown> = {
|
|
77
|
+
transitioned: boolean;
|
|
78
|
+
transitionId?: string;
|
|
79
|
+
snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
80
|
+
};
|
|
81
|
+
export type JourneyObservationEvent<TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>, TStepMeta = unknown> = {
|
|
82
|
+
type: "transition.start";
|
|
83
|
+
from: TStepId;
|
|
84
|
+
event: JourneyEvent<TStepId, TEventType, TPayloadMap>;
|
|
85
|
+
timestamp: number;
|
|
86
|
+
} | {
|
|
87
|
+
type: "transition.success";
|
|
88
|
+
from: TStepId;
|
|
89
|
+
to: TStepId | JourneyTerminal;
|
|
90
|
+
eventType: string;
|
|
91
|
+
transitionId: string | null;
|
|
92
|
+
timestamp: number;
|
|
93
|
+
} | {
|
|
94
|
+
type: "transition.error";
|
|
95
|
+
from: TStepId;
|
|
96
|
+
eventType: string;
|
|
97
|
+
transitionId: string | null;
|
|
98
|
+
error: unknown;
|
|
99
|
+
timestamp: number;
|
|
100
|
+
} | {
|
|
101
|
+
type: "step.exit";
|
|
102
|
+
stepId: TStepId;
|
|
103
|
+
timestamp: number;
|
|
104
|
+
} | {
|
|
105
|
+
type: "step.enter";
|
|
106
|
+
stepId: TStepId;
|
|
107
|
+
timestamp: number;
|
|
108
|
+
} | {
|
|
109
|
+
type: "journey.complete";
|
|
110
|
+
stepId: TStepId;
|
|
111
|
+
timestamp: number;
|
|
112
|
+
} | {
|
|
113
|
+
type: "journey.close";
|
|
114
|
+
stepId: TStepId;
|
|
115
|
+
timestamp: number;
|
|
116
|
+
} | {
|
|
117
|
+
type: "navigation.previous";
|
|
118
|
+
from: TStepId;
|
|
119
|
+
to: TStepId;
|
|
120
|
+
requestedSteps: number;
|
|
121
|
+
appliedSteps: number;
|
|
122
|
+
timestamp: number;
|
|
123
|
+
} | {
|
|
124
|
+
type: "navigation.lastVisited";
|
|
125
|
+
from: TStepId;
|
|
126
|
+
to: TStepId;
|
|
127
|
+
timestamp: number;
|
|
128
|
+
} | {
|
|
129
|
+
type: "metadata.updated";
|
|
130
|
+
stepId: TStepId;
|
|
131
|
+
previous: TStepMeta;
|
|
132
|
+
next: TStepMeta;
|
|
133
|
+
timestamp: number;
|
|
134
|
+
};
|
|
135
|
+
export type JourneyMachine<TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType> = Record<never, never>, TStepMeta = unknown> = {
|
|
136
|
+
getSnapshot: () => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
137
|
+
send: (event: JourneyEvent<TStepId, TEventType, TPayloadMap>) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;
|
|
138
|
+
goToNextStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;
|
|
139
|
+
terminateJourney: (payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, "terminateJourney">) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;
|
|
140
|
+
completeJourney: (payload?: JourneyPayloadForDefaultEvent<TEventType, TPayloadMap, "completeJourney">) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;
|
|
141
|
+
goToPreviousStep: (steps?: number) => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;
|
|
142
|
+
goToLastVisitedStep: () => Promise<JourneySendResult<TContext, TStepId, TStepMeta>>;
|
|
143
|
+
updateContext: (updater: (context: TContext) => TContext) => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
144
|
+
updateStepMetadata: (stepId: TStepId, updater: (metadata: TStepMeta) => TStepMeta) => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
145
|
+
clearStepError: (stepId?: TStepId) => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
146
|
+
resetMachine: () => JourneySnapshot<TContext, TStepId, TStepMeta>;
|
|
147
|
+
subscribe: (listener: () => void) => () => void;
|
|
148
|
+
subscribeEvent: (listener: (event: JourneyObservationEvent<TStepId, TEventType, TPayloadMap, TStepMeta>) => void) => () => void;
|
|
149
|
+
};
|
|
150
|
+
export {};
|