@upstash/qstash 2.7.9 → 2.7.11-canary

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