@upstash/workflow 0.2.13 → 0.2.15

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.
package/svelte.js CHANGED
@@ -91,7 +91,7 @@ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
91
91
  var DEFAULT_CONTENT_TYPE = "application/json";
92
92
  var NO_CONCURRENCY = 1;
93
93
  var DEFAULT_RETRIES = 3;
94
- var VERSION = "v0.2.13";
94
+ var VERSION = "v0.2.15";
95
95
  var SDK_TELEMETRY = `@upstash/workflow@${VERSION}`;
96
96
  var TELEMETRY_HEADER_SDK = "Upstash-Telemetry-Sdk";
97
97
  var TELEMETRY_HEADER_FRAMEWORK = "Upstash-Telemetry-Framework";
@@ -129,6 +129,16 @@ var WorkflowAbort = class extends Error {
129
129
  this.cancelWorkflow = cancelWorkflow;
130
130
  }
131
131
  };
132
+ var WorkflowNonRetryableError = class extends WorkflowAbort {
133
+ /**
134
+ * @param message error message to be displayed
135
+ */
136
+ constructor(message) {
137
+ super("fail", void 0, false);
138
+ this.name = "WorkflowNonRetryableError";
139
+ if (message) this.message = message;
140
+ }
141
+ };
132
142
  var formatWorkflowError = (error) => {
133
143
  return error instanceof Error ? {
134
144
  error: error.name,
@@ -599,59 +609,72 @@ var StepTypes = [
599
609
 
600
610
  // src/workflow-requests.ts
601
611
  var import_qstash3 = require("@upstash/qstash");
602
- var triggerFirstInvocation = async ({
603
- workflowContext,
604
- useJSONContent,
605
- telemetry: telemetry2,
606
- debug,
607
- invokeCount,
608
- delay
609
- }) => {
610
- const { headers } = getHeaders({
611
- initHeaderValue: "true",
612
- workflowConfig: {
613
- workflowRunId: workflowContext.workflowRunId,
614
- workflowUrl: workflowContext.url,
615
- failureUrl: workflowContext.failureUrl,
616
- retries: workflowContext.retries,
617
- telemetry: telemetry2,
618
- flowControl: workflowContext.flowControl,
619
- useJSONContent: useJSONContent ?? false
620
- },
621
- invokeCount: invokeCount ?? 0,
622
- userHeaders: workflowContext.headers
623
- });
624
- if (workflowContext.headers.get("content-type")) {
625
- headers["content-type"] = workflowContext.headers.get("content-type");
626
- }
627
- if (useJSONContent) {
628
- headers["content-type"] = "application/json";
629
- }
630
- try {
631
- const body = typeof workflowContext.requestPayload === "string" ? workflowContext.requestPayload : JSON.stringify(workflowContext.requestPayload);
632
- const result = await workflowContext.qstashClient.publish({
633
- headers,
634
- method: "POST",
635
- body,
636
- url: workflowContext.url,
637
- delay
638
- });
639
- if (result.deduplicated) {
640
- await debug?.log("WARN", "SUBMIT_FIRST_INVOCATION", {
641
- message: `Workflow run ${workflowContext.workflowRunId} already exists. A new one isn't created.`,
612
+ var triggerFirstInvocation = async (params) => {
613
+ const firstInvocationParams = Array.isArray(params) ? params : [params];
614
+ const workflowContextClient = firstInvocationParams[0].workflowContext.qstashClient;
615
+ const invocationBatch = firstInvocationParams.map(
616
+ ({ workflowContext, useJSONContent, telemetry: telemetry2, invokeCount, delay }) => {
617
+ const { headers } = getHeaders({
618
+ initHeaderValue: "true",
619
+ workflowConfig: {
620
+ workflowRunId: workflowContext.workflowRunId,
621
+ workflowUrl: workflowContext.url,
622
+ failureUrl: workflowContext.failureUrl,
623
+ retries: workflowContext.retries,
624
+ telemetry: telemetry2,
625
+ flowControl: workflowContext.flowControl,
626
+ useJSONContent: useJSONContent ?? false
627
+ },
628
+ invokeCount: invokeCount ?? 0,
629
+ userHeaders: workflowContext.headers
630
+ });
631
+ if (workflowContext.headers.get("content-type")) {
632
+ headers["content-type"] = workflowContext.headers.get("content-type");
633
+ }
634
+ if (useJSONContent) {
635
+ headers["content-type"] = "application/json";
636
+ }
637
+ const body = typeof workflowContext.requestPayload === "string" ? workflowContext.requestPayload : JSON.stringify(workflowContext.requestPayload);
638
+ return {
642
639
  headers,
643
- requestPayload: workflowContext.requestPayload,
640
+ method: "POST",
641
+ body,
644
642
  url: workflowContext.url,
645
- messageId: result.messageId
646
- });
643
+ delay
644
+ };
645
+ }
646
+ );
647
+ try {
648
+ const results = await workflowContextClient.batch(invocationBatch);
649
+ const invocationStatuses = [];
650
+ for (let i = 0; i < results.length; i++) {
651
+ const result = results[i];
652
+ const invocationParams = firstInvocationParams[i];
653
+ if (result.deduplicated) {
654
+ await invocationParams.debug?.log("WARN", "SUBMIT_FIRST_INVOCATION", {
655
+ message: `Workflow run ${invocationParams.workflowContext.workflowRunId} already exists. A new one isn't created.`,
656
+ headers: invocationBatch[i].headers,
657
+ requestPayload: invocationParams.workflowContext.requestPayload,
658
+ url: invocationParams.workflowContext.url,
659
+ messageId: result.messageId
660
+ });
661
+ invocationStatuses.push("workflow-run-already-exists");
662
+ } else {
663
+ await invocationParams.debug?.log("SUBMIT", "SUBMIT_FIRST_INVOCATION", {
664
+ headers: invocationBatch[i].headers,
665
+ requestPayload: invocationParams.workflowContext.requestPayload,
666
+ url: invocationParams.workflowContext.url,
667
+ messageId: result.messageId
668
+ });
669
+ invocationStatuses.push("success");
670
+ }
671
+ }
672
+ const hasAnyDeduplicated = invocationStatuses.some(
673
+ (status) => status === "workflow-run-already-exists"
674
+ );
675
+ if (hasAnyDeduplicated) {
647
676
  return ok("workflow-run-already-exists");
648
677
  } else {
649
- await debug?.log("SUBMIT", "SUBMIT_FIRST_INVOCATION", {
650
- headers,
651
- requestPayload: workflowContext.requestPayload,
652
- url: workflowContext.url,
653
- messageId: result.messageId
654
- });
655
678
  return ok("success");
656
679
  }
657
680
  } catch (error) {
@@ -680,6 +703,8 @@ var triggerRouteFunction = async ({
680
703
  return ok("workflow-was-finished");
681
704
  } else if (!(error_ instanceof WorkflowAbort)) {
682
705
  return err(error_);
706
+ } else if (error_ instanceof WorkflowNonRetryableError) {
707
+ return ok(error_);
683
708
  } else if (error_.cancelWorkflow) {
684
709
  await onCancel();
685
710
  return ok("workflow-finished");
@@ -841,7 +866,7 @@ ${atob(callbackMessage.body ?? "")}`
841
866
  var getTelemetryHeaders = (telemetry2) => {
842
867
  return {
843
868
  [TELEMETRY_HEADER_SDK]: telemetry2.sdk,
844
- [TELEMETRY_HEADER_FRAMEWORK]: telemetry2.framework,
869
+ [TELEMETRY_HEADER_FRAMEWORK]: telemetry2.framework ?? "unknown",
845
870
  [TELEMETRY_HEADER_RUNTIME]: telemetry2.runtime ?? "unknown"
846
871
  };
847
872
  };
@@ -1141,7 +1166,7 @@ var LazyCallStep = class _LazyCallStep extends BaseLazyStep {
1141
1166
  return { header, status, body };
1142
1167
  }
1143
1168
  }
1144
- static applicationHeaders = /* @__PURE__ */ new Set([
1169
+ static applicationContentTypes = [
1145
1170
  "application/json",
1146
1171
  "application/xml",
1147
1172
  "application/javascript",
@@ -1150,12 +1175,12 @@ var LazyCallStep = class _LazyCallStep extends BaseLazyStep {
1150
1175
  "application/ld+json",
1151
1176
  "application/rss+xml",
1152
1177
  "application/atom+xml"
1153
- ]);
1178
+ ];
1154
1179
  static isText = (contentTypeHeader) => {
1155
1180
  if (!contentTypeHeader) {
1156
1181
  return false;
1157
1182
  }
1158
- if (_LazyCallStep.applicationHeaders.has(contentTypeHeader)) {
1183
+ if (_LazyCallStep.applicationContentTypes.some((type) => contentTypeHeader.includes(type))) {
1159
1184
  return true;
1160
1185
  }
1161
1186
  if (contentTypeHeader.startsWith("text/")) {
@@ -2953,10 +2978,10 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
2953
2978
  throw new WorkflowAbort(_DisabledWorkflowContext.disabledMessage);
2954
2979
  }
2955
2980
  /**
2956
- * overwrite cancel method to do nothing
2981
+ * overwrite cancel method to throw WorkflowAbort with the disabledMessage
2957
2982
  */
2958
2983
  async cancel() {
2959
- return;
2984
+ throw new WorkflowAbort(_DisabledWorkflowContext.disabledMessage);
2960
2985
  }
2961
2986
  /**
2962
2987
  * copies the passed context to create a DisabledWorkflowContext. Then, runs the
@@ -2988,7 +3013,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
2988
3013
  try {
2989
3014
  await routeFunction(disabledContext);
2990
3015
  } catch (error) {
2991
- if (error instanceof WorkflowAbort && error.stepName === this.disabledMessage) {
3016
+ if (error instanceof WorkflowAbort && error.stepName === this.disabledMessage || error instanceof WorkflowNonRetryableError) {
2992
3017
  return ok("step-found");
2993
3018
  }
2994
3019
  return err(error);
@@ -3209,6 +3234,13 @@ var processOptions = (options) => {
3209
3234
  status: 400
3210
3235
  }
3211
3236
  );
3237
+ } else if (finishCondition instanceof WorkflowNonRetryableError) {
3238
+ return new Response(JSON.stringify(formatWorkflowError(finishCondition)), {
3239
+ headers: {
3240
+ "Upstash-NonRetryable-Error": "true"
3241
+ },
3242
+ status: 489
3243
+ });
3212
3244
  }
3213
3245
  return new Response(JSON.stringify({ workflowRunId }), {
3214
3246
  status: 200
@@ -3401,6 +3433,9 @@ var serveBase = (routeFunction, telemetry2, options) => {
3401
3433
  },
3402
3434
  debug
3403
3435
  });
3436
+ if (result.isOk() && result.value instanceof WorkflowNonRetryableError) {
3437
+ return onStepFinish(workflowRunId, result.value);
3438
+ }
3404
3439
  if (result.isErr()) {
3405
3440
  await debug?.log("ERROR", "ERROR", { error: result.error.message });
3406
3441
  throw result.error;
package/svelte.mjs CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  SDK_TELEMETRY,
3
3
  serveBase,
4
4
  serveManyBase
5
- } from "./chunk-XVNSBBDC.mjs";
5
+ } from "./chunk-AC5CQCN3.mjs";
6
6
 
7
7
  // platforms/svelte.ts
8
8
  var telemetry = {
@@ -1,9 +1,44 @@
1
- import { PublishRequest, FlowControl, Client, Receiver, HTTPMethods as HTTPMethods$1 } from '@upstash/qstash';
1
+ import { QstashError, PublishRequest, FlowControl, Client, Receiver, HTTPMethods as HTTPMethods$1 } from '@upstash/qstash';
2
2
  import { ZodType, z } from 'zod';
3
3
  import * as ai from 'ai';
4
4
  import { CoreTool, generateText } from 'ai';
5
5
  import { createOpenAI } from '@ai-sdk/openai';
6
6
 
7
+ /**
8
+ * Error raised during Workflow execution
9
+ */
10
+ declare class WorkflowError extends QstashError {
11
+ constructor(message: string);
12
+ }
13
+ /**
14
+ * Raised when the workflow executes a function successfully
15
+ * and aborts to end the execution
16
+ */
17
+ declare class WorkflowAbort extends Error {
18
+ stepInfo?: Step;
19
+ stepName: string;
20
+ /**
21
+ * whether workflow is to be canceled on abort
22
+ */
23
+ cancelWorkflow: boolean;
24
+ /**
25
+ *
26
+ * @param stepName name of the aborting step
27
+ * @param stepInfo step information
28
+ * @param cancelWorkflow
29
+ */
30
+ constructor(stepName: string, stepInfo?: Step, cancelWorkflow?: boolean);
31
+ }
32
+ /**
33
+ * Raised when the workflow is failed due to a non-retryable error
34
+ */
35
+ declare class WorkflowNonRetryableError extends WorkflowAbort {
36
+ /**
37
+ * @param message error message to be displayed
38
+ */
39
+ constructor(message?: string);
40
+ }
41
+
7
42
  declare const LOG_LEVELS: readonly ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
8
43
  type LogLevel = (typeof LOG_LEVELS)[number];
9
44
  type ChatLogEntry = {
@@ -1133,7 +1168,7 @@ type AsyncStepFunction<TResult> = () => Promise<TResult>;
1133
1168
  type StepFunction<TResult> = AsyncStepFunction<TResult> | SyncStepFunction<TResult>;
1134
1169
  type ParallelCallState = "first" | "partial" | "discard" | "last";
1135
1170
  type RouteFunction<TInitialPayload, TResult = unknown> = (context: WorkflowContext<TInitialPayload>) => Promise<TResult>;
1136
- type FinishCondition = "success" | "duplicate-step" | "fromCallback" | "auth-fail" | "failure-callback" | "workflow-already-ended";
1171
+ type FinishCondition = "success" | "duplicate-step" | "fromCallback" | "auth-fail" | "failure-callback" | "workflow-already-ended" | WorkflowNonRetryableError;
1137
1172
  type WorkflowServeOptions<TResponse extends Response = Response, TInitialPayload = unknown> = ValidationOptions<TInitialPayload> & {
1138
1173
  /**
1139
1174
  * QStash client
@@ -1260,7 +1295,7 @@ type Telemetry = {
1260
1295
  /**
1261
1296
  * platform (such as nextjs/cloudflare)
1262
1297
  */
1263
- framework: string;
1298
+ framework?: string;
1264
1299
  /**
1265
1300
  * node version
1266
1301
  */
@@ -1470,4 +1505,4 @@ type InvokableWorkflow<TInitialPayload, TResult> = {
1470
1505
  workflowId?: string;
1471
1506
  };
1472
1507
 
1473
- export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type ExclusiveValidationOptions as E, type FinishCondition as F, type HeaderParams as H, type InvokeWorkflowRequest as I, type LazyInvokeStepParams as L, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type StepType as S, type Telemetry as T, type WorkflowServeOptions as W, type RawStep as a, type Waiter as b, type Step as c, WorkflowTool as d, WorkflowContext as e, type WorkflowClient as f, type WorkflowReceiver as g, StepTypes as h, type SyncStepFunction as i, type StepFunction as j, type PublicServeOptions as k, type FailureFunctionPayload as l, type RequiredExceptFields as m, type WaitRequest as n, type WaitStepResponse as o, type NotifyStepResponse as p, type WaitEventOptions as q, type CallSettings as r, type InvokeStepResponse as s, type InvokableWorkflow as t, type LogLevel as u, type WorkflowLoggerOptions as v, WorkflowLogger as w };
1508
+ export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type ExclusiveValidationOptions as E, type FinishCondition as F, type HeaderParams as H, type InvokeWorkflowRequest as I, type LazyInvokeStepParams as L, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type StepType as S, type Telemetry as T, type WorkflowServeOptions as W, type RawStep as a, type Waiter as b, WorkflowError as c, WorkflowAbort as d, WorkflowNonRetryableError as e, WorkflowTool as f, WorkflowContext as g, type WorkflowClient as h, type WorkflowReceiver as i, StepTypes as j, type Step as k, type SyncStepFunction as l, type StepFunction as m, type PublicServeOptions as n, type FailureFunctionPayload as o, type RequiredExceptFields as p, type WaitRequest as q, type WaitStepResponse as r, type NotifyStepResponse as s, type WaitEventOptions as t, type CallSettings as u, type InvokeStepResponse as v, type InvokableWorkflow as w, type LogLevel as x, type WorkflowLoggerOptions as y, WorkflowLogger as z };
@@ -1,9 +1,44 @@
1
- import { PublishRequest, FlowControl, Client, Receiver, HTTPMethods as HTTPMethods$1 } from '@upstash/qstash';
1
+ import { QstashError, PublishRequest, FlowControl, Client, Receiver, HTTPMethods as HTTPMethods$1 } from '@upstash/qstash';
2
2
  import { ZodType, z } from 'zod';
3
3
  import * as ai from 'ai';
4
4
  import { CoreTool, generateText } from 'ai';
5
5
  import { createOpenAI } from '@ai-sdk/openai';
6
6
 
7
+ /**
8
+ * Error raised during Workflow execution
9
+ */
10
+ declare class WorkflowError extends QstashError {
11
+ constructor(message: string);
12
+ }
13
+ /**
14
+ * Raised when the workflow executes a function successfully
15
+ * and aborts to end the execution
16
+ */
17
+ declare class WorkflowAbort extends Error {
18
+ stepInfo?: Step;
19
+ stepName: string;
20
+ /**
21
+ * whether workflow is to be canceled on abort
22
+ */
23
+ cancelWorkflow: boolean;
24
+ /**
25
+ *
26
+ * @param stepName name of the aborting step
27
+ * @param stepInfo step information
28
+ * @param cancelWorkflow
29
+ */
30
+ constructor(stepName: string, stepInfo?: Step, cancelWorkflow?: boolean);
31
+ }
32
+ /**
33
+ * Raised when the workflow is failed due to a non-retryable error
34
+ */
35
+ declare class WorkflowNonRetryableError extends WorkflowAbort {
36
+ /**
37
+ * @param message error message to be displayed
38
+ */
39
+ constructor(message?: string);
40
+ }
41
+
7
42
  declare const LOG_LEVELS: readonly ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
8
43
  type LogLevel = (typeof LOG_LEVELS)[number];
9
44
  type ChatLogEntry = {
@@ -1133,7 +1168,7 @@ type AsyncStepFunction<TResult> = () => Promise<TResult>;
1133
1168
  type StepFunction<TResult> = AsyncStepFunction<TResult> | SyncStepFunction<TResult>;
1134
1169
  type ParallelCallState = "first" | "partial" | "discard" | "last";
1135
1170
  type RouteFunction<TInitialPayload, TResult = unknown> = (context: WorkflowContext<TInitialPayload>) => Promise<TResult>;
1136
- type FinishCondition = "success" | "duplicate-step" | "fromCallback" | "auth-fail" | "failure-callback" | "workflow-already-ended";
1171
+ type FinishCondition = "success" | "duplicate-step" | "fromCallback" | "auth-fail" | "failure-callback" | "workflow-already-ended" | WorkflowNonRetryableError;
1137
1172
  type WorkflowServeOptions<TResponse extends Response = Response, TInitialPayload = unknown> = ValidationOptions<TInitialPayload> & {
1138
1173
  /**
1139
1174
  * QStash client
@@ -1260,7 +1295,7 @@ type Telemetry = {
1260
1295
  /**
1261
1296
  * platform (such as nextjs/cloudflare)
1262
1297
  */
1263
- framework: string;
1298
+ framework?: string;
1264
1299
  /**
1265
1300
  * node version
1266
1301
  */
@@ -1470,4 +1505,4 @@ type InvokableWorkflow<TInitialPayload, TResult> = {
1470
1505
  workflowId?: string;
1471
1506
  };
1472
1507
 
1473
- export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type ExclusiveValidationOptions as E, type FinishCondition as F, type HeaderParams as H, type InvokeWorkflowRequest as I, type LazyInvokeStepParams as L, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type StepType as S, type Telemetry as T, type WorkflowServeOptions as W, type RawStep as a, type Waiter as b, type Step as c, WorkflowTool as d, WorkflowContext as e, type WorkflowClient as f, type WorkflowReceiver as g, StepTypes as h, type SyncStepFunction as i, type StepFunction as j, type PublicServeOptions as k, type FailureFunctionPayload as l, type RequiredExceptFields as m, type WaitRequest as n, type WaitStepResponse as o, type NotifyStepResponse as p, type WaitEventOptions as q, type CallSettings as r, type InvokeStepResponse as s, type InvokableWorkflow as t, type LogLevel as u, type WorkflowLoggerOptions as v, WorkflowLogger as w };
1508
+ export { type AsyncStepFunction as A, type CallResponse as C, type Duration as D, type ExclusiveValidationOptions as E, type FinishCondition as F, type HeaderParams as H, type InvokeWorkflowRequest as I, type LazyInvokeStepParams as L, type NotifyResponse as N, type ParallelCallState as P, type RouteFunction as R, type StepType as S, type Telemetry as T, type WorkflowServeOptions as W, type RawStep as a, type Waiter as b, WorkflowError as c, WorkflowAbort as d, WorkflowNonRetryableError as e, WorkflowTool as f, WorkflowContext as g, type WorkflowClient as h, type WorkflowReceiver as i, StepTypes as j, type Step as k, type SyncStepFunction as l, type StepFunction as m, type PublicServeOptions as n, type FailureFunctionPayload as o, type RequiredExceptFields as p, type WaitRequest as q, type WaitStepResponse as r, type NotifyStepResponse as s, type WaitEventOptions as t, type CallSettings as u, type InvokeStepResponse as v, type InvokableWorkflow as w, type LogLevel as x, type WorkflowLoggerOptions as y, WorkflowLogger as z };