@workflow/core 5.0.0-beta.9 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (339) hide show
  1. package/README.md +41 -0
  2. package/dist/attribute-changes.d.ts +4 -5
  3. package/dist/attribute-changes.d.ts.map +1 -1
  4. package/dist/attribute-changes.js +12 -4
  5. package/dist/capabilities.d.ts +35 -2
  6. package/dist/capabilities.d.ts.map +1 -1
  7. package/dist/capabilities.js +74 -5
  8. package/dist/capture-stack.d.ts +1 -1
  9. package/dist/capture-stack.js +2 -2
  10. package/dist/class-serialization.d.ts +32 -0
  11. package/dist/class-serialization.d.ts.map +1 -1
  12. package/dist/class-serialization.js +37 -1
  13. package/dist/classify-error.d.ts +15 -0
  14. package/dist/classify-error.d.ts.map +1 -1
  15. package/dist/classify-error.js +72 -4
  16. package/dist/context-violation-error.d.ts +5 -5
  17. package/dist/context-violation-error.d.ts.map +1 -1
  18. package/dist/context-violation-error.js +8 -6
  19. package/dist/create-hook.d.ts +109 -7
  20. package/dist/create-hook.d.ts.map +1 -1
  21. package/dist/create-hook.js +1 -1
  22. package/dist/define-hook.js +2 -2
  23. package/dist/describe-error.d.ts +7 -7
  24. package/dist/describe-error.d.ts.map +1 -1
  25. package/dist/describe-error.js +46 -7
  26. package/dist/encryption.d.ts +32 -4
  27. package/dist/encryption.d.ts.map +1 -1
  28. package/dist/encryption.js +85 -10
  29. package/dist/events-consumer.d.ts +300 -0
  30. package/dist/events-consumer.d.ts.map +1 -1
  31. package/dist/events-consumer.js +672 -42
  32. package/dist/flushable-stream.d.ts +97 -1
  33. package/dist/flushable-stream.d.ts.map +1 -1
  34. package/dist/flushable-stream.js +286 -10
  35. package/dist/global.d.ts +38 -2
  36. package/dist/global.d.ts.map +1 -1
  37. package/dist/global.js +21 -6
  38. package/dist/index.d.ts +2 -2
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +3 -3
  41. package/dist/log-format.d.ts +6 -2
  42. package/dist/log-format.d.ts.map +1 -1
  43. package/dist/log-format.js +60 -15
  44. package/dist/logger.d.ts +1 -0
  45. package/dist/logger.d.ts.map +1 -1
  46. package/dist/logger.js +10 -6
  47. package/dist/private.d.ts +258 -9
  48. package/dist/private.d.ts.map +1 -1
  49. package/dist/private.js +640 -7
  50. package/dist/replay-divergence.d.ts +25 -0
  51. package/dist/replay-divergence.d.ts.map +1 -0
  52. package/dist/replay-divergence.js +61 -0
  53. package/dist/replay-payload-cache.d.ts +64 -0
  54. package/dist/replay-payload-cache.d.ts.map +1 -0
  55. package/dist/replay-payload-cache.js +158 -0
  56. package/dist/runtime/compute-instance.d.ts +13 -0
  57. package/dist/runtime/compute-instance.d.ts.map +1 -0
  58. package/dist/runtime/compute-instance.js +14 -0
  59. package/dist/runtime/constants.d.ts +298 -5
  60. package/dist/runtime/constants.d.ts.map +1 -1
  61. package/dist/runtime/constants.js +500 -17
  62. package/dist/runtime/count-step-started-events.d.ts +52 -0
  63. package/dist/runtime/count-step-started-events.d.ts.map +1 -0
  64. package/dist/runtime/count-step-started-events.js +72 -0
  65. package/dist/runtime/deployment-guard.d.ts +100 -0
  66. package/dist/runtime/deployment-guard.d.ts.map +1 -0
  67. package/dist/runtime/deployment-guard.js +159 -0
  68. package/dist/runtime/dynamic-workflow.d.ts +148 -0
  69. package/dist/runtime/dynamic-workflow.d.ts.map +1 -0
  70. package/dist/runtime/dynamic-workflow.js +290 -0
  71. package/dist/runtime/get-port-lazy.d.ts +15 -0
  72. package/dist/runtime/get-port-lazy.d.ts.map +1 -1
  73. package/dist/runtime/get-port-lazy.js +75 -6
  74. package/dist/runtime/get-world-lazy.d.ts +5 -14
  75. package/dist/runtime/get-world-lazy.d.ts.map +1 -1
  76. package/dist/runtime/get-world-lazy.js +19 -29
  77. package/dist/runtime/helpers.d.ts +445 -29
  78. package/dist/runtime/helpers.d.ts.map +1 -1
  79. package/dist/runtime/helpers.js +717 -62
  80. package/dist/runtime/hook-wake.d.ts +122 -0
  81. package/dist/runtime/hook-wake.d.ts.map +1 -0
  82. package/dist/runtime/hook-wake.js +225 -0
  83. package/dist/runtime/invocations.d.ts +35 -0
  84. package/dist/runtime/invocations.d.ts.map +1 -0
  85. package/dist/runtime/invocations.js +172 -0
  86. package/dist/runtime/lifecycle-hooks.d.ts +93 -0
  87. package/dist/runtime/lifecycle-hooks.d.ts.map +1 -0
  88. package/dist/runtime/lifecycle-hooks.js +178 -0
  89. package/dist/runtime/open-hook-wait-state.d.ts +55 -0
  90. package/dist/runtime/open-hook-wait-state.d.ts.map +1 -0
  91. package/dist/runtime/open-hook-wait-state.js +93 -0
  92. package/dist/runtime/quickjs-assets.generated.d.ts +14 -0
  93. package/dist/runtime/quickjs-assets.generated.d.ts.map +1 -0
  94. package/dist/runtime/quickjs-assets.generated.js +30 -0
  95. package/dist/runtime/quickjs-entrypoint.d.ts +158 -0
  96. package/dist/runtime/quickjs-entrypoint.d.ts.map +1 -0
  97. package/dist/runtime/quickjs-entrypoint.js +1939 -0
  98. package/dist/runtime/quickjs-log-view.d.ts +129 -0
  99. package/dist/runtime/quickjs-log-view.d.ts.map +1 -0
  100. package/dist/runtime/quickjs-log-view.js +229 -0
  101. package/dist/runtime/quickjs-runtime.d.ts +247 -0
  102. package/dist/runtime/quickjs-runtime.d.ts.map +1 -0
  103. package/dist/runtime/quickjs-runtime.js +2599 -0
  104. package/dist/runtime/quickjs-serde.d.ts +107 -0
  105. package/dist/runtime/quickjs-serde.d.ts.map +1 -0
  106. package/dist/runtime/quickjs-serde.js +2234 -0
  107. package/dist/runtime/replay-budget.d.ts +17 -18
  108. package/dist/runtime/replay-budget.d.ts.map +1 -1
  109. package/dist/runtime/replay-budget.js +33 -81
  110. package/dist/runtime/replay-recovery-reporter.d.ts +36 -0
  111. package/dist/runtime/replay-recovery-reporter.d.ts.map +1 -0
  112. package/dist/runtime/replay-recovery-reporter.js +64 -0
  113. package/dist/runtime/resume-hook.d.ts +93 -8
  114. package/dist/runtime/resume-hook.d.ts.map +1 -1
  115. package/dist/runtime/resume-hook.js +709 -110
  116. package/dist/runtime/resume-latency.d.ts +150 -0
  117. package/dist/runtime/resume-latency.d.ts.map +1 -0
  118. package/dist/runtime/resume-latency.js +155 -0
  119. package/dist/runtime/run-id-time.d.ts +19 -0
  120. package/dist/runtime/run-id-time.d.ts.map +1 -0
  121. package/dist/runtime/run-id-time.js +42 -0
  122. package/dist/runtime/run-spec-version.d.ts +16 -0
  123. package/dist/runtime/run-spec-version.d.ts.map +1 -0
  124. package/dist/runtime/run-spec-version.js +19 -0
  125. package/dist/runtime/run.d.ts +72 -7
  126. package/dist/runtime/run.d.ts.map +1 -1
  127. package/dist/runtime/run.js +295 -58
  128. package/dist/runtime/runs.d.ts +54 -3
  129. package/dist/runtime/runs.d.ts.map +1 -1
  130. package/dist/runtime/runs.js +148 -21
  131. package/dist/runtime/start.d.ts +164 -3
  132. package/dist/runtime/start.d.ts.map +1 -1
  133. package/dist/runtime/start.js +700 -78
  134. package/dist/runtime/step-executor.d.ts +186 -5
  135. package/dist/runtime/step-executor.d.ts.map +1 -1
  136. package/dist/runtime/step-executor.js +756 -123
  137. package/dist/runtime/step-latency.d.ts +221 -0
  138. package/dist/runtime/step-latency.d.ts.map +1 -0
  139. package/dist/runtime/step-latency.js +215 -0
  140. package/dist/runtime/step-ownership.d.ts +72 -0
  141. package/dist/runtime/step-ownership.d.ts.map +1 -0
  142. package/dist/runtime/step-ownership.js +114 -0
  143. package/dist/runtime/step-single-flight.d.ts +12 -0
  144. package/dist/runtime/step-single-flight.d.ts.map +1 -0
  145. package/dist/runtime/step-single-flight.js +71 -0
  146. package/dist/runtime/suspension-handler.d.ts +279 -10
  147. package/dist/runtime/suspension-handler.d.ts.map +1 -1
  148. package/dist/runtime/suspension-handler.js +1442 -169
  149. package/dist/runtime/unserializable-step.d.ts +34 -0
  150. package/dist/runtime/unserializable-step.d.ts.map +1 -0
  151. package/dist/runtime/unserializable-step.js +52 -0
  152. package/dist/runtime/vm-mode.d.ts +44 -0
  153. package/dist/runtime/vm-mode.d.ts.map +1 -0
  154. package/dist/runtime/vm-mode.js +62 -0
  155. package/dist/runtime/vm-serde-bundle.generated.d.ts +14 -0
  156. package/dist/runtime/vm-serde-bundle.generated.d.ts.map +1 -0
  157. package/dist/runtime/vm-serde-bundle.generated.js +16 -0
  158. package/dist/runtime/wait-continuation.d.ts +106 -0
  159. package/dist/runtime/wait-continuation.d.ts.map +1 -0
  160. package/dist/runtime/wait-continuation.js +136 -0
  161. package/dist/runtime/wait-until.d.ts +18 -0
  162. package/dist/runtime/wait-until.d.ts.map +1 -0
  163. package/dist/runtime/wait-until.js +42 -0
  164. package/dist/runtime/world-compatibility.d.ts +32 -0
  165. package/dist/runtime/world-compatibility.d.ts.map +1 -0
  166. package/dist/runtime/world-compatibility.js +44 -0
  167. package/dist/runtime/world-init.d.ts +17 -42
  168. package/dist/runtime/world-init.d.ts.map +1 -1
  169. package/dist/runtime/world-init.js +18 -43
  170. package/dist/runtime/world.d.ts +14 -2
  171. package/dist/runtime/world.d.ts.map +1 -1
  172. package/dist/runtime/world.js +75 -19
  173. package/dist/runtime.d.ts +11 -7
  174. package/dist/runtime.d.ts.map +1 -1
  175. package/dist/runtime.js +4111 -446
  176. package/dist/schemas.d.ts +1 -1
  177. package/dist/schemas.d.ts.map +1 -1
  178. package/dist/schemas.js +1 -1
  179. package/dist/sealed-box.d.ts +167 -0
  180. package/dist/sealed-box.d.ts.map +1 -0
  181. package/dist/sealed-box.js +571 -0
  182. package/dist/serialization/client.d.ts +3 -3
  183. package/dist/serialization/client.d.ts.map +1 -1
  184. package/dist/serialization/client.js +8 -4
  185. package/dist/serialization/codec-devalue-vm.d.ts +16 -0
  186. package/dist/serialization/codec-devalue-vm.d.ts.map +1 -0
  187. package/dist/serialization/codec-devalue-vm.js +148 -0
  188. package/dist/serialization/codec-devalue.d.ts +1 -1
  189. package/dist/serialization/codec-devalue.d.ts.map +1 -1
  190. package/dist/serialization/codec-devalue.js +24 -6
  191. package/dist/serialization/codec.d.ts +37 -2
  192. package/dist/serialization/codec.d.ts.map +1 -1
  193. package/dist/serialization/codec.js +2 -2
  194. package/dist/serialization/compression.d.ts +105 -0
  195. package/dist/serialization/compression.d.ts.map +1 -0
  196. package/dist/serialization/compression.js +261 -0
  197. package/dist/serialization/encryption.d.ts +119 -17
  198. package/dist/serialization/encryption.d.ts.map +1 -1
  199. package/dist/serialization/encryption.js +152 -17
  200. package/dist/serialization/errors.d.ts +13 -0
  201. package/dist/serialization/errors.d.ts.map +1 -1
  202. package/dist/serialization/errors.js +20 -2
  203. package/dist/serialization/format.d.ts +6 -6
  204. package/dist/serialization/format.js +7 -7
  205. package/dist/serialization/hardened.d.ts +156 -0
  206. package/dist/serialization/hardened.d.ts.map +1 -0
  207. package/dist/serialization/hardened.js +538 -0
  208. package/dist/serialization/index.d.ts +10 -8
  209. package/dist/serialization/index.d.ts.map +1 -1
  210. package/dist/serialization/index.js +10 -8
  211. package/dist/serialization/reducers/class-vm.d.ts +20 -0
  212. package/dist/serialization/reducers/class-vm.d.ts.map +1 -0
  213. package/dist/serialization/reducers/class-vm.js +77 -0
  214. package/dist/serialization/reducers/class.d.ts.map +1 -1
  215. package/dist/serialization/reducers/class.js +11 -6
  216. package/dist/serialization/reducers/common-vm.d.ts +15 -0
  217. package/dist/serialization/reducers/common-vm.d.ts.map +1 -0
  218. package/dist/serialization/reducers/common-vm.js +661 -0
  219. package/dist/serialization/reducers/common.d.ts +1 -1
  220. package/dist/serialization/reducers/common.d.ts.map +1 -1
  221. package/dist/serialization/reducers/common.js +227 -66
  222. package/dist/serialization/reducers/step-function-vm.d.ts +44 -0
  223. package/dist/serialization/reducers/step-function-vm.d.ts.map +1 -0
  224. package/dist/serialization/reducers/step-function-vm.js +97 -0
  225. package/dist/serialization/reducers/step-function.d.ts.map +1 -1
  226. package/dist/serialization/reducers/step-function.js +25 -9
  227. package/dist/serialization/step.d.ts +4 -4
  228. package/dist/serialization/step.d.ts.map +1 -1
  229. package/dist/serialization/step.js +9 -5
  230. package/dist/serialization/types.d.ts +75 -1
  231. package/dist/serialization/types.d.ts.map +1 -1
  232. package/dist/serialization/types.js +15 -1
  233. package/dist/serialization/workflow-vm.d.ts +29 -0
  234. package/dist/serialization/workflow-vm.d.ts.map +1 -0
  235. package/dist/serialization/workflow-vm.js +74 -0
  236. package/dist/serialization-format.d.ts +64 -8
  237. package/dist/serialization-format.d.ts.map +1 -1
  238. package/dist/serialization-format.js +239 -73
  239. package/dist/serialization.d.ts +319 -34
  240. package/dist/serialization.d.ts.map +1 -1
  241. package/dist/serialization.js +1961 -321
  242. package/dist/set-attributes.d.ts +7 -7
  243. package/dist/set-attributes.d.ts.map +1 -1
  244. package/dist/set-attributes.js +42 -21
  245. package/dist/source-map.d.ts +25 -0
  246. package/dist/source-map.d.ts.map +1 -1
  247. package/dist/source-map.js +113 -7
  248. package/dist/step/context-storage.d.ts +50 -3
  249. package/dist/step/context-storage.d.ts.map +1 -1
  250. package/dist/step/context-storage.js +7 -5
  251. package/dist/step/writable-stream.d.ts +3 -3
  252. package/dist/step/writable-stream.d.ts.map +1 -1
  253. package/dist/step/writable-stream.js +53 -19
  254. package/dist/step.d.ts.map +1 -1
  255. package/dist/step.js +142 -28
  256. package/dist/symbols.d.ts +35 -1
  257. package/dist/symbols.d.ts.map +1 -1
  258. package/dist/symbols.js +36 -2
  259. package/dist/telemetry/semantic-conventions.d.ts +481 -2
  260. package/dist/telemetry/semantic-conventions.d.ts.map +1 -1
  261. package/dist/telemetry/semantic-conventions.js +349 -3
  262. package/dist/telemetry.d.ts +91 -0
  263. package/dist/telemetry.d.ts.map +1 -1
  264. package/dist/telemetry.js +244 -17
  265. package/dist/test-support/orchestrator-context.d.ts +25 -0
  266. package/dist/test-support/orchestrator-context.d.ts.map +1 -0
  267. package/dist/test-support/orchestrator-context.js +107 -0
  268. package/dist/types.d.ts +23 -0
  269. package/dist/types.d.ts.map +1 -1
  270. package/dist/types.js +76 -1
  271. package/dist/util.d.ts +0 -5
  272. package/dist/util.d.ts.map +1 -1
  273. package/dist/util.js +1 -15
  274. package/dist/version.d.ts +1 -1
  275. package/dist/version.d.ts.map +1 -1
  276. package/dist/version.js +2 -2
  277. package/dist/vm/index.d.ts.map +1 -1
  278. package/dist/vm/index.js +84 -14
  279. package/dist/vm/script-cache.d.ts +26 -0
  280. package/dist/vm/script-cache.d.ts.map +1 -0
  281. package/dist/vm/script-cache.js +131 -0
  282. package/dist/vm/uint8array-base64.js +1 -1
  283. package/dist/workflow/abort-controller.d.ts +2 -2
  284. package/dist/workflow/abort-controller.d.ts.map +1 -1
  285. package/dist/workflow/abort-controller.js +75 -21
  286. package/dist/workflow/attribute-dispatcher.d.ts +6 -0
  287. package/dist/workflow/attribute-dispatcher.d.ts.map +1 -0
  288. package/dist/workflow/attribute-dispatcher.js +65 -0
  289. package/dist/workflow/create-hook.d.ts.map +1 -1
  290. package/dist/workflow/create-hook.js +24 -3
  291. package/dist/workflow/get-workflow-metadata.js +2 -2
  292. package/dist/workflow/hook.d.ts.map +1 -1
  293. package/dist/workflow/hook.js +403 -53
  294. package/dist/workflow/index.d.ts +1 -1
  295. package/dist/workflow/index.d.ts.map +1 -1
  296. package/dist/workflow/index.js +2 -2
  297. package/dist/workflow/set-attributes.d.ts +19 -21
  298. package/dist/workflow/set-attributes.d.ts.map +1 -1
  299. package/dist/workflow/set-attributes.js +23 -25
  300. package/dist/workflow/sleep.d.ts.map +1 -1
  301. package/dist/workflow/sleep.js +42 -13
  302. package/dist/workflow/world-init-stub.d.ts +3 -3
  303. package/dist/workflow/world-init-stub.js +4 -4
  304. package/dist/workflow.d.ts +89 -3
  305. package/dist/workflow.d.ts.map +1 -1
  306. package/dist/workflow.js +920 -568
  307. package/docs/api-reference/create-hook.mdx +166 -10
  308. package/docs/api-reference/create-webhook.mdx +16 -15
  309. package/docs/api-reference/define-hook.mdx +37 -33
  310. package/docs/api-reference/fatal-error.mdx +30 -8
  311. package/docs/api-reference/fetch.mdx +14 -10
  312. package/docs/api-reference/get-step-metadata.mdx +2 -2
  313. package/docs/api-reference/get-workflow-metadata.mdx +3 -3
  314. package/docs/api-reference/get-writable.mdx +7 -7
  315. package/docs/api-reference/index.mdx +3 -3
  316. package/docs/api-reference/retryable-error.mdx +1 -1
  317. package/docs/api-reference/set-attributes.mdx +63 -0
  318. package/docs/api-reference/sleep.mdx +4 -4
  319. package/docs/foundations/cancellation.mdx +31 -32
  320. package/docs/foundations/errors-and-retries.mdx +54 -11
  321. package/docs/foundations/hooks.mdx +98 -35
  322. package/docs/foundations/idempotency.mdx +267 -12
  323. package/docs/foundations/index.mdx +1 -26
  324. package/docs/foundations/serialization.mdx +22 -22
  325. package/docs/foundations/starting-workflows.mdx +104 -30
  326. package/docs/foundations/streaming.mdx +108 -60
  327. package/docs/foundations/versioning.mdx +4 -4
  328. package/docs/foundations/workflows-and-steps.mdx +9 -9
  329. package/docs/how-it-works/cancellation.mdx +63 -63
  330. package/docs/how-it-works/code-transform.mdx +82 -66
  331. package/docs/how-it-works/encryption.mdx +30 -26
  332. package/docs/how-it-works/event-sourcing.mdx +132 -35
  333. package/docs/how-it-works/framework-integrations.mdx +96 -337
  334. package/docs/how-it-works/understanding-directives.mdx +22 -22
  335. package/package.json +29 -15
  336. package/dist/runtime/step-handler.d.ts +0 -2
  337. package/dist/runtime/step-handler.d.ts.map +0 -1
  338. package/dist/runtime/step-handler.js +0 -779
  339. package/docs/api-reference/experimental-set-attributes.mdx +0 -63
