@upstash/workflow 1.4.0 → 1.5.1-canary.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 (223) hide show
  1. package/README.md +9 -0
  2. package/astro.d.mts +19 -2
  3. package/astro.d.ts +19 -2
  4. package/astro.js +670 -159
  5. package/astro.mjs +1 -1
  6. package/{chunk-DRHEHWMS.mjs → chunk-J3PXPHSB.mjs} +828 -317
  7. package/cloudflare.d.mts +17 -2
  8. package/cloudflare.d.ts +17 -2
  9. package/cloudflare.js +670 -159
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +375 -0
  13. package/docs/agents/getting-started.mdx +139 -0
  14. package/docs/agents/overview.mdx +40 -0
  15. package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
  16. package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
  17. package/docs/agents/patterns/parallelization.mdx +77 -0
  18. package/docs/agents/patterns/prompt-chaining.mdx +84 -0
  19. package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
  20. package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
  21. package/docs/basics/best-practices/deterministic-code.mdx +132 -0
  22. package/docs/basics/best-practices/idempotency.mdx +38 -0
  23. package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
  24. package/docs/basics/best-practices/overview.mdx +35 -0
  25. package/docs/basics/best-practices/promise-any.mdx +9 -0
  26. package/docs/basics/best-practices/return-step-results.mdx +80 -0
  27. package/docs/basics/best-practices/workflow-limits.mdx +62 -0
  28. package/docs/basics/client/cancel.mdx +137 -0
  29. package/docs/basics/client/dlq/callback.mdx +21 -0
  30. package/docs/basics/client/dlq/delete.mdx +120 -0
  31. package/docs/basics/client/dlq/list.mdx +96 -0
  32. package/docs/basics/client/dlq/restart.mdx +164 -0
  33. package/docs/basics/client/dlq/resume.mdx +167 -0
  34. package/docs/basics/client/logs.mdx +139 -0
  35. package/docs/basics/client/notify.mdx +79 -0
  36. package/docs/basics/client/trigger.mdx +139 -0
  37. package/docs/basics/client/waiters.mdx +31 -0
  38. package/docs/basics/client.mdx +40 -0
  39. package/docs/basics/how.mdx +65 -0
  40. package/docs/basics/serve/advanced.mdx +435 -0
  41. package/docs/basics/serve.mdx +142 -0
  42. package/docs/changelog.mdx +174 -0
  43. package/docs/examples/allInOne.mdx +377 -0
  44. package/docs/examples/authWebhook.mdx +575 -0
  45. package/docs/examples/customRetry.mdx +309 -0
  46. package/docs/examples/customerOnboarding.mdx +230 -0
  47. package/docs/examples/dynamicWorkflow.mdx +203 -0
  48. package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
  49. package/docs/examples/imageProcessing.mdx +339 -0
  50. package/docs/examples/paymentRetry.mdx +438 -0
  51. package/docs/examples/waitForEvent.mdx +201 -0
  52. package/docs/features/dlq/callback.mdx +42 -0
  53. package/docs/features/dlq/delete.mdx +29 -0
  54. package/docs/features/dlq/restart.mdx +33 -0
  55. package/docs/features/dlq/resume.mdx +37 -0
  56. package/docs/features/dlq.mdx +39 -0
  57. package/docs/features/failure-callback.mdx +102 -0
  58. package/docs/features/failureFunction/advanced.mdx +36 -0
  59. package/docs/features/failureFunction/reliability.mdx +33 -0
  60. package/docs/features/flow-control/monitor.mdx +22 -0
  61. package/docs/features/flow-control/parallelism.mdx +45 -0
  62. package/docs/features/flow-control/rate-period.mdx +46 -0
  63. package/docs/features/flow-control.mdx +164 -0
  64. package/docs/features/invoke/serveMany.mdx +109 -0
  65. package/docs/features/invoke.mdx +39 -0
  66. package/docs/features/notify.mdx +127 -0
  67. package/docs/features/parallel-steps.mdx +41 -0
  68. package/docs/features/retries/prevent-retries.mdx +140 -0
  69. package/docs/features/retries.mdx +93 -0
  70. package/docs/features/wait-for-event.mdx +104 -0
  71. package/docs/features/wait.mdx +44 -0
  72. package/docs/features/webhooks.mdx +116 -0
  73. package/docs/getstarted.mdx +200 -0
  74. package/docs/howto/cancel.mdx +50 -0
  75. package/docs/howto/changes.mdx +33 -0
  76. package/docs/howto/configure.mdx +42 -0
  77. package/docs/howto/failures.mdx +185 -0
  78. package/docs/howto/get-token.mdx +18 -0
  79. package/docs/howto/local-development/development-server.mdx +130 -0
  80. package/docs/howto/local-development/local-tunnel.mdx +73 -0
  81. package/docs/howto/middlewares.mdx +263 -0
  82. package/docs/howto/migrations.mdx +335 -0
  83. package/docs/howto/multi-region.mdx +107 -0
  84. package/docs/howto/parallel-runs.mdx +52 -0
  85. package/docs/howto/readonly-token.mdx +19 -0
  86. package/docs/howto/realtime/basic.mdx +315 -0
  87. package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
  88. package/docs/howto/redact-fields.mdx +61 -0
  89. package/docs/howto/retry-now.mdx +41 -0
  90. package/docs/howto/schedule.mdx +114 -0
  91. package/docs/howto/security.mdx +143 -0
  92. package/docs/howto/singleton.mdx +137 -0
  93. package/docs/howto/start.mdx +69 -0
  94. package/docs/howto/use-webhooks.mdx +256 -0
  95. package/docs/integrations/aisdk.mdx +316 -0
  96. package/docs/integrations/anthropic.mdx +51 -0
  97. package/docs/integrations/datadog.mdx +69 -0
  98. package/docs/integrations/openai.mdx +87 -0
  99. package/docs/integrations/prometheus.mdx +65 -0
  100. package/docs/integrations/resend.mdx +82 -0
  101. package/docs/llms-txt.mdx +4 -0
  102. package/docs/openapi.yaml +2946 -0
  103. package/docs/pricing.mdx +22 -0
  104. package/docs/quickstarts/astro.mdx +185 -0
  105. package/docs/quickstarts/cloudflare-workers.mdx +190 -0
  106. package/docs/quickstarts/express.mdx +190 -0
  107. package/docs/quickstarts/fastapi.mdx +282 -0
  108. package/docs/quickstarts/flask.mdx +282 -0
  109. package/docs/quickstarts/hono.mdx +221 -0
  110. package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
  111. package/docs/quickstarts/nextjs-flask.mdx +147 -0
  112. package/docs/quickstarts/nuxt.mdx +169 -0
  113. package/docs/quickstarts/platforms.mdx +78 -0
  114. package/docs/quickstarts/solidjs.mdx +161 -0
  115. package/docs/quickstarts/svelte.mdx +170 -0
  116. package/docs/quickstarts/tanstack-start.mdx +205 -0
  117. package/docs/quickstarts/vercel-nextjs.mdx +233 -0
  118. package/docs/roadmap.mdx +8 -0
  119. package/docs/sdk/workflow-js.mdx +4 -0
  120. package/docs/sdk/workflow-py.mdx +4 -0
  121. package/docs/steps/api.mdx +64 -0
  122. package/docs/steps/call.mdx +183 -0
  123. package/docs/steps/cancel.mdx +25 -0
  124. package/docs/steps/createWebhook.mdx +40 -0
  125. package/docs/steps/invoke.mdx +100 -0
  126. package/docs/steps/notify.mdx +105 -0
  127. package/docs/steps/run.mdx +150 -0
  128. package/docs/steps/sleep.mdx +97 -0
  129. package/docs/steps/sleepUntil.mdx +88 -0
  130. package/docs/steps/waitForEvent.mdx +60 -0
  131. package/docs/steps/waitForWebhook.mdx +78 -0
  132. package/docs/steps.mdx +108 -0
  133. package/docs/troubleshooting/general.mdx +331 -0
  134. package/docs/troubleshooting/vercel.mdx +82 -0
  135. package/express.d.mts +19 -2
  136. package/express.d.ts +19 -2
  137. package/express.js +670 -159
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +19 -2
  140. package/h3.d.ts +19 -2
  141. package/h3.js +670 -159
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +17 -2
  144. package/hono.d.ts +17 -2
  145. package/hono.js +670 -159
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +50 -21
  148. package/index.d.ts +50 -21
  149. package/index.js +686 -171
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +40 -2
  152. package/nextjs.d.ts +40 -2
  153. package/nextjs.js +670 -159
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +16 -2
  157. package/react-router.d.ts +16 -2
  158. package/react-router.js +670 -159
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CG3BFvO3.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-iJF1IUXk.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +10 -1
  163. package/solidjs.d.ts +10 -1
  164. package/solidjs.js +670 -159
  165. package/solidjs.mjs +1 -1
  166. package/src/platforms/astro.ts +84 -0
  167. package/src/platforms/cloudflare.ts +127 -0
  168. package/src/platforms/express.ts +147 -0
  169. package/src/platforms/h3.ts +105 -0
  170. package/src/platforms/hono.ts +103 -0
  171. package/src/platforms/nextjs.ts +193 -0
  172. package/src/platforms/react-router.ts +92 -0
  173. package/src/platforms/solidjs.ts +59 -0
  174. package/src/platforms/svelte.ts +99 -0
  175. package/src/platforms/tanstack.ts +96 -0
  176. package/src/src/client/dlq.ts +387 -0
  177. package/src/src/client/filter-types.ts +166 -0
  178. package/src/src/client/index.ts +350 -0
  179. package/src/src/client/types.ts +501 -0
  180. package/src/src/client/utils.ts +307 -0
  181. package/src/src/constants.ts +82 -0
  182. package/src/src/context/api/anthropic.ts +58 -0
  183. package/src/src/context/api/base.ts +52 -0
  184. package/src/src/context/api/index.ts +24 -0
  185. package/src/src/context/api/openai.ts +125 -0
  186. package/src/src/context/api/resend.ts +57 -0
  187. package/src/src/context/auto-executor.ts +707 -0
  188. package/src/src/context/context.ts +681 -0
  189. package/src/src/context/index.ts +1 -0
  190. package/src/src/context/provider.ts +37 -0
  191. package/src/src/context/steps.ts +965 -0
  192. package/src/src/error.ts +203 -0
  193. package/src/src/index.ts +13 -0
  194. package/src/src/middleware/default-callbacks.ts +20 -0
  195. package/src/src/middleware/index.ts +2 -0
  196. package/src/src/middleware/logging.ts +39 -0
  197. package/src/src/middleware/manager.ts +148 -0
  198. package/src/src/middleware/middleware.ts +46 -0
  199. package/src/src/middleware/types.ts +72 -0
  200. package/src/src/qstash/headers.ts +397 -0
  201. package/src/src/qstash/step-config.ts +268 -0
  202. package/src/src/qstash/submit-steps.ts +284 -0
  203. package/src/src/serve/authorization.ts +118 -0
  204. package/src/src/serve/index.ts +475 -0
  205. package/src/src/serve/multi-region/handlers.ts +225 -0
  206. package/src/src/serve/multi-region/utils.ts +88 -0
  207. package/src/src/serve/options.ts +241 -0
  208. package/src/src/serve/serve-many.ts +117 -0
  209. package/src/src/serve/utils.ts +11 -0
  210. package/src/src/types.ts +590 -0
  211. package/src/src/utils.ts +141 -0
  212. package/src/src/workflow-parser.ts +472 -0
  213. package/src/src/workflow-requests.ts +575 -0
  214. package/svelte.d.mts +17 -2
  215. package/svelte.d.ts +17 -2
  216. package/svelte.js +670 -159
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +15 -2
  219. package/tanstack.d.ts +15 -2
  220. package/tanstack.js +670 -159
  221. package/tanstack.mjs +1 -1
  222. package/{types-CekOpKvz.d.ts → types-CrgK5P6p.d.mts} +372 -32
  223. package/{types-CekOpKvz.d.mts → types-CrgK5P6p.d.ts} +372 -32
