@upstash/workflow 0.1.1 → 0.1.2-omit-errors

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/astro.js ADDED
@@ -0,0 +1,2160 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // platforms/astro.ts
21
+ var astro_exports = {};
22
+ __export(astro_exports, {
23
+ serve: () => serve2
24
+ });
25
+ module.exports = __toCommonJS(astro_exports);
26
+
27
+ // src/error.ts
28
+ var import_qstash = require("@upstash/qstash");
29
+ var QStashWorkflowError = class extends import_qstash.QstashError {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = "QStashWorkflowError";
33
+ }
34
+ };
35
+ var QStashWorkflowAbort = class extends Error {
36
+ stepInfo;
37
+ stepName;
38
+ constructor(stepName, stepInfo) {
39
+ super(
40
+ `This is an Upstash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${stepName}'.`
41
+ );
42
+ this.name = "QStashWorkflowAbort";
43
+ this.stepName = stepName;
44
+ this.stepInfo = stepInfo;
45
+ }
46
+ };
47
+ var formatWorkflowError = (error) => {
48
+ return error instanceof Error ? {
49
+ error: error.name,
50
+ message: error.message
51
+ } : {
52
+ error: "Error",
53
+ message: "An error occured while executing workflow."
54
+ };
55
+ };
56
+
57
+ // node_modules/neverthrow/dist/index.es.js
58
+ var defaultErrorConfig = {
59
+ withStackTrace: false
60
+ };
61
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
62
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
63
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
64
+ return {
65
+ data,
66
+ message,
67
+ stack: maybeStack
68
+ };
69
+ };
70
+ function __awaiter(thisArg, _arguments, P, generator) {
71
+ function adopt(value) {
72
+ return value instanceof P ? value : new P(function(resolve) {
73
+ resolve(value);
74
+ });
75
+ }
76
+ return new (P || (P = Promise))(function(resolve, reject) {
77
+ function fulfilled(value) {
78
+ try {
79
+ step(generator.next(value));
80
+ } catch (e) {
81
+ reject(e);
82
+ }
83
+ }
84
+ function rejected(value) {
85
+ try {
86
+ step(generator["throw"](value));
87
+ } catch (e) {
88
+ reject(e);
89
+ }
90
+ }
91
+ function step(result) {
92
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
93
+ }
94
+ step((generator = generator.apply(thisArg, [])).next());
95
+ });
96
+ }
97
+ function __values(o) {
98
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
99
+ if (m) return m.call(o);
100
+ if (o && typeof o.length === "number") return {
101
+ next: function() {
102
+ if (o && i >= o.length) o = void 0;
103
+ return { value: o && o[i++], done: !o };
104
+ }
105
+ };
106
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
107
+ }
108
+ function __await(v) {
109
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
110
+ }
111
+ function __asyncGenerator(thisArg, _arguments, generator) {
112
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
113
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
114
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
115
+ return this;
116
+ }, i;
117
+ function verb(n) {
118
+ if (g[n]) i[n] = function(v) {
119
+ return new Promise(function(a, b) {
120
+ q.push([n, v, a, b]) > 1 || resume(n, v);
121
+ });
122
+ };
123
+ }
124
+ function resume(n, v) {
125
+ try {
126
+ step(g[n](v));
127
+ } catch (e) {
128
+ settle(q[0][3], e);
129
+ }
130
+ }
131
+ function step(r) {
132
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
133
+ }
134
+ function fulfill(value) {
135
+ resume("next", value);
136
+ }
137
+ function reject(value) {
138
+ resume("throw", value);
139
+ }
140
+ function settle(f, v) {
141
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
142
+ }
143
+ }
144
+ function __asyncDelegator(o) {
145
+ var i, p;
146
+ return i = {}, verb("next"), verb("throw", function(e) {
147
+ throw e;
148
+ }), verb("return"), i[Symbol.iterator] = function() {
149
+ return this;
150
+ }, i;
151
+ function verb(n, f) {
152
+ i[n] = o[n] ? function(v) {
153
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
154
+ } : f;
155
+ }
156
+ }
157
+ function __asyncValues(o) {
158
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
159
+ var m = o[Symbol.asyncIterator], i;
160
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
161
+ return this;
162
+ }, i);
163
+ function verb(n) {
164
+ i[n] = o[n] && function(v) {
165
+ return new Promise(function(resolve, reject) {
166
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
167
+ });
168
+ };
169
+ }
170
+ function settle(resolve, reject, d, v) {
171
+ Promise.resolve(v).then(function(v2) {
172
+ resolve({ value: v2, done: d });
173
+ }, reject);
174
+ }
175
+ }
176
+ var ResultAsync = class _ResultAsync {
177
+ constructor(res) {
178
+ this._promise = res;
179
+ }
180
+ static fromSafePromise(promise) {
181
+ const newPromise = promise.then((value) => new Ok(value));
182
+ return new _ResultAsync(newPromise);
183
+ }
184
+ static fromPromise(promise, errorFn) {
185
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
186
+ return new _ResultAsync(newPromise);
187
+ }
188
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
189
+ static fromThrowable(fn, errorFn) {
190
+ return (...args) => {
191
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
192
+ try {
193
+ return new Ok(yield fn(...args));
194
+ } catch (error) {
195
+ return new Err(errorFn ? errorFn(error) : error);
196
+ }
197
+ }))());
198
+ };
199
+ }
200
+ static combine(asyncResultList) {
201
+ return combineResultAsyncList(asyncResultList);
202
+ }
203
+ static combineWithAllErrors(asyncResultList) {
204
+ return combineResultAsyncListWithAllErrors(asyncResultList);
205
+ }
206
+ map(f) {
207
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
208
+ if (res.isErr()) {
209
+ return new Err(res.error);
210
+ }
211
+ return new Ok(yield f(res.value));
212
+ })));
213
+ }
214
+ andThrough(f) {
215
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
216
+ if (res.isErr()) {
217
+ return new Err(res.error);
218
+ }
219
+ const newRes = yield f(res.value);
220
+ if (newRes.isErr()) {
221
+ return new Err(newRes.error);
222
+ }
223
+ return new Ok(res.value);
224
+ })));
225
+ }
226
+ andTee(f) {
227
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
228
+ if (res.isErr()) {
229
+ return new Err(res.error);
230
+ }
231
+ try {
232
+ yield f(res.value);
233
+ } catch (e) {
234
+ }
235
+ return new Ok(res.value);
236
+ })));
237
+ }
238
+ mapErr(f) {
239
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
240
+ if (res.isOk()) {
241
+ return new Ok(res.value);
242
+ }
243
+ return new Err(yield f(res.error));
244
+ })));
245
+ }
246
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
247
+ andThen(f) {
248
+ return new _ResultAsync(this._promise.then((res) => {
249
+ if (res.isErr()) {
250
+ return new Err(res.error);
251
+ }
252
+ const newValue = f(res.value);
253
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
254
+ }));
255
+ }
256
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
257
+ orElse(f) {
258
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
259
+ if (res.isErr()) {
260
+ return f(res.error);
261
+ }
262
+ return new Ok(res.value);
263
+ })));
264
+ }
265
+ match(ok2, _err) {
266
+ return this._promise.then((res) => res.match(ok2, _err));
267
+ }
268
+ unwrapOr(t) {
269
+ return this._promise.then((res) => res.unwrapOr(t));
270
+ }
271
+ /**
272
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
273
+ */
274
+ safeUnwrap() {
275
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
276
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
277
+ });
278
+ }
279
+ // Makes ResultAsync implement PromiseLike<Result>
280
+ then(successCallback, failureCallback) {
281
+ return this._promise.then(successCallback, failureCallback);
282
+ }
283
+ };
284
+ var errAsync = (err2) => new ResultAsync(Promise.resolve(new Err(err2)));
285
+ var fromPromise = ResultAsync.fromPromise;
286
+ var fromSafePromise = ResultAsync.fromSafePromise;
287
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
288
+ var combineResultList = (resultList) => {
289
+ let acc = ok([]);
290
+ for (const result of resultList) {
291
+ if (result.isErr()) {
292
+ acc = err(result.error);
293
+ break;
294
+ } else {
295
+ acc.map((list) => list.push(result.value));
296
+ }
297
+ }
298
+ return acc;
299
+ };
300
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
301
+ var combineResultListWithAllErrors = (resultList) => {
302
+ let acc = ok([]);
303
+ for (const result of resultList) {
304
+ if (result.isErr() && acc.isErr()) {
305
+ acc.error.push(result.error);
306
+ } else if (result.isErr() && acc.isOk()) {
307
+ acc = err([result.error]);
308
+ } else if (result.isOk() && acc.isOk()) {
309
+ acc.value.push(result.value);
310
+ }
311
+ }
312
+ return acc;
313
+ };
314
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
315
+ var Result;
316
+ (function(Result2) {
317
+ function fromThrowable2(fn, errorFn) {
318
+ return (...args) => {
319
+ try {
320
+ const result = fn(...args);
321
+ return ok(result);
322
+ } catch (e) {
323
+ return err(errorFn ? errorFn(e) : e);
324
+ }
325
+ };
326
+ }
327
+ Result2.fromThrowable = fromThrowable2;
328
+ function combine(resultList) {
329
+ return combineResultList(resultList);
330
+ }
331
+ Result2.combine = combine;
332
+ function combineWithAllErrors(resultList) {
333
+ return combineResultListWithAllErrors(resultList);
334
+ }
335
+ Result2.combineWithAllErrors = combineWithAllErrors;
336
+ })(Result || (Result = {}));
337
+ var ok = (value) => new Ok(value);
338
+ function err(err2) {
339
+ return new Err(err2);
340
+ }
341
+ var Ok = class {
342
+ constructor(value) {
343
+ this.value = value;
344
+ }
345
+ isOk() {
346
+ return true;
347
+ }
348
+ isErr() {
349
+ return !this.isOk();
350
+ }
351
+ map(f) {
352
+ return ok(f(this.value));
353
+ }
354
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
355
+ mapErr(_f) {
356
+ return ok(this.value);
357
+ }
358
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
359
+ andThen(f) {
360
+ return f(this.value);
361
+ }
362
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
363
+ andThrough(f) {
364
+ return f(this.value).map((_value) => this.value);
365
+ }
366
+ andTee(f) {
367
+ try {
368
+ f(this.value);
369
+ } catch (e) {
370
+ }
371
+ return ok(this.value);
372
+ }
373
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
374
+ orElse(_f) {
375
+ return ok(this.value);
376
+ }
377
+ asyncAndThen(f) {
378
+ return f(this.value);
379
+ }
380
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
381
+ asyncAndThrough(f) {
382
+ return f(this.value).map(() => this.value);
383
+ }
384
+ asyncMap(f) {
385
+ return ResultAsync.fromSafePromise(f(this.value));
386
+ }
387
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
388
+ unwrapOr(_v) {
389
+ return this.value;
390
+ }
391
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
392
+ match(ok2, _err) {
393
+ return ok2(this.value);
394
+ }
395
+ safeUnwrap() {
396
+ const value = this.value;
397
+ return function* () {
398
+ return value;
399
+ }();
400
+ }
401
+ _unsafeUnwrap(_) {
402
+ return this.value;
403
+ }
404
+ _unsafeUnwrapErr(config) {
405
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
406
+ }
407
+ };
408
+ var Err = class {
409
+ constructor(error) {
410
+ this.error = error;
411
+ }
412
+ isOk() {
413
+ return false;
414
+ }
415
+ isErr() {
416
+ return !this.isOk();
417
+ }
418
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
419
+ map(_f) {
420
+ return err(this.error);
421
+ }
422
+ mapErr(f) {
423
+ return err(f(this.error));
424
+ }
425
+ andThrough(_f) {
426
+ return err(this.error);
427
+ }
428
+ andTee(_f) {
429
+ return err(this.error);
430
+ }
431
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
432
+ andThen(_f) {
433
+ return err(this.error);
434
+ }
435
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
436
+ orElse(f) {
437
+ return f(this.error);
438
+ }
439
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
440
+ asyncAndThen(_f) {
441
+ return errAsync(this.error);
442
+ }
443
+ asyncAndThrough(_f) {
444
+ return errAsync(this.error);
445
+ }
446
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
447
+ asyncMap(_f) {
448
+ return errAsync(this.error);
449
+ }
450
+ unwrapOr(v) {
451
+ return v;
452
+ }
453
+ match(_ok, err2) {
454
+ return err2(this.error);
455
+ }
456
+ safeUnwrap() {
457
+ const error = this.error;
458
+ return function* () {
459
+ yield err(error);
460
+ throw new Error("Do not use this generator out of `safeTry`");
461
+ }();
462
+ }
463
+ _unsafeUnwrap(config) {
464
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
465
+ }
466
+ _unsafeUnwrapErr(_) {
467
+ return this.error;
468
+ }
469
+ };
470
+ var fromThrowable = Result.fromThrowable;
471
+
472
+ // src/constants.ts
473
+ var WORKFLOW_ID_HEADER = "Upstash-Workflow-RunId";
474
+ var WORKFLOW_INIT_HEADER = "Upstash-Workflow-Init";
475
+ var WORKFLOW_URL_HEADER = "Upstash-Workflow-Url";
476
+ var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
477
+ var WORKFLOW_FEATURE_HEADER = "Upstash-Feature-Set";
478
+ var WORKFLOW_PROTOCOL_VERSION = "1";
479
+ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
480
+ var DEFAULT_CONTENT_TYPE = "application/json";
481
+ var NO_CONCURRENCY = 1;
482
+ var DEFAULT_RETRIES = 3;
483
+
484
+ // src/types.ts
485
+ var StepTypes = [
486
+ "Initial",
487
+ "Run",
488
+ "SleepFor",
489
+ "SleepUntil",
490
+ "Call",
491
+ "Wait",
492
+ "Notify"
493
+ ];
494
+
495
+ // src/workflow-requests.ts
496
+ var import_qstash2 = require("@upstash/qstash");
497
+ var triggerFirstInvocation = async (workflowContext, retries, debug) => {
498
+ const { headers } = getHeaders(
499
+ "true",
500
+ workflowContext.workflowRunId,
501
+ workflowContext.url,
502
+ workflowContext.headers,
503
+ void 0,
504
+ workflowContext.failureUrl,
505
+ retries
506
+ );
507
+ try {
508
+ const result = await workflowContext.qstashClient.publishJSON({
509
+ headers,
510
+ method: "POST",
511
+ body: workflowContext.requestPayload,
512
+ url: workflowContext.url
513
+ });
514
+ await debug?.log("SUBMIT", "SUBMIT_FIRST_INVOCATION", {
515
+ headers,
516
+ requestPayload: workflowContext.requestPayload,
517
+ url: workflowContext.url,
518
+ messageId: result.messageId
519
+ });
520
+ return ok("success");
521
+ } catch (error) {
522
+ const error_ = error;
523
+ if (error instanceof import_qstash2.QstashError && error.message.includes("a workflow already exists, can not initialize a new one with same id")) {
524
+ await debug?.log("WARN", "SUBMIT_FIRST_INVOCATION", {
525
+ message: `Workflow run ${workflowContext.workflowRunId} already exists.`,
526
+ name: error.name,
527
+ originalMessage: error.message
528
+ });
529
+ return ok("workflow-run-already-exists");
530
+ }
531
+ return err(error_);
532
+ }
533
+ };
534
+ var triggerRouteFunction = async ({
535
+ onCleanup,
536
+ onStep,
537
+ debug
538
+ }) => {
539
+ try {
540
+ await onStep();
541
+ await onCleanup();
542
+ return ok("workflow-finished");
543
+ } catch (error) {
544
+ const error_ = error;
545
+ if (error instanceof import_qstash2.QstashError && error.message.includes("can not append to a a cancelled workflow")) {
546
+ await debug?.log("WARN", "RESPONSE_WORKFLOW", {
547
+ message: `tried to append to a cancelled workflow. exiting without publishing.`,
548
+ name: error.name,
549
+ originalMessage: error.message
550
+ });
551
+ return ok("workflow-was-finished");
552
+ }
553
+ return error_ instanceof QStashWorkflowAbort ? ok("step-finished") : err(error_);
554
+ }
555
+ };
556
+ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
557
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
558
+ deletedWorkflowRunId: workflowContext.workflowRunId
559
+ });
560
+ try {
561
+ await workflowContext.qstashClient.http.request({
562
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
563
+ method: "DELETE",
564
+ parseResponseAsJson: false
565
+ });
566
+ await debug?.log(
567
+ "SUBMIT",
568
+ "SUBMIT_CLEANUP",
569
+ `workflow run ${workflowContext.workflowRunId} deleted.`
570
+ );
571
+ return { deleted: true };
572
+ } catch (error) {
573
+ if (error instanceof import_qstash2.QstashError && error.message.includes(`workflowRun ${workflowContext.workflowRunId} not found`)) {
574
+ await debug?.log("WARN", "SUBMIT_CLEANUP", {
575
+ message: `Failed to remove workflow run ${workflowContext.workflowRunId} as it doesn't exist.`,
576
+ name: error.name,
577
+ originalMessage: error.message
578
+ });
579
+ return { deleted: false };
580
+ }
581
+ throw error;
582
+ }
583
+ };
584
+ var recreateUserHeaders = (headers) => {
585
+ const filteredHeaders = new Headers();
586
+ const pairs = headers.entries();
587
+ for (const [header, value] of pairs) {
588
+ const headerLowerCase = header.toLowerCase();
589
+ if (!headerLowerCase.startsWith("upstash-workflow-") && !headerLowerCase.startsWith("x-vercel-") && !headerLowerCase.startsWith("x-forwarded-") && headerLowerCase !== "cf-connecting-ip") {
590
+ filteredHeaders.append(header, value);
591
+ }
592
+ }
593
+ return filteredHeaders;
594
+ };
595
+ var handleThirdPartyCallResult = async (request, requestPayload, client, workflowUrl, failureUrl, retries, debug) => {
596
+ try {
597
+ if (request.headers.get("Upstash-Workflow-Callback")) {
598
+ const callbackMessage = JSON.parse(requestPayload);
599
+ if (!(callbackMessage.status >= 200 && callbackMessage.status < 300) && callbackMessage.maxRetries && callbackMessage.retried !== callbackMessage.maxRetries) {
600
+ await debug?.log("WARN", "SUBMIT_THIRD_PARTY_RESULT", {
601
+ status: callbackMessage.status,
602
+ body: atob(callbackMessage.body)
603
+ });
604
+ console.warn(
605
+ `Workflow Warning: "context.call" failed with status ${callbackMessage.status} and will retry (retried ${callbackMessage.retried ?? 0} out of ${callbackMessage.maxRetries} times). Error Message:
606
+ ${atob(callbackMessage.body)}`
607
+ );
608
+ return ok("call-will-retry");
609
+ }
610
+ const workflowRunId = request.headers.get(WORKFLOW_ID_HEADER);
611
+ const stepIdString = request.headers.get("Upstash-Workflow-StepId");
612
+ const stepName = request.headers.get("Upstash-Workflow-StepName");
613
+ const stepType = request.headers.get("Upstash-Workflow-StepType");
614
+ const concurrentString = request.headers.get("Upstash-Workflow-Concurrent");
615
+ const contentType = request.headers.get("Upstash-Workflow-ContentType");
616
+ if (!(workflowRunId && stepIdString && stepName && StepTypes.includes(stepType) && concurrentString && contentType)) {
617
+ throw new Error(
618
+ `Missing info in callback message source header: ${JSON.stringify({
619
+ workflowRunId,
620
+ stepIdString,
621
+ stepName,
622
+ stepType,
623
+ concurrentString,
624
+ contentType
625
+ })}`
626
+ );
627
+ }
628
+ const userHeaders = recreateUserHeaders(request.headers);
629
+ const { headers: requestHeaders } = getHeaders(
630
+ "false",
631
+ workflowRunId,
632
+ workflowUrl,
633
+ userHeaders,
634
+ void 0,
635
+ failureUrl,
636
+ retries
637
+ );
638
+ const callResponse = {
639
+ status: callbackMessage.status,
640
+ body: atob(callbackMessage.body),
641
+ header: callbackMessage.header
642
+ };
643
+ const callResultStep = {
644
+ stepId: Number(stepIdString),
645
+ stepName,
646
+ stepType,
647
+ out: JSON.stringify(callResponse),
648
+ concurrent: Number(concurrentString)
649
+ };
650
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
651
+ step: callResultStep,
652
+ headers: requestHeaders,
653
+ url: workflowUrl
654
+ });
655
+ const result = await client.publishJSON({
656
+ headers: requestHeaders,
657
+ method: "POST",
658
+ body: callResultStep,
659
+ url: workflowUrl
660
+ });
661
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
662
+ messageId: result.messageId
663
+ });
664
+ return ok("is-call-return");
665
+ } else {
666
+ return ok("continue-workflow");
667
+ }
668
+ } catch (error) {
669
+ const isCallReturn = request.headers.get("Upstash-Workflow-Callback");
670
+ return err(
671
+ new QStashWorkflowError(
672
+ `Error when handling call return (isCallReturn=${isCallReturn}): ${error}`
673
+ )
674
+ );
675
+ }
676
+ };
677
+ var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step, failureUrl, retries) => {
678
+ const baseHeaders = {
679
+ [WORKFLOW_INIT_HEADER]: initHeaderValue,
680
+ [WORKFLOW_ID_HEADER]: workflowRunId,
681
+ [WORKFLOW_URL_HEADER]: workflowUrl
682
+ };
683
+ if (!step?.callUrl) {
684
+ baseHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
685
+ }
686
+ if (failureUrl) {
687
+ if (!step?.callUrl) {
688
+ baseHeaders[`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`] = "true";
689
+ }
690
+ baseHeaders["Upstash-Failure-Callback"] = failureUrl;
691
+ }
692
+ if (step?.callUrl) {
693
+ baseHeaders["Upstash-Retries"] = "0";
694
+ baseHeaders[WORKFLOW_FEATURE_HEADER] = "WF_NoDelete";
695
+ if (retries) {
696
+ baseHeaders["Upstash-Callback-Retries"] = retries.toString();
697
+ baseHeaders["Upstash-Failure-Callback-Retries"] = retries.toString();
698
+ }
699
+ } else if (retries !== void 0) {
700
+ baseHeaders["Upstash-Retries"] = retries.toString();
701
+ }
702
+ if (userHeaders) {
703
+ for (const header of userHeaders.keys()) {
704
+ if (step?.callHeaders) {
705
+ baseHeaders[`Upstash-Callback-Forward-${header}`] = userHeaders.get(header);
706
+ } else {
707
+ baseHeaders[`Upstash-Forward-${header}`] = userHeaders.get(header);
708
+ }
709
+ }
710
+ }
711
+ const contentType = (userHeaders ? userHeaders.get("Content-Type") : void 0) ?? DEFAULT_CONTENT_TYPE;
712
+ if (step?.callHeaders) {
713
+ const forwardedHeaders = Object.fromEntries(
714
+ Object.entries(step.callHeaders).map(([header, value]) => [
715
+ `Upstash-Forward-${header}`,
716
+ value
717
+ ])
718
+ );
719
+ return {
720
+ headers: {
721
+ ...baseHeaders,
722
+ ...forwardedHeaders,
723
+ "Upstash-Callback": workflowUrl,
724
+ "Upstash-Callback-Workflow-RunId": workflowRunId,
725
+ "Upstash-Callback-Workflow-CallType": "fromCallback",
726
+ "Upstash-Callback-Workflow-Init": "false",
727
+ "Upstash-Callback-Workflow-Url": workflowUrl,
728
+ "Upstash-Callback-Forward-Upstash-Workflow-Callback": "true",
729
+ "Upstash-Callback-Forward-Upstash-Workflow-StepId": step.stepId.toString(),
730
+ "Upstash-Callback-Forward-Upstash-Workflow-StepName": step.stepName,
731
+ "Upstash-Callback-Forward-Upstash-Workflow-StepType": step.stepType,
732
+ "Upstash-Callback-Forward-Upstash-Workflow-Concurrent": step.concurrent.toString(),
733
+ "Upstash-Callback-Forward-Upstash-Workflow-ContentType": contentType,
734
+ "Upstash-Workflow-CallType": "toCallback"
735
+ }
736
+ };
737
+ }
738
+ if (step?.waitEventId) {
739
+ return {
740
+ headers: {
741
+ ...baseHeaders,
742
+ "Upstash-Workflow-CallType": "step"
743
+ },
744
+ timeoutHeaders: {
745
+ // to include user headers:
746
+ ...Object.fromEntries(
747
+ Object.entries(baseHeaders).map(([header, value]) => [header, [value]])
748
+ ),
749
+ // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
750
+ "Upstash-Workflow-Runid": [workflowRunId],
751
+ [WORKFLOW_INIT_HEADER]: ["false"],
752
+ [WORKFLOW_URL_HEADER]: [workflowUrl],
753
+ "Upstash-Workflow-CallType": ["step"],
754
+ "Content-Type": [contentType]
755
+ }
756
+ };
757
+ }
758
+ return { headers: baseHeaders };
759
+ };
760
+ var verifyRequest = async (body, signature, verifier) => {
761
+ if (!verifier) {
762
+ return;
763
+ }
764
+ try {
765
+ if (!signature) {
766
+ throw new Error("`Upstash-Signature` header is not passed.");
767
+ }
768
+ const isValid = await verifier.verify({
769
+ body,
770
+ signature
771
+ });
772
+ if (!isValid) {
773
+ throw new Error("Signature in `Upstash-Signature` header is not valid");
774
+ }
775
+ } catch (error) {
776
+ throw new QStashWorkflowError(
777
+ `Failed to verify that the Workflow request comes from QStash: ${error}
778
+
779
+ If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
780
+
781
+ If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
782
+ );
783
+ }
784
+ };
785
+
786
+ // src/context/auto-executor.ts
787
+ var AutoExecutor = class _AutoExecutor {
788
+ context;
789
+ promises = /* @__PURE__ */ new WeakMap();
790
+ activeLazyStepList;
791
+ debug;
792
+ nonPlanStepCount;
793
+ steps;
794
+ indexInCurrentList = 0;
795
+ stepCount = 0;
796
+ planStepCount = 0;
797
+ executingStep = false;
798
+ constructor(context, steps, debug) {
799
+ this.context = context;
800
+ this.debug = debug;
801
+ this.steps = steps;
802
+ this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
803
+ }
804
+ /**
805
+ * Adds the step function to the list of step functions to run in
806
+ * parallel. After adding the function, defers the execution, so
807
+ * that if there is another step function to be added, it's also
808
+ * added.
809
+ *
810
+ * After all functions are added, list of functions are executed.
811
+ * If there is a single function, it's executed by itself. If there
812
+ * are multiple, they are run in parallel.
813
+ *
814
+ * If a function is already executing (this.executingStep), this
815
+ * means that there is a nested step which is not allowed. In this
816
+ * case, addStep throws QStashWorkflowError.
817
+ *
818
+ * @param stepInfo step plan to add
819
+ * @returns result of the step function
820
+ */
821
+ async addStep(stepInfo) {
822
+ if (this.executingStep) {
823
+ throw new QStashWorkflowError(
824
+ `A step can not be run inside another step. Tried to run '${stepInfo.stepName}' inside '${this.executingStep}'`
825
+ );
826
+ }
827
+ this.stepCount += 1;
828
+ const lazyStepList = this.activeLazyStepList ?? [];
829
+ if (!this.activeLazyStepList) {
830
+ this.activeLazyStepList = lazyStepList;
831
+ this.indexInCurrentList = 0;
832
+ }
833
+ lazyStepList.push(stepInfo);
834
+ const index = this.indexInCurrentList++;
835
+ const requestComplete = this.deferExecution().then(async () => {
836
+ if (!this.promises.has(lazyStepList)) {
837
+ const promise2 = this.getExecutionPromise(lazyStepList);
838
+ this.promises.set(lazyStepList, promise2);
839
+ this.activeLazyStepList = void 0;
840
+ this.planStepCount += lazyStepList.length > 1 ? lazyStepList.length : 0;
841
+ }
842
+ const promise = this.promises.get(lazyStepList);
843
+ return promise;
844
+ });
845
+ const result = await requestComplete;
846
+ return _AutoExecutor.getResult(lazyStepList, result, index);
847
+ }
848
+ /**
849
+ * Wraps a step function to set this.executingStep to step name
850
+ * before running and set this.executingStep to False after execution
851
+ * ends.
852
+ *
853
+ * this.executingStep allows us to detect nested steps which are not
854
+ * allowed.
855
+ *
856
+ * @param stepName name of the step being wrapped
857
+ * @param stepFunction step function to wrap
858
+ * @returns wrapped step function
859
+ */
860
+ wrapStep(stepName, stepFunction) {
861
+ this.executingStep = stepName;
862
+ const result = stepFunction();
863
+ this.executingStep = false;
864
+ return result;
865
+ }
866
+ /**
867
+ * Executes a step:
868
+ * - If the step result is available in the steps, returns the result
869
+ * - If the result is not avaiable, runs the function
870
+ * - Sends the result to QStash
871
+ *
872
+ * @param lazyStep lazy step to execute
873
+ * @returns step result
874
+ */
875
+ async runSingle(lazyStep) {
876
+ if (this.stepCount < this.nonPlanStepCount) {
877
+ const step = this.steps[this.stepCount + this.planStepCount];
878
+ validateStep(lazyStep, step);
879
+ await this.debug?.log("INFO", "RUN_SINGLE", {
880
+ fromRequest: true,
881
+ step,
882
+ stepCount: this.stepCount
883
+ });
884
+ return step.out;
885
+ }
886
+ const resultStep = await lazyStep.getResultStep(NO_CONCURRENCY, this.stepCount);
887
+ await this.debug?.log("INFO", "RUN_SINGLE", {
888
+ fromRequest: false,
889
+ step: resultStep,
890
+ stepCount: this.stepCount
891
+ });
892
+ await this.submitStepsToQStash([resultStep]);
893
+ return resultStep.out;
894
+ }
895
+ /**
896
+ * Runs steps in parallel.
897
+ *
898
+ * @param stepName parallel step name
899
+ * @param stepFunctions list of async functions to run in parallel
900
+ * @returns results of the functions run in parallel
901
+ */
902
+ async runParallel(parallelSteps) {
903
+ const initialStepCount = this.stepCount - (parallelSteps.length - 1);
904
+ const parallelCallState = this.getParallelCallState(parallelSteps.length, initialStepCount);
905
+ const sortedSteps = sortSteps(this.steps);
906
+ const plannedParallelStepCount = sortedSteps[initialStepCount + this.planStepCount]?.concurrent;
907
+ if (parallelCallState !== "first" && plannedParallelStepCount !== parallelSteps.length) {
908
+ throw new QStashWorkflowError(
909
+ `Incompatible number of parallel steps when call state was '${parallelCallState}'. Expected ${parallelSteps.length}, got ${plannedParallelStepCount} from the request.`
910
+ );
911
+ }
912
+ await this.debug?.log("INFO", "RUN_PARALLEL", {
913
+ parallelCallState,
914
+ initialStepCount,
915
+ plannedParallelStepCount,
916
+ stepCount: this.stepCount,
917
+ planStepCount: this.planStepCount
918
+ });
919
+ switch (parallelCallState) {
920
+ case "first": {
921
+ const planSteps = parallelSteps.map(
922
+ (parallelStep, index) => parallelStep.getPlanStep(parallelSteps.length, initialStepCount + index)
923
+ );
924
+ await this.submitStepsToQStash(planSteps);
925
+ break;
926
+ }
927
+ case "partial": {
928
+ const planStep = this.steps.at(-1);
929
+ if (!planStep || planStep.targetStep === void 0) {
930
+ throw new QStashWorkflowError(
931
+ `There must be a last step and it should have targetStep larger than 0.Received: ${JSON.stringify(planStep)}`
932
+ );
933
+ }
934
+ const stepIndex = planStep.targetStep - initialStepCount;
935
+ validateStep(parallelSteps[stepIndex], planStep);
936
+ try {
937
+ const resultStep = await parallelSteps[stepIndex].getResultStep(
938
+ parallelSteps.length,
939
+ planStep.targetStep
940
+ );
941
+ await this.submitStepsToQStash([resultStep]);
942
+ } catch (error) {
943
+ if (error instanceof QStashWorkflowAbort) {
944
+ throw error;
945
+ }
946
+ throw new QStashWorkflowError(
947
+ `Error submitting steps to QStash in partial parallel step execution: ${error}`
948
+ );
949
+ }
950
+ break;
951
+ }
952
+ case "discard": {
953
+ throw new QStashWorkflowAbort("discarded parallel");
954
+ }
955
+ case "last": {
956
+ const parallelResultSteps = sortedSteps.filter((step) => step.stepId >= initialStepCount).slice(0, parallelSteps.length);
957
+ validateParallelSteps(parallelSteps, parallelResultSteps);
958
+ return parallelResultSteps.map((step) => step.out);
959
+ }
960
+ }
961
+ const fillValue = void 0;
962
+ return Array.from({ length: parallelSteps.length }).fill(fillValue);
963
+ }
964
+ /**
965
+ * Determines the parallel call state
966
+ *
967
+ * First filters the steps to get the steps which are after `initialStepCount` parameter.
968
+ *
969
+ * Depending on the remaining steps, decides the parallel state:
970
+ * - "first": If there are no steps
971
+ * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
972
+ * because each step in a parallel execution will have 2 steps: a plan step and a result
973
+ * step.
974
+ * - "partial": If the last step is a plan step
975
+ * - "discard": If the last step is not a plan step. This means that the parallel execution
976
+ * is in progress (there are still steps to run) and one step has finished and submitted
977
+ * its result to QStash
978
+ *
979
+ * @param parallelStepCount number of steps to run in parallel
980
+ * @param initialStepCount steps after the parallel invocation
981
+ * @returns parallel call state
982
+ */
983
+ getParallelCallState(parallelStepCount, initialStepCount) {
984
+ const remainingSteps = this.steps.filter(
985
+ (step) => (step.targetStep || step.stepId) >= initialStepCount
986
+ );
987
+ if (remainingSteps.length === 0) {
988
+ return "first";
989
+ } else if (remainingSteps.length >= 2 * parallelStepCount) {
990
+ return "last";
991
+ } else if (remainingSteps.at(-1)?.targetStep) {
992
+ return "partial";
993
+ } else {
994
+ return "discard";
995
+ }
996
+ }
997
+ /**
998
+ * sends the steps to QStash as batch
999
+ *
1000
+ * @param steps steps to send
1001
+ */
1002
+ async submitStepsToQStash(steps) {
1003
+ if (steps.length === 0) {
1004
+ throw new QStashWorkflowError(
1005
+ `Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
1006
+ );
1007
+ }
1008
+ await this.debug?.log("SUBMIT", "SUBMIT_STEP", {
1009
+ length: steps.length,
1010
+ steps
1011
+ });
1012
+ if (steps[0].waitEventId && steps.length === 1) {
1013
+ const waitStep = steps[0];
1014
+ const { headers, timeoutHeaders } = getHeaders(
1015
+ "false",
1016
+ this.context.workflowRunId,
1017
+ this.context.url,
1018
+ this.context.headers,
1019
+ waitStep,
1020
+ this.context.failureUrl,
1021
+ this.context.retries
1022
+ );
1023
+ const waitBody = {
1024
+ url: this.context.url,
1025
+ timeout: waitStep.timeout,
1026
+ timeoutBody: void 0,
1027
+ timeoutUrl: this.context.url,
1028
+ timeoutHeaders,
1029
+ step: {
1030
+ stepId: waitStep.stepId,
1031
+ stepType: "Wait",
1032
+ stepName: waitStep.stepName,
1033
+ concurrent: waitStep.concurrent,
1034
+ targetStep: waitStep.targetStep
1035
+ }
1036
+ };
1037
+ await this.context.qstashClient.http.request({
1038
+ path: ["v2", "wait", waitStep.waitEventId],
1039
+ body: JSON.stringify(waitBody),
1040
+ headers,
1041
+ method: "POST",
1042
+ parseResponseAsJson: false
1043
+ });
1044
+ throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
1045
+ }
1046
+ const result = await this.context.qstashClient.batchJSON(
1047
+ steps.map((singleStep) => {
1048
+ const { headers } = getHeaders(
1049
+ "false",
1050
+ this.context.workflowRunId,
1051
+ this.context.url,
1052
+ this.context.headers,
1053
+ singleStep,
1054
+ this.context.failureUrl,
1055
+ this.context.retries
1056
+ );
1057
+ const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
1058
+ singleStep.out = JSON.stringify(singleStep.out);
1059
+ return singleStep.callUrl ? (
1060
+ // if the step is a third party call, we call the third party
1061
+ // url (singleStep.callUrl) and pass information about the workflow
1062
+ // in the headers (handled in getHeaders). QStash makes the request
1063
+ // to callUrl and returns the result to Workflow endpoint.
1064
+ // handleThirdPartyCallResult method sends the result of the third
1065
+ // party call to QStash.
1066
+ {
1067
+ headers,
1068
+ method: singleStep.callMethod,
1069
+ body: singleStep.callBody,
1070
+ url: singleStep.callUrl
1071
+ }
1072
+ ) : (
1073
+ // if the step is not a third party call, we use workflow
1074
+ // endpoint (context.url) as URL when calling QStash. QStash
1075
+ // calls us back with the updated steps list.
1076
+ {
1077
+ headers,
1078
+ method: "POST",
1079
+ body: singleStep,
1080
+ url: this.context.url,
1081
+ notBefore: willWait ? singleStep.sleepUntil : void 0,
1082
+ delay: willWait ? singleStep.sleepFor : void 0
1083
+ }
1084
+ );
1085
+ })
1086
+ );
1087
+ await this.debug?.log("INFO", "SUBMIT_STEP", {
1088
+ messageIds: result.map((message) => {
1089
+ return {
1090
+ message: message.messageId
1091
+ };
1092
+ })
1093
+ });
1094
+ throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
1095
+ }
1096
+ /**
1097
+ * Get the promise by executing the lazt steps list. If there is a single
1098
+ * step, we call `runSingle`. Otherwise `runParallel` is called.
1099
+ *
1100
+ * @param lazyStepList steps list to execute
1101
+ * @returns promise corresponding to the execution
1102
+ */
1103
+ getExecutionPromise(lazyStepList) {
1104
+ return lazyStepList.length === 1 ? this.runSingle(lazyStepList[0]) : this.runParallel(lazyStepList);
1105
+ }
1106
+ /**
1107
+ * @param lazyStepList steps we executed
1108
+ * @param result result of the promise from `getExecutionPromise`
1109
+ * @param index index of the current step
1110
+ * @returns result[index] if lazyStepList > 1, otherwise result
1111
+ */
1112
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
1113
+ static getResult(lazyStepList, result, index) {
1114
+ if (lazyStepList.length === 1) {
1115
+ return result;
1116
+ } else if (Array.isArray(result) && lazyStepList.length === result.length && index < lazyStepList.length) {
1117
+ return result[index];
1118
+ } else {
1119
+ throw new QStashWorkflowError(
1120
+ `Unexpected parallel call result while executing step ${index}: '${result}'. Expected ${lazyStepList.length} many items`
1121
+ );
1122
+ }
1123
+ }
1124
+ async deferExecution() {
1125
+ await Promise.resolve();
1126
+ await Promise.resolve();
1127
+ }
1128
+ };
1129
+ var validateStep = (lazyStep, stepFromRequest) => {
1130
+ if (lazyStep.stepName !== stepFromRequest.stepName) {
1131
+ throw new QStashWorkflowError(
1132
+ `Incompatible step name. Expected '${lazyStep.stepName}', got '${stepFromRequest.stepName}' from the request`
1133
+ );
1134
+ }
1135
+ if (lazyStep.stepType !== stepFromRequest.stepType) {
1136
+ throw new QStashWorkflowError(
1137
+ `Incompatible step type. Expected '${lazyStep.stepType}', got '${stepFromRequest.stepType}' from the request`
1138
+ );
1139
+ }
1140
+ };
1141
+ var validateParallelSteps = (lazySteps, stepsFromRequest) => {
1142
+ try {
1143
+ for (const [index, stepFromRequest] of stepsFromRequest.entries()) {
1144
+ validateStep(lazySteps[index], stepFromRequest);
1145
+ }
1146
+ } catch (error) {
1147
+ if (error instanceof QStashWorkflowError) {
1148
+ const lazyStepNames = lazySteps.map((lazyStep) => lazyStep.stepName);
1149
+ const lazyStepTypes = lazySteps.map((lazyStep) => lazyStep.stepType);
1150
+ const requestStepNames = stepsFromRequest.map((step) => step.stepName);
1151
+ const requestStepTypes = stepsFromRequest.map((step) => step.stepType);
1152
+ throw new QStashWorkflowError(
1153
+ `Incompatible steps detected in parallel execution: ${error.message}
1154
+ > Step Names from the request: ${JSON.stringify(requestStepNames)}
1155
+ Step Types from the request: ${JSON.stringify(requestStepTypes)}
1156
+ > Step Names expected: ${JSON.stringify(lazyStepNames)}
1157
+ Step Types expected: ${JSON.stringify(lazyStepTypes)}`
1158
+ );
1159
+ }
1160
+ throw error;
1161
+ }
1162
+ };
1163
+ var sortSteps = (steps) => {
1164
+ const getStepId = (step) => step.targetStep || step.stepId;
1165
+ return steps.toSorted((step, stepOther) => getStepId(step) - getStepId(stepOther));
1166
+ };
1167
+
1168
+ // src/client/utils.ts
1169
+ var makeNotifyRequest = async (requester, eventId, eventData) => {
1170
+ const result = await requester.request({
1171
+ path: ["v2", "notify", eventId],
1172
+ method: "POST",
1173
+ body: typeof eventData === "string" ? eventData : JSON.stringify(eventData)
1174
+ });
1175
+ return result;
1176
+ };
1177
+
1178
+ // src/context/steps.ts
1179
+ var BaseLazyStep = class {
1180
+ stepName;
1181
+ // will be set in the subclasses
1182
+ constructor(stepName) {
1183
+ this.stepName = stepName;
1184
+ }
1185
+ };
1186
+ var LazyFunctionStep = class extends BaseLazyStep {
1187
+ stepFunction;
1188
+ stepType = "Run";
1189
+ constructor(stepName, stepFunction) {
1190
+ super(stepName);
1191
+ this.stepFunction = stepFunction;
1192
+ }
1193
+ getPlanStep(concurrent, targetStep) {
1194
+ return {
1195
+ stepId: 0,
1196
+ stepName: this.stepName,
1197
+ stepType: this.stepType,
1198
+ concurrent,
1199
+ targetStep
1200
+ };
1201
+ }
1202
+ async getResultStep(concurrent, stepId) {
1203
+ let result = this.stepFunction();
1204
+ if (result instanceof Promise) {
1205
+ result = await result;
1206
+ }
1207
+ return {
1208
+ stepId,
1209
+ stepName: this.stepName,
1210
+ stepType: this.stepType,
1211
+ out: result,
1212
+ concurrent
1213
+ };
1214
+ }
1215
+ };
1216
+ var LazySleepStep = class extends BaseLazyStep {
1217
+ sleep;
1218
+ stepType = "SleepFor";
1219
+ constructor(stepName, sleep) {
1220
+ super(stepName);
1221
+ this.sleep = sleep;
1222
+ }
1223
+ getPlanStep(concurrent, targetStep) {
1224
+ return {
1225
+ stepId: 0,
1226
+ stepName: this.stepName,
1227
+ stepType: this.stepType,
1228
+ sleepFor: this.sleep,
1229
+ concurrent,
1230
+ targetStep
1231
+ };
1232
+ }
1233
+ async getResultStep(concurrent, stepId) {
1234
+ return await Promise.resolve({
1235
+ stepId,
1236
+ stepName: this.stepName,
1237
+ stepType: this.stepType,
1238
+ sleepFor: this.sleep,
1239
+ concurrent
1240
+ });
1241
+ }
1242
+ };
1243
+ var LazySleepUntilStep = class extends BaseLazyStep {
1244
+ sleepUntil;
1245
+ stepType = "SleepUntil";
1246
+ constructor(stepName, sleepUntil) {
1247
+ super(stepName);
1248
+ this.sleepUntil = sleepUntil;
1249
+ }
1250
+ getPlanStep(concurrent, targetStep) {
1251
+ return {
1252
+ stepId: 0,
1253
+ stepName: this.stepName,
1254
+ stepType: this.stepType,
1255
+ sleepUntil: this.sleepUntil,
1256
+ concurrent,
1257
+ targetStep
1258
+ };
1259
+ }
1260
+ async getResultStep(concurrent, stepId) {
1261
+ return await Promise.resolve({
1262
+ stepId,
1263
+ stepName: this.stepName,
1264
+ stepType: this.stepType,
1265
+ sleepUntil: this.sleepUntil,
1266
+ concurrent
1267
+ });
1268
+ }
1269
+ };
1270
+ var LazyCallStep = class extends BaseLazyStep {
1271
+ url;
1272
+ method;
1273
+ body;
1274
+ headers;
1275
+ stepType = "Call";
1276
+ constructor(stepName, url, method, body, headers) {
1277
+ super(stepName);
1278
+ this.url = url;
1279
+ this.method = method;
1280
+ this.body = body;
1281
+ this.headers = headers;
1282
+ }
1283
+ getPlanStep(concurrent, targetStep) {
1284
+ return {
1285
+ stepId: 0,
1286
+ stepName: this.stepName,
1287
+ stepType: this.stepType,
1288
+ concurrent,
1289
+ targetStep
1290
+ };
1291
+ }
1292
+ async getResultStep(concurrent, stepId) {
1293
+ return await Promise.resolve({
1294
+ stepId,
1295
+ stepName: this.stepName,
1296
+ stepType: this.stepType,
1297
+ concurrent,
1298
+ callUrl: this.url,
1299
+ callMethod: this.method,
1300
+ callBody: this.body,
1301
+ callHeaders: this.headers
1302
+ });
1303
+ }
1304
+ };
1305
+ var LazyWaitForEventStep = class extends BaseLazyStep {
1306
+ eventId;
1307
+ timeout;
1308
+ stepType = "Wait";
1309
+ constructor(stepName, eventId, timeout) {
1310
+ super(stepName);
1311
+ this.eventId = eventId;
1312
+ this.timeout = timeout;
1313
+ }
1314
+ getPlanStep(concurrent, targetStep) {
1315
+ return {
1316
+ stepId: 0,
1317
+ stepName: this.stepName,
1318
+ stepType: this.stepType,
1319
+ waitEventId: this.eventId,
1320
+ timeout: this.timeout,
1321
+ concurrent,
1322
+ targetStep
1323
+ };
1324
+ }
1325
+ async getResultStep(concurrent, stepId) {
1326
+ return await Promise.resolve({
1327
+ stepId,
1328
+ stepName: this.stepName,
1329
+ stepType: this.stepType,
1330
+ waitEventId: this.eventId,
1331
+ timeout: this.timeout,
1332
+ concurrent
1333
+ });
1334
+ }
1335
+ };
1336
+ var LazyNotifyStep = class extends LazyFunctionStep {
1337
+ stepType = "Notify";
1338
+ constructor(stepName, eventId, eventData, requester) {
1339
+ super(stepName, async () => {
1340
+ const notifyResponse = await makeNotifyRequest(requester, eventId, eventData);
1341
+ return {
1342
+ eventId,
1343
+ eventData,
1344
+ notifyResponse
1345
+ };
1346
+ });
1347
+ }
1348
+ };
1349
+
1350
+ // src/context/context.ts
1351
+ var WorkflowContext = class {
1352
+ executor;
1353
+ steps;
1354
+ /**
1355
+ * QStash client of the workflow
1356
+ *
1357
+ * Can be overwritten by passing `qstashClient` parameter in `serve`:
1358
+ *
1359
+ * ```ts
1360
+ * import { Client } from "@upstash/qstash"
1361
+ *
1362
+ * export const POST = serve(
1363
+ * async (context) => {
1364
+ * ...
1365
+ * },
1366
+ * {
1367
+ * qstashClient: new Client({...})
1368
+ * }
1369
+ * )
1370
+ * ```
1371
+ */
1372
+ qstashClient;
1373
+ /**
1374
+ * Run id of the workflow
1375
+ */
1376
+ workflowRunId;
1377
+ /**
1378
+ * URL of the workflow
1379
+ *
1380
+ * Can be overwritten by passing a `url` parameter in `serve`:
1381
+ *
1382
+ * ```ts
1383
+ * export const POST = serve(
1384
+ * async (context) => {
1385
+ * ...
1386
+ * },
1387
+ * {
1388
+ * url: "new-url-value"
1389
+ * }
1390
+ * )
1391
+ * ```
1392
+ */
1393
+ url;
1394
+ /**
1395
+ * URL to call in case of workflow failure with QStash failure callback
1396
+ *
1397
+ * https://upstash.com/docs/qstash/features/callbacks#what-is-a-failure-callback
1398
+ *
1399
+ * Can be overwritten by passing a `failureUrl` parameter in `serve`:
1400
+ *
1401
+ * ```ts
1402
+ * export const POST = serve(
1403
+ * async (context) => {
1404
+ * ...
1405
+ * },
1406
+ * {
1407
+ * failureUrl: "new-url-value"
1408
+ * }
1409
+ * )
1410
+ * ```
1411
+ */
1412
+ failureUrl;
1413
+ /**
1414
+ * Payload of the request which started the workflow.
1415
+ *
1416
+ * To specify its type, you can define `serve` as follows:
1417
+ *
1418
+ * ```ts
1419
+ * // set requestPayload type to MyPayload:
1420
+ * export const POST = serve<MyPayload>(
1421
+ * async (context) => {
1422
+ * ...
1423
+ * }
1424
+ * )
1425
+ * ```
1426
+ *
1427
+ * By default, `serve` tries to apply `JSON.parse` to the request payload.
1428
+ * If your payload is encoded in a format other than JSON, you can utilize
1429
+ * the `initialPayloadParser` parameter:
1430
+ *
1431
+ * ```ts
1432
+ * export const POST = serve<MyPayload>(
1433
+ * async (context) => {
1434
+ * ...
1435
+ * },
1436
+ * {
1437
+ * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
1438
+ * }
1439
+ * )
1440
+ * ```
1441
+ */
1442
+ requestPayload;
1443
+ /**
1444
+ * headers of the initial request
1445
+ */
1446
+ headers;
1447
+ /**
1448
+ * initial payload as a raw string
1449
+ */
1450
+ rawInitialPayload;
1451
+ /**
1452
+ * Map of environment variables and their values.
1453
+ *
1454
+ * Can be set using the `env` option of serve:
1455
+ *
1456
+ * ```ts
1457
+ * export const POST = serve<MyPayload>(
1458
+ * async (context) => {
1459
+ * const key = context.env["API_KEY"];
1460
+ * },
1461
+ * {
1462
+ * env: {
1463
+ * "API_KEY": "*****";
1464
+ * }
1465
+ * }
1466
+ * )
1467
+ * ```
1468
+ *
1469
+ * Default value is set to `process.env`.
1470
+ */
1471
+ env;
1472
+ /**
1473
+ * Number of retries
1474
+ */
1475
+ retries;
1476
+ constructor({
1477
+ qstashClient,
1478
+ workflowRunId,
1479
+ headers,
1480
+ steps,
1481
+ url,
1482
+ failureUrl,
1483
+ debug,
1484
+ initialPayload,
1485
+ rawInitialPayload,
1486
+ env,
1487
+ retries
1488
+ }) {
1489
+ this.qstashClient = qstashClient;
1490
+ this.workflowRunId = workflowRunId;
1491
+ this.steps = steps;
1492
+ this.url = url;
1493
+ this.failureUrl = failureUrl;
1494
+ this.headers = headers;
1495
+ this.requestPayload = initialPayload;
1496
+ this.rawInitialPayload = rawInitialPayload ?? JSON.stringify(this.requestPayload);
1497
+ this.env = env ?? {};
1498
+ this.retries = retries ?? DEFAULT_RETRIES;
1499
+ this.executor = new AutoExecutor(this, this.steps, debug);
1500
+ }
1501
+ /**
1502
+ * Executes a workflow step
1503
+ *
1504
+ * ```typescript
1505
+ * const result = await context.run("step 1", () => {
1506
+ * return "result"
1507
+ * })
1508
+ * ```
1509
+ *
1510
+ * Can also be called in parallel and the steps will be executed
1511
+ * simulatenously:
1512
+ *
1513
+ * ```typescript
1514
+ * const [result1, result2] = await Promise.all([
1515
+ * context.run("step 1", () => {
1516
+ * return "result1"
1517
+ * })
1518
+ * context.run("step 2", async () => {
1519
+ * return await fetchResults()
1520
+ * })
1521
+ * ])
1522
+ * ```
1523
+ *
1524
+ * @param stepName name of the step
1525
+ * @param stepFunction step function to be executed
1526
+ * @returns result of the step function
1527
+ */
1528
+ async run(stepName, stepFunction) {
1529
+ const wrappedStepFunction = () => this.executor.wrapStep(stepName, stepFunction);
1530
+ return this.addStep(new LazyFunctionStep(stepName, wrappedStepFunction));
1531
+ }
1532
+ /**
1533
+ * Stops the execution for the duration provided.
1534
+ *
1535
+ * @param stepName
1536
+ * @param duration sleep duration in seconds
1537
+ * @returns undefined
1538
+ */
1539
+ async sleep(stepName, duration) {
1540
+ await this.addStep(new LazySleepStep(stepName, duration));
1541
+ }
1542
+ /**
1543
+ * Stops the execution until the date time provided.
1544
+ *
1545
+ * @param stepName
1546
+ * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
1547
+ * as a Date object or a string (passed to `new Date(datetimeString)`)
1548
+ * @returns undefined
1549
+ */
1550
+ async sleepUntil(stepName, datetime) {
1551
+ let time;
1552
+ if (typeof datetime === "number") {
1553
+ time = datetime;
1554
+ } else {
1555
+ datetime = typeof datetime === "string" ? new Date(datetime) : datetime;
1556
+ time = Math.round(datetime.getTime() / 1e3);
1557
+ }
1558
+ await this.addStep(new LazySleepUntilStep(stepName, time));
1559
+ }
1560
+ /**
1561
+ * Makes a third party call through QStash in order to make a
1562
+ * network call without consuming any runtime.
1563
+ *
1564
+ * ```ts
1565
+ * const postResult = await context.call<string>(
1566
+ * "post call step",
1567
+ * `https://www.some-endpoint.com/api`,
1568
+ * "POST",
1569
+ * "my-payload"
1570
+ * );
1571
+ * ```
1572
+ *
1573
+ * tries to parse the result of the request as JSON. If it's
1574
+ * not a JSON which can be parsed, simply returns the response
1575
+ * body as it is.
1576
+ *
1577
+ * @param stepName
1578
+ * @param url url to call
1579
+ * @param method call method
1580
+ * @param body call body
1581
+ * @param headers call headers
1582
+ * @returns call result as {
1583
+ * status: number;
1584
+ * body: unknown;
1585
+ * header: Record<string, string[]>
1586
+ * }
1587
+ */
1588
+ async call(stepName, settings) {
1589
+ const { url, method = "GET", body, headers = {} } = settings;
1590
+ const result = await this.addStep(
1591
+ new LazyCallStep(stepName, url, method, body, headers ?? {})
1592
+ );
1593
+ if (typeof result === "string") {
1594
+ try {
1595
+ const body2 = JSON.parse(result);
1596
+ return {
1597
+ status: 200,
1598
+ header: {},
1599
+ body: body2
1600
+ };
1601
+ } catch {
1602
+ return {
1603
+ status: 200,
1604
+ header: {},
1605
+ body: result
1606
+ };
1607
+ }
1608
+ }
1609
+ try {
1610
+ return {
1611
+ ...result,
1612
+ body: JSON.parse(result.body)
1613
+ };
1614
+ } catch {
1615
+ return result;
1616
+ }
1617
+ }
1618
+ /**
1619
+ * Makes the workflow run wait until a notify request is sent or until the
1620
+ * timeout ends
1621
+ *
1622
+ * ```ts
1623
+ * const { eventData, timeout } = await context.waitForEvent(
1624
+ * "wait for event step",
1625
+ * "my-event-id",
1626
+ * 100 // timeout after 100 seconds
1627
+ * );
1628
+ * ```
1629
+ *
1630
+ * To notify a waiting workflow run, you can use the notify method:
1631
+ *
1632
+ * ```ts
1633
+ * import { Client } from "@upstash/workflow";
1634
+ *
1635
+ * const client = new Client({ token: });
1636
+ *
1637
+ * await client.notify({
1638
+ * eventId: "my-event-id",
1639
+ * eventData: "eventData"
1640
+ * })
1641
+ * ```
1642
+ *
1643
+ * @param stepName
1644
+ * @param eventId event id to wake up the waiting workflow run
1645
+ * @param timeout timeout duration in seconds
1646
+ * @returns wait response as `{ timeout: boolean, eventData: unknown }`.
1647
+ * timeout is true if the wait times out, if notified it is false. eventData
1648
+ * is the value passed to `client.notify`.
1649
+ */
1650
+ async waitForEvent(stepName, eventId, timeout) {
1651
+ const result = await this.addStep(
1652
+ new LazyWaitForEventStep(
1653
+ stepName,
1654
+ eventId,
1655
+ typeof timeout === "string" ? timeout : `${timeout}s`
1656
+ )
1657
+ );
1658
+ try {
1659
+ return {
1660
+ ...result,
1661
+ eventData: JSON.parse(result.eventData)
1662
+ };
1663
+ } catch {
1664
+ return result;
1665
+ }
1666
+ }
1667
+ async notify(stepName, eventId, eventData) {
1668
+ const result = await this.addStep(
1669
+ new LazyNotifyStep(stepName, eventId, eventData, this.qstashClient.http)
1670
+ );
1671
+ try {
1672
+ return {
1673
+ ...result,
1674
+ eventData: JSON.parse(result.eventData)
1675
+ };
1676
+ } catch {
1677
+ return result;
1678
+ }
1679
+ }
1680
+ /**
1681
+ * Adds steps to the executor. Needed so that it can be overwritten in
1682
+ * DisabledWorkflowContext.
1683
+ */
1684
+ async addStep(step) {
1685
+ return await this.executor.addStep(step);
1686
+ }
1687
+ };
1688
+
1689
+ // src/logger.ts
1690
+ var LOG_LEVELS = ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
1691
+ var WorkflowLogger = class _WorkflowLogger {
1692
+ logs = [];
1693
+ options;
1694
+ workflowRunId = void 0;
1695
+ constructor(options) {
1696
+ this.options = options;
1697
+ }
1698
+ async log(level, eventType, details) {
1699
+ if (this.shouldLog(level)) {
1700
+ const timestamp = Date.now();
1701
+ const logEntry = {
1702
+ timestamp,
1703
+ workflowRunId: this.workflowRunId ?? "",
1704
+ logLevel: level,
1705
+ eventType,
1706
+ details
1707
+ };
1708
+ this.logs.push(logEntry);
1709
+ if (this.options.logOutput === "console") {
1710
+ this.writeToConsole(logEntry);
1711
+ }
1712
+ await new Promise((resolve) => setTimeout(resolve, 100));
1713
+ }
1714
+ }
1715
+ setWorkflowRunId(workflowRunId) {
1716
+ this.workflowRunId = workflowRunId;
1717
+ }
1718
+ writeToConsole(logEntry) {
1719
+ const JSON_SPACING = 2;
1720
+ const logMethod = logEntry.logLevel === "ERROR" ? console.error : logEntry.logLevel === "WARN" ? console.warn : console.log;
1721
+ logMethod(JSON.stringify(logEntry, void 0, JSON_SPACING));
1722
+ }
1723
+ shouldLog(level) {
1724
+ return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(this.options.logLevel);
1725
+ }
1726
+ static getLogger(verbose) {
1727
+ if (typeof verbose === "object") {
1728
+ return verbose;
1729
+ } else {
1730
+ return verbose ? new _WorkflowLogger({
1731
+ logLevel: "INFO",
1732
+ logOutput: "console"
1733
+ }) : void 0;
1734
+ }
1735
+ }
1736
+ };
1737
+
1738
+ // src/utils.ts
1739
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1740
+ var NANOID_LENGTH = 21;
1741
+ function nanoid() {
1742
+ return [...crypto.getRandomValues(new Uint8Array(NANOID_LENGTH))].map((x) => NANOID_CHARS[x % NANOID_CHARS.length]).join("");
1743
+ }
1744
+ function decodeBase64(base64) {
1745
+ try {
1746
+ const binString = atob(base64);
1747
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
1748
+ return new TextDecoder().decode(intArray);
1749
+ } catch (error) {
1750
+ console.warn(
1751
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
1752
+ );
1753
+ return atob(base64);
1754
+ }
1755
+ }
1756
+
1757
+ // src/workflow-parser.ts
1758
+ var getPayload = async (request) => {
1759
+ try {
1760
+ return await request.text();
1761
+ } catch {
1762
+ return;
1763
+ }
1764
+ };
1765
+ var parsePayload = (rawPayload) => {
1766
+ const [encodedInitialPayload, ...encodedSteps] = JSON.parse(rawPayload);
1767
+ const rawInitialPayload = decodeBase64(encodedInitialPayload.body);
1768
+ const initialStep = {
1769
+ stepId: 0,
1770
+ stepName: "init",
1771
+ stepType: "Initial",
1772
+ out: rawInitialPayload,
1773
+ concurrent: NO_CONCURRENCY
1774
+ };
1775
+ const stepsToDecode = encodedSteps.filter((step) => step.callType === "step");
1776
+ const otherSteps = stepsToDecode.map((rawStep) => {
1777
+ const step = JSON.parse(decodeBase64(rawStep.body));
1778
+ try {
1779
+ step.out = JSON.parse(step.out);
1780
+ } catch {
1781
+ }
1782
+ if (step.waitEventId) {
1783
+ const newOut = {
1784
+ eventData: step.out ? decodeBase64(step.out) : void 0,
1785
+ timeout: step.waitTimeout ?? false
1786
+ };
1787
+ step.out = newOut;
1788
+ }
1789
+ return step;
1790
+ });
1791
+ const steps = [initialStep, ...otherSteps];
1792
+ return {
1793
+ rawInitialPayload,
1794
+ steps
1795
+ };
1796
+ };
1797
+ var deduplicateSteps = (steps) => {
1798
+ const targetStepIds = [];
1799
+ const stepIds = [];
1800
+ const deduplicatedSteps = [];
1801
+ for (const step of steps) {
1802
+ if (step.stepId === 0) {
1803
+ if (!targetStepIds.includes(step.targetStep ?? 0)) {
1804
+ deduplicatedSteps.push(step);
1805
+ targetStepIds.push(step.targetStep ?? 0);
1806
+ }
1807
+ } else {
1808
+ if (!stepIds.includes(step.stepId)) {
1809
+ deduplicatedSteps.push(step);
1810
+ stepIds.push(step.stepId);
1811
+ }
1812
+ }
1813
+ }
1814
+ return deduplicatedSteps;
1815
+ };
1816
+ var checkIfLastOneIsDuplicate = async (steps, debug) => {
1817
+ if (steps.length < 2) {
1818
+ return false;
1819
+ }
1820
+ const lastStep = steps.at(-1);
1821
+ const lastStepId = lastStep.stepId;
1822
+ const lastTargetStepId = lastStep.targetStep;
1823
+ for (let index = 0; index < steps.length - 1; index++) {
1824
+ const step = steps[index];
1825
+ if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
1826
+ const message = `Upstash Workflow: The step '${step.stepName}' with id '${step.stepId}' has run twice during workflow execution. Rest of the workflow will continue running as usual.`;
1827
+ await debug?.log("WARN", "RESPONSE_DEFAULT", message);
1828
+ console.warn(message);
1829
+ return true;
1830
+ }
1831
+ }
1832
+ return false;
1833
+ };
1834
+ var validateRequest = (request) => {
1835
+ const versionHeader = request.headers.get(WORKFLOW_PROTOCOL_VERSION_HEADER);
1836
+ const isFirstInvocation = !versionHeader;
1837
+ if (!isFirstInvocation && versionHeader !== WORKFLOW_PROTOCOL_VERSION) {
1838
+ throw new QStashWorkflowError(
1839
+ `Incompatible workflow sdk protocol version. Expected ${WORKFLOW_PROTOCOL_VERSION}, got ${versionHeader} from the request.`
1840
+ );
1841
+ }
1842
+ const workflowRunId = isFirstInvocation ? `wfr_${nanoid()}` : request.headers.get(WORKFLOW_ID_HEADER) ?? "";
1843
+ if (workflowRunId.length === 0) {
1844
+ throw new QStashWorkflowError("Couldn't get workflow id from header");
1845
+ }
1846
+ return {
1847
+ isFirstInvocation,
1848
+ workflowRunId
1849
+ };
1850
+ };
1851
+ var parseRequest = async (requestPayload, isFirstInvocation, debug) => {
1852
+ if (isFirstInvocation) {
1853
+ return {
1854
+ rawInitialPayload: requestPayload ?? "",
1855
+ steps: [],
1856
+ isLastDuplicate: false
1857
+ };
1858
+ } else {
1859
+ if (!requestPayload) {
1860
+ throw new QStashWorkflowError("Only first call can have an empty body");
1861
+ }
1862
+ const { rawInitialPayload, steps } = parsePayload(requestPayload);
1863
+ const isLastDuplicate = await checkIfLastOneIsDuplicate(steps, debug);
1864
+ const deduplicatedSteps = deduplicateSteps(steps);
1865
+ return {
1866
+ rawInitialPayload,
1867
+ steps: deduplicatedSteps,
1868
+ isLastDuplicate
1869
+ };
1870
+ }
1871
+ };
1872
+ var handleFailure = async (request, requestPayload, qstashClient, initialPayloadParser, failureFunction, debug) => {
1873
+ if (request.headers.get(WORKFLOW_FAILURE_HEADER) !== "true") {
1874
+ return ok("not-failure-callback");
1875
+ }
1876
+ if (!failureFunction) {
1877
+ return err(
1878
+ new QStashWorkflowError(
1879
+ "Workflow endpoint is called to handle a failure, but a failureFunction is not provided in serve options. Either provide a failureUrl or a failureFunction."
1880
+ )
1881
+ );
1882
+ }
1883
+ try {
1884
+ const { status, header, body, url, sourceHeader, sourceBody, workflowRunId } = JSON.parse(
1885
+ requestPayload
1886
+ );
1887
+ const decodedBody = body ? decodeBase64(body) : "{}";
1888
+ const errorPayload = JSON.parse(decodedBody);
1889
+ const {
1890
+ rawInitialPayload,
1891
+ steps,
1892
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1893
+ isLastDuplicate: _isLastDuplicate
1894
+ } = await parseRequest(decodeBase64(sourceBody), false, debug);
1895
+ const workflowContext = new WorkflowContext({
1896
+ qstashClient,
1897
+ workflowRunId,
1898
+ initialPayload: initialPayloadParser(rawInitialPayload),
1899
+ rawInitialPayload,
1900
+ headers: recreateUserHeaders(new Headers(sourceHeader)),
1901
+ steps,
1902
+ url,
1903
+ failureUrl: url,
1904
+ debug
1905
+ });
1906
+ await failureFunction(workflowContext, status, errorPayload.message, header);
1907
+ } catch (error) {
1908
+ return err(error);
1909
+ }
1910
+ return ok("is-failure-callback");
1911
+ };
1912
+
1913
+ // src/serve/authorization.ts
1914
+ var import_qstash3 = require("@upstash/qstash");
1915
+ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
1916
+ static disabledMessage = "disabled-qstash-worklfow-run";
1917
+ /**
1918
+ * overwrite the WorkflowContext.addStep method to always raise QStashWorkflowAbort
1919
+ * error in order to stop the execution whenever we encounter a step.
1920
+ *
1921
+ * @param _step
1922
+ */
1923
+ async addStep(_step) {
1924
+ throw new QStashWorkflowAbort(_DisabledWorkflowContext.disabledMessage);
1925
+ }
1926
+ /**
1927
+ * copies the passed context to create a DisabledWorkflowContext. Then, runs the
1928
+ * route function with the new context.
1929
+ *
1930
+ * - returns "run-ended" if there are no steps found or
1931
+ * if the auth failed and user called `return`
1932
+ * - returns "step-found" if DisabledWorkflowContext.addStep is called.
1933
+ * - if there is another error, returns the error.
1934
+ *
1935
+ * @param routeFunction
1936
+ */
1937
+ static async tryAuthentication(routeFunction, context) {
1938
+ const disabledContext = new _DisabledWorkflowContext({
1939
+ qstashClient: new import_qstash3.Client({
1940
+ baseUrl: "disabled-client",
1941
+ token: "disabled-client"
1942
+ }),
1943
+ workflowRunId: context.workflowRunId,
1944
+ headers: context.headers,
1945
+ steps: [],
1946
+ url: context.url,
1947
+ failureUrl: context.failureUrl,
1948
+ initialPayload: context.requestPayload,
1949
+ rawInitialPayload: context.rawInitialPayload,
1950
+ env: context.env,
1951
+ retries: context.retries
1952
+ });
1953
+ try {
1954
+ await routeFunction(disabledContext);
1955
+ } catch (error) {
1956
+ if (error instanceof QStashWorkflowAbort && error.stepName === this.disabledMessage) {
1957
+ return ok("step-found");
1958
+ }
1959
+ return err(error);
1960
+ }
1961
+ return ok("run-ended");
1962
+ }
1963
+ };
1964
+
1965
+ // src/serve/options.ts
1966
+ var import_qstash4 = require("@upstash/qstash");
1967
+ var import_qstash5 = require("@upstash/qstash");
1968
+ var processOptions = (options) => {
1969
+ const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
1970
+ const receiverEnvironmentVariablesSet = Boolean(
1971
+ environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
1972
+ );
1973
+ return {
1974
+ qstashClient: new import_qstash5.Client({
1975
+ baseUrl: environment.QSTASH_URL,
1976
+ token: environment.QSTASH_TOKEN
1977
+ }),
1978
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1979
+ onStepFinish: (workflowRunId, _finishCondition) => new Response(JSON.stringify({ workflowRunId }), {
1980
+ status: 200
1981
+ }),
1982
+ initialPayloadParser: (initialRequest) => {
1983
+ if (!initialRequest) {
1984
+ return void 0;
1985
+ }
1986
+ try {
1987
+ return JSON.parse(initialRequest);
1988
+ } catch (error) {
1989
+ if (error instanceof SyntaxError) {
1990
+ return initialRequest;
1991
+ }
1992
+ throw error;
1993
+ }
1994
+ },
1995
+ receiver: receiverEnvironmentVariablesSet ? new import_qstash4.Receiver({
1996
+ currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
1997
+ nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
1998
+ }) : void 0,
1999
+ baseUrl: environment.UPSTASH_WORKFLOW_URL,
2000
+ env: environment,
2001
+ retries: DEFAULT_RETRIES,
2002
+ ...options
2003
+ };
2004
+ };
2005
+ var determineUrls = async (request, url, baseUrl, failureFunction, failureUrl, debug) => {
2006
+ const initialWorkflowUrl = url ?? request.url;
2007
+ const workflowUrl = baseUrl ? initialWorkflowUrl.replace(/^(https?:\/\/[^/]+)(\/.*)?$/, (_, matchedBaseUrl, path) => {
2008
+ return baseUrl + (path || "");
2009
+ }) : initialWorkflowUrl;
2010
+ if (workflowUrl !== initialWorkflowUrl) {
2011
+ await debug?.log("WARN", "ENDPOINT_START", {
2012
+ warning: `Upstash Workflow: replacing the base of the url with "${baseUrl}" and using it as workflow endpoint.`,
2013
+ originalURL: initialWorkflowUrl,
2014
+ updatedURL: workflowUrl
2015
+ });
2016
+ }
2017
+ const workflowFailureUrl = failureFunction ? workflowUrl : failureUrl;
2018
+ return {
2019
+ workflowUrl,
2020
+ workflowFailureUrl
2021
+ };
2022
+ };
2023
+
2024
+ // src/serve/index.ts
2025
+ var serve = (routeFunction, options) => {
2026
+ const {
2027
+ qstashClient,
2028
+ onStepFinish,
2029
+ initialPayloadParser,
2030
+ url,
2031
+ verbose,
2032
+ receiver,
2033
+ failureUrl,
2034
+ failureFunction,
2035
+ baseUrl,
2036
+ env,
2037
+ retries
2038
+ } = processOptions(options);
2039
+ const debug = WorkflowLogger.getLogger(verbose);
2040
+ const handler = async (request) => {
2041
+ await debug?.log("INFO", "ENDPOINT_START");
2042
+ const { workflowUrl, workflowFailureUrl } = await determineUrls(
2043
+ request,
2044
+ url,
2045
+ baseUrl,
2046
+ failureFunction,
2047
+ failureUrl,
2048
+ debug
2049
+ );
2050
+ const requestPayload = await getPayload(request) ?? "";
2051
+ await verifyRequest(requestPayload, request.headers.get("upstash-signature"), receiver);
2052
+ const { isFirstInvocation, workflowRunId } = validateRequest(request);
2053
+ debug?.setWorkflowRunId(workflowRunId);
2054
+ const { rawInitialPayload, steps, isLastDuplicate } = await parseRequest(
2055
+ requestPayload,
2056
+ isFirstInvocation,
2057
+ debug
2058
+ );
2059
+ if (isLastDuplicate) {
2060
+ return onStepFinish("no-workflow-id", "duplicate-step");
2061
+ }
2062
+ const failureCheck = await handleFailure(
2063
+ request,
2064
+ requestPayload,
2065
+ qstashClient,
2066
+ initialPayloadParser,
2067
+ failureFunction
2068
+ );
2069
+ if (failureCheck.isErr()) {
2070
+ throw failureCheck.error;
2071
+ } else if (failureCheck.value === "is-failure-callback") {
2072
+ await debug?.log("WARN", "RESPONSE_DEFAULT", "failureFunction executed");
2073
+ return onStepFinish("no-workflow-id", "failure-callback");
2074
+ }
2075
+ const workflowContext = new WorkflowContext({
2076
+ qstashClient,
2077
+ workflowRunId,
2078
+ initialPayload: initialPayloadParser(rawInitialPayload),
2079
+ rawInitialPayload,
2080
+ headers: recreateUserHeaders(request.headers),
2081
+ steps,
2082
+ url: workflowUrl,
2083
+ failureUrl: workflowFailureUrl,
2084
+ debug,
2085
+ env,
2086
+ retries
2087
+ });
2088
+ const authCheck = await DisabledWorkflowContext.tryAuthentication(
2089
+ routeFunction,
2090
+ workflowContext
2091
+ );
2092
+ if (authCheck.isErr()) {
2093
+ await debug?.log("ERROR", "ERROR", { error: authCheck.error.message });
2094
+ throw authCheck.error;
2095
+ } else if (authCheck.value === "run-ended") {
2096
+ return onStepFinish("no-workflow-id", "auth-fail");
2097
+ }
2098
+ const callReturnCheck = await handleThirdPartyCallResult(
2099
+ request,
2100
+ rawInitialPayload,
2101
+ qstashClient,
2102
+ workflowUrl,
2103
+ workflowFailureUrl,
2104
+ retries,
2105
+ debug
2106
+ );
2107
+ if (callReturnCheck.isErr()) {
2108
+ await debug?.log("ERROR", "SUBMIT_THIRD_PARTY_RESULT", {
2109
+ error: callReturnCheck.error.message
2110
+ });
2111
+ throw callReturnCheck.error;
2112
+ } else if (callReturnCheck.value === "continue-workflow") {
2113
+ const result = isFirstInvocation ? await triggerFirstInvocation(workflowContext, retries, debug) : await triggerRouteFunction({
2114
+ onStep: async () => routeFunction(workflowContext),
2115
+ onCleanup: async () => {
2116
+ await triggerWorkflowDelete(workflowContext, debug);
2117
+ },
2118
+ debug
2119
+ });
2120
+ if (result.isErr()) {
2121
+ await debug?.log("ERROR", "ERROR", { error: result.error.message });
2122
+ throw result.error;
2123
+ }
2124
+ await debug?.log("INFO", "RESPONSE_WORKFLOW");
2125
+ return onStepFinish(workflowContext.workflowRunId, "success");
2126
+ }
2127
+ await debug?.log("INFO", "RESPONSE_DEFAULT");
2128
+ return onStepFinish("no-workflow-id", "fromCallback");
2129
+ };
2130
+ const safeHandler = async (request) => {
2131
+ try {
2132
+ return await handler(request);
2133
+ } catch (error) {
2134
+ console.error(error);
2135
+ return new Response(JSON.stringify(formatWorkflowError(error)), {
2136
+ status: 500
2137
+ });
2138
+ }
2139
+ };
2140
+ return { handler: safeHandler };
2141
+ };
2142
+
2143
+ // src/client/index.ts
2144
+ var import_qstash6 = require("@upstash/qstash");
2145
+
2146
+ // platforms/astro.ts
2147
+ function serve2(routeFunction, options) {
2148
+ const POST = (apiContext) => {
2149
+ const { handler } = serve(
2150
+ (workflowContext) => routeFunction(workflowContext, apiContext),
2151
+ options
2152
+ );
2153
+ return handler(apiContext.request);
2154
+ };
2155
+ return { POST };
2156
+ }
2157
+ // Annotate the CommonJS export names for ESM import in node:
2158
+ 0 && (module.exports = {
2159
+ serve
2160
+ });