@@ -8,6 +8,7 @@ prerequisites:
8
8
  related:
9
9
  - /docs/api-reference/workflow/define-hook
10
10
  - /docs/api-reference/workflow/create-webhook
11
+ - /docs/foundations/idempotency
11
12
  ---
12
13
 
13
14
  Creates a low-level hook primitive that can be used to resume a workflow run with arbitrary payloads.
@@ -25,7 +26,7 @@ export async function hookWorkflow() {
25
26
  }
26
27
  ```
27
28
 
28
- ## API Signature
29
+ ## API signature
29
30
 
30
31
  ### Parameters
31
32
 
@@ -65,9 +66,11 @@ export default Hook;`}
65
66
 
66
67
  The returned `Hook` object also implements `AsyncIterable<T>`, which allows you to iterate over incoming payloads using `for await...of` syntax.
67
68
 
69
+ Use `hook.getConflict()` to check whether the hook token is already claimed by another hook, including one kept reserved after its run ends, without waiting for hook payload data. Calling `createHook()` on its own does not register the hook: registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the registration, then resolves with `null` once `hook_created` is recorded, or with the conflicting [`Run`](/docs/api-reference/workflow-api/get-run).
70
+
68
71
  ## Examples
69
72
 
70
- ### Basic Usage
73
+ ### Basic usage
71
74
 
