@upstash/qstash 2.7.10 → 2.7.11-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/nextjs.js CHANGED
@@ -1,25 +1,2963 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
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/nextjs.ts
31
+ var nextjs_exports = {};
32
+ __export(nextjs_exports, {
33
+ serve: () => serve2,
34
+ servePagesRouter: () => servePagesRouter,
35
+ verifySignature: () => verifySignature,
36
+ verifySignatureAppRouter: () => verifySignatureAppRouter,
37
+ verifySignatureEdge: () => verifySignatureEdge
38
+ });
39
+ module.exports = __toCommonJS(nextjs_exports);
40
+ var import_server = require("next/server");
41
+
42
+ // src/receiver.ts
43
+ var jose = __toESM(require("jose"));
44
+ var import_crypto_js = __toESM(require("crypto-js"));
45
+ var SignatureError = class extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = "SignatureError";
49
+ }
50
+ };
51
+ var Receiver = class {
52
+ currentSigningKey;
53
+ nextSigningKey;
54
+ constructor(config) {
55
+ this.currentSigningKey = config.currentSigningKey;
56
+ this.nextSigningKey = config.nextSigningKey;
57
+ }
58
+ /**
59
+ * Verify the signature of a request.
60
+ *
61
+ * Tries to verify the signature with the current signing key.
62
+ * If that fails, maybe because you have rotated the keys recently, it will
63
+ * try to verify the signature with the next signing key.
64
+ *
65
+ * If that fails, the signature is invalid and a `SignatureError` is thrown.
66
+ */
67
+ async verify(request) {
68
+ const isValid = await this.verifyWithKey(this.currentSigningKey, request);
69
+ if (isValid) {
70
+ return true;
71
+ }
72
+ return this.verifyWithKey(this.nextSigningKey, request);
73
+ }
74
+ /**
75
+ * Verify signature with a specific signing key
76
+ */
77
+ async verifyWithKey(key, request) {
78
+ const jwt = await jose.jwtVerify(request.signature, new TextEncoder().encode(key), {
79
+ issuer: "Upstash",
80
+ clockTolerance: request.clockTolerance
81
+ }).catch((error) => {
82
+ throw new SignatureError(error.message);
83
+ });
84
+ const p = jwt.payload;
85
+ if (request.url !== void 0 && p.sub !== request.url) {
86
+ throw new SignatureError(`invalid subject: ${p.sub}, want: ${request.url}`);
87
+ }
88
+ const bodyHash = import_crypto_js.default.SHA256(request.body).toString(import_crypto_js.default.enc.Base64url);
89
+ const padding = new RegExp(/=+$/);
90
+ if (p.body.replace(padding, "") !== bodyHash.replace(padding, "")) {
91
+ throw new SignatureError(`body hash does not match, want: ${p.body}, got: ${bodyHash}`);
92
+ }
93
+ return true;
94
+ }
95
+ };
96
+
97
+ // src/client/dlq.ts
98
+ var DLQ = class {
99
+ http;
100
+ constructor(http) {
101
+ this.http = http;
102
+ }
103
+ /**
104
+ * List messages in the dlq
105
+ */
106
+ async listMessages(options) {
107
+ const filterPayload = {
108
+ ...options?.filter,
109
+ topicName: options?.filter?.urlGroup
110
+ };
111
+ const messagesPayload = await this.http.request({
112
+ method: "GET",
113
+ path: ["v2", "dlq"],
114
+ query: {
115
+ cursor: options?.cursor,
116
+ count: options?.count,
117
+ ...filterPayload
118
+ }
119
+ });
120
+ return {
121
+ messages: messagesPayload.messages.map((message) => {
122
+ return {
123
+ ...message,
124
+ urlGroup: message.topicName
125
+ };
126
+ }),
127
+ cursor: messagesPayload.cursor
128
+ };
129
+ }
130
+ /**
131
+ * Remove a message from the dlq using it's `dlqId`
132
+ */
133
+ async delete(dlqMessageId) {
134
+ return await this.http.request({
135
+ method: "DELETE",
136
+ path: ["v2", "dlq", dlqMessageId],
137
+ parseResponseAsJson: false
138
+ // there is no response
139
+ });
140
+ }
141
+ /**
142
+ * Remove multiple messages from the dlq using their `dlqId`s
143
+ */
144
+ async deleteMany(request) {
145
+ return await this.http.request({
146
+ method: "DELETE",
147
+ path: ["v2", "dlq"],
148
+ headers: { "Content-Type": "application/json" },
149
+ body: JSON.stringify({ dlqIds: request.dlqIds })
150
+ });
151
+ }
152
+ };
153
+
154
+ // src/client/error.ts
155
+ var QstashError = class extends Error {
156
+ constructor(message) {
157
+ super(message);
158
+ this.name = "QstashError";
159
+ }
160
+ };
161
+ var QstashRatelimitError = class extends QstashError {
162
+ limit;
163
+ remaining;
164
+ reset;
165
+ constructor(args) {
166
+ super(`Exceeded burst rate limit. ${JSON.stringify(args)} `);
167
+ this.name = "QstashRatelimitError";
168
+ this.limit = args.limit;
169
+ this.remaining = args.remaining;
170
+ this.reset = args.reset;
171
+ }
172
+ };
173
+ var QstashChatRatelimitError = class extends QstashError {
174
+ limitRequests;
175
+ limitTokens;
176
+ remainingRequests;
177
+ remainingTokens;
178
+ resetRequests;
179
+ resetTokens;
180
+ constructor(args) {
181
+ super(`Exceeded chat rate limit. ${JSON.stringify(args)} `);
182
+ this.limitRequests = args["limit-requests"];
183
+ this.limitTokens = args["limit-tokens"];
184
+ this.remainingRequests = args["remaining-requests"];
185
+ this.remainingTokens = args["remaining-tokens"];
186
+ this.resetRequests = args["reset-requests"];
187
+ this.resetTokens = args["reset-tokens"];
188
+ }
189
+ };
190
+ var QstashDailyRatelimitError = class extends QstashError {
191
+ limit;
192
+ remaining;
193
+ reset;
194
+ constructor(args) {
195
+ super(`Exceeded daily rate limit. ${JSON.stringify(args)} `);
196
+ this.limit = args.limit;
197
+ this.remaining = args.remaining;
198
+ this.reset = args.reset;
199
+ this.name = "QstashChatRatelimitError";
200
+ }
201
+ };
202
+ var QStashWorkflowError = class extends QstashError {
203
+ constructor(message) {
204
+ super(message);
205
+ this.name = "QStashWorkflowError";
206
+ }
207
+ };
208
+ var QStashWorkflowAbort = class extends Error {
209
+ stepInfo;
210
+ stepName;
211
+ constructor(stepName, stepInfo) {
212
+ super(
213
+ `This is an QStash 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}'.`
214
+ );
215
+ this.name = "QStashWorkflowAbort";
216
+ this.stepName = stepName;
217
+ this.stepInfo = stepInfo;
218
+ }
219
+ };
220
+ var formatWorkflowError = (error) => {
221
+ return error instanceof Error ? {
222
+ error: error.name,
223
+ message: error.message
224
+ } : {
225
+ error: "Error",
226
+ message: "An error occured while executing workflow."
227
+ };
228
+ };
229
+
230
+ // src/client/http.ts
231
+ var HttpClient = class {
232
+ baseUrl;
233
+ authorization;
234
+ options;
235
+ retry;
236
+ constructor(config) {
237
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
238
+ this.authorization = config.authorization;
239
+ this.retry = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
240
+ typeof config.retry === "boolean" && !config.retry ? {
241
+ attempts: 1,
242
+ backoff: () => 0
243
+ } : {
244
+ attempts: config.retry?.retries ? config.retry.retries + 1 : 5,
245
+ backoff: config.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50)
246
+ };
247
+ }
248
+ async request(request) {
249
+ const { response } = await this.requestWithBackoff(request);
250
+ if (request.parseResponseAsJson === false) {
251
+ return void 0;
252
+ }
253
+ return await response.json();
254
+ }
255
+ async *requestStream(request) {
256
+ const { response } = await this.requestWithBackoff(request);
257
+ if (!response.body) {
258
+ throw new Error("No response body");
259
+ }
260
+ const body = response.body;
261
+ const reader = body.getReader();
262
+ const decoder = new TextDecoder();
263
+ try {
264
+ while (true) {
265
+ const { done, value } = await reader.read();
266
+ if (done) {
267
+ break;
268
+ }
269
+ const chunkText = decoder.decode(value, { stream: true });
270
+ const chunks = chunkText.split("\n").filter(Boolean);
271
+ for (const chunk of chunks) {
272
+ if (chunk.startsWith("data: ")) {
273
+ const data = chunk.slice(6);
274
+ if (data === "[DONE]") {
275
+ break;
276
+ }
277
+ yield JSON.parse(data);
278
+ }
279
+ }
280
+ }
281
+ } finally {
282
+ await reader.cancel();
283
+ }
284
+ }
285
+ requestWithBackoff = async (request) => {
286
+ const [url, requestOptions] = this.processRequest(request);
287
+ let response = void 0;
288
+ let error = void 0;
289
+ for (let index = 0; index < this.retry.attempts; index++) {
290
+ try {
291
+ response = await fetch(url.toString(), requestOptions);
292
+ break;
293
+ } catch (error_) {
294
+ error = error_;
295
+ await new Promise((r) => setTimeout(r, this.retry.backoff(index)));
296
+ }
297
+ }
298
+ if (!response) {
299
+ throw error ?? new Error("Exhausted all retries");
300
+ }
301
+ await this.checkResponse(response);
302
+ return {
303
+ response,
304
+ error
305
+ };
306
+ };
307
+ processRequest = (request) => {
308
+ const headers = new Headers(request.headers);
309
+ if (!headers.has("Authorization")) {
310
+ headers.set("Authorization", this.authorization);
311
+ }
312
+ const requestOptions = {
313
+ method: request.method,
314
+ headers,
315
+ body: request.body,
316
+ keepalive: request.keepalive
317
+ };
318
+ const url = new URL([request.baseUrl ?? this.baseUrl, ...request.path].join("/"));
319
+ if (request.query) {
320
+ for (const [key, value] of Object.entries(request.query)) {
321
+ if (value !== void 0) {
322
+ url.searchParams.set(key, value.toString());
323
+ }
324
+ }
325
+ }
326
+ return [url.toString(), requestOptions];
327
+ };
328
+ async checkResponse(response) {
329
+ if (response.status === 429) {
330
+ if (response.headers.get("x-ratelimit-limit-requests")) {
331
+ throw new QstashChatRatelimitError({
332
+ "limit-requests": response.headers.get("x-ratelimit-limit-requests"),
333
+ "limit-tokens": response.headers.get("x-ratelimit-limit-tokens"),
334
+ "remaining-requests": response.headers.get("x-ratelimit-remaining-requests"),
335
+ "remaining-tokens": response.headers.get("x-ratelimit-remaining-tokens"),
336
+ "reset-requests": response.headers.get("x-ratelimit-reset-requests"),
337
+ "reset-tokens": response.headers.get("x-ratelimit-reset-tokens")
338
+ });
339
+ } else if (response.headers.get("RateLimit-Limit")) {
340
+ throw new QstashDailyRatelimitError({
341
+ limit: response.headers.get("RateLimit-Limit"),
342
+ remaining: response.headers.get("RateLimit-Remaining"),
343
+ reset: response.headers.get("RateLimit-Reset")
344
+ });
345
+ }
346
+ throw new QstashRatelimitError({
347
+ limit: response.headers.get("Burst-RateLimit-Limit"),
348
+ remaining: response.headers.get("Burst-RateLimit-Remaining"),
349
+ reset: response.headers.get("Burst-RateLimit-Reset")
350
+ });
351
+ }
352
+ if (response.status < 200 || response.status >= 300) {
353
+ const body = await response.text();
354
+ throw new QstashError(body.length > 0 ? body : `Error: status=${response.status}`);
355
+ }
356
+ }
357
+ };
358
+
359
+ // src/client/llm/providers.ts
360
+ var setupAnalytics = (analytics, providerApiKey, providerBaseUrl, provider) => {
361
+ if (!analytics)
362
+ return {};
363
+ switch (analytics.name) {
364
+ case "helicone": {
365
+ switch (provider) {
366
+ case "upstash": {
367
+ return {
368
+ baseURL: "https://qstash.helicone.ai/llm/v1/chat/completions",
369
+ defaultHeaders: {
370
+ "Helicone-Auth": `Bearer ${analytics.token}`,
371
+ Authorization: `Bearer ${providerApiKey}`
372
+ }
373
+ };
374
+ }
375
+ default: {
376
+ return {
377
+ baseURL: "https://gateway.helicone.ai/v1/chat/completions",
378
+ defaultHeaders: {
379
+ "Helicone-Auth": `Bearer ${analytics.token}`,
380
+ "Helicone-Target-Url": providerBaseUrl,
381
+ Authorization: `Bearer ${providerApiKey}`
382
+ }
383
+ };
384
+ }
385
+ }
386
+ }
387
+ default: {
388
+ throw new Error("Unknown analytics provider");
389
+ }
390
+ }
391
+ };
392
+
393
+ // src/client/llm/chat.ts
394
+ var Chat = class _Chat {
395
+ http;
396
+ token;
397
+ constructor(http, token) {
398
+ this.http = http;
399
+ this.token = token;
400
+ }
401
+ static toChatRequest(request) {
402
+ const messages = [];
403
+ messages.push(
404
+ { role: "system", content: request.system },
405
+ { role: "user", content: request.user }
406
+ );
407
+ const chatRequest = { ...request, messages };
408
+ return chatRequest;
409
+ }
410
+ /**
411
+ * Calls the Upstash completions api given a ChatRequest.
412
+ *
413
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
414
+ * if stream is enabled.
415
+ *
416
+ * @param request ChatRequest with messages
417
+ * @returns Chat completion or stream
418
+ */
419
+ create = async (request) => {
420
+ if (request.provider.owner != "upstash")
421
+ return this.createThirdParty(request);
422
+ const body = JSON.stringify(request);
423
+ let baseUrl = void 0;
424
+ let headers = {
425
+ "Content-Type": "application/json",
426
+ Authorization: `Bearer ${this.token}`,
427
+ ..."stream" in request && request.stream ? {
428
+ Connection: "keep-alive",
429
+ Accept: "text/event-stream",
430
+ "Cache-Control": "no-cache"
431
+ } : {}
432
+ };
433
+ if (request.analytics) {
434
+ const { baseURL, defaultHeaders } = setupAnalytics(
435
+ { name: "helicone", token: request.analytics.token },
436
+ this.getAuthorizationToken(),
437
+ request.provider.baseUrl,
438
+ "upstash"
439
+ );
440
+ headers = { ...headers, ...defaultHeaders };
441
+ baseUrl = baseURL;
442
+ }
443
+ const path = request.analytics ? [] : ["llm", "v1", "chat", "completions"];
444
+ return "stream" in request && request.stream ? this.http.requestStream({
445
+ path,
446
+ method: "POST",
447
+ headers,
448
+ baseUrl,
449
+ body
450
+ }) : this.http.request({
451
+ path,
452
+ method: "POST",
453
+ headers,
454
+ baseUrl,
455
+ body
456
+ });
457
+ };
458
+ /**
459
+ * Calls the Upstash completions api given a ChatRequest.
460
+ *
461
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
462
+ * if stream is enabled.
463
+ *
464
+ * @param request ChatRequest with messages
465
+ * @returns Chat completion or stream
466
+ */
467
+ // eslint-disable-next-line @typescript-eslint/require-await
468
+ createThirdParty = async (request) => {
469
+ const { baseUrl, token, owner } = request.provider;
470
+ if (owner === "upstash")
471
+ throw new Error("Upstash is not 3rd party provider!");
472
+ delete request.provider;
473
+ delete request.system;
474
+ const analytics = request.analytics;
475
+ delete request.analytics;
476
+ const body = JSON.stringify(request);
477
+ const isAnalyticsEnabled = analytics?.name && analytics.token;
478
+ const analyticsConfig = analytics?.name && analytics.token ? setupAnalytics({ name: analytics.name, token: analytics.token }, token, baseUrl, owner) : { defaultHeaders: void 0, baseURL: baseUrl };
479
+ const isStream = "stream" in request && request.stream;
480
+ const headers = {
481
+ "Content-Type": "application/json",
482
+ Authorization: `Bearer ${token}`,
483
+ ...isStream ? {
484
+ Connection: "keep-alive",
485
+ Accept: "text/event-stream",
486
+ "Cache-Control": "no-cache"
487
+ } : {},
488
+ ...analyticsConfig.defaultHeaders
489
+ };
490
+ const response = await this.http[isStream ? "requestStream" : "request"]({
491
+ path: isAnalyticsEnabled ? [] : ["v1", "chat", "completions"],
492
+ method: "POST",
493
+ headers,
494
+ body,
495
+ baseUrl: analyticsConfig.baseURL
496
+ });
497
+ return response;
498
+ };
499
+ // Helper method to get the authorization token
500
+ getAuthorizationToken() {
501
+ const authHeader = String(this.http.authorization);
502
+ const match = /Bearer (.+)/.exec(authHeader);
503
+ if (!match) {
504
+ throw new Error("Invalid authorization header format");
505
+ }
506
+ return match[1];
507
+ }
508
+ /**
509
+ * Calls the Upstash completions api given a PromptRequest.
510
+ *
511
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
512
+ * if stream is enabled.
513
+ *
514
+ * @param request PromptRequest with system and user messages.
515
+ * Note that system parameter shouldn't be passed in the case of
516
+ * mistralai/Mistral-7B-Instruct-v0.2 model.
517
+ * @returns Chat completion or stream
518
+ */
519
+ prompt = async (request) => {
520
+ const chatRequest = _Chat.toChatRequest(request);
521
+ return this.create(chatRequest);
522
+ };
523
+ };
524
+
525
+ // src/client/llm/utils.ts
526
+ function appendLLMOptionsIfNeeded(request, headers, http) {
527
+ if (!request.api)
528
+ return;
529
+ const provider = request.api.provider;
530
+ const analytics = request.api.analytics;
531
+ if (provider?.owner === "upstash") {
532
+ handleUpstashProvider(request, headers, http, analytics);
533
+ return;
534
+ }
535
+ if (!("provider" in request.api))
536
+ return;
537
+ const { baseUrl, token } = validateProviderConfig(provider);
538
+ const analyticsConfig = analytics ? setupAnalytics({ name: analytics.name, token: analytics.token }, token, baseUrl, "custom") : void 0;
539
+ if (analyticsConfig) {
540
+ setAnalyticsHeaders(headers, analyticsConfig);
541
+ request.url = analyticsConfig.baseURL;
542
+ } else {
543
+ request.url = `${baseUrl}/v1/chat/completions`;
544
+ headers.set("Authorization", `Bearer ${token}`);
545
+ }
546
+ }
547
+ function handleUpstashProvider(request, headers, http, analytics) {
548
+ if (analytics) {
549
+ const analyticsConfig = setupAnalytics(
550
+ { name: analytics.name, token: analytics.token },
551
+ //@ts-expect-error hacky way to get bearer token
552
+ String(http.authorization).split("Bearer ")[1],
553
+ request.api?.provider?.baseUrl,
554
+ "upstash"
555
+ );
556
+ setAnalyticsHeaders(headers, analyticsConfig);
557
+ request.url = analyticsConfig.baseURL;
558
+ } else {
559
+ request.api = { name: "llm" };
560
+ }
561
+ }
562
+ function validateProviderConfig(provider) {
563
+ if (!provider?.baseUrl)
564
+ throw new Error("baseUrl cannot be empty or undefined!");
565
+ if (!provider.token)
566
+ throw new Error("token cannot be empty or undefined!");
567
+ return { baseUrl: provider.baseUrl, token: provider.token };
568
+ }
569
+ function setAnalyticsHeaders(headers, analyticsConfig) {
570
+ headers.set("Helicone-Auth", analyticsConfig.defaultHeaders?.["Helicone-Auth"] ?? "");
571
+ headers.set("Authorization", analyticsConfig.defaultHeaders?.Authorization ?? "");
572
+ if (analyticsConfig.defaultHeaders?.["Helicone-Target-Url"]) {
573
+ headers.set("Helicone-Target-Url", analyticsConfig.defaultHeaders["Helicone-Target-Url"]);
574
+ }
575
+ }
576
+ function ensureCallbackPresent(request) {
577
+ if (request.api?.name === "llm" && !request.callback) {
578
+ throw new TypeError("Callback cannot be undefined when using LLM");
579
+ }
580
+ }
581
+
582
+ // src/client/messages.ts
583
+ var Messages = class {
584
+ http;
585
+ constructor(http) {
586
+ this.http = http;
587
+ }
588
+ /**
589
+ * Get a message
590
+ */
591
+ async get(messageId) {
592
+ const messagePayload = await this.http.request({
593
+ method: "GET",
594
+ path: ["v2", "messages", messageId]
595
+ });
596
+ const message = {
597
+ ...messagePayload,
598
+ urlGroup: messagePayload.topicName
599
+ };
600
+ return message;
601
+ }
602
+ /**
603
+ * Cancel a message
604
+ */
605
+ async delete(messageId) {
606
+ return await this.http.request({
607
+ method: "DELETE",
608
+ path: ["v2", "messages", messageId],
609
+ parseResponseAsJson: false
610
+ });
611
+ }
612
+ async deleteMany(messageIds) {
613
+ const result = await this.http.request({
614
+ method: "DELETE",
615
+ path: ["v2", "messages"],
616
+ headers: { "Content-Type": "application/json" },
617
+ body: JSON.stringify({ messageIds })
618
+ });
619
+ return result.cancelled;
620
+ }
621
+ async deleteAll() {
622
+ const result = await this.http.request({
623
+ method: "DELETE",
624
+ path: ["v2", "messages"]
625
+ });
626
+ return result.cancelled;
627
+ }
628
+ };
629
+
630
+ // src/client/utils.ts
631
+ var isIgnoredHeader = (header) => {
632
+ const lowerCaseHeader = header.toLowerCase();
633
+ return lowerCaseHeader.startsWith("content-type") || lowerCaseHeader.startsWith("upstash-");
634
+ };
635
+ function prefixHeaders(headers) {
636
+ const keysToBePrefixed = [...headers.keys()].filter((key) => !isIgnoredHeader(key));
637
+ for (const key of keysToBePrefixed) {
638
+ const value = headers.get(key);
639
+ if (value !== null) {
640
+ headers.set(`Upstash-Forward-${key}`, value);
641
+ }
642
+ headers.delete(key);
643
+ }
644
+ return headers;
645
+ }
646
+ function processHeaders(request) {
647
+ const headers = prefixHeaders(new Headers(request.headers));
648
+ headers.set("Upstash-Method", request.method ?? "POST");
649
+ if (request.delay !== void 0) {
650
+ if (typeof request.delay === "string") {
651
+ headers.set("Upstash-Delay", request.delay);
652
+ } else {
653
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
654
+ }
655
+ }
656
+ if (request.notBefore !== void 0) {
657
+ headers.set("Upstash-Not-Before", request.notBefore.toFixed(0));
658
+ }
659
+ if (request.deduplicationId !== void 0) {
660
+ headers.set("Upstash-Deduplication-Id", request.deduplicationId);
661
+ }
662
+ if (request.contentBasedDeduplication !== void 0) {
663
+ headers.set("Upstash-Content-Based-Deduplication", "true");
664
+ }
665
+ if (request.retries !== void 0) {
666
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
667
+ }
668
+ if (request.callback !== void 0) {
669
+ headers.set("Upstash-Callback", request.callback);
670
+ }
671
+ if (request.failureCallback !== void 0) {
672
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
673
+ }
674
+ if (request.timeout !== void 0) {
675
+ if (typeof request.timeout === "string") {
676
+ headers.set("Upstash-Timeout", request.timeout);
677
+ } else {
678
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
679
+ }
680
+ }
681
+ return headers;
682
+ }
683
+ function getRequestPath(request) {
684
+ return request.url ?? request.urlGroup ?? request.topic ?? `api/${request.api?.name}`;
685
+ }
686
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
687
+ var NANOID_LENGTH = 21;
688
+ function nanoid() {
689
+ return [...crypto.getRandomValues(new Uint8Array(NANOID_LENGTH))].map((x) => NANOID_CHARS[x % NANOID_CHARS.length]).join("");
690
+ }
691
+ function decodeBase64(base64) {
692
+ try {
693
+ const binString = atob(base64);
694
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
695
+ return new TextDecoder().decode(intArray);
696
+ } catch (error) {
697
+ console.warn(
698
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. Error: ${error}`
699
+ );
700
+ return atob(base64);
701
+ }
702
+ }
703
+
704
+ // src/client/queue.ts
705
+ var Queue = class {
706
+ http;
707
+ queueName;
708
+ constructor(http, queueName) {
709
+ this.http = http;
710
+ this.queueName = queueName;
711
+ }
712
+ /**
713
+ * Create or update the queue
714
+ */
715
+ async upsert(request) {
716
+ if (!this.queueName) {
717
+ throw new Error("Please provide a queue name to the Queue constructor");
718
+ }
719
+ const body = {
720
+ queueName: this.queueName,
721
+ parallelism: request.parallelism ?? 1,
722
+ paused: request.paused ?? false
723
+ };
724
+ await this.http.request({
725
+ method: "POST",
726
+ path: ["v2", "queues"],
727
+ headers: {
728
+ "Content-Type": "application/json"
729
+ },
730
+ body: JSON.stringify(body),
731
+ parseResponseAsJson: false
732
+ });
733
+ }
734
+ /**
735
+ * Get the queue details
736
+ */
737
+ async get() {
738
+ if (!this.queueName) {
739
+ throw new Error("Please provide a queue name to the Queue constructor");
740
+ }
741
+ return await this.http.request({
742
+ method: "GET",
743
+ path: ["v2", "queues", this.queueName]
744
+ });
745
+ }
746
+ /**
747
+ * List queues
748
+ */
749
+ async list() {
750
+ return await this.http.request({
751
+ method: "GET",
752
+ path: ["v2", "queues"]
753
+ });
754
+ }
755
+ /**
756
+ * Delete the queue
757
+ */
758
+ async delete() {
759
+ if (!this.queueName) {
760
+ throw new Error("Please provide a queue name to the Queue constructor");
761
+ }
762
+ await this.http.request({
763
+ method: "DELETE",
764
+ path: ["v2", "queues", this.queueName],
765
+ parseResponseAsJson: false
766
+ });
767
+ }
768
+ /**
769
+ * Enqueue a message to a queue.
770
+ */
771
+ async enqueue(request) {
772
+ if (!this.queueName) {
773
+ throw new Error("Please provide a queue name to the Queue constructor");
774
+ }
775
+ const headers = processHeaders(request);
776
+ const destination = getRequestPath(request);
777
+ const response = await this.http.request({
778
+ path: ["v2", "enqueue", this.queueName, destination],
779
+ body: request.body,
780
+ headers,
781
+ method: "POST"
782
+ });
783
+ return response;
784
+ }
785
+ /**
786
+ * Enqueue a message to a queue, serializing the body to JSON.
787
+ */
788
+ async enqueueJSON(request) {
789
+ const headers = prefixHeaders(new Headers(request.headers));
790
+ headers.set("Content-Type", "application/json");
791
+ ensureCallbackPresent(request);
792
+ appendLLMOptionsIfNeeded(request, headers, this.http);
793
+ const response = await this.enqueue({
794
+ ...request,
795
+ body: JSON.stringify(request.body),
796
+ headers
797
+ });
798
+ return response;
799
+ }
800
+ /**
801
+ * Pauses the queue.
802
+ *
803
+ * A paused queue will not deliver messages until
804
+ * it is resumed.
805
+ */
806
+ async pause() {
807
+ if (!this.queueName) {
808
+ throw new Error("Please provide a queue name to the Queue constructor");
809
+ }
810
+ await this.http.request({
811
+ method: "POST",
812
+ path: ["v2", "queues", this.queueName, "pause"],
813
+ parseResponseAsJson: false
814
+ });
815
+ }
816
+ /**
817
+ * Resumes the queue.
818
+ */
819
+ async resume() {
820
+ if (!this.queueName) {
821
+ throw new Error("Please provide a queue name to the Queue constructor");
822
+ }
823
+ await this.http.request({
824
+ method: "POST",
825
+ path: ["v2", "queues", this.queueName, "resume"],
826
+ parseResponseAsJson: false
827
+ });
828
+ }
829
+ };
830
+
831
+ // src/client/schedules.ts
832
+ var Schedules = class {
833
+ http;
834
+ constructor(http) {
835
+ this.http = http;
836
+ }
837
+ /**
838
+ * Create a schedule
839
+ */
840
+ async create(request) {
841
+ const headers = prefixHeaders(new Headers(request.headers));
842
+ if (!headers.has("Content-Type")) {
843
+ headers.set("Content-Type", "application/json");
844
+ }
845
+ headers.set("Upstash-Cron", request.cron);
846
+ if (request.method !== void 0) {
847
+ headers.set("Upstash-Method", request.method);
848
+ }
849
+ if (request.delay !== void 0) {
850
+ if (typeof request.delay === "string") {
851
+ headers.set("Upstash-Delay", request.delay);
852
+ } else {
853
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
854
+ }
855
+ }
856
+ if (request.retries !== void 0) {
857
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
858
+ }
859
+ if (request.callback !== void 0) {
860
+ headers.set("Upstash-Callback", request.callback);
861
+ }
862
+ if (request.failureCallback !== void 0) {
863
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
864
+ }
865
+ if (request.timeout !== void 0) {
866
+ if (typeof request.timeout === "string") {
867
+ headers.set("Upstash-Timeout", request.timeout);
868
+ } else {
869
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
870
+ }
871
+ }
872
+ if (request.scheduleId !== void 0) {
873
+ headers.set("Upstash-Schedule-Id", request.scheduleId);
874
+ }
875
+ return await this.http.request({
876
+ method: "POST",
877
+ headers,
878
+ path: ["v2", "schedules", request.destination],
879
+ body: request.body
880
+ });
881
+ }
882
+ /**
883
+ * Get a schedule
884
+ */
885
+ async get(scheduleId) {
886
+ return await this.http.request({
887
+ method: "GET",
888
+ path: ["v2", "schedules", scheduleId]
889
+ });
890
+ }
891
+ /**
892
+ * List your schedules
893
+ */
894
+ async list() {
895
+ return await this.http.request({
896
+ method: "GET",
897
+ path: ["v2", "schedules"]
898
+ });
899
+ }
900
+ /**
901
+ * Delete a schedule
902
+ */
903
+ async delete(scheduleId) {
904
+ return await this.http.request({
905
+ method: "DELETE",
906
+ path: ["v2", "schedules", scheduleId],
907
+ parseResponseAsJson: false
908
+ });
909
+ }
910
+ /**
911
+ * Pauses the schedule.
912
+ *
913
+ * A paused schedule will not deliver messages until
914
+ * it is resumed.
915
+ */
916
+ async pause({ schedule }) {
917
+ await this.http.request({
918
+ method: "PATCH",
919
+ path: ["v2", "schedules", schedule, "pause"],
920
+ parseResponseAsJson: false
921
+ });
922
+ }
923
+ /**
924
+ * Resumes the schedule.
925
+ */
926
+ async resume({ schedule }) {
927
+ await this.http.request({
928
+ method: "PATCH",
929
+ path: ["v2", "schedules", schedule, "resume"],
930
+ parseResponseAsJson: false
931
+ });
932
+ }
933
+ };
934
+
935
+ // src/client/url-groups.ts
936
+ var UrlGroups = class {
937
+ http;
938
+ constructor(http) {
939
+ this.http = http;
940
+ }
941
+ /**
942
+ * Create a new url group with the given name and endpoints
943
+ */
944
+ async addEndpoints(request) {
945
+ await this.http.request({
946
+ method: "POST",
947
+ path: ["v2", "topics", request.name, "endpoints"],
948
+ headers: { "Content-Type": "application/json" },
949
+ body: JSON.stringify({ endpoints: request.endpoints }),
950
+ parseResponseAsJson: false
951
+ });
952
+ }
953
+ /**
954
+ * Remove endpoints from a url group.
955
+ */
956
+ async removeEndpoints(request) {
957
+ await this.http.request({
958
+ method: "DELETE",
959
+ path: ["v2", "topics", request.name, "endpoints"],
960
+ headers: { "Content-Type": "application/json" },
961
+ body: JSON.stringify({ endpoints: request.endpoints }),
962
+ parseResponseAsJson: false
963
+ });
964
+ }
965
+ /**
966
+ * Get a list of all url groups.
967
+ */
968
+ async list() {
969
+ return await this.http.request({
970
+ method: "GET",
971
+ path: ["v2", "topics"]
972
+ });
973
+ }
974
+ /**
975
+ * Get a single url group
976
+ */
977
+ async get(name) {
978
+ return await this.http.request({
979
+ method: "GET",
980
+ path: ["v2", "topics", name]
981
+ });
982
+ }
983
+ /**
984
+ * Delete a url group
985
+ */
986
+ async delete(name) {
987
+ return await this.http.request({
988
+ method: "DELETE",
989
+ path: ["v2", "topics", name],
990
+ parseResponseAsJson: false
991
+ });
992
+ }
993
+ };
994
+
995
+ // src/client/client.ts
996
+ var Client = class {
997
+ http;
998
+ token;
999
+ constructor(config) {
1000
+ this.http = new HttpClient({
1001
+ retry: config.retry,
1002
+ baseUrl: config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "https://qstash.upstash.io",
1003
+ authorization: `Bearer ${config.token}`
1004
+ });
1005
+ this.token = config.token;
1006
+ }
1007
+ /**
1008
+ * Access the urlGroup API.
1009
+ *
1010
+ * Create, read, update or delete urlGroups.
1011
+ */
1012
+ get urlGroups() {
1013
+ return new UrlGroups(this.http);
1014
+ }
1015
+ /**
1016
+ * Deprecated. Use urlGroups instead.
1017
+ *
1018
+ * Access the topic API.
1019
+ *
1020
+ * Create, read, update or delete topics.
1021
+ */
1022
+ get topics() {
1023
+ return this.urlGroups;
1024
+ }
1025
+ /**
1026
+ * Access the dlq API.
1027
+ *
1028
+ * List or remove messages from the DLQ.
1029
+ */
1030
+ get dlq() {
1031
+ return new DLQ(this.http);
1032
+ }
1033
+ /**
1034
+ * Access the message API.
1035
+ *
1036
+ * Read or cancel messages.
1037
+ */
1038
+ get messages() {
1039
+ return new Messages(this.http);
1040
+ }
1041
+ /**
1042
+ * Access the schedule API.
1043
+ *
1044
+ * Create, read or delete schedules.
1045
+ */
1046
+ get schedules() {
1047
+ return new Schedules(this.http);
1048
+ }
1049
+ /**
1050
+ * Access the workflow API.
1051
+ *
1052
+ * cancel workflows.
1053
+ */
1054
+ get workflow() {
1055
+ return new Workflow(this.http);
1056
+ }
1057
+ /**
1058
+ * Access the queue API.
1059
+ *
1060
+ * Create, read, update or delete queues.
1061
+ */
1062
+ queue(request) {
1063
+ return new Queue(this.http, request?.queueName);
1064
+ }
1065
+ /**
1066
+ * Access the Chat API
1067
+ *
1068
+ * Call the create or prompt methods
1069
+ */
1070
+ chat() {
1071
+ return new Chat(this.http, this.token);
1072
+ }
1073
+ async publish(request) {
1074
+ const headers = processHeaders(request);
1075
+ const response = await this.http.request({
1076
+ path: ["v2", "publish", getRequestPath(request)],
1077
+ body: request.body,
1078
+ headers,
1079
+ method: "POST"
1080
+ });
1081
+ return response;
1082
+ }
1083
+ /**
1084
+ * publishJSON is a utility wrapper around `publish` that automatically serializes the body
1085
+ * and sets the `Content-Type` header to `application/json`.
1086
+ */
1087
+ async publishJSON(request) {
1088
+ const headers = prefixHeaders(new Headers(request.headers));
1089
+ headers.set("Content-Type", "application/json");
1090
+ ensureCallbackPresent(request);
1091
+ appendLLMOptionsIfNeeded(request, headers, this.http);
1092
+ const response = await this.publish({
1093
+ ...request,
1094
+ headers,
1095
+ body: JSON.stringify(request.body)
1096
+ });
1097
+ return response;
1098
+ }
1099
+ /**
1100
+ * Batch publish messages to QStash.
1101
+ */
1102
+ async batch(request) {
1103
+ const messages = [];
1104
+ for (const message of request) {
1105
+ const headers = processHeaders(message);
1106
+ const headerEntries = Object.fromEntries(headers.entries());
1107
+ messages.push({
1108
+ destination: getRequestPath(message),
1109
+ headers: headerEntries,
1110
+ body: message.body,
1111
+ ...message.queueName && { queue: message.queueName }
1112
+ });
1113
+ }
1114
+ const response = await this.http.request({
1115
+ path: ["v2", "batch"],
1116
+ body: JSON.stringify(messages),
1117
+ headers: {
1118
+ "Content-Type": "application/json"
1119
+ },
1120
+ method: "POST"
1121
+ });
1122
+ const arrayResposne = Array.isArray(response) ? response : [response];
1123
+ return arrayResposne;
1124
+ }
1125
+ /**
1126
+ * Batch publish messages to QStash, serializing each body to JSON.
1127
+ */
1128
+ async batchJSON(request) {
1129
+ for (const message of request) {
1130
+ if ("body" in message) {
1131
+ message.body = JSON.stringify(message.body);
1132
+ }
1133
+ message.headers = new Headers(message.headers);
1134
+ ensureCallbackPresent(message);
1135
+ appendLLMOptionsIfNeeded(message, message.headers, this.http);
1136
+ message.headers.set("Content-Type", "application/json");
1137
+ }
1138
+ const response = await this.batch(request);
1139
+ return response;
1140
+ }
1141
+ /**
1142
+ * Retrieve your logs.
1143
+ *
1144
+ * The logs endpoint is paginated and returns only 100 logs at a time.
1145
+ * If you want to receive more logs, you can use the cursor to paginate.
1146
+ *
1147
+ * The cursor is a unix timestamp with millisecond precision
1148
+ *
1149
+ * @example
1150
+ * ```ts
1151
+ * let cursor = Date.now()
1152
+ * const logs: Log[] = []
1153
+ * while (cursor > 0) {
1154
+ * const res = await qstash.logs({ cursor })
1155
+ * logs.push(...res.logs)
1156
+ * cursor = res.cursor ?? 0
1157
+ * }
1158
+ * ```
1159
+ */
1160
+ async events(request) {
1161
+ const query = {};
1162
+ if (typeof request?.cursor === "number" && request.cursor > 0) {
1163
+ query.cursor = request.cursor.toString();
1164
+ } else if (typeof request?.cursor === "string" && request.cursor !== "") {
1165
+ query.cursor = request.cursor;
1166
+ }
1167
+ for (const [key, value] of Object.entries(request?.filter ?? {})) {
1168
+ if (typeof value === "number" && value < 0) {
1169
+ continue;
1170
+ }
1171
+ if (key === "urlGroup") {
1172
+ query.topicName = value.toString();
1173
+ } else if (typeof value !== "undefined") {
1174
+ query[key] = value.toString();
1175
+ }
1176
+ }
1177
+ const responsePayload = await this.http.request({
1178
+ path: ["v2", "events"],
1179
+ method: "GET",
1180
+ query
1181
+ });
1182
+ return {
1183
+ cursor: responsePayload.cursor,
1184
+ events: responsePayload.events.map((event) => {
1185
+ return {
1186
+ ...event,
1187
+ urlGroup: event.topicName
1188
+ };
1189
+ })
1190
+ };
1191
+ }
1192
+ };
1193
+
1194
+ // src/client/workflow/constants.ts
1195
+ var WORKFLOW_ID_HEADER = "Upstash-Workflow-RunId";
1196
+ var WORKFLOW_INIT_HEADER = "Upstash-Workflow-Init";
1197
+ var WORKFLOW_URL_HEADER = "Upstash-Workflow-Url";
1198
+ var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
1199
+ var WORKFLOW_PROTOCOL_VERSION = "1";
1200
+ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
1201
+ var DEFAULT_CONTENT_TYPE = "application/json";
1202
+ var NO_CONCURRENCY = 1;
1203
+ var DEFAULT_RETRIES = 3;
1204
+
1205
+ // node_modules/neverthrow/dist/index.es.js
1206
+ var defaultErrorConfig = {
1207
+ withStackTrace: false
1208
+ };
1209
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
1210
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
1211
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
1212
+ return {
1213
+ data,
1214
+ message,
1215
+ stack: maybeStack
1216
+ };
1217
+ };
1218
+ function __awaiter(thisArg, _arguments, P, generator) {
1219
+ function adopt(value) {
1220
+ return value instanceof P ? value : new P(function(resolve) {
1221
+ resolve(value);
1222
+ });
1223
+ }
1224
+ return new (P || (P = Promise))(function(resolve, reject) {
1225
+ function fulfilled(value) {
1226
+ try {
1227
+ step(generator.next(value));
1228
+ } catch (e) {
1229
+ reject(e);
1230
+ }
1231
+ }
1232
+ function rejected(value) {
1233
+ try {
1234
+ step(generator["throw"](value));
1235
+ } catch (e) {
1236
+ reject(e);
1237
+ }
1238
+ }
1239
+ function step(result) {
1240
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1241
+ }
1242
+ step((generator = generator.apply(thisArg, [])).next());
1243
+ });
1244
+ }
1245
+ function __values(o) {
1246
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
1247
+ if (m)
1248
+ return m.call(o);
1249
+ if (o && typeof o.length === "number")
1250
+ return {
1251
+ next: function() {
1252
+ if (o && i >= o.length)
1253
+ o = void 0;
1254
+ return { value: o && o[i++], done: !o };
1255
+ }
1256
+ };
1257
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1258
+ }
1259
+ function __await(v) {
1260
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
1261
+ }
1262
+ function __asyncGenerator(thisArg, _arguments, generator) {
1263
+ if (!Symbol.asyncIterator)
1264
+ throw new TypeError("Symbol.asyncIterator is not defined.");
1265
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
1266
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
1267
+ return this;
1268
+ }, i;
1269
+ function verb(n) {
1270
+ if (g[n])
1271
+ i[n] = function(v) {
1272
+ return new Promise(function(a, b) {
1273
+ q.push([n, v, a, b]) > 1 || resume(n, v);
1274
+ });
1275
+ };
1276
+ }
1277
+ function resume(n, v) {
1278
+ try {
1279
+ step(g[n](v));
1280
+ } catch (e) {
1281
+ settle(q[0][3], e);
1282
+ }
1283
+ }
1284
+ function step(r) {
1285
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
1286
+ }
1287
+ function fulfill(value) {
1288
+ resume("next", value);
1289
+ }
1290
+ function reject(value) {
1291
+ resume("throw", value);
1292
+ }
1293
+ function settle(f, v) {
1294
+ if (f(v), q.shift(), q.length)
1295
+ resume(q[0][0], q[0][1]);
1296
+ }
1297
+ }
1298
+ function __asyncDelegator(o) {
1299
+ var i, p;
1300
+ return i = {}, verb("next"), verb("throw", function(e) {
1301
+ throw e;
1302
+ }), verb("return"), i[Symbol.iterator] = function() {
1303
+ return this;
1304
+ }, i;
1305
+ function verb(n, f) {
1306
+ i[n] = o[n] ? function(v) {
1307
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
1308
+ } : f;
1309
+ }
1310
+ }
1311
+ function __asyncValues(o) {
1312
+ if (!Symbol.asyncIterator)
1313
+ throw new TypeError("Symbol.asyncIterator is not defined.");
1314
+ var m = o[Symbol.asyncIterator], i;
1315
+ 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() {
1316
+ return this;
1317
+ }, i);
1318
+ function verb(n) {
1319
+ i[n] = o[n] && function(v) {
1320
+ return new Promise(function(resolve, reject) {
1321
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
1322
+ });
1323
+ };
1324
+ }
1325
+ function settle(resolve, reject, d, v) {
1326
+ Promise.resolve(v).then(function(v2) {
1327
+ resolve({ value: v2, done: d });
1328
+ }, reject);
1329
+ }
1330
+ }
1331
+ var ResultAsync = class _ResultAsync {
1332
+ constructor(res) {
1333
+ this._promise = res;
1334
+ }
1335
+ static fromSafePromise(promise) {
1336
+ const newPromise = promise.then((value) => new Ok(value));
1337
+ return new _ResultAsync(newPromise);
1338
+ }
1339
+ static fromPromise(promise, errorFn) {
1340
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
1341
+ return new _ResultAsync(newPromise);
1342
+ }
1343
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1344
+ static fromThrowable(fn, errorFn) {
1345
+ return (...args) => {
1346
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
1347
+ try {
1348
+ return new Ok(yield fn(...args));
1349
+ } catch (error) {
1350
+ return new Err(errorFn ? errorFn(error) : error);
1351
+ }
1352
+ }))());
1353
+ };
1354
+ }
1355
+ static combine(asyncResultList) {
1356
+ return combineResultAsyncList(asyncResultList);
1357
+ }
1358
+ static combineWithAllErrors(asyncResultList) {
1359
+ return combineResultAsyncListWithAllErrors(asyncResultList);
1360
+ }
1361
+ map(f) {
1362
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1363
+ if (res.isErr()) {
1364
+ return new Err(res.error);
1365
+ }
1366
+ return new Ok(yield f(res.value));
1367
+ })));
1368
+ }
1369
+ mapErr(f) {
1370
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1371
+ if (res.isOk()) {
1372
+ return new Ok(res.value);
1373
+ }
1374
+ return new Err(yield f(res.error));
1375
+ })));
1376
+ }
1377
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1378
+ andThen(f) {
1379
+ return new _ResultAsync(this._promise.then((res) => {
1380
+ if (res.isErr()) {
1381
+ return new Err(res.error);
1382
+ }
1383
+ const newValue = f(res.value);
1384
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
1385
+ }));
1386
+ }
1387
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1388
+ orElse(f) {
1389
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1390
+ if (res.isErr()) {
1391
+ return f(res.error);
1392
+ }
1393
+ return new Ok(res.value);
1394
+ })));
1395
+ }
1396
+ match(ok2, _err) {
1397
+ return this._promise.then((res) => res.match(ok2, _err));
1398
+ }
1399
+ unwrapOr(t) {
1400
+ return this._promise.then((res) => res.unwrapOr(t));
1401
+ }
1402
+ /**
1403
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
1404
+ */
1405
+ safeUnwrap() {
1406
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
1407
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
1408
+ });
1409
+ }
1410
+ // Makes ResultAsync implement PromiseLike<Result>
1411
+ then(successCallback, failureCallback) {
1412
+ return this._promise.then(successCallback, failureCallback);
1413
+ }
1414
+ };
1415
+ var errAsync = (err2) => new ResultAsync(Promise.resolve(new Err(err2)));
1416
+ var fromPromise = ResultAsync.fromPromise;
1417
+ var fromSafePromise = ResultAsync.fromSafePromise;
1418
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
1419
+ var combineResultList = (resultList) => {
1420
+ let acc = ok([]);
1421
+ for (const result of resultList) {
1422
+ if (result.isErr()) {
1423
+ acc = err(result.error);
1424
+ break;
1425
+ } else {
1426
+ acc.map((list) => list.push(result.value));
1427
+ }
1428
+ }
1429
+ return acc;
1430
+ };
1431
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
1432
+ var combineResultListWithAllErrors = (resultList) => {
1433
+ let acc = ok([]);
1434
+ for (const result of resultList) {
1435
+ if (result.isErr() && acc.isErr()) {
1436
+ acc.error.push(result.error);
1437
+ } else if (result.isErr() && acc.isOk()) {
1438
+ acc = err([result.error]);
1439
+ } else if (result.isOk() && acc.isOk()) {
1440
+ acc.value.push(result.value);
1441
+ }
1442
+ }
1443
+ return acc;
1444
+ };
1445
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
1446
+ var Result;
1447
+ (function(Result2) {
1448
+ function fromThrowable2(fn, errorFn) {
1449
+ return (...args) => {
1450
+ try {
1451
+ const result = fn(...args);
1452
+ return ok(result);
1453
+ } catch (e) {
1454
+ return err(errorFn ? errorFn(e) : e);
1455
+ }
1456
+ };
1457
+ }
1458
+ Result2.fromThrowable = fromThrowable2;
1459
+ function combine(resultList) {
1460
+ return combineResultList(resultList);
1461
+ }
1462
+ Result2.combine = combine;
1463
+ function combineWithAllErrors(resultList) {
1464
+ return combineResultListWithAllErrors(resultList);
1465
+ }
1466
+ Result2.combineWithAllErrors = combineWithAllErrors;
1467
+ })(Result || (Result = {}));
1468
+ var ok = (value) => new Ok(value);
1469
+ var err = (err2) => new Err(err2);
1470
+ var Ok = class {
1471
+ constructor(value) {
1472
+ this.value = value;
1473
+ }
1474
+ isOk() {
1475
+ return true;
1476
+ }
1477
+ isErr() {
1478
+ return !this.isOk();
1479
+ }
1480
+ map(f) {
1481
+ return ok(f(this.value));
1482
+ }
1483
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1484
+ mapErr(_f) {
1485
+ return ok(this.value);
1486
+ }
1487
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1488
+ andThen(f) {
1489
+ return f(this.value);
1490
+ }
1491
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1492
+ orElse(_f) {
1493
+ return ok(this.value);
1494
+ }
1495
+ asyncAndThen(f) {
1496
+ return f(this.value);
1497
+ }
1498
+ asyncMap(f) {
1499
+ return ResultAsync.fromSafePromise(f(this.value));
1500
+ }
1501
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1502
+ unwrapOr(_v) {
1503
+ return this.value;
1504
+ }
1505
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1506
+ match(ok2, _err) {
1507
+ return ok2(this.value);
1508
+ }
1509
+ safeUnwrap() {
1510
+ const value = this.value;
1511
+ return function* () {
1512
+ return value;
1513
+ }();
1514
+ }
1515
+ _unsafeUnwrap(_) {
1516
+ return this.value;
1517
+ }
1518
+ _unsafeUnwrapErr(config) {
1519
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
1520
+ }
1521
+ };
1522
+ var Err = class {
1523
+ constructor(error) {
1524
+ this.error = error;
1525
+ }
1526
+ isOk() {
1527
+ return false;
1528
+ }
1529
+ isErr() {
1530
+ return !this.isOk();
1531
+ }
1532
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1533
+ map(_f) {
1534
+ return err(this.error);
1535
+ }
1536
+ mapErr(f) {
1537
+ return err(f(this.error));
1538
+ }
1539
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1540
+ andThen(_f) {
1541
+ return err(this.error);
1542
+ }
1543
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1544
+ orElse(f) {
1545
+ return f(this.error);
1546
+ }
1547
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1548
+ asyncAndThen(_f) {
1549
+ return errAsync(this.error);
1550
+ }
1551
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1552
+ asyncMap(_f) {
1553
+ return errAsync(this.error);
1554
+ }
1555
+ unwrapOr(v) {
1556
+ return v;
1557
+ }
1558
+ match(_ok, err2) {
1559
+ return err2(this.error);
1560
+ }
1561
+ safeUnwrap() {
1562
+ const error = this.error;
1563
+ return function* () {
1564
+ yield err(error);
1565
+ throw new Error("Do not use this generator out of `safeTry`");
1566
+ }();
1567
+ }
1568
+ _unsafeUnwrap(config) {
1569
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
1570
+ }
1571
+ _unsafeUnwrapErr(_) {
1572
+ return this.error;
1573
+ }
1574
+ };
1575
+ var fromThrowable = Result.fromThrowable;
1576
+
1577
+ // src/client/workflow/types.ts
1578
+ var StepTypes = ["Initial", "Run", "SleepFor", "SleepUntil", "Call"];
1579
+
1580
+ // src/client/workflow/workflow-requests.ts
1581
+ var triggerFirstInvocation = async (workflowContext, retries, debug) => {
1582
+ const headers = getHeaders(
1583
+ "true",
1584
+ workflowContext.workflowRunId,
1585
+ workflowContext.url,
1586
+ workflowContext.headers,
1587
+ void 0,
1588
+ workflowContext.failureUrl,
1589
+ retries
1590
+ );
1591
+ await debug?.log("SUBMIT", "SUBMIT_FIRST_INVOCATION", {
1592
+ headers,
1593
+ requestPayload: workflowContext.requestPayload,
1594
+ url: workflowContext.url
1595
+ });
1596
+ try {
1597
+ await workflowContext.qstashClient.publishJSON({
1598
+ headers,
1599
+ method: "POST",
1600
+ body: workflowContext.requestPayload,
1601
+ url: workflowContext.url
1602
+ });
1603
+ return ok("success");
1604
+ } catch (error) {
1605
+ const error_ = error;
1606
+ return err(error_);
1607
+ }
1608
+ };
1609
+ var triggerRouteFunction = async ({
1610
+ onCleanup,
1611
+ onStep
1612
+ }) => {
1613
+ try {
1614
+ await onStep();
1615
+ await onCleanup();
1616
+ return ok("workflow-finished");
1617
+ } catch (error) {
1618
+ const error_ = error;
1619
+ return error_ instanceof QStashWorkflowAbort ? ok("step-finished") : err(error_);
1620
+ }
1621
+ };
1622
+ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
1623
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
1624
+ deletedWorkflowRunId: workflowContext.workflowRunId
1625
+ });
1626
+ const result = await workflowContext.qstashClient.http.request({
1627
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
1628
+ method: "DELETE",
1629
+ parseResponseAsJson: false
1630
+ });
1631
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", result);
1632
+ };
1633
+ var recreateUserHeaders = (headers) => {
1634
+ const filteredHeaders = new Headers();
1635
+ const pairs = headers.entries();
1636
+ for (const [header, value] of pairs) {
1637
+ const headerLowerCase = header.toLowerCase();
1638
+ if (!headerLowerCase.startsWith("upstash-workflow-") && !headerLowerCase.startsWith("x-vercel-") && !headerLowerCase.startsWith("x-forwarded-") && headerLowerCase !== "cf-connecting-ip") {
1639
+ filteredHeaders.append(header, value);
1640
+ }
1641
+ }
1642
+ return filteredHeaders;
1643
+ };
1644
+ var handleThirdPartyCallResult = async (request, requestPayload, client, workflowUrl, failureUrl, retries, debug) => {
1645
+ try {
1646
+ if (request.headers.get("Upstash-Workflow-Callback")) {
1647
+ const callbackMessage = JSON.parse(requestPayload);
1648
+ if (!(callbackMessage.status >= 200 && callbackMessage.status < 300)) {
1649
+ await debug?.log("WARN", "SUBMIT_THIRD_PARTY_RESULT", {
1650
+ status: callbackMessage.status,
1651
+ body: decodeBase64(callbackMessage.body)
1652
+ });
1653
+ console.warn(
1654
+ `Workflow Warning: "context.call" failed with status ${callbackMessage.status} and will retry (if there are retries remaining). Error Message:
1655
+ ${decodeBase64(callbackMessage.body)}`
1656
+ );
1657
+ return ok("call-will-retry");
1658
+ }
1659
+ const workflowRunId = request.headers.get(WORKFLOW_ID_HEADER);
1660
+ const stepIdString = request.headers.get("Upstash-Workflow-StepId");
1661
+ const stepName = request.headers.get("Upstash-Workflow-StepName");
1662
+ const stepType = request.headers.get("Upstash-Workflow-StepType");
1663
+ const concurrentString = request.headers.get("Upstash-Workflow-Concurrent");
1664
+ const contentType = request.headers.get("Upstash-Workflow-ContentType");
1665
+ if (!(workflowRunId && stepIdString && stepName && StepTypes.includes(stepType) && concurrentString && contentType)) {
1666
+ throw new Error(
1667
+ `Missing info in callback message source header: ${JSON.stringify({
1668
+ workflowRunId,
1669
+ stepIdString,
1670
+ stepName,
1671
+ stepType,
1672
+ concurrentString,
1673
+ contentType
1674
+ })}`
1675
+ );
1676
+ }
1677
+ const userHeaders = recreateUserHeaders(request.headers);
1678
+ const requestHeaders = getHeaders(
1679
+ "false",
1680
+ workflowRunId,
1681
+ workflowUrl,
1682
+ userHeaders,
1683
+ void 0,
1684
+ failureUrl,
1685
+ retries
1686
+ );
1687
+ const callResultStep = {
1688
+ stepId: Number(stepIdString),
1689
+ stepName,
1690
+ stepType,
1691
+ out: decodeBase64(callbackMessage.body),
1692
+ concurrent: Number(concurrentString)
1693
+ };
1694
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
1695
+ step: callResultStep,
1696
+ headers: requestHeaders,
1697
+ url: workflowUrl
1698
+ });
1699
+ const result = await client.publishJSON({
1700
+ headers: requestHeaders,
1701
+ method: "POST",
1702
+ body: callResultStep,
1703
+ url: workflowUrl
1704
+ });
1705
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
1706
+ messageId: result.messageId
1707
+ });
1708
+ return ok("is-call-return");
1709
+ } else {
1710
+ return ok("continue-workflow");
1711
+ }
1712
+ } catch (error) {
1713
+ const isCallReturn = request.headers.get("Upstash-Workflow-Callback");
1714
+ return err(
1715
+ new QStashWorkflowError(
1716
+ `Error when handling call return (isCallReturn=${isCallReturn}): ${error}`
1717
+ )
1718
+ );
1719
+ }
1720
+ };
1721
+ var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step, failureUrl, retries) => {
1722
+ const baseHeaders = {
1723
+ [WORKFLOW_INIT_HEADER]: initHeaderValue,
1724
+ [WORKFLOW_ID_HEADER]: workflowRunId,
1725
+ [WORKFLOW_URL_HEADER]: workflowUrl,
1726
+ [`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`]: WORKFLOW_PROTOCOL_VERSION,
1727
+ ...failureUrl ? {
1728
+ [`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`]: "true",
1729
+ "Upstash-Failure-Callback": failureUrl
1730
+ } : {},
1731
+ ...retries === void 0 ? {} : {
1732
+ "Upstash-Retries": retries.toString()
1733
+ }
1734
+ };
1735
+ if (userHeaders) {
1736
+ for (const header of userHeaders.keys()) {
1737
+ if (step?.callHeaders) {
1738
+ baseHeaders[`Upstash-Callback-Forward-${header}`] = userHeaders.get(header);
1739
+ } else {
1740
+ baseHeaders[`Upstash-Forward-${header}`] = userHeaders.get(header);
1741
+ }
1742
+ }
1743
+ }
1744
+ if (step?.callHeaders) {
1745
+ const forwardedHeaders = Object.fromEntries(
1746
+ Object.entries(step.callHeaders).map(([header, value]) => [
1747
+ `Upstash-Forward-${header}`,
1748
+ value
1749
+ ])
1750
+ );
1751
+ const contentType = step.callHeaders["Content-Type"];
1752
+ return {
1753
+ ...baseHeaders,
1754
+ ...forwardedHeaders,
1755
+ "Upstash-Callback": workflowUrl,
1756
+ "Upstash-Callback-Workflow-RunId": workflowRunId,
1757
+ "Upstash-Callback-Workflow-CallType": "fromCallback",
1758
+ "Upstash-Callback-Workflow-Init": "false",
1759
+ "Upstash-Callback-Workflow-Url": workflowUrl,
1760
+ "Upstash-Callback-Forward-Upstash-Workflow-Callback": "true",
1761
+ "Upstash-Callback-Forward-Upstash-Workflow-StepId": step.stepId.toString(),
1762
+ "Upstash-Callback-Forward-Upstash-Workflow-StepName": step.stepName,
1763
+ "Upstash-Callback-Forward-Upstash-Workflow-StepType": step.stepType,
1764
+ "Upstash-Callback-Forward-Upstash-Workflow-Concurrent": step.concurrent.toString(),
1765
+ "Upstash-Callback-Forward-Upstash-Workflow-ContentType": contentType ?? DEFAULT_CONTENT_TYPE,
1766
+ "Upstash-Workflow-CallType": "toCallback"
1767
+ };
1768
+ }
1769
+ return baseHeaders;
1770
+ };
1771
+ var verifyRequest = async (body, signature, verifier) => {
1772
+ if (!verifier) {
1773
+ return;
1774
+ }
1775
+ try {
1776
+ if (!signature) {
1777
+ throw new Error("`Upstash-Signature` header is not passed.");
1778
+ }
1779
+ const isValid = await verifier.verify({
1780
+ body,
1781
+ signature
1782
+ });
1783
+ if (!isValid) {
1784
+ throw new Error("Signature in `Upstash-Signature` header is not valid");
1785
+ }
1786
+ } catch (error) {
1787
+ throw new QStashWorkflowError(
1788
+ `Failed to verify that the Workflow request comes from QStash: ${error}
1789
+
1790
+ If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
1791
+
1792
+ If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
1793
+ );
1794
+ }
1795
+ };
1796
+
1797
+ // src/client/workflow/auto-executor.ts
1798
+ var AutoExecutor = class _AutoExecutor {
1799
+ context;
1800
+ promises = /* @__PURE__ */ new WeakMap();
1801
+ activeLazyStepList;
1802
+ debug;
1803
+ nonPlanStepCount;
1804
+ steps;
1805
+ indexInCurrentList = 0;
1806
+ stepCount = 0;
1807
+ planStepCount = 0;
1808
+ executingStep = false;
1809
+ constructor(context, steps, debug) {
1810
+ this.context = context;
1811
+ this.debug = debug;
1812
+ this.steps = steps;
1813
+ this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
1814
+ }
1815
+ /**
1816
+ * Adds the step function to the list of step functions to run in
1817
+ * parallel. After adding the function, defers the execution, so
1818
+ * that if there is another step function to be added, it's also
1819
+ * added.
1820
+ *
1821
+ * After all functions are added, list of functions are executed.
1822
+ * If there is a single function, it's executed by itself. If there
1823
+ * are multiple, they are run in parallel.
1824
+ *
1825
+ * If a function is already executing (this.executingStep), this
1826
+ * means that there is a nested step which is not allowed. In this
1827
+ * case, addStep throws QStashWorkflowError.
1828
+ *
1829
+ * @param stepInfo step plan to add
1830
+ * @returns result of the step function
1831
+ */
1832
+ async addStep(stepInfo) {
1833
+ if (this.executingStep) {
1834
+ throw new QStashWorkflowError(
1835
+ `A step can not be run inside another step. Tried to run '${stepInfo.stepName}' inside '${this.executingStep}'`
1836
+ );
1837
+ }
1838
+ this.stepCount += 1;
1839
+ const lazyStepList = this.activeLazyStepList ?? [];
1840
+ if (!this.activeLazyStepList) {
1841
+ this.activeLazyStepList = lazyStepList;
1842
+ this.indexInCurrentList = 0;
1843
+ }
1844
+ lazyStepList.push(stepInfo);
1845
+ const index = this.indexInCurrentList++;
1846
+ const requestComplete = this.deferExecution().then(async () => {
1847
+ if (!this.promises.has(lazyStepList)) {
1848
+ const promise2 = this.getExecutionPromise(lazyStepList);
1849
+ this.promises.set(lazyStepList, promise2);
1850
+ this.activeLazyStepList = void 0;
1851
+ this.planStepCount += lazyStepList.length > 1 ? lazyStepList.length : 0;
1852
+ }
1853
+ const promise = this.promises.get(lazyStepList);
1854
+ return promise;
1855
+ });
1856
+ const result = await requestComplete;
1857
+ return _AutoExecutor.getResult(lazyStepList, result, index);
1858
+ }
1859
+ /**
1860
+ * Wraps a step function to set this.executingStep to step name
1861
+ * before running and set this.executingStep to False after execution
1862
+ * ends.
1863
+ *
1864
+ * this.executingStep allows us to detect nested steps which are not
1865
+ * allowed.
1866
+ *
1867
+ * @param stepName name of the step being wrapped
1868
+ * @param stepFunction step function to wrap
1869
+ * @returns wrapped step function
1870
+ */
1871
+ wrapStep(stepName, stepFunction) {
1872
+ this.executingStep = stepName;
1873
+ const result = stepFunction();
1874
+ this.executingStep = false;
1875
+ return result;
1876
+ }
1877
+ /**
1878
+ * Executes a step:
1879
+ * - If the step result is available in the steps, returns the result
1880
+ * - If the result is not avaiable, runs the function
1881
+ * - Sends the result to QStash
1882
+ *
1883
+ * @param lazyStep lazy step to execute
1884
+ * @returns step result
1885
+ */
1886
+ async runSingle(lazyStep) {
1887
+ if (this.stepCount < this.nonPlanStepCount) {
1888
+ const step = this.steps[this.stepCount + this.planStepCount];
1889
+ validateStep(lazyStep, step);
1890
+ await this.debug?.log("INFO", "RUN_SINGLE", {
1891
+ fromRequest: true,
1892
+ step,
1893
+ stepCount: this.stepCount
1894
+ });
1895
+ return step.out;
1896
+ }
1897
+ const resultStep = await lazyStep.getResultStep(NO_CONCURRENCY, this.stepCount);
1898
+ await this.debug?.log("INFO", "RUN_SINGLE", {
1899
+ fromRequest: false,
1900
+ step: resultStep,
1901
+ stepCount: this.stepCount
1902
+ });
1903
+ await this.submitStepsToQStash([resultStep]);
1904
+ return resultStep.out;
1905
+ }
1906
+ /**
1907
+ * Runs steps in parallel.
1908
+ *
1909
+ * @param stepName parallel step name
1910
+ * @param stepFunctions list of async functions to run in parallel
1911
+ * @returns results of the functions run in parallel
1912
+ */
1913
+ async runParallel(parallelSteps) {
1914
+ const initialStepCount = this.stepCount - (parallelSteps.length - 1);
1915
+ const parallelCallState = this.getParallelCallState(parallelSteps.length, initialStepCount);
1916
+ const sortedSteps = sortSteps(this.steps);
1917
+ const plannedParallelStepCount = sortedSteps[initialStepCount + this.planStepCount]?.concurrent;
1918
+ if (parallelCallState !== "first" && plannedParallelStepCount !== parallelSteps.length) {
1919
+ throw new QStashWorkflowError(
1920
+ `Incompatible number of parallel steps when call state was '${parallelCallState}'. Expected ${parallelSteps.length}, got ${plannedParallelStepCount} from the request.`
1921
+ );
1922
+ }
1923
+ await this.debug?.log("INFO", "RUN_PARALLEL", {
1924
+ parallelCallState,
1925
+ initialStepCount,
1926
+ plannedParallelStepCount,
1927
+ stepCount: this.stepCount,
1928
+ planStepCount: this.planStepCount
1929
+ });
1930
+ switch (parallelCallState) {
1931
+ case "first": {
1932
+ const planSteps = parallelSteps.map(
1933
+ (parallelStep, index) => parallelStep.getPlanStep(parallelSteps.length, initialStepCount + index)
1934
+ );
1935
+ await this.submitStepsToQStash(planSteps);
1936
+ break;
1937
+ }
1938
+ case "partial": {
1939
+ const planStep = this.steps.at(-1);
1940
+ if (!planStep || planStep.targetStep === void 0) {
1941
+ throw new QStashWorkflowError(
1942
+ `There must be a last step and it should have targetStep larger than 0.Received: ${JSON.stringify(planStep)}`
1943
+ );
1944
+ }
1945
+ const stepIndex = planStep.targetStep - initialStepCount;
1946
+ validateStep(parallelSteps[stepIndex], planStep);
1947
+ try {
1948
+ const resultStep = await parallelSteps[stepIndex].getResultStep(
1949
+ parallelSteps.length,
1950
+ planStep.targetStep
1951
+ );
1952
+ await this.submitStepsToQStash([resultStep]);
1953
+ } catch (error) {
1954
+ if (error instanceof QStashWorkflowAbort) {
1955
+ throw error;
1956
+ }
1957
+ throw new QStashWorkflowError(
1958
+ `Error submitting steps to QStash in partial parallel step execution: ${error}`
1959
+ );
1960
+ }
1961
+ break;
1962
+ }
1963
+ case "discard": {
1964
+ throw new QStashWorkflowAbort("discarded parallel");
1965
+ }
1966
+ case "last": {
1967
+ const parallelResultSteps = sortedSteps.filter((step) => step.stepId >= initialStepCount).slice(0, parallelSteps.length);
1968
+ validateParallelSteps(parallelSteps, parallelResultSteps);
1969
+ return parallelResultSteps.map((step) => step.out);
1970
+ }
1971
+ }
1972
+ const fillValue = void 0;
1973
+ return Array.from({ length: parallelSteps.length }).fill(fillValue);
1974
+ }
1975
+ /**
1976
+ * Determines the parallel call state
1977
+ *
1978
+ * First filters the steps to get the steps which are after `initialStepCount` parameter.
1979
+ *
1980
+ * Depending on the remaining steps, decides the parallel state:
1981
+ * - "first": If there are no steps
1982
+ * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
1983
+ * because each step in a parallel execution will have 2 steps: a plan step and a result
1984
+ * step.
1985
+ * - "partial": If the last step is a plan step
1986
+ * - "discard": If the last step is not a plan step. This means that the parallel execution
1987
+ * is in progress (there are still steps to run) and one step has finished and submitted
1988
+ * its result to QStash
1989
+ *
1990
+ * @param parallelStepCount number of steps to run in parallel
1991
+ * @param initialStepCount steps after the parallel invocation
1992
+ * @returns parallel call state
1993
+ */
1994
+ getParallelCallState(parallelStepCount, initialStepCount) {
1995
+ const remainingSteps = this.steps.filter(
1996
+ (step) => (step.targetStep ?? step.stepId) >= initialStepCount
1997
+ );
1998
+ if (remainingSteps.length === 0) {
1999
+ return "first";
2000
+ } else if (remainingSteps.length >= 2 * parallelStepCount) {
2001
+ return "last";
2002
+ } else if (remainingSteps.at(-1)?.targetStep) {
2003
+ return "partial";
2004
+ } else {
2005
+ return "discard";
2006
+ }
2007
+ }
2008
+ /**
2009
+ * sends the steps to QStash as batch
2010
+ *
2011
+ * @param steps steps to send
2012
+ */
2013
+ async submitStepsToQStash(steps) {
2014
+ if (steps.length === 0) {
2015
+ throw new QStashWorkflowError(
2016
+ `Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
2017
+ );
2018
+ }
2019
+ await this.debug?.log("SUBMIT", "SUBMIT_STEP", { length: steps.length, steps });
2020
+ const result = await this.context.qstashClient.batchJSON(
2021
+ steps.map((singleStep) => {
2022
+ const headers = getHeaders(
2023
+ "false",
2024
+ this.context.workflowRunId,
2025
+ this.context.url,
2026
+ this.context.headers,
2027
+ singleStep,
2028
+ this.context.failureUrl,
2029
+ this.context.retries
2030
+ );
2031
+ const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
2032
+ return singleStep.callUrl ? (
2033
+ // if the step is a third party call, we call the third party
2034
+ // url (singleStep.callUrl) and pass information about the workflow
2035
+ // in the headers (handled in getHeaders). QStash makes the request
2036
+ // to callUrl and returns the result to Workflow endpoint.
2037
+ // handleThirdPartyCallResult method sends the result of the third
2038
+ // party call to QStash.
2039
+ {
2040
+ headers,
2041
+ method: singleStep.callMethod,
2042
+ body: singleStep.callBody,
2043
+ url: singleStep.callUrl
2044
+ }
2045
+ ) : (
2046
+ // if the step is not a third party call, we use workflow
2047
+ // endpoint (context.url) as URL when calling QStash. QStash
2048
+ // calls us back with the updated steps list.
2049
+ {
2050
+ headers,
2051
+ method: "POST",
2052
+ body: singleStep,
2053
+ url: this.context.url,
2054
+ notBefore: willWait ? singleStep.sleepUntil : void 0,
2055
+ delay: willWait ? singleStep.sleepFor : void 0
2056
+ }
2057
+ );
2058
+ })
2059
+ );
2060
+ await this.debug?.log("INFO", "SUBMIT_STEP", {
2061
+ messageIds: result.map((message) => {
2062
+ return {
2063
+ message: message.messageId
2064
+ };
2065
+ })
2066
+ });
2067
+ throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
2068
+ }
2069
+ /**
2070
+ * Get the promise by executing the lazt steps list. If there is a single
2071
+ * step, we call `runSingle`. Otherwise `runParallel` is called.
2072
+ *
2073
+ * @param lazyStepList steps list to execute
2074
+ * @returns promise corresponding to the execution
2075
+ */
2076
+ getExecutionPromise(lazyStepList) {
2077
+ return lazyStepList.length === 1 ? this.runSingle(lazyStepList[0]) : this.runParallel(lazyStepList);
2078
+ }
2079
+ /**
2080
+ * @param lazyStepList steps we executed
2081
+ * @param result result of the promise from `getExecutionPromise`
2082
+ * @param index index of the current step
2083
+ * @returns result[index] if lazyStepList > 1, otherwise result
2084
+ */
2085
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2086
+ static getResult(lazyStepList, result, index) {
2087
+ if (lazyStepList.length === 1) {
2088
+ return result;
2089
+ } else if (Array.isArray(result) && lazyStepList.length === result.length && index < lazyStepList.length) {
2090
+ return result[index];
2091
+ } else {
2092
+ throw new QStashWorkflowError(
2093
+ `Unexpected parallel call result while executing step ${index}: '${result}'. Expected ${lazyStepList.length} many items`
2094
+ );
2095
+ }
2096
+ }
2097
+ async deferExecution() {
2098
+ await Promise.resolve();
2099
+ await Promise.resolve();
2100
+ }
2101
+ };
2102
+ var validateStep = (lazyStep, stepFromRequest) => {
2103
+ if (lazyStep.stepName !== stepFromRequest.stepName) {
2104
+ throw new QStashWorkflowError(
2105
+ `Incompatible step name. Expected '${lazyStep.stepName}', got '${stepFromRequest.stepName}' from the request`
2106
+ );
2107
+ }
2108
+ if (lazyStep.stepType !== stepFromRequest.stepType) {
2109
+ throw new QStashWorkflowError(
2110
+ `Incompatible step type. Expected '${lazyStep.stepType}', got '${stepFromRequest.stepType}' from the request`
2111
+ );
2112
+ }
2113
+ };
2114
+ var validateParallelSteps = (lazySteps, stepsFromRequest) => {
2115
+ try {
2116
+ for (const [index, stepFromRequest] of stepsFromRequest.entries()) {
2117
+ validateStep(lazySteps[index], stepFromRequest);
2118
+ }
2119
+ } catch (error) {
2120
+ if (error instanceof QStashWorkflowError) {
2121
+ const lazyStepNames = lazySteps.map((lazyStep) => lazyStep.stepName);
2122
+ const lazyStepTypes = lazySteps.map((lazyStep) => lazyStep.stepType);
2123
+ const requestStepNames = stepsFromRequest.map((step) => step.stepName);
2124
+ const requestStepTypes = stepsFromRequest.map((step) => step.stepType);
2125
+ throw new QStashWorkflowError(
2126
+ `Incompatible steps detected in parallel execution: ${error.message}
2127
+ > Step Names from the request: ${JSON.stringify(requestStepNames)}
2128
+ Step Types from the request: ${JSON.stringify(requestStepTypes)}
2129
+ > Step Names expected: ${JSON.stringify(lazyStepNames)}
2130
+ Step Types expected: ${JSON.stringify(lazyStepTypes)}`
2131
+ );
2132
+ }
2133
+ throw error;
2134
+ }
2135
+ };
2136
+ var sortSteps = (steps) => {
2137
+ const getStepId = (step) => step.targetStep ?? step.stepId;
2138
+ return steps.toSorted((step, stepOther) => getStepId(step) - getStepId(stepOther));
2139
+ };
2140
+
2141
+ // src/client/workflow/steps.ts
2142
+ var BaseLazyStep = class {
2143
+ stepName;
2144
+ // will be set in the subclasses
2145
+ constructor(stepName) {
2146
+ this.stepName = stepName;
2147
+ }
2148
+ };
2149
+ var LazyFunctionStep = class extends BaseLazyStep {
2150
+ stepFunction;
2151
+ stepType = "Run";
2152
+ constructor(stepName, stepFunction) {
2153
+ super(stepName);
2154
+ this.stepFunction = stepFunction;
2155
+ }
2156
+ getPlanStep(concurrent, targetStep) {
2157
+ {
2158
+ return {
2159
+ stepId: 0,
2160
+ stepName: this.stepName,
2161
+ stepType: this.stepType,
2162
+ concurrent,
2163
+ targetStep
2164
+ };
2165
+ }
2166
+ }
2167
+ async getResultStep(concurrent, stepId) {
2168
+ let result = this.stepFunction();
2169
+ if (result instanceof Promise) {
2170
+ result = await result;
2171
+ }
2172
+ return {
2173
+ stepId,
2174
+ stepName: this.stepName,
2175
+ stepType: this.stepType,
2176
+ out: result,
2177
+ concurrent
2178
+ };
2179
+ }
2180
+ };
2181
+ var LazySleepStep = class extends BaseLazyStep {
2182
+ sleep;
2183
+ stepType = "SleepFor";
2184
+ constructor(stepName, sleep) {
2185
+ super(stepName);
2186
+ this.sleep = sleep;
2187
+ }
2188
+ getPlanStep(concurrent, targetStep) {
2189
+ {
2190
+ return {
2191
+ stepId: 0,
2192
+ stepName: this.stepName,
2193
+ stepType: this.stepType,
2194
+ sleepFor: this.sleep,
2195
+ concurrent,
2196
+ targetStep
2197
+ };
2198
+ }
2199
+ }
2200
+ async getResultStep(concurrent, stepId) {
2201
+ return await Promise.resolve({
2202
+ stepId,
2203
+ stepName: this.stepName,
2204
+ stepType: this.stepType,
2205
+ sleepFor: this.sleep,
2206
+ concurrent
2207
+ });
2208
+ }
2209
+ };
2210
+ var LazySleepUntilStep = class extends BaseLazyStep {
2211
+ sleepUntil;
2212
+ stepType = "SleepUntil";
2213
+ constructor(stepName, sleepUntil) {
2214
+ super(stepName);
2215
+ this.sleepUntil = sleepUntil;
2216
+ }
2217
+ getPlanStep(concurrent, targetStep) {
2218
+ {
2219
+ return {
2220
+ stepId: 0,
2221
+ stepName: this.stepName,
2222
+ stepType: this.stepType,
2223
+ sleepUntil: this.sleepUntil,
2224
+ concurrent,
2225
+ targetStep
2226
+ };
2227
+ }
2228
+ }
2229
+ async getResultStep(concurrent, stepId) {
2230
+ return await Promise.resolve({
2231
+ stepId,
2232
+ stepName: this.stepName,
2233
+ stepType: this.stepType,
2234
+ sleepUntil: this.sleepUntil,
2235
+ concurrent
2236
+ });
2237
+ }
2238
+ };
2239
+ var LazyCallStep = class extends BaseLazyStep {
2240
+ url;
2241
+ method;
2242
+ body;
2243
+ headers;
2244
+ stepType = "Call";
2245
+ constructor(stepName, url, method, body, headers) {
2246
+ super(stepName);
2247
+ this.url = url;
2248
+ this.method = method;
2249
+ this.body = body;
2250
+ this.headers = headers;
2251
+ }
2252
+ getPlanStep(concurrent, targetStep) {
2253
+ {
2254
+ return {
2255
+ stepId: 0,
2256
+ stepName: this.stepName,
2257
+ stepType: this.stepType,
2258
+ concurrent,
2259
+ targetStep
2260
+ };
2261
+ }
2262
+ }
2263
+ async getResultStep(concurrent, stepId) {
2264
+ return await Promise.resolve({
2265
+ stepId,
2266
+ stepName: this.stepName,
2267
+ stepType: this.stepType,
2268
+ concurrent,
2269
+ callUrl: this.url,
2270
+ callMethod: this.method,
2271
+ callBody: this.body,
2272
+ callHeaders: this.headers
2273
+ });
2274
+ }
2275
+ };
2
2276
 
2277
+ // src/client/workflow/context.ts
2278
+ var WorkflowContext = class {
2279
+ executor;
2280
+ steps;
2281
+ /**
2282
+ * QStash client of the workflow
2283
+ *
2284
+ * Can be overwritten by passing `qstashClient` parameter in `serve`:
2285
+ *
2286
+ * ```ts
2287
+ * import { Client } from "@upstash/qstash"
2288
+ *
2289
+ * export const POST = serve(
2290
+ * async (context) => {
2291
+ * ...
2292
+ * },
2293
+ * {
2294
+ * qstashClient: new Client({...})
2295
+ * }
2296
+ * )
2297
+ * ```
2298
+ */
2299
+ qstashClient;
2300
+ /**
2301
+ * Run id of the workflow
2302
+ */
2303
+ workflowRunId;
2304
+ /**
2305
+ * URL of the workflow
2306
+ *
2307
+ * Can be overwritten by passing a `url` parameter in `serve`:
2308
+ *
2309
+ * ```ts
2310
+ * export const POST = serve(
2311
+ * async (context) => {
2312
+ * ...
2313
+ * },
2314
+ * {
2315
+ * url: "new-url-value"
2316
+ * }
2317
+ * )
2318
+ * ```
2319
+ */
2320
+ url;
2321
+ /**
2322
+ * URL to call in case of workflow failure with QStash failure callback
2323
+ *
2324
+ * https://upstash.com/docs/qstash/features/callbacks#what-is-a-failure-callback
2325
+ *
2326
+ * Can be overwritten by passing a `failureUrl` parameter in `serve`:
2327
+ *
2328
+ * ```ts
2329
+ * export const POST = serve(
2330
+ * async (context) => {
2331
+ * ...
2332
+ * },
2333
+ * {
2334
+ * failureUrl: "new-url-value"
2335
+ * }
2336
+ * )
2337
+ * ```
2338
+ */
2339
+ failureUrl;
2340
+ /**
2341
+ * Payload of the request which started the workflow.
2342
+ *
2343
+ * To specify its type, you can define `serve` as follows:
2344
+ *
2345
+ * ```ts
2346
+ * // set requestPayload type to MyPayload:
2347
+ * export const POST = serve<MyPayload>(
2348
+ * async (context) => {
2349
+ * ...
2350
+ * }
2351
+ * )
2352
+ * ```
2353
+ *
2354
+ * By default, `serve` tries to apply `JSON.parse` to the request payload.
2355
+ * If your payload is encoded in a format other than JSON, you can utilize
2356
+ * the `initialPayloadParser` parameter:
2357
+ *
2358
+ * ```ts
2359
+ * export const POST = serve<MyPayload>(
2360
+ * async (context) => {
2361
+ * ...
2362
+ * },
2363
+ * {
2364
+ * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
2365
+ * }
2366
+ * )
2367
+ * ```
2368
+ */
2369
+ requestPayload;
2370
+ /**
2371
+ * headers of the initial request
2372
+ */
2373
+ headers;
2374
+ /**
2375
+ * initial payload as a raw string
2376
+ */
2377
+ rawInitialPayload;
2378
+ /**
2379
+ * Map of environment variables and their values.
2380
+ *
2381
+ * Can be set using the `env` option of serve:
2382
+ *
2383
+ * ```ts
2384
+ * export const POST = serve<MyPayload>(
2385
+ * async (context) => {
2386
+ * const key = context.env["API_KEY"];
2387
+ * },
2388
+ * {
2389
+ * env: {
2390
+ * "API_KEY": "*****";
2391
+ * }
2392
+ * }
2393
+ * )
2394
+ * ```
2395
+ *
2396
+ * Default value is set to `process.env`.
2397
+ */
2398
+ env;
2399
+ /**
2400
+ * Number of retries
2401
+ */
2402
+ retries;
2403
+ constructor({
2404
+ qstashClient,
2405
+ workflowRunId,
2406
+ headers,
2407
+ steps,
2408
+ url,
2409
+ failureUrl,
2410
+ debug,
2411
+ initialPayload,
2412
+ rawInitialPayload,
2413
+ env,
2414
+ retries
2415
+ }) {
2416
+ this.qstashClient = qstashClient;
2417
+ this.workflowRunId = workflowRunId;
2418
+ this.steps = steps;
2419
+ this.url = url;
2420
+ this.failureUrl = failureUrl;
2421
+ this.headers = headers;
2422
+ this.requestPayload = initialPayload;
2423
+ this.rawInitialPayload = rawInitialPayload ?? JSON.stringify(this.requestPayload);
2424
+ this.env = env ?? {};
2425
+ this.retries = retries ?? DEFAULT_RETRIES;
2426
+ this.executor = new AutoExecutor(this, this.steps, debug);
2427
+ }
2428
+ /**
2429
+ * Executes a workflow step
2430
+ *
2431
+ * ```typescript
2432
+ * const result = await context.run("step 1", () => {
2433
+ * return "result"
2434
+ * })
2435
+ * ```
2436
+ *
2437
+ * Can also be called in parallel and the steps will be executed
2438
+ * simulatenously:
2439
+ *
2440
+ * ```typescript
2441
+ * const [result1, result2] = await Promise.all([
2442
+ * context.run("step 1", () => {
2443
+ * return "result1"
2444
+ * })
2445
+ * context.run("step 2", async () => {
2446
+ * return await fetchResults()
2447
+ * })
2448
+ * ])
2449
+ * ```
2450
+ *
2451
+ * @param stepName name of the step
2452
+ * @param stepFunction step function to be executed
2453
+ * @returns result of the step function
2454
+ */
2455
+ async run(stepName, stepFunction) {
2456
+ const wrappedStepFunction = () => this.executor.wrapStep(stepName, stepFunction);
2457
+ return this.addStep(new LazyFunctionStep(stepName, wrappedStepFunction));
2458
+ }
2459
+ /**
2460
+ * Stops the execution for the duration provided.
2461
+ *
2462
+ * @param stepName
2463
+ * @param duration sleep duration in seconds
2464
+ * @returns undefined
2465
+ */
2466
+ async sleep(stepName, duration) {
2467
+ await this.addStep(new LazySleepStep(stepName, duration));
2468
+ }
2469
+ /**
2470
+ * Stops the execution until the date time provided.
2471
+ *
2472
+ * @param stepName
2473
+ * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
2474
+ * as a Date object or a string (passed to `new Date(datetimeString)`)
2475
+ * @returns undefined
2476
+ */
2477
+ async sleepUntil(stepName, datetime) {
2478
+ let time;
2479
+ if (typeof datetime === "number") {
2480
+ time = datetime;
2481
+ } else {
2482
+ datetime = typeof datetime === "string" ? new Date(datetime) : datetime;
2483
+ time = Math.round(datetime.getTime() / 1e3);
2484
+ }
2485
+ await this.addStep(new LazySleepUntilStep(stepName, time));
2486
+ }
2487
+ /**
2488
+ * Makes a third party call through QStash in order to make a
2489
+ * network call without consuming any runtime.
2490
+ *
2491
+ * ```ts
2492
+ * const postResult = await context.call<string>(
2493
+ * "post call step",
2494
+ * `https://www.some-endpoint.com/api`,
2495
+ * "POST",
2496
+ * "my-payload"
2497
+ * );
2498
+ * ```
2499
+ *
2500
+ * tries to parse the result of the request as JSON. If it's
2501
+ * not a JSON which can be parsed, simply returns the response
2502
+ * body as it is.
2503
+ *
2504
+ * @param stepName
2505
+ * @param url url to call
2506
+ * @param method call method
2507
+ * @param body call body
2508
+ * @param headers call headers
2509
+ * @returns call result (parsed as JSON if possible)
2510
+ */
2511
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2512
+ async call(stepName, url, method, body, headers) {
2513
+ const result = await this.addStep(
2514
+ new LazyCallStep(stepName, url, method, body, headers ?? {})
2515
+ );
2516
+ try {
2517
+ return JSON.parse(result);
2518
+ } catch {
2519
+ return result;
2520
+ }
2521
+ }
2522
+ /**
2523
+ * Adds steps to the executor. Needed so that it can be overwritten in
2524
+ * DisabledWorkflowContext.
2525
+ */
2526
+ async addStep(step) {
2527
+ return await this.executor.addStep(step);
2528
+ }
2529
+ };
2530
+ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
2531
+ static disabledMessage = "disabled-qstash-worklfow-run";
2532
+ /**
2533
+ * overwrite the WorkflowContext.addStep method to always raise QStashWorkflowAbort
2534
+ * error in order to stop the execution whenever we encounter a step.
2535
+ *
2536
+ * @param _step
2537
+ */
2538
+ // eslint-disable-next-line @typescript-eslint/require-await
2539
+ async addStep(_step) {
2540
+ throw new QStashWorkflowAbort(_DisabledWorkflowContext.disabledMessage);
2541
+ }
2542
+ /**
2543
+ * copies the passed context to create a DisabledWorkflowContext. Then, runs the
2544
+ * route function with the new context.
2545
+ *
2546
+ * - returns "run-ended" if there are no steps found or
2547
+ * if the auth failed and user called `return`
2548
+ * - returns "step-found" if DisabledWorkflowContext.addStep is called.
2549
+ * - if there is another error, returns the error.
2550
+ *
2551
+ * @param routeFunction
2552
+ */
2553
+ static async tryAuthentication(routeFunction, context) {
2554
+ const disabledContext = new _DisabledWorkflowContext({
2555
+ qstashClient: new Client({ baseUrl: "disabled-client", token: "disabled-client" }),
2556
+ workflowRunId: context.workflowRunId,
2557
+ headers: context.headers,
2558
+ steps: [],
2559
+ url: context.url,
2560
+ failureUrl: context.failureUrl,
2561
+ initialPayload: context.requestPayload,
2562
+ rawInitialPayload: context.rawInitialPayload,
2563
+ env: context.env,
2564
+ retries: context.retries
2565
+ });
2566
+ try {
2567
+ await routeFunction(disabledContext);
2568
+ } catch (error) {
2569
+ if (error instanceof QStashWorkflowAbort && error.stepName === this.disabledMessage) {
2570
+ return ok("step-found");
2571
+ }
2572
+ return err(error);
2573
+ }
2574
+ return ok("run-ended");
2575
+ }
2576
+ };
3
2577
 
4
- var _chunkKZOQ64Z6js = require('./chunk-KZOQ64Z6.js');
2578
+ // src/client/workflow/logger.ts
2579
+ var LOG_LEVELS = ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
2580
+ var WorkflowLogger = class _WorkflowLogger {
2581
+ logs = [];
2582
+ options;
2583
+ workflowRunId = void 0;
2584
+ constructor(options) {
2585
+ this.options = options;
2586
+ }
2587
+ async log(level, eventType, details) {
2588
+ if (this.shouldLog(level)) {
2589
+ const timestamp = Date.now();
2590
+ const logEntry = {
2591
+ timestamp,
2592
+ workflowRunId: this.workflowRunId ?? "",
2593
+ logLevel: level,
2594
+ eventType,
2595
+ details
2596
+ };
2597
+ this.logs.push(logEntry);
2598
+ if (this.options.logOutput === "console") {
2599
+ this.writeToConsole(logEntry);
2600
+ }
2601
+ await new Promise((resolve) => setTimeout(resolve, 100));
2602
+ }
2603
+ }
2604
+ setWorkflowRunId(workflowRunId) {
2605
+ this.workflowRunId = workflowRunId;
2606
+ }
2607
+ writeToConsole(logEntry) {
2608
+ const JSON_SPACING = 2;
2609
+ console.log(JSON.stringify(logEntry, void 0, JSON_SPACING));
2610
+ }
2611
+ shouldLog(level) {
2612
+ return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(this.options.logLevel);
2613
+ }
2614
+ static getLogger(verbose) {
2615
+ if (typeof verbose === "object") {
2616
+ return verbose;
2617
+ } else {
2618
+ return verbose ? new _WorkflowLogger({
2619
+ logLevel: "INFO",
2620
+ logOutput: "console"
2621
+ }) : void 0;
2622
+ }
2623
+ }
2624
+ };
2625
+
2626
+ // src/client/workflow/workflow-parser.ts
2627
+ var getPayload = async (request) => {
2628
+ try {
2629
+ return await request.text();
2630
+ } catch {
2631
+ return;
2632
+ }
2633
+ };
2634
+ var parsePayload = (rawPayload) => {
2635
+ const [encodedInitialPayload, ...encodedSteps] = JSON.parse(rawPayload);
2636
+ const rawInitialPayload = decodeBase64(encodedInitialPayload.body);
2637
+ const initialStep = {
2638
+ stepId: 0,
2639
+ stepName: "init",
2640
+ stepType: "Initial",
2641
+ out: rawInitialPayload,
2642
+ concurrent: NO_CONCURRENCY
2643
+ };
2644
+ const stepsToDecode = encodedSteps.filter((step) => step.callType === "step");
2645
+ const otherSteps = stepsToDecode.map((rawStep) => {
2646
+ return JSON.parse(decodeBase64(rawStep.body));
2647
+ });
2648
+ const steps = [initialStep, ...otherSteps];
2649
+ return {
2650
+ rawInitialPayload,
2651
+ steps
2652
+ };
2653
+ };
2654
+ var deduplicateSteps = (steps) => {
2655
+ const targetStepIds = [];
2656
+ const stepIds = [];
2657
+ const deduplicatedSteps = [];
2658
+ for (const step of steps) {
2659
+ if (step.stepId === 0) {
2660
+ if (!targetStepIds.includes(step.targetStep ?? 0)) {
2661
+ deduplicatedSteps.push(step);
2662
+ targetStepIds.push(step.targetStep ?? 0);
2663
+ }
2664
+ } else {
2665
+ if (!stepIds.includes(step.stepId)) {
2666
+ deduplicatedSteps.push(step);
2667
+ stepIds.push(step.stepId);
2668
+ }
2669
+ }
2670
+ }
2671
+ return deduplicatedSteps;
2672
+ };
2673
+ var checkIfLastOneIsDuplicate = async (steps, debug) => {
2674
+ if (steps.length < 2) {
2675
+ return false;
2676
+ }
2677
+ const lastStep = steps.at(-1);
2678
+ const lastStepId = lastStep.stepId;
2679
+ const lastTargetStepId = lastStep.targetStep;
2680
+ for (let index = 0; index < steps.length - 1; index++) {
2681
+ const step = steps[index];
2682
+ if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
2683
+ const message = `QStash Workflow: The step '${step.stepName}' with id '${step.stepId}' has run twice during workflow execution. Rest of the workflow will continue running as usual.`;
2684
+ await debug?.log("WARN", "RESPONSE_DEFAULT", message);
2685
+ console.warn(message);
2686
+ return true;
2687
+ }
2688
+ }
2689
+ return false;
2690
+ };
2691
+ var validateRequest = (request) => {
2692
+ const versionHeader = request.headers.get(WORKFLOW_PROTOCOL_VERSION_HEADER);
2693
+ const isFirstInvocation = !versionHeader;
2694
+ if (!isFirstInvocation && versionHeader !== WORKFLOW_PROTOCOL_VERSION) {
2695
+ throw new QStashWorkflowError(
2696
+ `Incompatible workflow sdk protocol version. Expected ${WORKFLOW_PROTOCOL_VERSION}, got ${versionHeader} from the request.`
2697
+ );
2698
+ }
2699
+ const workflowRunId = isFirstInvocation ? `wfr_${nanoid()}` : request.headers.get(WORKFLOW_ID_HEADER) ?? "";
2700
+ if (workflowRunId.length === 0) {
2701
+ throw new QStashWorkflowError("Couldn't get workflow id from header");
2702
+ }
2703
+ return {
2704
+ isFirstInvocation,
2705
+ workflowRunId
2706
+ };
2707
+ };
2708
+ var parseRequest = async (requestPayload, isFirstInvocation, debug) => {
2709
+ if (isFirstInvocation) {
2710
+ return {
2711
+ rawInitialPayload: requestPayload ?? "",
2712
+ steps: [],
2713
+ isLastDuplicate: false
2714
+ };
2715
+ } else {
2716
+ if (!requestPayload) {
2717
+ throw new QStashWorkflowError("Only first call can have an empty body");
2718
+ }
2719
+ const { rawInitialPayload, steps } = parsePayload(requestPayload);
2720
+ const isLastDuplicate = await checkIfLastOneIsDuplicate(steps, debug);
2721
+ const deduplicatedSteps = deduplicateSteps(steps);
2722
+ return {
2723
+ rawInitialPayload,
2724
+ steps: deduplicatedSteps,
2725
+ isLastDuplicate
2726
+ };
2727
+ }
2728
+ };
2729
+ var handleFailure = async (request, requestPayload, qstashClient, initialPayloadParser, failureFunction, debug) => {
2730
+ if (request.headers.get(WORKFLOW_FAILURE_HEADER) !== "true") {
2731
+ return ok("not-failure-callback");
2732
+ }
2733
+ if (!failureFunction) {
2734
+ return err(
2735
+ new QStashWorkflowError(
2736
+ "Workflow endpoint is called to handle a failure, but a failureFunction is not provided in serve options. Either provide a failureUrl or a failureFunction."
2737
+ )
2738
+ );
2739
+ }
2740
+ try {
2741
+ const { status, header, body, url, sourceHeader, sourceBody, workflowRunId } = JSON.parse(
2742
+ requestPayload
2743
+ );
2744
+ const decodedBody = body ? decodeBase64(body) : "{}";
2745
+ const errorPayload = JSON.parse(decodedBody);
2746
+ const {
2747
+ rawInitialPayload,
2748
+ steps,
2749
+ isLastDuplicate: _isLastDuplicate
2750
+ } = await parseRequest(decodeBase64(sourceBody), false, debug);
2751
+ const workflowContext = new WorkflowContext({
2752
+ qstashClient,
2753
+ workflowRunId,
2754
+ initialPayload: initialPayloadParser(rawInitialPayload),
2755
+ rawInitialPayload,
2756
+ headers: recreateUserHeaders(new Headers(sourceHeader)),
2757
+ steps,
2758
+ url,
2759
+ failureUrl: url,
2760
+ debug
2761
+ });
2762
+ await failureFunction(workflowContext, status, errorPayload.message, header);
2763
+ } catch (error) {
2764
+ return err(error);
2765
+ }
2766
+ return ok("is-failure-callback");
2767
+ };
2768
+
2769
+ // src/client/workflow/serve.ts
2770
+ var processOptions = (options) => {
2771
+ const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
2772
+ const receiverEnvironmentVariablesSet = Boolean(
2773
+ environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
2774
+ );
2775
+ return {
2776
+ qstashClient: new Client({
2777
+ baseUrl: environment.QSTASH_URL,
2778
+ token: environment.QSTASH_TOKEN
2779
+ }),
2780
+ onStepFinish: (workflowRunId, _finishCondition) => new Response(JSON.stringify({ workflowRunId }), {
2781
+ status: 200
2782
+ }),
2783
+ initialPayloadParser: (initialRequest) => {
2784
+ if (!initialRequest) {
2785
+ return void 0;
2786
+ }
2787
+ try {
2788
+ return JSON.parse(initialRequest);
2789
+ } catch (error) {
2790
+ if (error instanceof SyntaxError) {
2791
+ return initialRequest;
2792
+ }
2793
+ throw error;
2794
+ }
2795
+ },
2796
+ receiver: receiverEnvironmentVariablesSet ? new Receiver({
2797
+ currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
2798
+ nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
2799
+ }) : void 0,
2800
+ baseUrl: environment.UPSTASH_WORKFLOW_URL,
2801
+ env: environment,
2802
+ retries: DEFAULT_RETRIES,
2803
+ ...options
2804
+ };
2805
+ };
2806
+ var serve = (routeFunction, options) => {
2807
+ const {
2808
+ qstashClient,
2809
+ onStepFinish,
2810
+ initialPayloadParser,
2811
+ url,
2812
+ verbose,
2813
+ receiver,
2814
+ failureUrl,
2815
+ failureFunction,
2816
+ baseUrl,
2817
+ env,
2818
+ retries
2819
+ } = processOptions(options);
2820
+ const debug = WorkflowLogger.getLogger(verbose);
2821
+ const handler = async (request) => {
2822
+ const initialWorkflowUrl = url ?? request.url;
2823
+ const workflowUrl = baseUrl ? initialWorkflowUrl.replace(/^(https?:\/\/[^/]+)(\/.*)?$/, (_, matchedBaseUrl, path) => {
2824
+ return baseUrl + (path || "");
2825
+ }) : initialWorkflowUrl;
2826
+ if (workflowUrl !== initialWorkflowUrl) {
2827
+ await debug?.log("WARN", "ENDPOINT_START", {
2828
+ warning: `QStash Workflow: replacing the base of the url with "${baseUrl}" and using it as workflow endpoint.`,
2829
+ originalURL: initialWorkflowUrl,
2830
+ updatedURL: workflowUrl
2831
+ });
2832
+ }
2833
+ const workflowFailureUrl = failureFunction ? workflowUrl : failureUrl;
2834
+ const requestPayload = await getPayload(request) ?? "";
2835
+ await verifyRequest(requestPayload, request.headers.get("upstash-signature"), receiver);
2836
+ await debug?.log("INFO", "ENDPOINT_START");
2837
+ const failureCheck = await handleFailure(
2838
+ request,
2839
+ requestPayload,
2840
+ qstashClient,
2841
+ initialPayloadParser,
2842
+ failureFunction
2843
+ );
2844
+ if (failureCheck.isErr()) {
2845
+ throw failureCheck.error;
2846
+ } else if (failureCheck.value === "is-failure-callback") {
2847
+ await debug?.log("WARN", "RESPONSE_DEFAULT", "failureFunction executed");
2848
+ return onStepFinish("no-workflow-id", "failure-callback");
2849
+ }
2850
+ const { isFirstInvocation, workflowRunId } = validateRequest(request);
2851
+ debug?.setWorkflowRunId(workflowRunId);
2852
+ const { rawInitialPayload, steps, isLastDuplicate } = await parseRequest(
2853
+ requestPayload,
2854
+ isFirstInvocation,
2855
+ debug
2856
+ );
2857
+ if (isLastDuplicate) {
2858
+ return onStepFinish("no-workflow-id", "duplicate-step");
2859
+ }
2860
+ const workflowContext = new WorkflowContext({
2861
+ qstashClient,
2862
+ workflowRunId,
2863
+ initialPayload: initialPayloadParser(rawInitialPayload),
2864
+ rawInitialPayload,
2865
+ headers: recreateUserHeaders(request.headers),
2866
+ steps,
2867
+ url: workflowUrl,
2868
+ failureUrl: workflowFailureUrl,
2869
+ debug,
2870
+ env
2871
+ });
2872
+ const authCheck = await DisabledWorkflowContext.tryAuthentication(
2873
+ routeFunction,
2874
+ workflowContext
2875
+ );
2876
+ if (authCheck.isErr()) {
2877
+ await debug?.log("ERROR", "ERROR", { error: authCheck.error.message });
2878
+ throw authCheck.error;
2879
+ } else if (authCheck.value === "run-ended") {
2880
+ return onStepFinish("no-workflow-id", "auth-fail");
2881
+ }
2882
+ const callReturnCheck = await handleThirdPartyCallResult(
2883
+ request,
2884
+ rawInitialPayload,
2885
+ qstashClient,
2886
+ workflowUrl,
2887
+ workflowFailureUrl,
2888
+ retries,
2889
+ debug
2890
+ );
2891
+ if (callReturnCheck.isErr()) {
2892
+ await debug?.log("ERROR", "SUBMIT_THIRD_PARTY_RESULT", {
2893
+ error: callReturnCheck.error.message
2894
+ });
2895
+ throw callReturnCheck.error;
2896
+ } else if (callReturnCheck.value === "continue-workflow") {
2897
+ const result = isFirstInvocation ? await triggerFirstInvocation(workflowContext, retries, debug) : await triggerRouteFunction({
2898
+ onStep: async () => routeFunction(workflowContext),
2899
+ onCleanup: async () => {
2900
+ await triggerWorkflowDelete(workflowContext, debug);
2901
+ }
2902
+ });
2903
+ if (result.isErr()) {
2904
+ await debug?.log("ERROR", "ERROR", { error: result.error.message });
2905
+ throw result.error;
2906
+ }
2907
+ await debug?.log("INFO", "RESPONSE_WORKFLOW");
2908
+ return onStepFinish(workflowContext.workflowRunId, "success");
2909
+ }
2910
+ await debug?.log("INFO", "RESPONSE_DEFAULT");
2911
+ return onStepFinish("no-workflow-id", "fromCallback");
2912
+ };
2913
+ return async (request) => {
2914
+ try {
2915
+ return await handler(request);
2916
+ } catch (error) {
2917
+ console.error(error);
2918
+ return new Response(JSON.stringify(formatWorkflowError(error)), { status: 500 });
2919
+ }
2920
+ };
2921
+ };
2922
+
2923
+ // src/client/workflow/index.ts
2924
+ var Workflow = class {
2925
+ http;
2926
+ constructor(http) {
2927
+ this.http = http;
2928
+ }
2929
+ /**
2930
+ * Cancel an ongoing workflow
2931
+ *
2932
+ * @param workflowRunId run id of the workflow to delete
2933
+ * @returns true if workflow is succesfully deleted. Otherwise throws QStashError
2934
+ */
2935
+ async cancel(workflowRunId) {
2936
+ const result = await this.http.request({
2937
+ path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
2938
+ method: "DELETE",
2939
+ parseResponseAsJson: false
2940
+ });
2941
+ return result ?? true;
2942
+ }
2943
+ };
5
2944
 
6
2945
  // platforms/nextjs.ts
7
- var _server = require('next/server');
8
2946
  var BAD_REQUEST = 400;
9
2947
  function verifySignature(handler, config) {
10
- const currentSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _ => _.currentSigningKey]), () => ( process.env.QSTASH_CURRENT_SIGNING_KEY));
2948
+ const currentSigningKey = config?.currentSigningKey ?? process.env.QSTASH_CURRENT_SIGNING_KEY;
11
2949
  if (!currentSigningKey) {
12
2950
  throw new Error(
13
2951
  "currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY"
14
2952
  );
15
2953
  }
16
- const nextSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _2 => _2.nextSigningKey]), () => ( process.env.QSTASH_NEXT_SIGNING_KEY));
2954
+ const nextSigningKey = config?.nextSigningKey ?? process.env.QSTASH_NEXT_SIGNING_KEY;
17
2955
  if (!nextSigningKey) {
18
2956
  throw new Error(
19
2957
  "nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY"
20
2958
  );
21
2959
  }
22
- const receiver = new (0, _chunkKZOQ64Z6js.Receiver)({
2960
+ const receiver = new Receiver({
23
2961
  currentSigningKey,
24
2962
  nextSigningKey
25
2963
  });
@@ -42,7 +2980,7 @@ function verifySignature(handler, config) {
42
2980
  const isValid = await receiver.verify({
43
2981
  signature,
44
2982
  body,
45
- clockTolerance: _optionalChain([config, 'optionalAccess', _3 => _3.clockTolerance])
2983
+ clockTolerance: config?.clockTolerance
46
2984
  });
47
2985
  if (!isValid) {
48
2986
  response.status(BAD_REQUEST);
@@ -52,26 +2990,26 @@ function verifySignature(handler, config) {
52
2990
  }
53
2991
  try {
54
2992
  request.body = request.headers["content-type"] === "application/json" ? JSON.parse(body) : body;
55
- } catch (e) {
2993
+ } catch {
56
2994
  request.body = body;
57
2995
  }
58
2996
  return handler(request, response);
59
2997
  };
60
2998
  }
61
2999
  function verifySignatureEdge(handler, config) {
62
- const currentSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _4 => _4.currentSigningKey]), () => ( process.env.QSTASH_CURRENT_SIGNING_KEY));
3000
+ const currentSigningKey = config?.currentSigningKey ?? process.env.QSTASH_CURRENT_SIGNING_KEY;
63
3001
  if (!currentSigningKey) {
64
3002
  throw new Error(
65
3003
  "currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY"
66
3004
  );
67
3005
  }
68
- const nextSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _5 => _5.nextSigningKey]), () => ( process.env.QSTASH_NEXT_SIGNING_KEY));
3006
+ const nextSigningKey = config?.nextSigningKey ?? process.env.QSTASH_NEXT_SIGNING_KEY;
69
3007
  if (!nextSigningKey) {
70
3008
  throw new Error(
71
3009
  "nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY"
72
3010
  );
73
3011
  }
74
- const receiver = new (0, _chunkKZOQ64Z6js.Receiver)({
3012
+ const receiver = new Receiver({
75
3013
  currentSigningKey,
76
3014
  nextSigningKey
77
3015
  });
@@ -79,7 +3017,7 @@ function verifySignatureEdge(handler, config) {
79
3017
  const requestClone = request.clone();
80
3018
  const signature = request.headers.get("upstash-signature");
81
3019
  if (!signature) {
82
- return new (0, _server.NextResponse)(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
3020
+ return new import_server.NextResponse(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
83
3021
  status: 403
84
3022
  });
85
3023
  }
@@ -90,28 +3028,28 @@ function verifySignatureEdge(handler, config) {
90
3028
  const isValid = await receiver.verify({
91
3029
  signature,
92
3030
  body,
93
- clockTolerance: _optionalChain([config, 'optionalAccess', _6 => _6.clockTolerance])
3031
+ clockTolerance: config?.clockTolerance
94
3032
  });
95
3033
  if (!isValid) {
96
- return new (0, _server.NextResponse)(new TextEncoder().encode("invalid signature"), { status: 403 });
3034
+ return new import_server.NextResponse(new TextEncoder().encode("invalid signature"), { status: 403 });
97
3035
  }
98
3036
  return handler(request, nfe);
99
3037
  };
100
3038
  }
101
3039
  function verifySignatureAppRouter(handler, config) {
102
- const currentSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _7 => _7.currentSigningKey]), () => ( process.env.QSTASH_CURRENT_SIGNING_KEY));
3040
+ const currentSigningKey = config?.currentSigningKey ?? process.env.QSTASH_CURRENT_SIGNING_KEY;
103
3041
  if (!currentSigningKey) {
104
3042
  throw new Error(
105
3043
  "currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY"
106
3044
  );
107
3045
  }
108
- const nextSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _8 => _8.nextSigningKey]), () => ( process.env.QSTASH_NEXT_SIGNING_KEY));
3046
+ const nextSigningKey = config?.nextSigningKey ?? process.env.QSTASH_NEXT_SIGNING_KEY;
109
3047
  if (!nextSigningKey) {
110
3048
  throw new Error(
111
3049
  "nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY"
112
3050
  );
113
3051
  }
114
- const receiver = new (0, _chunkKZOQ64Z6js.Receiver)({
3052
+ const receiver = new Receiver({
115
3053
  currentSigningKey,
116
3054
  nextSigningKey
117
3055
  });
@@ -119,7 +3057,7 @@ function verifySignatureAppRouter(handler, config) {
119
3057
  const requestClone = request.clone();
120
3058
  const signature = request.headers.get("upstash-signature");
121
3059
  if (!signature) {
122
- return new (0, _server.NextResponse)(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
3060
+ return new import_server.NextResponse(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
123
3061
  status: 403
124
3062
  });
125
3063
  }
@@ -130,17 +3068,17 @@ function verifySignatureAppRouter(handler, config) {
130
3068
  const isValid = await receiver.verify({
131
3069
  signature,
132
3070
  body,
133
- clockTolerance: _optionalChain([config, 'optionalAccess', _9 => _9.clockTolerance])
3071
+ clockTolerance: config?.clockTolerance
134
3072
  });
135
3073
  if (!isValid) {
136
- return new (0, _server.NextResponse)(new TextEncoder().encode("invalid signature"), { status: 403 });
3074
+ return new import_server.NextResponse(new TextEncoder().encode("invalid signature"), { status: 403 });
137
3075
  }
138
3076
  return handler(request, params);
139
3077
  };
140
3078
  }
141
3079
  var serve2 = (routeFunction, options) => {
142
- const handler = _chunkKZOQ64Z6js.serve.call(void 0, routeFunction, {
143
- onStepFinish: (workflowRunId) => new (0, _server.NextResponse)(JSON.stringify({ workflowRunId }), { status: 200 }),
3080
+ const handler = serve(routeFunction, {
3081
+ onStepFinish: (workflowRunId) => new import_server.NextResponse(JSON.stringify({ workflowRunId }), { status: 200 }),
144
3082
  ...options
145
3083
  });
146
3084
  return async (request) => {
@@ -148,9 +3086,9 @@ var serve2 = (routeFunction, options) => {
148
3086
  };
149
3087
  };
150
3088
  var servePagesRouter = (routeFunction, options) => {
151
- const handler = _chunkKZOQ64Z6js.serve.call(void 0, routeFunction, options);
3089
+ const handler = serve(routeFunction, options);
152
3090
  return async (req, res) => {
153
- if (_optionalChain([req, 'access', _10 => _10.method, 'optionalAccess', _11 => _11.toUpperCase, 'call', _12 => _12()]) !== "POST") {
3091
+ if (req.method?.toUpperCase() !== "POST") {
154
3092
  res.status(405).json("Only POST requests are allowed in worklfows");
155
3093
  return;
156
3094
  } else if (!req.url) {
@@ -158,10 +3096,10 @@ var servePagesRouter = (routeFunction, options) => {
158
3096
  return;
159
3097
  }
160
3098
  const protocol = req.headers["x-forwarded-proto"];
161
- const baseUrl = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _13 => _13.baseUrl]), () => ( `${protocol}://${req.headers.host}`));
162
- const request = new Request(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _14 => _14.url]), () => ( `${baseUrl}${req.url}`)), {
3099
+ const baseUrl = options?.baseUrl ?? `${protocol}://${req.headers.host}`;
3100
+ const request = new Request(options?.url ?? `${baseUrl}${req.url}`, {
163
3101
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
164
- body: _nullishCoalesce(JSON.stringify(req.body), () => ( "")),
3102
+ body: JSON.stringify(req.body) ?? "",
165
3103
  headers: new Headers(req.headersDistinct),
166
3104
  method: "POST"
167
3105
  });
@@ -169,10 +3107,11 @@ var servePagesRouter = (routeFunction, options) => {
169
3107
  res.status(response.status).json(await response.json());
170
3108
  };
171
3109
  };
172
-
173
-
174
-
175
-
176
-
177
-
178
- exports.serve = serve2; exports.servePagesRouter = servePagesRouter; exports.verifySignature = verifySignature; exports.verifySignatureAppRouter = verifySignatureAppRouter; exports.verifySignatureEdge = verifySignatureEdge;
3110
+ // Annotate the CommonJS export names for ESM import in node:
3111
+ 0 && (module.exports = {
3112
+ serve,
3113
+ servePagesRouter,
3114
+ verifySignature,
3115
+ verifySignatureAppRouter,
3116
+ verifySignatureEdge
3117
+ });