@upstash/qstash 2.7.10 → 2.7.11-canary

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