package/react-router.js CHANGED
@@ -34,6 +34,14 @@ var WORKFLOW_CREATED_AT_HEADER = "Upstash-Workflow-CreatedAt";
34
34
  var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
35
35
  var WORKFLOW_FAILURE_CALLBACK_HEADER = "Upstash-Workflow-Failure-Callback";
36
36
  var WORKFLOW_FEATURE_HEADER = "Upstash-Feature-Set";
37
+ var WORKFLOW_FEATURE_SET = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
38
+ var WORKFLOW_STEP_CONFIG_CALL_TYPE = "stepConfig";
39
+ var WORKFLOW_STEP_CONFIG_HEADER = "Upstash-Workflow-Step-Config";
40
+ var FLOW_CONTROL_KEY_HEADER = "Upstash-Flow-Control-Key";
41
+ var FLOW_CONTROL_VALUE_HEADER = "Upstash-Flow-Control-Value";
42
+ var RETRIES_HEADER = "Upstash-Retries";
43
+ var RETRY_DELAY_HEADER = "Upstash-Retry-Delay";
44
+ var WORKFLOW_STEP_CONFIG_FEATURE = "WF_StepConfig";
37
45
  var WORKFLOW_INVOKE_COUNT_HEADER = "Upstash-Workflow-Invoke-Count";
38
46
  var WORKFLOW_RETRIED_HEADER = "Upstash-Retried";
39
47
  var WORKFLOW_LABEL_HEADER = "Upstash-Label";
@@ -234,102 +242,6 @@ var getSteps = async (requester, workflowRunId, messageId, dispatchDebug) => {
234
242
  }
235
243
  };
236
244
 
