@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/index.js CHANGED
@@ -304,6 +304,14 @@ var WORKFLOW_CREATED_AT_HEADER = "Upstash-Workflow-CreatedAt";
304
304
  var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
305
305
  var WORKFLOW_FAILURE_CALLBACK_HEADER = "Upstash-Workflow-Failure-Callback";
306
306
  var WORKFLOW_FEATURE_HEADER = "Upstash-Feature-Set";
307
+ var WORKFLOW_FEATURE_SET = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
308
+ var WORKFLOW_STEP_CONFIG_CALL_TYPE = "stepConfig";
309
+ var WORKFLOW_STEP_CONFIG_HEADER = "Upstash-Workflow-Step-Config";
310
+ var FLOW_CONTROL_KEY_HEADER = "Upstash-Flow-Control-Key";
311
+ var FLOW_CONTROL_VALUE_HEADER = "Upstash-Flow-Control-Value";
312
+ var RETRIES_HEADER = "Upstash-Retries";
313
+ var RETRY_DELAY_HEADER = "Upstash-Retry-Delay";
314
+ var WORKFLOW_STEP_CONFIG_FEATURE = "WF_StepConfig";
307
315
  var WORKFLOW_INVOKE_COUNT_HEADER = "Upstash-Workflow-Invoke-Count";
308
316
  var WORKFLOW_RETRIED_HEADER = "Upstash-Retried";
309
317
  var WORKFLOW_LABEL_HEADER = "Upstash-Label";
@@ -321,102 +329,6 @@ var TELEMETRY_HEADER_SDK = "Upstash-Telemetry-Sdk";
321
329
  var TELEMETRY_HEADER_FRAMEWORK = "Upstash-Telemetry-Framework";
322
330
  var TELEMETRY_HEADER_RUNTIME = "Upstash-Telemetry-Runtime";
323
331
 