72
75
  When creating a hook, you can specify a payload type for automatic type safety:
73
76
 
@@ -88,7 +91,7 @@ export async function approvalWorkflow() {
88
91
  }
89
92
  ```
90
93
 
91
- ### Customizing Tokens
94
+ ### Customizing tokens
92
95
 
93
96
  Tokens are used to identify a specific hook. You can customize the token to be more specific to a use case.
94
97
 
@@ -112,7 +115,159 @@ export async function slackBotWorkflow(channelId: string) {
112
115
  }
113
116
  ```
114
117
 
115
- ### Waiting for Multiple Payloads
118
+ ### Detecting token conflicts
119
+
120
+ Use `hook.getConflict()` when the workflow needs to claim a hook token before doing other work, but does not need a payload yet:
121
+
122
+ ```typescript lineNumbers
123
+ import { createHook } from "workflow";
124
+
125
+ declare function chargeOrder(orderId: string): Promise<void>; // @setup
126
+
127
+ async function processOrder(orderId: string) {
128
+ "use workflow";
129
+
130
+ using hook = createHook({ // [!code highlight]
131
+ token: `order:${orderId}` // [!code highlight]
132
+ }); // [!code highlight]
133
+
134
+ const conflict = await hook.getConflict(); // [!code highlight]
135
+ if (conflict) { // [!code highlight]
136
+ // Another active workflow run already owns this token.
137
+ return { dedupedTo: conflict.runId };
138
+ }
139
+
140
+ await chargeOrder(orderId);
141
+ }
142
+ ```
143
+
144
+ Because `createHook()` alone does not suspend the workflow, awaiting `hook.getConflict()` is what actually suspends the run and commits the hook registration. It only waits for registration. To receive payload data from a future `resumeHook()` call, await the hook itself or iterate it with `for await...of`.
145
+
146
+ ### Registering a hook before a step uses it
147
+
148
+ A hook's registration is committed alongside everything else the workflow started before it suspended, not ahead of it. When a workflow creates a hook and calls a step without awaiting anything in between, the step can start running before the hook is registered, and it can run even if the registration turns out to conflict. That matters in two cases:
149
+
150
+ - The step hands the token to something that may call `resumeHook()` right away, which throws `HookNotFoundError` until the hook exists.
151
+ - The hook guards against duplicate runs. A run that only learns of the conflict after calling the step, for example by awaiting the hook and letting `HookConflictError` end the run, may already have started that step.
152
+
153
+ In either case, await `hook.getConflict()` before calling the step:
154
+
155
+ ```typescript lineNumbers
156
+ import { createHook } from "workflow";
157
+
158
+ declare function requestApproval(token: string): Promise<void>; // @setup
159
+
160
+ async function approvalWorkflow() {
161
+ "use workflow";
162
+
163
+ using hook = createHook<{ approved: boolean }>();
164
+ await hook.getConflict(); // [!code highlight]
165
+
166
+ // The hook is registered, so an approver that resumes it immediately
167
+ // finds it.
168
+ await requestApproval(hook.token);
169
+
170
+ const { approved } = await hook;
171
+ return approved;
172
+ }
173
+ ```
174
+
175
+ On a conflict, the resolved value is a `Run` handle for the run that owns the token, with durable step-backed accessors. The duplicate run can decide in code how to handle it: return or log `conflict.runId`, inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()` and continue in the current run. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies in context.
176
+
177
+ <Callout type="info">
178
+ Custom hook tokens are the recommended way to coordinate active workflow runs. Use a deterministic token from your domain, such as an order ID or conversation ID, create the hook near the beginning of the workflow, and check `await hook.getConflict()` before work that depends on owning the token. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
179
+ </Callout>
180
+
181
+ ### Keep a token unavailable after the run ends
182
+
183
+ By default, another Hook can use the token after its workflow ends. Set `experimental_minRetention` to keep the token unavailable for at least a specific time after `createHook()` runs:
184
+
185
+ ```typescript lineNumbers
186
+ import { createHook } from "workflow";
187
+
188
+ declare function processOwnedOrder(orderId: string): Promise<void>; // @setup
189
+
190
+ export async function processOrder(orderId: string) {
191
+ "use workflow";
192
+
193
+ const hook = createHook({ // [!code highlight]
194
+ token: `order:${orderId}`, // [!code highlight]
195
+ experimental_minRetention: "30d", // [!code highlight]
196
+ }); // [!code highlight]
197
+
198
+ const conflict = await hook.getConflict();
199
+ if (conflict) {
200
+ return { status: "duplicate" as const, runId: conflict.runId };
201
+ }
202
+
203
+ await processOwnedOrder(orderId);
204
+ return { status: "processed" as const };
205
+ }
206
+ ```
207
+
208
+ `experimental_minRetention` accepts the same values as [`sleep()`](/docs/api-reference/workflow/sleep): a duration string such as `"30d"`, a number of milliseconds, or an absolute `Date`. Durations start when `createHook()` runs.
209
+
210
+ The Hook remains active until the workflow ends, even if the configured time passes first. Another Hook can use the token only after both the workflow has ended and the configured time has passed. For example, `"30d"` keeps the token unavailable for 29 more days if the workflow ends after 1 day. A workflow that runs for more than 30 days releases the token when it ends.
211
+
212
+ After the workflow ends, [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) can still find the Hook until retention ends, but the Hook cannot be resumed.
213
+
214
+ <Callout type="warn">
215
+ `using` auto-disposes the Hook at scope exit, which releases the token immediately and defeats `experimental_minRetention`. Declare retained Hooks with `const` and let the runtime clean them up when the run ends.
216
+ </Callout>
217
+
218
+ <Callout type="warn">
219
+ This option is experimental. Worlds can limit how long tokens are retained; see [World configuration](/docs/configuration/worlds) for each World's limit. If the configured World does not support minimum retention, the workflow fails when registering the Hook. `createWebhook()` does not accept this option.
220
+ </Callout>
221
+
222
+ ### Take over a token another run holds
223
+
224
+ By default, a token that another active run already registered makes the new Hook reject with [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error). Set `experimental_force` when the newest run should own the token instead, for example when a fresh deployment or a restarted conversation must replace a run that is still waiting:
225
+
226
+ ```typescript lineNumbers
227
+ import { createHook } from "workflow";
228
+
229
+ declare function processMessage(message: SlackMessage): Promise<void>; // @setup
230
+ type SlackMessage = { text: string }; // @setup
231
+
232
+ export async function slackChannelWorkflow(channelId: string) {
233
+ "use workflow";
234
+
235
+ // Whichever run for this channel started most recently owns the token.
236
+ const hook = createHook<SlackMessage>({ // [!code highlight]
237
+ token: `slack_messages:${channelId}`, // [!code highlight]
238
+ experimental_force: true, // [!code highlight]
239
+ }); // [!code highlight]
240
+
241
+ for await (const message of hook) {
242
+ await processMessage(message);
243
+ }
244
+ }
245
+ ```
246
+
247
+ With `experimental_force`, this run always ends up owning the token:
248
+
249
+ - The previous owner's Hook is disposed, recorded in that run's event log, and the previous owner is woken. If it was awaiting the Hook, that `await` rejects with [`HookForceClaimedError`](/docs/api-reference/workflow-errors/hook-force-claimed-error), which names the run that took the token. Payloads it received before the takeover stay with it; a `for await...of` loop drains them before it throws.
250
+ - Every [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) for the token from then on reaches this run, including a call that was already in flight when the takeover happened. Callers never see the token move; a delivery aimed at the previous owner is redirected to this run inside `resumeHook()`.
251
+ - Any number of runs forcing the same token at the same time converge on a single owner. The takeovers form a chain: each run that loses the token gets `HookForceClaimedError`, exactly one run ends up owning it, and none of them can get stuck. Which run wins among simultaneous claimers is not defined; if the order matters, start them in order.
252
+ - A finished run that still holds the token under [`experimental_minRetention`](#keep-a-token-unavailable-after-the-run-ends) is taken over silently, since there is nothing left to wake. A run can also take over a token held by its own earlier Hook.
253
+
254
+ The takeover is durable. If either run's compute fails partway through, the next request for the token completes it, so the token never ends up held by nobody or by both runs. The previous owner's wake is durable too: if the new owner's compute fails between registering the Hook and waking the previous owner, the new owner's next invocation republishes the wake, whatever else the new owner has recorded since (a step it started alongside the Hook, for example). Every invocation of the new owner within 24 hours of the takeover republishes it under the same idempotency key, which collapses the repeats into one wake; a repeat that does get through only replays the previous owner, which finds nothing new.
255
+
256
+ <Callout type="info">
257
+ A token can only be taken from a run whose runtime understands being taken from. Runs started at a Workflow spec version below 8, which includes every run started by an older SDK release, a Python SDK run, or a deployment with `WORKFLOW_SEALED_LOG=0`, would never learn that their Hook was disposed. The World declines to take their token and the forced Hook rejects with the ordinary [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) instead, exactly as if `experimental_force` had not been set. Finished runs holding a retained token are taken over at any version.
258
+ </Callout>
259
+
260
+ `hook.getConflict()` on a forced Hook resolves with `null` once the takeover succeeds: the token is this run's by construction. If the World declines the takeover because the current owner predates spec version 8, `getConflict()` behaves as it does for an ordinary conflict and resolves with that owner's `Run`. Read `hook.claimedFrom` on the value returned by [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) to find out which run, if any, the token was taken from.
261
+
262
+ <Callout type="warn">
263
+ This option is experimental. It requires an explicit `token` (a generated token can never conflict) and is not accepted by `createWebhook()`. If the configured World does not support force-claiming at all, the workflow fails when registering the Hook; a World that declines a specific takeover because the current owner cannot be woken answers with `HookConflictError` instead.
264
+
265
+ Senders on an older SDK release are not redirected. A `resumeHook()` from a deployment that predates this option and that looked the token up inside the short handoff window gets an error (`EntityConflictError`) instead of following the token; the payload is refused, never delivered to the wrong run, and a retry resolves the new owner. Upgrade the sending deployment for the transparent redirect.
266
+
267
+ Webhook requests are not redirected either. [`resumeWebhook()`](/docs/api-reference/workflow-api/resume-webhook) streams the request body once, and buffering a copy of every webhook body on the chance that its token is being taken over at that moment would be a cost paid by everyone who never uses this option. A webhook delivery that lands inside the handoff window fails with a retryable error naming the takeover; nothing is delivered anywhere, and the sender's retry reaches the new owner. A forced `createHook()` can take over a token that a webhook holds, but the token then belongs to a Hook that is not a webhook, so `resumeWebhook()` answers every later request for it as not found, exactly as it does for any `createHook()` token, and never redirects one into it.
268
+ </Callout>
269
+
270
+ ### Waiting for multiple payloads
116
271
 
117
272
  You can also wait for multiple payloads by using the `for await...of` syntax.
118
273
 
@@ -135,7 +290,7 @@ export async function collectHookWorkflow() {
135
290
  }
136
291
  ```
