@upstash/workflow 0.1.0

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