@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
@@ -0,0 +1,99 @@
1
+ import type { RequestHandler } from "@sveltejs/kit";
2
+
3
+ import type { InvokableWorkflow, WorkflowServeOptions, RouteFunction, Telemetry } from "../src";
4
+ import { serveBase } from "../src/serve";
5
+ import { SDK_TELEMETRY } from "../src/constants";
6
+ import { OmitOptionsInServeMany, serveManyBase } from "../src/serve/serve-many";
7
+ import { startDevServer } from "@upstash/qstash";
8
+
9
+ const telemetry: Telemetry = {
10
+ sdk: SDK_TELEMETRY,
11
+ framework: "svelte",
12
+ };
13
+
14
+ type RequireEnv<T> = T & {
15
+ env: WorkflowServeOptions["env"]; // make env required
16
+ };
17
+
18
+ /**
19
+ * Serve method to serve a Upstash Workflow in a Svelte project
20
+ *
21
+ * See for options https://upstash.com/docs/qstash/workflows/basics/serve
22
+ *
23
+ * Code outside steps runs again on every request of the run. Anything it branches on or
24
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
25
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
26
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
27
+ * result.
28
+ *
29
+ * @param routeFunction workflow function
30
+ * @param options workflow options
31
+ * @returns
32
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
33
+ * @see node_modules/@upstash/workflow/docs/quickstarts/svelte.mdx
34
+ */
35
+ export const serve = <TInitialPayload = unknown, TResult = unknown>(
36
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
37
+ options: WorkflowServeOptions<TInitialPayload, TResult> & {
38
+ env: WorkflowServeOptions["env"]; // make env required
39
+ }
40
+ ): {
41
+ POST: RequestHandler;
42
+ } => {
43
+ void startDevServer();
44
+
45
+ const handler: RequestHandler = async ({ request }) => {
46
+ const { handler: serveHandler } = serveBase<TInitialPayload, Request, Response, TResult>(
47
+ routeFunction,
48
+ telemetry,
49
+ options,
50
+ {
51
+ useJSONContent: true,
52
+ }
53
+ );
54
+ return await serveHandler(request);
55
+ };
56
+ return { POST: handler };
57
+ };
58
+
59
+ /**
60
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
61
+ */
62
+ export const createWorkflow = <TInitialPayload, TResult>(
63
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
64
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
65
+ const [routeFunction, options = {}] = params;
66
+ return {
67
+ workflowId: undefined,
68
+ routeFunction,
69
+ options,
70
+ useJSONContent: true,
71
+ };
72
+ };
73
+
74
+ /**
75
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
76
+ */
77
+ export const serveMany = (
78
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
79
+ options?: Parameters<typeof serveManyBase>[0]["options"]
80
+ ) => {
81
+ type Params = Parameters<typeof serve>;
82
+
83
+ return {
84
+ POST: serveManyBase<
85
+ ReturnType<typeof serve>["POST"],
86
+ OmitOptionsInServeMany<Params[1]>,
87
+ [Params[0], RequireEnv<Params[1]>]
88
+ >({
89
+ workflows: workflows,
90
+ getUrl(params) {
91
+ return params.url.toString();
92
+ },
93
+ options,
94
+ serveMethod: (routeFunction, serveOptions) => {
95
+ return serve(routeFunction, serveOptions).POST;
96
+ },
97
+ }).handler,
98
+ };
99
+ };
@@ -0,0 +1,96 @@
1
+ import type {
2
+ WorkflowServeOptions,
3
+ Telemetry,
4
+ InvokableWorkflow,
5
+ RouteFunction,
6
+ ExclusiveValidationOptions,
7
+ } from "../src";
8
+ import { serveBase } from "../src/serve";
9
+ import { SDK_TELEMETRY } from "../src/constants";
10
+ import { serveManyBase } from "../src/serve/serve-many";
11
+ import { startDevServer } from "@upstash/qstash";
12
+
13
+ const telemetry: Telemetry = {
14
+ sdk: SDK_TELEMETRY,
15
+ framework: "tanstack",
16
+ runtime: `node@${process.version}`,
17
+ };
18
+
19
+ /**
20
+ * Serve method to serve a Upstash Workflow in a TanStack Start project
21
+ *
22
+ * This wrapper allows you to access both the workflow context and TanStack route context
23
+ *
24
+ * Code outside steps runs again on every request of the run. Anything it branches on or
25
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
26
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
27
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
28
+ * result.
29
+ *
30
+ * @param routeFunction workflow function that receives both workflow context and TanStack route context
31
+ * @param options workflow options (same as Next.js serve options)
32
+ * @returns handler object with POST method compatible with TanStack Start
33
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
34
+ * @see node_modules/@upstash/workflow/docs/quickstarts/tanstack-start.mdx
35
+ */
36
+ export function serve<TInitialPayload = unknown, TResult = unknown>(
37
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
38
+ options?: Omit<
39
+ WorkflowServeOptions<TInitialPayload, TResult>,
40
+ "schema" | "initialPayloadParser"
41
+ > &
42
+ ExclusiveValidationOptions<TInitialPayload>
43
+ ) {
44
+ void startDevServer();
45
+
46
+ const POST = (tanstackContext: { request: Request }) => {
47
+ // Create a Next.js compatible handler that passes the route context
48
+ const { handler } = serveBase<TInitialPayload, Request, Response, TResult>(
49
+ routeFunction,
50
+ telemetry,
51
+ options
52
+ );
53
+
54
+ return handler(tanstackContext.request);
55
+ };
56
+
57
+ return { POST };
58
+ }
59
+
60
+ /**
61
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
62
+ */
63
+ export const createWorkflow = <TInitialPayload, TResult>(
64
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
65
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
66
+ const [routeFunction, options = {}] = params;
67
+ return {
68
+ options,
69
+ workflowId: undefined,
70
+ routeFunction,
71
+ };
72
+ };
73
+
74
+ /**
75
+ * Serve multiple workflows from a single endpoint using dynamic routing in TanStack Start
76
+ *
77
+ * @param workflows object containing workflow definitions
78
+ * @param options serve options
79
+ * @returns handler object with POST method
80
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
81
+ */
82
+ export const serveMany = (
83
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
84
+ options?: Parameters<typeof serveManyBase>[0]["options"]
85
+ ) => {
86
+ return {
87
+ POST: serveManyBase<ReturnType<typeof serve>["POST"]>({
88
+ workflows,
89
+ getUrl(context) {
90
+ return context.request.url;
91
+ },
92
+ serveMethod: (...params: Parameters<typeof serve>) => serve(...params).POST,
93
+ options,
94
+ }).handler,
95
+ };
96
+ };
@@ -0,0 +1,387 @@
1
+ import { Client as QStashClient, QstashError } from "@upstash/qstash";
2
+ import type { FlowControl } from "@upstash/qstash";
3
+ import { isInstanceOf } from "../error";
4
+ import type { DLQResumeRestartOptions, DLQResumeRestartResponse, FailureFunctionState } from "./types";
5
+ import {
6
+ assertNonEmptyId,
7
+ buildBulkActionQueryParameters,
8
+ normalizeCursor,
9
+ toNonEmptyIdArray,
10
+ } from "./utils";
11
+ import { WorkflowDLQActionFilters, WorkflowDLQListFilters } from "./filter-types";
12
+ import { prepareFlowControl } from "../qstash/headers";
13
+
14
+ type ResumeRestartOptions = {
15
+ flowControl?: FlowControl;
16
+ retries?: number;
17
+ };
18
+
19
+ type FailureCallbackInfo = {
20
+ state?: FailureFunctionState;
21
+ responseStatus?: number;
22
+ responseBody?: string;
23
+ responseHeaders?: Record<string, string[]>;
24
+ };
25
+
26
+ type DLQMessage = {
27
+ messageId: string;
28
+ /**
29
+ * URL of the workflow
30
+ */
31
+ url: string;
32
+ method: string;
33
+ header: Record<string, string[]>;
34
+ body: string;
35
+ maxRetries: number;
36
+ notBefore: number;
37
+ createdAt: number;
38
+ callerIP: string;
39
+ workflowRunId: string;
40
+ workflowCreatedAt: number;
41
+ workflowUrl: string;
42
+ responseStatus: number;
43
+ responseHeader: Record<string, string[]>;
44
+ responseBody: string;
45
+ dlqId: string;
46
+ /**
47
+ * URL of the failure callback
48
+ */
49
+ failureCallback?: string;
50
+ /**
51
+ * status of the failure callback
52
+ */
53
+ failureCallbackInfo?: FailureCallbackInfo;
54
+ /**
55
+ * Label passed when triggering the workflow run.
56
+ *
57
+ * @deprecated Use `labels` instead. When a run has multiple labels, this
58
+ * field only contains the first one.
59
+ */
60
+ label?: string;
61
+ /**
62
+ * Labels attached to the workflow run.
63
+ *
64
+ * A run can have multiple labels when triggered with `label: string[]`.
65
+ */
66
+ labels?: string[];
67
+ };
68
+
69
+ type PublicDLQMessage = Pick<
70
+ DLQMessage,
71
+ | "header"
72
+ | "body"
73
+ | "maxRetries"
74
+ | "notBefore"
75
+ | "createdAt"
76
+ | "callerIP"
77
+ | "workflowRunId"
78
+ | "workflowCreatedAt"
79
+ | "workflowUrl"
80
+ | "responseStatus"
81
+ | "responseHeader"
82
+ | "responseBody"
83
+ | "dlqId"
84
+ | "failureCallback"
85
+ | "failureCallbackInfo"
86
+ | "label"
87
+ | "labels"
88
+ >;
89
+
90
+ function buildResumeRestartHeaders(options?: ResumeRestartOptions): Record<string, string> {
91
+ const headers: Record<string, string> = {};
92
+ if (options?.flowControl) {
93
+ const { flowControlKey, flowControlValue } = prepareFlowControl(options.flowControl);
94
+ headers["Upstash-Flow-Control-Key"] = flowControlKey;
95
+ headers["Upstash-Flow-Control-Value"] = flowControlValue;
96
+ }
97
+ if (options?.retries !== undefined) {
98
+ headers["Upstash-Retries"] = options.retries.toString();
99
+ }
100
+ return headers;
101
+ }
102
+
103
+ export class DLQ {
104
+ constructor(private client: QStashClient) {}
105
+
106
+ /**
107
+ * list the items in the DLQ
108
+ *
109
+ * @param parameters - Optional parameters object
110
+ * @param parameters.cursor - Optional cursor for pagination
111
+ * @param parameters.count - Optional number of items to return
112
+ * @param parameters.filter - Optional filter options to apply to the DLQ items.
113
+ * The available filter options are:
114
+ * - `fromDate`: Filter items which entered the DLQ after this date.
115
+ * - `toDate`: Filter items which entered the DLQ before this date.
116
+ * - `url`: Filter items by the URL they were sent to.
117
+ * - `responseStatus`: Filter items by the response status code.
118
+ * - `workflowRunId`: Filter items by workflow run ID.
119
+ * - `workflowCreatedAt`: Filter items by workflow creation time.
120
+ * - `failureFunctionState`: Filter items by failure callback state.
121
+ * - `label`: Filter items by label.
122
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/list.mdx
123
+ */
124
+ async list(parameters?: { cursor?: string; count?: number; filter?: WorkflowDLQListFilters }) {
125
+ const { cursor, count, filter } = parameters || {};
126
+ return normalizeCursor(
127
+ (await this.client.http.request({
128
+ path: ["v2", "dlq"],
129
+ method: "GET",
130
+ query: {
131
+ cursor,
132
+ count,
133
+ ...filter,
134
+ source: "workflow",
135
+ },
136
+ })) as { messages: PublicDLQMessage[]; cursor?: string }
137
+ );
138
+ }
139
+
140
+ /**
141
+ * Resumes the workflow run for the given DLQ message(s).
142
+ *
143
+ * Resuming means that the new workflow run will start executing from where
144
+ * the original workflow run failed, using the same input and context.
145
+ *
146
+ * If you want to restart the workflow run from the beginning, use
147
+ * `restart` method instead.
148
+ *
149
+ * Can be called with:
150
+ * - A single dlqId: `resume("id")`
151
+ * - An array of dlqIds: `resume(["id1", "id2"])`
152
+ * - A filter object: `resume({ filter: { label: "my-label", fromDate: 1640995200000 } })`
153
+ * - To target all entries: `resume({ all: true })`
154
+ *
155
+ * Processes up to `count` messages per call (defaults to 100).
156
+ * Call in a loop until cursor is undefined to process all:
157
+ *
158
+ * ```ts
159
+ * let cursor: string | undefined;
160
+ * do {
161
+ * const result = await client.dlq.resume({ all: true, count: 100, cursor });
162
+ * cursor = result.cursor;
163
+ * } while (cursor);
164
+ * ```
165
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/resume.mdx
166
+ */
167
+ async resume(
168
+ request: string | string[] | WorkflowDLQActionFilters,
169
+ options?: ResumeRestartOptions
170
+ ): Promise<{ cursor?: string; workflowRuns: DLQResumeRestartResponse[] }>;
171
+ /** @deprecated Use `resume(dlqId)` instead */
172
+ async resume(request: DLQResumeRestartOptions<string>): Promise<DLQResumeRestartResponse>;
173
+ /** @deprecated Use `resume([dlqId1, dlqId2])` instead */
174
+ async resume(request: DLQResumeRestartOptions<string[]>): Promise<DLQResumeRestartResponse[]>;
175
+ async resume(
176
+ request: string | string[] | WorkflowDLQActionFilters | DLQResumeRestartOptions,
177
+ options?: ResumeRestartOptions
178
+ ): Promise<
179
+ | { cursor?: string; workflowRuns: DLQResumeRestartResponse[] }
180
+ | DLQResumeRestartResponse
181
+ | DLQResumeRestartResponse[]
182
+ > {
183
+ // Legacy format: { dlqId, flowControl?, retries? }
184
+ if (typeof request === "object" && !Array.isArray(request) && "dlqId" in request) {
185
+ const { dlqId, flowControl, retries } = request as DLQResumeRestartOptions;
186
+
187
+ const dlqIds = Array.isArray(dlqId) ? dlqId : [dlqId];
188
+ const { workflowRuns } = await this.client.http.request<{
189
+ workflowRuns: DLQResumeRestartResponse[];
190
+ }>({
191
+ path: ["v2", "workflows", "dlq", "resume"],
192
+ query: { dlqIds },
193
+ method: "POST",
194
+ headers: buildResumeRestartHeaders({ flowControl, retries }),
195
+ });
196
+
197
+ return Array.isArray(dlqId) ? workflowRuns : workflowRuns[0];
198
+ }
199
+
200
+ // New format
201
+ if (typeof request === "string" || Array.isArray(request)) {
202
+ const ids = toNonEmptyIdArray(request, "DLQ id");
203
+ if (ids.length === 0) return { workflowRuns: [] };
204
+ request = ids;
205
+ }
206
+ const filters: WorkflowDLQActionFilters = Array.isArray(request)
207
+ ? { dlqIds: request }
208
+ : request;
209
+
210
+ return normalizeCursor(
211
+ await this.client.http.request<{
212
+ cursor?: string;
213
+ workflowRuns: DLQResumeRestartResponse[];
214
+ }>({
215
+ path: ["v2", "workflows", "dlq", "resume"],
216
+ query: buildBulkActionQueryParameters(filters),
217
+ method: "POST",
218
+ headers: buildResumeRestartHeaders(options),
219
+ })
220
+ );
221
+ }
222
+
223
+ /**
224
+ * Restarts the workflow run for the given DLQ message(s).
225
+ *
226
+ * Restarting means that the new workflow run will start executing from the
227
+ * beginning with the same initial payload and configuration.
228
+ *
229
+ * If you want to resume the workflow run from where it failed, use
230
+ * `resume` method instead.
231
+ *
232
+ * Can be called with:
233
+ * - A single dlqId: `restart("id")`
234
+ * - An array of dlqIds: `restart(["id1", "id2"])`
235
+ * - A filter object: `restart({ filter: { label: "my-label", fromDate: 1640995200000 } })`
236
+ * - To target all entries: `restart({ all: true })`
237
+ *
238
+ * Processes up to `count` messages per call (defaults to 100).
239
+ * Call in a loop until cursor is undefined to process all:
240
+ *
241
+ * ```ts
242
+ * let cursor: string | undefined;
243
+ * do {
244
+ * const result = await client.dlq.restart({ all: true, count: 100, cursor });
245
+ * cursor = result.cursor;
246
+ * } while (cursor);
247
+ * ```
248
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/restart.mdx
249
+ */
250
+ async restart(
251
+ request: string | string[] | WorkflowDLQActionFilters,
252
+ options?: ResumeRestartOptions
253
+ ): Promise<{ cursor?: string; workflowRuns: DLQResumeRestartResponse[] }>;
254
+ /** @deprecated Use `restart(dlqId)` instead */
255
+ async restart(request: DLQResumeRestartOptions<string>): Promise<DLQResumeRestartResponse>;
256
+ /** @deprecated Use `restart([dlqId1, dlqId2])` instead */
257
+ async restart(request: DLQResumeRestartOptions<string[]>): Promise<DLQResumeRestartResponse[]>;
258
+ async restart(
259
+ request: string | string[] | WorkflowDLQActionFilters | DLQResumeRestartOptions,
260
+ options?: ResumeRestartOptions
261
+ ): Promise<
262
+ | { cursor?: string; workflowRuns: DLQResumeRestartResponse[] }
263
+ | DLQResumeRestartResponse
264
+ | DLQResumeRestartResponse[]
265
+ > {
266
+ // Legacy format: { dlqId, flowControl?, retries? }
267
+ if (typeof request === "object" && !Array.isArray(request) && "dlqId" in request) {
268
+ const { dlqId, flowControl, retries } = request as DLQResumeRestartOptions;
269
+
270
+ const dlqIds = Array.isArray(dlqId) ? dlqId : [dlqId];
271
+ const { workflowRuns } = await this.client.http.request<{
272
+ workflowRuns: DLQResumeRestartResponse[];
273
+ }>({
274
+ path: ["v2", "workflows", "dlq", "restart"],
275
+ query: { dlqIds },
276
+ method: "POST",
277
+ headers: buildResumeRestartHeaders({ flowControl, retries }),
278
+ });
279
+
280
+ return Array.isArray(dlqId) ? workflowRuns : workflowRuns[0];
281
+ }
282
+
283
+ // New format
284
+ if (typeof request === "string" || Array.isArray(request)) {
285
+ const ids = toNonEmptyIdArray(request, "DLQ id");
286
+ if (ids.length === 0) return { workflowRuns: [] };
287
+ request = ids;
288
+ }
289
+ const filters: WorkflowDLQActionFilters = Array.isArray(request)
290
+ ? { dlqIds: request }
291
+ : request;
292
+
293
+ return normalizeCursor(
294
+ await this.client.http.request<{
295
+ cursor?: string;
296
+ workflowRuns: DLQResumeRestartResponse[];
297
+ }>({
298
+ path: ["v2", "workflows", "dlq", "restart"],
299
+ query: buildBulkActionQueryParameters(filters),
300
+ method: "POST",
301
+ headers: buildResumeRestartHeaders(options),
302
+ })
303
+ );
304
+ }
305
+
306
+ /**
307
+ * Retry the failure callback of a workflow run whose failureUrl/failureFunction
308
+ * request has failed.
309
+ *
310
+ * @param dlqId - The ID of the DLQ message to retry
311
+ * @returns response with workflow run information
312
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/callback.mdx
313
+ */
314
+ async retryFailureFunction({ dlqId }: Pick<DLQResumeRestartOptions<string>, "dlqId">) {
315
+ assertNonEmptyId(dlqId, "DLQ id");
316
+ const response = await this.client.http.request<DLQResumeRestartResponse>({
317
+ path: ["v2", "workflows", "dlq", "callback", dlqId],
318
+ method: "POST",
319
+ });
320
+
321
+ return response;
322
+ }
323
+
324
+ /**
325
+ * Cancel the in-progress failure function (failureUrl/failureFunction) call
326
+ * of a workflow run.
327
+ *
328
+ * Fails if the run has no failure function call in progress.
329
+ *
330
+ * @param dlqId - The ID of the DLQ message whose failure function call will be canceled
331
+ */
332
+ async cancelFailureFunction({ dlqId }: Pick<DLQResumeRestartOptions<string>, "dlqId">) {
333
+ assertNonEmptyId(dlqId, "DLQ id");
334
+ try {
335
+ await this.client.http.request({
336
+ path: ["v2", "workflows", "dlq", "callback", dlqId],
337
+ method: "DELETE",
338
+ parseResponseAsJson: false,
339
+ });
340
+ } catch (error) {
341
+ // A successful cancel answers with 302 and an empty body, which the HTTP
342
+ // client rejects. Everything else is a genuine failure.
343
+ if (isInstanceOf(error, QstashError) && error.status === 302) return;
344
+ throw error;
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Delete DLQ messages.
350
+ *
351
+ * Can be called with:
352
+ * - A single dlqId: `delete("id")`
353
+ * - An array of dlqIds: `delete(["id1", "id2"])`
354
+ * - A filter object: `delete({ filter: { label: "my-label", fromDate: 1640995200000 } })`
355
+ * - To target all entries: `delete({ all: true })`
356
+ *
357
+ * Processes up to `count` messages per call (defaults to 100).
358
+ * Call in a loop until cursor is undefined to process all:
359
+ *
360
+ * ```ts
361
+ * let cursor: string | undefined;
362
+ * do {
363
+ * const result = await client.dlq.delete({ all: true, count: 100, cursor });
364
+ * cursor = result.cursor;
365
+ * } while (cursor);
366
+ * ```
367
+ * @see node_modules/@upstash/workflow/docs/basics/client/dlq/delete.mdx
368
+ */
369
+ async delete(request: string | string[] | WorkflowDLQActionFilters) {
370
+ if (typeof request === "string" || Array.isArray(request)) {
371
+ const ids = toNonEmptyIdArray(request, "DLQ id");
372
+ if (ids.length === 0) return { deleted: 0 };
373
+ request = ids;
374
+ }
375
+ const filters: WorkflowDLQActionFilters = Array.isArray(request)
376
+ ? { dlqIds: request }
377
+ : request;
378
+
379
+ return normalizeCursor(
380
+ await this.client.http.request<{ cursor?: string; deleted: number }>({
381
+ path: ["v2", "workflows", "dlq"],
382
+ method: "DELETE",
383
+ query: buildBulkActionQueryParameters(filters),
384
+ })
385
+ );
386
+ }
387
+ }