137
292
 
138
- ### Disposing Hooks Early
293
+ ### Disposing hooks early
139
294
 
140
295
  You can dispose a hook early to release its token for reuse by another workflow. This is useful for handoff patterns where one workflow needs to transfer a hook token to another workflow while still running.
141
296
 
@@ -164,7 +319,7 @@ export async function handoffWorkflow(channelId: string) {
164
319
 
165
320
  After calling `dispose()`, the hook will no longer receive events and its token becomes available for other workflows to use.
166
321
 
167
- ### Automatic Disposal with `using`
322
+ ### Automatic disposal with `using`
168
323
 
169
324
  Hooks implement the [TC39 Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management) proposal, allowing automatic disposal with the `using` keyword:
170
325
 
@@ -190,8 +345,9 @@ export async function scopedHookWorkflow(channelId: string) {
190
345
 
191
346
  This is equivalent to manually calling `dispose()` but ensures the hook is always cleaned up, even if an error occurs.
192
347
 
193
- ## Related Functions
348
+ ## Related functions
194
349
 
195
- - [`defineHook()`](/docs/api-reference/workflow/define-hook) - Type-safe hook helper
196
- - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) - Resume a hook with a payload
197
- - [`createWebhook()`](/docs/api-reference/workflow/create-webhook) - Higher-level HTTP webhook abstraction
350
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook): Type-safe hook helper
351
+ - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resume a hook with a payload
352
+ - [`createWebhook()`](/docs/api-reference/workflow/create-webhook): Higher-level HTTP webhook abstraction
353
+ - [Idempotency](/docs/foundations/idempotency): Deduplicate step side effects and workflow starts
@@ -14,7 +14,7 @@ Creates a webhook that can be used to suspend and resume a workflow run upon rec
14
14
  Webhooks provide a way for external systems to send HTTP requests directly to your workflow. Unlike hooks which accept arbitrary payloads, webhooks work with standard HTTP `Request` objects and can return HTTP `Response` objects.
