@upstash/qstash 2.7.0-canary-1 → 2.7.0-workflow-alpha.2

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