@upstash/workflow 1.4.0-rc → 1.5.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 +18 -2
  3. package/astro.d.ts +18 -2
  4. package/astro.js +129 -29
  5. package/astro.mjs +1 -1
  6. package/{chunk-UH6O5IJY.mjs → chunk-J3PXPHSB.mjs} +129 -29
  7. package/cloudflare.d.mts +16 -2
  8. package/cloudflare.d.ts +16 -2
  9. package/cloudflare.js +129 -29
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +374 -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 +567 -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 +104 -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 +2944 -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 +18 -2
  136. package/express.d.ts +18 -2
  137. package/express.js +129 -29
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +18 -2
  140. package/h3.d.ts +18 -2
  141. package/h3.js +129 -29
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +16 -2
  144. package/hono.d.ts +16 -2
  145. package/hono.js +129 -29
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +49 -21
  148. package/index.d.ts +49 -21
  149. package/index.js +145 -41
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +39 -2
  152. package/nextjs.d.ts +39 -2
  153. package/nextjs.js +129 -29
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +15 -2
  157. package/react-router.d.ts +15 -2
  158. package/react-router.js +129 -29
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CbIV7145.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-BCtZg31b.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +9 -1
  163. package/solidjs.d.ts +9 -1
  164. package/solidjs.js +129 -29
  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 +16 -2
  215. package/svelte.d.ts +16 -2
  216. package/svelte.js +129 -29
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +14 -2
  219. package/tanstack.d.ts +14 -2
  220. package/tanstack.js +129 -29
  221. package/tanstack.mjs +1 -1
  222. package/{types-ffLPVG5_.d.ts → types-CrgK5P6p.d.mts} +124 -24
  223. package/{types-ffLPVG5_.d.mts → types-CrgK5P6p.d.ts} +124 -24