15
15
 
16
16
  <Callout type="warn">
17
- `createWebhook()` creates a public endpoint at `/.well-known/workflow/v1/webhook/:token`, and the token in that URL is the only authorization performed for incoming requests resuming that webhook. This is convenient for prototypes and simple resume links because it avoids creating another route, but if you need stronger security, prefer [`createHook()`](/docs/api-reference/workflow/create-hook) behind your own route and authorize the request before calling [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) to avoid unauthenticated workflow resumptions.
17
+ `createWebhook()` creates a public endpoint at `/.well-known/workflow/v1/webhook/:token`, and the token in that URL is the only authorization performed for incoming requests resuming that webhook. This is convenient for prototypes and basic resume links because it avoids creating another route, but if you need stronger security, prefer [`createHook()`](/docs/api-reference/workflow/create-hook) behind your own route and authorize the request before calling [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) to avoid unauthenticated workflow resumptions.
18
18
  </Callout>
19
19
 
20
20
  ```ts lineNumbers
@@ -31,7 +31,7 @@ export async function webhookWorkflow() {
31
31
  }
32
32
  ```
33
33
 
34
- ## API Signature
34
+ ## API signature
35
35
 
36
36
  ### Parameters
37
37
 
@@ -55,6 +55,7 @@ The returned `Webhook` object has:
55
55
 
