ai-workflows 2.1.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +17 -1
  3. package/README.md +305 -184
  4. package/dist/barrier.d.ts +159 -0
  5. package/dist/barrier.d.ts.map +1 -0
  6. package/dist/barrier.js +377 -0
  7. package/dist/barrier.js.map +1 -0
  8. package/dist/cascade-context.d.ts +149 -0
  9. package/dist/cascade-context.d.ts.map +1 -0
  10. package/dist/cascade-context.js +324 -0
  11. package/dist/cascade-context.js.map +1 -0
  12. package/dist/cascade-executor.d.ts +196 -0
  13. package/dist/cascade-executor.d.ts.map +1 -0
  14. package/dist/cascade-executor.js +384 -0
  15. package/dist/cascade-executor.js.map +1 -0
  16. package/dist/context.d.ts.map +1 -1
  17. package/dist/context.js +27 -8
  18. package/dist/context.js.map +1 -1
  19. package/dist/cron-parser.d.ts +65 -0
  20. package/dist/cron-parser.d.ts.map +1 -0
  21. package/dist/cron-parser.js +294 -0
  22. package/dist/cron-parser.js.map +1 -0
  23. package/dist/cron-scheduler.d.ts +117 -0
  24. package/dist/cron-scheduler.d.ts.map +1 -0
  25. package/dist/cron-scheduler.js +176 -0
  26. package/dist/cron-scheduler.js.map +1 -0
  27. package/dist/database-context.d.ts +184 -0
  28. package/dist/database-context.d.ts.map +1 -0
  29. package/dist/database-context.js +428 -0
  30. package/dist/database-context.js.map +1 -0
  31. package/dist/dependency-graph.d.ts +157 -0
  32. package/dist/dependency-graph.d.ts.map +1 -0
  33. package/dist/dependency-graph.js +382 -0
  34. package/dist/dependency-graph.js.map +1 -0
  35. package/dist/digital-objects-adapter.d.ts +159 -0
  36. package/dist/digital-objects-adapter.d.ts.map +1 -0
  37. package/dist/digital-objects-adapter.js +229 -0
  38. package/dist/digital-objects-adapter.js.map +1 -0
  39. package/dist/durable-execution-cloudflare.d.ts +427 -0
  40. package/dist/durable-execution-cloudflare.d.ts.map +1 -0
  41. package/dist/durable-execution-cloudflare.js +510 -0
  42. package/dist/durable-execution-cloudflare.js.map +1 -0
  43. package/dist/durable-execution.d.ts +482 -0
  44. package/dist/durable-execution.d.ts.map +1 -0
  45. package/dist/durable-execution.js +594 -0
  46. package/dist/durable-execution.js.map +1 -0
  47. package/dist/durable-workflow.d.ts +176 -0
  48. package/dist/durable-workflow.d.ts.map +1 -0
  49. package/dist/durable-workflow.js +552 -0
  50. package/dist/durable-workflow.js.map +1 -0
  51. package/dist/every.d.ts +31 -2
  52. package/dist/every.d.ts.map +1 -1
  53. package/dist/every.js +63 -32
  54. package/dist/every.js.map +1 -1
  55. package/dist/graph/index.d.ts +8 -0
  56. package/dist/graph/index.d.ts.map +1 -0
  57. package/dist/graph/index.js +8 -0
  58. package/dist/graph/index.js.map +1 -0
  59. package/dist/graph/topological-sort.d.ts +121 -0
  60. package/dist/graph/topological-sort.d.ts.map +1 -0
  61. package/dist/graph/topological-sort.js +292 -0
  62. package/dist/graph/topological-sort.js.map +1 -0
  63. package/dist/index.d.ts +10 -1
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +25 -0
  66. package/dist/index.js.map +1 -1
  67. package/dist/logger.d.ts +101 -0
  68. package/dist/logger.d.ts.map +1 -0
  69. package/dist/logger.js +115 -0
  70. package/dist/logger.js.map +1 -0
  71. package/dist/on.d.ts +35 -10
  72. package/dist/on.d.ts.map +1 -1
  73. package/dist/on.js +53 -19
  74. package/dist/on.js.map +1 -1
  75. package/dist/runtime.d.ts +169 -0
  76. package/dist/runtime.d.ts.map +1 -0
  77. package/dist/runtime.js +275 -0
  78. package/dist/runtime.js.map +1 -0
  79. package/dist/send.d.ts.map +1 -1
  80. package/dist/send.js +4 -3
  81. package/dist/send.js.map +1 -1
  82. package/dist/telemetry.d.ts +150 -0
  83. package/dist/telemetry.d.ts.map +1 -0
  84. package/dist/telemetry.js +388 -0
  85. package/dist/telemetry.js.map +1 -0
  86. package/dist/timer-registry.d.ts +77 -0
  87. package/dist/timer-registry.d.ts.map +1 -0
  88. package/dist/timer-registry.js +154 -0
  89. package/dist/timer-registry.js.map +1 -0
  90. package/dist/types.d.ts +105 -6
  91. package/dist/types.d.ts.map +1 -1
  92. package/dist/types.js +17 -1
  93. package/dist/types.js.map +1 -1
  94. package/dist/worker/durable-step.d.ts +481 -0
  95. package/dist/worker/durable-step.d.ts.map +1 -0
  96. package/dist/worker/durable-step.js +606 -0
  97. package/dist/worker/durable-step.js.map +1 -0
  98. package/dist/worker/index.d.ts +106 -0
  99. package/dist/worker/index.d.ts.map +1 -0
  100. package/dist/worker/index.js +124 -0
  101. package/dist/worker/index.js.map +1 -0
  102. package/dist/worker/state-adapter.d.ts +230 -0
  103. package/dist/worker/state-adapter.d.ts.map +1 -0
  104. package/dist/worker/state-adapter.js +409 -0
  105. package/dist/worker/state-adapter.js.map +1 -0
  106. package/dist/worker/topological-executor.d.ts +282 -0
  107. package/dist/worker/topological-executor.d.ts.map +1 -0
  108. package/dist/worker/topological-executor.js +396 -0
  109. package/dist/worker/topological-executor.js.map +1 -0
  110. package/dist/worker/workflow-builder.d.ts +286 -0
  111. package/dist/worker/workflow-builder.d.ts.map +1 -0
  112. package/dist/worker/workflow-builder.js +565 -0
  113. package/dist/worker/workflow-builder.js.map +1 -0
  114. package/dist/worker.d.ts +800 -0
  115. package/dist/worker.d.ts.map +1 -0
  116. package/dist/worker.js +2428 -0
  117. package/dist/worker.js.map +1 -0
  118. package/dist/workflow-builder.d.ts +287 -0
  119. package/dist/workflow-builder.d.ts.map +1 -0
  120. package/dist/workflow-builder.js +762 -0
  121. package/dist/workflow-builder.js.map +1 -0
  122. package/dist/workflow.d.ts +14 -30
  123. package/dist/workflow.d.ts.map +1 -1
  124. package/dist/workflow.js +136 -292
  125. package/dist/workflow.js.map +1 -1
  126. package/examples/01-ecommerce-order-pipeline.ts +358 -0
  127. package/examples/02-content-moderation-cascade.ts +454 -0
  128. package/examples/03-scheduled-reporting-dependencies.ts +479 -0
  129. package/examples/04-database-persistence.ts +518 -0
  130. package/examples/README.md +173 -0
  131. package/package.json +21 -4
  132. package/src/__tests__/digital-objects-adapter.test.ts +274 -0
  133. package/src/__tests__/durable-workflow.test.ts +297 -0
  134. package/src/barrier.ts +507 -0
  135. package/src/cascade-context.ts +495 -0
  136. package/src/cascade-executor.ts +588 -0
  137. package/src/context.ts +51 -17
  138. package/src/cron-parser.ts +347 -0
  139. package/src/cron-scheduler.ts +239 -0
  140. package/src/database-context.ts +658 -0
  141. package/src/dependency-graph.ts +518 -0
  142. package/src/digital-objects-adapter.ts +351 -0
  143. package/src/durable-execution-cloudflare.ts +855 -0
  144. package/src/durable-execution.ts +1042 -0
  145. package/src/durable-workflow.ts +717 -0
  146. package/src/every.ts +104 -35
  147. package/src/graph/index.ts +19 -0
  148. package/src/graph/topological-sort.ts +412 -0
  149. package/src/index.ts +147 -0
  150. package/src/logger.ts +148 -0
  151. package/src/on.ts +81 -26
  152. package/src/runtime.ts +436 -0
  153. package/src/send.ts +4 -5
  154. package/src/telemetry.ts +577 -0
  155. package/src/timer-registry.ts +179 -0
  156. package/src/types.ts +146 -10
  157. package/src/worker/durable-step.ts +976 -0
  158. package/src/worker/index.ts +216 -0
  159. package/src/worker/state-adapter.ts +589 -0
  160. package/src/worker/topological-executor.ts +625 -0
  161. package/src/worker/workflow-builder.ts +871 -0
  162. package/src/worker.ts +2906 -0
  163. package/src/workflow-builder.ts +1068 -0
  164. package/src/workflow.ts +199 -355
  165. package/test/barrier-join.test.ts +442 -0
  166. package/test/barrier-unhandled-rejections.test.ts +359 -0
  167. package/test/cascade-context.test.ts +390 -0
  168. package/test/cascade-executor.test.ts +852 -0
  169. package/test/cron-parser.test.ts +314 -0
  170. package/test/cron-scheduler.test.ts +291 -0
  171. package/test/database-context.test.ts +770 -0
  172. package/test/db-provider-adapter.test.ts +862 -0
  173. package/test/dependency-graph.test.ts +512 -0
  174. package/test/durable-execution-cloudflare.test.ts +606 -0
  175. package/test/durable-execution-in-process.test.ts +286 -0
  176. package/test/durable-execution.test.ts +247 -0
  177. package/test/e2e/workflow-scenarios.e2e.test.ts +1039 -0
  178. package/test/graph/topological-sort.test.ts +586 -0
  179. package/test/integration.test.ts +442 -0
  180. package/test/rpc-surface.test.ts +946 -0
  181. package/test/runtime.test.ts +262 -0
  182. package/test/schedule-timer-cleanup.test.ts +353 -0
  183. package/test/send-race-conditions.test.ts +400 -0
  184. package/test/type-safety-every.test.ts +303 -0
  185. package/test/worker/durable-cascade.test.ts +1117 -0
  186. package/test/worker/durable-step.test.ts +723 -0
  187. package/test/worker/topological-executor.test.ts +1240 -0
  188. package/test/worker/workflow-builder.test.ts +1067 -0
  189. package/test/worker.test.ts +608 -0
  190. package/test/workflow-builder.test.ts +1670 -0
  191. package/test/workflow-cron.test.ts +256 -0
  192. package/test/workflow-state-adapter.test.ts +923 -0
  193. package/test/workflow.test.ts +25 -22
  194. package/tsconfig.json +3 -1
  195. package/vitest.config.ts +38 -1
  196. package/vitest.workers.config.ts +44 -0
  197. package/wrangler.jsonc +22 -0
  198. package/.turbo/turbo-test.log +0 -7
  199. package/src/context.js +0 -83
  200. package/src/every.js +0 -267
  201. package/src/index.js +0 -71
  202. package/src/on.js +0 -79
  203. package/src/send.js +0 -111
  204. package/src/types.js +0 -4
  205. package/src/workflow.js +0 -455
  206. package/test/context.test.js +0 -116
  207. package/test/every.test.js +0 -282
  208. package/test/on.test.js +0 -80
  209. package/test/send.test.js +0 -89
  210. package/test/workflow.test.js +0 -224
  211. package/vitest.config.js +0 -7