237
- // src/context/auto-executor.ts
238
- var import_qstash5 = require("@upstash/qstash");
239
-
240
- // src/qstash/headers.ts
241
- var import_qstash4 = require("@upstash/qstash");
242
-
243
- // src/utils.ts
244
- var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
245
- var NANOID_LENGTH = 21;
246
- var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
247
- function validateLabel(label) {
248
- if (label === void 0) return;
249
- const labels = Array.isArray(label) ? label : [label];
250
- if (labels.length === 0) {
251
- throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
252
- }
253
- for (const value of labels) {
254
- if (!RESOURCE_NAME_PATTERN.test(value)) {
255
- throw new WorkflowNonRetryableError(
256
- `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
257
- );
258
- }
259
- }
260
- }
261
- function serializeLabel(label) {
262
- return Array.isArray(label) ? label.join(",") : label;
263
- }
264
- function validateFlowControl(flowControl) {
265
- if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
266
- throw new WorkflowNonRetryableError(
267
- `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
268
- );
269
- }
270
- }
271
- function getRandomInt() {
272
- return Math.floor(Math.random() * NANOID_CHARS.length);
273
- }
274
- function nanoid(length = NANOID_LENGTH) {
275
- return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
276
- }
277
- function getWorkflowRunId(id) {
278
- return `wfr_${id ?? nanoid()}`;
279
- }
280
- function decodeBase64(base64) {
281
- const binString = atob(base64);
282
- try {
283
- const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
284
- return new TextDecoder().decode(intArray);
285
- } catch (error) {
286
- console.warn(
287
- `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
288
- );
289
- return binString;
290
- }
291
- }
292
- function getUserIdFromToken(qstashClient) {
293
- try {
294
- const token = qstashClient.token;
295
- const decodedToken = decodeBase64(token);
296
- const tokenPayload = JSON.parse(decodedToken);
297
- const userId = tokenPayload.UserID;
298
- if (!userId) {
299
- throw new WorkflowError("QStash token payload does not contain userId");
300
- }
301
- return userId;
302
- } catch (error) {
303
- throw new WorkflowError(
304
- `Failed to decode QStash token while running create webhook step: ${error.message}`
305
- );
306
- }
307
- }
308
- function getQStashUrl(qstashClient) {
309
- try {
310
- const requester = qstashClient.http;
311
- const baseUrl = requester.baseUrl;
312
- if (!baseUrl) {
313
- throw new WorkflowError("QStash client does not have a baseUrl");
314
- }
315
- return baseUrl;
316
- } catch (error) {
317
- throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
318
- }
319
- }
320
- function getEventId() {
321
- return `evt_${nanoid(15)}`;
322
- }
323
- function stringifyBody(body) {
324
- if (body === void 0) {
325
- return void 0;
326
- }
327
- if (typeof body === "string") {
328
- return body;
329
- }
330
- return JSON.stringify(body);
331
- }
332
-
333
245
  // node_modules/neverthrow/dist/index.es.js
334
246
  var defaultErrorConfig = {
335
247
  withStackTrace: false
@@ -745,6 +657,102 @@ var Err = class {
745
657
  };
746
658
  var fromThrowable = Result.fromThrowable;
747
659
 
660
+ // src/context/auto-executor.ts
661
+ var import_qstash5 = require("@upstash/qstash");
662
+
663
+ // src/qstash/headers.ts
664
+ var import_qstash4 = require("@upstash/qstash");
665
+
666
+ // src/utils.ts
667
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
668
+ var NANOID_LENGTH = 21;
669
+ var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
670
+ function validateLabel(label) {
671
+ if (label === void 0) return;
672
+ const labels = Array.isArray(label) ? label : [label];
673
+ if (labels.length === 0) {
674
+ throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
675
+ }
676
+ for (const value of labels) {
677
+ if (!RESOURCE_NAME_PATTERN.test(value)) {
678
+ throw new WorkflowNonRetryableError(
679
+ `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
680
+ );
681
+ }
682
+ }
683
+ }
684
+ function serializeLabel(label) {
685
+ return Array.isArray(label) ? label.join(",") : label;
686
+ }
687
+ function validateFlowControl(flowControl) {
688
+ if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
689
+ throw new WorkflowNonRetryableError(
690
+ `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
691
+ );
692
+ }
693
+ }
694
+ function getRandomInt() {
695
+ return Math.floor(Math.random() * NANOID_CHARS.length);
696
+ }
697
+ function nanoid(length = NANOID_LENGTH) {
698
+ return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
699
+ }
700
+ function getWorkflowRunId(id) {
701
+ return `wfr_${id ?? nanoid()}`;
702
+ }
703
+ function decodeBase64(base64) {
704
+ const binString = atob(base64);
705
+ try {
706
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
707
+ return new TextDecoder().decode(intArray);
708
+ } catch (error) {
709
+ console.warn(
710
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
711
+ );
712
+ return binString;
713
+ }
714
+ }
715
+ function getUserIdFromToken(qstashClient) {
716
+ try {
717
+ const token = qstashClient.token;
718
+ const decodedToken = decodeBase64(token);
719
+ const tokenPayload = JSON.parse(decodedToken);
720
+ const userId = tokenPayload.UserID;
721
+ if (!userId) {
722
+ throw new WorkflowError("QStash token payload does not contain userId");
723
+ }
724
+ return userId;
725
+ } catch (error) {
726
+ throw new WorkflowError(
727
+ `Failed to decode QStash token while running create webhook step: ${error.message}`
728
+ );
729
+ }
730
+ }
731
+ function getQStashUrl(qstashClient) {
732
+ try {
733
+ const requester = qstashClient.http;
734
+ const baseUrl = requester.baseUrl;
735
+ if (!baseUrl) {
736
+ throw new WorkflowError("QStash client does not have a baseUrl");
737
+ }
738
+ return baseUrl;
739
+ } catch (error) {
740
+ throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
741
+ }
742
+ }
743
+ function getEventId() {
744
+ return `evt_${nanoid(15)}`;
745
+ }
746
+ function stringifyBody(body) {
747
+ if (body === void 0) {
748
+ return void 0;
749
+ }
750
+ if (typeof body === "string") {
751
+ return body;
752
+ }
753
+ return JSON.stringify(body);
754
+ }
755
+
748
756
  // src/types.ts
749
757
  var StepTypes = [
750
758
  "Initial",
@@ -854,6 +862,10 @@ var triggerFirstInvocation = async (params) => {
854
862
  return err(error_);
855
863
  }
856
864
  };
865
+ var flushPendingStep = async (workflowContext) => {
866
+ const { executor } = workflowContext;
867
+ return await executor.submitPendingStep();
868
+ };
857
869
  var triggerRouteFunction = async ({
858
870
  onCleanup,
859
871
  onStep,
@@ -1066,8 +1078,29 @@ If you want to disable QStash Verification, you should clear env variables QSTAS
1066
1078
  var BaseLazyStep = class _BaseLazyStep {
1067
1079
  stepName;
1068
1080
  context;
1069
- constructor(context, stepName) {
1081
+ /**
1082
+ * step-level settings (flow control, retries etc.) which override the
1083
+ * settings the workflow run was triggered with, for this step only.
1084
+ */
1085
+ stepSettings;
1086
+ /**
1087
+ * whether this step's result can be submitted after the route function
1088
+ * has moved on, instead of right away.
1089
+ *
1090
+ * Enabled for steps whose `getResultStep` produces the final `out` —
1091
+ * which is not the same as "needs no server round trip":
1092
+ * `LazyCreateWebhookStep` builds its result in `getBody` and returns
1093
+ * `out: undefined` from `getResultStep`, so deferring it would hand
1094
+ * `undefined` to the route function.
1095
+ *
1096
+ * Deferring lets the route function continue and reveal the next step,
1097
+ * so that step's settings can ride on this step's submission instead
1098
+ * of needing a step config request of their own.
1099
+ */
1100
+ supportsDeferredSubmission = false;
1101
+ constructor(context, stepName, stepSettings) {
1070
1102
  this.context = context;
1103
+ this.stepSettings = stepSettings;
1071
1104
  if (!stepName) {
1072
1105
  throw new WorkflowError(
1073
1106
  "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
@@ -1131,7 +1164,13 @@ var BaseLazyStep = class _BaseLazyStep {
1131
1164
  step.out = JSON.stringify(step.out);
1132
1165
  return JSON.stringify(step);
1133
1166
  }
1134
- getHeaders({ context, telemetry: telemetry2, invokeCount, step }) {
1167
+ getHeaders({
1168
+ context,
1169
+ telemetry: telemetry2,
1170
+ invokeCount,
1171
+ step,
1172
+ stepSettings
1173
+ }) {
1135
1174
  return getHeaders({
1136
1175
  initHeaderValue: "false",
1137
1176
  workflowConfig: {
@@ -1145,7 +1184,8 @@ var BaseLazyStep = class _BaseLazyStep {
1145
1184
  stepInfo: {
1146
1185
  step,
1147
1186
  lazyStep: this
1148
- }
1187
+ },
1188
+ stepSettings
1149
1189
  });
1150
1190
  }
1151
1191
  async submitStep({ context, body, headers }) {
@@ -1163,8 +1203,9 @@ var LazyFunctionStep = class extends BaseLazyStep {
1163
1203
  stepFunction;
1164
1204
  stepType = "Run";
1165
1205
  allowUndefinedOut = true;
1166
- constructor(context, stepName, stepFunction) {
1167
- super(context, stepName);
1206
+ supportsDeferredSubmission = true;
1207
+ constructor(context, stepName, stepFunction, stepSettings) {
1208
+ super(context, stepName, stepSettings);
1168
1209
  this.stepFunction = stepFunction;
1169
1210
  }
1170
1211
  getPlanStep(concurrent, targetStep) {
@@ -1194,6 +1235,7 @@ var LazySleepStep = class extends BaseLazyStep {
1194
1235
  sleep;
1195
1236
  stepType = "SleepFor";
1196
1237
  allowUndefinedOut = true;
1238
+ supportsDeferredSubmission = true;
1197
1239
  constructor(context, stepName, sleep) {
1198
1240
  super(context, stepName);
1199
1241
  this.sleep = sleep;
@@ -1233,6 +1275,7 @@ var LazySleepUntilStep = class extends BaseLazyStep {
1233
1275
  sleepUntil;
1234
1276
  stepType = "SleepUntil";
1235
1277
  allowUndefinedOut = true;
1278
+ supportsDeferredSubmission = true;
1236
1279
  constructor(context, stepName, sleepUntil) {
1237
1280
  super(context, stepName);
1238
1281
  this.sleepUntil = sleepUntil;
@@ -1734,6 +1777,7 @@ var WorkflowHeaders = class {
1734
1777
  invokeCount;
1735
1778
  initHeaderValue;
1736
1779
  stepInfo;
1780
+ stepSettings;
1737
1781
  headers;
1738
1782
  /**
1739
1783
  * @param params workflow header parameters
@@ -1743,17 +1787,20 @@ var WorkflowHeaders = class {
1743
1787
  workflowConfig,
1744
1788
  invokeCount,
1745
1789
  initHeaderValue,
1746
- stepInfo
1790
+ stepInfo,
1791
+ stepSettings
1747
1792
  }) {
1748
1793
  this.userHeaders = userHeaders;
1749
1794
  this.workflowConfig = workflowConfig;
1750
1795
  this.invokeCount = invokeCount;
1751
1796
  this.initHeaderValue = initHeaderValue;
1752
1797
  this.stepInfo = stepInfo;
1798
+ this.stepSettings = stepSettings;
1753
1799
  this.headers = {
1754
1800
  rawHeaders: {},
1755
1801
  workflowHeaders: {},
1756
- failureHeaders: {}
1802
+ failureHeaders: {},
1803
+ stepSettingsHeaders: {}
1757
1804
  };
1758
1805
  }
1759
1806
  getHeaders() {
@@ -1764,6 +1811,7 @@ var WorkflowHeaders = class {
1764
1811
  this.addUserHeaders();
1765
1812
  this.addInvokeCount();
1766
1813
  this.addFailureUrl();
1814
+ this.addStepSettings();
1767
1815
  const contentType = this.addContentType();
1768
1816
  return this.prefixHeaders(contentType);
1769
1817
  }
@@ -1773,7 +1821,7 @@ var WorkflowHeaders = class {
1773
1821
  [WORKFLOW_INIT_HEADER]: this.initHeaderValue,
1774
1822
  [WORKFLOW_ID_HEADER]: this.workflowConfig.workflowRunId,
1775
1823
  [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
1776
- [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig",
1824
+ [WORKFLOW_FEATURE_HEADER]: WORKFLOW_FEATURE_SET,
1777
1825
  [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1778
1826
  ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}
1779
1827
  };
@@ -1854,7 +1902,7 @@ var WorkflowHeaders = class {
1854
1902
  this.headers.failureHeaders["Workflow-Init"] = "false";
1855
1903
  this.headers.failureHeaders["Workflow-Url"] = this.workflowConfig.workflowUrl;
1856
1904
  this.headers.failureHeaders["Workflow-Calltype"] = "failureCall";
1857
- this.headers.failureHeaders["Feature-Set"] = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
1905
+ this.headers.failureHeaders["Feature-Set"] = WORKFLOW_FEATURE_SET;
1858
1906
  if (this.workflowConfig.retries !== void 0 && this.workflowConfig.retries !== DEFAULT_RETRIES) {
1859
1907
  this.headers.failureHeaders["Retries"] = this.workflowConfig.retries.toString();
1860
1908
  }
@@ -1862,6 +1910,42 @@ var WorkflowHeaders = class {
1862
1910
  this.headers.failureHeaders["Retry-Delay"] = this.workflowConfig.retryDelay.toString();
1863
1911
  }
1864
1912
  }
1913
+ /**
1914
+ * Applies the step-level settings of a step to the message.
1915
+ *
1916
+ * These headers configure the message itself, so that QStash uses them
1917
+ * instead of the settings the run was triggered with. The delivery of
1918
+ * the message is what executes the step, which is how a step's
1919
+ * settings reach it.
1920
+ *
1921
+ * When any setting is present the feature set is extended with
1922
+ * `WF_StepConfig`, which is what tells QStash to keep them. QStash
1923
+ * reports that back on the delivery as `Upstash-Workflow-Step-Config`.
1924
+ */
1925
+ addStepSettings() {
1926
+ if (!this.stepSettings) {
1927
+ return;
1928
+ }
1929
+ const headers = {};
1930
+ if (this.stepSettings.flowControl) {
1931
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
1932
+ this.stepSettings.flowControl
1933
+ );
1934
+ headers[FLOW_CONTROL_KEY_HEADER] = flowControlKey;
1935
+ headers[FLOW_CONTROL_VALUE_HEADER] = flowControlValue;
1936
+ }
1937
+ if (this.stepSettings.retries !== void 0) {
1938
+ headers[RETRIES_HEADER] = this.stepSettings.retries.toString();
1939
+ }
1940
+ if (this.stepSettings.retryDelay) {
1941
+ headers[RETRY_DELAY_HEADER] = this.stepSettings.retryDelay;
1942
+ }
1943
+ if (Object.keys(headers).length === 0) {
1944
+ return;
1945
+ }
1946
+ headers[WORKFLOW_FEATURE_HEADER] = `${WORKFLOW_FEATURE_SET},${WORKFLOW_STEP_CONFIG_FEATURE}`;
1947
+ this.headers.stepSettingsHeaders = headers;
1948
+ }
1865
1949
  addContentType() {
1866
1950
  if (this.workflowConfig.useJSONContent) {
1867
1951
  this.headers.rawHeaders["content-type"] = "application/json";
@@ -1875,14 +1959,17 @@ var WorkflowHeaders = class {
1875
1959
  return contentType;
1876
1960
  }
1877
1961
  prefixHeaders(contentType) {
1878
- const { rawHeaders, workflowHeaders, failureHeaders } = this.headers;
1962
+ const { rawHeaders, workflowHeaders, failureHeaders, stepSettingsHeaders } = this.headers;
1879
1963
  const isCall = this.stepInfo?.lazyStep.stepType === "Call";
1880
1964
  return {
1881
1965
  headers: {
1882
1966
  ...rawHeaders,
1883
1967
  ...addPrefixToHeaders(workflowHeaders, isCall ? "Upstash-Callback-" : "Upstash-"),
1884
1968
  ...addPrefixToHeaders(failureHeaders, "Upstash-Failure-Callback-"),
1885
- ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {}
1969
+ ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {},
1970
+ // last, so they override the run's settings above. Never
1971
+ // prefixed: they configure this message, not its callback.
1972
+ ...stepSettingsHeaders
1886
1973
  },
1887
1974
  contentType
1888
1975
  };
@@ -1933,7 +2020,7 @@ var submitParallelSteps = async ({
1933
2020
  info: `Submitting ${planSteps.length} parallel steps.`
1934
2021
  });
1935
2022
  const result = await context.qstashClient.batch(
1936
- planSteps.map((planStep) => {
2023
+ planSteps.map((planStep, index) => {
1937
2024
  const { headers } = getHeaders({
1938
2025
  initHeaderValue: "false",
1939
2026
  workflowConfig: {
@@ -1942,7 +2029,8 @@ var submitParallelSteps = async ({
1942
2029
  workflowRunCreatedAt: context.workflowRunCreatedAt,
1943
2030
  telemetry: telemetry2
1944
2031
  },
1945
- invokeCount
2032
+ invokeCount,
2033
+ stepSettings: steps[index].stepSettings
1946
2034
  });
1947
2035
  return {
1948
2036
  headers,
@@ -1961,31 +2049,38 @@ var submitParallelSteps = async ({
1961
2049
  }
1962
2050
  throw new WorkflowAbort(planSteps[0].stepName, planSteps[0]);
1963
2051
  };
1964
- var submitSingleStep = async ({
1965
- context,
2052
+ var executeStep = async ({
1966
2053
  lazyStep,
1967
2054
  stepId,
1968
- invokeCount,
1969
2055
  concurrency,
1970
- telemetry: telemetry2,
1971
- dispatchDebug,
1972
2056
  dispatchLifecycle
1973
2057
  }) => {
1974
2058
  await dispatchLifecycle("beforeExecution", {
1975
2059
  stepName: lazyStep.stepName
1976
2060
  });
1977
- let resultStep;
1978
2061
  try {
1979
- resultStep = await lazyStep.getResultStep(concurrency, stepId);
2062
+ return await lazyStep.getResultStep(concurrency, stepId);
1980
2063
  } catch (error) {
1981
2064
  attachStepNameToError(error, lazyStep.stepName);
1982
2065
  throw error;
1983
2066
  }
2067
+ };
2068
+ var submitStepResult = async ({
2069
+ context,
2070
+ lazyStep,
2071
+ resultStep,
2072
+ invokeCount,
2073
+ concurrency,
2074
+ telemetry: telemetry2,
2075
+ dispatchDebug,
2076
+ nextStepSettings
2077
+ }) => {
1984
2078
  const { headers } = lazyStep.getHeaders({
1985
2079
  context,
1986
2080
  step: resultStep,
1987
2081
  invokeCount,
1988
- telemetry: telemetry2
2082
+ telemetry: telemetry2,
2083
+ stepSettings: nextStepSettings
1989
2084
  });
1990
2085
  const body = lazyStep.getBody({
1991
2086
  context,
@@ -2010,6 +2105,154 @@ var submitSingleStep = async ({
2010
2105
  }
2011
2106
  return resultStep;
2012
2107
  };
2108
+ var publishStepConfigRequest = async ({
2109
+ context,
2110
+ lazyStep,
2111
+ targetStep,
2112
+ invokeCount,
2113
+ telemetry: telemetry2,
2114
+ dispatchDebug
2115
+ }) => {
2116
+ const { headers } = getHeaders({
2117
+ initHeaderValue: "false",
2118
+ workflowConfig: {
2119
+ workflowRunId: context.workflowRunId,
2120
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2121
+ workflowUrl: context.url,
2122
+ telemetry: telemetry2
2123
+ },
2124
+ invokeCount,
2125
+ stepSettings: lazyStep.stepSettings
2126
+ });
2127
+ await dispatchDebug("onInfo", {
2128
+ info: `Step "${lazyStep.stepName}" (${targetStep}) has step-level settings which the current delivery does not carry. Requesting a delivery which does.`
2129
+ });
2130
+ const result = await context.qstashClient.publishJSON({
2131
+ headers: {
2132
+ ...headers,
2133
+ "Upstash-Workflow-CallType": WORKFLOW_STEP_CONFIG_CALL_TYPE,
2134
+ "Upstash-Forward-Upstash-Workflow-StepId": targetStep.toString(),
2135
+ "Upstash-Forward-Upstash-Workflow-StepName": lazyStep.stepName
2136
+ },
2137
+ method: "POST",
2138
+ body: { targetStep, invokeCount },
2139
+ url: context.url,
2140
+ contentBasedDeduplication: true
2141
+ });
2142
+ if (result?.deduplicated) {
2143
+ await dispatchDebug("onWarning", {
2144
+ warning: `A step config request for step "${lazyStep.stepName}" (${targetStep}) was already published and this one was deduplicated. Expected when the delivery which published it is being retried; otherwise the run stops here.`
2145
+ });
2146
+ } else if (result?.messageId) {
2147
+ await dispatchDebug("onInfo", {
2148
+ info: `Requested a delivery under the settings of step "${lazyStep.stepName}" with messageId: ${result.messageId}.`
2149
+ });
2150
+ }
2151
+ };
2152
+
2153
+ // src/qstash/step-config.ts
2154
+ var normalizeStepSettings = (settings) => {
2155
+ if (settings === void 0) {
2156
+ return void 0;
2157
+ }
2158
+ const { retries, retryDelay } = settings;
2159
+ if (retryDelay !== void 0 && typeof retryDelay !== "string") {
2160
+ throw new WorkflowNonRetryableError("Invalid step retryDelay: must be a string.");
2161
+ }
2162
+ if (retries !== void 0 && (!Number.isInteger(retries) || retries < 0)) {
2163
+ throw new WorkflowNonRetryableError("Invalid step retries: must be a non-negative integer.");
2164
+ }
2165
+ return { ...settings, retryDelay: retryDelay?.trim() || void 0 };
2166
+ };
2167
+ var DEFAULT_PARALLELISM = 0;
2168
+ var DEFAULT_RATE = 0;
2169
+ var DEFAULT_PERIOD_SECONDS = 1;
2170
+ var SECONDS_PER_UNIT = {
2171
+ s: 1,
2172
+ m: 60,
2173
+ h: 60 * 60,
2174
+ d: 24 * 60 * 60
2175
+ };
2176
+ var durationToSeconds = (duration) => {
2177
+ if (typeof duration === "number") {
2178
+ return Number.isFinite(duration) ? duration : void 0;
2179
+ }
2180
+ const match = /^(\d+)([smhd])$/.exec(duration.trim());
2181
+ if (match) {
2182
+ return Number(match[1]) * SECONDS_PER_UNIT[match[2]];
2183
+ }
2184
+ const seconds = Number(duration.trim());
2185
+ return Number.isFinite(seconds) ? seconds : void 0;
2186
+ };
2187
+ var normalizeFlowControl = (flowControl) => {
2188
+ const period = flowControl.period === void 0 ? void 0 : durationToSeconds(flowControl.period);
2189
+ return {
2190
+ key: flowControl.key,
2191
+ parallelism: flowControl.parallelism ?? DEFAULT_PARALLELISM,
2192
+ rate: flowControl.rate ?? flowControl.ratePerSecond ?? DEFAULT_RATE,
2193
+ period: period ?? DEFAULT_PERIOD_SECONDS
2194
+ };
2195
+ };
2196
+ var parseFlowControlHeaders = (key, value) => {
2197
+ if (!key) {
2198
+ return void 0;
2199
+ }
2200
+ const flowControl = {
2201
+ key,
2202
+ parallelism: DEFAULT_PARALLELISM,
2203
+ rate: DEFAULT_RATE,
2204
+ period: DEFAULT_PERIOD_SECONDS
2205
+ };
2206
+ for (const entry of (value ?? "").split(",")) {
2207
+ const [name, rawValue] = entry.split("=").map((part) => part.trim());
2208
+ if (!name || rawValue === void 0) {
2209
+ continue;
2210
+ }
2211
+ switch (name) {
2212
+ case "parallelism": {
2213
+ flowControl.parallelism = Number(rawValue);
2214
+ break;
2215
+ }
2216
+ case "rate": {
2217
+ flowControl.rate = Number(rawValue);
2218
+ break;
2219
+ }
2220
+ case "period": {
2221
+ flowControl.period = durationToSeconds(rawValue) ?? DEFAULT_PERIOD_SECONDS;
2222
+ break;
2223
+ }
2224
+ }
2225
+ }
2226
+ return flowControl;
2227
+ };
2228
+ var getEffectiveConfig = (headers) => {
2229
+ const retriesHeader = headers.get(RETRIES_HEADER);
2230
+ return {
2231
+ flowControl: parseFlowControlHeaders(
2232
+ headers.get(FLOW_CONTROL_KEY_HEADER),
2233
+ headers.get(FLOW_CONTROL_VALUE_HEADER)
2234
+ ),
2235
+ retries: retriesHeader === null ? void 0 : Number(retriesHeader),
2236
+ retryDelay: headers.get(RETRY_DELAY_HEADER) ?? void 0,
2237
+ hasStepConfig: headers.get(WORKFLOW_STEP_CONFIG_HEADER) === "true"
2238
+ };
2239
+ };
2240
+ var describeStepSettingsMismatch = (stepSettings, effectiveConfig) => {
2241
+ if (stepSettings.flowControl) {
2242
+ const wanted = normalizeFlowControl(stepSettings.flowControl);
2243
+ const applied = effectiveConfig.flowControl;
2244
+ if (!applied || applied.key !== wanted.key || applied.parallelism !== wanted.parallelism || applied.rate !== wanted.rate || applied.period !== wanted.period) {
2245
+ return `flow control: expected ${JSON.stringify(wanted)}, delivery has ${JSON.stringify(applied)}`;
2246
+ }
2247
+ }
2248
+ if (stepSettings.retries !== void 0 && effectiveConfig.retries !== void 0 && stepSettings.retries !== effectiveConfig.retries) {
2249
+ return `retries: expected ${stepSettings.retries}, delivery has ${effectiveConfig.retries}`;
2250
+ }
2251
+ if (stepSettings.retryDelay !== void 0 && stepSettings.retryDelay !== effectiveConfig.retryDelay) {
2252
+ return `retry delay: expected '${stepSettings.retryDelay}', delivery has '${effectiveConfig.retryDelay ?? ""}'`;
2253
+ }
2254
+ return void 0;
2255
+ };
2013
2256
 
2014
2257
  // src/context/auto-executor.ts
2015
2258
  var AutoExecutor = class _AutoExecutor {
@@ -2026,6 +2269,25 @@ var AutoExecutor = class _AutoExecutor {
2026
2269
  stepCount = 0;
2027
2270
  planStepCount = 0;
2028
2271
  executingStep = false;
2272
+ /**
2273
+ * an executed step whose result hasn't been submitted to QStash yet.
2274
+ *
2275
+ * Set when a step which can produce its result in-process executes. The
2276
+ * submission waits so that the route function can continue and reveal
2277
+ * what comes next: if that is a single step with step-level settings,
2278
+ * the settings ride on this submission and no step config request is
2279
+ * needed, since the delivery of the submission is what executes it.
2280
+ *
2281
+ * Flushed when the next step is reached (see `addStep`) or when the
2282
+ * route function ends (see `flushPendingStep` in `serve`).
2283
+ */
2284
+ pendingStep;
2285
+ /**
2286
+ * configuration QStash applied to the delivery being handled. A step
2287
+ * with step-level settings is settled by comparing its settings against
2288
+ * this.
2289
+ */
2290
+ effectiveConfig;
2029
2291
  /**
2030
2292
  * @param context workflow context
2031
2293
  * @param steps list of steps
@@ -2033,14 +2295,17 @@ var AutoExecutor = class _AutoExecutor {
2033
2295
  * @param dispatchLifecycle lifecycle event dispatcher
2034
2296
  * @param telemetry optional telemetry information
2035
2297
  * @param invokeCount optional invoke count
2298
+ * @param effectiveConfig configuration QStash applied to the delivery
2299
+ * being handled
2036
2300
  */
2037
- constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry2, invokeCount) {
2301
+ constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry2, invokeCount, effectiveConfig) {
2038
2302
  this.context = context;
2039
2303
  this.steps = steps;
2040
2304
  this.dispatchDebug = dispatchDebug;
2041
2305
  this.dispatchLifecycle = dispatchLifecycle;
2042
2306
  this.telemetry = telemetry2;
2043
2307
  this.invokeCount = invokeCount ?? 0;
2308
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2044
2309
  this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
2045
2310
  }
2046
2311
  /**
@@ -2075,6 +2340,15 @@ var AutoExecutor = class _AutoExecutor {
2075
2340
  lazyStepList.push(stepInfo);
2076
2341
  const index = this.indexInCurrentList++;
2077
2342
  const requestComplete = this.deferExecution().then(async () => {
2343
+ const submitted = await this.submitPendingStep(
2344
+ lazyStepList.length === 1 ? lazyStepList[0].stepSettings : void 0
2345
+ );
2346
+ if (submitted.isErr()) {
2347
+ throw submitted.error;
2348
+ }
2349
+ if (submitted.value.result === "submitted-step") {
2350
+ throw submitted.value.abort;
2351
+ }
2078
2352
  if (!this.promises.has(lazyStepList)) {
2079
2353
  const promise2 = this.getExecutionPromise(lazyStepList);
2080
2354
  this.promises.set(lazyStepList, promise2);
@@ -2128,18 +2402,108 @@ var AutoExecutor = class _AutoExecutor {
2128
2402
  }
2129
2403
  return parsedOut;
2130
2404
  }
2131
- const resultStep = await submitSingleStep({
2132
- context: this.context,
2405
+ const mismatch = lazyStep.stepSettings ? describeStepSettingsMismatch(lazyStep.stepSettings, this.effectiveConfig) : void 0;
2406
+ if (mismatch) {
2407
+ if (!this.effectiveConfig.hasStepConfig) {
2408
+ await publishStepConfigRequest({
2409
+ context: this.context,
2410
+ lazyStep,
2411
+ targetStep: this.stepCount,
2412
+ invokeCount: this.invokeCount,
2413
+ telemetry: this.telemetry,
2414
+ dispatchDebug: this.dispatchDebug
2415
+ });
2416
+ throw new WorkflowAbort(lazyStep.stepName);
2417
+ } else {
2418
+ await this.dispatchDebug("onWarning", {
2419
+ warning: `The step-level settings of step '${lazyStep.stepName}' were published but are not recognized on the delivery which carries them (${mismatch}). Executing the step with the settings of the delivery instead. This is a bug in @upstash/workflow, please report it.`
2420
+ });
2421
+ }
2422
+ }
2423
+ const resultStep = await executeStep({
2133
2424
  lazyStep,
2134
2425
  stepId: this.stepCount,
2426
+ concurrency: NO_CONCURRENCY,
2427
+ dispatchLifecycle: this.dispatchLifecycle
2428
+ });
2429
+ if (lazyStep.supportsDeferredSubmission) {
2430
+ const serializedOut = JSON.stringify(resultStep.out);
2431
+ this.pendingStep = {
2432
+ status: "held",
2433
+ lazyStep,
2434
+ resultStep: {
2435
+ ...resultStep,
2436
+ out: serializedOut === void 0 ? void 0 : JSON.parse(serializedOut)
2437
+ }
2438
+ };
2439
+ return lazyStep.parseOut({
2440
+ ...resultStep,
2441
+ out: serializedOut
2442
+ });
2443
+ }
2444
+ await submitStepResult({
2445
+ context: this.context,
2446
+ lazyStep,
2447
+ resultStep,
2135
2448
  invokeCount: this.invokeCount,
2136
- concurrency: 1,
2449
+ concurrency: NO_CONCURRENCY,
2137
2450
  telemetry: this.telemetry,
2138
- dispatchDebug: this.dispatchDebug,
2139
- dispatchLifecycle: this.dispatchLifecycle
2451
+ dispatchDebug: this.dispatchDebug
2140
2452
  });
2141
2453
  throw new WorkflowAbort(lazyStep.stepName, resultStep);
2142
2454
  }
2455
+ /**
2456
+ * Submits the result of the step being held, if there is one, and
2457
+ * returns the abort the caller has to throw to end the invocation.
2458
+ *
2459
+ * Returns undefined when no step is being held, which is the caller's
2460
+ * signal that there is nothing to end. Throws instead of returning
2461
+ * when the submission itself fails, so that error reaches the caller
2462
+ * rather than an abort claiming the step was submitted.
2463
+ *
2464
+ * Callers which arrive while a submission is already under way (the
2465
+ * steps of a parallel group, added together) wait for that one and get
2466
+ * the same abort, rather than submitting a second time.
2467
+ *
2468
+ * The next step's settings are attached whenever it has any, without
2469
+ * checking them against the current delivery: the executor only knows
2470
+ * the configuration of the delivery in hand, which inside a
2471
+ * delivery is the *previous* step's, so such a check would be wrong
2472
+ * exactly when two steps with settings follow each other.
2473
+ *
2474
+ * @param nextStepSettings step-level settings of the next step
2475
+ * @returns `submitted-step` with the abort which ends this invocation,
2476
+ * or `no-pending-step` when nothing was held and there is nothing to
2477
+ * end
2478
+ */
2479
+ async submitPendingStep(nextStepSettings) {
2480
+ if (!this.pendingStep) {
2481
+ return ok({ result: "no-pending-step" });
2482
+ }
2483
+ try {
2484
+ if (this.pendingStep.status === "submitting") {
2485
+ return ok({ result: "submitted-step", abort: await this.pendingStep.submitted });
2486
+ }
2487
+ const { lazyStep, resultStep } = this.pendingStep;
2488
+ const submitted = (async () => {
2489
+ await submitStepResult({
2490
+ context: this.context,
2491
+ lazyStep,
2492
+ resultStep,
2493
+ invokeCount: this.invokeCount,
2494
+ concurrency: NO_CONCURRENCY,
2495
+ telemetry: this.telemetry,
2496
+ dispatchDebug: this.dispatchDebug,
2497
+ nextStepSettings
2498
+ });
2499
+ return new WorkflowAbort(lazyStep.stepName, resultStep);
2500
+ })();
2501
+ this.pendingStep = { status: "submitting", submitted };
2502
+ return ok({ result: "submitted-step", abort: await submitted });
2503
+ } catch (error) {
2504
+ return err(error);
2505
+ }
2506
+ }
2143
2507
  /**
2144
2508
  * Runs steps in parallel.
2145
2509
  *
@@ -2188,15 +2552,20 @@ var AutoExecutor = class _AutoExecutor {
2188
2552
  validateStep(parallelSteps[stepIndex], planStep);
2189
2553
  try {
2190
2554
  const parallelStep = parallelSteps[stepIndex];
2191
- const resultStep = await submitSingleStep({
2192
- context: this.context,
2555
+ const resultStep = await executeStep({
2193
2556
  lazyStep: parallelStep,
2194
2557
  stepId: planStep.targetStep,
2558
+ concurrency: parallelSteps.length,
2559
+ dispatchLifecycle: this.dispatchLifecycle
2560
+ });
2561
+ await submitStepResult({
2562
+ context: this.context,
2563
+ lazyStep: parallelStep,
2564
+ resultStep,
2195
2565
  invokeCount: this.invokeCount,
2196
2566
  concurrency: parallelSteps.length,
2197
2567
  telemetry: this.telemetry,
2198
- dispatchDebug: this.dispatchDebug,
2199
- dispatchLifecycle: this.dispatchLifecycle
2568
+ dispatchDebug: this.dispatchDebug
2200
2569
  });
2201
2570
  throw new WorkflowAbort(parallelStep.stepName, resultStep);
2202
2571
  } catch (error) {
@@ -2414,6 +2783,11 @@ var BaseWorkflowApi = class {
2414
2783
 
2415
2784
  // src/context/api/anthropic.ts
2416
2785
  var AnthropicAPI = class extends BaseWorkflowApi {
2786
+ /**
2787
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2788
+ *
2789
+ * @see node_modules/@upstash/workflow/docs/integrations/anthropic.mdx
2790
+ */
2417
2791
  async call(stepName, settings) {
2418
2792
  const { token, operation, ...parameters } = settings;
2419
2793
  return await this.callApi(stepName, {
@@ -2429,6 +2803,11 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2429
2803
  // src/context/api/openai.ts
2430
2804
  var import_qstash7 = require("@upstash/qstash");
2431
2805
  var OpenAIAPI = class extends BaseWorkflowApi {
2806
+ /**
2807
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2808
+ *
2809
+ * @see node_modules/@upstash/workflow/docs/integrations/openai.mdx
2810
+ */
2432
2811
  async call(stepName, settings) {
2433
2812
  const { token, organization, operation, baseURL, ...parameters } = settings;
2434
2813
  const useOpenAI = baseURL === void 0;
@@ -2446,6 +2825,11 @@ var OpenAIAPI = class extends BaseWorkflowApi {
2446
2825
  // src/context/api/resend.ts
2447
2826
  var import_qstash8 = require("@upstash/qstash");
2448
2827
  var ResendAPI = class extends BaseWorkflowApi {
2828
+ /**
2829
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2830
+ *
2831
+ * @see node_modules/@upstash/workflow/docs/integrations/resend.mdx
2832
+ */
2449
2833
  async call(stepName, settings) {
2450
2834
  const { token, batch = false, ...parameters } = settings;
2451
2835
  return await this.callApi(stepName, {
@@ -2687,8 +3071,9 @@ var WorkflowContext = class {
2687
3071
  *
2688
3072
  * ```ts
2689
3073
  * import { Client } from "@upstash/qstash"
3074
+ * import { serve } from "@upstash/workflow/nextjs"
2690
3075
  *
2691
- * export const POST = serve(
3076
+ * export const { POST } = serve(
2692
3077
  * async (context) => {
2693
3078
  * ...
2694
3079
  * },
@@ -2713,7 +3098,7 @@ var WorkflowContext = class {
2713
3098
  * Can be overwritten by passing a `url` parameter in `serve`:
2714
3099
  *
2715
3100
  * ```ts
2716
- * export const POST = serve(
3101
+ * export const { POST } = serve(
2717
3102
  * async (context) => {
2718
3103
  * ...
2719
3104
  * },
@@ -2731,7 +3116,7 @@ var WorkflowContext = class {
2731
3116
  *
2732
3117
  * ```ts
2733
3118
  * // set requestPayload type to MyPayload:
2734
- * export const POST = serve<MyPayload>(
3119
+ * export const { POST } = serve<MyPayload>(
2735
3120
  * async (context) => {
2736
3121
  * ...
2737
3122
  * }
@@ -2743,7 +3128,7 @@ var WorkflowContext = class {
2743
3128
  * the `initialPayloadParser` parameter:
2744
3129
  *
2745
3130
  * ```ts
2746
- * export const POST = serve<MyPayload>(
3131
+ * export const { POST } = serve<MyPayload>(
2747
3132
  * async (context) => {
2748
3133
  * ...
2749
3134
  * },
@@ -2752,6 +3137,13 @@ var WorkflowContext = class {
2752
3137
  * }
2753
3138
  * )
2754
3139
  * ```
3140
+ *
3141
+ * When a `context.call` response comes back, the route runs up to its first step with this
3142
+ * set to the call-result envelope (and `workflowRunId` set to a random id) before the SDK
3143
+ * recognizes the request. Code before the first step must not dereference, validate or
3144
+ * return early on the payload; read it inside `context.run`.
3145
+ *
3146
+ * @see node_modules/@upstash/workflow/docs/basics/serve/advanced.mdx
2755
3147
  */
2756
3148
  requestPayload;
2757
3149
  /**
@@ -2764,7 +3156,7 @@ var WorkflowContext = class {
2764
3156
  * Can be set using the `env` option of serve:
2765
3157
  *
2766
3158
  * ```ts
2767
- * export const POST = serve<MyPayload>(
3159
+ * export const { POST } = serve<MyPayload>(
2768
3160
  * async (context) => {
2769
3161
  * const key = context.env["API_KEY"];
2770
3162
  * },
@@ -2812,6 +3204,46 @@ var WorkflowContext = class {
2812
3204
  * `1` on the first retry, `2` on the second, and so on.
2813
3205
  */
2814
3206
  retried;
3207
+ /**
3208
+ * Configuration QStash applied to the request being handled.
3209
+ *
3210
+ * This is the configuration of *this delivery*, not of the run: it is
3211
+ * the configuration the run was triggered with, except inside the
3212
+ * delivery which executes a step that has step-level settings, where
3213
+ * it is that step's settings. The fields below expose it; the executor
3214
+ * gets it directly rather than reaching through the context.
3215
+ */
3216
+ effectiveConfig;
3217
+ /**
3218
+ * Flow control QStash applied to the request being handled, if any.
3219
+ *
3220
+ * This is the flow control of the request in hand, which is the one the
3221
+ * run was triggered with except inside a step carrying its own.
3222
+ */
3223
+ get flowControl() {
3224
+ return this.effectiveConfig.flowControl;
3225
+ }
3226
+ /**
3227
+ * Retry limit QStash applied to the request being handled, if it
3228
+ * reported one.
3229
+ *
3230
+ * Not to be confused with {@link retried}, which is how many retries
3231
+ * have already happened.
3232
+ *
3233
+ * @see {@link flowControl} for what "the request being handled" means
3234
+ */
3235
+ get retries() {
3236
+ return this.effectiveConfig.retries;
3237
+ }
3238
+ /**
3239
+ * Retry delay expression QStash applied to the request being handled,
3240
+ * if any.
3241
+ *
3242
+ * @see {@link flowControl} for what "the request being handled" means
3243
+ */
3244
+ get retryDelay() {
3245
+ return this.effectiveConfig.retryDelay;
3246
+ }
2815
3247
  constructor({
2816
3248
  qstashClient,
2817
3249
  workflowRunId,
@@ -2825,7 +3257,8 @@ var WorkflowContext = class {
2825
3257
  invokeCount,
2826
3258
  label,
2827
3259
  retried,
2828
- middlewareManager
3260
+ middlewareManager,
3261
+ effectiveConfig
2829
3262
  }) {
2830
3263
  this.qstashClient = qstashClient;
2831
3264
  this.workflowRunId = workflowRunId;
@@ -2837,6 +3270,7 @@ var WorkflowContext = class {
2837
3270
  this.env = env ?? {};
2838
3271
  this.labels = label === void 0 ? [] : Array.isArray(label) ? label : label ? label.split(",") : [];
2839
3272
  this.retried = retried ?? 0;
3273
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2840
3274
  const middlewareManagerInstance = middlewareManager ?? new MiddlewareManager([]);
2841
3275
  middlewareManagerInstance.assignContext(this);
2842
3276
  this.executor = new AutoExecutor(
@@ -2845,7 +3279,8 @@ var WorkflowContext = class {
2845
3279
  middlewareManagerInstance.dispatchDebug.bind(middlewareManagerInstance),
2846
3280
  middlewareManagerInstance.dispatchLifecycle.bind(middlewareManagerInstance),
2847
3281
  telemetry2,
2848
- invokeCount
3282
+ invokeCount,
3283
+ this.effectiveConfig
2849
3284
  );
2850
3285
  }
2851
3286
  /**
@@ -2871,13 +3306,41 @@ var WorkflowContext = class {
2871
3306
  * ])
2872
3307
  * ```
2873
3308
  *
3309
+ * Step-level settings can be passed as a third argument, overriding
3310
+ * the settings the workflow run was triggered with for this step only:
3311
+ *
3312
+ * ```typescript
3313
+ * const result = await context.run(
3314
+ * "step 1",
3315
+ * () => {
3316
+ * return "result"
3317
+ * },
3318
+ * {
3319
+ * flowControl: { key: "custom-key", parallelism: 3 },
3320
+ * retries: 5,
3321
+ * }
3322
+ * )
3323
+ * ```
3324
+ *
3325
+ * Do not wrap steps in try/catch or `.catch` without rethrowing `WorkflowAbort`: each step
3326
+ * throws it to end the request. To stop retrying a failed step, throw
3327
+ * `WorkflowNonRetryableError`.
3328
+ *
2874
3329
  * @param stepName name of the step
2875
3330
  * @param stepFunction step function to be executed
3331
+ * @param stepSettings step-level settings for this step
2876
3332
  * @returns result of the step function
3333
+ * @see node_modules/@upstash/workflow/docs/steps/run.mdx
2877
3334
  */
2878
- async run(stepName, stepFunction) {
3335
+ async run(stepName, stepFunction, stepSettings) {
3336
+ const normalizedSettings = normalizeStepSettings(stepSettings);
3337
+ if (stepSettings) {
3338
+ validateFlowControl(stepSettings.flowControl);
3339
+ }
2879
3340
  const wrappedStepFunction = (() => this.executor.wrapStep(stepName, stepFunction));
2880
- return await this.addStep(new LazyFunctionStep(this, stepName, wrappedStepFunction));
3341
+ return await this.addStep(
3342
+ new LazyFunctionStep(this, stepName, wrappedStepFunction, normalizedSettings)
3343
+ );
2881
3344
  }
2882
3345
  /**
2883
3346
  * Stops the execution for the duration provided.
@@ -2887,8 +3350,9 @@ var WorkflowContext = class {
2887
3350
  * ```
2888
3351
  *
2889
3352
  * @param stepName
2890
- * @param duration sleep duration in seconds
3353
+ * @param duration sleep duration in seconds, or a duration string such as "10m"
2891
3354
  * @returns undefined
3355
+ * @see node_modules/@upstash/workflow/docs/steps/sleep.mdx
2892
3356
  */
2893
3357
  async sleep(stepName, duration) {
2894
3358
  await this.addStep(new LazySleepStep(this, stepName, duration));
@@ -2902,8 +3366,11 @@ var WorkflowContext = class {
2902
3366
  *
2903
3367
  * @param stepName
2904
3368
  * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
2905
- * as a Date object or a string (passed to `new Date(datetimeString)`)
3369
+ * as a Date object or a string (passed to `new Date(datetimeString)`).
3370
+ * A millisecond timestamp such as `Date.now()` is too far in the future, so QStash
3371
+ * rejects the step and the run fails. Pass `new Date(ms)` instead.
2906
3372
  * @returns undefined
3373
+ * @see node_modules/@upstash/workflow/docs/steps/sleepUntil.mdx
2907
3374
  */
2908
3375
  async sleepUntil(stepName, datetime) {
2909
3376
  let time;
@@ -2954,7 +3421,7 @@ var WorkflowContext = class {
2954
3421
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
2955
3422
  *
2956
3423
  *```ts
2957
- * const result = await workflow.waitForEvent("payment-confirmed", "payment.confirmed", {
3424
+ * const result = await context.waitForEvent("payment-confirmed", "payment.confirmed", {
2958
3425
  * timeout: "5m"
2959
3426
  * });
2960
3427
  *```
@@ -2978,11 +3445,14 @@ var WorkflowContext = class {
2978
3445
  * Alternatively, you can use the `context.notify` method.
2979
3446
  *
2980
3447
  * @param stepName
2981
- * @param eventId - Unique identifier for the event to wait for
3448
+ * @param eventId - Unique identifier for the event to wait for. Only letters, digits,
3449
+ * "-", "_" and "." are allowed. QStash rejects other characters, such as ":", which
3450
+ * stops the run with only a "Tried to append to a cancelled workflow" warning.
2982
3451
  * @param options - Configuration options.
2983
3452
  * @returns `{ timeout: boolean, eventData: TEventData }`.
2984
3453
  * The `timeout` property specifies if the workflow has timed out. The `eventData`
2985
3454
  * is the data passed when notifying this workflow of an event.
3455
+ * @see node_modules/@upstash/workflow/docs/steps/waitForEvent.mdx
2986
3456
  */
2987
3457
  async waitForEvent(stepName, eventId, options = {}) {
2988
3458
  const { timeout = "7d" } = options;
@@ -3004,28 +3474,31 @@ var WorkflowContext = class {
3004
3474
  * will receive the given event data and resume execution.
3005
3475
  *
3006
3476
  * The response includes the same eventId and eventData. Additionally, there is
3007
- * a notifyResponse field which contains a list of `Waiter` objects, each corresponding
3008
- * to a notified workflow run.
3009
- *
3010
- * Optionally, you can pass a workflowRunId to enable lookback functionality:
3011
- *
3012
- * ```ts
3013
- * const { eventId, eventData, notifyResponse } = await context.notify(
3014
- * "notify step", "event-id", "event-data", "wfr_123"
3015
- * );
3016
- * ```
3477
+ * a notifyResponse field which contains a list of `NotifyResponse` objects, each corresponding
3478
+ * to a notified workflow run. The notified `Waiter` is under `notifyResponse[i].waiter`.
3017
3479
  *
3018
3480
  * @param stepName
3019
- * @param eventId event id to notify
3481
+ * @param eventId event id to notify. Only letters, digits, "-", "_" and "." are allowed.
3482
+ * QStash rejects other characters, such as ":", which stops the run with only a
3483
+ * "Tried to append to a cancelled workflow" warning.
3020
3484
  * @param eventData event data to notify with
3021
- * @param workflowRunId optional workflow run id for lookback support
3022
- * @returns notify response which has event id, event data and list of waiters which were notified
3485
+ * @param workflowRunId optional workflow run id for lookback: the event is kept for the run
3486
+ * even if it has not reached `waitForEvent` yet
3487
+ * @returns notify response which has event id, event data and list of waiters which were
3488
+ * notified. With `workflowRunId`, QStash returns `notifyResponse` as a single object instead
3489
+ * of an array, despite the type.
3490
+ * @see node_modules/@upstash/workflow/docs/steps/notify.mdx
3023
3491
  */
3024
3492
  async notify(stepName, eventId, eventData, workflowRunId) {
3025
3493
  return await this.addStep(
3026
3494
  new LazyNotifyStep(this, stepName, eventId, eventData, this.qstashClient.http, workflowRunId)
3027
3495
  );
3028
3496
  }
3497
+ /**
3498
+ * Starts another workflow run and waits for its result.
3499
+ *
3500
+ * @see node_modules/@upstash/workflow/docs/steps/invoke.mdx
3501
+ */
3029
3502
  async invoke(stepName, settings) {
3030
3503
  validateLabel(settings.label);
3031
3504
  validateFlowControl(settings.flowControl);
@@ -3033,9 +3506,15 @@ var WorkflowContext = class {
3033
3506
  new LazyInvokeStep(this, stepName, settings)
3034
3507
  );
3035
3508
  }
3509
+ /**
3510
+ * @see node_modules/@upstash/workflow/docs/steps/createWebhook.mdx
3511
+ */
3036
3512
  async createWebhook(stepName) {
3037
3513
  return await this.addStep(new LazyCreateWebhookStep(this, stepName));
3038
3514
  }
3515
+ /**
3516
+ * @see node_modules/@upstash/workflow/docs/steps/waitForWebhook.mdx
3517
+ */
3039
3518
  async waitForWebhook(stepName, webhook, timeout) {
3040
3519
  return await this.addStep(new LazyWaitForWebhookStep(this, stepName, webhook, timeout));
3041
3520
  }
@@ -3044,6 +3523,8 @@ var WorkflowContext = class {
3044
3523
  *
3045
3524
  * Will throw WorkflowCancelAbort to stop workflow execution.
3046
3525
  * Shouldn't be inside try/catch.
3526
+ *
3527
+ * @see node_modules/@upstash/workflow/docs/steps/cancel.mdx
3047
3528
  */
3048
3529
  async cancel() {
3049
3530
  throw new WorkflowCancelAbort();
@@ -3062,6 +3543,11 @@ var WorkflowContext = class {
3062
3543
  throw error;
3063
3544
  }
3064
3545
  }
3546
+ /**
3547
+ * Calls OpenAI, Anthropic or Resend through QStash, like `context.call`.
3548
+ *
3549
+ * @see node_modules/@upstash/workflow/docs/steps/api.mdx
3550
+ */
3065
3551
  get api() {
3066
3552
  return new WorkflowApi({
3067
3553
  context: this
@@ -3100,7 +3586,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3100
3586
  *
3101
3587
  * @param routeFunction
3102
3588
  */
3103
- static async tryAuthentication(routeFunction, context) {
3589
+ static async tryAuthentication(routeFunction, context, effectiveConfig) {
3104
3590
  const disabledContext = new _DisabledWorkflowContext({
3105
3591
  qstashClient: new import_qstash10.Client({
3106
3592
  baseUrl: "disabled-client",
@@ -3115,7 +3601,10 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3115
3601
  initialPayload: context.requestPayload,
3116
3602
  env: context.env,
3117
3603
  label: context.labels,
3118
- retried: context.retried
3604
+ retried: context.retried,
3605
+ // the route function runs for real here until it reaches a step, so
3606
+ // it observes the same configuration as it will on the real context
3607
+ effectiveConfig
3119
3608
  });
3120
3609
  try {
3121
3610
  await routeFunction(disabledContext);
@@ -3332,6 +3821,7 @@ var handleFailure = async ({
3332
3821
  }
3333
3822
  const userHeaders = recreateUserHeaders(request.headers);
3334
3823
  const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
3824
+ const effectiveConfig = getEffectiveConfig(request.headers);
3335
3825
  const workflowContext = new WorkflowContext({
3336
3826
  qstashClient,
3337
3827
  workflowRunId,
@@ -3345,11 +3835,13 @@ var handleFailure = async ({
3345
3835
  label: userHeaders.get(WORKFLOW_LABEL_HEADER) ?? void 0,
3346
3836
  retried,
3347
3837
  workflowRunCreatedAt: workflowCreatedAt,
3348
- middlewareManager: void 0
3838
+ middlewareManager: void 0,
3839
+ effectiveConfig
3349
3840
  });
3350
3841
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3351
3842
  routeFunction,
3352
- workflowContext
3843
+ workflowContext,
3844
+ effectiveConfig
3353
3845
  );
3354
3846
  if (authCheck.isErr()) {
3355
3847
  await dispatchDebug?.("onError", {
@@ -3840,12 +4332,14 @@ var serveBase = (routeFunction, telemetry2, options, internalOptions) => {
3840
4332
  const label = request.headers.get(WORKFLOW_LABEL_HEADER) ?? void 0;
3841
4333
  const workflowRunCreatedAtHeader = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
3842
4334
  const workflowRunCreatedAt = workflowRunCreatedAtHeader ? Number(workflowRunCreatedAtHeader) : isFirstInvocation ? Date.now() : 0;
4335
+ const effectiveConfig = getEffectiveConfig(request.headers);
3843
4336
  const workflowContext = new WorkflowContext({
3844
4337
  qstashClient: regionalClient,
3845
4338
  workflowRunId,
3846
4339
  initialPayload: isThirdPartyCallResult(request) ? JSON.parse(rawInitialPayload) : initialPayloadParser(rawInitialPayload),
3847
4340
  headers: recreateUserHeaders(request.headers),
3848
4341
  steps,
4342
+ effectiveConfig,
3849
4343
  url: workflowUrl,
3850
4344
  env,
3851
4345
  telemetry: telemetry2,
@@ -3857,7 +4351,8 @@ var serveBase = (routeFunction, telemetry2, options, internalOptions) => {
3857
4351
  });
3858
4352
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3859
4353
  routeFunction,
3860
- workflowContext
4354
+ workflowContext,
4355
+ effectiveConfig
3861
4356
  );
3862
4357
  if (authCheck.isErr()) {
3863
4358
  throw authCheck.error;
@@ -3894,7 +4389,23 @@ var serveBase = (routeFunction, telemetry2, options, internalOptions) => {
3894
4389
  if (steps.length === 1) {
3895
4390
  await middlewareManager.dispatchLifecycle("runStarted", {});
3896
4391
  }
3897
- return await routeFunction(workflowContext);
4392
+ let outcome;
4393
+ try {
4394
+ outcome = { ran: true, result: await routeFunction(workflowContext) };
4395
+ } catch (error) {
4396
+ outcome = { ran: false, error };
4397
+ }
4398
+ const submitted = await flushPendingStep(workflowContext);
4399
+ if (submitted.isErr()) {
4400
+ throw submitted.error;
4401
+ }
4402
+ if (submitted.value.result === "submitted-step") {
4403
+ throw submitted.value.abort;
4404
+ }
4405
+ if (!outcome.ran) {
4406
+ throw outcome.error;
4407
+ }
4408
+ return outcome.result;
3898
4409
  },
3899
4410
  onCleanup: async (result2) => {
3900
4411
  await middlewareManager.dispatchLifecycle("runCompleted", {