56
56
  - `url`: The HTTP endpoint URL that external systems can call
57
57
  - `token`: The unique token identifying this webhook
58
+ - `getConflict()`: A promise that resolves with the conflicting run if another active hook already owns this token, or `null` once the webhook endpoint has been registered. The endpoint is registered alongside the steps the workflow starts at the same time, not ahead of them, so await `getConflict()` before a step that hands `url` to a caller who may request it right away. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
58
59
  - Implements `AsyncIterable<T>` for handling multiple requests, where `T` is `Request` (default) or `RequestWithResponse` (manual mode)
59
60
 
60
61
  When using `createWebhook({ respondWith: 'manual' })`, the resolved request type is `RequestWithResponse`, which extends the standard `Request` interface with a `respondWith(response: Response): Promise<void>` method for sending custom responses back to the caller.
@@ -62,22 +63,22 @@ When using `createWebhook({ respondWith: 'manual' })`, the resolved request type
62
63
  <Callout type="info">
63
64
  Use the simplest option that satisfies the prompt:
64
65
 
65
- - `createWebhook()` — generated callback URL, and the default `202 Accepted` response is fine
66
- - `createWebhook({ respondWith: 'manual' })` — generated callback URL, but you must send a custom body, status, or headers
67
- - `createHook()` + `resumeHook()` — the app resumes from server-side code with a deterministic business token instead of a generated callback URL
66
+ - `createWebhook()`: generated callback URL, and the default `202 Accepted` response is fine
67
+ - `createWebhook({ respondWith: 'manual' })`: generated callback URL, but you must send a custom body, status, or headers
68
+ - `createHook()` + `resumeHook()`: the app resumes from server-side code with a deterministic business token instead of a generated callback URL
68
69
  </Callout>
69
70
 
70
71
  <details>
71
72
  <summary>Common wrong turns</summary>
72
73
 
73
- - Do not use `respondWith: 'manual'` just because the flow has a callback URL.
74
+ - A callback URL alone does not require `respondWith: 'manual'`.
74
75
  - Do not use `RequestWithResponse` unless you chose manual mode.
75
76
  - Do not invent a custom callback route when `webhook.url` is the intended callback surface.
76
77
  </details>
77
78
 
78
79
  ## Examples
79
80
 
80
- ### Basic Usage
81
+ ### Basic usage
81
82
 
82
83
  Create a webhook that receives HTTP requests and logs the request details:
83
84
 
@@ -100,11 +101,11 @@ export async function basicWebhookWorkflow() {
100
101
  }
101
102
  ```
102
103
 
103
- ### Responding to Webhook Requests (Manual Mode)
104
+ ### Responding to webhook requests (manual mode)
104
105
 
105
106
  Use this section only when the caller requires a non-default HTTP response. If `202 Accepted` is acceptable, use `createWebhook()` without `respondWith: "manual"`.
106
107
 
107
- Pass `{ respondWith: "manual" }` to get a `RequestWithResponse` object with a `respondWith()` method. Note that `respondWith()` must be called from within a step function:
108
+ Pass `{ respondWith: "manual" }` to get a `RequestWithResponse` object with a `respondWith()` method. Call `respondWith()` from within a step function:
108
109
 
109
110
  ```typescript lineNumbers
110
111
  import { createWebhook, type RequestWithResponse } from "workflow"
@@ -142,7 +143,7 @@ async function processData(data: any): Promise<void> {
142
143
  }
143
144
  ```
144
145
 
145
- ### Waiting for Multiple Requests
146
+ ### Waiting for multiple requests
146
147
 
147
148
  You can also wait for multiple requests by using the `for await...of` syntax.
148
149
 
@@ -181,9 +182,9 @@ export async function eventCollectorWorkflow() {
181
182
  }
182
183
  ```