324
- // src/context/auto-executor.ts
325
- var import_qstash5 = require("@upstash/qstash");
326
-
327
- // src/qstash/headers.ts
328
- var import_qstash4 = require("@upstash/qstash");
329
-
330
- // src/utils.ts
331
- var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
332
- var NANOID_LENGTH = 21;
333
- var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
334
- function validateLabel(label) {
335
- if (label === void 0) return;
336
- const labels = Array.isArray(label) ? label : [label];
337
- if (labels.length === 0) {
338
- throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
339
- }
340
- for (const value of labels) {
341
- if (!RESOURCE_NAME_PATTERN.test(value)) {
342
- throw new WorkflowNonRetryableError(
343
- `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
344
- );
345
- }
346
- }
347
- }
348
- function serializeLabel(label) {
349
- return Array.isArray(label) ? label.join(",") : label;
350
- }
351
- function validateFlowControl(flowControl) {
352
- if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
353
- throw new WorkflowNonRetryableError(
354
- `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
355
- );
356
- }
357
- }
358
- function getRandomInt() {
359
- return Math.floor(Math.random() * NANOID_CHARS.length);
360
- }
361
- function nanoid(length = NANOID_LENGTH) {
362
- return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
363
- }
364
- function getWorkflowRunId(id) {
365
- return `wfr_${id ?? nanoid()}`;
366
- }
367
- function decodeBase64(base64) {
368
- const binString = atob(base64);
369
- try {
370
- const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
371
- return new TextDecoder().decode(intArray);
372
- } catch (error) {
373
- console.warn(
374
- `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
375
- );
376
- return binString;
377
- }
378
- }
379
- function getUserIdFromToken(qstashClient) {
380
- try {
381
- const token = qstashClient.token;
382
- const decodedToken = decodeBase64(token);
383
- const tokenPayload = JSON.parse(decodedToken);
384
- const userId = tokenPayload.UserID;
385
- if (!userId) {
386
- throw new WorkflowError("QStash token payload does not contain userId");
387
- }
388
- return userId;
389
- } catch (error) {
390
- throw new WorkflowError(
391
- `Failed to decode QStash token while running create webhook step: ${error.message}`
392
- );
393
- }
394
- }
395
- function getQStashUrl(qstashClient) {
396
- try {
397
- const requester = qstashClient.http;
398
- const baseUrl = requester.baseUrl;
399
- if (!baseUrl) {
400
- throw new WorkflowError("QStash client does not have a baseUrl");
401
- }
402
- return baseUrl;
403
- } catch (error) {
404
- throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
405
- }
406
- }
407
- function getEventId() {
408
- return `evt_${nanoid(15)}`;
409
- }
410
- function stringifyBody(body) {
411
- if (body === void 0) {
412
- return void 0;
413
- }
414
- if (typeof body === "string") {
415
- return body;
416
- }
417
- return JSON.stringify(body);
418
- }
419
-
420
332
  // node_modules/neverthrow/dist/index.es.js
421
333
  var defaultErrorConfig = {
422
334
  withStackTrace: false
@@ -832,6 +744,102 @@ var Err = class {
832
744
  };
833
745
  var fromThrowable = Result.fromThrowable;
834
746
 
747
+ // src/context/auto-executor.ts
748
+ var import_qstash5 = require("@upstash/qstash");
749
+
750
+ // src/qstash/headers.ts
751
+ var import_qstash4 = require("@upstash/qstash");
752
+
753
+ // src/utils.ts
754
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
755
+ var NANOID_LENGTH = 21;
756
+ var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
757
+ function validateLabel(label) {
758
+ if (label === void 0) return;
759
+ const labels = Array.isArray(label) ? label : [label];
760
+ if (labels.length === 0) {
761
+ throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
762
+ }
763
+ for (const value of labels) {
764
+ if (!RESOURCE_NAME_PATTERN.test(value)) {
765
+ throw new WorkflowNonRetryableError(
766
+ `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
767
+ );
768
+ }
769
+ }
770
+ }
771
+ function serializeLabel(label) {
772
+ return Array.isArray(label) ? label.join(",") : label;
773
+ }
774
+ function validateFlowControl(flowControl) {
775
+ if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
776
+ throw new WorkflowNonRetryableError(
777
+ `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
778
+ );
779
+ }
780
+ }
781
+ function getRandomInt() {
782
+ return Math.floor(Math.random() * NANOID_CHARS.length);
783
+ }
784
+ function nanoid(length = NANOID_LENGTH) {
785
+ return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
786
+ }
787
+ function getWorkflowRunId(id) {
788
+ return `wfr_${id ?? nanoid()}`;
789
+ }
790
+ function decodeBase64(base64) {
791
+ const binString = atob(base64);
792
+ try {
793
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
794
+ return new TextDecoder().decode(intArray);
795
+ } catch (error) {
796
+ console.warn(
797
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
798
+ );
799
+ return binString;
800
+ }
801
+ }
802
+ function getUserIdFromToken(qstashClient) {
803
+ try {
804
+ const token = qstashClient.token;
805
+ const decodedToken = decodeBase64(token);
806
+ const tokenPayload = JSON.parse(decodedToken);
807
+ const userId = tokenPayload.UserID;
808
+ if (!userId) {
809
+ throw new WorkflowError("QStash token payload does not contain userId");
810
+ }
811
+ return userId;
812
+ } catch (error) {
813
+ throw new WorkflowError(
814
+ `Failed to decode QStash token while running create webhook step: ${error.message}`
815
+ );
816
+ }
817
+ }
818
+ function getQStashUrl(qstashClient) {
819
+ try {
820
+ const requester = qstashClient.http;
821
+ const baseUrl = requester.baseUrl;
822
+ if (!baseUrl) {
823
+ throw new WorkflowError("QStash client does not have a baseUrl");
824
+ }
825
+ return baseUrl;
826
+ } catch (error) {
827
+ throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
828
+ }
829
+ }
830
+ function getEventId() {
831
+ return `evt_${nanoid(15)}`;
832
+ }
833
+ function stringifyBody(body) {
834
+ if (body === void 0) {
835
+ return void 0;
836
+ }
837
+ if (typeof body === "string") {
838
+ return body;
839
+ }
840
+ return JSON.stringify(body);
841
+ }
842
+
835
843
  // src/types.ts
836
844
  var StepTypes = [
837
845
  "Initial",
@@ -941,6 +949,10 @@ var triggerFirstInvocation = async (params) => {
941
949
  return err(error_);
942
950
  }
943
951
  };
952
+ var flushPendingStep = async (workflowContext) => {
953
+ const { executor } = workflowContext;
954
+ return await executor.submitPendingStep();
955
+ };
944
956
  var triggerRouteFunction = async ({
945
957
  onCleanup,
946
958
  onStep,
@@ -1153,8 +1165,29 @@ If you want to disable QStash Verification, you should clear env variables QSTAS
1153
1165
  var BaseLazyStep = class _BaseLazyStep {
1154
1166
  stepName;
1155
1167
  context;
1156
- constructor(context, stepName) {
1168
+ /**
1169
+ * step-level settings (flow control, retries etc.) which override the
1170
+ * settings the workflow run was triggered with, for this step only.
1171
+ */
1172
+ stepSettings;
1173
+ /**
1174
+ * whether this step's result can be submitted after the route function
1175
+ * has moved on, instead of right away.
1176
+ *
1177
+ * Enabled for steps whose `getResultStep` produces the final `out` —
1178
+ * which is not the same as "needs no server round trip":
1179
+ * `LazyCreateWebhookStep` builds its result in `getBody` and returns
1180
+ * `out: undefined` from `getResultStep`, so deferring it would hand
1181
+ * `undefined` to the route function.
1182
+ *
1183
+ * Deferring lets the route function continue and reveal the next step,
1184
+ * so that step's settings can ride on this step's submission instead
1185
+ * of needing a step config request of their own.
1186
+ */
1187
+ supportsDeferredSubmission = false;
1188
+ constructor(context, stepName, stepSettings) {
1157
1189
  this.context = context;
1190
+ this.stepSettings = stepSettings;
1158
1191
  if (!stepName) {
1159
1192
  throw new WorkflowError(
1160
1193
  "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
@@ -1218,7 +1251,13 @@ var BaseLazyStep = class _BaseLazyStep {
1218
1251
  step.out = JSON.stringify(step.out);
1219
1252
  return JSON.stringify(step);
1220
1253
  }
1221
- getHeaders({ context, telemetry, invokeCount, step }) {
1254
+ getHeaders({
1255
+ context,
1256
+ telemetry,
1257
+ invokeCount,
1258
+ step,
1259
+ stepSettings
1260
+ }) {
1222
1261
  return getHeaders({
1223
1262
  initHeaderValue: "false",
1224
1263
  workflowConfig: {
@@ -1232,7 +1271,8 @@ var BaseLazyStep = class _BaseLazyStep {
1232
1271
  stepInfo: {
1233
1272
  step,
1234
1273
  lazyStep: this
1235
- }
1274
+ },
1275
+ stepSettings
1236
1276
  });
1237
1277
  }
1238
1278
  async submitStep({ context, body, headers }) {
@@ -1250,8 +1290,9 @@ var LazyFunctionStep = class extends BaseLazyStep {
1250
1290
  stepFunction;
1251
1291
  stepType = "Run";
1252
1292
  allowUndefinedOut = true;
1253
- constructor(context, stepName, stepFunction) {
1254
- super(context, stepName);
1293
+ supportsDeferredSubmission = true;
1294
+ constructor(context, stepName, stepFunction, stepSettings) {
1295
+ super(context, stepName, stepSettings);
1255
1296
  this.stepFunction = stepFunction;
1256
1297
  }
1257
1298
  getPlanStep(concurrent, targetStep) {
@@ -1281,6 +1322,7 @@ var LazySleepStep = class extends BaseLazyStep {
1281
1322
  sleep;
1282
1323
  stepType = "SleepFor";
1283
1324
  allowUndefinedOut = true;
1325
+ supportsDeferredSubmission = true;
1284
1326
  constructor(context, stepName, sleep) {
1285
1327
  super(context, stepName);
1286
1328
  this.sleep = sleep;
@@ -1320,6 +1362,7 @@ var LazySleepUntilStep = class extends BaseLazyStep {
1320
1362
  sleepUntil;
1321
1363
  stepType = "SleepUntil";
1322
1364
  allowUndefinedOut = true;
1365
+ supportsDeferredSubmission = true;
1323
1366
  constructor(context, stepName, sleepUntil) {
1324
1367
  super(context, stepName);
1325
1368
  this.sleepUntil = sleepUntil;
@@ -1821,6 +1864,7 @@ var WorkflowHeaders = class {
1821
1864
  invokeCount;
1822
1865
  initHeaderValue;
1823
1866
  stepInfo;
1867
+ stepSettings;
1824
1868
  headers;
1825
1869
  /**
1826
1870
  * @param params workflow header parameters
@@ -1830,17 +1874,20 @@ var WorkflowHeaders = class {
1830
1874
  workflowConfig,
1831
1875
  invokeCount,
1832
1876
  initHeaderValue,
1833
- stepInfo
1877
+ stepInfo,
1878
+ stepSettings
1834
1879
  }) {
1835
1880
  this.userHeaders = userHeaders;
1836
1881
  this.workflowConfig = workflowConfig;
1837
1882
  this.invokeCount = invokeCount;
1838
1883
  this.initHeaderValue = initHeaderValue;
1839
1884
  this.stepInfo = stepInfo;
1885
+ this.stepSettings = stepSettings;
1840
1886
  this.headers = {
1841
1887
  rawHeaders: {},
1842
1888
  workflowHeaders: {},
1843
- failureHeaders: {}
1889
+ failureHeaders: {},
1890
+ stepSettingsHeaders: {}
1844
1891
  };
1845
1892
  }
1846
1893
  getHeaders() {
@@ -1851,6 +1898,7 @@ var WorkflowHeaders = class {
1851
1898
  this.addUserHeaders();
1852
1899
  this.addInvokeCount();
1853
1900
  this.addFailureUrl();
1901
+ this.addStepSettings();
1854
1902
  const contentType = this.addContentType();
1855
1903
  return this.prefixHeaders(contentType);
1856
1904
  }
@@ -1860,7 +1908,7 @@ var WorkflowHeaders = class {
1860
1908
  [WORKFLOW_INIT_HEADER]: this.initHeaderValue,
1861
1909
  [WORKFLOW_ID_HEADER]: this.workflowConfig.workflowRunId,
1862
1910
  [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
1863
- [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig",
1911
+ [WORKFLOW_FEATURE_HEADER]: WORKFLOW_FEATURE_SET,
1864
1912
  [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1865
1913
  ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}
1866
1914
  };
@@ -1941,7 +1989,7 @@ var WorkflowHeaders = class {
1941
1989
  this.headers.failureHeaders["Workflow-Init"] = "false";
1942
1990
  this.headers.failureHeaders["Workflow-Url"] = this.workflowConfig.workflowUrl;
1943
1991
  this.headers.failureHeaders["Workflow-Calltype"] = "failureCall";
1944
- this.headers.failureHeaders["Feature-Set"] = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
1992
+ this.headers.failureHeaders["Feature-Set"] = WORKFLOW_FEATURE_SET;
1945
1993
  if (this.workflowConfig.retries !== void 0 && this.workflowConfig.retries !== DEFAULT_RETRIES) {
1946
1994
  this.headers.failureHeaders["Retries"] = this.workflowConfig.retries.toString();
1947
1995
  }
@@ -1949,6 +1997,42 @@ var WorkflowHeaders = class {
1949
1997
  this.headers.failureHeaders["Retry-Delay"] = this.workflowConfig.retryDelay.toString();
1950
1998
  }
1951
1999
  }
2000
+ /**
2001
+ * Applies the step-level settings of a step to the message.
2002
+ *
2003
+ * These headers configure the message itself, so that QStash uses them
2004
+ * instead of the settings the run was triggered with. The delivery of
2005
+ * the message is what executes the step, which is how a step's
2006
+ * settings reach it.
2007
+ *
2008
+ * When any setting is present the feature set is extended with
2009
+ * `WF_StepConfig`, which is what tells QStash to keep them. QStash
2010
+ * reports that back on the delivery as `Upstash-Workflow-Step-Config`.
2011
+ */
2012
+ addStepSettings() {
2013
+ if (!this.stepSettings) {
2014
+ return;
2015
+ }
2016
+ const headers = {};
2017
+ if (this.stepSettings.flowControl) {
2018
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
2019
+ this.stepSettings.flowControl
2020
+ );
2021
+ headers[FLOW_CONTROL_KEY_HEADER] = flowControlKey;
2022
+ headers[FLOW_CONTROL_VALUE_HEADER] = flowControlValue;
2023
+ }
2024
+ if (this.stepSettings.retries !== void 0) {
2025
+ headers[RETRIES_HEADER] = this.stepSettings.retries.toString();
2026
+ }
2027
+ if (this.stepSettings.retryDelay) {
2028
+ headers[RETRY_DELAY_HEADER] = this.stepSettings.retryDelay;
2029
+ }
2030
+ if (Object.keys(headers).length === 0) {
2031
+ return;
2032
+ }
2033
+ headers[WORKFLOW_FEATURE_HEADER] = `${WORKFLOW_FEATURE_SET},${WORKFLOW_STEP_CONFIG_FEATURE}`;
2034
+ this.headers.stepSettingsHeaders = headers;
2035
+ }
1952
2036
  addContentType() {
1953
2037
  if (this.workflowConfig.useJSONContent) {
1954
2038
  this.headers.rawHeaders["content-type"] = "application/json";
@@ -1962,14 +2046,17 @@ var WorkflowHeaders = class {
1962
2046
  return contentType;
1963
2047
  }
1964
2048
  prefixHeaders(contentType) {
1965
- const { rawHeaders, workflowHeaders, failureHeaders } = this.headers;
2049
+ const { rawHeaders, workflowHeaders, failureHeaders, stepSettingsHeaders } = this.headers;
1966
2050
  const isCall = this.stepInfo?.lazyStep.stepType === "Call";
1967
2051
  return {
1968
2052
  headers: {
1969
2053
  ...rawHeaders,
1970
2054
  ...addPrefixToHeaders(workflowHeaders, isCall ? "Upstash-Callback-" : "Upstash-"),
1971
2055
  ...addPrefixToHeaders(failureHeaders, "Upstash-Failure-Callback-"),
1972
- ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {}
2056
+ ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {},
2057
+ // last, so they override the run's settings above. Never
2058
+ // prefixed: they configure this message, not its callback.
2059
+ ...stepSettingsHeaders
1973
2060
  },
1974
2061
  contentType
1975
2062
  };
@@ -2020,7 +2107,7 @@ var submitParallelSteps = async ({
2020
2107
  info: `Submitting ${planSteps.length} parallel steps.`
2021
2108
  });
2022
2109
  const result = await context.qstashClient.batch(
2023
- planSteps.map((planStep) => {
2110
+ planSteps.map((planStep, index) => {
2024
2111
  const { headers } = getHeaders({
2025
2112
  initHeaderValue: "false",
2026
2113
  workflowConfig: {
@@ -2029,7 +2116,8 @@ var submitParallelSteps = async ({
2029
2116
  workflowRunCreatedAt: context.workflowRunCreatedAt,
2030
2117
  telemetry
2031
2118
  },
2032
- invokeCount
2119
+ invokeCount,
2120
+ stepSettings: steps[index].stepSettings
2033
2121
  });
2034
2122
  return {
2035
2123
  headers,
@@ -2048,31 +2136,38 @@ var submitParallelSteps = async ({
2048
2136
  }
2049
2137
  throw new WorkflowAbort(planSteps[0].stepName, planSteps[0]);
2050
2138
  };
2051
- var submitSingleStep = async ({
2052
- context,
2139
+ var executeStep = async ({
2053
2140
  lazyStep,
2054
2141
  stepId,
2055
- invokeCount,
2056
2142
  concurrency,
2057
- telemetry,
2058
- dispatchDebug,
2059
2143
  dispatchLifecycle
2060
2144
  }) => {
2061
2145
  await dispatchLifecycle("beforeExecution", {
2062
2146
  stepName: lazyStep.stepName
2063
2147
  });
2064
- let resultStep;
2065
2148
  try {
2066
- resultStep = await lazyStep.getResultStep(concurrency, stepId);
2149
+ return await lazyStep.getResultStep(concurrency, stepId);
2067
2150
  } catch (error) {
2068
2151
  attachStepNameToError(error, lazyStep.stepName);
2069
2152
  throw error;
2070
2153
  }
2154
+ };
2155
+ var submitStepResult = async ({
2156
+ context,
2157
+ lazyStep,
2158
+ resultStep,
2159
+ invokeCount,
2160
+ concurrency,
2161
+ telemetry,
2162
+ dispatchDebug,
2163
+ nextStepSettings
2164
+ }) => {
2071
2165
  const { headers } = lazyStep.getHeaders({
2072
2166
  context,
2073
2167
  step: resultStep,
2074
2168
  invokeCount,
2075
- telemetry
2169
+ telemetry,
2170
+ stepSettings: nextStepSettings
2076
2171
  });
2077
2172
  const body = lazyStep.getBody({
2078
2173
  context,
@@ -2097,6 +2192,154 @@ var submitSingleStep = async ({
2097
2192
  }
2098
2193
  return resultStep;
2099
2194
  };
2195
+ var publishStepConfigRequest = async ({
2196
+ context,
2197
+ lazyStep,
2198
+ targetStep,
2199
+ invokeCount,
2200
+ telemetry,
2201
+ dispatchDebug
2202
+ }) => {
2203
+ const { headers } = getHeaders({
2204
+ initHeaderValue: "false",
2205
+ workflowConfig: {
2206
+ workflowRunId: context.workflowRunId,
2207
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2208
+ workflowUrl: context.url,
2209
+ telemetry
2210
+ },
2211
+ invokeCount,
2212
+ stepSettings: lazyStep.stepSettings
2213
+ });
2214
+ await dispatchDebug("onInfo", {
2215
+ info: `Step "${lazyStep.stepName}" (${targetStep}) has step-level settings which the current delivery does not carry. Requesting a delivery which does.`
2216
+ });
2217
+ const result = await context.qstashClient.publishJSON({
2218
+ headers: {
2219
+ ...headers,
2220
+ "Upstash-Workflow-CallType": WORKFLOW_STEP_CONFIG_CALL_TYPE,
2221
+ "Upstash-Forward-Upstash-Workflow-StepId": targetStep.toString(),
2222
+ "Upstash-Forward-Upstash-Workflow-StepName": lazyStep.stepName
2223
+ },
2224
+ method: "POST",
2225
+ body: { targetStep, invokeCount },
2226
+ url: context.url,
2227
+ contentBasedDeduplication: true
2228
+ });
2229
+ if (result?.deduplicated) {
2230
+ await dispatchDebug("onWarning", {
2231
+ 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.`
2232
+ });
2233
+ } else if (result?.messageId) {
2234
+ await dispatchDebug("onInfo", {
2235
+ info: `Requested a delivery under the settings of step "${lazyStep.stepName}" with messageId: ${result.messageId}.`
2236
+ });
2237
+ }
2238
+ };
2239
+
2240
+ // src/qstash/step-config.ts
2241
+ var normalizeStepSettings = (settings) => {
2242
+ if (settings === void 0) {
2243
+ return void 0;
2244
+ }
2245
+ const { retries, retryDelay } = settings;
2246
+ if (retryDelay !== void 0 && typeof retryDelay !== "string") {
2247
+ throw new WorkflowNonRetryableError("Invalid step retryDelay: must be a string.");
2248
+ }
2249
+ if (retries !== void 0 && (!Number.isInteger(retries) || retries < 0)) {
2250
+ throw new WorkflowNonRetryableError("Invalid step retries: must be a non-negative integer.");
2251
+ }
2252
+ return { ...settings, retryDelay: retryDelay?.trim() || void 0 };
2253
+ };
2254
+ var DEFAULT_PARALLELISM = 0;
2255
+ var DEFAULT_RATE = 0;
2256
+ var DEFAULT_PERIOD_SECONDS = 1;
2257
+ var SECONDS_PER_UNIT = {
2258
+ s: 1,
2259
+ m: 60,
2260
+ h: 60 * 60,
2261
+ d: 24 * 60 * 60
2262
+ };
2263
+ var durationToSeconds = (duration) => {
2264
+ if (typeof duration === "number") {
2265
+ return Number.isFinite(duration) ? duration : void 0;
2266
+ }
2267
+ const match = /^(\d+)([smhd])$/.exec(duration.trim());
2268
+ if (match) {
2269
+ return Number(match[1]) * SECONDS_PER_UNIT[match[2]];
2270
+ }
2271
+ const seconds = Number(duration.trim());
2272
+ return Number.isFinite(seconds) ? seconds : void 0;
2273
+ };
2274
+ var normalizeFlowControl = (flowControl) => {
2275
+ const period = flowControl.period === void 0 ? void 0 : durationToSeconds(flowControl.period);
2276
+ return {
2277
+ key: flowControl.key,
2278
+ parallelism: flowControl.parallelism ?? DEFAULT_PARALLELISM,
2279
+ rate: flowControl.rate ?? flowControl.ratePerSecond ?? DEFAULT_RATE,
2280
+ period: period ?? DEFAULT_PERIOD_SECONDS
2281
+ };
2282
+ };
2283
+ var parseFlowControlHeaders = (key, value) => {
2284
+ if (!key) {
2285
+ return void 0;
2286
+ }
2287
+ const flowControl = {
2288
+ key,
2289
+ parallelism: DEFAULT_PARALLELISM,
2290
+ rate: DEFAULT_RATE,
2291
+ period: DEFAULT_PERIOD_SECONDS
2292
+ };
2293
+ for (const entry of (value ?? "").split(",")) {
2294
+ const [name, rawValue] = entry.split("=").map((part) => part.trim());
2295
+ if (!name || rawValue === void 0) {
2296
+ continue;
2297
+ }
2298
+ switch (name) {
2299
+ case "parallelism": {
2300
+ flowControl.parallelism = Number(rawValue);
2301
+ break;
2302
+ }
2303
+ case "rate": {
2304
+ flowControl.rate = Number(rawValue);
2305
+ break;
2306
+ }
2307
+ case "period": {
2308
+ flowControl.period = durationToSeconds(rawValue) ?? DEFAULT_PERIOD_SECONDS;
2309
+ break;
2310
+ }
2311
+ }
2312
+ }
2313
+ return flowControl;
2314
+ };
2315
+ var getEffectiveConfig = (headers) => {
2316
+ const retriesHeader = headers.get(RETRIES_HEADER);
2317
+ return {
2318
+ flowControl: parseFlowControlHeaders(
2319
+ headers.get(FLOW_CONTROL_KEY_HEADER),
2320
+ headers.get(FLOW_CONTROL_VALUE_HEADER)
2321
+ ),
2322
+ retries: retriesHeader === null ? void 0 : Number(retriesHeader),
2323
+ retryDelay: headers.get(RETRY_DELAY_HEADER) ?? void 0,
2324
+ hasStepConfig: headers.get(WORKFLOW_STEP_CONFIG_HEADER) === "true"
2325
+ };
2326
+ };
2327
+ var describeStepSettingsMismatch = (stepSettings, effectiveConfig) => {
2328
+ if (stepSettings.flowControl) {
2329
+ const wanted = normalizeFlowControl(stepSettings.flowControl);
2330
+ const applied = effectiveConfig.flowControl;
2331
+ if (!applied || applied.key !== wanted.key || applied.parallelism !== wanted.parallelism || applied.rate !== wanted.rate || applied.period !== wanted.period) {
2332
+ return `flow control: expected ${JSON.stringify(wanted)}, delivery has ${JSON.stringify(applied)}`;
2333
+ }
2334
+ }
2335
+ if (stepSettings.retries !== void 0 && effectiveConfig.retries !== void 0 && stepSettings.retries !== effectiveConfig.retries) {
2336
+ return `retries: expected ${stepSettings.retries}, delivery has ${effectiveConfig.retries}`;
2337
+ }
2338
+ if (stepSettings.retryDelay !== void 0 && stepSettings.retryDelay !== effectiveConfig.retryDelay) {
2339
+ return `retry delay: expected '${stepSettings.retryDelay}', delivery has '${effectiveConfig.retryDelay ?? ""}'`;
2340
+ }
2341
+ return void 0;
2342
+ };
2100
2343
 
