@upstash/workflow 0.1.2 → 0.1.3-crpyto-canary

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