awaitly 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/di-Biw_plBn.d.cts +15 -0
  2. package/dist/di-DxyH2N3i.d.ts +15 -0
  3. package/dist/durable.cjs +4670 -0
  4. package/dist/durable.cjs.map +1 -0
  5. package/dist/durable.d.cts +9 -0
  6. package/dist/durable.d.ts +9 -0
  7. package/dist/durable.js +4610 -0
  8. package/dist/durable.js.map +1 -0
  9. package/dist/{di-BbFFfO8y.d.ts → duration-BjVn3QpB.d.cts} +1 -15
  10. package/dist/{di-BDlT7InM.d.cts → duration-BjVn3QpB.d.ts} +1 -15
  11. package/dist/engine.cjs +4501 -0
  12. package/dist/engine.cjs.map +1 -0
  13. package/dist/engine.d.cts +113 -0
  14. package/dist/engine.d.ts +113 -0
  15. package/dist/engine.js +4474 -0
  16. package/dist/engine.js.map +1 -0
  17. package/dist/{errors-DtXvrCiO.d.cts → errors-sDSeaZBO.d.cts} +1 -1
  18. package/dist/{errors-DtXvrCiO.d.ts → errors-sDSeaZBO.d.ts} +1 -1
  19. package/dist/guards-CwQZro1F.d.ts +72 -0
  20. package/dist/guards-DhhOJZda.d.cts +72 -0
  21. package/dist/hitl-BnnnLzh2.d.cts +468 -0
  22. package/dist/hitl-pYfkQMv_.d.ts +468 -0
  23. package/dist/hitl.cjs +646 -0
  24. package/dist/hitl.cjs.map +1 -0
  25. package/dist/hitl.d.cts +440 -0
  26. package/dist/hitl.d.ts +440 -0
  27. package/dist/hitl.js +605 -0
  28. package/dist/hitl.js.map +1 -0
  29. package/dist/index-Bew12SZ8.d.ts +417 -0
  30. package/dist/index-Bwt-iz50.d.cts +417 -0
  31. package/dist/{types-B8NfNRGX.d.ts → index-Cv4K_3sZ.d.ts} +2 -1162
  32. package/dist/{types-BZ2f4MRR.d.cts → index-ICmfQi08.d.cts} +2 -1162
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +11 -1527
  35. package/dist/index.d.ts +11 -1527
  36. package/dist/persistence.cjs +552 -0
  37. package/dist/persistence.cjs.map +1 -0
  38. package/dist/persistence.d.cts +254 -0
  39. package/dist/persistence.d.ts +254 -0
  40. package/dist/persistence.js +499 -0
  41. package/dist/persistence.js.map +1 -0
  42. package/dist/reliability.cjs +1651 -0
  43. package/dist/reliability.cjs.map +1 -0
  44. package/dist/reliability.d.cts +1442 -0
  45. package/dist/reliability.d.ts +1442 -0
  46. package/dist/reliability.js +1589 -0
  47. package/dist/reliability.js.map +1 -0
  48. package/dist/result.d.cts +1 -1
  49. package/dist/result.d.ts +1 -1
  50. package/dist/run.cjs +2283 -0
  51. package/dist/run.cjs.map +1 -0
  52. package/dist/run.d.cts +90 -0
  53. package/dist/run.d.ts +90 -0
  54. package/dist/run.js +2247 -0
  55. package/dist/run.js.map +1 -0
  56. package/dist/saga.cjs +3699 -0
  57. package/dist/saga.cjs.map +1 -0
  58. package/dist/saga.d.cts +162 -0
  59. package/dist/saga.d.ts +162 -0
  60. package/dist/saga.js +3670 -0
  61. package/dist/saga.js.map +1 -0
  62. package/dist/store-contract-BI98VYmX.d.ts +66 -0
  63. package/dist/store-contract-C2HyR_o6.d.cts +66 -0
  64. package/dist/streaming.cjs +895 -0
  65. package/dist/streaming.cjs.map +1 -0
  66. package/dist/streaming.d.cts +594 -0
  67. package/dist/streaming.d.ts +594 -0
  68. package/dist/streaming.js +832 -0
  69. package/dist/streaming.js.map +1 -0
  70. package/dist/testing.d.cts +4 -2
  71. package/dist/testing.d.ts +4 -2
  72. package/dist/types-BDTxgKKc.d.ts +845 -0
  73. package/dist/types-C9Y71dua.d.cts +845 -0
  74. package/dist/types-d8q8iQlk.d.cts +323 -0
  75. package/dist/types-sObbY4mX.d.ts +323 -0
  76. package/dist/webhook.cjs +461 -0
  77. package/dist/webhook.cjs.map +1 -0
  78. package/dist/webhook.d.cts +497 -0
  79. package/dist/webhook.d.ts +497 -0
  80. package/dist/webhook.js +422 -0
  81. package/dist/webhook.js.map +1 -0
  82. package/dist/workflow.cjs +2 -2614
  83. package/dist/workflow.cjs.map +1 -1
  84. package/dist/workflow.d.cts +12 -3023
  85. package/dist/workflow.d.ts +12 -3023
  86. package/dist/workflow.js +2 -2535
  87. package/dist/workflow.js.map +1 -1
  88. package/package.json +46 -1
@@ -1,5 +1,4 @@
1
- import { U as UnexpectedError } from './errors-DtXvrCiO.cjs';
2
- import { StandardSchemaV1 } from '@standard-schema/spec';
1
+ import { U as UnexpectedError } from './errors-sDSeaZBO.cjs';
3
2
 