@@ -0,0 +1,800 @@
1
+ /**
2
+ * Worker Export - WorkerEntrypoint for RPC access to AI Workflows
3
+ *
4
+ * Exposes workflow functionality via Cloudflare RPC.
5
+ * Works both in Cloudflare Workers and standalone (for testing).
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * // wrangler.jsonc
10
+ * {
11
+ * "services": [
12
+ * { "binding": "WORKFLOWS", "service": "ai-workflows" }
13
+ * ]
14
+ * }
15
+ *
16
+ * // worker.ts - consuming service
17
+ * export default {
18
+ * async fetch(request: Request, env: Env) {
19
+ * const service = env.WORKFLOWS.connect()
20
+ * const workflow = service.create('my-workflow', {
21
+ * context: { userId: '123' }
22
+ * })
23
+ * await workflow.emit('Customer.created', { name: 'John' })
24
+ * return Response.json({ status: 'ok' })
25
+ * }
26
+ * }
27
+ * ```
28
+ *
29
+ * @packageDocumentation
30
+ */
31
+ import { WorkerEntrypoint, RpcTarget, WorkflowEntrypoint, WorkflowStep } from 'cloudflare:workers';
32
+ import type { WorkflowEvent } from 'cloudflare:workers';
33
+ import type { WorkflowContext, WorkflowState, WorkflowOptions, EventRegistration, ScheduleRegistration, ScheduleInterval, ParsedEvent } from './types.js';
34
+ import { WorkflowStateAdapter, type DatabaseConnection, type PersistedWorkflowState, type StepCheckpoint, type SnapshotInfo } from './worker/state-adapter.js';
35
+ /**
36
+ * Environment bindings for the worker
37
+ */
38
+ export interface Env {
39
+ DB?: DatabaseConnection;
40
+ }
41
+ /**
42
+ * Workflow instance info returned by the service
43
+ */
44
+ export interface WorkflowInstanceInfo {
45
+ id: string;
46
+ name: string;
47
+ state: WorkflowState;
48
+ eventCount: number;
49
+ scheduleCount: number;
50
+ started: boolean;
51
+ }
52
+ /**
53
+ * WorkflowServiceCore - RpcTarget wrapper around workflow functionality
54
+ *
55
+ * Exposes all required methods as RPC-callable methods.
56
+ * This is the core service class that can be instantiated directly.
57
+ *
58
+ * ## State Persistence
59
+ *
60
+ * The service supports optional state persistence via WorkflowStateAdapter.
61
+ * When a database connection is provided, workflow state is automatically
62
+ * persisted across restarts and can be queried.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * // With state persistence
67
+ * import { DB } from 'ai-database'
68
+ * import { WorkflowServiceCore } from 'ai-workflows/worker'
69
+ *
70
+ * const { db } = DB({ WorkflowState: { status: 'string' } })
71
+ * const service = new WorkflowServiceCore(db)
72
+ *
73
+ * // Create and persist workflow
74
+ * const workflow = service.create('order-processor')
75
+ * await service.persistState(workflow.id, { status: 'running' })
76
+ *
77
+ * // Query workflows by status
78
+ * const running = await service.queryByStatus('running')
79
+ * ```
80
+ */
81
+ export declare class WorkflowServiceCore extends RpcTarget {
82
+ private stateAdapter;
83
+ /**
84
+ * Create a WorkflowServiceCore instance
85
+ *
86
+ * @param database - Optional database connection for state persistence
87
+ */
88
+ constructor(database?: DatabaseConnection);
89
+ /**
90
+ * Check if state persistence is enabled
91
+ *
92
+ * @returns True if a database connection was provided
93
+ */
94
+ hasStatePersistence(): boolean;
95
+ /**
96
+ * Get the state adapter for direct access
97
+ *
98
+ * @returns WorkflowStateAdapter or null if persistence is not enabled
99
+ */
100
+ getStateAdapter(): WorkflowStateAdapter | null;
101
+ /**
102
+ * Persist workflow state to the database
103
+ *
104
+ * Saves the current state of a workflow. If the workflow doesn't exist,
105
+ * creates a new record. If it exists, updates the existing record.
106
+ *
107
+ * @param workflowId - The workflow ID
108
+ * @param state - Partial state to save (merged with existing)
109
+ * @throws Error if state persistence is not enabled
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * await service.persistState('wf-123', {
114
+ * status: 'running',
115
+ * currentStep: 'process-payment',
116
+ * context: { orderId: 'order-1' }
117
+ * })
118
+ * ```
119
+ */
120
+ persistState(workflowId: string, state: Partial<PersistedWorkflowState>): Promise<void>;
121
+ /**
122
+ * Load persisted workflow state from the database
123
+ *
124
+ * @param workflowId - The workflow ID to load
125
+ * @returns The persisted state or null if not found
126
+ * @throws Error if state persistence is not enabled
127
+ *
128
+ * @example
129
+ * ```typescript
130
+ * const state = await service.loadPersistedState('wf-123')
131
+ * if (state) {
132
+ * console.log(`Workflow status: ${state.status}`)
133
+ * console.log(`Current step: ${state.currentStep}`)
134
+ * }
135
+ * ```
136
+ */
137
+ loadPersistedState(workflowId: string): Promise<PersistedWorkflowState | null>;
138
+ /**
139
+ * Save a checkpoint for a workflow step
140
+ *
141
+ * Checkpoints track the execution state of individual steps within a workflow.
142
+ * They enable resumption from the last successful step after failures.
143
+ *
144
+ * @param workflowId - The workflow ID
145
+ * @param stepId - The step ID
146
+ * @param checkpoint - Checkpoint data including status and result
147
+ * @throws Error if state persistence is not enabled
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * await service.saveCheckpoint('wf-123', 'process-payment', {
152
+ * stepId: 'process-payment',
153
+ * status: 'completed',
154
+ * result: { transactionId: 'tx-456' },
155
+ * attempt: 1,
156
+ * completedAt: new Date()
157
+ * })
158
+ * ```
159
+ */
160
+ saveCheckpoint(workflowId: string, stepId: string, checkpoint: StepCheckpoint): Promise<void>;
161
+ /**
162
+ * Get a checkpoint for a workflow step
163
+ *
164
+ * @param workflowId - The workflow ID
165
+ * @param stepId - The step ID
166
+ * @returns The checkpoint or null if not found
167
+ * @throws Error if state persistence is not enabled
168
+ */
169
+ getCheckpoint(workflowId: string, stepId: string): Promise<StepCheckpoint | null>;
170
+ /**
171
+ * Update state with optimistic locking
172
+ *
173
+ * Only updates if the current version matches expectedVersion.
174
+ * Use this for concurrent updates to prevent lost writes.
175
+ *
176
+ * @param workflowId - The workflow ID
177
+ * @param expectedVersion - Expected current version
178
+ * @param state - State updates to apply
179
+ * @returns true if updated, false if version mismatch (concurrent modification)
180
+ * @throws Error if state persistence is not enabled
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * const state = await service.loadPersistedState('wf-123')
185
+ * const success = await service.updateStateWithVersion(
186
+ * 'wf-123',
187
+ * state.version,
188
+ * { status: 'completed' }
189
+ * )
190
+ * if (!success) {
191
+ * console.log('Concurrent modification detected, retrying...')
192
+ * }
193
+ * ```
194
+ */
195
+ updateStateWithVersion(workflowId: string, expectedVersion: number, state: Partial<PersistedWorkflowState>): Promise<boolean>;
196
+ /**
197
+ * Query workflows by status
198
+ *
199
+ * @param status - Status to filter by ('pending', 'running', 'completed', 'failed', 'paused')
200
+ * @returns Array of workflows matching the status
201
+ * @throws Error if state persistence is not enabled
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * const runningWorkflows = await service.queryByStatus('running')
206
+ * console.log(`${runningWorkflows.length} workflows currently running`)
207
+ * ```
208
+ */
209
+ queryByStatus(status: PersistedWorkflowState['status']): Promise<PersistedWorkflowState[]>;
210
+ /**
211
+ * Query multiple workflows by their IDs
212
+ *
213
+ * @param workflowIds - Array of workflow IDs to query
214
+ * @returns Array of found workflows (non-existent IDs are excluded)
215
+ * @throws Error if state persistence is not enabled
216
+ */
217
+ queryByIds(workflowIds: string[]): Promise<PersistedWorkflowState[]>;
218
+ /**
219
+ * Delete persisted workflow state
220
+ *
221
+ * @param workflowId - The workflow ID to delete
222
+ * @returns true if deleted, false if not found
223
+ * @throws Error if state persistence is not enabled
224
+ */
225
+ deletePersistedState(workflowId: string): Promise<boolean>;
226
+ /**
227
+ * List all persisted workflows with pagination
228
+ *
229
+ * @param options - Pagination options (limit, offset)
230
+ * @returns Array of workflows
231
+ * @throws Error if state persistence is not enabled
232
+ *
233
+ * @example
234
+ * ```typescript
235
+ * // Get first 10 workflows
236
+ * const workflows = await service.listPersistedWorkflows({ limit: 10, offset: 0 })
237
+ *
238
+ * // Get next page
239
+ * const nextPage = await service.listPersistedWorkflows({ limit: 10, offset: 10 })
240
+ * ```
241
+ */
242
+ listPersistedWorkflows(options?: {
243
+ limit?: number;
244
+ offset?: number;
245
+ }): Promise<PersistedWorkflowState[]>;
246
+ /**
247
+ * Create a snapshot of current workflow state
248
+ *
249
+ * Snapshots allow point-in-time recovery of workflow state.
250
+ * Useful before executing risky operations.
251
+ *
252
+ * @param workflowId - The workflow ID
253
+ * @param label - Optional human-readable label
254
+ * @returns Snapshot ID
255
+ * @throws Error if state persistence is not enabled or workflow not found
256
+ *
257
+ * @example
258
+ * ```typescript
259
+ * const snapshotId = await service.createSnapshot('wf-123', 'before-payment')
260
+ * // ... execute risky operation ...
261
+ * // If something goes wrong:
262
+ * await service.restoreSnapshot('wf-123', snapshotId)
263
+ * ```
264
+ */
265
+ createSnapshot(workflowId: string, label?: string): Promise<string>;
266
+ /**
267
+ * Restore workflow state from a snapshot
268
+ *
269
+ * @param workflowId - The workflow ID
270
+ * @param snapshotId - The snapshot ID to restore from
271
+ * @throws Error if state persistence is not enabled or snapshot not found
272
+ */
273
+ restoreSnapshot(workflowId: string, snapshotId: string): Promise<void>;
274
+ /**
275
+ * Get all snapshots for a workflow
276
+ *
277
+ * @param workflowId - The workflow ID
278
+ * @returns Array of snapshot metadata
279
+ * @throws Error if state persistence is not enabled
280
+ */
281
+ getSnapshots(workflowId: string): Promise<SnapshotInfo[]>;
282
+ /**
283
+ * Create a new workflow instance
284
+ *
285
+ * @param name - Optional workflow name
286
+ * @param options - Workflow options (initial context, etc.)
287
+ * @returns Workflow instance info including ID
288
+ */
289
+ create(name?: string, options?: WorkflowOptions): WorkflowInstanceInfo;
290
+ /**
291
+ * Create a workflow with a definition function
292
+ * The definition function receives the $ context for registering handlers
293
+ *
294
+ * @param setup - Setup function that receives $ context
295
+ * @param options - Workflow options
296
+ * @returns Workflow instance info
297
+ */
298
+ createWithSetup(setup: ($: WorkflowContext) => void, options?: WorkflowOptions): WorkflowInstanceInfo;
299
+ /**
300
+ * Start a workflow (begin processing schedules)
301
+ *
302
+ * @param workflowId - The workflow ID to start
303
+ */
304
+ start(workflowId: string): Promise<void>;
305
+ /**
306
+ * Stop a workflow
307
+ *
308
+ * @param workflowId - The workflow ID to stop
309
+ */
310
+ stop(workflowId: string): Promise<void>;
311
+ /**
312
+ * Destroy a workflow and clean up resources
313
+ *
314
+ * @param workflowId - The workflow ID to destroy
315
+ */
316
+ destroy(workflowId: string): Promise<void>;
317
+ /**
318
+ * Send an event to a workflow
319
+ *
320
+ * @param workflowId - The workflow ID
321
+ * @param event - Event name in Noun.event format (e.g., 'Customer.created')
322
+ * @param data - Event data
323
+ * @returns Event ID
324
+ */
325
+ emit<T = unknown>(workflowId: string, event: string, data: T): string;
326
+ /**
327
+ * Send an event using the global event bus (for standalone/testing)
328
+ *
329
+ * @param event - Event name
330
+ * @param data - Event data
331
+ */
332
+ sendGlobal<T = unknown>(event: string, data: T): Promise<void>;
333
+ /**
334
+ * Get workflow state
335
+ *
336
+ * @param workflowId - The workflow ID
337
+ * @returns Current workflow state
338
+ */
339
+ getState(workflowId: string): WorkflowState;
340
+ /**
341
+ * Set a value in workflow context
342
+ *
343
+ * @param workflowId - The workflow ID
344
+ * @param key - Context key
345
+ * @param value - Value to set
346
+ */
347
+ setState<T = unknown>(workflowId: string, key: string, value: T): void;
348
+ /**
349
+ * Get a value from workflow context
350
+ *
351
+ * @param workflowId - The workflow ID
352
+ * @param key - Context key
353
+ * @returns Value or undefined
354
+ */
355
+ getValue<T = unknown>(workflowId: string, key: string): T | undefined;
356
+ /**
357
+ * Get workflow info
358
+ *
359
+ * @param workflowId - The workflow ID
360
+ * @returns Workflow instance info
361
+ */
362
+ get(workflowId: string): WorkflowInstanceInfo | null;
363
+ /**
364
+ * List all workflow IDs
365
+ *
366
+ * @returns Array of workflow IDs
367
+ */
368
+ list(): string[];
369
+ /**
370
+ * Check if a workflow exists
371
+ *
372
+ * @param workflowId - The workflow ID
373
+ * @returns True if workflow exists
374
+ */
375
+ has(workflowId: string): boolean;
376
+ /**
377
+ * Register a global event handler (for standalone usage)
378
+ *
379
+ * @param noun - Noun (e.g., 'Customer')
380
+ * @param event - Event name (e.g., 'created')
381
+ * @param handler - Handler function
382
+ */
383
+ registerGlobalEvent(noun: string, event: string, handler: (data: unknown, $: WorkflowContext) => void | Promise<void>): void;
384
+ /**
385
+ * Get all global event handlers
386
+ *
387
+ * @returns Array of event registrations
388
+ */
389
+ getGlobalEventHandlers(): EventRegistration[];
390
+ /**
391
+ * Clear all global event handlers
392
+ */
393
+ clearGlobalEventHandlers(): void;
394
+ /**
395
+ * Register a global schedule handler (for standalone usage)
396
+ *
397
+ * @param interval - Schedule interval
398
+ * @param handler - Handler function
399
+ */
400
+ registerGlobalSchedule(interval: ScheduleInterval, handler: ($: WorkflowContext) => void | Promise<void>): void;
401
+ /**
402
+ * Get all global schedule handlers
403
+ *
404
+ * @returns Array of schedule registrations
405
+ */
406
+ getGlobalScheduleHandlers(): ScheduleRegistration[];
407
+ /**
408
+ * Clear all global schedule handlers
409
+ */
410
+ clearGlobalScheduleHandlers(): void;
411
+ /**
412
+ * Parse an event string into noun and event
413
+ *
414
+ * @param event - Event string (e.g., 'Customer.created')
415
+ * @returns Parsed event or null if invalid
416
+ */
417
+ parseEvent(event: string): ParsedEvent | null;
418
+ /**
419
+ * Convert a natural language schedule description to cron expression
420
+ *
421
+ * @param description - Natural language description (e.g., 'every hour', 'every Monday')
422
+ * @returns Cron expression
423
+ */
424
+ toCron(description: string): Promise<string>;
425
+ /**
426
+ * Convert a schedule interval to milliseconds
427
+ *
428
+ * @param interval - Schedule interval
429
+ * @returns Milliseconds
430
+ */
431
+ intervalToMs(interval: ScheduleInterval): number;
432
+ /**
433
+ * Format a schedule interval as a human-readable string
434
+ *
435
+ * @param interval - Schedule interval
436
+ * @returns Formatted string
437
+ */
438
+ formatInterval(interval: ScheduleInterval): string;
439
+ /**
440
+ * Create an isolated test context
441
+ *
442
+ * @returns Test context with emittedEvents tracking
443
+ */
444
+ createTestContext(): WorkflowContext & {
445
+ emittedEvents: Array<{
446
+ event: string;
447
+ data: unknown;
448
+ }>;
449
+ };
450
+ /**
451
+ * Clear all workflows (for testing)
452
+ */
453
+ clear(): void;
454
+ /**
455
+ * Register a built workflow from WorkflowBuilder
456
+ *
457
+ * @param workflow - The built workflow from WorkflowBuilder.build()
458
+ * @returns Registration info with unique ID
459
+ */
460
+ registerWorkflow(workflow: {
461
+ name: string;
462
+ steps: ReadonlyArray<{
463
+ name: string;
464
+ fn: Function;
465
+ }>;
466
+ triggers: {
467
+ events: ReadonlyArray<{
468
+ event: string;
469
+ stepName: string;
470
+ filter?: Function;
471
+ }>;
472
+ schedules: ReadonlyArray<{
473
+ schedule: string;
474
+ stepName: string;
475
+ time?: string;
476
+ timezone?: string;
477
+ }>;
478
+ };
479
+ execute?: (input?: unknown) => Promise<unknown>;
480
+ }): {
481
+ id: string;
482
+ };
483
+ /**
484
+ * Parse schedule string to ScheduleInterval
485
+ */
486
+ private parseScheduleToInterval;
487
+ }
488
+ /**
489
+ * WorkflowService - WorkerEntrypoint for RPC access
490
+ *
491
+ * Provides `connect()` method that returns an RpcTarget service
492
+ * with all workflow methods.
493
+ *
494
+ * @example
495
+ * ```typescript
496
+ * // In consuming worker
497
+ * const service = env.WORKFLOWS.connect()
498
+ * const workflow = service.create('my-workflow')
499
+ * await service.start(workflow.id)
500
+ * service.emit(workflow.id, 'Customer.created', { name: 'John' })
501
+ * ```
502
+ */
503
+ export declare class WorkflowService extends WorkerEntrypoint<Env> {
504
+ /**
505
+ * Connect to the workflow service and get an RPC-enabled service
506
+ *
507
+ * @returns WorkflowServiceCore instance for RPC calls
508
+ */
509
+ connect(): WorkflowServiceCore;
510
+ }
511
+ /**
512
+ * Test workflow event parameters
513
+ */
514
+ interface TestWorkflowParams {
515
+ testId?: string;
516
+ input?: unknown;
517
+ }
518
+ /**
519
+ * TestWorkflow - A Cloudflare Workflow class for testing DurableStep
520
+ *
521
+ * This workflow handles various test scenarios based on the workflow instance ID.
522
+ * Each test creates a workflow instance with a specific ID pattern, and this
523
+ * workflow executes the appropriate test scenario.
524
+ *
525
+ * @example
526
+ * ```typescript
527
+ * // In wrangler.jsonc
528
+ * {
529
+ * "workflows": [{
530
+ * "name": "test-workflow",
531
+ * "binding": "WORKFLOW",
532
+ * "class_name": "TestWorkflow"
533
+ * }]
534
+ * }
535
+ * ```
536
+ */
537
+ export declare class TestWorkflow extends WorkflowEntrypoint<Env, TestWorkflowParams> {
538
+ /**
539
+ * Main workflow entry point
540
+ * Routes to different test scenarios based on the workflow instance ID
541
+ */
542
+ run(event: WorkflowEvent<TestWorkflowParams>, step: WorkflowStep): Promise<unknown>;
543
+ /**
544
+ * Basic execution test - verifies DurableStep executes and returns value
545
+ */
546
+ private execTest;
547
+ /**
548
+ * Durability test - verifies step.do() is called with correct name
549
+ */
550
+ private durabilityTest;
551
+ /**
552
+ * Config test - verifies configuration is passed to step.do()
553
+ */
554
+ private configTest;
555
+ /**
556
+ * Result test - verifies correct values are returned
557
+ */
558
+ private resultTest;
559
+ /**
560
+ * Error test - verifies errors are propagated
561
+ * Explicitly disable retries so error propagates immediately
562
+ */
563
+ private errorTest;
564
+ /**
565
+ * Typed test - verifies generic types work correctly
566
+ */
567
+ private typedTest;
568
+ /**
569
+ * Void input test - verifies void input works
570
+ */
571
+ private voidInputTest;
572
+ /**
573
+ * Context test - verifies StepContext is provided
574
+ */
575
+ private ctxTest;
576
+ /**
577
+ * Metadata test - verifies step metadata is accessible
578
+ */
579
+ private metadataTest;
580
+ /**
581
+ * Side effect test - verifies ctx.do() works
582
+ */
583
+ private sideEffectTest;
584
+ /**
585
+ * Retry config test - verifies ctx.do() with config works
586
+ */
587
+ private retryConfigTest;
588
+ /**
589
+ * Side effect error test - verifies errors propagate from ctx.do()
590
+ * Explicitly disable retries so error propagates immediately
591
+ */
592
+ private sideEffectErrorTest;
593
+ /**
594
+ * Sequential test - verifies multiple ctx.do() calls work
595
+ */
596
+ private sequentialTest;
597
+ /**
598
+ * Sleep test - verifies step.sleep() works
599
+ * Note: sleep must be called at workflow level, not inside step.do()
600
+ * Using '1 second' as miniflare may not support very short durations
601
+ */
602
+ private sleepTest;
603
+ /**
604
+ * Multi-sleep test - verifies multiple sleep calls with different units
605
+ * Note: sleep must be called at workflow level, not inside step.do()
606
+ * Using standard duration formats that Cloudflare Workflows supports
607
+ */
608
+ private multiSleepTest;
609
+ /**
610
+ * Sleep until test - verifies step.sleepUntil() with Date works
611
+ * Note: sleep must be called at workflow level, not inside step.do()
612
+ */
613
+ private sleepUntilTest;
614
+ /**
615
+ * Timestamp sleep test - verifies step.sleepUntil() with timestamp works
616
+ * Note: sleep must be called at workflow level, not inside step.do()
617
+ */
618
+ private timestampSleepTest;
619
+ /**
620
+ * Step ID test - verifies step ID is exposed in metadata
621
+ */
622
+ private stepIdTest;
623
+ /**
624
+ * Attempt test - verifies attempt number is exposed
625
+ */
626
+ private attemptTest;
627
+ /**
628
+ * Retries limit test - verifies retries limit is exposed
629
+ */
630
+ private retriesLimitTest;
631
+ /**
632
+ * No retries test - verifies retries is 0 when not configured
633
+ */
634
+ private noRetriesTest;
635
+ /**
636
+ * Retry behavior test - verifies actual retry behavior
637
+ *
638
+ * Note: In Cloudflare Workflows, retries are handled by the runtime.
639
+ * Each retry is a fresh execution, so we can't track attempts across retries
640
+ * using in-memory state. Instead, we verify that a step with retries
641
+ * eventually succeeds after initial failures.
642
+ *
643
+ * We use a counter stored in the step context to track attempts.
644
+ */
645
+ private retryBehaviorTest;
646
+ /**
647
+ * Timeout test - verifies timeout behavior
648
+ */
649
+ private timeoutTest;
650
+ /**
651
+ * Exponential backoff test - verifies exponential backoff config
652
+ */
653
+ private expBackoffTest;
654
+ /**
655
+ * Linear backoff test - verifies linear backoff config
656
+ */
657
+ private linearBackoffTest;
658
+ /**
659
+ * Constant backoff test - verifies constant backoff config
660
+ */
661
+ private constantBackoffTest;
662
+ /**
663
+ * No retry error test - verifies immediate failure without retries
664
+ * Explicitly disable retries to ensure error propagates immediately
665
+ */
666
+ private noRetryErrorTest;
667
+ /**
668
+ * Sequential steps test - verifies multiple DurableSteps run sequentially
669
+ */
670
+ private sequentialStepsTest;
671
+ /**
672
+ * Factory test - verifies DurableStep factory pattern
673
+ */
674
+ private factoryTest;
675
+ /**
676
+ * Parallel test - verifies parallel DurableStep execution
677
+ */
678
+ private parallelTest;
679
+ /**
680
+ * Persist before test - verifies state is persisted before execution
681
+ */
682
+ private persistBeforeTest;
683
+ /**
684
+ * Persist after test - verifies state is persisted after execution
685
+ */
686
+ private persistAfterTest;
687
+ /**
688
+ * Resume test - verifies workflow resumes from last successful step
689
+ */
690
+ private resumeTest;
691
+ /**
692
+ * History test - verifies execution history is tracked
693
+ */
694
+ private historyTest;
695
+ /**
696
+ * Graceful timeout test - verifies timeout is handled gracefully
697
+ */
698
+ private gracefulTimeoutTest;
699
+ /**
700
+ * After timeout test - verifies subsequent steps work after timeout handling
701
+ */
702
+ private afterTimeoutTest;
703
+ /**
704
+ * Per-step timeout test - verifies different timeouts per step
705
+ */
706
+ private perStepTimeoutTest;
707
+ /**
708
+ * Service integration test - verifies DurableStep works with WorkflowService
709
+ */
710
+ private serviceIntegrationTest;
711
+ /**
712
+ * Context access test - verifies workflow context is accessible
713
+ */
714
+ private contextAccessTest;
715
+ /**
716
+ * State sharing test - verifies state can be shared between steps
717
+ */
718
+ private stateSharingTest;
719
+ /**
720
+ * Empty input test - verifies empty/undefined input is handled
721
+ */
722
+ private emptyInputTest;
723
+ /**
724
+ * Large input test - verifies large input data is handled
725
+ */
726
+ private largeInputTest;
727
+ /**
728
+ * Large output test - verifies large output data is handled
729
+ */
730
+ private largeOutputTest;
731
+ /**
732
+ * Nested do test - verifies nested ctx.do() calls work
733
+ */
734
+ private nestedDoTest;
735
+ /**
736
+ * Concurrent test - verifies concurrent workflow instances work
737
+ */
738
+ private concurrentTest;
739
+ private cascadeOrderTest;
740
+ private cascadeShortcircuitTest;
741
+ private cascadeEscalateTest;
742
+ private cascadeSkipTest;
743
+ private aiHumanFallbackTest;
744
+ private aiErrorContextTest;
745
+ private aiReasoningTest;
746
+ private customEscalationTest;
747
+ private fastSlowModelTest;
748
+ private modelCascadeTest;
749
+ private customModelOrderTest;
750
+ private modelTimeoutTest;
751
+ private aiGatewayCacheTest;
752
+ private tierTimeoutConfigTest;
753
+ private defaultTimeoutTest;
754
+ private timeoutEscalationTest;
755
+ private timeoutRecordTest;
756
+ private totalTimeoutTest;
757
+ private returnSuccessTest;
758
+ private throwFailureTest;
759
+ private customSuccessTest;
760
+ private partialSuccessTest;
761
+ private retryBeforeEscalateTest;
762
+ private resultAccumulateTest;
763
+ private resultMergeTest;
764
+ private individualResultsTest;
765
+ private customMergerTest;
766
+ private tierMetadataTest;
767
+ private errorPropagateTest;
768
+ private errorAccumulateTest;
769
+ private allTiersFailTest;
770
+ private errorHistoryTest;
771
+ private customErrorHandlerTest;
772
+ private errorTransformTest;
773
+ private durableCheckpointTest;
774
+ private cascadeResumeTest;
775
+ private durableIoTest;
776
+ private cascadeSnapshotTest;
777
+ private auditWhoTest;
778
+ private auditWhatTest;
779
+ private auditWhenTest;
780
+ private auditWhereTest;
781
+ private auditWhyTest;
782
+ private auditHowTest;
783
+ private auditPersistTest;
784
+ private aiGatewayBindingTest;
785
+ private aiGatewayCachingTest;
786
+ private aiContextTest;
787
+ private aiGatewayErrorTest;
788
+ private cascadeContextTest;
789
+ private fivewhEventsTest;
790
+ private metricsTest;
791
+ }
792
+ /**
793
+ * Default export for Cloudflare Workers
794
+ */
795
+ declare const _default: {
796
+ fetch: () => Response;
797
+ };
798
+ export default _default;
799
+ export { WorkflowService as WorkflowWorker };
800
+ //# sourceMappingURL=worker.d.ts.map