@upstash/workflow 0.1.2 → 0.1.3-crpyto-canary-2

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