183
184
 
184
- ## Related Functions
185
+ ## Related functions
185
186
 
186
- - [`createHook()`](/docs/api-reference/workflow/create-hook) — Use when the app resumes from server-side code with a deterministic business token.
187
- - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) — Pairs with `createHook()` for deterministic server-side resume.
188
- - [`defineHook()`](/docs/api-reference/workflow/define-hook) — Type-safe hook helper.
189
- - [`resumeWebhook()`](/docs/api-reference/workflow-api/resume-webhook) — Low-level runtime API. Most integrations should call `webhook.url` directly instead of adding a custom callback route.
187
+ - [`createHook()`](/docs/api-reference/workflow/create-hook): Use when the app resumes from server-side code with a deterministic business token.
188
+ - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Pairs with `createHook()` for deterministic server-side resume.
189
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook): Type-safe hook helper.
190
+ - [`resumeWebhook()`](/docs/api-reference/workflow-api/resume-webhook): Low-level runtime API. Most integrations should call `webhook.url` directly instead of adding a custom callback route.
@@ -33,7 +33,7 @@ export async function nameWorkflow() {
33
33
  }
34
34
  ```
35
35
 
36
- ## API Signature
36
+ ## API signature
37
37
 
38
38
  ### Parameters
39
39
 
@@ -46,27 +46,24 @@ showSections={['parameters']}
46
46
 
47
47
  ### Returns
48
48
 
49
+ `defineHook()` returns a `TypedHook<TInput, TOutput>`:
50
+
49
51
  <TSDoc
50
52
  definition={`
51
- interface DefineHook<T> {
52
- /**
53
-
54
- * Creates a new hook with the defined payload type.
55
- */
56
- create: (options?: HookOptions) => Hook<T>;
57
-
58
- /**
59
-
60
- * Resumes a hook by sending a payload with the defined type.
61
- */
62
- resume: (token: string, payload: T) => Promise<HookEntity | null>;
53
+ interface TypedHook<TInput, TOutput> {
54
+ /** Creates the hook. Call inside a "use workflow" function. */
55
+ create(options?: HookOptions): Hook<TOutput>;
56
+ /** Resumes the hook from runtime code. Resolves to the resumed hook; throws HookNotFoundError if the token does not match an active hook. */
57
+ resume(token: string, payload: TInput): Promise<HookEntity>;
63
58
  }
64
- export default DefineHook;`}
59
+ export default TypedHook;`}
65
60
  />
66
61
 
62
+ `create()` is called inside a `"use workflow"` function to create the hook; `resume()` is called from runtime code (an API route or server action). When a `schema` is provided, `resume()` accepts the raw input type (`TInput`) and the workflow receives the validated and possibly transformed output type (`TOutput`); without a schema, `TOutput` defaults to `TInput`. `resume()` throws [`HookNotFoundError`](/docs/api-reference/workflow-errors/hook-not-found-error) if the token does not match an active hook. It does not return `null`.
63
+
67
64
  ## Examples
68
65
 
69
- ### Basic Type-Safe Hook Definition
66
+ ### Basic type-safe hook definition
70
67
 
71
68
  By defining the hook once with a specific payload type, you can reuse it in multiple workflows and API routes with automatic type safety.
72
69
 
@@ -91,30 +88,35 @@ export async function workflowWithApproval() {
91
88
  }
92
89
  ```
93
90
 
94
- ### Resuming with Type Safety
91
+ ### Resuming with type safety
95
92
 
96
- Hooks can be resumed using the same defined hook and a token. By using the same hook, you can ensure that the payload matches the defined type when resuming a hook.
93
+ Hooks can be resumed using the same defined hook and a token. By using the same hook, you can ensure that the payload matches the defined type when resuming a hook. `resume()` resolves to the resumed hook and throws [`HookNotFoundError`](/docs/api-reference/workflow-errors/hook-not-found-error) if the token does not match an active hook.
97
94
 
98
95
  ```typescript lineNumbers
96
+ import { HookNotFoundError } from "workflow/errors";
97
+
99
98
  // Use the same defined hook to resume