4
3
  /**
5
4
  * Bound steps for the deps-first forms: run(deps, fn) and workflow({ steps }).
@@ -1922,1163 +1921,4 @@ declare const run: typeof runFn & {
1922
1921
  }) => AsyncResult<T, E, unknown>;
1923
1922
  };
1924
1923
 
1925
- /**
1926
- * awaitly/streaming - Types
1927
- *
1928
- * Core types for Result-aware streaming in workflows.
1929
- * All stream operations return Result types, enabling typed error handling
1930
- * throughout the streaming pipeline.
1931
- */
1932
-
1933
- /** Discriminant for stream write errors */
1934
- declare const STREAM_WRITE_ERROR: "STREAM_WRITE_ERROR";
1935
- /** Discriminant for stream read errors */
1936
- declare const STREAM_READ_ERROR: "STREAM_READ_ERROR";
1937
- /** Discriminant for stream close errors */
1938
- declare const STREAM_CLOSE_ERROR: "STREAM_CLOSE_ERROR";
1939
- /** Discriminant for stream store errors */
1940
- declare const STREAM_STORE_ERROR: "STREAM_STORE_ERROR";
1941
- /** Discriminant for stream ended marker */
1942
- declare const STREAM_ENDED: "STREAM_ENDED";
1943
- /** Discriminant for stream backpressure errors */
1944
- declare const STREAM_BACKPRESSURE_ERROR: "STREAM_BACKPRESSURE_ERROR";
1945
- /**
1946
- * Error returned when a write operation fails.
1947
- */
1948
- type StreamWriteError = {
1949
- type: typeof STREAM_WRITE_ERROR;
1950
- reason: "closed" | "aborted" | "store_error";
1951
- message: string;
1952
- cause?: unknown;
1953
- };
1954
- /**
1955
- * Error returned when a read operation fails.
1956
- */
1957
- type StreamReadError = {
1958
- type: typeof STREAM_READ_ERROR;
1959
- reason: "closed" | "store_error";
1960
- message: string;
1961
- cause?: unknown;
1962
- };
1963
- /**
1964
- * Error returned when closing a stream fails.
1965
- */
1966
- type StreamCloseError = {
1967
- type: typeof STREAM_CLOSE_ERROR;
1968
- reason: "already_closed" | "store_error";
1969
- message: string;
1970
- cause?: unknown;
1971
- };
1972
- /**
1973
- * Error returned from StreamStore operations.
1974
- */
1975
- type StreamStoreError = {
1976
- type: typeof STREAM_STORE_ERROR;
1977
- reason: "read_error" | "write_error" | "metadata_error" | "close_error";
1978
- message: string;
1979
- cause?: unknown;
1980
- };
1981
- /**
1982
- * Marker indicating stream has ended (not an error, but a terminal state).
1983
- * Used as the "error" type when stream is exhausted.
1984
- */
1985
- type StreamEndedMarker = {
1986
- type: typeof STREAM_ENDED;
1987
- finalPosition: number;
1988
- };
1989
- /**
1990
- * Backpressure error when writer is paused.
1991
- */
1992
- type StreamBackpressureError = {
1993
- type: typeof STREAM_BACKPRESSURE_ERROR;
1994
- bufferedCount: number;
1995
- highWaterMark: number;
1996
- };
1997
- /**
1998
- * Union of all stream errors.
1999
- */
2000
- type StreamError = StreamWriteError | StreamReadError | StreamCloseError | StreamStoreError | StreamBackpressureError;
2001
- /**
2002
- * A single item in the stream with metadata.
2003
- */
2004
- interface StreamItem<T> {
2005
- /** The value stored in this stream item */
2006
- value: T;
2007
- /** Position in the stream (0-indexed) */
2008
- position: number;
2009
- /** Timestamp when item was written */
2010
- ts: number;
2011
- }
2012
- /**
2013
- * Metadata about a stream.
2014
- */
2015
- interface StreamMetadata {
2016
- /** Unique identifier for the stream (workflowId + namespace) */
2017
- id: string;
2018
- /** Namespace within the workflow */
2019
- namespace: string;
2020
- /** Workflow ID that owns this stream */
2021
- workflowId: string;
2022
- /** Number of items in the stream */
2023
- length: number;
2024
- /** Whether the stream has been closed */
2025
- closed: boolean;
2026
- /** Timestamp when stream was created */
2027
- createdAt: number;
2028
- /** Timestamp when stream was last written to */
2029
- lastWriteAt?: number;
2030
- /** Timestamp when stream was closed */
2031
- closedAt?: number;
2032
- }
2033
- /**
2034
- * Options for creating a writable stream.
2035
- */
2036
- interface StreamOptions {
2037
- /** Named streams (default: 'default') */
2038
- namespace?: string;
2039
- /** Backpressure threshold (default: 16) */
2040
- highWaterMark?: number;
2041
- }
2042
- /**
2043
- * Options for creating a readable stream.
2044
- */
2045
- interface StreamReadOptions {
2046
- /** Named streams (default: 'default') */
2047
- namespace?: string;
2048
- /** Resume from position (0-indexed) */
2049
- startIndex?: number;
2050
- }
2051
- /**
2052
- * Options for streamForEach operation.
2053
- */
2054
- interface StreamForEachOptions {
2055
- /** Name for the operation (used in events) */
2056
- name?: string;
2057
- /** Checkpoint after every N items (default: 1 = checkpoint each item) */
2058
- checkpointInterval?: number;
2059
- /** Maximum concurrent processors (default: 1 = sequential) */
2060
- concurrency?: number;
2061
- }
2062
- /**
2063
- * Result from streamForEach operation.
2064
- */
2065
- interface StreamForEachResult<R> {
2066
- /** Results from each processed item */
2067
- results: R[];
2068
- /** Total items processed */
2069
- processedCount: number;
2070
- /** Position of last processed item */
2071
- lastPosition: number;
2072
- }
2073
- /**
2074
- * Writable stream interface - never throws, returns Results.
2075
- *
2076
- * Use within a step to write values to a stream that can be consumed
2077
- * by readers (e.g., HTTP response streaming, AI token streaming).
2078
- *
2079
- * @template T - Type of values written to the stream
2080
- *
2081
- * @example
2082
- * ```typescript
2083
- * const writer = step.getWritable<string>({ namespace: 'ai-response' });
2084
- *
2085
- * await step(() => generateAI({
2086
- * prompt: 'Hello',
2087
- * onToken: async (token) => { await writer.write(token); }
2088
- * }), { key: 'generate' });
2089
- *
2090
- * await writer.close();
2091
- * ```
2092
- */
2093
- interface StreamWriter<T> {
2094
- /**
2095
- * Write a value to the stream.
2096
- * Returns an error if the stream is closed, aborted, or store fails.
2097
- */
2098
- write(value: T): AsyncResult<void, StreamWriteError>;
2099
- /**
2100
- * Close the stream normally.
2101
- * Signals to readers that no more data will be written.
2102
- */
2103
- close(): AsyncResult<void, StreamCloseError>;
2104
- /**
2105
- * Abort the stream with a reason.
2106
- * Use for error conditions that should terminate the stream.
2107
- */
2108
- abort(reason: unknown): void;
2109
- /** Whether the stream is still writable */
2110
- readonly writable: boolean;
2111
- /** Current write position (number of items written) */
2112
- readonly position: number;
2113
- /** Stream namespace */
2114
- readonly namespace: string;
2115
- }
2116
- /**
2117
- * Readable stream interface - returns STREAM_ENDED marker when complete.
2118
- *
2119
- * Use to consume values from a stream, with support for resuming from
2120
- * a specific position.
2121
- *
2122
- * @template T - Type of values read from the stream
2123
- *
2124
- * @example
2125
- * ```typescript
2126
- * const reader = getStreamReader<string>(runId, { namespace: 'ai-response' });
2127
- *
2128
- * let result = await reader.read();
2129
- * while (result.ok) {
2130
- * response.write(result.value);
2131
- * result = await reader.read();
2132
- * }
2133
- *
2134
- * if (result.error.type === 'STREAM_ENDED') {
2135
- * console.log('Stream complete at position', result.error.finalPosition);
2136
- * }
2137
- * ```
2138
- */
2139
- interface StreamReader<T> {
2140
- /**
2141
- * Read the next value from the stream.
2142
- * Returns StreamEndedMarker when stream is exhausted.
2143
- */
2144
- read(): AsyncResult<T, StreamReadError | StreamEndedMarker>;
2145
- /**
2146
- * Close the reader (stop consuming).
2147
- * Does not affect the underlying stream.
2148
- */
2149
- close(): void;
2150
- /** Whether there may be more data to read */
2151
- readonly readable: boolean;
2152
- /** Current read position */
2153
- readonly position: number;
2154
- /** Stream namespace */
2155
- readonly namespace: string;
2156
- }
2157
- /** Unsubscribe function returned by subscribe */
2158
- type Unsubscribe = () => void;
2159
- /**
2160
- * Storage backend for stream data.
2161
- * Follows the same patterns as persistence.ts adapters.
2162
- *
2163
- * @example In-memory store
2164
- * ```typescript
2165
- * const store = createMemoryStreamStore();
2166
- * ```
2167
- *
2168
- * @example File-based store
2169
- * ```typescript
2170
- * const store = createFileStreamStore({ directory: './streams', fs });
2171
- * ```
2172
- */
2173
- interface StreamStore {
2174
- /**
2175
- * Append an item to the stream.
2176
- */
2177
- append<T>(workflowId: string, namespace: string, item: StreamItem<T>): AsyncResult<void, StreamStoreError>;
2178
- /**
2179
- * Read items from the stream starting at an index.
2180
- * @param startIndex - Position to start reading from (0-indexed)
2181
- * @param limit - Maximum number of items to read (default: all remaining)
2182
- */
2183
- read<T>(workflowId: string, namespace: string, startIndex: number, limit?: number): AsyncResult<StreamItem<T>[], StreamStoreError>;
2184
- /**
2185
- * Get metadata about a stream.
2186
- * Returns undefined if stream doesn't exist.
2187
- */
2188
- getMetadata(workflowId: string, namespace: string): AsyncResult<StreamMetadata | undefined, StreamStoreError>;
2189
- /**
2190
- * Mark stream as closed.
2191
- */
2192
- closeStream(workflowId: string, namespace: string): AsyncResult<void, StreamStoreError>;
2193
- /**
2194
- * Subscribe to new items in a stream.
2195
- * Callback is invoked for each new item written.
2196
- * Returns unsubscribe function.
2197
- */
2198
- subscribe<T>(workflowId: string, namespace: string, callback: (item: StreamItem<T>) => void): Unsubscribe;
2199
- }
2200
- /**
2201
- * Check if an error is a StreamEndedMarker.
2202
- */
2203
- declare function isStreamEnded(error: unknown): error is StreamEndedMarker;
2204
- /**
2205
- * Check if an error is a StreamWriteError.
2206
- */
2207
- declare function isStreamWriteError(error: unknown): error is StreamWriteError;
2208
- /**
2209
- * Check if an error is a StreamReadError.
2210
- */
2211
- declare function isStreamReadError(error: unknown): error is StreamReadError;
2212
- /**
2213
- * Check if an error is a StreamStoreError.
2214
- */
2215
- declare function isStreamStoreError(error: unknown): error is StreamStoreError;
2216
- /**
2217
- * Check if an error is a StreamBackpressureError.
2218
- */
2219
- declare function isStreamBackpressureError(error: unknown): error is StreamBackpressureError;
2220
- /**
2221
- * Create a StreamWriteError.
2222
- */
2223
- declare function streamWriteError(reason: StreamWriteError["reason"], message: string, cause?: unknown): StreamWriteError;
2224
- /**
2225
- * Create a StreamReadError.
2226
- */
2227
- declare function streamReadError(reason: StreamReadError["reason"], message: string, cause?: unknown): StreamReadError;
2228
- /**
2229
- * Create a StreamCloseError.
2230
- */
2231
- declare function streamCloseError(reason: StreamCloseError["reason"], message: string, cause?: unknown): StreamCloseError;
2232
- /**
2233
- * Create a StreamStoreError.
2234
- */
2235
- declare function streamStoreError(reason: StreamStoreError["reason"], message: string, cause?: unknown): StreamStoreError;
2236
- /**
2237
- * Create a StreamEndedMarker.
2238
- */
2239
- declare function streamEnded(finalPosition: number): StreamEndedMarker;
2240
- /**
2241
- * Create a StreamBackpressureError.
2242
- */
2243
- declare function streamBackpressureError(bufferedCount: number, highWaterMark: number): StreamBackpressureError;
2244
-
2245
- /**
2246
- * awaitly/persistence
2247
- *
2248
- * Simplified Persistence API for workflow snapshots.
2249
- * Provides JSON-serializable snapshot format and store adapters.
2250
- */
2251
-
2252
- /**
2253
- * Enforce JSON-safety at type level.
2254
- * Only allows values that can be safely serialized with JSON.stringify.
2255
- */
2256
- type JSONValue = null | boolean | number | string | JSONValue[] | {
2257
- [k: string]: JSONValue;
2258
- };
2259
- /**
2260
- * Canonical error wire format - handles both Error instances and thrown non-Errors.
2261
- * This is the single source of truth for serialized errors in snapshots.
2262
- */
2263
- type SerializedCause = {
2264
- type: "error";
2265
- name: string;
2266
- message: string;
2267
- stack?: string;
2268
- cause?: SerializedCause;
2269
- } | {
2270
- type: "thrown";
2271
- originalType?: string;
2272
- value?: JSONValue;
2273
- stringRepresentation: string;
2274
- truncated?: true;
2275
- };
2276
- /**
2277
- * Single source of truth for step outcome (no error/cause confusion).
2278
- * Uses discriminated union with `ok` field.
2279
- */
2280
- type StepResult = {
2281
- ok: true;
2282
- value: JSONValue;
2283
- } | {
2284
- ok: false;
2285
- error: JSONValue;
2286
- cause: SerializedCause;
2287
- meta?: {
2288
- origin: "result" | "throw";
2289
- };
2290
- };
2291
- /**
2292
- * JSON-serializable workflow snapshot.
2293
- * Designed to be passed directly to JSON.stringify without special handling.
2294
- *
2295
- * @example
2296
- * ```typescript
2297
- * // Persist
2298
- * localStorage.setItem('wf-123', JSON.stringify(wf.getSnapshot()));
2299
- *
2300
- * // Restore (safe pattern - storage can be empty/corrupt)
2301
- * const raw = localStorage.getItem('wf-123');
2302
- * const snapshot = raw ? JSON.parse(raw) : null;
2303
- * createWorkflow(deps, { snapshot }); // null = fresh start
2304
- * ```
2305
- */
2306
- interface WorkflowSnapshot {
2307
- /** Snapshot format version (literal type - bump when shape changes) */
2308
- formatVersion: 1;
2309
- /** Workflow name (from createWorkflow first argument). */
2310
- workflowName?: string;
2311
- /** Step results keyed by step ID. Uses Object.create(null) internally. */
2312
- steps: Record<string, StepResult>;
2313
- /** Execution state metadata */
2314
- execution: {
2315
- status: "running" | "completed" | "failed";
2316
- /** ISO timestamp (UTC toISOString()) */
2317
- lastUpdated: string;
2318
- /** ISO timestamp if finished */
2319
- completedAt?: string;
2320
- /**
2321
- * For paused/running workflows: the step key of the current step.
2322
- * Aligns with Workflow Diagram DSL step state ids (see awaitly/workflow diagram-dsl)
2323
- * so visualizers can highlight the current node.
2324
- */
2325
- currentStepId?: string;
2326
- };
2327
- /** Optional metadata for workflow identification and replay */
2328
- metadata?: {
2329
- /** Detect wrong snapshot for wrong workflow */
2330
- workflowId?: string;
2331
- /** Optional: detect definition changes (user-supplied, advisory only) */
2332
- definitionHash?: string;
2333
- /** Original input for replay */
2334
- input?: JSONValue;
2335
- [key: string]: JSONValue | undefined;
2336
- };
2337
- /** Warnings for lossy serialization (keeps step results pure) */
2338
- warnings?: Array<{
2339
- type: "lossy_value";
2340
- stepId: string;
2341
- path: string;
2342
- reason: "non-json" | "circular" | "encode-failed";
2343
- }>;
2344
- }
2345
- /**
2346
- * Warning entry for lossy value serialization.
2347
- */
2348
- type SnapshotWarning = NonNullable<WorkflowSnapshot["warnings"]>[number];
2349
- /**
2350
- * Error thrown when snapshot structure is invalid.
2351
- */
2352
- declare class SnapshotFormatError extends Error {
2353
- readonly errors: string[];
2354
- constructor(message: string, errors?: string[]);
2355
- }
2356
- /**
2357
- * Error thrown when snapshot doesn't match workflow (unknown steps, workflowId mismatch).
2358
- */
2359
- declare class SnapshotMismatchError extends Error {
2360
- readonly mismatchType: "unknown_steps" | "workflow_id" | "definition_hash";
2361
- readonly details?: {
2362
- unknownSteps?: string[];
2363
- snapshotWorkflowId?: string;
2364
- expectedWorkflowId?: string;
2365
- snapshotHash?: string;
2366
- expectedHash?: string;
2367
- } | undefined;
2368
- constructor(message: string, mismatchType: "unknown_steps" | "workflow_id" | "definition_hash", details?: {
2369
- unknownSteps?: string[];
2370
- snapshotWorkflowId?: string;
2371
- expectedWorkflowId?: string;
2372
- snapshotHash?: string;
2373
- expectedHash?: string;
2374
- } | undefined);
2375
- }
2376
- /**
2377
- * Error thrown when decode fails during restore.
2378
- */
2379
- declare class SnapshotDecodeError extends Error {
2380
- readonly stepId: string;
2381
- readonly originalError?: unknown | undefined;
2382
- constructor(message: string, stepId: string, originalError?: unknown | undefined);
2383
- }
2384
- /**
2385
- * Light check to see if an object looks like a WorkflowSnapshot.
2386
- * Cheap check for basic structure - use validateSnapshot() for full validation.
2387
- *
2388
- * @example
2389
- * ```typescript
2390
- * const raw = JSON.parse(localStorage.getItem('wf-123') || 'null');
2391
- * if (looksLikeWorkflowSnapshot(raw)) {
2392
- * createWorkflow(deps, { snapshot: raw });
2393
- * }
2394
- * ```
2395
- */
2396
- declare function looksLikeWorkflowSnapshot(obj: unknown): obj is WorkflowSnapshot;
2397
- /**
2398
- * Type guard for WorkflowSnapshot. Same as looksLikeWorkflowSnapshot; use for consistent naming with isResumeState / isSerializedResumeState.
2399
- */
2400
- declare const isWorkflowSnapshot: typeof looksLikeWorkflowSnapshot;
2401
- /**
2402
- * Full validation with detailed errors.
2403
- * Returns either a validated snapshot or an array of validation errors.
2404
- */
2405
- declare function validateSnapshot(obj: unknown): {
2406
- valid: true;
2407
- snapshot: WorkflowSnapshot;
2408
- } | {
2409
- valid: false;
2410
- errors: string[];
2411
- };
2412
- /**
2413
- * Throwing helper for cleaner code.
2414
- * Validates a snapshot and throws SnapshotFormatError if invalid.
2415
- *
2416
- * @throws {SnapshotFormatError} If snapshot is invalid
2417
- */
2418
- declare function assertValidSnapshot(obj: unknown): WorkflowSnapshot;
2419
- /**
2420
- * Merge two snapshots (for incremental updates).
2421
- * Delta steps overwrite base steps; execution from delta; metadata shallow merge.
2422
- */
2423
- declare function mergeSnapshots(base: WorkflowSnapshot, delta: WorkflowSnapshot): WorkflowSnapshot;
2424
- /**
2425
- * Serialize an Error object to SerializedCause format.
2426
- * Preserves Error.cause recursively.
2427
- */
2428
- declare function serializeError(error: Error): SerializedCause;
2429
- /**
2430
- * Serialize a non-Error thrown value to SerializedCause format.
2431
- */
2432
- declare function serializeThrown(value: unknown): SerializedCause;
2433
- /**
2434
- * Deserialize a SerializedCause back to its original form.
2435
- */
2436
- declare function deserializeCauseNew(serialized: SerializedCause): unknown;
2437
- /**
2438
- * Simplified store interface for workflow snapshot persistence.
2439
- * Works directly with WorkflowSnapshot objects.
2440
- *
2441
- * Adapters may implement an extended contract (see awaitly/workflow): save can accept
2442
- * WorkflowSnapshot | ResumeState; load can return WorkflowSnapshot | ResumeState | null.
2443
- * Use isWorkflowSnapshot / isSerializedResumeState and serializeResumeState / deserializeResumeState
2444
- * when branching. For type-safe restore, use store.loadResumeState(id) or toResumeState(await store.load(id)).
2445
- *
2446
- * @example
2447
- * ```typescript
2448
- * import { postgres } from 'awaitly-postgres';
2449
- * import { createWorkflow } from 'awaitly/workflow';
2450
- *
2451
- * const store = postgres('postgresql://localhost/mydb');
2452
- * const workflow = createWorkflow(deps);
2453
- *
2454
- * // Run and persist resume state
2455
- * const { result, resumeState } = await workflow.runWithState(fn);
2456
- * await store.save('wf-123', resumeState);
2457
- *
2458
- * // Restore
2459
- * const loaded = await store.load('wf-123');
2460
- * const resumeState = toResumeState(loaded);
2461
- * if (resumeState) await workflow.run(fn, { resumeState });
2462
- * ```
2463
- */
2464
- interface SnapshotStore {
2465
- /** Save a workflow snapshot (upsert - insert or update). Adapters may also accept ResumeState. */
2466
- save(id: string, snapshot: WorkflowSnapshot): Promise<void>;
2467
- /** Load a workflow snapshot. Returns null if not found. Adapters may return ResumeState when stored as such. */
2468
- load(id: string): Promise<WorkflowSnapshot | null>;
2469
- /** Delete a workflow snapshot. */
2470
- delete(id: string): Promise<void>;
2471
- /** List workflow IDs with their last update time. */
2472
- list(options?: {
2473
- prefix?: string;
2474
- limit?: number;
2475
- }): Promise<Array<{
2476
- id: string;
2477
- updatedAt: string;
2478
- }>>;
2479
- /** Clean shutdown for tests/graceful exit. */
2480
- close(): Promise<void>;
2481
- }
2482
- /**
2483
- * Options for the in-memory cache adapter.
2484
- */
2485
- interface MemoryCacheOptions {
2486
- /**
2487
- * Maximum number of entries to store.
2488
- * Oldest entries are evicted when limit is reached.
2489
- */
2490
- maxSize?: number;
2491
- /**
2492
- * Time-to-live in milliseconds.
2493
- * Entries are automatically removed after this duration.
2494
- */
2495
- ttl?: number;
2496
- }
2497
- /**
2498
- * Create an in-memory StepCache with optional LRU eviction and TTL.
2499
- *
2500
- * @param options - Cache options
2501
- * @returns StepCache implementation
2502
- *
2503
- * @example
2504
- * ```typescript
2505
- * const cache = createMemoryCache({ maxSize: 1000, ttl: 60000 });
2506
- * const workflow = createWorkflow(deps, { cache });
2507
- * ```
2508
- */
2509
- declare function createMemoryCache(options?: MemoryCacheOptions): StepCache;
2510
-
2511
- /**
2512
- * Workflow type definitions.
2513
- * Pure types and interfaces; no runtime code.
2514
- */
2515
-
2516
- /**
2517
- * Interface for step result caching.
2518
- * Implement this interface to provide custom caching strategies.
2519
- * A simple Map<string, Result> works for in-memory caching.
2520
- *
2521
- * ## When Cache is Populated
2522
- *
2523
- * The cache `set()` method is called after each step completes (success or error)
2524
- * when the step has a `key` option. Both calling patterns work identically:
2525
- *
2526
- * ```typescript
2527
- * // Function-wrapped pattern - cache is populated
2528
- * await step(() => fetchUser("1"), { key: "user:1" });
2529
- *
2530
- * // Direct AsyncResult pattern - cache is also populated
2531
- * await step(fetchUser("1"), { key: "user:1" });
2532
- * ```
2533
- *
2534
- * Note: Cache stores Result<unknown, unknown, unknown> because different steps
2535
- * have different value/error/cause types. The actual runtime values are preserved;
2536
- * only the static types are widened. For error results, the cause value is encoded
2537
- * in CachedErrorCause to preserve metadata for proper replay.
2538
- *
2539
- * @example
2540
- * // Simple in-memory cache
2541
- * const cache = new Map<string, Result<unknown, unknown, unknown>>();
2542
- *
2543
- * // Or implement custom cache with TTL, LRU, etc.
2544
- * const cache: StepCache = {
2545
- * get: (key) => myCache.get(key),
2546
- * set: (key, result) => myCache.set(key, result, { ttl: 60000 }),
2547
- * has: (key) => myCache.has(key),
2548
- * delete: (key) => myCache.delete(key),
2549
- * clear: () => myCache.clear(),
2550
- * };
2551
- */
2552
- interface StepCache {
2553
- get(key: string): Result<unknown, unknown, unknown> | undefined;
2554
- set(key: string, result: Result<unknown, unknown, unknown>, options?: {
2555
- ttl?: number;
2556
- }): void;
2557
- has(key: string): boolean;
2558
- delete(key: string): boolean;
2559
- clear(): void;
2560
- }
2561
- /**
2562
- * Entry for a saved step result with optional metadata.
2563
- * The meta field preserves origin information for proper replay.
2564
- */
2565
- interface ResumeStateEntry {
2566
- result: Result<unknown, unknown, unknown>;
2567
- /** Optional metadata for error origin (from step_complete event) */
2568
- meta?: StepFailureMeta;
2569
- }
2570
- /**
2571
- * Resume state for workflow replay.
2572
- * Pre-populate step results to skip execution on resume.
2573
- *
2574
- * Note: When saving to persistent storage, you may need custom serialization
2575
- * for complex cause types. JSON.stringify works for simple values, but Error
2576
- * objects and other non-plain types require special handling.
2577
- *
2578
- * @example
2579
- * // Collect from step_complete events using the helper
2580
- * const collector = createResumeStateCollector();
2581
- * const workflow = createWorkflow({ fetchUser }, {
2582
- * onEvent: collector.handleEvent,
2583
- * });
2584
- * // Later: collector.getResumeState() returns ResumeState
2585
- *
2586
- * @example
2587
- * // Resume with saved state
2588
- * const workflow = createWorkflow({ fetchUser }, {
2589
- * resumeState: { steps: savedSteps }
2590
- * });
2591
- */
2592
- interface ResumeState {
2593
- /** Map of step keys to their cached results with optional metadata */
2594
- steps: Map<string, ResumeStateEntry>;
2595
- }
2596
- /**
2597
- * Constraint for Result-returning functions
2598
- * Used by createWorkflow to ensure only valid functions are passed
2599
- */
2600
- type AnyResultFn = (...args: any[]) => Result<any, any, any> | Promise<Result<any, any, any>>;
2601
- /**
2602
- * Extract union of error types from a deps object
2603
- * Example: ErrorsOfDeps<{ fetchUser: typeof fetchUser, fetchPosts: typeof fetchPosts }>
2604
- * yields: 'NOT_FOUND' | 'FETCH_ERROR'
2605
- */
2606
- type ErrorsOfDeps<Deps extends Record<string, AnyResultFn>> = {
2607
- [K in keyof Deps]: ErrorOf<Deps[K]>;
2608
- }[keyof Deps];
2609
- /**
2610
- * Extract union of cause types from a deps object.
2611
- * Example: CausesOfDeps<{ fetchUser: typeof fetchUser }> where fetchUser returns Result<User, "NOT_FOUND", Error>
2612
- * yields: Error
2613
- *
2614
- * Note: This represents the domain cause types from declared functions.
2615
- * However, workflow results may also have unknown causes from step.try failures
2616
- * or uncaught exceptions, so the actual Result cause type is `unknown`.
2617
- */
2618
- type CausesOfDeps<Deps extends Record<string, AnyResultFn>> = CauseOf<Deps[keyof Deps]>;
2619
- /**
2620
- * Execution-time options that can override creation-time options.
2621
- * Pass these to `workflow.run(fn, execOptions)` for per-run configuration.
2622
- *
2623
- * Rule: Use `workflow(...)` for normal runs. Use `workflow.run(...)` when you need per-run hooks/options.
2624
- *
2625
- * @example
2626
- * ```typescript
2627
- * const workflow = createWorkflow(deps, { cache, onEvent: defaultHandler });
2628
- *
2629
- * // Normal run uses creation-time options
2630
- * await workflow(async ({ step }) => { ... });
2631
- *
2632
- * // Per-run options override creation-time options
2633
- * await workflow.run(async ({ step }) => { ... }, { onEvent: viz.handleEvent });
2634
- *
2635
- * // Pre-bind defaults with .with() (overridable by .run())
2636
- * const visualized = workflow.with({ onEvent: viz.handleEvent });
2637
- * await visualized(async ({ step }) => { ... });
2638
- * ```
2639
- */
2640
- type ExecutionOptions<E, U = UnexpectedError, C = void> = {
2641
- /**
2642
- * Event handler for workflow and step lifecycle events.
2643
- * Overrides `onEvent` from creation-time options.
2644
- */
2645
- onEvent?: (event: WorkflowEvent<E | U, C>, ctx: C) => void;
2646
- /**
2647
- * Error handler called when a step fails.
2648
- * Overrides `onError` from creation-time options.
2649
- */
2650
- onError?: (error: E | U, stepName?: string, ctx?: C) => void;
2651
- /**
2652
- * AbortSignal for workflow-level cancellation.
2653
- * Overrides `signal` from creation-time options.
2654
- */
2655
- signal?: AbortSignal;
2656
- /**
2657
- * Factory to create per-run context. Can be async.
2658
- * Overrides `createContext` from creation-time options.
2659
- */
2660
- createContext?: () => C | Promise<C>;
2661
- /**
2662
- * Resume state for workflow replay. Can be a factory function (sync or async).
2663
- * Overrides `resumeState` from creation-time options.
2664
- */
2665
- resumeState?: ResumeState | (() => ResumeState | Promise<ResumeState>);
2666
- /**
2667
- * Hook to check if workflow should run (concurrency control).
2668
- * Overrides `shouldRun` from creation-time options.
2669
- */
2670
- shouldRun?: (workflowId: string, context: C) => boolean | Promise<boolean>;
2671
- /**
2672
- * Hook called before workflow execution starts.
2673
- * Overrides `onBeforeStart` from creation-time options.
2674
- */
2675
- onBeforeStart?: (workflowId: string, context: C) => boolean | Promise<boolean>;
2676
- /**
2677
- * Hook called after each step completes (only for steps with a `key`).
2678
- * Overrides `onAfterStep` from creation-time options.
2679
- */
2680
- onAfterStep?: (stepKey: string, result: Result<unknown, unknown, unknown>, workflowId: string, context: C) => void | Promise<void>;
2681
- /**
2682
- * Enable strict mode for this specific run (analyzer validation only).
2683
- */
2684
- strict?: boolean;
2685
- /**
2686
- * Declared workflow graph for strict runtime validation.
2687
- * Undeclared step/decision ids fail the run immediately.
2688
- * Overrides `graph` from creation-time options.
2689
- */
2690
- graph?: DeclaredGraph;
2691
- /**
2692
- * Enable development warnings for this run.
2693
- * Only active when NODE_ENV !== 'production'.
2694
- */
2695
- devWarnings?: boolean;
2696
- };
2697
- /**
2698
- * Per-run configuration. Extends ExecutionOptions with dep overrides.
2699
- * Pass to `workflow.run(fn, config)` or `workflow.run(name, fn, config)`.
2700
- */
2701
- type RunConfig<E, U = UnexpectedError, C = void, Deps = unknown> = ExecutionOptions<E, U, C> & {
2702
- /** Override creation-time deps (partial merge). */
2703
- deps?: Partial<Deps>;
2704
- /** Step result cache for this run. */
2705
- cache?: StepCache;
2706
- /** Restore workflow from a previously saved snapshot. */
2707
- snapshot?: WorkflowSnapshot | null;
2708
- /** Stream store for this run. */
2709
- streamStore?: StreamStore;
2710
- };
2711
- /**
2712
- * Workflow options. Error union is always closed: E | U.
2713
- * When catchUnexpected is omitted, U defaults to UnexpectedError.
2714
- */
2715
- type WorkflowOptions<E, U = UnexpectedError, C = void, Errs extends readonly string[] = readonly string[]> = {
2716
- /** Standard Schema for input validation. Works with Zod, Valibot, ArkType, etc. */
2717
- inputSchema?: StandardSchemaV1;
2718
- /** Input data to validate against inputSchema and pass to workflow context. */
2719
- input?: unknown;
2720
- /** Short description for labels/tooltips (static analysis) */
2721
- description?: string;
2722
- /** Full markdown documentation (static analysis) */
2723
- markdown?: string;
2724
- /**
2725
- * Map uncaught exceptions (and cancellation) to your error type U.
2726
- * When omitted, U = UnexpectedError and the default mapper returns an UnexpectedError instance.
2727
- */
2728
- catchUnexpected?: (cause: unknown) => U;
2729
- /**
2730
- * Declared errors for the workflow (strict validation).
2731
- * When provided, the analyzer validates that computed errors match declared errors.
2732
- */
2733
- errors?: Errs;
2734
- onError?: (error: E | U, stepName?: string, ctx?: C) => void;
2735
- /**
2736
- * Unified event stream for workflow and step lifecycle.
2737
- *
2738
- * Context is automatically included in `event.context` when provided via `createContext`.
2739
- * The separate `ctx` parameter is provided for convenience.
2740
- */
2741
- onEvent?: (event: WorkflowEvent<E | U, C>, ctx: C) => void;
2742
- /** Create per-run context for event correlation */
2743
- createContext?: () => C;
2744
- /** Step result cache - only steps with a `key` option are cached */
2745
- cache?: StepCache;
2746
- /** Pre-populate cache from saved state for workflow resume. Prefer `snapshot` option. */
2747
- resumeState?: ResumeState | (() => ResumeState | Promise<ResumeState>);
2748
- /**
2749
- * Restore workflow from a previously saved snapshot.
2750
- * Pass `null` for fresh start (e.g., when store.load() returns nothing).
2751
- */
2752
- snapshot?: WorkflowSnapshot | null;
2753
- /**
2754
- * Custom serialization for encoding/decoding values during snapshot operations.
2755
- */
2756
- serialization?: {
2757
- encode?: (value: unknown) => JSONValue;
2758
- decode?: (value: JSONValue) => unknown;
2759
- };
2760
- snapshotSerialization?: {
2761
- strict?: boolean;
2762
- };
2763
- onUnknownSteps?: "warn" | "error" | "ignore";
2764
- onDefinitionChange?: "warn" | "error" | "ignore";
2765
- /**
2766
- * External AbortSignal for workflow-level cancellation.
2767
- * Cancellation is mapped through catchUnexpected (default: UnexpectedError with cause.thrown = WorkflowCancelledError).
2768
- */
2769
- signal?: AbortSignal;
2770
- onBeforeStart?: (workflowId: string, context: C) => boolean | Promise<boolean>;
2771
- onAfterStep?: (stepKey: string, result: Result<unknown, unknown, unknown>, workflowId: string, context: C) => void | Promise<void>;
2772
- shouldRun?: (workflowId: string, context: C) => boolean | Promise<boolean>;
2773
- streamStore?: StreamStore;
2774
- /**
2775
- * Declared workflow graph for strict runtime validation.
2776
- * When provided, any runtime step/decision id not present in the graph
2777
- * fails the workflow immediately, guaranteeing the static diagram matches
2778
- * what actually runs. Produce it with awaitly-analyze's renderWorkflowDSL,
2779
- * or pass a plain list of ids.
2780
- */
2781
- graph?: DeclaredGraph;
2782
- /**
2783
- * Enable development warnings.
2784
- * Only active when NODE_ENV !== 'production'.
2785
- */
2786
- devWarnings?: boolean;
2787
- };
2788
- /**
2789
- * Workflow context provided to callbacks, containing workflow metadata
2790
- * and data store for step outputs.
2791
- * This allows conditional helpers and other utilities to access workflowId, onEvent, and context.
2792
- */
2793
- type WorkflowContext<C = void, Input = Record<string, unknown>, Data = Record<string, unknown>> = {
2794
- /**
2795
- * Unique ID for this workflow run.
2796
- */
2797
- workflowId: string;
2798
- /**
2799
- * Event emitter function for workflow events.
2800
- * Can be used with conditional helpers to emit step_skipped events.
2801
- */
2802
- onEvent?: (event: WorkflowEvent<unknown, C>) => void;
2803
- /**
2804
- * Per-run context created by createContext (or undefined if not provided).
2805
- * Automatically included in all workflow events.
2806
- */
2807
- context?: C;
2808
- /**
2809
- * Workflow-level AbortSignal (if provided in workflow options).
2810
- * Use this to check cancellation or pass to operations that support AbortSignal.
2811
- *
2812
- * @example
2813
- * ```typescript
2814
- * const result = await workflow(async ({ step, deps, ctx }) => {
2815
- * // Pass signal to fetch
2816
- * const response = await fetch(url, { signal: ctx.signal });
2817
- * // Or check manually
2818
- * if (ctx.signal?.aborted) return early();
2819
- * });
2820
- * ```
2821
- */
2822
- signal?: AbortSignal;
2823
- /**
2824
- * Input data passed to the workflow.
2825
- * Access via `ctx.input.key` for static analysis tracking.
2826
- *
2827
- * @example
2828
- * ```typescript
2829
- * await step('getCart', () => getCart(ctx.input.cartId), {
2830
- * errors: ['CART_NOT_FOUND'],
2831
- * });
2832
- * ```
2833
- */
2834
- input: Input;
2835
- /**
2836
- * Get a value from the workflow data store by key.
2837
- * Preferred over `ctx.get()` for static analysis as it's easier to trace.
2838
- *
2839
- * @param key - The key to retrieve
2840
- * @returns The value at that key
2841
- *
2842
- * @example
2843
- * ```typescript
2844
- * // Use ctx.ref() inside step callbacks for tracked dependencies
2845
- * await step('charge', () => chargeCard(ctx.ref('cart').total), {
2846
- * errors: ['CARD_DECLINED'],
2847
- * });
2848
- * ```
2849
- */
2850
- ref: <K extends keyof Data>(key: K) => Data[K];
2851
- /**
2852
- * Set a value in the workflow data store.
2853
- * Prefer using `out` option on steps instead for better static analysis.
2854
- *
2855
- * @param key - The key to set
2856
- * @param value - The value to store
2857
- *
2858
- * @example
2859
- * ```typescript
2860
- * // Prefer out option:
2861
- * await step('getCart', () => getCart(id), { out: 'cart' });
2862
- *
2863
- * // Escape hatch (less analyzable):
2864
- * const cart = await step('getCart', () => getCart(id));
2865
- * ctx.set('cart', cart);
2866
- * ```
2867
- */
2868
- set: <K extends string>(key: K, value: unknown) => void;
2869
- /**
2870
- * Get a value from the workflow data store.
2871
- * Prefer `ctx.ref()` for better static analysis.
2872
- *
2873
- * @param key - The key to retrieve
2874
- * @returns The value at that key (or undefined)
2875
- */
2876
- get: <K extends keyof Data>(key: K) => Data[K] | undefined;
2877
- };
2878
- /**
2879
- * Bound steps for a workflow's deps: each dep key becomes a step function
2880
- * with the dep's arguments that unwraps ok / early-exits on err — same as
2881
- * the deps-first run(deps, fn) form. `never` deps (no deps) yield no steps.
2882
- */
2883
- type WorkflowSteps<Deps> = [Deps] extends [
2884
- Record<string, (...args: never[]) => unknown>
2885
- ] ? BoundSteps<Deps> : Record<string, never>;
2886
- /** Workflow function type (no args). E is the full step error union (deps errors + any ExtraE from step.workflow/withFallback). */
2887
- type WorkflowFn<T, E, Deps, C = void> = (context: {
2888
- step: RunStep<E>;
2889
- steps: WorkflowSteps<Deps>;
2890
- deps: Deps;
2891
- ctx: WorkflowContext<C>;
2892
- }) => T | Promise<T>;
2893
- /**
2894
- * Return type of runWithState: result plus resume state for persistence.
2895
- * resumeState is always present, even when the run fails or returns an error Result.
2896
- */
2897
- type RunWithStateResult<T, E, U> = {
2898
- result: Result<T, E | U, unknown>;
2899
- resumeState: ResumeState;
2900
- };
2901
- /**
2902
- * Workflow return type. Error union is always closed: E | ExtraE | U (default U = UnexpectedError).
2903
- * ExtraE is inferred from the callback when using step.workflow or step.withFallback with errors not in deps.
2904
- * Methods: .run() (4 overloads) and .runWithState() (4 overloads) for run-and-persist flows.
2905
- *
2906
- * Cause type is `unknown` because step.try/catchUnexpected receive thrown values.
2907
- */
2908
- interface Workflow<E, U = UnexpectedError, Deps = unknown, C = void> {
2909
- /**
2910
- * Pre-bind dependency overrides and return another `Workflow`.
2911
- * Chain `.withDeps()` and call `.run()` / `.runWithState()` as normal.
2912
- * Precedence: createWorkflow deps < withDeps deps < run config deps.
2913
- */
2914
- withDeps(overrides: Partial<Deps>): Workflow<E, U, Deps, C>;
2915
- /**
2916
- * Execute workflow (anonymous run).
2917
- * ExtraE is inferred from the callback (e.g. from step.workflow / step.withFallback); result is Result<T, E | ExtraE | U>.
2918
- * T is inferred from the callback return type. For nested workflows (calling another workflow.run() inside the callback),
2919
- * inference can sometimes fall back to `any`; adding an explicit return type to the callback (e.g.
2920
- * `async (ctx): Promise<{ user: User; enriched: Enriched }> => { ... }`) gives the compiler a target and preserves types.
2921
- */
2922
- run<T, ExtraE = never>(fn: WorkflowFn<T, E | ExtraE, Deps, C>): AsyncResult<T, E | ExtraE | U, unknown>;
2923
- /**
2924
- * Execute workflow with config overrides.
2925
- */
2926
- run<T, ExtraE = never>(fn: WorkflowFn<T, E | ExtraE, Deps, C>, config: RunConfig<E, U, C, Deps>): AsyncResult<T, E | ExtraE | U, unknown>;
2927
- /**
2928
- * Execute named workflow run (for logging, tracing, resume).
2929
- */
2930
- run<T, ExtraE = never>(name: string, fn: WorkflowFn<T, E | ExtraE, Deps, C>): AsyncResult<T, E | ExtraE | U, unknown>;
2931
- /**
2932
- * Execute named workflow run with config overrides.
2933
- */
2934
- run<T, ExtraE = never>(name: string, fn: WorkflowFn<T, E | ExtraE, Deps, C>, config: RunConfig<E, U, C, Deps>): AsyncResult<T, E | ExtraE | U, unknown>;
2935
- /**
2936
- * Execute workflow and return result plus resume state for persistence.
2937
- * resumeState is always present (even on failure) so callers can persist partial state.
2938
- * Same overloads as run(); does not throw — follows the same "never throw, always Result" contract as run().
2939
- *
2940
- * @example
2941
- * const { result, resumeState } = await workflow.runWithState(fn);
2942
- * await store.save(id, resumeState);
2943
- */
2944
- runWithState<T, ExtraE = never>(fn: WorkflowFn<T, E | ExtraE, Deps, C>): Promise<RunWithStateResult<T, E | ExtraE, U>>;
2945
- /**
2946
- * Execute workflow with config overrides and return result plus resume state.
2947
- */
2948
- runWithState<T, ExtraE = never>(fn: WorkflowFn<T, E | ExtraE, Deps, C>, config: RunConfig<E, U, C, Deps>): Promise<RunWithStateResult<T, E | ExtraE, U>>;
2949
- /**
2950
- * Execute named workflow run and return result plus resume state.
2951
- */
2952
- runWithState<T, ExtraE = never>(name: string, fn: WorkflowFn<T, E | ExtraE, Deps, C>): Promise<RunWithStateResult<T, E | ExtraE, U>>;
2953
- /**
2954
- * Execute named workflow run with config overrides and return result plus resume state.
2955
- */
2956
- runWithState<T, ExtraE = never>(name: string, fn: WorkflowFn<T, E | ExtraE, Deps, C>, config: RunConfig<E, U, C, Deps>): Promise<RunWithStateResult<T, E | ExtraE, U>>;
2957
- }
2958
- /**
2959
- * Error returned when a workflow is cancelled via AbortSignal.
2960
- *
2961
- * @example
2962
- * ```typescript
2963
- * const controller = new AbortController();
2964
- * const workflow = createWorkflow(deps, { signal: controller.signal });
2965
- *
2966
- * // Later:
2967
- * controller.abort('User navigated away');
2968
- *
2969
- * const result = await workflowPromise;
2970
- * if (!result.ok && isWorkflowCancelled(result.error)) {
2971
- * console.log('Cancelled:', result.error.reason);
2972
- * }
2973
- * ```
2974
- */
2975
- type WorkflowCancelledError = {
2976
- type: "WORKFLOW_CANCELLED";
2977
- /** Reason from AbortSignal.reason (if provided) */
2978
- reason?: string;
2979
- /** Last successfully completed keyed step (for resume purposes) */
2980
- lastStepKey?: string;
2981
- };
2982
- /**
2983
- * Standard error type for steps awaiting human approval.
2984
- * Use this as the error type for approval-gated steps.
2985
- *
2986
- * @example
2987
- * const requireApproval = async (userId: string): AsyncResult<Approval, PendingApproval> => {
2988
- * const status = await checkApprovalStatus(userId);
2989
- * if (status === 'pending') {
2990
- * return err({ type: 'PENDING_APPROVAL', stepKey: `approval:${userId}` });
2991
- * }
2992
- * return ok(status.approval);
2993
- * };
2994
- */
2995
- type PendingApproval = {
2996
- type: "PENDING_APPROVAL";
2997
- /** Step key for correlation when resuming */
2998
- stepKey: string;
2999
- /** Optional reason for the pending state */
3000
- reason?: string;
3001
- /** Optional metadata for the approval request */
3002
- metadata?: Record<string, unknown>;
3003
- };
3004
- /**
3005
- * Standard error type for steps awaiting an HTTP callback (webhook).
3006
- * Use with injectHook() to resume when the app receives the callback.
3007
- * stepKey is always "hook:" + hookId for resume state.
3008
- */
3009
- type PendingHook = {
3010
- type: "PENDING_HOOK";
3011
- hookId: string;
3012
- /** Step key used in resume state; always "hook:" + hookId */
3013
- stepKey: string;
3014
- metadata?: Record<string, unknown>;
3015
- };
3016
- /**
3017
- * Error returned when approval is rejected.
3018
- */
3019
- type ApprovalRejected = {
3020
- type: "APPROVAL_REJECTED";
3021
- /** Step key for correlation */
3022
- stepKey: string;
3023
- /** Reason the approval was rejected */
3024
- reason: string;
3025
- };
3026
- /**
3027
- * Options for creating an approval-gated step.
3028
- */
3029
- interface ApprovalStepOptions<T> {
3030
- /** Stable key for this approval step (used for resume) */
3031
- key: string;
3032
- /** Function to check current approval status from external source */
3033
- checkApproval: () => Promise<{
3034
- status: "pending";
3035
- } | {
3036
- status: "approved";
3037
- value: T;
3038
- } | {
3039
- status: "rejected";
3040
- reason: string;
3041
- }>;
3042
- /** Optional reason shown when pending */
3043
- pendingReason?: string;
3044
- /** Optional metadata for the approval request */
3045
- metadata?: Record<string, unknown>;
3046
- }
3047
- /**
3048
- * Options for creating a gated (pre-approval) step.
3049
- */
3050
- interface GatedStepOptions<TArgs, T> {
3051
- /** Stable key for this gated step (used for approval tracking) */
3052
- key: string;
3053
- /**
3054
- * Condition to check if approval is required.
3055
- * If returns true, execution pauses for approval.
3056
- * If returns false, operation executes immediately.
3057
- */
3058
- requiresApproval: boolean | ((args: TArgs) => boolean | Promise<boolean>);
3059
- /**
3060
- * Human-readable description of what this operation does.
3061
- * Shown in the approval UI so humans understand what they're approving.
3062
- */
3063
- description: string | ((args: TArgs) => string);
3064
- /**
3065
- * Check if approval has been granted externally.
3066
- * If not provided, the step always returns PendingApproval when gated.
3067
- */
3068
- checkApproval?: () => Promise<{
3069
- status: "pending";
3070
- } | {
3071
- status: "approved";
3072
- value?: T;
3073
- } | {
3074
- status: "rejected";
3075
- reason: string;
3076
- }>;
3077
- /**
3078
- * Optional metadata to include in the approval request.
3079
- * The args are automatically included as `pendingArgs`.
3080
- */
3081
- metadata?: Record<string, unknown>;
3082
- }
3083
-
3084
- export { STREAM_ENDED as $, type AsyncResult as A, type BackoffStrategy as B, type WorkflowSnapshot as C, type DepValueOfReturn as D, EARLY_EXIT_SYMBOL as E, type ApprovalStepOptions as F, type GatedStepOptions as G, type Workflow as H, type WorkflowOptions as I, type SnapshotStore as J, type ResumeStateEntry as K, type StreamStore as L, type StreamReader as M, type CausesOfDeps as N, type Ok as O, type PendingApproval as P, type ExecutionOptions as Q, type Result as R, type StepOptions as S, type TimeoutOptions as T, type JSONValue as U, type MemoryCacheOptions as V, type WorkflowEvent as W, type RunConfig as X, type RunWithStateResult as Y, STREAM_BACKPRESSURE_ERROR as Z, STREAM_CLOSE_ERROR as _, type RetryOptions as a, STREAM_READ_ERROR as a0, STREAM_STORE_ERROR as a1, STREAM_WRITE_ERROR as a2, type SerializedCause as a3, SnapshotDecodeError as a4, SnapshotFormatError as a5, SnapshotMismatchError as a6, type SnapshotWarning as a7, type StepCache as a8, type StepErrorDiagnostics as a9, isWorkflowSnapshot as aA, looksLikeWorkflowSnapshot as aB, mergeSnapshots as aC, serializeError as aD, serializeThrown as aE, streamBackpressureError as aF, streamCloseError as aG, streamEnded as aH, streamReadError as aI, streamStoreError as aJ, streamWriteError as aK, validateSnapshot as aL, type StepMetadata as aa, type StreamBackpressureError as ab, type StreamCloseError as ac, type StreamEndedMarker as ad, type StreamError as ae, type StreamForEachOptions as af, type StreamForEachResult as ag, type StreamItem as ah, type StreamMetadata as ai, type StreamOptions as aj, type StreamReadError as ak, type StreamReadOptions as al, type StreamStoreError as am, type StreamWriteError as an, type StreamWriter as ao, type Unsubscribe as ap, type WorkflowFn as aq, type WorkflowSteps as ar, assertValidSnapshot as as, createMemoryCache as at, deserializeCauseNew as au, isStreamBackpressureError as av, isStreamEnded as aw, isStreamReadError as ax, isStreamStoreError as ay, isStreamWriteError as az, type BoundSteps as b, type EarlyExit as c, type RunOptions as d, type RunOptionsWithCatch as e, type RunOptionsWithoutCatch as f, type RunStep as g, STEP_TIMEOUT_MARKER as h, type ScopeType as i, type StepFailureMeta as j, type StepTimeoutError as k, type StepTimeoutMarkerMeta as l, createEarlyExit as m, getStepTimeoutMeta as n, isEarlyExit as o, isStepTimeoutError as p, type AnyResultFn as q, run as r, type ErrorsOfDeps as s, type WorkflowContext as t, type Err as u, type ApprovalRejected as v, type PendingHook as w, type ResumeState as x, type WorkflowCancelledError as y, type StepResult as z };
1924
+ export { type AsyncResult as A, type BackoffStrategy as B, type CauseOf as C, type DeclaredGraph as D, EARLY_EXIT_SYMBOL as E, type Ok as O, type Result as R, STEP_TIMEOUT_MARKER as S, type TimeoutOptions as T, type WorkflowEvent as W, type RunStep as a, type BoundSteps as b, type EarlyExit as c, type RetryOptions as d, type RunOptions as e, type RunOptionsWithCatch as f, type RunOptionsWithoutCatch as g, type ScopeType as h, type StepFailureMeta as i, type StepOptions as j, type StepTimeoutError as k, type StepTimeoutMarkerMeta as l, createEarlyExit as m, getStepTimeoutMeta as n, isEarlyExit as o, isStepTimeoutError as p, type Err as q, run as r, type ErrorOf as s, type StepErrorDiagnostics as t, type StepMetadata as u, type DepValueOfReturn as v, type ErrorsOf as w };