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