awaitly 1.35.0 → 2.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.
- package/dist/{duration.d.ts → di-BDlT7InM.d.cts} +15 -1
- package/dist/{duration.d.cts → di-BbFFfO8y.d.ts} +15 -1
- package/dist/errors-DtXvrCiO.d.cts +708 -0
- package/dist/errors-DtXvrCiO.d.ts +708 -0
- package/dist/index.cjs +4594 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1970 -141
- package/dist/index.d.ts +1970 -141
- package/dist/index.js +4398 -1
- package/dist/index.js.map +1 -1
- package/dist/result.cjs +641 -1
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +29 -4
- package/dist/result.d.ts +29 -4
- package/dist/result.js +561 -1
- package/dist/result.js.map +1 -1
- package/dist/testing.cjs +4202 -8
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +2 -6
- package/dist/testing.d.ts +2 -6
- package/dist/testing.js +4154 -8
- package/dist/testing.js.map +1 -1
- package/dist/{run-entry-DGs0tySr.d.cts → types-B8NfNRGX.d.ts} +1078 -1502
- package/dist/{run-entry-BOuNyVoO.d.ts → types-BZ2f4MRR.d.cts} +1078 -1502
- package/dist/workflow.cjs +7096 -6
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +3346 -22
- package/dist/workflow.d.ts +3346 -22
- package/dist/workflow.js +6929 -6
- package/dist/workflow.js.map +1 -1
- package/package.json +3 -168
- package/dist/adapters.cjs +0 -7
- package/dist/adapters.cjs.map +0 -1
- package/dist/adapters.d.cts +0 -179
- package/dist/adapters.d.ts +0 -179
- package/dist/adapters.js +0 -7
- package/dist/adapters.js.map +0 -1
- package/dist/batch.cjs +0 -7
- package/dist/batch.cjs.map +0 -1
- package/dist/batch.d.cts +0 -200
- package/dist/batch.d.ts +0 -200
- package/dist/batch.js +0 -7
- package/dist/batch.js.map +0 -1
- package/dist/bind-deps.cjs +0 -2
- package/dist/bind-deps.cjs.map +0 -1
- package/dist/bind-deps.d.cts +0 -28
- package/dist/bind-deps.d.ts +0 -28
- package/dist/bind-deps.js +0 -2
- package/dist/bind-deps.js.map +0 -1
- package/dist/cache.cjs +0 -2
- package/dist/cache.cjs.map +0 -1
- package/dist/cache.d.cts +0 -269
- package/dist/cache.d.ts +0 -269
- package/dist/cache.js +0 -2
- package/dist/cache.js.map +0 -1
- package/dist/circuit-breaker.cjs +0 -7
- package/dist/circuit-breaker.cjs.map +0 -1
- package/dist/circuit-breaker.d.cts +0 -211
- package/dist/circuit-breaker.d.ts +0 -211
- package/dist/circuit-breaker.js +0 -7
- package/dist/circuit-breaker.js.map +0 -1
- package/dist/conditional.cjs +0 -2
- package/dist/conditional.cjs.map +0 -1
- package/dist/conditional.d.cts +0 -252
- package/dist/conditional.d.ts +0 -252
- package/dist/conditional.js +0 -2
- package/dist/conditional.js.map +0 -1
- package/dist/core.cjs +0 -7
- package/dist/core.cjs.map +0 -1
- package/dist/core.d.cts +0 -5
- package/dist/core.d.ts +0 -5
- package/dist/core.js +0 -7
- package/dist/core.js.map +0 -1
- package/dist/di-By77n4Fa.d.ts +0 -15
- package/dist/di-OJfsohf-.d.cts +0 -15
- package/dist/diagnostics.cjs +0 -8
- package/dist/diagnostics.cjs.map +0 -1
- package/dist/diagnostics.d.cts +0 -68
- package/dist/diagnostics.d.ts +0 -68
- package/dist/diagnostics.js +0 -8
- package/dist/diagnostics.js.map +0 -1
- package/dist/durable.cjs +0 -11
- package/dist/durable.cjs.map +0 -1
- package/dist/durable.d.cts +0 -9
- package/dist/durable.d.ts +0 -9
- package/dist/durable.js +0 -11
- package/dist/durable.js.map +0 -1
- package/dist/duration.cjs +0 -2
- package/dist/duration.cjs.map +0 -1
- package/dist/duration.js +0 -2
- package/dist/duration.js.map +0 -1
- package/dist/engine.cjs +0 -11
- package/dist/engine.cjs.map +0 -1
- package/dist/engine.d.cts +0 -115
- package/dist/engine.d.ts +0 -115
- package/dist/engine.js +0 -11
- package/dist/engine.js.map +0 -1
- package/dist/errors.cjs +0 -2
- package/dist/errors.cjs.map +0 -1
- package/dist/errors.d.cts +0 -361
- package/dist/errors.d.ts +0 -361
- package/dist/errors.js +0 -2
- package/dist/errors.js.map +0 -1
- package/dist/fetch.cjs +0 -7
- package/dist/fetch.cjs.map +0 -1
- package/dist/fetch.d.cts +0 -86
- package/dist/fetch.d.ts +0 -86
- package/dist/fetch.js +0 -7
- package/dist/fetch.js.map +0 -1
- package/dist/flow.cjs +0 -7
- package/dist/flow.cjs.map +0 -1
- package/dist/flow.d.cts +0 -163
- package/dist/flow.d.ts +0 -163
- package/dist/flow.js +0 -7
- package/dist/flow.js.map +0 -1
- package/dist/functional.cjs +0 -2
- package/dist/functional.cjs.map +0 -1
- package/dist/functional.d.cts +0 -444
- package/dist/functional.d.ts +0 -444
- package/dist/functional.js +0 -2
- package/dist/functional.js.map +0 -1
- package/dist/guards-4sV7mTqj.d.cts +0 -72
- package/dist/guards-BIX05ALH.d.ts +0 -72
- package/dist/hitl-DFn4Xa_l.d.cts +0 -468
- package/dist/hitl-DU5VpKq7.d.ts +0 -468
- package/dist/hitl.cjs +0 -7
- package/dist/hitl.cjs.map +0 -1
- package/dist/hitl.d.cts +0 -442
- package/dist/hitl.d.ts +0 -442
- package/dist/hitl.js +0 -7
- package/dist/hitl.js.map +0 -1
- package/dist/index-CnvBryQB.d.ts +0 -417
- package/dist/index-DEZEf8Fs.d.cts +0 -417
- package/dist/match-entry-DjI2bLpD.d.cts +0 -209
- package/dist/match-entry-DjI2bLpD.d.ts +0 -209
- package/dist/match.cjs +0 -2
- package/dist/match.cjs.map +0 -1
- package/dist/match.d.cts +0 -1
- package/dist/match.d.ts +0 -1
- package/dist/match.js +0 -2
- package/dist/match.js.map +0 -1
- package/dist/otel.cjs +0 -2
- package/dist/otel.cjs.map +0 -1
- package/dist/otel.d.cts +0 -188
- package/dist/otel.d.ts +0 -188
- package/dist/otel.js +0 -2
- package/dist/otel.js.map +0 -1
- package/dist/persistence-entry-B-8PjnSR.d.cts +0 -831
- package/dist/persistence-entry-D8zRkLiT.d.ts +0 -831
- package/dist/persistence.cjs +0 -2
- package/dist/persistence.cjs.map +0 -1
- package/dist/persistence.d.cts +0 -7
- package/dist/persistence.d.ts +0 -7
- package/dist/persistence.js +0 -2
- package/dist/persistence.js.map +0 -1
- package/dist/policies.cjs +0 -2
- package/dist/policies.cjs.map +0 -1
- package/dist/policies.d.cts +0 -379
- package/dist/policies.d.ts +0 -379
- package/dist/policies.js +0 -2
- package/dist/policies.js.map +0 -1
- package/dist/ratelimit.cjs +0 -7
- package/dist/ratelimit.cjs.map +0 -1
- package/dist/ratelimit.d.cts +0 -458
- package/dist/ratelimit.d.ts +0 -458
- package/dist/ratelimit.js +0 -7
- package/dist/ratelimit.js.map +0 -1
- package/dist/reliability.cjs +0 -11
- package/dist/reliability.cjs.map +0 -1
- package/dist/reliability.d.cts +0 -11
- package/dist/reliability.d.ts +0 -11
- package/dist/reliability.js +0 -11
- package/dist/reliability.js.map +0 -1
- package/dist/resolver.cjs +0 -7
- package/dist/resolver.cjs.map +0 -1
- package/dist/resolver.d.cts +0 -68
- package/dist/resolver.d.ts +0 -68
- package/dist/resolver.js +0 -7
- package/dist/resolver.js.map +0 -1
- package/dist/resource.cjs +0 -7
- package/dist/resource.cjs.map +0 -1
- package/dist/resource.d.cts +0 -174
- package/dist/resource.d.ts +0 -174
- package/dist/resource.js +0 -7
- package/dist/resource.js.map +0 -1
- package/dist/result/retry.cjs +0 -2
- package/dist/result/retry.cjs.map +0 -1
- package/dist/result/retry.d.cts +0 -70
- package/dist/result/retry.d.ts +0 -70
- package/dist/result/retry.js +0 -2
- package/dist/result/retry.js.map +0 -1
- package/dist/retry.cjs +0 -2
- package/dist/retry.cjs.map +0 -1
- package/dist/retry.d.cts +0 -388
- package/dist/retry.d.ts +0 -388
- package/dist/retry.js +0 -2
- package/dist/retry.js.map +0 -1
- package/dist/run.cjs +0 -7
- package/dist/run.cjs.map +0 -1
- package/dist/run.d.cts +0 -4
- package/dist/run.d.ts +0 -4
- package/dist/run.js +0 -7
- package/dist/run.js.map +0 -1
- package/dist/saga.cjs +0 -11
- package/dist/saga.cjs.map +0 -1
- package/dist/saga.d.cts +0 -164
- package/dist/saga.d.ts +0 -164
- package/dist/saga.js +0 -11
- package/dist/saga.js.map +0 -1
- package/dist/singleflight.cjs +0 -2
- package/dist/singleflight.cjs.map +0 -1
- package/dist/singleflight.d.cts +0 -145
- package/dist/singleflight.d.ts +0 -145
- package/dist/singleflight.js +0 -2
- package/dist/singleflight.js.map +0 -1
- package/dist/slugs.cjs +0 -2
- package/dist/slugs.cjs.map +0 -1
- package/dist/slugs.d.cts +0 -67
- package/dist/slugs.d.ts +0 -67
- package/dist/slugs.js +0 -2
- package/dist/slugs.js.map +0 -1
- package/dist/streaming.cjs +0 -9
- package/dist/streaming.cjs.map +0 -1
- package/dist/streaming.d.cts +0 -596
- package/dist/streaming.d.ts +0 -596
- package/dist/streaming.js +0 -9
- package/dist/streaming.js.map +0 -1
- package/dist/tagged-error.cjs +0 -2
- package/dist/tagged-error.cjs.map +0 -1
- package/dist/tagged-error.d.cts +0 -275
- package/dist/tagged-error.d.ts +0 -275
- package/dist/tagged-error.js +0 -2
- package/dist/tagged-error.js.map +0 -1
- package/dist/types-BziYHFkD.d.ts +0 -323
- package/dist/types-C5jLEUqY.d.cts +0 -323
- package/dist/webhook.cjs +0 -7
- package/dist/webhook.cjs.map +0 -1
- package/dist/webhook.d.cts +0 -499
- package/dist/webhook.d.ts +0 -499
- package/dist/webhook.js +0 -7
- package/dist/webhook.js.map +0 -1
package/dist/engine.d.cts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { S as SnapshotStore, A as AnyResultFn, b as WorkflowContext } from './persistence-entry-B-8PjnSR.cjs';
|
|
2
|
-
import { af as RunStep } from './run-entry-DGs0tySr.cjs';
|
|
3
|
-
import { b as DurableOptions } from './index-DEZEf8Fs.cjs';
|
|
4
|
-
import './types-C5jLEUqY.cjs';
|
|
5
|
-
import '@standard-schema/spec';
|
|
6
|
-
import './errors.cjs';
|
|
7
|
-
import './tagged-error.cjs';
|
|
8
|
-
import './slugs.cjs';
|
|
9
|
-
|
|
10
|
-
/** A registered workflow definition */
|
|
11
|
-
interface WorkflowRegistration<Deps extends Readonly<Record<string, AnyResultFn>> = Readonly<Record<string, AnyResultFn>>> {
|
|
12
|
-
/** Workflow dependencies (Result-returning functions) */
|
|
13
|
-
deps: Deps;
|
|
14
|
-
/** Workflow function */
|
|
15
|
-
fn: (context: {
|
|
16
|
-
step: RunStep<any>;
|
|
17
|
-
deps: Deps;
|
|
18
|
-
ctx: WorkflowContext;
|
|
19
|
-
}) => any;
|
|
20
|
-
/** Default durable options (version, lockTtlMs, etc.) */
|
|
21
|
-
durableDefaults?: Partial<Pick<DurableOptions, 'version' | 'lockTtlMs' | 'heartbeatIntervalMs'>>;
|
|
22
|
-
}
|
|
23
|
-
interface EnqueueOptions {
|
|
24
|
-
/** Custom workflow execution ID (default: auto-generated UUID) */
|
|
25
|
-
id?: string;
|
|
26
|
-
/** Idempotency key for deduplication */
|
|
27
|
-
idempotencyKey?: string;
|
|
28
|
-
/** Workflow input for idempotency conflict detection */
|
|
29
|
-
input?: unknown;
|
|
30
|
-
/** Custom metadata */
|
|
31
|
-
metadata?: Record<string, unknown>;
|
|
32
|
-
}
|
|
33
|
-
interface ScheduleOptions {
|
|
34
|
-
/** Repeat interval in milliseconds */
|
|
35
|
-
intervalMs: number;
|
|
36
|
-
/** Run immediately on schedule creation */
|
|
37
|
-
immediate?: boolean;
|
|
38
|
-
}
|
|
39
|
-
interface EngineOptions {
|
|
40
|
-
/** Snapshot store for workflow persistence */
|
|
41
|
-
store: SnapshotStore;
|
|
42
|
-
/** Registered workflows keyed by name */
|
|
43
|
-
workflows: Record<string, WorkflowRegistration>;
|
|
44
|
-
/** Max parallel workflow runs per tick (default: 5) */
|
|
45
|
-
concurrency?: number;
|
|
46
|
-
/** Event handler */
|
|
47
|
-
onEvent?: (event: EngineEvent) => void;
|
|
48
|
-
/** Error handler for background operations */
|
|
49
|
-
onError?: (error: unknown) => void;
|
|
50
|
-
}
|
|
51
|
-
type EngineEvent = {
|
|
52
|
-
type: "engine_start";
|
|
53
|
-
ts: number;
|
|
54
|
-
} | {
|
|
55
|
-
type: "engine_stop";
|
|
56
|
-
ts: number;
|
|
57
|
-
} | {
|
|
58
|
-
type: "engine_tick";
|
|
59
|
-
ts: number;
|
|
60
|
-
processed: number;
|
|
61
|
-
} | {
|
|
62
|
-
type: "workflow_enqueued";
|
|
63
|
-
workflowName: string;
|
|
64
|
-
id: string;
|
|
65
|
-
ts: number;
|
|
66
|
-
} | {
|
|
67
|
-
type: "workflow_started";
|
|
68
|
-
workflowName: string;
|
|
69
|
-
id: string;
|
|
70
|
-
ts: number;
|
|
71
|
-
} | {
|
|
72
|
-
type: "workflow_completed";
|
|
73
|
-
workflowName: string;
|
|
74
|
-
id: string;
|
|
75
|
-
ts: number;
|
|
76
|
-
} | {
|
|
77
|
-
type: "workflow_failed";
|
|
78
|
-
workflowName: string;
|
|
79
|
-
id: string;
|
|
80
|
-
error: unknown;
|
|
81
|
-
ts: number;
|
|
82
|
-
} | {
|
|
83
|
-
type: "schedule_created";
|
|
84
|
-
workflowName: string;
|
|
85
|
-
scheduleId: string;
|
|
86
|
-
intervalMs: number;
|
|
87
|
-
ts: number;
|
|
88
|
-
} | {
|
|
89
|
-
type: "schedule_removed";
|
|
90
|
-
scheduleId: string;
|
|
91
|
-
ts: number;
|
|
92
|
-
};
|
|
93
|
-
interface Engine {
|
|
94
|
-
/** Enqueue a workflow for execution. Returns the workflow execution ID. */
|
|
95
|
-
enqueue(name: string, options?: EnqueueOptions): Promise<string>;
|
|
96
|
-
/** Schedule recurring workflow execution. Returns the schedule ID. */
|
|
97
|
-
schedule(name: string, options: ScheduleOptions & EnqueueOptions): string;
|
|
98
|
-
/** Remove a schedule */
|
|
99
|
-
unschedule(scheduleId: string): boolean;
|
|
100
|
-
/** Start the polling loop */
|
|
101
|
-
start(pollIntervalMs?: number): void;
|
|
102
|
-
/** Stop the polling loop gracefully */
|
|
103
|
-
stop(): Promise<void>;
|
|
104
|
-
/** Execute a single tick manually (process pending workflows). Returns number processed. */
|
|
105
|
-
tick(): Promise<number>;
|
|
106
|
-
/** Get engine status */
|
|
107
|
-
status(): {
|
|
108
|
-
running: boolean;
|
|
109
|
-
pendingSchedules: number;
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
declare function createEngine(options: EngineOptions): Engine;
|
|
114
|
-
|
|
115
|
-
export { type Engine, type EngineEvent, type EngineOptions, type EnqueueOptions, type ScheduleOptions, type WorkflowRegistration, createEngine };
|
package/dist/engine.d.ts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { S as SnapshotStore, A as AnyResultFn, b as WorkflowContext } from './persistence-entry-D8zRkLiT.js';
|
|
2
|
-
import { af as RunStep } from './run-entry-BOuNyVoO.js';
|
|
3
|
-
import { b as DurableOptions } from './index-CnvBryQB.js';
|
|
4
|
-
import './types-BziYHFkD.js';
|
|
5
|
-
import '@standard-schema/spec';
|
|
6
|
-
import './errors.js';
|
|
7
|
-
import './tagged-error.js';
|
|
8
|
-
import './slugs.js';
|
|
9
|
-
|
|
10
|
-
/** A registered workflow definition */
|
|
11
|
-
interface WorkflowRegistration<Deps extends Readonly<Record<string, AnyResultFn>> = Readonly<Record<string, AnyResultFn>>> {
|
|
12
|
-
/** Workflow dependencies (Result-returning functions) */
|
|
13
|
-
deps: Deps;
|
|
14
|
-
/** Workflow function */
|
|
15
|
-
fn: (context: {
|
|
16
|
-
step: RunStep<any>;
|
|
17
|
-
deps: Deps;
|
|
18
|
-
ctx: WorkflowContext;
|
|
19
|
-
}) => any;
|
|
20
|
-
/** Default durable options (version, lockTtlMs, etc.) */
|
|
21
|
-
durableDefaults?: Partial<Pick<DurableOptions, 'version' | 'lockTtlMs' | 'heartbeatIntervalMs'>>;
|
|
22
|
-
}
|
|
23
|
-
interface EnqueueOptions {
|
|
24
|
-
/** Custom workflow execution ID (default: auto-generated UUID) */
|
|
25
|
-
id?: string;
|
|
26
|
-
/** Idempotency key for deduplication */
|
|
27
|
-
idempotencyKey?: string;
|
|
28
|
-
/** Workflow input for idempotency conflict detection */
|
|
29
|
-
input?: unknown;
|
|
30
|
-
/** Custom metadata */
|
|
31
|
-
metadata?: Record<string, unknown>;
|
|
32
|
-
}
|
|
33
|
-
interface ScheduleOptions {
|
|
34
|
-
/** Repeat interval in milliseconds */
|
|
35
|
-
intervalMs: number;
|
|
36
|
-
/** Run immediately on schedule creation */
|
|
37
|
-
immediate?: boolean;
|
|
38
|
-
}
|
|
39
|
-
interface EngineOptions {
|
|
40
|
-
/** Snapshot store for workflow persistence */
|
|
41
|
-
store: SnapshotStore;
|
|
42
|
-
/** Registered workflows keyed by name */
|
|
43
|
-
workflows: Record<string, WorkflowRegistration>;
|
|
44
|
-
/** Max parallel workflow runs per tick (default: 5) */
|
|
45
|
-
concurrency?: number;
|
|
46
|
-
/** Event handler */
|
|
47
|
-
onEvent?: (event: EngineEvent) => void;
|
|
48
|
-
/** Error handler for background operations */
|
|
49
|
-
onError?: (error: unknown) => void;
|
|
50
|
-
}
|
|
51
|
-
type EngineEvent = {
|
|
52
|
-
type: "engine_start";
|
|
53
|
-
ts: number;
|
|
54
|
-
} | {
|
|
55
|
-
type: "engine_stop";
|
|
56
|
-
ts: number;
|
|
57
|
-
} | {
|
|
58
|
-
type: "engine_tick";
|
|
59
|
-
ts: number;
|
|
60
|
-
processed: number;
|
|
61
|
-
} | {
|
|
62
|
-
type: "workflow_enqueued";
|
|
63
|
-
workflowName: string;
|
|
64
|
-
id: string;
|
|
65
|
-
ts: number;
|
|
66
|
-
} | {
|
|
67
|
-
type: "workflow_started";
|
|
68
|
-
workflowName: string;
|
|
69
|
-
id: string;
|
|
70
|
-
ts: number;
|
|
71
|
-
} | {
|
|
72
|
-
type: "workflow_completed";
|
|
73
|
-
workflowName: string;
|
|
74
|
-
id: string;
|
|
75
|
-
ts: number;
|
|
76
|
-
} | {
|
|
77
|
-
type: "workflow_failed";
|
|
78
|
-
workflowName: string;
|
|
79
|
-
id: string;
|
|
80
|
-
error: unknown;
|
|
81
|
-
ts: number;
|
|
82
|
-
} | {
|
|
83
|
-
type: "schedule_created";
|
|
84
|
-
workflowName: string;
|
|
85
|
-
scheduleId: string;
|
|
86
|
-
intervalMs: number;
|
|
87
|
-
ts: number;
|
|
88
|
-
} | {
|
|
89
|
-
type: "schedule_removed";
|
|
90
|
-
scheduleId: string;
|
|
91
|
-
ts: number;
|
|
92
|
-
};
|
|
93
|
-
interface Engine {
|
|
94
|
-
/** Enqueue a workflow for execution. Returns the workflow execution ID. */
|
|
95
|
-
enqueue(name: string, options?: EnqueueOptions): Promise<string>;
|
|
96
|
-
/** Schedule recurring workflow execution. Returns the schedule ID. */
|
|
97
|
-
schedule(name: string, options: ScheduleOptions & EnqueueOptions): string;
|
|
98
|
-
/** Remove a schedule */
|
|
99
|
-
unschedule(scheduleId: string): boolean;
|
|
100
|
-
/** Start the polling loop */
|
|
101
|
-
start(pollIntervalMs?: number): void;
|
|
102
|
-
/** Stop the polling loop gracefully */
|
|
103
|
-
stop(): Promise<void>;
|
|
104
|
-
/** Execute a single tick manually (process pending workflows). Returns number processed. */
|
|
105
|
-
tick(): Promise<number>;
|
|
106
|
-
/** Get engine status */
|
|
107
|
-
status(): {
|
|
108
|
-
running: boolean;
|
|
109
|
-
pendingSchedules: number;
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
declare function createEngine(options: EngineOptions): Engine;
|
|
114
|
-
|
|
115
|
-
export { type Engine, type EngineEvent, type EngineOptions, type EnqueueOptions, type ScheduleOptions, type WorkflowRegistration, createEngine };
|
package/dist/engine.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{randomUUID as Mt}from"crypto";var Ut={"step-require-id":"step-require-id","step-no-immediate-execution":"step-no-immediate-execution","step-require-thunk-for-key":"step-require-thunk-for-key","step-no-bare-await":"step-no-bare-await","step-no-try-catch-wrap":"step-no-try-catch-wrap","step-stable-cache-keys":"step-stable-cache-keys","workflow-no-floating":"workflow-no-floating","workflow-options-position":"workflow-options-position","workflow-callback-shape":"workflow-callback-shape","workflow-no-callable-form":"workflow-no-callable-form","workflow-no-dynamic-import":"workflow-no-dynamic-import","result-no-floating":"result-no-floating","result-require-handling":"result-require-handling","result-no-double-wrap":"result-no-double-wrap","result-no-manual-propagation":"result-no-manual-propagation","result-no-direct-ok-err":"result-no-direct-ok-err","error-check-unexpected-first":"error-check-unexpected-first","error-access-cause":"error-access-cause","error-normalize":"error-normalize","error-no-throw-in-deps":"error-no-throw-in-deps","concurrency-no-promise-all":"concurrency-no-promise-all","concurrency-no-promise-race":"concurrency-no-promise-race","concurrency-no-promise-allsettled":"concurrency-no-promise-allsettled","runtime-step-timeout":"runtime-step-timeout","runtime-step-aborted":"runtime-step-aborted","runtime-retry-exhausted":"runtime-retry-exhausted","runtime-rate-limit":"runtime-rate-limit","runtime-circuit-open":"runtime-circuit-open","runtime-unexpected":"runtime-unexpected","runtime-resolver-not-found":"runtime-resolver-not-found","runtime-saga-compensation":"runtime-saga-compensation"};function it(e){return`https://jagreehal.github.io/awaitly/rules/#${e}`}var or=Object.keys(Ut);var Ne=class extends Error{_tag};function ke(e,t){return class extends Ne{_tag=e;constructor(a,c){let f=t?.message?t.message(a??{}):e;if(super(f),this.name=e,t?.slug!==void 0){if(!t.hint)throw new TypeError(`TaggedError: 'hint' is required when 'slug' is set (slug: "${t.slug}")`);Object.defineProperty(this,"code",{value:t.slug,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"hint",{value:t.hint,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"docsUrl",{value:it(t.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),a&&typeof a=="object"){let u;if(t?.slug!==void 0){let{_tag:W,name:D,message:K,stack:r,code:se,hint:ee,docsUrl:ge,...ne}=a;u=ne}else{let{_tag:W,name:D,message:K,stack:r,...se}=a;u=se}let w=Object.prototype.hasOwnProperty.call(u,"cause"),I=w?u.cause:void 0;w&&delete u.cause;let $=c?.cause!==void 0;if(w&&$)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,u),w&&(this.cause=I),$&&(this.cause=c?.cause)}else c?.cause!==void 0&&(this.cause=c.cause)}}}Object.defineProperty(ke,Symbol.hasInstance,{value:e=>e instanceof Ne});(f=>{function e(u){return u instanceof Error}f.isError=e;function t(u){return u instanceof Ne}f.isTaggedError=t;function a(u,w){let I=u._tag,$=w[I];return $(u)}f.match=a;function c(u,w,I){let $=u._tag,W=w[$];return W?W(u):I(u)}f.matchPartial=c})(ke||={});var ut=class extends ke("TimeoutError",{slug:"runtime-step-timeout",hint:"Increase the step's timeout option, or check why the upstream operation is slow.",message:t=>t.operation?`TimeoutError: ${t.operation} timed out after ${t.ms}ms`:`TimeoutError: Operation timed out after ${t.ms}ms`}){},lt=class extends ke("RetryExhaustedError",{slug:"runtime-retry-exhausted",hint:"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",message:t=>t.operation?`RetryExhaustedError: ${t.operation} failed after ${t.attempts} attempts`:`RetryExhaustedError: Operation failed after ${t.attempts} attempts`}){},ct=class extends ke("RateLimitError",{slug:"runtime-rate-limit",hint:"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",message:t=>t.limiterName?`RateLimitError: Rate limit exceeded for ${t.limiterName}${t.retryAfterMs?`, retry after ${t.retryAfterMs}ms`:""}`:`RateLimitError: Rate limit exceeded${t.retryAfterMs?`, retry after ${t.retryAfterMs}ms`:""}`}){},pt=class extends ke("CircuitBreakerOpenError",{slug:"runtime-circuit-open",hint:"The circuit is open. Wait for it to half-open or fall back to a degraded path.",message:t=>`CircuitBreakerOpenError: Circuit ${t.circuitName} is ${t.state??"OPEN"}${t.retryAfterMs?`, retry after ${Math.ceil(t.retryAfterMs/1e3)}s`:""}`}){},dt=class extends ke("ValidationError",{message:t=>`ValidationError: Invalid ${t.field} - ${t.reason}`}){},mt=class extends ke("NotFoundError",{message:t=>t.id?`NotFoundError: ${t.resource} with id ${t.id} not found`:`NotFoundError: ${t.resource} not found`}){},ft=class extends ke("UnauthorizedError",{message:t=>t.reason?`UnauthorizedError: ${t.reason}`:t.action&&t.resource?`UnauthorizedError: Not authorized to ${t.action} ${t.resource}`:"UnauthorizedError: Access denied"}){},Et=class extends ke("NetworkError",{message:t=>t.url?`NetworkError: ${t.reason} (${t.url})`:`NetworkError: ${t.reason}`}){},wt=class extends ke("CompensationError",{slug:"runtime-saga-compensation",hint:"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",message:t=>`CompensationError: Failed to compensate step ${t.step}`}){},Ke=class extends ke("UnexpectedError",{slug:"runtime-unexpected",hint:"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",message:t=>`UnexpectedError: ${t.cause instanceof Error?t.cause.message:String(t.cause??"unknown")}`}){};function yt(e){return{ok:!0,value:e}}var Wt=e=>typeof e=="object"&&e!==null&&"ok"in e&&typeof e.ok=="boolean"&&(e.ok?"value"in e:"error"in e),je=(e,t)=>{let a={},c=new Map;for(let f of Object.keys(e)){let u=e[f];typeof u=="function"&&(a[f]=(...w)=>{let I=(c.get(f)??0)+1;c.set(f,I);let $=I===1?f:`${f}#${I}`;return t($,async()=>{let W=await u(...w);return Wt(W)?W:yt(W)})})}return a};function Nt(e){let t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!t)return;let a=parseFloat(t[1]),c=t[2].toLowerCase();return{_tag:"Duration",millis:a*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[c]??1)}}function $e(e){return new Ke({cause:e})}function oe(e){return{ok:!0,value:e}}function A(e,t){let a=t?.cause;return{ok:!1,error:e,...a!==void 0?{cause:a}:{}}}var Rt=e=>e instanceof Ke||typeof e=="object"&&e!==null&&"_tag"in e&&e._tag==="UnexpectedError";function Kt(e){if(e==null)return"unknown";if(typeof e=="string")return e.trim()||"unknown";if(typeof e=="object"){let t=e;if(typeof t._tag=="string"){let a=t._tag.trim();if(a)return a}if(typeof t.tag=="string"){let a=t.tag.trim();if(a)return a}if(typeof t.code=="string"){let a=t.code.trim();if(a)return a}else if(typeof t.code=="number")return String(t.code);if(e instanceof Error&&e.name){let a=e.name.trim();if(a)return a}}return"unknown"}function jt(e,t){if(!(!t||!e))return t[e]}function Ye(e){let{intent:t,domain:a,owner:c,tags:f,stateChanges:u,emits:w,calls:I}=e;if(!t&&!a&&!c&&!f?.length&&!u?.length&&!w?.length&&!I?.length)return;let $={};return t&&($.intent=t),a&&($.domain=a),c&&($.owner=c),f?.length&&($.tags=f),u?.length&&($.stateChanges=u),w?.length&&($.emits=w),I?.length&&($.calls=I),$}function xe(e,t,a,c,f){let u=Kt(e),w=jt(u,t),I={tag:u,origin:a};return w!==void 0&&(I.classification=w),c!==void 0&&(I.attempt=c),f!==void 0&&(I.cumulativeDurationMs=f),I}var Oe=Symbol.for("step_timeout_marker");function kt(e){return typeof e!="object"||e===null?!1:e.type==="STEP_TIMEOUT"?!0:Oe in e}function Ft(e){if(!(typeof e!="object"||e===null)){if(e.type==="STEP_TIMEOUT"){let t=e;return{timeoutMs:t.timeoutMs,stepName:t.stepName,stepKey:t.stepKey,attempt:t.attempt}}if(Oe in e)return e[Oe]}}var xt=Symbol("early-exit");function De(e,t){return{[xt]:!0,error:e,meta:t}}function be(e){return typeof e=="object"&&e!==null&&e[xt]===!0}var ht=Symbol("mapper-exception");function Ae(e){return{[ht]:!0,thrown:e}}function Vt(e){return typeof e=="object"&&e!==null&&e[ht]===!0}function ze(e,t){let{backoff:a,initialDelay:c,maxDelay:f,jitter:u}=t,w;switch(a){case"fixed":w=c;break;case"linear":w=c*e;break;case"exponential":w=c*Math.pow(2,e-1);break}if(w=Math.min(w,f),u){let I=w*.25*Math.random();w=w+I}return Math.floor(w)}function Je(e){return new Promise(t=>setTimeout(t,e))}var gt=Symbol("timeout"),Be=Symbol("timeout-option");function Lt(e){return typeof e=="object"&&e!==null&&e[Be]===!0}async function Bt(e,t,a,c){let f=new AbortController,u=t.onTimeout??"error",w=()=>typeof u=="function"?u({name:a.name,key:a.key,ms:t.ms}):t.error??{type:"STEP_TIMEOUT",stepName:a.name,stepKey:a.key,timeoutMs:t.ms,attempt:a.attempt},I;c?.aborted&&f.abort(c.reason);let $;c&&!c.aborted&&($=()=>f.abort(c.reason),c.addEventListener("abort",$,{once:!0}));let W=new Promise((K,r)=>{I=setTimeout(()=>{if(u!=="disconnect"&&f.abort(),u==="option"){r({[Be]:!0,ms:t.ms});return}r({[gt]:!0,error:w()})},t.ms)}),D;t.signal?D=Promise.resolve(e(f.signal)):D=Promise.resolve(e());try{return await Promise.race([D,W])}catch(K){if(typeof K=="object"&&K!==null&&K[Be]===!0)throw{[Be]:!0,ms:t.ms};if(typeof K=="object"&&K!==null&&K[gt]===!0){u==="disconnect"&&D.catch(()=>{});let r=K.error;if(typeof r=="object"&&r!==null&&r.type!=="STEP_TIMEOUT"){let se={timeoutMs:t.ms,stepName:a.name,stepKey:a.key,attempt:a.attempt};Oe in r?r[Oe]=se:Object.defineProperty(r,Oe,{value:se,enumerable:!1,writable:!0,configurable:!1})}throw r}throw K}finally{clearTimeout(I),$&&c&&c.removeEventListener("abort",$)}}var Pe={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function Fe(e,t,a){if(typeof e!="function"){let m=e,Y=t;if(typeof Y!="function")throw new TypeError("[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))");return Fe(({step:me})=>Y(je(m,me),{step:me}),a)}let c=e,f=t,{onError:u,onEvent:w,catchUnexpected:I,workflowId:$,workflowName:W,context:D,_workflowSignal:K}=f&&typeof f=="object"?f:{},r=$??crypto.randomUUID(),se=I??$e,ee=[],ge=0,ne=m=>m??`step_${++ge}`,n=m=>{let Y=m.context!==void 0||D===void 0?m:{...m,context:D},ue=W!==void 0&&Y.workflowName===void 0?{...Y,workflowName:W}:Y;if(ue.type==="step_success"){let me=ue.stepId;for(let Te=ee.length-1;Te>=0;Te--){let j=ee[Te];if(j.type==="race"&&!j.winnerId){j.winnerId=me;break}}}w?.(ue,D)},S=De,G=m=>be(m),ae=(m,Y)=>m,X=m=>typeof m=="function"?!1:!!(m&&typeof m=="object"&&"ok"in m||m&&typeof m=="object"&&"then"in m&&typeof m.then=="function");try{let Y=function(o){let y={};for(let[l,p]of Object.entries(o))if(typeof p=="function")y[l]=p;else if(p&&typeof p=="object"&&"fn"in p)y[l]=p.fn;else throw new TypeError(`step.all: operation "${l}" must be a function or { fn, errors? } object`);return y},ue=function(o,y){let l=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let p=performance.now(),s=!1;ee.push({scopeId:l,type:"parallel"});let i=()=>{if(s)return;s=!0;let g=ee.findIndex(x=>x.scopeId===l);g!==-1&&ee.splice(g,1),n({type:"scope_end",workflowId:r,scopeId:l,ts:Date.now(),durationMs:performance.now()-p})};n({type:"scope_start",workflowId:r,scopeId:l,scopeType:"parallel",name:o,ts:Date.now()});try{let g=await y();if(i(),!g.ok)throw u?.(g.error,o,D),S(g.error,{origin:"result",resultCause:g.cause});return g.value}catch(g){throw i(),g}})()},me=function(o,y){let l=Object.keys(o),p=y.name??`Parallel(${l.join(", ")})`,s=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let i=performance.now(),g=!1;ee.push({scopeId:s,type:"parallel"});let x=()=>{if(g)return;g=!0;let b=ee.findIndex(v=>v.scopeId===s);b!==-1&&ee.splice(b,1),n({type:"scope_end",workflowId:r,scopeId:s,ts:Date.now(),durationMs:performance.now()-i})};n({type:"scope_start",workflowId:r,scopeId:s,scopeType:"parallel",name:p,ts:Date.now()});try{let b=await new Promise(M=>{if(l.length===0){M([]);return}let B=!1,te=l.length,V=new Array(l.length);for(let z=0;z<l.length;z++){let L=l[z],q=z;Promise.resolve(o[L]()).catch(P=>A({type:"PROMISE_REJECTED",cause:P},{cause:{type:"PROMISE_REJECTION",reason:P}})).then(P=>{if(!B){if(!P.ok){B=!0,M([{key:L,result:P}]);return}V[q]={key:L,result:P},te--,te===0&&M(V)}})}});x();let v={};for(let{key:M,result:B}of b){if(!B.ok)throw u?.(B.error,M,D),S(B.error,{origin:"result",resultCause:B.cause});v[M]=B.value}return v}catch(b){throw x(),b}})()};var le=Y,ye=ue,pe=me;let m=(o,y,l)=>(async()=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let p=l??{},s=Ye(p),i=o,g=p.key??o,x=p.key??o,{description:b,retry:v,timeout:M}=p,B=ne(g),te=w,V=te?performance.now():0,L=X(y)?()=>y:y,P={attempts:Math.max(1,v?.attempts??1),backoff:v?.backoff??Pe.backoff,initialDelay:v?.initialDelay??Pe.initialDelay,maxDelay:v?.maxDelay??Pe.maxDelay,jitter:v?.jitter??Pe.jitter,shouldRetry:v?.shouldRetry??Pe.shouldRetry,onRetry:v?.onRetry??Pe.onRetry};w&&n({type:"step_start",workflowId:r,stepId:B,stepKey:g,name:i,description:b,ts:Date.now(),...s&&{metadata:s}});let Re;for(let C=1;C<=P.attempts;C++){let R=te?performance.now():0;try{let d;if(M?d=await Bt(L,M,{name:i,key:g,attempt:C},K):d=await L(),d.ok){let h=performance.now()-V;return n({type:"step_success",workflowId:r,stepId:B,stepKey:g,name:i,description:b,ts:Date.now(),durationMs:h,...s&&{metadata:s}}),x&&n({type:"step_complete",workflowId:r,stepKey:x,name:i,description:b,ts:Date.now(),durationMs:h,result:d,...s&&{metadata:s}}),d.value}if(Re=d,C<P.attempts&&P.shouldRetry(d.error,C)){let h=ze(C,P);n({type:"step_retry",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),attempt:C+1,maxAttempts:P.attempts,delayMs:h,error:d.error,...s&&{metadata:s},diagnostics:xe(d.error,p.errorMeta,"result",C,performance.now()-V)}),P.onRetry(d.error,C,h),await Je(h);continue}P.attempts>1&&n({type:"step_retries_exhausted",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),durationMs:performance.now()-V,attempts:C,lastError:d.error,...s&&{metadata:s},diagnostics:xe(d.error,p.errorMeta,"result",C,performance.now()-V)});break}catch(d){let h=performance.now()-R;if(Lt(d)){let U=d.ms;n({type:"step_timeout",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),timeoutMs:U,attempt:C,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"timeout",C)}),n({type:"step_success",workflowId:r,stepId:B,stepKey:g,name:i,description:b,ts:Date.now(),durationMs:performance.now()-V,...s&&{metadata:s}}),x&&n({type:"step_complete",workflowId:r,stepKey:x,name:i,description:b,ts:Date.now(),durationMs:performance.now()-V,result:oe(void 0),...s&&{metadata:s}});return}if(G(d))throw n({type:"step_aborted",workflowId:r,stepId:B,stepKey:g,name:i,description:b,ts:Date.now(),durationMs:h,...s&&{metadata:s}}),d;if(kt(d)){let U=Ft(d),T=M?.ms??U?.timeoutMs??0;if(n({type:"step_timeout",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),timeoutMs:T,attempt:C,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"timeout",C)}),C<P.attempts&&P.shouldRetry(d,C)){let Z=ze(C,P);n({type:"step_retry",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),attempt:C+1,maxAttempts:P.attempts,delayMs:Z,error:d,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"timeout",C,performance.now()-V)}),P.onRetry(d,C,Z),await Je(Z);continue}P.attempts>1&&n({type:"step_retries_exhausted",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),durationMs:performance.now()-V,attempts:C,lastError:d,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"timeout",C,performance.now()-V)});let F=performance.now()-V;throw n({type:"step_error",workflowId:r,stepId:B,stepKey:g,name:i,description:b,ts:Date.now(),durationMs:F,error:d,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"timeout",C,F)}),x&&n({type:"step_complete",workflowId:r,stepKey:x,name:i,description:b,ts:Date.now(),durationMs:F,result:A(d,{cause:d}),meta:{origin:"throw",thrown:d},...s&&{metadata:s}}),u?.(d,i,D),S(d,{origin:"throw",thrown:d})}if(C<P.attempts&&P.shouldRetry(d,C)){let U=ze(C,P);n({type:"step_retry",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),attempt:C+1,maxAttempts:P.attempts,delayMs:U,error:d,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"throw",C,performance.now()-V)}),P.onRetry(d,C,U),await Je(U);continue}P.attempts>1&&!kt(d)&&n({type:"step_retries_exhausted",workflowId:r,stepId:B,stepKey:g,name:i,ts:Date.now(),durationMs:performance.now()-V,attempts:C,lastError:d,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"throw",C,performance.now()-V)});let _=performance.now()-V,O;try{O=se(d)}catch(U){throw Ae(U)}throw n({type:"step_error",workflowId:r,stepId:B,stepKey:g,name:i,description:b,ts:Date.now(),durationMs:_,error:O,...s&&{metadata:s},diagnostics:xe(d,p.errorMeta,"throw",C,_)}),x&&n({type:"step_complete",workflowId:r,stepKey:x,name:i,description:b,ts:Date.now(),durationMs:_,result:A(O,{cause:d}),meta:{origin:"throw",thrown:d},...s&&{metadata:s}}),u?.(O,i,D),S(O,{origin:"throw",thrown:d})}}let E=Re,k=performance.now()-V,J=ae(E.error,{origin:"result",resultCause:E.cause});throw n({type:"step_error",workflowId:r,stepId:B,stepKey:g,name:i,description:b,ts:Date.now(),durationMs:k,error:J,...s&&{metadata:s},diagnostics:xe(E.error,p.errorMeta,"result",P.attempts,k)}),x&&n({type:"step_complete",workflowId:r,stepKey:x,name:i,description:b,ts:Date.now(),durationMs:k,result:E,meta:{origin:"result",resultCause:E.cause},...s&&{metadata:s}}),u?.(J,i,D),S(J,{origin:"result",resultCause:E.cause})})();m.try=(o,y,l)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })');let p="error"in l?()=>l.error:l.onError;if(l.retry||l.timeout)return m.retry(o,async()=>{try{return oe(await y())}catch(b){return A(p(b),{cause:b})}},{attempts:l.retry?.attempts??1,...l.retry??{},key:l.key,timeout:l.timeout});let s=l.key??o,i=o,g=o,x=w;return(async()=>{let b=x?performance.now():0;w&&n({type:"step_start",workflowId:r,stepId:g,stepKey:s,name:i,ts:Date.now()});try{let v=await y(),M=performance.now()-b;return n({type:"step_success",workflowId:r,stepId:g,stepKey:s,name:i,ts:Date.now(),durationMs:M}),s&&n({type:"step_complete",workflowId:r,stepKey:s,name:i,ts:Date.now(),durationMs:M,result:oe(v)}),v}catch(v){let M=p(v),B=performance.now()-b,te=ae(M,{origin:"throw",thrown:v});throw n({type:"step_error",workflowId:r,stepId:g,stepKey:s,name:i,ts:Date.now(),durationMs:B,error:te}),s&&n({type:"step_complete",workflowId:r,stepKey:s,name:i,ts:Date.now(),durationMs:B,result:A(M,{cause:v}),meta:{origin:"throw",thrown:v}}),u?.(te,i,D),S(te,{origin:"throw",thrown:v})}})()},m.fromResult=(o,y,l)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })');let p=l.key??o,s=o,i=o,g="error"in l?()=>l.error:l.onError,x=w;return(async()=>{let b=x?performance.now():0;w&&n({type:"step_start",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now()});let v=await y();if(v.ok){let M=performance.now()-b;return n({type:"step_success",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:M}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:M,result:oe(v.value)}),v.value}else{let M=g(v.error),B=performance.now()-b,te=ae(M,{origin:"result",resultCause:v.error});throw n({type:"step_error",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:B,error:te}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:B,result:A(M,{cause:v.error}),meta:{origin:"result",resultCause:v.error}}),u?.(te,s,D),S(te,{origin:"result",resultCause:v.error})}})()},m.fromNullable=(o,y,l,p)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))');return m(o,async()=>{let s=await y();return s!=null?oe(s):A(l())},p)},m.retry=(o,y,l)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })');return m(o,y,{key:l.key??o,retry:{attempts:l.attempts,backoff:l.backoff,initialDelay:l.initialDelay,maxDelay:l.maxDelay,jitter:l.jitter,shouldRetry:l.shouldRetry,onRetry:l.onRetry},timeout:l.timeout})},m.withTimeout=(o,y,l)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })');return m(o,y,{key:l.key??o,timeout:l})},m.sleep=(o,y,l)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")');let p=typeof y=="string"?Nt(y):y;if(!p)throw new Error(`step.sleep: invalid duration '${y}'`);let s=p.millis,i=l?.signal;return m(o,async()=>{if(K?.aborted||i?.aborted){let g=new Error("Sleep aborted");throw g.name="AbortError",g}return new Promise((g,x)=>{let b={timeoutId:void 0},v=()=>{b.timeoutId&&clearTimeout(b.timeoutId);let M=new Error("Sleep aborted");M.name="AbortError",x(M)};K?.addEventListener("abort",v,{once:!0}),i?.addEventListener("abort",v,{once:!0}),b.timeoutId=setTimeout(()=>{K?.removeEventListener("abort",v),i?.removeEventListener("abort",v),g(oe(void 0))},s)})},{key:l?.key??o,description:l?.description})},m.all=((...o)=>{if(typeof o[0]!="string")throw new TypeError("step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })");let y=o[0],l=o[1];if(typeof l=="function")return ue(y,l);if(l&&typeof l=="object"&&!Array.isArray(l)){let s=Y(l);return me(s,{name:y})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),m.race=(o,y)=>{let l=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let p=performance.now(),s=!1,i={scopeId:l,type:"race",winnerId:void 0};ee.push(i);let g=()=>{if(s)return;s=!0;let x=ee.findIndex(b=>b.scopeId===l);x!==-1&&ee.splice(x,1),n({type:"scope_end",workflowId:r,scopeId:l,ts:Date.now(),durationMs:performance.now()-p,winnerId:i.winnerId})};n({type:"scope_start",workflowId:r,scopeId:l,scopeType:"race",name:o,ts:Date.now()});try{let x=await y();if(g(),!x.ok)throw u?.(x.error,o,D),S(x.error,{origin:"result",resultCause:x.cause});return x.value}catch(x){throw g(),x}})()},m.if=(o,y,l)=>l(),m.label=m.if,m.branch=async(o,y)=>{let{condition:l,then:p,else:s}=y;if(l())return await p();if(s)return await s()},m.arm=(o,y)=>({fn:o,errors:y}),m.forEach=async(o,y,l)=>{let p=[],s=l.maxIterations,i=0,g="run"in l,x=Symbol.asyncIterator in y?y:(async function*(){yield*y})();for await(let b of x){if(s!==void 0&&i>=s)break;let v;g?v=await l.run(b,i):v=await l.item.handler(b,i,m),p.push(v),i++}return p},m.item=o=>({__forEachItemHandler:!0,handler:o}),m.dep=(o,y)=>y,m.workflow=(o,y,l)=>m(o,y,l),m.map=async(o,y,l,p)=>{let s=p?.concurrency??y.length;return m(o,()=>s>=y.length?Tt(y.map((i,g)=>l(i,g))):(async()=>{let i=[];for(let g=0;g<y.length;g+=s){let x=y.slice(g,g+s),b=await Tt(x.map((v,M)=>l(v,g+M)));if(!b.ok)return b;i.push(...b.value)}return oe(i)})(),{key:p?.key})},m.withFallback=(o,y,l)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })');let p=l.key??o,s=o,i=ne(p),g=w;return(async()=>{let x=g?performance.now():0;w&&n({type:"step_start",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now()});let b;try{b=await y()}catch(V){if(G(V))throw n({type:"step_aborted",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:performance.now()-x}),V;let z;try{z=se(V)}catch(q){throw Ae(q)}if(l.on!==void 0&&l.on!==z){let q=performance.now()-x;throw n({type:"step_error",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:q,error:z}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:q,result:A(z,{cause:V}),meta:{origin:"throw",thrown:V}}),u?.(z,s,D),S(z,{origin:"throw",thrown:V})}let L;try{L=await l.fallback()}catch(q){if(G(q))throw n({type:"step_aborted",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:performance.now()-x}),q;let P;try{P=se(q)}catch(E){throw Ae(E)}let Re=performance.now()-x;throw n({type:"step_error",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:Re,error:P}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:Re,result:A(P,{cause:q}),meta:{origin:"throw",thrown:q}}),u?.(P,s,D),S(P,{origin:"throw",thrown:q})}if(L.ok){let q=performance.now()-x;return n({type:"step_success",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:q}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:q,result:L,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(z)}}),L.value}else{let q=performance.now()-x,P=ae(L.error,{origin:"result",resultCause:L.cause});throw n({type:"step_error",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:q,error:P}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:q,result:L,meta:{origin:"result",resultCause:L.cause}}),u?.(P,s,D),S(P,{origin:"result",resultCause:L.cause})}}if(b.ok){let V=performance.now()-x;return n({type:"step_success",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:V}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:V,result:b}),b.value}let v=b.error;if(l.on!==void 0&&l.on!==v){let V=performance.now()-x,z=ae(v,{origin:"result",resultCause:b.cause});throw n({type:"step_error",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:V,error:z}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:V,result:b,meta:{origin:"result",resultCause:b.cause}}),u?.(z,s,D),S(z,{origin:"result",resultCause:b.cause})}let M;try{M=await l.fallback()}catch(V){if(G(V))throw n({type:"step_aborted",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:performance.now()-x}),V;let z;try{z=se(V)}catch(q){throw Ae(q)}let L=performance.now()-x;throw n({type:"step_error",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:L,error:z}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:L,result:A(z,{cause:V}),meta:{origin:"throw",thrown:V}}),u?.(z,s,D),S(z,{origin:"throw",thrown:V})}if(M.ok){let V=performance.now()-x;return n({type:"step_success",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:V}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:V,result:M,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(v)}}),M.value}let B=performance.now()-x,te=ae(M.error,{origin:"result",resultCause:M.cause});throw n({type:"step_error",workflowId:r,stepId:i,stepKey:p,name:s,ts:Date.now(),durationMs:B,error:te}),p&&n({type:"step_complete",workflowId:r,stepKey:p,name:s,ts:Date.now(),durationMs:B,result:M,meta:{origin:"result",resultCause:M.cause}}),u?.(te,s,D),S(te,{origin:"result",resultCause:M.cause})})()},m.withResource=(o,y)=>{if(typeof o!="string"||o.length===0)throw new Error('[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })');let l=o,p=o,s=ne(l),i=w;return(async()=>{let g=i?performance.now():0;w&&n({type:"step_start",workflowId:r,stepId:s,stepKey:l,name:p,ts:Date.now()});let x;try{x=await y.acquire()}catch(L){if(G(L))throw n({type:"step_aborted",workflowId:r,stepId:s,stepKey:l,name:p,ts:Date.now(),durationMs:performance.now()-g}),L;let q;try{q=se(L)}catch(Re){throw Ae(Re)}let P=performance.now()-g;throw n({type:"step_error",workflowId:r,stepId:s,stepKey:l,name:p,ts:Date.now(),durationMs:P,error:q}),l&&n({type:"step_complete",workflowId:r,stepKey:l,name:p,ts:Date.now(),durationMs:P,result:A(q,{cause:L}),meta:{origin:"throw",thrown:L}}),u?.(q,p,D),S(q,{origin:"throw",thrown:L})}if(!x.ok){let L=performance.now()-g,q=ae(x.error,{origin:"result",resultCause:x.cause});throw n({type:"step_error",workflowId:r,stepId:s,stepKey:l,name:p,ts:Date.now(),durationMs:L,error:q}),l&&n({type:"step_complete",workflowId:r,stepKey:l,name:p,ts:Date.now(),durationMs:L,result:x,meta:{origin:"result",resultCause:x.cause}}),u?.(q,p,D),S(q,{origin:"result",resultCause:x.cause})}let b=x.value,v,M,B=!1;try{v=await y.use(b)}catch(L){if(G(L)){try{await y.release(b)}catch(q){console.warn(`[awaitly] step.withResource("${o}"): release threw after earlyExit:`,q)}throw L}M=L,B=!0}try{await y.release(b)}catch(L){console.warn(`[awaitly] step.withResource("${o}"): release threw:`,L)}if(B){let L;try{L=se(M)}catch(P){throw Ae(P)}let q=performance.now()-g;throw n({type:"step_error",workflowId:r,stepId:s,stepKey:l,name:p,ts:Date.now(),durationMs:q,error:L}),l&&n({type:"step_complete",workflowId:r,stepKey:l,name:p,ts:Date.now(),durationMs:q,result:A(L,{cause:M}),meta:{origin:"throw",thrown:M}}),u?.(L,p,D),S(L,{origin:"throw",thrown:M})}let te=v;if(te.ok){let L=performance.now()-g;return n({type:"step_success",workflowId:r,stepId:s,stepKey:l,name:p,ts:Date.now(),durationMs:L}),l&&n({type:"step_complete",workflowId:r,stepKey:l,name:p,ts:Date.now(),durationMs:L,result:te}),te.value}let V=performance.now()-g,z=ae(te.error,{origin:"result",resultCause:te.cause});throw n({type:"step_error",workflowId:r,stepId:s,stepKey:l,name:p,ts:Date.now(),durationMs:V,error:z}),l&&n({type:"step_complete",workflowId:r,stepKey:l,name:p,ts:Date.now(),durationMs:V,result:te,meta:{origin:"result",resultCause:te.cause}}),u?.(z,p,D),S(z,{origin:"result",resultCause:te.cause})})()};let j=await c({step:m});if(process.env.NODE_ENV!=="production"&&j!==null&&typeof j=="object"&&"ok"in j&&typeof j.ok=="boolean"){let o=j;(o.ok===!0&&"value"in o||o.ok===!1&&"error"in o)&&console.warn(`awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
|
|
2
|
-
|
|
3
|
-
Incorrect: return ok({ data });
|
|
4
|
-
Correct: return { data };
|
|
5
|
-
|
|
6
|
-
See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`)}return oe(j)}catch(m){if(Vt(m))throw m.thrown;if(G(m)){let ue=m.meta.origin==="throw"?m.meta.thrown:m.meta.origin==="result"?m.meta.resultCause:void 0;return A(m.error,{cause:ue})}let Y=se(m);return u?.(Y,"unexpected",D),A(Y,{cause:m})}}Fe.strict=(e,t)=>Fe(e,t);async function Tt(e){return e.length===0?oe([]):new Promise(t=>{let a=!1,c=e.length,f=new Array(e.length);for(let u=0;u<e.length;u++){let w=u;Promise.resolve(e[w]).catch(I=>A({type:"PROMISE_REJECTED",cause:I},{cause:{type:"PROMISE_REJECTION",reason:I}})).then(I=>{if(!a){if(!I.ok){a=!0,t(I);return}f[w]=I.value,c--,c===0&&t(oe(f))}})}})}function St(e){return e.type==="step_complete"}function Ge(e){return typeof e=="object"&&e!==null&&e.type==="WORKFLOW_CANCELLED"}var ve=class extends Error{constructor(a,c=[]){super(a);this.errors=c;this.name="SnapshotFormatError"}errors};var _e=class extends Error{constructor(a,c,f){super(a);this.stepId=c;this.originalError=f;this.name="SnapshotDecodeError"}stepId;originalError};function $t(e){let t=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Snapshot must be an object"]};let a=e;if("formatVersion"in a?a.formatVersion!==1&&t.push(`Invalid formatVersion: expected 1, got ${a.formatVersion}`):t.push("Missing required field: formatVersion"),!("steps"in a))t.push("Missing required field: steps");else if(typeof a.steps!="object"||a.steps===null)t.push("steps must be an object");else{let c=a.steps;for(let[f,u]of Object.entries(c)){if(typeof u!="object"||u===null){t.push(`steps["${f}"] must be an object`);continue}let w=u;"ok"in w?typeof w.ok!="boolean"?t.push(`steps["${f}"].ok must be a boolean`):w.ok===!1&&("error"in w||t.push(`steps["${f}"] is error result but missing error field`),"cause"in w||t.push(`steps["${f}"] is error result but missing cause field`)):t.push(`steps["${f}"] missing required field: ok`)}}if(!("execution"in a))t.push("Missing required field: execution");else if(typeof a.execution!="object"||a.execution===null)t.push("execution must be an object");else{let c=a.execution;"status"in c?["running","completed","failed"].includes(c.status)||t.push("execution.status must be one of: running, completed, failed"):t.push("execution missing required field: status"),"lastUpdated"in c?typeof c.lastUpdated!="string"&&t.push("execution.lastUpdated must be a string (ISO timestamp)"):t.push("execution missing required field: lastUpdated")}return t.length>0?{valid:!1,errors:t}:{valid:!0,snapshot:e}}function bt(e){let t=$t(e);if(!t.valid)throw new ve(`Invalid snapshot format: ${t.errors[0]}`,t.errors);return t.snapshot}function vt(e,t){let a=Object.create(null);for(let[w,I]of Object.entries(e.steps))Object.prototype.hasOwnProperty.call(e.steps,w)&&(a[w]=I);for(let[w,I]of Object.entries(t.steps))Object.prototype.hasOwnProperty.call(t.steps,w)&&(a[w]=I);let c=e.metadata||t.metadata?{...e.metadata,...t.metadata}:void 0,u=[...(e.warnings||[]).filter(w=>!Object.prototype.hasOwnProperty.call(t.steps,w.stepId)),...t.warnings||[]];return{formatVersion:1,steps:a,execution:{...t.execution},metadata:c,warnings:u.length>0?u:void 0}}var Ct=1e3;function Xe(e){let t={type:"error",name:e.name,message:e.message};e.stack&&(t.stack=e.stack);let a=e;return a.cause!==void 0&&(a.cause instanceof Error?t.cause=Xe(a.cause):t.cause=Ze(a.cause)),t}function Ze(e){let t,a=!1;try{t=String(e),t.length>Ct&&(t=t.slice(0,Ct),a=!0)}catch{t="[unable to convert to string]"}let c=e===null?"null":typeof e=="object"?e.constructor?.name??"Object":typeof e,f;try{let w=JSON.stringify(e);w!==void 0&&(f=JSON.parse(w))}catch{}let u={type:"thrown",originalType:c,stringRepresentation:t};return f!==void 0&&(u.value=f),a&&(u.truncated=!0),u}function Qe(e){if(e.type==="error"){let t=new Error(e.message);return t.name=e.name,e.stack&&(t.stack=e.stack),e.cause&&(t.cause=Qe(e.cause)),t}return e.value!==void 0?e.value:e.stringRepresentation}function Ht(e){return typeof e=="object"&&e!==null&&e.__cachedMeta===!0}function Ce(e,t,a){return A(e,{cause:{__cachedMeta:!0,originalCause:a,meta:t}})}function Ve(e){return Ht(e)?e.meta:{origin:"result",resultCause:e}}function Le(){let e=new Map;return{handleEvent:t=>{St(t)&&e.set(t.stepKey,{result:t.result,meta:t.meta})},getResumeState:()=>({steps:new Map(e)}),clear:()=>e.clear()}}var qt="STREAM_WRITE_ERROR",zt="STREAM_READ_ERROR",Jt="STREAM_CLOSE_ERROR";var Yt="STREAM_ENDED";function He(e,t,a){return{type:qt,reason:e,message:t,...a!==void 0?{cause:a}:{}}}function et(e,t,a){return{type:zt,reason:e,message:t,...a!==void 0?{cause:a}:{}}}function tt(e,t,a){return{type:Jt,reason:e,message:t,...a!==void 0?{cause:a}:{}}}function qe(e){return{type:Yt,finalPosition:e}}function At(e={}){let t=e.highWaterMark??16,a=e.lowWaterMark??Math.floor(t/2),c=e.onStateChange,f="flowing",u=0,w=[];function I(W){if(f!==W&&(f=W,c?.(W),W==="flowing"&&w.length>0)){let D=w;w=[];for(let K of D)K()}}function $(){f==="flowing"&&u>=t?I("paused"):f==="paused"&&u<=a&&I("flowing")}return{get state(){return f},get bufferedCount(){return u},get highWaterMark(){return t},get lowWaterMark(){return a},increment(){u++,$()},decrement(){u>0&&(u--,$())},setCount(W){u=Math.max(0,W),$()},waitForDrain(){return f==="flowing"?Promise.resolve():new Promise(W=>{w.push(W)})},reset(){u=0,w=[],I("flowing")}}}function Gt(e){return{_tag:"Duration",millis:e}}function Xt(e){return{_tag:"Duration",millis:e*1e3}}function Zt(e){return{_tag:"Duration",millis:e*60*1e3}}function Qt(e){return{_tag:"Duration",millis:e*60*60*1e3}}function er(e){return{_tag:"Duration",millis:e*24*60*60*1e3}}function Pt(e){return e.millis}function Ot(e){let t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!t)return;let a=parseFloat(t[1]);switch(t[2].toLowerCase()){case"ms":return Gt(a);case"s":return Xt(a);case"m":return Zt(a);case"h":return Qt(a);case"d":return er(a);default:return}}async function Dt(e,t){let a=e["~standard"].validate(t),c=a instanceof Promise?await a:a;return c.issues?A({type:"INPUT_VALIDATION_ERROR",issues:c.issues.map(f=>({message:f.message,path:f.path?.map(u=>typeof u=="object"?u.key:u)})),message:`Input validation failed: ${c.issues.map(f=>f.message).join(", ")}`}):oe(c.value)}function rt(e,t){let a=c=>((...f)=>{let u=f.at(-1),w=f.length>0&&typeof u=="object"&&u!==null&&!Array.isArray(u)&&typeof u!="function",I=w?u:void 0,$=w?f.slice(0,-1):f,W={...t,...I?.deps??{}},D=I?{...I,deps:W}:{deps:W};return e[c](...$,D)});return{run:a("run"),runWithState:a("runWithState"),withDeps(c){return rt(e,{...t,...c})}}}function nt(e,t,a){if(typeof e!="string"||e.length===0)throw new TypeError("createWorkflow(workflowName, deps, options?): first argument must be a non-empty string. Example: createWorkflow('checkout', { chargeCard, sendEmail })");let c=t??{},f=a;async function u(W,D,K){let r=W??crypto.randomUUID(),se=K?.deps?{...c,...K.deps}:c,ee=[],ge=K?.createContext??f?.createContext,ne=ge?await ge():void 0,n=K?.signal??f?.signal,S=K?.onEvent??f?.onEvent,G=K?.onError??f?.onError,ae=K?.shouldRun??f?.shouldRun,X=K?.onBeforeStart??f?.onBeforeStart,le=K?.onAfterStep??f?.onAfterStep,ye=K?.resumeState??f?.resumeState,pe=f?.catchUnexpected??$e,m={},Y=(K?.devWarnings??f?.devWarnings)===!0&&process.env.NODE_ENV!=="production",ue=new Set,me=new Set,Te={workflowId:r,onEvent:S,context:ne!==void 0?ne:void 0,signal:n,input:{},ref:E=>m[E],set:(E,k)=>{Y&&!ue.has(E)&&(ue.add(E),console.warn(`awaitly: ctx.set('${E}', ...) is deprecated for static analysis. Use step('id', fn, { out: '${E}' }) instead.`)),m[E]=k},get:E=>(Y&&!me.has(E)&&(me.add(E),console.warn(`awaitly: ctx.get('${E}') is deprecated for static analysis. Use ctx.ref('${E}') instead for tracked dependencies.`)),m[E])},j=E=>{let k=E.context!==void 0||ne===void 0?E:{...E,context:ne},J=k.workflowName===void 0?{...k,workflowName:e}:k;S?.(J,ne)},o=(E,k)=>{let J={type:"WORKFLOW_CANCELLED",reason:E,lastStepKey:k};return A(pe(J),{cause:J})};if(n?.aborted){let E=typeof n.reason=="string"?n.reason:n.reason instanceof Error?n.reason.message:void 0;return j({type:"workflow_cancelled",workflowId:r,ts:Date.now(),durationMs:0,reason:E}),o(E)}if(ae){let E=performance.now();try{let k=await ae(r,ne),J=performance.now()-E;if(j({type:"hook_should_run",workflowId:r,ts:Date.now(),durationMs:J,result:k,skipped:!k}),!k){let C=new Error("Workflow skipped by shouldRun hook");return A(pe(C),{cause:C})}}catch(k){let J=performance.now()-E;return j({type:"hook_should_run_error",workflowId:r,ts:Date.now(),durationMs:J,error:k}),A(pe(k),{cause:k})}}if(X){let E=performance.now();try{let k=await X(r,ne),J=performance.now()-E;if(j({type:"hook_before_start",workflowId:r,ts:Date.now(),durationMs:J,result:k,skipped:!k}),!k){let C=new Error("Workflow skipped by onBeforeStart hook");return A(pe(C),{cause:C})}}catch(k){let J=performance.now()-E;return j({type:"hook_before_start_error",workflowId:r,ts:Date.now(),durationMs:J,error:k}),A(pe(k),{cause:k})}}let y=f?.inputSchema,l=f?.input;if(y){let E=await Dt(y,l);if(!E.ok)return A(E.error);Te.input=E.value}else l!==void 0&&(Te.input=l);let p=Date.now(),s=performance.now();j({type:"workflow_start",workflowId:r,ts:p});let i=K?.cache??f?.cache,g=K?.streamStore??f?.streamStore;if(ye&&!i&&(i=new Map),ye&&i){let E=typeof ye=="function"?await ye():ye;E.steps instanceof Map||(console.warn(`awaitly: resumeState.steps is not a Map (got ${typeof E.steps}). This usually happens when state is serialized with JSON.stringify() directly.
|
|
7
|
-
Use stringifyState() and parseState() from 'awaitly/persistence' instead:
|
|
8
|
-
import { stringifyState, parseState } from 'awaitly/persistence';
|
|
9
|
-
const json = stringifyState(state); // Save this
|
|
10
|
-
const restored = parseState(json); // Load this`),typeof E.steps=="object"&&E.steps!==null&&(E.steps=new Map(Object.entries(E.steps))));for(let[k,J]of E.steps){let{result:C,meta:R}=J;if(C.ok)i.set(k,C);else{let d=R??{origin:"result",resultCause:C.cause};i.set(k,Ce(C.error,d,C.cause))}}}let x=K?.snapshot??f?.snapshot,b=f?.serialization;if(x&&!ye){i||(i=new Map);let E=x,k=b?.decode;for(let[J,C]of Object.entries(E.steps))if(Object.prototype.hasOwnProperty.call(E.steps,J))try{if(C.ok){let R=k?k(C.value):C.value;i.set(J,oe(R))}else{let R=k?k(C.error):C.error,d=Qe(C.cause),h=C.meta?.origin==="throw"?{origin:"throw",thrown:d}:{origin:"result",resultCause:d};i.set(J,Ce(R,h,d))}}catch(R){throw new _e(`Failed to decode step "${J}": ${R instanceof Error?R.message:String(R)}`,J,R instanceof Error?R:void 0)}}let v=!1,M,B,te=()=>{v=!0,M=typeof n?.reason=="string"?n.reason:n?.reason instanceof Error?n.reason.message:void 0};n&&!n.aborted&&n.addEventListener("abort",te,{once:!0});let V=()=>{if(v||n?.aborted)throw{type:"WORKFLOW_CANCELLED",reason:M??(typeof n?.reason=="string"?n.reason:n?.reason instanceof Error?n.reason.message:void 0),lastStepKey:B}},z=async(E,k,J)=>{if(!le)return;let C=performance.now();try{await le(E,k,r,ne);let R=performance.now()-C;j({type:"hook_after_step",workflowId:r,stepKey:E,ts:Date.now(),durationMs:R})}catch(R){let d=performance.now()-C;throw j({type:"hook_after_step_error",workflowId:r,stepKey:E,ts:Date.now(),durationMs:d,error:R}),R}},L=E=>{let k=async(R,d,h)=>{if(typeof R!="string")throw new Error('[awaitly] step() requires a string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let _=R,O=h??{},U=_,T=Object.prototype.hasOwnProperty.call(O,"key")?O.key:_,{ttl:F,out:Z}=O;V();let re=Ye(O);if(T&&i&&i.has(T)){j({type:"step_cache_hit",workflowId:r,stepKey:T,name:U,ts:Date.now(),...re&&{metadata:re}});let N=i.get(T);if(N.ok)return B=T,Z&&(m[Z]=N.value),N.value;let H=Ve(N.cause);throw De(N.error,H)}T&&i&&j({type:"step_cache_miss",workflowId:r,stepKey:T,name:U,ts:Date.now(),...re&&{metadata:re}});try{let N=await E(_,d,O);return Z&&(m[Z]=N),O.compensate&&ee.push({stepName:U,value:N,compensate:O.compensate}),T&&(B=T,i&&i.set(T,oe(N),F?{ttl:F}:void 0),await z(T,oe(N))),N}catch(N){if(T&&be(N)){let H=N,de=H.meta.origin==="result"?H.meta.resultCause:H.meta.origin==="throw"?H.meta.thrown:void 0,Q=Ce(H.error,H.meta,de);i&&i.set(T,Q,F?{ttl:F}:void 0),await z(T,Q,H.meta)}throw N}};k.try=async(R,d,h)=>{let{ttl:_}=h,O=h.key??R,U=R;if(i&&i.has(O)){j({type:"step_cache_hit",workflowId:r,stepKey:O,name:U,ts:Date.now()});let T=i.get(O);if(T.ok)return T.value;let F=Ve(T.cause);throw De(T.error,F)}i&&j({type:"step_cache_miss",workflowId:r,stepKey:O,name:U,ts:Date.now()});try{let T=await E.try(R,d,{...h,key:O});return h.compensate&&ee.push({stepName:U,value:T,compensate:h.compensate}),i&&i.set(O,oe(T),_?{ttl:_}:void 0),await z(O,oe(T)),T}catch(T){if(be(T)){let F=T,Z=F.meta.origin==="result"?F.meta.resultCause:F.meta.origin==="throw"?F.meta.thrown:void 0,re=Ce(F.error,F.meta,Z);i&&i.set(O,re,_?{ttl:_}:void 0),await z(O,re,F.meta)}throw T}},k.fromResult=async(R,d,h)=>{let{ttl:_}=h,O=h.key??R,U=R;if(i&&i.has(O)){j({type:"step_cache_hit",workflowId:r,stepKey:O,name:U,ts:Date.now()});let T=i.get(O);if(T.ok)return T.value;let F=Ve(T.cause);throw De(T.error,F)}i&&j({type:"step_cache_miss",workflowId:r,stepKey:O,name:U,ts:Date.now()});try{let T=await E.fromResult(R,d,{...h,key:O});return i&&i.set(O,oe(T),_?{ttl:_}:void 0),await z(O,oe(T)),T}catch(T){if(be(T)){let F=T,Z=F.meta.origin==="result"?F.meta.resultCause:F.meta.origin==="throw"?F.meta.thrown:void 0,re=Ce(F.error,F.meta,Z);i&&i.set(O,re,_?{ttl:_}:void 0),await z(O,re,F.meta)}throw T}},k.race=E.race,k.withFallback=async(R,d,h)=>{let _=h.key??R,O=R;if(i&&i.has(_)){j({type:"step_cache_hit",workflowId:r,stepKey:_,name:O,ts:Date.now()});let U=i.get(_);if(U.ok)return U.value;let T=Ve(U.cause);throw De(U.error,T)}i&&j({type:"step_cache_miss",workflowId:r,stepKey:_,name:O,ts:Date.now()});try{let U=await E.withFallback(R,d,h);return i&&i.set(_,oe(U)),await z(_,oe(U)),U}catch(U){if(be(U)){let T=U,F=T.meta.origin==="result"?T.meta.resultCause:T.meta.origin==="throw"?T.meta.thrown:void 0,Z=Ce(T.error,T.meta,F);i&&i.set(_,Z),await z(_,Z,T.meta)}throw U}},k.withResource=async(R,d)=>{let h=R;try{let _=await E.withResource(R,d);return await z(h,oe(_)),_}catch(_){if(be(_)){let O=_,U=O.meta.origin==="result"?O.meta.resultCause:O.meta.origin==="throw"?O.meta.thrown:void 0,T=Ce(O.error,O.meta,U);await z(h,T,O.meta)}throw _}},k.retry=(R,d,h)=>{let _={key:h.key,retry:{attempts:h.attempts,backoff:h.backoff,initialDelay:h.initialDelay,maxDelay:h.maxDelay,jitter:h.jitter,shouldRetry:h.shouldRetry,onRetry:h.onRetry},timeout:h.timeout,ttl:h.ttl};return k(R,d,_)},k.withTimeout=(R,d,h)=>{let _={key:h.key,timeout:h,ttl:h.ttl};return k(R,d,_)},k.sleep=(R,d,h)=>{if(typeof R!="string"||R.length===0)throw new Error('[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")');let _=typeof d=="string"?Ot(d):d;if(!_)throw new Error(`step.sleep: invalid duration '${d}'`);let O=Pt(_),U=h?.signal;return k(R,async()=>{if(n?.aborted||U?.aborted){let F=new Error("Sleep aborted");throw F.name="AbortError",F}return new Promise((F,Z)=>{let re={timeoutId:void 0},N=()=>{re.timeoutId&&clearTimeout(re.timeoutId);let H=new Error("Sleep aborted");H.name="AbortError",Z(H)};n?.addEventListener("abort",N,{once:!0}),U?.addEventListener("abort",N,{once:!0}),re.timeoutId=setTimeout(()=>{n?.removeEventListener("abort",N),U?.removeEventListener("abort",N),F(oe(void 0))},O)})},{key:h?.key,ttl:h?.ttl,description:h?.description})};let J=new Map,C=new Map;return k.getWritable=R=>{let d=R?.namespace??"default",h=R?.highWaterMark??16;if(!g)throw new Error("streamStore is required to use getWritable(). Pass a streamStore to createWorkflow options.");let _=`${r}:${d}`,O=J.get(_);if(O&&!O.closed&&!O.aborted)return O.writer;let U=At({highWaterMark:h,onStateChange:H=>{j({type:"stream_backpressure",workflowId:r,namespace:d,bufferedCount:U.bufferedCount,state:H,ts:Date.now()})}}),T=0,F=!0,Z=!1,re=!1;j({type:"stream_created",workflowId:r,namespace:d,ts:Date.now()});let N={async write(H){if(re)return A(He("closed","Stream is closed"));if(Z)return A(He("aborted","Stream was aborted"));U.state==="paused"&&await U.waitForDrain();let de={value:H,position:T,ts:Date.now()},Q=await g.append(r,d,de);return Q.ok?(j({type:"stream_write",workflowId:r,namespace:d,position:T,ts:Date.now()}),T++,U.increment(),oe(void 0)):(j({type:"stream_error",workflowId:r,namespace:d,error:Q.error,position:T,ts:Date.now()}),A(He("store_error",Q.error.message,Q.error)))},async close(){if(re)return A(tt("already_closed","Stream is already closed"));let H=await g.closeStream(r,d);return H.ok?(re=!0,F=!1,j({type:"stream_close",workflowId:r,namespace:d,finalPosition:T,ts:Date.now()}),J.delete(_),oe(void 0)):A(tt("store_error",H.error.message,H.error))},abort(H){Z=!0,F=!1,re=!0,j({type:"stream_error",workflowId:r,namespace:d,error:H,position:T,ts:Date.now()}),J.delete(_)},get writable(){return F},get position(){return T},get namespace(){return d}};return J.set(_,{writer:N,backpressure:U,aborted:Z,closed:re}),N},k.getReadable=R=>{let d=R?.namespace??"default",h=R?.startIndex??0,_=R?.pollInterval??10,O=R?.pollTimeout??3e4;if(!g)throw new Error("streamStore is required to use getReadable(). Pass a streamStore to createWorkflow options.");let U=`${r}:${d}:${h}`,T=C.get(U);if(T&&!T.closed)return T.reader;let F=()=>{let he=`${r}:${d}`,ce=J.get(he);ce&&ce.backpressure.decrement()},Z=h,re=!0,N=!1,H=[],de=0,Q={async read(){if(N)return A(et("closed","Reader is closed"));if(de<H.length){let we=H[de++];return Z=we.position+1,F(),j({type:"stream_read",workflowId:r,namespace:d,position:we.position,ts:Date.now()}),oe(we.value)}let he=`${r}:${d}`,ce=Date.now(),Ee=J.has(he),ie=await g.getMetadata(r,d),fe=ie.ok&&ie.value!==void 0;for(;Date.now()-ce<O;){let we=await g.read(r,d,Z,100);if(!we.ok)return A(et("store_error",we.error.message,we.error));let Me=we.value;if(Me.length>0){H=Me,de=1;let We=Me[0];return Z=We.position+1,F(),j({type:"stream_read",workflowId:r,namespace:d,position:We.position,ts:Date.now()}),oe(We.value)}let Ue=J.has(he),Se=await g.getMetadata(r,d),at=Se.ok&&Se.value!==void 0;if(Ue&&(Ee=!0),at&&(fe=!0),Se.ok&&Se.value?.closed)return re=!1,A(qe(Z));if(Ee&&!Ue&&!at)return re=!1,A(qe(Z));fe&&!Ue&&Se.ok&&Se.value?.closed,await new Promise(We=>setTimeout(We,_))}return re=!1,A(qe(Z))},close(){N=!0,re=!1,H=[],C.delete(U)},get readable(){return re},get position(){return Z},get namespace(){return d}};return C.set(U,{reader:Q,position:Z,closed:N}),Q},k.streamForEach=async(R,d,h)=>{let _=h?.checkpointInterval??1,O=h?.concurrency??1,U=[],T=0,F=-1,Z=N=>typeof N=="object"&&N!==null&&"read"in N&&typeof N.read=="function",re=async(N,H,de,Q)=>{let ce=_>0&&H%_===0?`stream-foreach:${Q}:pos-${de}`:void 0,Ee=ce??`stream-item-${de}`,ie=await k(Ee,()=>d(N,H),{key:ce});return{index:H,position:de,result:ie}};if(Z(R))if(O<=1){let N=R.position,H=await R.read();for(;H.ok;){let de=H.value,{result:Q}=await re(de,T,N,R.namespace);U.push(Q),F=N,T++,N=R.position,H=await R.read()}}else{let N=new Map,H=0,de=0,Q=new Array(O).fill(null),he=async()=>{for(let we=0;we<Q.length;we++)if(Q[we]===null)return we;let ie=Q.filter(we=>we!==null),fe=await Promise.race(ie);return N.set(fe.index,{position:fe.position,result:fe.result}),Q[fe.slotIndex]=null,fe.slotIndex},ce=R.position,Ee=await R.read();for(;Ee.ok;){let ie=await he(),fe=H,we=ce,Me=Ee.value,Ue=ie;Q[ie]=re(Me,fe,we,R.namespace).then(Se=>({slotIndex:Ue,...Se})),de++,H++,ce=R.position,Ee=await R.read()}for(let ie=0;ie<Q.length;ie++)if(Q[ie]!==null){let fe=await Q[ie];N.set(fe.index,{position:fe.position,result:fe.result})}for(let ie=0;ie<de;ie++){let fe=N.get(ie);fe&&(U.push(fe.result),F=fe.position,T++)}}else if(O<=1){let N=0;for await(let H of R){let{result:de}=await re(H,N,N,"async-iterable");U.push(de),F=N,T++,N++}}else{let N=new Map,H=0,de=0,Q=new Array(O).fill(null),he=async()=>{for(let ie=0;ie<Q.length;ie++)if(Q[ie]===null)return ie;let ce=Q.filter(ie=>ie!==null),Ee=await Promise.race(ce);return N.set(Ee.index,Ee.result),Q[Ee.slotIndex]=null,Ee.slotIndex};for await(let ce of R){let Ee=await he(),ie=H,fe=Ee;Q[Ee]=re(ce,ie,ie,"async-iterable").then(we=>({slotIndex:fe,...we})),de++,H++}for(let ce=0;ce<Q.length;ce++)if(Q[ce]!==null){let Ee=await Q[ce];N.set(Ee.index,Ee.result)}for(let ce=0;ce<de;ce++)N.has(ce)&&(U.push(N.get(ce)),F=ce,T++)}return{results:U,processedCount:T,lastPosition:F}},k.if=E.if,k.label=E.label,k.branch=E.branch,k.arm=E.arm,k.forEach=E.forEach,k.item=E.item,k.dep=E.dep,k.workflow=(R,d,h)=>k(R,d,h),k.all=(R,d,h)=>{let _=h!==void 0&&Object.prototype.hasOwnProperty.call(h,"key")?h:{...h,key:void 0};return k(R,async()=>oe(await E.all(R,d)),_)},k.map=(R,d,h,_)=>{let O=_!==void 0&&Object.prototype.hasOwnProperty.call(_,"key")?_:{..._,key:void 0};return k(R,async()=>oe(await E.map(R,d,h,_)),O)},k},q=({step:E})=>{let k=L(E);return D({step:k,steps:je(se??{},k),deps:se,ctx:Te})},P;try{P=await Fe(q,{onError:G,onEvent:S,catchUnexpected:pe,workflowId:r,workflowName:e,context:ne,_workflowSignal:n})}finally{n&&n.removeEventListener("abort",te)}if(!P.ok&&ee.length>0){let E=[];for(let k=ee.length-1;k>=0;k--){let J=ee[k];try{await J.compensate(J.value)}catch(C){E.push({stepName:J.stepName,error:C})}}if(E.length>0){let k={type:"SAGA_COMPENSATION_ERROR",originalError:P.error,compensationErrors:E};P=A(k,{cause:P.cause})}}let Re=performance.now()-s;if(!P.ok){let E;if(Ge(P.cause)&&(E=P.cause),!E&&v&&Rt(P.error)){let k=P.cause;k!=null&&typeof k=="object"&&"name"in k&&k.name==="AbortError"&&(E={type:"WORKFLOW_CANCELLED",reason:M??(typeof n?.reason=="string"?n.reason:n?.reason instanceof Error?n.reason.message:void 0),lastStepKey:B})}if(E)return j({type:"workflow_cancelled",workflowId:r,ts:Date.now(),durationMs:Re,reason:E.reason,lastStepKey:E.lastStepKey}),E&&!Ge(P.cause)?A(P.error,{cause:E}):P}if(P.ok&&v){let E=M??(typeof n?.reason=="string"?n.reason:n?.reason instanceof Error?n.reason.message:void 0);j({type:"workflow_cancelled",workflowId:r,ts:Date.now(),durationMs:Re,reason:E,lastStepKey:B});let k={type:"WORKFLOW_CANCELLED",reason:E,lastStepKey:B};return A(pe(k),{cause:k})}return P.ok?j({type:"workflow_success",workflowId:r,ts:Date.now(),durationMs:Re}):j({type:"workflow_error",workflowId:r,ts:Date.now(),durationMs:Re,error:P.error}),P}function w(W,D,K){let r,se,ee;return typeof W=="string"?(r=W,se=D,ee=K):(se=W,ee=D),u(r,se,ee)}async function I(W,D,K){let r,se,ee;typeof W=="string"?(r=W,se=D,ee=K):(se=W,ee=D);let ge=Le(),ne=ee?.onEvent,S={...ee,onEvent:(X,le)=>{ge.handleEvent(X);try{ne?.(X,le)}catch{}}},G,ae;try{G=await u(r,se,S)}catch(X){let le=f?.catchUnexpected??$e;G=A(le(X),{cause:X})}finally{ae=ge.getResumeState()}return{result:G,resumeState:ae}}let $={withDeps:W=>rt($,W),run:w,runWithState:I};return $}var ot;function tr(){let e=new Map;return{async save(t,a){e.set(t,{snapshot:a,updatedAt:new Date})},async load(t){return e.get(t)?.snapshot??null},async delete(t){e.delete(t)},async list(t){let a=t?.prefix??"",c=t?.limit??100,f=[];for(let[u,w]of e.entries())if(!(a&&!u.startsWith(a))&&(f.push({id:u,updatedAt:w.updatedAt.toISOString()}),f.length>=c))break;return f.sort((u,w)=>w.updatedAt.localeCompare(u.updatedAt)),f},async close(){}}}function rr(){return ot===void 0&&(ot=tr()),ot}function _t(e){return typeof e.tryAcquire=="function"&&typeof e.release=="function"}var st=new Set,Ie=new Map,It={async run(e,t,a){let{id:c,store:f,version:u=1,allowConcurrent:w=!1,lockTtlMs:I=6e4,heartbeatIntervalMs:$,abortOnLeaseLoss:W,metadata:D,signal:K,createContext:r,onEvent:se,onError:ee,onVersionMismatch:ge,idempotencyKey:ne,input:n}=a,S=f??rr(),G;if(ne){let m=`idem:${ne}`,Y=Ie.get(m);if(Y)return await Y;Ie.set(m,new Promise(ue=>{G=ue}));try{let ue=await S.load(m);if(ue){if(n!==void 0&&ue.metadata?.input!==void 0){let me=JSON.stringify(ue.metadata.input),Te=JSON.stringify(n);if(me!==Te){let j=A({type:"IDEMPOTENCY_CONFLICT",idempotencyKey:ne,workflowId:c,message:`Idempotency key '${ne}' already used with different input for workflow '${c}'.`});return G(j),Ie.delete(m),G=void 0,j}}if(ue.execution.status==="completed"&&ue.metadata?.finalResult!==void 0){let me=ue.metadata.finalResult;return G(me),Ie.delete(m),G=void 0,me}if(ue.execution.status==="running"){let me=A({type:"CONCURRENT_EXECUTION",workflowId:c,message:`Workflow '${c}' with idempotency key '${ne}' is already running.`,reason:"cross-process"});return G(me),Ie.delete(m),G=void 0,me}}}catch{}try{await S.save(m,{formatVersion:1,steps:{},execution:{status:"running",lastUpdated:new Date().toISOString()},metadata:{workflowId:c,idempotencyKey:ne,input:n}})}catch{}}if(!w&&st.has(c)){let m={type:"CONCURRENT_EXECUTION",workflowId:c,message:`Workflow '${c}' is already running. Set allowConcurrent: true to allow parallel executions.`,reason:"in-process"};return A(m)}let ae=null;if(!w&&_t(S)){let m;try{m=await S.tryAcquire(c,{ttlMs:I})}catch(Y){let ue={type:"PERSISTENCE_ERROR",operation:"load",workflowId:c,cause:Y,message:`Failed to acquire lock for workflow '${c}': ${Y instanceof Error?Y.message:String(Y)}`};return A(ue)}if(m===null){let Y={type:"CONCURRENT_EXECUTION",workflowId:c,message:`Workflow '${c}' is already running (lease held by another process). Set allowConcurrent: true to allow parallel executions.`,reason:"cross-process"};return A(Y)}ae=m.ownerToken}let X,le,ye=S;if(ae&&typeof ye.renew=="function"){let m=$??Math.floor(I/3);le=new AbortController,X=setInterval(async()=>{try{await ye.renew(c,ae,{ttlMs:I})||le.abort(new Error("Lease expired"))}catch{le.abort(new Error("Lease renewal failed"))}},m)}st.add(c);let pe;try{let m=null;try{m=await S.load(c)}catch(o){let y={type:"PERSISTENCE_ERROR",operation:"load",workflowId:c,cause:o,message:`Failed to load state for workflow '${c}': ${o instanceof Error?o.message:String(o)}`};return pe=A(y),A(y)}if(m)try{bt(m)}catch(o){if(o instanceof ve){let y={type:"PERSISTENCE_ERROR",operation:"load",workflowId:c,cause:o,message:`Invalid snapshot format for workflow '${c}': ${o.message}`};return pe=A(y),A(y)}throw o}if(m){let o=typeof m.metadata?.version=="number"?m.metadata.version:1;if(o!==u){let y={type:"VERSION_MISMATCH",workflowId:c,storedVersion:o,requestedVersion:u,currentVersion:u,message:`Workflow '${c}' has stored state at version ${o} but this run requested version ${u}. Migrate the stored state to the new version, or clear state for this id (e.g. durable.deleteState(store, '${c}')) and re-run.`};if(!ge)return pe=A(y),A(y);let l=await Promise.resolve(ge({id:c,storedVersion:o,requestedVersion:u}));if(l==="throw")return pe=A(y),A(y);if(l==="clear"){try{await S.delete(c)}catch{}m=null}else m=l.migratedSnapshot}}let Y=(o,y)=>{se&&se(o,y)},ue=Le(),me={snapshot:m,onAfterStep:async(o,y,l,p)=>{try{let s=ue.getResumeState(),i={};for(let[b,v]of s.steps)if(v.result.ok)i[b]={ok:!0,value:v.result.value};else{let M=v.result.cause,B=M instanceof Error?Xe(M):Ze(M),te=v.meta?.origin==="throw"?"throw":"result";i[b]={ok:!1,error:v.result.error,cause:B,meta:{origin:te}}}let g={formatVersion:1,workflowName:c,steps:i,execution:{status:"running",lastUpdated:new Date().toISOString(),currentStepId:o},metadata:{...m?.metadata??{},...D,version:u,lastStepKey:o}},x=m?vt(m,g):g;if(x.warnings&&x.warnings.length>0){let b=new Set(Object.keys(g.steps)),v=x.warnings.filter(M=>!b.has(M.stepId));x={...x,warnings:v.length>0?v:void 0}}await S.save(c,x),Y({type:"persist_success",workflowId:l,stepKey:o,ts:Date.now(),context:p},p)}catch(s){Y({type:"persist_error",workflowId:l,stepKey:o,error:s,ts:Date.now(),context:p},p)}},onEvent:(o,y)=>{ue.handleEvent(o),Y(o,y)},onError:ee,signal:le&&K?AbortSignal.any([K,le.signal]):le?.signal??K,createContext:r},Te;try{Te=nt(c,e,me)}catch(o){if(o instanceof ve){let y={type:"PERSISTENCE_ERROR",operation:"load",workflowId:c,cause:o,message:`Invalid snapshot format for workflow '${c}': ${o.message}`};return pe=A(y),A(y)}throw o}let j;try{j=await Te.run(t)}catch(o){if(o instanceof ve||o instanceof _e){let y={type:"PERSISTENCE_ERROR",operation:"load",workflowId:c,cause:o,message:`Invalid snapshot format for workflow '${c}': ${o.message}`};return pe=A(y),A(y)}throw o}if(W!==!1&&le?.signal.aborted){let o=A({type:"LEASE_EXPIRED",workflowId:c,message:`Lease expired for workflow '${c}' during execution. The workflow may have been reclaimed by another process.`});return pe=o,o}if(j.ok){try{await S.delete(c)}catch(o){let y={type:"PERSISTENCE_ERROR",operation:"delete",workflowId:c,cause:o,message:`Failed to delete state for workflow '${c}': ${o instanceof Error?o.message:String(o)}`};return pe=A(y),A(y)}if(ne){let o=`idem:${ne}`;try{await S.save(o,{formatVersion:1,steps:{},execution:{status:"completed",lastUpdated:new Date().toISOString(),completedAt:new Date().toISOString()},metadata:{workflowId:c,idempotencyKey:ne,input:n,finalResult:j}})}catch{}}}return pe=j,j}finally{if(st.delete(c),G&&(G(pe),Ie.delete(`idem:${ne}`)),X&&clearInterval(X),ae!==null&&_t(S))try{await S.release(c,ae)}catch{}}},async clearState(e){let t=e;if(typeof t.clear=="function"){await t.clear();return}let a=100;for(;;){let c=await e.list({limit:a});if(c.length===0)break;let f=c.map(u=>u.id);if(await this.deleteStates(e,f,{continueOnError:!0}),c.length<a)break}},async hasState(e,t){try{return await e.load(t)!==null}catch{return!1}},async deleteState(e,t){try{return await e.delete(t),!0}catch{return!1}},async deleteStates(e,t,a={}){let{concurrency:c=10,continueOnError:f=!0}=a;if(t.length===0)return{deleted:0};let u=[],w=0,I=async W=>{try{await e.delete(W),w++}catch(D){if(f)u.push({id:W,error:D});else throw D}},$=Math.max(1,c);for(let W=0;W<t.length;W+=$){let D=t.slice(W,W+$);await Promise.all(D.map(K=>I(K)))}return u.length>0?{deleted:w,errors:u}:{deleted:w}},async listPending(e,t){try{return await e.list(t)}catch{return[]}}};function nr(e){let{store:t,workflows:a,concurrency:c=5,onEvent:f,onError:u}=e,w=new Map,I,$=!1,W=!1;function D(n){try{f?.(n)}catch{}}async function K(n,S){if(!a[n])throw new Error(`Unknown workflow: '${n}'. Registered: ${Object.keys(a).join(", ")}`);let ae=S?.id??`${n}:${Mt()}`,X={formatVersion:1,workflowName:n,steps:{},execution:{status:"running",lastUpdated:new Date().toISOString()},metadata:{engineState:"queued",workflowName:n,input:S?.input??null,idempotencyKey:S?.idempotencyKey,enqueuedAt:new Date().toISOString(),...S?.metadata}};return await t.save(ae,X),D({type:"workflow_enqueued",workflowName:n,id:ae,ts:Date.now()}),ae}async function r(){if(W)return 0;W=!0;try{let n=await t.list({limit:c*2}),S=0,G=[];for(let X of n){if(G.length>=c)break;let le=await t.load(X.id);le&&le.metadata?.engineState==="queued"&&typeof le.metadata?.workflowName=="string"&&G.push({id:X.id,workflowName:le.metadata.workflowName,snapshot:le})}let ae=await Promise.allSettled(G.map(async({id:X,workflowName:le,snapshot:ye})=>{let pe=a[le];if(!pe)return;let m={...ye,metadata:{...ye.metadata,engineState:"processing"}};await t.save(X,m),D({type:"workflow_started",workflowName:le,id:X,ts:Date.now()});let Y=await It.run(pe.deps,pe.fn,{id:X,store:t,idempotencyKey:ye.metadata?.idempotencyKey,input:ye.metadata?.input,...pe.durableDefaults});Y.ok?D({type:"workflow_completed",workflowName:le,id:X,ts:Date.now()}):D({type:"workflow_failed",workflowName:le,id:X,error:Y.error,ts:Date.now()}),S++}));for(let X of ae)if(X.status==="rejected")try{u?.(X.reason)}catch{}return D({type:"engine_tick",ts:Date.now(),processed:S}),S}finally{W=!1}}function se(n,S){let G=S?.id?`schedule:${S.id}`:`schedule:${Mt()}`;S.immediate&&K(n,S).catch(X=>{try{u?.(X)}catch{}});let ae=setInterval(()=>{K(n,S).catch(X=>{try{u?.(X)}catch{}})},S.intervalMs);return w.set(G,ae),D({type:"schedule_created",workflowName:n,scheduleId:G,intervalMs:S.intervalMs,ts:Date.now()}),G}function ee(n){let S=w.get(n);return S?(clearInterval(S),w.delete(n),D({type:"schedule_removed",scheduleId:n,ts:Date.now()}),!0):!1}function ge(n=1e3){$||($=!0,D({type:"engine_start",ts:Date.now()}),r().catch(S=>{try{u?.(S)}catch{}}),I=setInterval(()=>{r().catch(S=>{try{u?.(S)}catch{}})},n))}async function ne(){if($){$=!1,I&&(clearInterval(I),I=void 0);for(let[n,S]of w)clearInterval(S),w.delete(n);for(;W;)await new Promise(n=>setTimeout(n,50));D({type:"engine_stop",ts:Date.now()})}}return{enqueue:K,schedule:se,unschedule:ee,start:ge,stop:ne,tick:r,status:()=>({running:$,pendingSchedules:w.size})}}export{nr as createEngine};
|
|
11
|
-
//# sourceMappingURL=engine.js.map
|