@jagreehal/workflow 1.7.0 → 1.9.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 +21 -1102
- package/dist/batch.cjs +2 -0
- package/dist/batch.cjs.map +1 -0
- package/dist/batch.d.cts +197 -0
- package/dist/batch.d.ts +197 -0
- package/dist/batch.js +2 -0
- package/dist/batch.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +98 -12
- package/dist/core.d.ts +98 -12
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +284 -17
- package/dist/index.d.ts +284 -17
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/resource.cjs +2 -0
- package/dist/resource.cjs.map +1 -0
- package/dist/resource.d.cts +171 -0
- package/dist/resource.d.ts +171 -0
- package/dist/resource.js +2 -0
- package/dist/resource.js.map +1 -0
- package/dist/workflow.cjs +1 -1
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +47 -15
- package/dist/workflow.d.ts +47 -15
- package/dist/workflow.js +1 -1
- package/dist/workflow.js.map +1 -1
- package/docs/advanced.md +57 -4
- package/docs/api.md +37 -6
- package/package.json +11 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,261 @@
|
|
|
1
1
|
import { WorkflowEvent, Result, AsyncResult, UnexpectedError, StepOptions, RetryOptions, TimeoutOptions, StepFailureMeta } from './core.cjs';
|
|
2
|
-
export { BackoffStrategy, CauseOf, EmptyInputError, ErrorOf, Errors, ExtractCause, ExtractError, ExtractValue, MaybeAsyncResult, PromiseRejectedError, PromiseRejectionCause, RunOptions, RunOptionsWithCatch, RunOptionsWithoutCatch, RunStep, STEP_TIMEOUT_MARKER, ScopeType, SettledError, StepTimeoutError, StepTimeoutMarkerMeta, UnexpectedCause, UnexpectedStepFailureCause, UnwrapError, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, bimap, err, from, fromNullable, fromPromise, getStepTimeoutMeta, isErr, isOk, isStepTimeoutError, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, orElse, orElseAsync, partition, recover, recoverAsync, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse } from './core.cjs';
|
|
2
|
+
export { BackoffStrategy, CauseOf, EmptyInputError, ErrorOf, Errors, ExtractCause, ExtractError, ExtractValue, MaybeAsyncResult, PromiseRejectedError, PromiseRejectionCause, RunOptions, RunOptionsWithCatch, RunOptionsWithoutCatch, RunStep, STEP_TIMEOUT_MARKER, ScopeType, SettledError, StepTimeoutError, StepTimeoutMarkerMeta, UnexpectedCause, UnexpectedStepFailureCause, UnwrapError, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, bimap, err, from, fromNullable, fromPromise, getStepTimeoutMeta, hydrate, isErr, isOk, isSerializedResult, isStepTimeoutError, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, orElse, orElseAsync, partition, recover, recoverAsync, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse } from './core.cjs';
|
|
3
3
|
import { ResumeState, ResumeStateEntry, Workflow, WorkflowStrict, StepCache, AnyResultFn as AnyResultFn$1, ErrorsOfDeps as ErrorsOfDeps$1 } from './workflow.cjs';
|
|
4
|
-
export { ApprovalRejected, ApprovalStepOptions, CausesOfDeps, PendingApproval, WorkflowOptions, WorkflowOptionsStrict, clearStep, createApprovalStep, createHITLCollector, createStepCollector, createWorkflow, getPendingApprovals, hasPendingApproval, injectApproval, isApprovalRejected, isPendingApproval, isStepComplete, pendingApproval } from './workflow.cjs';
|
|
4
|
+
export { ApprovalRejected, ApprovalStepOptions, CausesOfDeps, PendingApproval, WorkflowContext, WorkflowOptions, WorkflowOptionsStrict, clearStep, createApprovalStep, createHITLCollector, createStepCollector, createWorkflow, getPendingApprovals, hasPendingApproval, injectApproval, isApprovalRejected, isPendingApproval, isStepComplete, pendingApproval } from './workflow.cjs';
|
|
5
5
|
import { CollectableEvent, VisualizerOptions, DecisionStartEvent, DecisionBranchEvent, DecisionEndEvent, OutputFormat } from './visualize.cjs';
|
|
6
|
+
export { BatchConfig, BatchOptions, BatchProcessingError, BatchProgress, InvalidBatchConfigError, batchPresets, isBatchProcessingError, isInvalidBatchConfigError, processInBatches } from './batch.cjs';
|
|
7
|
+
export { Resource, ResourceCleanupError, ResourceScope, createResource, createResourceScope, isResourceCleanupError, withScope } from './resource.cjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @jagreehal/workflow/tagged-error
|
|
11
|
+
*
|
|
12
|
+
* Factory for creating tagged error types with exhaustive pattern matching.
|
|
13
|
+
* Enables TypeScript to enforce that all error variants are handled.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* // Define error types (Props via generic)
|
|
18
|
+
* class NotFoundError extends TaggedError("NotFoundError")<{
|
|
19
|
+
* id: string;
|
|
20
|
+
* resource: string;
|
|
21
|
+
* }> {}
|
|
22
|
+
*
|
|
23
|
+
* // Define with type-safe message (Props inferred from callback annotation)
|
|
24
|
+
* class ValidationError extends TaggedError("ValidationError", {
|
|
25
|
+
* message: (p: { field: string; reason: string }) => `Invalid ${p.field}: ${p.reason}`,
|
|
26
|
+
* }) {}
|
|
27
|
+
*
|
|
28
|
+
* // Create instances
|
|
29
|
+
* const error = new NotFoundError({ id: "123", resource: "User" });
|
|
30
|
+
*
|
|
31
|
+
* // Runtime type check: instanceof TaggedError works!
|
|
32
|
+
* console.log(error instanceof TaggedError); // true
|
|
33
|
+
*
|
|
34
|
+
* // Exhaustive matching
|
|
35
|
+
* type AppError = NotFoundError | ValidationError;
|
|
36
|
+
* const message = TaggedError.match(error as AppError, {
|
|
37
|
+
* NotFoundError: (e) => `Missing: ${e.resource} ${e.id}`,
|
|
38
|
+
* ValidationError: (e) => `Invalid ${e.field}: ${e.reason}`,
|
|
39
|
+
* });
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
/**
|
|
43
|
+
* Options for Error constructor (compatible with ES2022 ErrorOptions).
|
|
44
|
+
*/
|
|
45
|
+
interface TaggedErrorOptions {
|
|
46
|
+
cause?: unknown;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Options for TaggedError factory with type-safe message callback.
|
|
50
|
+
*/
|
|
51
|
+
interface TaggedErrorCreateOptions<Props extends Record<string, unknown>> {
|
|
52
|
+
/** Custom message generator from props. Annotate parameter for type safety. */
|
|
53
|
+
message: (props: Props) => string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Base interface for all tagged errors.
|
|
57
|
+
*/
|
|
58
|
+
interface TaggedErrorBase extends Error {
|
|
59
|
+
readonly _tag: string;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Instance type for factory-created TaggedErrors.
|
|
63
|
+
*/
|
|
64
|
+
type TaggedErrorInstance<Tag extends string, Props> = TaggedErrorBase & {
|
|
65
|
+
readonly _tag: Tag;
|
|
66
|
+
} & Readonly<Props>;
|
|
67
|
+
/**
|
|
68
|
+
* Constructor args type - conditionally optional based on whether Props has required fields.
|
|
69
|
+
* - If Props is empty or all properties are optional: props argument is optional
|
|
70
|
+
* - If Props has any required properties: props argument is required
|
|
71
|
+
* @internal
|
|
72
|
+
*/
|
|
73
|
+
type ConstructorArgs<Props extends Record<string, unknown>> = {} extends Props ? [props?: Props | void, options?: TaggedErrorOptions] : [props: Props, options?: TaggedErrorOptions];
|
|
74
|
+
/**
|
|
75
|
+
* Constructor type returned by TaggedError factory.
|
|
76
|
+
*/
|
|
77
|
+
interface TaggedErrorConstructor<Tag extends string, Props extends Record<string, unknown>> {
|
|
78
|
+
new (...args: ConstructorArgs<Props>): TaggedErrorInstance<Tag, Props>;
|
|
79
|
+
readonly prototype: TaggedErrorInstance<Tag, Props>;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Generic class factory type that allows `<Props>` parameterization.
|
|
83
|
+
* This enables the Effect.js-style syntax: `class X extends TaggedError("X")<Props> {}`
|
|
84
|
+
* @internal
|
|
85
|
+
*/
|
|
86
|
+
interface TaggedErrorClassFactory<Tag extends string> {
|
|
87
|
+
new <Props extends Record<string, unknown> = Record<string, never>>(...args: ConstructorArgs<Props>): TaggedErrorInstance<Tag, Props>;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Helper type to extract return type from a function type.
|
|
91
|
+
* @internal
|
|
92
|
+
*/
|
|
93
|
+
type FnReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
|
|
94
|
+
/**
|
|
95
|
+
* Helper type to get union of return types from all handlers.
|
|
96
|
+
* @internal
|
|
97
|
+
*/
|
|
98
|
+
type HandlersReturnType<H> = {
|
|
99
|
+
[K in keyof H]: FnReturnType<H[K]>;
|
|
100
|
+
}[keyof H];
|
|
101
|
+
/**
|
|
102
|
+
* Helper type to extract keys whose values are definitely functions (not undefined).
|
|
103
|
+
* Only excludes a tag from the fallback type if its handler is guaranteed to be
|
|
104
|
+
* a function. Keys where the value type includes undefined are NOT excluded,
|
|
105
|
+
* ensuring type safety with dynamic/conditional handlers.
|
|
106
|
+
* @internal
|
|
107
|
+
*/
|
|
108
|
+
type DefinitelyHandledKeys<H> = {
|
|
109
|
+
[K in keyof H]-?: undefined extends H[K] ? never : K;
|
|
110
|
+
}[keyof H];
|
|
111
|
+
/**
|
|
112
|
+
* Factory function to create tagged error classes.
|
|
113
|
+
*
|
|
114
|
+
* Two usage patterns:
|
|
115
|
+
*
|
|
116
|
+
* 1. **Props via generic** (default message is tag name):
|
|
117
|
+
* ```typescript
|
|
118
|
+
* class NotFoundError extends TaggedError("NotFoundError")<{ id: string }> {}
|
|
119
|
+
* ```
|
|
120
|
+
*
|
|
121
|
+
* 2. **Props inferred from message callback** (type-safe message):
|
|
122
|
+
* ```typescript
|
|
123
|
+
* class NotFoundError extends TaggedError("NotFoundError", {
|
|
124
|
+
* message: (p: { id: string }) => `Not found: ${p.id}`,
|
|
125
|
+
* }) {}
|
|
126
|
+
* ```
|
|
127
|
+
*
|
|
128
|
+
* Both support `instanceof TaggedError` checks at runtime.
|
|
129
|
+
*
|
|
130
|
+
* @param tag - The unique tag string for this error type
|
|
131
|
+
* @param options - Optional configuration with message generator (annotate param for type safety)
|
|
132
|
+
* @returns A class constructor that can be extended
|
|
133
|
+
*/
|
|
134
|
+
declare function TaggedError<Tag extends string>(tag: Tag): TaggedErrorClassFactory<Tag>;
|
|
135
|
+
declare function TaggedError<Tag extends string, Props extends Record<string, unknown>>(tag: Tag, options: TaggedErrorCreateOptions<Props>): TaggedErrorConstructor<Tag, Props>;
|
|
136
|
+
/**
|
|
137
|
+
* Namespace for static methods on TaggedError.
|
|
138
|
+
*/
|
|
139
|
+
declare namespace TaggedError {
|
|
140
|
+
/**
|
|
141
|
+
* Type guard to check if a value is an Error instance.
|
|
142
|
+
*/
|
|
143
|
+
function isError(value: unknown): value is Error;
|
|
144
|
+
/**
|
|
145
|
+
* Type guard to check if a value is a TaggedError instance.
|
|
146
|
+
* Uses the same check as `instanceof TaggedError` - only genuine
|
|
147
|
+
* TaggedError instances (created via the factory) pass this guard.
|
|
148
|
+
*/
|
|
149
|
+
function isTaggedError(value: unknown): value is TaggedErrorBase;
|
|
150
|
+
/**
|
|
151
|
+
* Exhaustively matches on a tagged error, requiring handlers for all variants.
|
|
152
|
+
*
|
|
153
|
+
* TypeScript will error if any variant in the error union is not handled.
|
|
154
|
+
*
|
|
155
|
+
* @param error - The tagged error to match
|
|
156
|
+
* @param handlers - Object mapping _tag values to handler functions
|
|
157
|
+
* @returns The return value of the matched handler
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```typescript
|
|
161
|
+
* type AppError = NotFoundError | ValidationError;
|
|
162
|
+
*
|
|
163
|
+
* const message = TaggedError.match(error, {
|
|
164
|
+
* NotFoundError: (e) => `Not found: ${e.id}`,
|
|
165
|
+
* ValidationError: (e) => `Invalid: ${e.field}`,
|
|
166
|
+
* });
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
function match<E extends TaggedErrorBase, H extends {
|
|
170
|
+
[K in E["_tag"]]: (e: Extract<E, {
|
|
171
|
+
_tag: K;
|
|
172
|
+
}>) => unknown;
|
|
173
|
+
}>(error: E, handlers: H): HandlersReturnType<H>;
|
|
174
|
+
/**
|
|
175
|
+
* Partially matches on a tagged error with a fallback for unhandled variants.
|
|
176
|
+
*
|
|
177
|
+
* The fallback receives variants that are NOT definitely handled. A tag is
|
|
178
|
+
* considered "definitely handled" only if its handler is a function (not
|
|
179
|
+
* `undefined`). This ensures type safety even with dynamic/conditional handlers:
|
|
180
|
+
*
|
|
181
|
+
* ```typescript
|
|
182
|
+
* const maybeHandle = featureFlag ? (e) => e.id : undefined;
|
|
183
|
+
* TaggedError.matchPartial(
|
|
184
|
+
* error,
|
|
185
|
+
* { NotFoundError: maybeHandle }, // maybeHandle might be undefined
|
|
186
|
+
* (e) => e._tag // e correctly includes NotFoundError
|
|
187
|
+
* );
|
|
188
|
+
* ```
|
|
189
|
+
*
|
|
190
|
+
* @param error - The tagged error to match
|
|
191
|
+
* @param handlers - Partial object mapping _tag values to handler functions
|
|
192
|
+
* @param otherwise - Fallback handler for unmatched variants
|
|
193
|
+
* @returns The return value of the matched handler or fallback
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```typescript
|
|
197
|
+
* const message = TaggedError.matchPartial(
|
|
198
|
+
* error,
|
|
199
|
+
* { NotFoundError: (e) => `Not found: ${e.id}` },
|
|
200
|
+
* (e) => `Other error: ${e.message}`
|
|
201
|
+
* );
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
function matchPartial<E extends TaggedErrorBase, H extends Partial<{
|
|
205
|
+
[K in E["_tag"]]: (e: Extract<E, {
|
|
206
|
+
_tag: K;
|
|
207
|
+
}>) => unknown;
|
|
208
|
+
}>, T>(error: E, handlers: H, otherwise: (e: Exclude<E, {
|
|
209
|
+
_tag: DefinitelyHandledKeys<H>;
|
|
210
|
+
}>) => T): HandlersReturnType<H> | T;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Helper type to extract the _tag literal type from a TaggedError.
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* ```typescript
|
|
218
|
+
* class MyError extends TaggedError("MyError")<{ id: string }> {}
|
|
219
|
+
* type Tag = TagOf<MyError>; // "MyError"
|
|
220
|
+
* ```
|
|
221
|
+
*/
|
|
222
|
+
type TagOf<E extends TaggedErrorBase> = E["_tag"];
|
|
223
|
+
/**
|
|
224
|
+
* Helper type to extract a specific variant from a TaggedError union by tag.
|
|
225
|
+
*
|
|
226
|
+
* @example
|
|
227
|
+
* ```typescript
|
|
228
|
+
* type AppError = NotFoundError | ValidationError;
|
|
229
|
+
* type NotFound = ErrorByTag<AppError, "NotFoundError">; // NotFoundError
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
type ErrorByTag<E extends TaggedErrorBase, Tag extends E["_tag"]> = Extract<E, {
|
|
233
|
+
_tag: Tag;
|
|
234
|
+
}>;
|
|
235
|
+
/**
|
|
236
|
+
* Reserved keys that are stripped from user props at runtime.
|
|
237
|
+
* These keys cannot be used as user-defined properties:
|
|
238
|
+
* - _tag: discriminant for pattern matching
|
|
239
|
+
* - name, message, stack: Error internals (preserved for logging/debugging)
|
|
240
|
+
*
|
|
241
|
+
* Note: 'cause' is NOT reserved - it can be used as a user prop.
|
|
242
|
+
*/
|
|
243
|
+
type ReservedErrorKeys = "_tag" | "name" | "message" | "stack";
|
|
244
|
+
/**
|
|
245
|
+
* Helper type to extract props from a TaggedError.
|
|
246
|
+
* Excludes reserved keys that are stripped at runtime.
|
|
247
|
+
*
|
|
248
|
+
* @example
|
|
249
|
+
* ```typescript
|
|
250
|
+
* class MyError extends TaggedError("MyError")<{ id: string }> {}
|
|
251
|
+
* type Props = PropsOf<MyError>; // { id: string }
|
|
252
|
+
*
|
|
253
|
+
* // 'cause' is allowed as a user prop
|
|
254
|
+
* class DomainError extends TaggedError("DomainError")<{ cause: { field: string } }> {}
|
|
255
|
+
* type DomainProps = PropsOf<DomainError>; // { cause: { field: string } }
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
type PropsOf<E extends TaggedErrorBase> = Omit<E, ReservedErrorKeys>;
|
|
6
259
|
|
|
7
260
|
/**
|
|
8
261
|
* @jagreehal/workflow/conditional
|
|
@@ -35,7 +288,7 @@ type ConditionalOptions = {
|
|
|
35
288
|
/**
|
|
36
289
|
* Context for conditional execution, used to emit events.
|
|
37
290
|
*/
|
|
38
|
-
type ConditionalContext = {
|
|
291
|
+
type ConditionalContext<C = unknown> = {
|
|
39
292
|
/**
|
|
40
293
|
* The workflow ID for event emission.
|
|
41
294
|
*/
|
|
@@ -43,7 +296,12 @@ type ConditionalContext = {
|
|
|
43
296
|
/**
|
|
44
297
|
* Event emitter function.
|
|
45
298
|
*/
|
|
46
|
-
onEvent?: (event: WorkflowEvent<unknown>) => void;
|
|
299
|
+
onEvent?: (event: WorkflowEvent<unknown, C>) => void;
|
|
300
|
+
/**
|
|
301
|
+
* Optional context value to include in emitted events.
|
|
302
|
+
* When provided, this context is automatically added to step_skipped events.
|
|
303
|
+
*/
|
|
304
|
+
context?: C;
|
|
47
305
|
};
|
|
48
306
|
/**
|
|
49
307
|
* Type for operations that can be either sync or async.
|
|
@@ -82,11 +340,11 @@ type Operation<T> = () => MaybeAsync<T>;
|
|
|
82
340
|
* });
|
|
83
341
|
* ```
|
|
84
342
|
*/
|
|
85
|
-
declare function when<T>(condition: boolean, operation: Operation<T>, options?: ConditionalOptions, ctx?: ConditionalContext): Promise<T | undefined>;
|
|
343
|
+
declare function when<T, C = unknown>(condition: boolean, operation: Operation<T>, options?: ConditionalOptions, ctx?: ConditionalContext<C>): Promise<T | undefined>;
|
|
86
344
|
/**
|
|
87
345
|
* Synchronous overload for when the operation returns a non-Promise value.
|
|
88
346
|
*/
|
|
89
|
-
declare function when<T>(condition: boolean, operation: () => T, options?: ConditionalOptions, ctx?: ConditionalContext): T | undefined | Promise<T | undefined>;
|
|
347
|
+
declare function when<T, C = unknown>(condition: boolean, operation: () => T, options?: ConditionalOptions, ctx?: ConditionalContext<C>): T | undefined | Promise<T | undefined>;
|
|
90
348
|
/**
|
|
91
349
|
* Run a step only if condition is false, return undefined if skipped.
|
|
92
350
|
*
|
|
@@ -115,11 +373,11 @@ declare function when<T>(condition: boolean, operation: () => T, options?: Condi
|
|
|
115
373
|
* });
|
|
116
374
|
* ```
|
|
117
375
|
*/
|
|
118
|
-
declare function unless<T>(condition: boolean, operation: Operation<T>, options?: ConditionalOptions, ctx?: ConditionalContext): Promise<T | undefined>;
|
|
376
|
+
declare function unless<T, C = unknown>(condition: boolean, operation: Operation<T>, options?: ConditionalOptions, ctx?: ConditionalContext<C>): Promise<T | undefined>;
|
|
119
377
|
/**
|
|
120
378
|
* Synchronous overload for unless when the operation returns a non-Promise value.
|
|
121
379
|
*/
|
|
122
|
-
declare function unless<T>(condition: boolean, operation: () => T, options?: ConditionalOptions, ctx?: ConditionalContext): T | undefined | Promise<T | undefined>;
|
|
380
|
+
declare function unless<T, C = unknown>(condition: boolean, operation: () => T, options?: ConditionalOptions, ctx?: ConditionalContext<C>): T | undefined | Promise<T | undefined>;
|
|
123
381
|
/**
|
|
124
382
|
* Run a step only if condition is true, return default value if skipped.
|
|
125
383
|
*
|
|
@@ -150,11 +408,11 @@ declare function unless<T>(condition: boolean, operation: () => T, options?: Con
|
|
|
150
408
|
* });
|
|
151
409
|
* ```
|
|
152
410
|
*/
|
|
153
|
-
declare function whenOr<T, D>(condition: boolean, operation: Operation<T>, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext): Promise<T | D>;
|
|
411
|
+
declare function whenOr<T, D, C = unknown>(condition: boolean, operation: Operation<T>, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext<C>): Promise<T | D>;
|
|
154
412
|
/**
|
|
155
413
|
* Synchronous overload for whenOr when the operation returns a non-Promise value.
|
|
156
414
|
*/
|
|
157
|
-
declare function whenOr<T, D>(condition: boolean, operation: () => T, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext): T | D | Promise<T | D>;
|
|
415
|
+
declare function whenOr<T, D, C = unknown>(condition: boolean, operation: () => T, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext<C>): T | D | Promise<T | D>;
|
|
158
416
|
/**
|
|
159
417
|
* Run a step only if condition is false, return default value if skipped.
|
|
160
418
|
*
|
|
@@ -185,24 +443,25 @@ declare function whenOr<T, D>(condition: boolean, operation: () => T, defaultVal
|
|
|
185
443
|
* });
|
|
186
444
|
* ```
|
|
187
445
|
*/
|
|
188
|
-
declare function unlessOr<T, D>(condition: boolean, operation: Operation<T>, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext): Promise<T | D>;
|
|
446
|
+
declare function unlessOr<T, D, C = unknown>(condition: boolean, operation: Operation<T>, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext<C>): Promise<T | D>;
|
|
189
447
|
/**
|
|
190
448
|
* Synchronous overload for unlessOr when the operation returns a non-Promise value.
|
|
191
449
|
*/
|
|
192
|
-
declare function unlessOr<T, D>(condition: boolean, operation: () => T, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext): T | D | Promise<T | D>;
|
|
450
|
+
declare function unlessOr<T, D, C = unknown>(condition: boolean, operation: () => T, defaultValue: D, options?: ConditionalOptions, ctx?: ConditionalContext<C>): T | D | Promise<T | D>;
|
|
193
451
|
/**
|
|
194
452
|
* Create a set of conditional helpers bound to a workflow context.
|
|
195
453
|
*
|
|
196
454
|
* Use this factory when you want to automatically emit step_skipped events
|
|
197
455
|
* to the workflow's event stream without passing context manually.
|
|
198
456
|
*
|
|
199
|
-
* @param ctx - The workflow context containing workflowId and
|
|
457
|
+
* @param ctx - The workflow context containing workflowId, onEvent, and optional context
|
|
200
458
|
* @returns Object with bound when, unless, whenOr, and unlessOr functions
|
|
201
459
|
*
|
|
202
460
|
* @example
|
|
203
461
|
* ```typescript
|
|
462
|
+
* // With run() - context is automatically included in events
|
|
204
463
|
* const result = await run(async (step) => {
|
|
205
|
-
* const ctx = { workflowId, onEvent };
|
|
464
|
+
* const ctx = { workflowId, onEvent, context: requestContext };
|
|
206
465
|
* const { when, whenOr } = createConditionalHelpers(ctx);
|
|
207
466
|
*
|
|
208
467
|
* const user = await step(fetchUser(id));
|
|
@@ -214,10 +473,18 @@ declare function unlessOr<T, D>(condition: boolean, operation: () => T, defaultV
|
|
|
214
473
|
* );
|
|
215
474
|
*
|
|
216
475
|
* return { user, premium };
|
|
217
|
-
* }, { onEvent, workflowId });
|
|
476
|
+
* }, { onEvent, workflowId, context: requestContext });
|
|
477
|
+
*
|
|
478
|
+
* // With createWorkflow - access context from onEvent callback
|
|
479
|
+
* const workflow = createWorkflow({ fetchUser }, {
|
|
480
|
+
* createContext: () => ({ requestId: 'req-123' }),
|
|
481
|
+
* onEvent: (event, ctx) => {
|
|
482
|
+
* // ctx is available here, can be passed to conditional helpers
|
|
483
|
+
* }
|
|
484
|
+
* });
|
|
218
485
|
* ```
|
|
219
486
|
*/
|
|
220
|
-
declare function createConditionalHelpers(ctx: ConditionalContext): {
|
|
487
|
+
declare function createConditionalHelpers<C = unknown>(ctx: ConditionalContext<C>): {
|
|
221
488
|
/**
|
|
222
489
|
* Run a step only if condition is true, return undefined if skipped.
|
|
223
490
|
*/
|
|
@@ -3263,4 +3530,4 @@ declare function errOutcome<E>(error: E): ScriptedOutcome<never, E>;
|
|
|
3263
3530
|
*/
|
|
3264
3531
|
declare function throwOutcome(error: unknown): ScriptedOutcome<never, never>;
|
|
3265
3532
|
|
|
3266
|
-
export { AnyResultFn$1 as AnyResultFn, type ApprovalStatus, type ApprovalStore, type ApprovalWebhookRequest, type ApprovalWebhookResponse, type AssertionResult, AsyncResult, type AutotelAdapter, type AutotelAdapterConfig, type AutotelMetrics, type AutotelTraceFn, type CircuitBreaker, type CircuitBreakerConfig, type CircuitBreakerStats, CircuitOpenError, type CircuitState, type CombinedLimiterConfig, type CompensationAction, type ConcurrencyLimiter, type ConcurrencyLimiterConfig, type ConcurrencyLimiterStats, type ConditionalContext, type ConditionalOptions, type Devtools, type DevtoolsOptions, type ErrorMapping, type ErrorResponseBody, ErrorsOfDeps$1 as ErrorsOfDeps, type EventHandler, type EventMessage, type EventProcessingResult, type EventTriggerConfig, type ExpressLikeRequest, type ExpressLikeResponse, type FileCacheOptions, type FileSystemInterface, type HITLExecutionResult, type HITLOrchestrator, type HITLOrchestratorOptions, type HITLWorkflowFactoryOptions, type KVCacheOptions, type KeyValueStore, type MemoryCacheOptions, type MigrationError, type MigrationFn, type Migrations, type MockFunction, type MockStep, type NamedPolicy, type Policy, type PolicyFactory, type PolicyRegistry, type PollerOptions, type QueueFullError, type RateLimitExceededError, type RateLimiter, type RateLimiterConfig, type RateLimiterStats, Result, ResumeState, ResumeStateEntry, RetryOptions, type RunDiff, type SagaCompensationError, type SagaContext, type SagaEvent, type SagaResult, type SagaStepOptions, type SagaWorkflowOptions, type SavedWorkflowState, type ScriptedOutcome, type SerializedCause, type SerializedEntry, type SerializedMeta, type SerializedResult, type SerializedState, type SimpleHandlerConfig, type StatePersistence, StepCache, type StepDiff, type StepInvocation, StepOptions, type StepOptionsBuilder, type TestHarnessOptions, type TimelineEntry, TimeoutOptions, UnexpectedError, type ValidationError, type ValidationResult, type Version, type VersionIncompatibleError, type VersionedState, type VersionedWorkflowConfig, type WebhookHandler, type WebhookHandlerConfig, type WebhookRequest, type WebhookResponse, type WithPoliciesOptions, Workflow, WorkflowEvent, type WorkflowHarness, type WorkflowRun, type WorkflowSnapshot, type WorkflowStateStore, WorkflowStrict, circuitBreakerPresets, compareSnapshots, composeMigrations, composeValidators, conditionalPolicy, createApprovalChecker, createApprovalWebhookHandler, createAutotelAdapter, createAutotelEventHandler, createCircuitBreaker, createCombinedLimiter, createConcurrencyLimiter, createConditionalHelpers, createConsoleLogger, createDevtools, createEventHandler, createExpressHandler, createFileCache, createHITLOrchestrator, createHydratingCache, createKVCache, createKeyRemoveMigration, createKeyRenameMigration, createMemoryApprovalStore, createMemoryCache, createMemoryWorkflowStateStore, createMockFn, createPolicyApplier, createPolicyBundle, createPolicyRegistry, createRateLimiter, createResultMapper, createSagaWorkflow, createSimpleHandler, createSnapshot, createStatePersistence, createTestClock, createValueTransformMigration, createVersionedState, createVersionedStateLoader, createWebhookHandler, createWorkflowHarness, defaultUnexpectedErrorMapper, defaultValidationErrorMapper, deserializeCause, deserializeEntry, deserializeMeta, deserializeResult, deserializeState, envPolicy, errOutcome, isCircuitOpenError, isMigrationError, isQueueFullError, isRateLimitExceededError, isSagaCompensationError, isValidationError, isVersionIncompatibleError, mergePolicies, migrateState, okOutcome, parseState, parseVersionedState, quickVisualize, rateLimiterPresets, renderDiff, requireFields, retryPolicies, retryPolicy, runSaga, sendWebhookResponse, serializeCause, serializeEntry, serializeMeta, serializeResult, serializeState, servicePolicies, stepOptions, stringifyState, stringifyVersionedState, throwOutcome, timeoutPolicies, timeoutPolicy, toWebhookRequest, unless, unlessOr, validationError, when, whenOr, withAutotelTracing, withPolicies, withPolicy };
|
|
3533
|
+
export { AnyResultFn$1 as AnyResultFn, type ApprovalStatus, type ApprovalStore, type ApprovalWebhookRequest, type ApprovalWebhookResponse, type AssertionResult, AsyncResult, type AutotelAdapter, type AutotelAdapterConfig, type AutotelMetrics, type AutotelTraceFn, type CircuitBreaker, type CircuitBreakerConfig, type CircuitBreakerStats, CircuitOpenError, type CircuitState, type CombinedLimiterConfig, type CompensationAction, type ConcurrencyLimiter, type ConcurrencyLimiterConfig, type ConcurrencyLimiterStats, type ConditionalContext, type ConditionalOptions, type Devtools, type DevtoolsOptions, type ErrorByTag, type ErrorMapping, type ErrorResponseBody, ErrorsOfDeps$1 as ErrorsOfDeps, type EventHandler, type EventMessage, type EventProcessingResult, type EventTriggerConfig, type ExpressLikeRequest, type ExpressLikeResponse, type FileCacheOptions, type FileSystemInterface, type HITLExecutionResult, type HITLOrchestrator, type HITLOrchestratorOptions, type HITLWorkflowFactoryOptions, type KVCacheOptions, type KeyValueStore, type MemoryCacheOptions, type MigrationError, type MigrationFn, type Migrations, type MockFunction, type MockStep, type NamedPolicy, type Policy, type PolicyFactory, type PolicyRegistry, type PollerOptions, type PropsOf, type QueueFullError, type RateLimitExceededError, type RateLimiter, type RateLimiterConfig, type RateLimiterStats, Result, ResumeState, ResumeStateEntry, RetryOptions, type RunDiff, type SagaCompensationError, type SagaContext, type SagaEvent, type SagaResult, type SagaStepOptions, type SagaWorkflowOptions, type SavedWorkflowState, type ScriptedOutcome, type SerializedCause, type SerializedEntry, type SerializedMeta, type SerializedResult, type SerializedState, type SimpleHandlerConfig, type StatePersistence, StepCache, type StepDiff, type StepInvocation, StepOptions, type StepOptionsBuilder, type TagOf, TaggedError, type TaggedErrorBase, type TaggedErrorConstructor, type TaggedErrorCreateOptions, type TaggedErrorOptions, type TestHarnessOptions, type TimelineEntry, TimeoutOptions, UnexpectedError, type ValidationError, type ValidationResult, type Version, type VersionIncompatibleError, type VersionedState, type VersionedWorkflowConfig, type WebhookHandler, type WebhookHandlerConfig, type WebhookRequest, type WebhookResponse, type WithPoliciesOptions, Workflow, WorkflowEvent, type WorkflowHarness, type WorkflowRun, type WorkflowSnapshot, type WorkflowStateStore, WorkflowStrict, circuitBreakerPresets, compareSnapshots, composeMigrations, composeValidators, conditionalPolicy, createApprovalChecker, createApprovalWebhookHandler, createAutotelAdapter, createAutotelEventHandler, createCircuitBreaker, createCombinedLimiter, createConcurrencyLimiter, createConditionalHelpers, createConsoleLogger, createDevtools, createEventHandler, createExpressHandler, createFileCache, createHITLOrchestrator, createHydratingCache, createKVCache, createKeyRemoveMigration, createKeyRenameMigration, createMemoryApprovalStore, createMemoryCache, createMemoryWorkflowStateStore, createMockFn, createPolicyApplier, createPolicyBundle, createPolicyRegistry, createRateLimiter, createResultMapper, createSagaWorkflow, createSimpleHandler, createSnapshot, createStatePersistence, createTestClock, createValueTransformMigration, createVersionedState, createVersionedStateLoader, createWebhookHandler, createWorkflowHarness, defaultUnexpectedErrorMapper, defaultValidationErrorMapper, deserializeCause, deserializeEntry, deserializeMeta, deserializeResult, deserializeState, envPolicy, errOutcome, isCircuitOpenError, isMigrationError, isQueueFullError, isRateLimitExceededError, isSagaCompensationError, isValidationError, isVersionIncompatibleError, mergePolicies, migrateState, okOutcome, parseState, parseVersionedState, quickVisualize, rateLimiterPresets, renderDiff, requireFields, retryPolicies, retryPolicy, runSaga, sendWebhookResponse, serializeCause, serializeEntry, serializeMeta, serializeResult, serializeState, servicePolicies, stepOptions, stringifyState, stringifyVersionedState, throwOutcome, timeoutPolicies, timeoutPolicy, toWebhookRequest, unless, unlessOr, validationError, when, whenOr, withAutotelTracing, withPolicies, withPolicy };
|