@upstash/qstash 2.7.9 → 2.7.11-canary

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