package/solidjs.js CHANGED
@@ -790,6 +790,10 @@ var triggerFirstInvocation = async (params) => {
790
790
  workflowConfig: {
791
791
  workflowRunId: workflowContext.workflowRunId,
792
792
  workflowUrl: workflowContext.url,
793
+ // the run doesn't exist yet, so the trigger time is sent when the creation time
794
+ // is not known. serve and client.trigger set it on the context already, so a
795
+ // retry of this request carries the same value and is deduplicated.
796
+ workflowRunCreatedAt: workflowContext.workflowRunCreatedAt || Date.now(),
793
797
  failureUrl,
794
798
  retries,
795
799
  retryDelay,
@@ -897,7 +901,10 @@ var triggerWorkflowDelete = async (workflowContext, result, cancel = false, disp
897
901
  path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
898
902
  method: "DELETE",
899
903
  parseResponseAsJson: false,
900
- body: JSON.stringify(result)
904
+ body: JSON.stringify(result),
905
+ // with the creation time, QStash deletes the run only if it is the same run.
906
+ // a late delete of a previous run can't delete a new run with the same id.
907
+ headers: workflowContext.workflowRunCreatedAt ? { [WORKFLOW_CREATED_AT_HEADER]: workflowContext.workflowRunCreatedAt.toString() } : void 0
901
908
  });
902
909
  await dispatchDebug?.("onInfo", {
903
910
  info: `Workflow run ${workflowContext.workflowRunId} deleted from QStash successfully.`
@@ -974,6 +981,7 @@ ${atob(callbackMessage.body ?? "")}`
974
981
  const concurrentString = request.headers.get("Upstash-Workflow-Concurrent");
975
982
  const contentType = request.headers.get("Upstash-Workflow-ContentType");
976
983
  const invokeCount = request.headers.get(WORKFLOW_INVOKE_COUNT_HEADER);
984
+ const workflowRunCreatedAt = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
977
985
  if (!(workflowRunId && stepIdString && stepName && StepTypes.includes(stepType) && concurrentString && contentType)) {
978
986
  throw new Error(
979
987
  `Missing info in callback message source header: ${JSON.stringify({
@@ -991,6 +999,7 @@ ${atob(callbackMessage.body ?? "")}`
991
999
  workflowConfig: {
992
1000
  workflowRunId,
993
1001
  workflowUrl,
1002
+ workflowRunCreatedAt: Number(workflowRunCreatedAt ?? "0"),
994
1003
  telemetry
995
1004
  },
996
1005
  invokeCount: Number(invokeCount)
@@ -1165,6 +1174,7 @@ var BaseLazyStep = class _BaseLazyStep {
1165
1174
  workflowConfig: {
1166
1175
  workflowRunId: context.workflowRunId,
1167
1176
  workflowUrl: context.url,
1177
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
1168
1178
  useJSONContent: false,
1169
1179
  telemetry
1170
1180
  },
@@ -1496,6 +1506,8 @@ var LazyWaitEventStep = class extends BaseLazyStep {
1496
1506
  ) : {},
1497
1507
  // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
1498
1508
  "Upstash-Workflow-Runid": [context.workflowRunId],
1509
+ // same for WORKFLOW_CREATED_AT_HEADER, because Createdat -> CreatedAt:
1510
+ ...context.workflowRunCreatedAt ? { "Upstash-Workflow-Createdat": [context.workflowRunCreatedAt.toString()] } : {},
1499
1511
  [WORKFLOW_INIT_HEADER]: ["false"],
1500
1512
  [WORKFLOW_URL_HEADER]: [context.url],
1501
1513
  "Upstash-Workflow-CallType": ["step"]
@@ -1598,6 +1610,7 @@ var LazyInvokeStep = class extends BaseLazyStep {
1598
1610
  workflowConfig: {
1599
1611
  workflowRunId: context.workflowRunId,
1600
1612
  workflowUrl: context.url,
1613
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
1601
1614
  telemetry,
1602
1615
  useJSONContent: false
1603
1616
  },
@@ -1607,6 +1620,9 @@ var LazyInvokeStep = class extends BaseLazyStep {
1607
1620
  invokerHeaders[key] = value;
1608
1621
  });
1609
1622
  invokerHeaders["Upstash-Workflow-Runid"] = context.workflowRunId;
1623
+ if (context.workflowRunCreatedAt) {
1624
+ invokerHeaders["Upstash-Workflow-Createdat"] = context.workflowRunCreatedAt.toString();
1625
+ }
1610
1626
  const request = {
1611
1627
  body: stringifyBody(this.params.body),
1612
1628
  headers: Object.fromEntries(
@@ -1635,6 +1651,9 @@ var LazyInvokeStep = class extends BaseLazyStep {
1635
1651
  workflowConfig: {
1636
1652
  workflowRunId: getWorkflowRunId(workflowRunId),
1637
1653
  workflowUrl: newUrl,
1654
+ // the invoked run doesn't exist yet, so the creation time of the invoker run is sent.
1655
+ // it separates the invocations made by different runs of the invoker.
1656
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
1638
1657
  retries,
1639
1658
  retryDelay,
1640
1659
  telemetry,
@@ -1804,6 +1823,9 @@ var WorkflowHeaders = class {
1804
1823
  [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1805
1824
  ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}
1806
1825
  };
1826
+ if (this.workflowConfig.workflowRunCreatedAt) {
1827
+ this.headers.rawHeaders[WORKFLOW_CREATED_AT_HEADER] = this.workflowConfig.workflowRunCreatedAt.toString();
1828
+ }
1807
1829
  if (this.stepInfo?.lazyStep.stepType !== "Call") {
1808
1830
  this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
1809
1831
  }
@@ -2002,6 +2024,7 @@ var submitParallelSteps = async ({
2002
2024
  workflowConfig: {
2003
2025
  workflowRunId: context.workflowRunId,
2004
2026
  workflowUrl: context.url,
2027
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2005
2028
  telemetry
2006
2029
  },
2007
2030
  invokeCount,
@@ -2092,6 +2115,7 @@ var publishStepConfigRequest = async ({
2092
2115
  initHeaderValue: "false",
2093
2116
  workflowConfig: {
2094
2117
  workflowRunId: context.workflowRunId,
2118
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2095
2119
  workflowUrl: context.url,
2096
2120
  telemetry
2097
2121
  },
@@ -2104,7 +2128,9 @@ var publishStepConfigRequest = async ({
2104
2128
  const result = await context.qstashClient.publishJSON({
2105
2129
  headers: {
2106
2130
  ...headers,
2107
- "Upstash-Workflow-CallType": WORKFLOW_STEP_CONFIG_CALL_TYPE
2131
+ "Upstash-Workflow-CallType": WORKFLOW_STEP_CONFIG_CALL_TYPE,
2132
+ "Upstash-Forward-Upstash-Workflow-StepId": targetStep.toString(),
2133
+ "Upstash-Forward-Upstash-Workflow-StepName": lazyStep.stepName
2108
2134
  },
2109
2135
  method: "POST",
2110
2136
  body: { targetStep, invokeCount },
@@ -2123,6 +2149,19 @@ var publishStepConfigRequest = async ({
2123
2149
  };
2124
2150
 
2125
2151
  // src/qstash/step-config.ts
2152
+ var normalizeStepSettings = (settings) => {
2153
+ if (settings === void 0) {
2154
+ return void 0;
2155
+ }
2156
+ const { retries, retryDelay } = settings;
2157
+ if (retryDelay !== void 0 && typeof retryDelay !== "string") {
2158
+ throw new WorkflowNonRetryableError("Invalid step retryDelay: must be a string.");
2159
+ }
2160
+ if (retries !== void 0 && (!Number.isInteger(retries) || retries < 0)) {
2161
+ throw new WorkflowNonRetryableError("Invalid step retries: must be a non-negative integer.");
2162
+ }
2163
+ return { ...settings, retryDelay: retryDelay?.trim() || void 0 };
2164
+ };
2126
2165
  var DEFAULT_PARALLELISM = 0;
2127
2166
  var DEFAULT_RATE = 0;
2128
2167
  var DEFAULT_PERIOD_SECONDS = 1;
@@ -2386,10 +2425,18 @@ var AutoExecutor = class _AutoExecutor {
2386
2425
  dispatchLifecycle: this.dispatchLifecycle
2387
2426
  });
2388
2427
  if (lazyStep.supportsDeferredSubmission) {
2389
- this.pendingStep = { status: "held", lazyStep, resultStep };
2428
+ const serializedOut = JSON.stringify(resultStep.out);
2429
+ this.pendingStep = {
2430
+ status: "held",
2431
+ lazyStep,
2432
+ resultStep: {
2433
+ ...resultStep,
2434
+ out: serializedOut === void 0 ? void 0 : JSON.parse(serializedOut)
2435
+ }
2436
+ };
2390
2437
  return lazyStep.parseOut({
2391
2438
  ...resultStep,
2392
- out: resultStep.out === void 0 ? void 0 : JSON.stringify(resultStep.out)
2439
+ out: serializedOut
2393
2440
  });
2394
2441
  }
2395
2442
  await submitStepResult({
@@ -2734,6 +2781,11 @@ var BaseWorkflowApi = class {
2734
2781
 
2735
2782
  // src/context/api/anthropic.ts
2736
2783
  var AnthropicAPI = class extends BaseWorkflowApi {
2784
+ /**
2785
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2786
+ *
2787
+ * @see node_modules/@upstash/workflow/docs/integrations/anthropic.mdx
2788
+ */
2737
2789
  async call(stepName, settings) {
2738
2790
  const { token, operation, ...parameters } = settings;
2739
2791
  return await this.callApi(stepName, {
@@ -2749,6 +2801,11 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2749
2801
  // src/context/api/openai.ts
2750
2802
  var import_qstash7 = require("@upstash/qstash");
2751
2803
  var OpenAIAPI = class extends BaseWorkflowApi {
2804
+ /**
2805
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2806
+ *
2807
+ * @see node_modules/@upstash/workflow/docs/integrations/openai.mdx
2808
+ */
2752
2809
  async call(stepName, settings) {
2753
2810
  const { token, organization, operation, baseURL, ...parameters } = settings;
2754
2811
  const useOpenAI = baseURL === void 0;
@@ -2766,6 +2823,11 @@ var OpenAIAPI = class extends BaseWorkflowApi {
2766
2823
  // src/context/api/resend.ts
2767
2824
  var import_qstash8 = require("@upstash/qstash");
2768
2825
  var ResendAPI = class extends BaseWorkflowApi {
2826
+ /**
2827
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2828
+ *
2829
+ * @see node_modules/@upstash/workflow/docs/integrations/resend.mdx
2830
+ */
2769
2831
  async call(stepName, settings) {
2770
2832
  const { token, batch = false, ...parameters } = settings;
2771
2833
  return await this.callApi(stepName, {
@@ -2940,8 +3002,9 @@ var WorkflowContext = class {
2940
3002
  *
2941
3003
  * ```ts
2942
3004
  * import { Client } from "@upstash/qstash"
3005
+ * import { serve } from "@upstash/workflow/nextjs"
2943
3006
  *
2944
- * export const POST = serve(
3007
+ * export const { POST } = serve(
2945
3008
  * async (context) => {
2946
3009
  * ...
2947
3010
  * },
@@ -2966,7 +3029,7 @@ var WorkflowContext = class {
2966
3029
  * Can be overwritten by passing a `url` parameter in `serve`:
2967
3030
  *
2968
3031
  * ```ts
2969
- * export const POST = serve(
3032
+ * export const { POST } = serve(
2970
3033
  * async (context) => {
2971
3034
  * ...
2972
3035
  * },
@@ -2984,7 +3047,7 @@ var WorkflowContext = class {
2984
3047
  *
2985
3048
  * ```ts
2986
3049
  * // set requestPayload type to MyPayload:
2987
- * export const POST = serve<MyPayload>(
3050
+ * export const { POST } = serve<MyPayload>(
2988
3051
  * async (context) => {
2989
3052
  * ...
2990
3053
  * }
@@ -2996,7 +3059,7 @@ var WorkflowContext = class {
2996
3059
  * the `initialPayloadParser` parameter:
2997
3060
  *
2998
3061
  * ```ts
2999
- * export const POST = serve<MyPayload>(
3062
+ * export const { POST } = serve<MyPayload>(
3000
3063
  * async (context) => {
3001
3064
  * ...
3002
3065
  * },
@@ -3005,6 +3068,13 @@ var WorkflowContext = class {
3005
3068
  * }
3006
3069
  * )
3007
3070
  * ```
3071
+ *
3072
+ * When a `context.call` response comes back, the route runs up to its first step with this
3073
+ * set to the call-result envelope (and `workflowRunId` set to a random id) before the SDK
3074
+ * recognizes the request. Code before the first step must not dereference, validate or
3075
+ * return early on the payload; read it inside `context.run`.
3076
+ *
3077
+ * @see node_modules/@upstash/workflow/docs/basics/serve/advanced.mdx
3008
3078
  */
3009
3079
  requestPayload;
3010
3080
  /**
@@ -3017,7 +3087,7 @@ var WorkflowContext = class {
3017
3087
  * Can be set using the `env` option of serve:
3018
3088
  *
3019
3089
  * ```ts
3020
- * export const POST = serve<MyPayload>(
3090
+ * export const { POST } = serve<MyPayload>(
3021
3091
  * async (context) => {
3022
3092
  * const key = context.env["API_KEY"];
3023
3093
  * },
@@ -3183,18 +3253,24 @@ var WorkflowContext = class {
3183
3253
  * )
3184
3254
  * ```
3185
3255
  *
3256
+ * Do not wrap steps in try/catch or `.catch` without rethrowing `WorkflowAbort`: each step
3257
+ * throws it to end the request. To stop retrying a failed step, throw
3258
+ * `WorkflowNonRetryableError`.
3259
+ *
3186
3260
  * @param stepName name of the step
3187
3261
  * @param stepFunction step function to be executed
3188
3262
  * @param stepSettings step-level settings for this step
3189
3263
  * @returns result of the step function
3264
+ * @see node_modules/@upstash/workflow/docs/steps/run.mdx
3190
3265
  */
3191
3266
  async run(stepName, stepFunction, stepSettings) {
3267
+ const normalizedSettings = normalizeStepSettings(stepSettings);
3192
3268
  if (stepSettings) {
3193
3269
  validateFlowControl(stepSettings.flowControl);
3194
3270
  }
3195
3271
  const wrappedStepFunction = (() => this.executor.wrapStep(stepName, stepFunction));
3196
3272
  return await this.addStep(
3197
- new LazyFunctionStep(this, stepName, wrappedStepFunction, stepSettings)
3273
+ new LazyFunctionStep(this, stepName, wrappedStepFunction, normalizedSettings)
3198
3274
  );
3199
3275
  }
3200
3276
  /**
@@ -3205,8 +3281,9 @@ var WorkflowContext = class {
3205
3281
  * ```
3206
3282
  *
3207
3283
  * @param stepName
3208
- * @param duration sleep duration in seconds
3284
+ * @param duration sleep duration in seconds, or a duration string such as "10m"
3209
3285
  * @returns undefined
3286
+ * @see node_modules/@upstash/workflow/docs/steps/sleep.mdx
3210
3287
  */
3211
3288
  async sleep(stepName, duration) {
3212
3289
  await this.addStep(new LazySleepStep(this, stepName, duration));
@@ -3220,8 +3297,11 @@ var WorkflowContext = class {
3220
3297
  *
3221
3298
  * @param stepName
3222
3299
  * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
3223
- * as a Date object or a string (passed to `new Date(datetimeString)`)
3300
+ * as a Date object or a string (passed to `new Date(datetimeString)`).
3301
+ * A millisecond timestamp such as `Date.now()` is too far in the future, so QStash
3302
+ * rejects the step and the run fails. Pass `new Date(ms)` instead.
3224
3303
  * @returns undefined
3304
+ * @see node_modules/@upstash/workflow/docs/steps/sleepUntil.mdx
3225
3305
  */
3226
3306
  async sleepUntil(stepName, datetime) {
3227
3307
  let time;
@@ -3272,7 +3352,7 @@ var WorkflowContext = class {
3272
3352
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
3273
3353
  *
3274
3354
  *```ts
3275
- * const result = await workflow.waitForEvent("payment-confirmed", "payment.confirmed", {
3355
+ * const result = await context.waitForEvent("payment-confirmed", "payment.confirmed", {
3276
3356
  * timeout: "5m"
3277
3357
  * });
3278
3358
  *```
@@ -3296,11 +3376,14 @@ var WorkflowContext = class {
3296
3376
  * Alternatively, you can use the `context.notify` method.
3297
3377
  *
3298
3378
  * @param stepName
3299
- * @param eventId - Unique identifier for the event to wait for
3379
+ * @param eventId - Unique identifier for the event to wait for. Only letters, digits,
3380
+ * "-", "_" and "." are allowed. QStash rejects other characters, such as ":", which
3381
+ * stops the run with only a "Tried to append to a cancelled workflow" warning.
3300
3382
  * @param options - Configuration options.
3301
3383
  * @returns `{ timeout: boolean, eventData: TEventData }`.
3302
3384
  * The `timeout` property specifies if the workflow has timed out. The `eventData`
3303
3385
  * is the data passed when notifying this workflow of an event.
3386
+ * @see node_modules/@upstash/workflow/docs/steps/waitForEvent.mdx
3304
3387
  */
3305
3388
  async waitForEvent(stepName, eventId, options = {}) {
3306
3389
  const { timeout = "7d" } = options;
@@ -3322,28 +3405,31 @@ var WorkflowContext = class {
3322
3405
  * will receive the given event data and resume execution.
3323
3406
  *
3324
3407
  * The response includes the same eventId and eventData. Additionally, there is
3325
- * a notifyResponse field which contains a list of `Waiter` objects, each corresponding
3326
- * to a notified workflow run.
3327
- *
3328
- * Optionally, you can pass a workflowRunId to enable lookback functionality:
3329
- *
3330
- * ```ts
3331
- * const { eventId, eventData, notifyResponse } = await context.notify(
3332
- * "notify step", "event-id", "event-data", "wfr_123"
3333
- * );
3334
- * ```
3408
+ * a notifyResponse field which contains a list of `NotifyResponse` objects, each corresponding
3409
+ * to a notified workflow run. The notified `Waiter` is under `notifyResponse[i].waiter`.
3335
3410
  *
3336
3411
  * @param stepName
3337
- * @param eventId event id to notify
3412
+ * @param eventId event id to notify. Only letters, digits, "-", "_" and "." are allowed.
3413
+ * QStash rejects other characters, such as ":", which stops the run with only a
3414
+ * "Tried to append to a cancelled workflow" warning.
3338
3415
  * @param eventData event data to notify with
3339
- * @param workflowRunId optional workflow run id for lookback support
3340
- * @returns notify response which has event id, event data and list of waiters which were notified
3416
+ * @param workflowRunId optional workflow run id for lookback: the event is kept for the run
3417
+ * even if it has not reached `waitForEvent` yet
3418
+ * @returns notify response which has event id, event data and list of waiters which were
3419
+ * notified. With `workflowRunId`, QStash returns `notifyResponse` as a single object instead
3420
+ * of an array, despite the type.
3421
+ * @see node_modules/@upstash/workflow/docs/steps/notify.mdx
3341
3422
  */
3342
3423
  async notify(stepName, eventId, eventData, workflowRunId) {
3343
3424
  return await this.addStep(
3344
3425
  new LazyNotifyStep(this, stepName, eventId, eventData, this.qstashClient.http, workflowRunId)
3345
3426
  );
3346
3427
  }
3428
+ /**
3429
+ * Starts another workflow run and waits for its result.
3430
+ *
3431
+ * @see node_modules/@upstash/workflow/docs/steps/invoke.mdx
3432
+ */
3347
3433
  async invoke(stepName, settings) {
3348
3434
  validateLabel(settings.label);
3349
3435
  validateFlowControl(settings.flowControl);
@@ -3351,9 +3437,15 @@ var WorkflowContext = class {
3351
3437
  new LazyInvokeStep(this, stepName, settings)
3352
3438
  );
3353
3439
  }
3440
+ /**
3441
+ * @see node_modules/@upstash/workflow/docs/steps/createWebhook.mdx
3442
+ */
3354
3443
  async createWebhook(stepName) {
3355
3444
  return await this.addStep(new LazyCreateWebhookStep(this, stepName));
3356
3445
  }
3446
+ /**
3447
+ * @see node_modules/@upstash/workflow/docs/steps/waitForWebhook.mdx
3448
+ */
3357
3449
  async waitForWebhook(stepName, webhook, timeout) {
3358
3450
  return await this.addStep(new LazyWaitForWebhookStep(this, stepName, webhook, timeout));
3359
3451
  }
@@ -3362,6 +3454,8 @@ var WorkflowContext = class {
3362
3454
  *
3363
3455
  * Will throw WorkflowCancelAbort to stop workflow execution.
3364
3456
  * Shouldn't be inside try/catch.
3457
+ *
3458
+ * @see node_modules/@upstash/workflow/docs/steps/cancel.mdx
3365
3459
  */
3366
3460
  async cancel() {
3367
3461
  throw new WorkflowCancelAbort();
@@ -3380,6 +3474,11 @@ var WorkflowContext = class {
3380
3474
  throw error;
3381
3475
  }
3382
3476
  }
3477
+ /**
3478
+ * Calls OpenAI, Anthropic or Resend through QStash, like `context.call`.
3479
+ *
3480
+ * @see node_modules/@upstash/workflow/docs/steps/api.mdx
3481
+ */
3383
3482
  get api() {
3384
3483
  return new WorkflowApi({
3385
3484
  context: this
@@ -4162,7 +4261,8 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
4162
4261
  const invokeCount = Number(request.headers.get(WORKFLOW_INVOKE_COUNT_HEADER) ?? "0");
4163
4262
  const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
4164
4263
  const label = request.headers.get(WORKFLOW_LABEL_HEADER) ?? void 0;
4165
- const workflowRunCreatedAt = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
4264
+ const workflowRunCreatedAtHeader = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
4265
+ const workflowRunCreatedAt = workflowRunCreatedAtHeader ? Number(workflowRunCreatedAtHeader) : isFirstInvocation ? Date.now() : 0;
4166
4266
  const effectiveConfig = getEffectiveConfig(request.headers);
4167
4267
  const workflowContext = new WorkflowContext({
4168
4268
  qstashClient: regionalClient,
@@ -4177,7 +4277,7 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
4177
4277
  invokeCount,
4178
4278
  label,
4179
4279
  retried,
4180
- workflowRunCreatedAt: Number(workflowRunCreatedAt),
4280
+ workflowRunCreatedAt,
4181
4281
  middlewareManager
4182
4282
  });
4183
4283
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
package/solidjs.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SDK_TELEMETRY,
3
3
  serveBase
4
- } from "./chunk-UH6O5IJY.mjs";
4
+ } from "./chunk-J3PXPHSB.mjs";
5
5
 
6
6
  // platforms/solidjs.ts
7
7
  import { startDevServer } from "@upstash/qstash";
@@ -0,0 +1,84 @@
1
+ import type { APIContext, APIRoute } from "astro";
2
+
3
+ import { InvokableWorkflow, WorkflowServeOptions, Telemetry, WorkflowContext } from "../src";
4
+ import { serveBase } from "../src/serve";
5
+ import { SDK_TELEMETRY } from "../src/constants";
6
+ import { serveManyBase } from "../src/serve/serve-many";
7
+ import { startDevServer } from "@upstash/qstash";
8
+
9
+ const telemetry: Telemetry = {
10
+ sdk: SDK_TELEMETRY,
11
+ framework: "astro",
12
+ runtime: process.versions.bun
13
+ ? `bun@${process.versions.bun}/node@${process.version}`
14
+ : `node@${process.version}`,
15
+ };
16
+
17
+ /**
18
+ * Code outside steps runs again on every request of the run. Anything it branches on or
19
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
20
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
21
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
22
+ * result.
23
+ *
24
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
25
+ * @see node_modules/@upstash/workflow/docs/quickstarts/astro.mdx
26
+ */
27
+ export function serve<TInitialPayload = unknown, TResult = unknown>(
28
+ routeFunction: (
29
+ workflowContext: WorkflowContext<TInitialPayload>,
30
+ apiContext: APIContext
31
+ ) => Promise<TResult>,
32
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
33
+ ) {
34
+ void startDevServer();
35
+
36
+ const POST: APIRoute = (apiContext) => {
37
+ const { handler } = serveBase<TInitialPayload, Request, Response, TResult>(
38
+ (workflowContext) => routeFunction(workflowContext, apiContext),
39
+ telemetry,
40
+ options
41
+ );
42
+
43
+ return handler(apiContext.request);
44
+ };
45
+
46
+ return { POST };
47
+ }
48
+
49
+ /**
50
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
51
+ */
52
+ export const createWorkflow = <TInitialPayload, TResult>(
53
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
54
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
55
+ const [routeFunction, options = {}] = params;
56
+ return {
57
+ workflowId: undefined,
58
+ // @ts-expect-error because astro route function has another parameter,
59
+ // the RouteFunction type can't cover this. We need to make RouteFunction
60
+ // accept more variables than simply the context. Until then, ignoring the
61
+ // error here. Tested the usage in astro project and it's fine. TODO.
62
+ routeFunction,
63
+ options,
64
+ };
65
+ };
66
+
67
+ /**
68
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
69
+ */
70
+ export const serveMany = (
71
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
72
+ options?: Parameters<typeof serveManyBase>[0]["options"]
73
+ ) => {
74
+ return {
75
+ POST: serveManyBase<ReturnType<typeof serve>["POST"]>({
76
+ workflows: workflows,
77
+ getUrl(...params) {
78
+ return params[0].request.url;
79
+ },
80
+ serveMethod: (...params: Parameters<typeof serve>) => serve(...params).POST,
81
+ options,
82
+ }).handler,
83
+ };
84
+ };
@@ -0,0 +1,127 @@
1
+ import type { InvokableWorkflow, WorkflowServeOptions, RouteFunction, Telemetry } from "../src";
2
+ import { SDK_TELEMETRY } from "../src/constants";
3
+ import { serveBase } from "../src/serve";
4
+ import { serveManyBase } from "../src/serve/serve-many";
5
+ import { startDevServer } from "@upstash/qstash";
6
+
7
+ export type WorkflowBindings = {
8
+ QSTASH_TOKEN: string;
9
+ QSTASH_URL?: string;
10
+ QSTASH_CURRENT_SIGNING_KEY?: string;
11
+ QSTASH_NEXT_SIGNING_KEY?: string;
12
+ UPSTASH_WORKFLOW_URL?: string;
13
+ };
14
+
15
+ /**
16
+ * Cloudflare Pages Function arguments
17
+ */
18
+ export type PagesHandlerArgs = [{ request: Request; env: Record<string, string | undefined> }];
19
+
20
+ /**
21
+ * Cloudflare Worker arguments
22
+ */
23
+ export type WorkersHandlerArgs = [Request, Record<string, string | undefined>];
24
+
25
+ /**
26
+ * Support both Cloudflare Pages Functions and Cloudflare Workers
27
+ */
28
+ const getArgs = (
29
+ args: PagesHandlerArgs | WorkersHandlerArgs
30
+ ): { request: Request; env: Record<string, string | undefined> } => {
31
+ // @ts-expect-error types of args don't allow length 0, but want to sanity check
32
+ if (!Array.isArray(args) || args.length === 0) {
33
+ throw new Error("No arguments passed to serve handler");
34
+ }
35
+
36
+ if (typeof args[0] === "object" && "request" in args[0] && "env" in args[0]) {
37
+ return {
38
+ request: args[0].request,
39
+ env: args[0].env,
40
+ };
41
+ }
42
+
43
+ if (args.length > 1 && typeof args[1] === "object") {
44
+ return {
45
+ request: args[0],
46
+ env: args[1],
47
+ };
48
+ }
49
+
50
+ throw new Error("Could not derive handler arguments from input. Please check how serve is used.");
51
+ };
52
+
53
+ const telemetry: Telemetry = {
54
+ sdk: SDK_TELEMETRY,
55
+ framework: "cloudflare",
56
+ };
57
+
58
+ /**
59
+ * Serve method to serve a Upstash Workflow in a Cloudflare project
60
+ *
61
+ * See for options https://upstash.com/docs/qstash/workflows/basics/serve
62
+ *
63
+ * Code outside steps runs again on every request of the run. Anything it branches on or
64
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
65
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
66
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
67
+ * result.
68
+ *
69
+ * @param routeFunction workflow function
70
+ * @param options workflow options
71
+ * @returns
72
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
73
+ * @see node_modules/@upstash/workflow/docs/quickstarts/cloudflare-workers.mdx
74
+ */
75
+ export const serve = <TInitialPayload = unknown, TResult = unknown>(
76
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
77
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
78
+ ): {
79
+ fetch: (...args: PagesHandlerArgs | WorkersHandlerArgs) => Promise<Response>;
80
+ } => {
81
+ void startDevServer();
82
+
83
+ const fetch = async (...args: PagesHandlerArgs | WorkersHandlerArgs) => {
84
+ const { request, env } = getArgs(args);
85
+ const { handler: serveHandler } = serveBase(routeFunction, telemetry, {
86
+ env,
87
+ ...options,
88
+ });
89
+ return await serveHandler(request);
90
+ };
91
+
92
+ return { fetch };
93
+ };
94
+
95
+ /**
96
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
97
+ */
98
+ export const createWorkflow = <TInitialPayload, TResult>(
99
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
100
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
101
+ const [routeFunction, options = {}] = params;
102
+ return {
103
+ workflowId: undefined,
104
+ routeFunction,
105
+ options,
106
+ };
107
+ };
108
+
109
+ /**
110
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
111
+ */
112
+ export const serveMany = (
113
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
114
+ options?: Parameters<typeof serveManyBase>[0]["options"]
115
+ ) => {
116
+ return {
117
+ fetch: serveManyBase<ReturnType<typeof serve>["fetch"]>({
118
+ workflows: workflows,
119
+ getUrl(...params) {
120
+ const { request } = getArgs(params);
121
+ return request.url;
122
+ },
123
+ options,
124
+ serveMethod: (...params: Parameters<typeof serve>) => serve(...params).fetch,
125
+ }).handler,
126
+ };
127
+ };