100
99
  export async function POST(request: Request) {
101
100
  const { token, approved, comment } = await request.json();
102
101
 
103
- // Type-safe resumption - TypeScript ensures the payload matches
104
- const result = await approvalHook.resume(token, { // [!code highlight]
105
- approved, // [!code highlight]
106
- comment, // [!code highlight]
107
- }); // [!code highlight]
108
-
109
- if (!result) {
110
- return Response.json({ error: "Hook not found" }, { status: 404 });
102
+ try {
103
+ // Type-safe resumption - TypeScript ensures the payload matches
104
+ const hook = await approvalHook.resume(token, { // [!code highlight]
105
+ approved, // [!code highlight]
106
+ comment, // [!code highlight]
107
+ }); // [!code highlight]
108
+
109
+ return Response.json({ success: true, runId: hook.runId });
110
+ } catch (error) {
111
+ if (HookNotFoundError.is(error)) { // [!code highlight]
112
+ return Response.json({ error: "Hook not found" }, { status: 404 });
113
+ }
114
+ throw error;
111
115
  }
112
-
113
- return Response.json({ success: true, runId: result.runId });
114
116
  }
115
117
  ```
116
118
 
117
- ### Validate and Transform with Schema
119
+ ### Validate and transform with schema
118
120
 
119
121
  You can provide runtime validation and transformation of hook payloads using the `schema` option. This option accepts any validator that conforms to the [Standard Schema v1](https://standardschema.dev) specification.
120
122
 
@@ -172,7 +174,7 @@ export async function POST(request: Request) {
172
174
  }
173
175
  ```
174
176
 
175
- #### Using Other Standard Schema Libraries
177
+ #### Using other Standard Schema libraries
176
178
 
177
179
  The same pattern works with any Standard Schema v1 compliant library. Here's an example with [Valibot](https://valibot.dev):
178
180
 
@@ -188,7 +190,7 @@ export const approvalHook = defineHook({
188
190
  });
189
191
  ```
190
192
 
191
- ### Customizing Tokens
193
+ ### Customizing tokens
192
194
 
193
195
  Tokens are used to identify a specific hook and for resuming a hook. You can customize the token to be more specific to a use case.
194
196
 
@@ -209,7 +211,9 @@ export async function slackBotWorkflow(channelId: string) {
209
211
  }
210
212
  ```
211
213
 
212
- ## Related Functions
214
+ `create()` accepts the same options as `createHook()`. If a newer run should replace one that still holds the token, pass [`experimental_force: true`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds) to take the token over instead of getting [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error).
215
+
216
+ ## Related functions
213
217
 
214
- * [`createHook()`](/docs/api-reference/workflow/create-hook) - Create a hook in a workflow.
215
- * [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) - Resume a hook with a payload.
218
+ - [`createHook()`](/docs/api-reference/workflow/create-hook): Create a hook in a workflow.
219
+ - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resume a hook with a payload.
@@ -27,18 +27,40 @@ async function fallibleStep() {
27
27
  }
28
28
  ```
29
29
 
30
- ## API Signature
30
+ ## API signature
31
31
 
32
- ### Parameters
32
+ ### Constructor
33
+
34
+ `new FatalError(message)`
35
+
36
+ | Parameter | Type | Description |
37
+ | --------- | -------- | ------------------ |
38
+ | `message` | `string` | The error message. |
39
+
40
+ ### Properties
33
41
 
34
42
  <TSDoc
35
43
  definition={`
36
- interface Error {
37
- /**
38
-
39
- * The error message.
40
- */
44
+ interface FatalError {
45
+ /** The error message. */
41
46
  message: string;
47
+ /** Always true. Marks the error as non-retryable. */
48
+ fatal: boolean;
42
49
  }
43
- export default Error;`}
50
+ export default FatalError;`}
44
51
  />
52
+
53
+ ### Static methods
54
+
55
+ #### `FatalError.is(value)`
56
+
57
+ Type-safe check for `FatalError` instances. Preferred over `instanceof` because it works across module boundaries and VM contexts.
58
+
59
+ ```typescript
60
+ import { FatalError } from "workflow"
61
+ declare const error: unknown; // @setup
62
+
63
+ if (FatalError.is(error)) {
64
+ // error is typed as FatalError
65
+ }
66
+ ```
@@ -7,12 +7,17 @@ prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
9
9
  - /docs/errors/fetch-in-workflow
10
+ - /docs/foundations/idempotency
10
11
  ---
11
12
 
12
13
  Makes HTTP requests from within a workflow. This is a special step function that wraps the standard `fetch` API, automatically handling serialization and providing retry semantics.
13
14
 
14
15
  This is useful when you need to call external APIs or services from within your workflow.
15
16
 
17
+ <Callout type="warn">
18
+ Because workflow `fetch()` has retry semantics, use idempotency keys when the request mutates an external system, such as creating a charge, sending an email, or enqueueing work. See [Idempotency](/docs/foundations/idempotency).
19
+ </Callout>
20
+
16
21
  <Callout>
17
22
  `fetch` is a *special* type of step function provided and should be called directly inside workflow functions.
18
23
  </Callout>
@@ -29,7 +34,7 @@ async function apiWorkflow() {
29
34
  }
30
35
  ```
31
36
 
32
- ## API Signature
37
+ ## API signature
33
38
 
34
39
  ### Parameters
35
40
 
@@ -55,9 +60,9 @@ showSections={['returns']}
55
60
 
56
61
  ## Examples
57
62
 
58
- ### Basic Usage
63
+ ### Basic usage
59
64
 
60
- Here's a simple example of how you can use `fetch` inside your workflow.
65
+ Here's an example of how you can use `fetch` inside your workflow.
61
66
 
62
67
  ```typescript lineNumbers
63
68
  import { fetch } from "workflow"
@@ -82,13 +87,13 @@ async function apiWorkflow() {
82
87
  }
83
88
  ```
84
89
 
85
- We call `fetch()` with a URL and optional request options, just like the standard fetch API. The workflow runtime automatically handles the response serialization.
90
+ We call `fetch()` with a URL and optional request options, like the standard fetch API. The workflow runtime automatically handles the response serialization.
86
91
 
87
- This API is provided as a convenience to easily use `fetch` in workflow, but often, you might want to extend and implement your own fetch for more powerful error handing and retry logic.
92
+ This API lets you use `fetch` in a workflow. You can also implement a custom fetch for different error handling and retry logic.
88
93
 
89
- ### Customizing Fetch Behavior
94
+ ### Customizing fetch behavior
90
95
 
91
- Here's an example of a custom fetch wrapper that provides more sophisticated error handling with custom retry logic:
96
+ The following custom fetch wrapper provides more advanced error handling with custom retry logic. Call `globalThis.fetch` inside your own `"use step"` function because calling the workflow `fetch` imported from `workflow` would nest a step inside a step:
92
97
 
93
98
  ```typescript lineNumbers
94
99
  import { FatalError, RetryableError } from "workflow"
@@ -99,7 +104,7 @@ export async function customFetch(
99
104
  ) {
100
105
  "use step"
101
106
 
102
- const response = await fetch(url, init)
107
+ const response = await globalThis.fetch(url, init)
103
108
 
104
109
  // Handle client errors (4xx) - don't retry
105
110
  if (response.status >= 400 && response.status < 500) {
@@ -140,7 +145,6 @@ export async function customFetch(
140
145
 
141
146
  This example demonstrates:
142
147
 
143
- - Setting custom `maxRetries` to 5 retries (6 total attempts including the initial attempt).
144
148
  - Throwing [`FatalError`](/docs/api-reference/workflow/fatal-error) for client errors (400-499) to prevent retries.
145
149
  - Handling 429 rate limiting by reading the `Retry-After` header and using [`RetryableError`](/docs/api-reference/workflow/retryable-error).
146
- - Allowing automatic retries for server errors (5xx).
150
+ - Allowing automatic retries for server errors (5xx) by throwing a plain `Error`.
@@ -34,7 +34,7 @@ async function logStepId() {
34
34
  }
35
35
  ```
36
36
 
37
- ### Example: Use `stepId` as an idempotency key
37
+ ### Example: use `stepId` as an idempotency key
38
38
 
39
39
  ```typescript lineNumbers
40
40
  import { getStepMetadata } from "workflow";
@@ -61,7 +61,7 @@ async function chargeUser(userId: string, amount: number) {
61
61
  <a href="/docs/foundations/idempotency">Idempotency</a> guide.
62
62
  </Callout>
63
63
 
64
- ## API Signature
64
+ ## API signature
65
65
 
66
66
  ### Parameters
67
67
 
@@ -30,7 +30,7 @@ async function testWorkflow() {
30
30
  }
31
31
  ```
32
32
 
33
- ### Detecting Workflow Runtime
33
+ ### Detecting workflow runtime
34
34
 
35
35
  You can use `getWorkflowMetadata` to detect whether your code is running inside a workflow context. This is useful when building shared utilities that need to behave differently inside and outside of workflows.
36
36
 
@@ -64,7 +64,7 @@ function log(message: string) {
64
64
  }
65
65
  ```
66
66
 
67
- ### Detecting Encryption
67
+ ### Detecting encryption
68
68
 
69
69
  The `features` object indicates which capabilities are active for the current run. Library authors can use `features.encryption` to control whether sensitive data is included in step return values, which are serialized to the event log:
70
70
 
@@ -90,7 +90,7 @@ async function fetchUserProfile(userId: string) {
90
90
  }
91
91
  ```
92
92
 
93
- ## API Signature
93
+ ## API signature
94
94
 
95
95
  ### Parameters
96
96