2101
2344
  // src/context/auto-executor.ts
2102
2345
  var AutoExecutor = class _AutoExecutor {
@@ -2113,6 +2356,25 @@ var AutoExecutor = class _AutoExecutor {
2113
2356
  stepCount = 0;
2114
2357
  planStepCount = 0;
2115
2358
  executingStep = false;
2359
+ /**
2360
+ * an executed step whose result hasn't been submitted to QStash yet.
2361
+ *
2362
+ * Set when a step which can produce its result in-process executes. The
2363
+ * submission waits so that the route function can continue and reveal
2364
+ * what comes next: if that is a single step with step-level settings,
2365
+ * the settings ride on this submission and no step config request is
2366
+ * needed, since the delivery of the submission is what executes it.
2367
+ *
2368
+ * Flushed when the next step is reached (see `addStep`) or when the
2369
+ * route function ends (see `flushPendingStep` in `serve`).
2370
+ */
2371
+ pendingStep;
2372
+ /**
2373
+ * configuration QStash applied to the delivery being handled. A step
2374
+ * with step-level settings is settled by comparing its settings against
2375
+ * this.
2376
+ */
2377
+ effectiveConfig;
2116
2378
  /**
2117
2379
  * @param context workflow context
2118
2380
  * @param steps list of steps
@@ -2120,14 +2382,17 @@ var AutoExecutor = class _AutoExecutor {
2120
2382
  * @param dispatchLifecycle lifecycle event dispatcher
2121
2383
  * @param telemetry optional telemetry information
2122
2384
  * @param invokeCount optional invoke count
2385
+ * @param effectiveConfig configuration QStash applied to the delivery
2386
+ * being handled
2123
2387
  */
2124
- constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry, invokeCount) {
2388
+ constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry, invokeCount, effectiveConfig) {
2125
2389
  this.context = context;
2126
2390
  this.steps = steps;
2127
2391
  this.dispatchDebug = dispatchDebug;
2128
2392
  this.dispatchLifecycle = dispatchLifecycle;
2129
2393
  this.telemetry = telemetry;
2130
2394
  this.invokeCount = invokeCount ?? 0;
2395
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2131
2396
  this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
2132
2397
  }
2133
2398
  /**
@@ -2162,6 +2427,15 @@ var AutoExecutor = class _AutoExecutor {
2162
2427
  lazyStepList.push(stepInfo);
2163
2428
  const index = this.indexInCurrentList++;
2164
2429
  const requestComplete = this.deferExecution().then(async () => {
2430
+ const submitted = await this.submitPendingStep(
2431
+ lazyStepList.length === 1 ? lazyStepList[0].stepSettings : void 0
2432
+ );
2433
+ if (submitted.isErr()) {
2434
+ throw submitted.error;
2435
+ }
2436
+ if (submitted.value.result === "submitted-step") {
2437
+ throw submitted.value.abort;
2438
+ }
2165
2439
  if (!this.promises.has(lazyStepList)) {
2166
2440
  const promise2 = this.getExecutionPromise(lazyStepList);
2167
2441
  this.promises.set(lazyStepList, promise2);
@@ -2215,18 +2489,108 @@ var AutoExecutor = class _AutoExecutor {
2215
2489
  }
2216
2490
  return parsedOut;
2217
2491
  }
2218
- const resultStep = await submitSingleStep({
2219
- context: this.context,
2492
+ const mismatch = lazyStep.stepSettings ? describeStepSettingsMismatch(lazyStep.stepSettings, this.effectiveConfig) : void 0;
2493
+ if (mismatch) {
2494
+ if (!this.effectiveConfig.hasStepConfig) {
2495
+ await publishStepConfigRequest({
2496
+ context: this.context,
2497
+ lazyStep,
2498
+ targetStep: this.stepCount,
2499
+ invokeCount: this.invokeCount,
2500
+ telemetry: this.telemetry,
2501
+ dispatchDebug: this.dispatchDebug
2502
+ });
2503
+ throw new WorkflowAbort(lazyStep.stepName);
2504
+ } else {
2505
+ await this.dispatchDebug("onWarning", {
2506
+ 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.`
2507
+ });
2508
+ }
2509
+ }
2510
+ const resultStep = await executeStep({
2220
2511
  lazyStep,
2221
2512
  stepId: this.stepCount,
2513
+ concurrency: NO_CONCURRENCY,
2514
+ dispatchLifecycle: this.dispatchLifecycle
2515
+ });
2516
+ if (lazyStep.supportsDeferredSubmission) {
2517
+ const serializedOut = JSON.stringify(resultStep.out);
2518
+ this.pendingStep = {
2519
+ status: "held",
2520
+ lazyStep,
2521
+ resultStep: {
2522
+ ...resultStep,
2523
+ out: serializedOut === void 0 ? void 0 : JSON.parse(serializedOut)
2524
+ }
2525
+ };
2526
+ return lazyStep.parseOut({
2527
+ ...resultStep,
2528
+ out: serializedOut
2529
+ });
2530
+ }
2531
+ await submitStepResult({
2532
+ context: this.context,
2533
+ lazyStep,
2534
+ resultStep,
2222
2535
  invokeCount: this.invokeCount,
2223
- concurrency: 1,
2536
+ concurrency: NO_CONCURRENCY,
2224
2537
  telemetry: this.telemetry,
2225
- dispatchDebug: this.dispatchDebug,
2226
- dispatchLifecycle: this.dispatchLifecycle
2538
+ dispatchDebug: this.dispatchDebug
2227
2539
  });
2228
2540
  throw new WorkflowAbort(lazyStep.stepName, resultStep);
2229
2541
  }
2542
+ /**
2543
+ * Submits the result of the step being held, if there is one, and
2544
+ * returns the abort the caller has to throw to end the invocation.
2545
+ *
2546
+ * Returns undefined when no step is being held, which is the caller's
2547
+ * signal that there is nothing to end. Throws instead of returning
2548
+ * when the submission itself fails, so that error reaches the caller
2549
+ * rather than an abort claiming the step was submitted.
2550
+ *
2551
+ * Callers which arrive while a submission is already under way (the
2552
+ * steps of a parallel group, added together) wait for that one and get
2553
+ * the same abort, rather than submitting a second time.
2554
+ *
2555
+ * The next step's settings are attached whenever it has any, without
2556
+ * checking them against the current delivery: the executor only knows
2557
+ * the configuration of the delivery in hand, which inside a
2558
+ * delivery is the *previous* step's, so such a check would be wrong
2559
+ * exactly when two steps with settings follow each other.
2560
+ *
2561
+ * @param nextStepSettings step-level settings of the next step
2562
+ * @returns `submitted-step` with the abort which ends this invocation,
2563
+ * or `no-pending-step` when nothing was held and there is nothing to
2564
+ * end
2565
+ */
2566
+ async submitPendingStep(nextStepSettings) {
2567
+ if (!this.pendingStep) {
2568
+ return ok({ result: "no-pending-step" });
2569
+ }
2570
+ try {
2571
+ if (this.pendingStep.status === "submitting") {
2572
+ return ok({ result: "submitted-step", abort: await this.pendingStep.submitted });
2573
+ }
2574
+ const { lazyStep, resultStep } = this.pendingStep;
2575
+ const submitted = (async () => {
2576
+ await submitStepResult({
2577
+ context: this.context,
2578
+ lazyStep,
2579
+ resultStep,
2580
+ invokeCount: this.invokeCount,
2581
+ concurrency: NO_CONCURRENCY,
2582
+ telemetry: this.telemetry,
2583
+ dispatchDebug: this.dispatchDebug,
2584
+ nextStepSettings
2585
+ });
2586
+ return new WorkflowAbort(lazyStep.stepName, resultStep);
2587
+ })();
2588
+ this.pendingStep = { status: "submitting", submitted };
2589
+ return ok({ result: "submitted-step", abort: await submitted });
2590
+ } catch (error) {
2591
+ return err(error);
2592
+ }
2593
+ }
2230
2594
  /**
2231
2595
  * Runs steps in parallel.
2232
2596
  *
@@ -2275,15 +2639,20 @@ var AutoExecutor = class _AutoExecutor {
2275
2639
  validateStep(parallelSteps[stepIndex], planStep);
2276
2640
  try {
2277
2641
  const parallelStep = parallelSteps[stepIndex];
2278
- const resultStep = await submitSingleStep({
2279
- context: this.context,
2642
+ const resultStep = await executeStep({
2280
2643
  lazyStep: parallelStep,
2281
2644
  stepId: planStep.targetStep,
2645
+ concurrency: parallelSteps.length,
2646
+ dispatchLifecycle: this.dispatchLifecycle
2647
+ });
2648
+ await submitStepResult({
2649
+ context: this.context,
2650
+ lazyStep: parallelStep,
2651
+ resultStep,
2282
2652
  invokeCount: this.invokeCount,
2283
2653
  concurrency: parallelSteps.length,
2284
2654
  telemetry: this.telemetry,
2285
- dispatchDebug: this.dispatchDebug,
2286
- dispatchLifecycle: this.dispatchLifecycle
2655
+ dispatchDebug: this.dispatchDebug
2287
2656
  });
2288
2657
  throw new WorkflowAbort(parallelStep.stepName, resultStep);
2289
2658
  } catch (error) {
@@ -2501,6 +2870,11 @@ var BaseWorkflowApi = class {
2501
2870
 
2502
2871
  // src/context/api/anthropic.ts
2503
2872
  var AnthropicAPI = class extends BaseWorkflowApi {
2873
+ /**
2874
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2875
+ *
2876
+ * @see node_modules/@upstash/workflow/docs/integrations/anthropic.mdx
2877
+ */
2504
2878
  async call(stepName, settings) {
2505
2879
  const { token, operation, ...parameters } = settings;
2506
2880
  return await this.callApi(stepName, {
@@ -2516,6 +2890,11 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2516
2890
  // src/context/api/openai.ts
2517
2891
  var import_qstash7 = require("@upstash/qstash");
2518
2892
  var OpenAIAPI = class extends BaseWorkflowApi {
2893
+ /**
2894
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2895
+ *
2896
+ * @see node_modules/@upstash/workflow/docs/integrations/openai.mdx
2897
+ */
2519
2898
  async call(stepName, settings) {
2520
2899
  const { token, organization, operation, baseURL, ...parameters } = settings;
2521
2900
  const useOpenAI = baseURL === void 0;
@@ -2533,6 +2912,11 @@ var OpenAIAPI = class extends BaseWorkflowApi {
2533
2912
  // src/context/api/resend.ts
2534
2913
  var import_qstash8 = require("@upstash/qstash");
2535
2914
  var ResendAPI = class extends BaseWorkflowApi {
2915
+ /**
2916
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2917
+ *
2918
+ * @see node_modules/@upstash/workflow/docs/integrations/resend.mdx
2919
+ */
2536
2920
  async call(stepName, settings) {
2537
2921
  const { token, batch = false, ...parameters } = settings;
2538
2922
  return await this.callApi(stepName, {
@@ -2707,8 +3091,9 @@ var WorkflowContext = class {
2707
3091
  *
2708
3092
  * ```ts
2709
3093
  * import { Client } from "@upstash/qstash"
3094
+ * import { serve } from "@upstash/workflow/nextjs"
2710
3095
  *
2711
- * export const POST = serve(
3096
+ * export const { POST } = serve(
2712
3097
  * async (context) => {
2713
3098
  * ...
2714
3099
  * },
@@ -2733,7 +3118,7 @@ var WorkflowContext = class {
2733
3118
  * Can be overwritten by passing a `url` parameter in `serve`:
2734
3119
  *
2735
3120
  * ```ts
2736
- * export const POST = serve(
3121
+ * export const { POST } = serve(
2737
3122
  * async (context) => {
2738
3123
  * ...
2739
3124
  * },
@@ -2751,7 +3136,7 @@ var WorkflowContext = class {
2751
3136
  *
2752
3137
  * ```ts
2753
3138
  * // set requestPayload type to MyPayload:
2754
- * export const POST = serve<MyPayload>(
3139
+ * export const { POST } = serve<MyPayload>(
2755
3140
  * async (context) => {
2756
3141
  * ...
2757
3142
  * }
@@ -2763,7 +3148,7 @@ var WorkflowContext = class {
2763
3148
  * the `initialPayloadParser` parameter:
2764
3149
  *
2765
3150
  * ```ts
2766
- * export const POST = serve<MyPayload>(
3151
+ * export const { POST } = serve<MyPayload>(
2767
3152
  * async (context) => {
2768
3153
  * ...
2769
3154
  * },
@@ -2772,6 +3157,13 @@ var WorkflowContext = class {
2772
3157
  * }
2773
3158
  * )
2774
3159
  * ```
3160
+ *
3161
+ * When a `context.call` response comes back, the route runs up to its first step with this
3162
+ * set to the call-result envelope (and `workflowRunId` set to a random id) before the SDK
3163
+ * recognizes the request. Code before the first step must not dereference, validate or
3164
+ * return early on the payload; read it inside `context.run`.
3165
+ *
3166
+ * @see node_modules/@upstash/workflow/docs/basics/serve/advanced.mdx
2775
3167
  */
2776
3168
  requestPayload;
2777
3169
  /**
@@ -2784,7 +3176,7 @@ var WorkflowContext = class {
2784
3176
  * Can be set using the `env` option of serve:
2785
3177
  *
2786
3178
  * ```ts
2787
- * export const POST = serve<MyPayload>(
3179
+ * export const { POST } = serve<MyPayload>(
2788
3180
  * async (context) => {
2789
3181
  * const key = context.env["API_KEY"];
2790
3182
  * },
@@ -2832,6 +3224,46 @@ var WorkflowContext = class {
2832
3224
  * `1` on the first retry, `2` on the second, and so on.
2833
3225
  */
2834
3226
  retried;
3227
+ /**
3228
+ * Configuration QStash applied to the request being handled.
3229
+ *
3230
+ * This is the configuration of *this delivery*, not of the run: it is
3231
+ * the configuration the run was triggered with, except inside the
3232
+ * delivery which executes a step that has step-level settings, where
3233
+ * it is that step's settings. The fields below expose it; the executor
3234
+ * gets it directly rather than reaching through the context.
3235
+ */
3236
+ effectiveConfig;
3237
+ /**
3238
+ * Flow control QStash applied to the request being handled, if any.
3239
+ *
3240
+ * This is the flow control of the request in hand, which is the one the
3241
+ * run was triggered with except inside a step carrying its own.
3242
+ */
3243
+ get flowControl() {
3244
+ return this.effectiveConfig.flowControl;
3245
+ }
3246
+ /**
3247
+ * Retry limit QStash applied to the request being handled, if it
3248
+ * reported one.
3249
+ *
3250
+ * Not to be confused with {@link retried}, which is how many retries
3251
+ * have already happened.
3252
+ *
3253
+ * @see {@link flowControl} for what "the request being handled" means
3254
+ */
3255
+ get retries() {
3256
+ return this.effectiveConfig.retries;
3257
+ }
3258
+ /**
3259
+ * Retry delay expression QStash applied to the request being handled,
3260
+ * if any.
3261
+ *
3262
+ * @see {@link flowControl} for what "the request being handled" means
3263
+ */
3264
+ get retryDelay() {
3265
+ return this.effectiveConfig.retryDelay;
3266
+ }
2835
3267
  constructor({
2836
3268
  qstashClient,
2837
3269
  workflowRunId,
@@ -2845,7 +3277,8 @@ var WorkflowContext = class {
2845
3277
  invokeCount,
2846
3278
  label,
2847
3279
  retried,
2848
- middlewareManager
3280
+ middlewareManager,
3281
+ effectiveConfig
2849
3282
  }) {
2850
3283
  this.qstashClient = qstashClient;
2851
3284
  this.workflowRunId = workflowRunId;
@@ -2857,6 +3290,7 @@ var WorkflowContext = class {
2857
3290
  this.env = env ?? {};
2858
3291
  this.labels = label === void 0 ? [] : Array.isArray(label) ? label : label ? label.split(",") : [];
2859
3292
  this.retried = retried ?? 0;
3293
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2860
3294
  const middlewareManagerInstance = middlewareManager ?? new MiddlewareManager([]);
2861
3295
  middlewareManagerInstance.assignContext(this);
2862
3296
  this.executor = new AutoExecutor(
@@ -2865,7 +3299,8 @@ var WorkflowContext = class {
2865
3299
  middlewareManagerInstance.dispatchDebug.bind(middlewareManagerInstance),
2866
3300
  middlewareManagerInstance.dispatchLifecycle.bind(middlewareManagerInstance),
2867
3301
  telemetry,
2868
- invokeCount
3302
+ invokeCount,
3303
+ this.effectiveConfig
2869
3304
  );
2870
3305
  }
2871
3306
  /**
@@ -2891,13 +3326,41 @@ var WorkflowContext = class {
2891
3326
  * ])
2892
3327
  * ```
2893
3328
  *
3329
+ * Step-level settings can be passed as a third argument, overriding
3330
+ * the settings the workflow run was triggered with for this step only:
3331
+ *
3332
+ * ```typescript
3333
+ * const result = await context.run(
3334
+ * "step 1",
3335
+ * () => {
3336
+ * return "result"
3337
+ * },
3338
+ * {
3339
+ * flowControl: { key: "custom-key", parallelism: 3 },
3340
+ * retries: 5,
3341
+ * }
3342
+ * )
3343
+ * ```
3344
+ *
3345
+ * Do not wrap steps in try/catch or `.catch` without rethrowing `WorkflowAbort`: each step
3346
+ * throws it to end the request. To stop retrying a failed step, throw
3347
+ * `WorkflowNonRetryableError`.
3348
+ *
2894
3349
  * @param stepName name of the step
2895
3350
  * @param stepFunction step function to be executed
3351
+ * @param stepSettings step-level settings for this step
2896
3352
  * @returns result of the step function
3353
+ * @see node_modules/@upstash/workflow/docs/steps/run.mdx
2897
3354
  */
2898
- async run(stepName, stepFunction) {
3355
+ async run(stepName, stepFunction, stepSettings) {
3356
+ const normalizedSettings = normalizeStepSettings(stepSettings);
3357
+ if (stepSettings) {
3358
+ validateFlowControl(stepSettings.flowControl);
3359
+ }
2899
3360
  const wrappedStepFunction = (() => this.executor.wrapStep(stepName, stepFunction));
2900
- return await this.addStep(new LazyFunctionStep(this, stepName, wrappedStepFunction));
3361
+ return await this.addStep(
3362
+ new LazyFunctionStep(this, stepName, wrappedStepFunction, normalizedSettings)
3363
+ );
2901
3364
  }
2902
3365
  /**
2903
3366
  * Stops the execution for the duration provided.
@@ -2907,8 +3370,9 @@ var WorkflowContext = class {
2907
3370
  * ```
2908
3371
  *
2909
3372
  * @param stepName
2910
- * @param duration sleep duration in seconds
3373
+ * @param duration sleep duration in seconds, or a duration string such as "10m"
2911
3374
  * @returns undefined
3375
+ * @see node_modules/@upstash/workflow/docs/steps/sleep.mdx
2912
3376
  */
2913
3377
  async sleep(stepName, duration) {
2914
3378
  await this.addStep(new LazySleepStep(this, stepName, duration));
@@ -2922,8 +3386,11 @@ var WorkflowContext = class {
2922
3386
  *
2923
3387
  * @param stepName
2924
3388
  * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
2925
- * as a Date object or a string (passed to `new Date(datetimeString)`)
3389
+ * as a Date object or a string (passed to `new Date(datetimeString)`).
3390
+ * A millisecond timestamp such as `Date.now()` is too far in the future, so QStash
3391
+ * rejects the step and the run fails. Pass `new Date(ms)` instead.
2926
3392
  * @returns undefined
3393
+ * @see node_modules/@upstash/workflow/docs/steps/sleepUntil.mdx
2927
3394
  */
2928
3395
  async sleepUntil(stepName, datetime) {
2929
3396
  let time;
@@ -2974,7 +3441,7 @@ var WorkflowContext = class {
2974
3441
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
2975
3442
  *
2976
3443
  *```ts
2977
- * const result = await workflow.waitForEvent("payment-confirmed", "payment.confirmed", {
3444
+ * const result = await context.waitForEvent("payment-confirmed", "payment.confirmed", {
2978
3445
  * timeout: "5m"
2979
3446
  * });
2980
3447
  *```
@@ -2998,11 +3465,14 @@ var WorkflowContext = class {
2998
3465
  * Alternatively, you can use the `context.notify` method.
2999
3466
  *
3000
3467
  * @param stepName
3001
- * @param eventId - Unique identifier for the event to wait for
3468
+ * @param eventId - Unique identifier for the event to wait for. Only letters, digits,
3469
+ * "-", "_" and "." are allowed. QStash rejects other characters, such as ":", which
3470
+ * stops the run with only a "Tried to append to a cancelled workflow" warning.
3002
3471
  * @param options - Configuration options.
3003
3472
  * @returns `{ timeout: boolean, eventData: TEventData }`.
3004
3473
  * The `timeout` property specifies if the workflow has timed out. The `eventData`
3005
3474
  * is the data passed when notifying this workflow of an event.
3475
+ * @see node_modules/@upstash/workflow/docs/steps/waitForEvent.mdx
3006
3476
  */
3007
3477
  async waitForEvent(stepName, eventId, options = {}) {
3008
3478
  const { timeout = "7d" } = options;
@@ -3024,28 +3494,31 @@ var WorkflowContext = class {
3024
3494
  * will receive the given event data and resume execution.
3025
3495
  *
3026
3496
  * The response includes the same eventId and eventData. Additionally, there is
3027
- * a notifyResponse field which contains a list of `Waiter` objects, each corresponding
3028
- * to a notified workflow run.
3029
- *
3030
- * Optionally, you can pass a workflowRunId to enable lookback functionality:
3031
- *
3032
- * ```ts
3033
- * const { eventId, eventData, notifyResponse } = await context.notify(
3034
- * "notify step", "event-id", "event-data", "wfr_123"
3035
- * );
3036
- * ```
3497
+ * a notifyResponse field which contains a list of `NotifyResponse` objects, each corresponding
3498
+ * to a notified workflow run. The notified `Waiter` is under `notifyResponse[i].waiter`.
3037
3499
  *
3038
3500
  * @param stepName
3039
- * @param eventId event id to notify
3501
+ * @param eventId event id to notify. Only letters, digits, "-", "_" and "." are allowed.
3502
+ * QStash rejects other characters, such as ":", which stops the run with only a
3503
+ * "Tried to append to a cancelled workflow" warning.
3040
3504
  * @param eventData event data to notify with
3041
- * @param workflowRunId optional workflow run id for lookback support
3042
- * @returns notify response which has event id, event data and list of waiters which were notified
3505
+ * @param workflowRunId optional workflow run id for lookback: the event is kept for the run
3506
+ * even if it has not reached `waitForEvent` yet
3507
+ * @returns notify response which has event id, event data and list of waiters which were
3508
+ * notified. With `workflowRunId`, QStash returns `notifyResponse` as a single object instead
3509
+ * of an array, despite the type.
3510
+ * @see node_modules/@upstash/workflow/docs/steps/notify.mdx
3043
3511
  */
3044
3512
  async notify(stepName, eventId, eventData, workflowRunId) {
3045
3513
  return await this.addStep(
3046
3514
  new LazyNotifyStep(this, stepName, eventId, eventData, this.qstashClient.http, workflowRunId)
3047
3515
  );
3048
3516
  }
3517
+ /**
3518
+ * Starts another workflow run and waits for its result.
3519
+ *
3520
+ * @see node_modules/@upstash/workflow/docs/steps/invoke.mdx
3521
+ */
3049
3522
  async invoke(stepName, settings) {
3050
3523
  validateLabel(settings.label);
3051
3524
  validateFlowControl(settings.flowControl);
@@ -3053,9 +3526,15 @@ var WorkflowContext = class {
3053
3526
  new LazyInvokeStep(this, stepName, settings)
3054
3527
  );
3055
3528
  }
3529
+ /**
3530
+ * @see node_modules/@upstash/workflow/docs/steps/createWebhook.mdx
3531
+ */
3056
3532
  async createWebhook(stepName) {
3057
3533
  return await this.addStep(new LazyCreateWebhookStep(this, stepName));
3058
3534
  }
3535
+ /**
3536
+ * @see node_modules/@upstash/workflow/docs/steps/waitForWebhook.mdx
3537
+ */
3059
3538
  async waitForWebhook(stepName, webhook, timeout) {
3060
3539
  return await this.addStep(new LazyWaitForWebhookStep(this, stepName, webhook, timeout));
3061
3540
  }
@@ -3064,6 +3543,8 @@ var WorkflowContext = class {
3064
3543
  *
3065
3544
  * Will throw WorkflowCancelAbort to stop workflow execution.
3066
3545
  * Shouldn't be inside try/catch.
3546
+ *
3547
+ * @see node_modules/@upstash/workflow/docs/steps/cancel.mdx
3067
3548
  */
3068
3549
  async cancel() {
3069
3550
  throw new WorkflowCancelAbort();
@@ -3082,6 +3563,11 @@ var WorkflowContext = class {
3082
3563
  throw error;
3083
3564
  }
3084
3565
  }
3566
+ /**
3567
+ * Calls OpenAI, Anthropic or Resend through QStash, like `context.call`.
3568
+ *
3569
+ * @see node_modules/@upstash/workflow/docs/steps/api.mdx
3570
+ */
3085
3571
  get api() {
3086
3572
  return new WorkflowApi({
3087
3573
  context: this
@@ -3120,7 +3606,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3120
3606
  *
3121
3607
  * @param routeFunction
3122
3608
  */
3123
- static async tryAuthentication(routeFunction, context) {
3609
+ static async tryAuthentication(routeFunction, context, effectiveConfig) {
3124
3610
  const disabledContext = new _DisabledWorkflowContext({
3125
3611
  qstashClient: new import_qstash10.Client({
3126
3612
  baseUrl: "disabled-client",
@@ -3135,7 +3621,10 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3135
3621
  initialPayload: context.requestPayload,
3136
3622
  env: context.env,
3137
3623
  label: context.labels,
3138
- retried: context.retried
3624
+ retried: context.retried,
3625
+ // the route function runs for real here until it reaches a step, so
3626
+ // it observes the same configuration as it will on the real context
3627
+ effectiveConfig
3139
3628
  });
3140
3629
  try {
3141
3630
  await routeFunction(disabledContext);
@@ -3352,6 +3841,7 @@ var handleFailure = async ({
3352
3841
  }
3353
3842
  const userHeaders = recreateUserHeaders(request.headers);
3354
3843
  const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
3844
+ const effectiveConfig = getEffectiveConfig(request.headers);
3355
3845
  const workflowContext = new WorkflowContext({
3356
3846
  qstashClient,
3357
3847
  workflowRunId,
@@ -3365,11 +3855,13 @@ var handleFailure = async ({
3365
3855
  label: userHeaders.get(WORKFLOW_LABEL_HEADER) ?? void 0,
3366
3856
  retried,
3367
3857
  workflowRunCreatedAt: workflowCreatedAt,
3368
- middlewareManager: void 0
3858
+ middlewareManager: void 0,
3859
+ effectiveConfig
3369
3860
  });
3370
3861
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3371
3862
  routeFunction,
3372
- workflowContext
3863
+ workflowContext,
3864
+ effectiveConfig
3373
3865
  );
3374
3866
  if (authCheck.isErr()) {
3375
3867
  await dispatchDebug?.("onError", {
@@ -3860,12 +4352,14 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3860
4352
  const label = request.headers.get(WORKFLOW_LABEL_HEADER) ?? void 0;
3861
4353
  const workflowRunCreatedAtHeader = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
3862
4354
  const workflowRunCreatedAt = workflowRunCreatedAtHeader ? Number(workflowRunCreatedAtHeader) : isFirstInvocation ? Date.now() : 0;
4355
+ const effectiveConfig = getEffectiveConfig(request.headers);
3863
4356
  const workflowContext = new WorkflowContext({
3864
4357
  qstashClient: regionalClient,
3865
4358
  workflowRunId,
3866
4359
  initialPayload: isThirdPartyCallResult(request) ? JSON.parse(rawInitialPayload) : initialPayloadParser(rawInitialPayload),
3867
4360
  headers: recreateUserHeaders(request.headers),
3868
4361
  steps,
4362
+ effectiveConfig,
3869
4363
  url: workflowUrl,
3870
4364
  env,
3871
4365
  telemetry,
@@ -3877,7 +4371,8 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3877
4371
  });
3878
4372
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3879
4373
  routeFunction,
3880
- workflowContext
4374
+ workflowContext,
4375
+ effectiveConfig
3881
4376
  );
3882
4377
  if (authCheck.isErr()) {
3883
4378
  throw authCheck.error;
@@ -3914,7 +4409,23 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3914
4409
  if (steps.length === 1) {
3915
4410
  await middlewareManager.dispatchLifecycle("runStarted", {});
3916
4411
  }
3917
- return await routeFunction(workflowContext);
4412
+ let outcome;
4413
+ try {
4414
+ outcome = { ran: true, result: await routeFunction(workflowContext) };
4415
+ } catch (error) {
4416
+ outcome = { ran: false, error };
4417
+ }
4418
+ const submitted = await flushPendingStep(workflowContext);
4419
+ if (submitted.isErr()) {
4420
+ throw submitted.error;
4421
+ }
4422
+ if (submitted.value.result === "submitted-step") {
4423
+ throw submitted.value.abort;
4424
+ }
4425
+ if (!outcome.ran) {
4426
+ throw outcome.error;
4427
+ }
4428
+ return outcome.result;
3918
4429
  },
3919
4430
  onCleanup: async (result2) => {
3920
4431
  await middlewareManager.dispatchLifecycle("runCompleted", {
@@ -4042,6 +4553,7 @@ var DLQ = class {
4042
4553
  * - `workflowCreatedAt`: Filter items by workflow creation time.
4043
4554
  * - `failureFunctionState`: Filter items by failure callback state.
4044
4555
  * - `label`: Filter items by label.
4556
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/list.mdx
4045
4557
  */
4046
4558
  async list(parameters) {
4047
4559
  const { cursor, count, filter } = parameters || {};
@@ -4118,6 +4630,7 @@ var DLQ = class {
4118
4630
  *
4119
4631
  * @param dlqId - The ID of the DLQ message to retry
4120
4632
  * @returns response with workflow run information
4633
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/callback.mdx
4121
4634
  */
4122
4635
  async retryFailureFunction({ dlqId }) {
4123
4636
  assertNonEmptyId(dlqId, "DLQ id");
@@ -4167,6 +4680,7 @@ var DLQ = class {
4167
4680
  * cursor = result.cursor;
4168
4681
  * } while (cursor);
4169
4682
  * ```
4683
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/delete.mdx
4170
4684
  */
4171
4685
  async delete(request) {
4172
4686
  if (typeof request === "string" || Array.isArray(request)) {
@@ -4227,19 +4741,14 @@ var Client4 = class {
4227
4741
  * });
4228
4742
  * ```
4229
4743
  *
4230
- * Optionally, you can pass a workflowRunId to enable lookback functionality:
4231
- *
4232
- * ```ts
4233
- * await client.notify({
4234
- * eventId: "my-event-id",
4235
- * eventData: "my-data",
4236
- * workflowRunId: "wfr_123" // enables lookback
4237
- * });
4238
- * ```
4239
- *
4240
- * @param eventId event id to notify
4744
+ * @param eventId event id to notify. Only letters, digits, "-", "_" and "." are allowed;
4745
+ * QStash rejects other characters, such as ":".
4241
4746
  * @param eventData data to provide to the workflow
4242
- * @param workflowRunId optional workflow run id for lookback support
4747
+ * @param workflowRunId optional workflow run id for lookback: the event is kept for the run
4748
+ * even if it has not reached `waitForEvent` yet
4749
+ * @returns the notified waiters. With `workflowRunId`, QStash returns a single object
4750
+ * instead of an array, despite the type.
4751
+ * @see node_modules/@upstash/workflow/docs/basics/client/notify.mdx
4243
4752
  */
4244
4753
  async notify({
4245
4754
  eventId,
@@ -4261,6 +4770,7 @@ var Client4 = class {
4261
4770
  * ```
4262
4771
  *
4263
4772
  * @param eventId event id to check
4773
+ * @see node_modules/@upstash/workflow/docs/basics/client/waiters.mdx
4264
4774
  */
4265
4775
  async getWaiters({ eventId }) {
4266
4776
  return await makeGetWaitersRequest(this.client.http, eventId);
@@ -4336,6 +4846,8 @@ var Client4 = class {
4336
4846
  *
4337
4847
  * const { runs: nextRuns, cursor: nextCursor } = await client.logs({ cursor, count: 2 });
4338
4848
  * ```
4849
+ *
4850
+ * @see node_modules/@upstash/workflow/docs/basics/client/logs.mdx
4339
4851
  */
4340
4852
  async logs(params) {
4341
4853
  const { cursor, count, filter, ...legacyFilter } = params ?? {};
@@ -4350,6 +4862,9 @@ var Client4 = class {
4350
4862
  }
4351
4863
  });
4352
4864
  }
4865
+ /**
4866
+ * @see node_modules/@upstash/workflow/docs/features/dlq.mdx
4867
+ */
4353
4868
  get dlq() {
4354
4869
  return new DLQ(this.client);
4355
4870
  }