@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/nextjs.js CHANGED
@@ -1,25 +1,4588 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return 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; }
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js
34
+ var require_detect_domain_locale = __commonJS({
35
+ "node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js"(exports2) {
36
+ "use strict";
37
+ Object.defineProperty(exports2, "__esModule", {
38
+ value: true
39
+ });
40
+ Object.defineProperty(exports2, "detectDomainLocale", {
41
+ enumerable: true,
42
+ get: function() {
43
+ return detectDomainLocale;
44
+ }
45
+ });
46
+ function detectDomainLocale(domainItems, hostname, detectedLocale) {
47
+ if (!domainItems)
48
+ return;
49
+ if (detectedLocale) {
50
+ detectedLocale = detectedLocale.toLowerCase();
51
+ }
52
+ for (const item of domainItems) {
53
+ var _item_domain, _item_locales;
54
+ const domainHostname = (_item_domain = item.domain) == null ? void 0 : _item_domain.split(":", 1)[0].toLowerCase();
55
+ if (hostname === domainHostname || detectedLocale === item.defaultLocale.toLowerCase() || ((_item_locales = item.locales) == null ? void 0 : _item_locales.some((locale) => locale.toLowerCase() === detectedLocale))) {
56
+ return item;
57
+ }
58
+ }
59
+ }
60
+ }
61
+ });
62
+
63
+ // node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js
64
+ var require_remove_trailing_slash = __commonJS({
65
+ "node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js"(exports2) {
66
+ "use strict";
67
+ Object.defineProperty(exports2, "__esModule", {
68
+ value: true
69
+ });
70
+ Object.defineProperty(exports2, "removeTrailingSlash", {
71
+ enumerable: true,
72
+ get: function() {
73
+ return removeTrailingSlash;
74
+ }
75
+ });
76
+ function removeTrailingSlash(route) {
77
+ return route.replace(/\/$/, "") || "/";
78
+ }
79
+ }
80
+ });
81
+
82
+ // node_modules/next/dist/shared/lib/router/utils/parse-path.js
83
+ var require_parse_path = __commonJS({
84
+ "node_modules/next/dist/shared/lib/router/utils/parse-path.js"(exports2) {
85
+ "use strict";
86
+ Object.defineProperty(exports2, "__esModule", {
87
+ value: true
88
+ });
89
+ Object.defineProperty(exports2, "parsePath", {
90
+ enumerable: true,
91
+ get: function() {
92
+ return parsePath;
93
+ }
94
+ });
95
+ function parsePath(path) {
96
+ const hashIndex = path.indexOf("#");
97
+ const queryIndex = path.indexOf("?");
98
+ const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex);
99
+ if (hasQuery || hashIndex > -1) {
100
+ return {
101
+ pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),
102
+ query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : void 0) : "",
103
+ hash: hashIndex > -1 ? path.slice(hashIndex) : ""
104
+ };
105
+ }
106
+ return {
107
+ pathname: path,
108
+ query: "",
109
+ hash: ""
110
+ };
111
+ }
112
+ }
113
+ });
114
+
115
+ // node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js
116
+ var require_add_path_prefix = __commonJS({
117
+ "node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js"(exports2) {
118
+ "use strict";
119
+ Object.defineProperty(exports2, "__esModule", {
120
+ value: true
121
+ });
122
+ Object.defineProperty(exports2, "addPathPrefix", {
123
+ enumerable: true,
124
+ get: function() {
125
+ return addPathPrefix;
126
+ }
127
+ });
128
+ var _parsepath = require_parse_path();
129
+ function addPathPrefix(path, prefix) {
130
+ if (!path.startsWith("/") || !prefix) {
131
+ return path;
132
+ }
133
+ const { pathname, query, hash } = (0, _parsepath.parsePath)(path);
134
+ return "" + prefix + pathname + query + hash;
135
+ }
136
+ }
137
+ });
138
+
139
+ // node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js
140
+ var require_add_path_suffix = __commonJS({
141
+ "node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js"(exports2) {
142
+ "use strict";
143
+ Object.defineProperty(exports2, "__esModule", {
144
+ value: true
145
+ });
146
+ Object.defineProperty(exports2, "addPathSuffix", {
147
+ enumerable: true,
148
+ get: function() {
149
+ return addPathSuffix;
150
+ }
151
+ });
152
+ var _parsepath = require_parse_path();
153
+ function addPathSuffix(path, suffix) {
154
+ if (!path.startsWith("/") || !suffix) {
155
+ return path;
156
+ }
157
+ const { pathname, query, hash } = (0, _parsepath.parsePath)(path);
158
+ return "" + pathname + suffix + query + hash;
159
+ }
160
+ }
161
+ });
162
+
163
+ // node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js
164
+ var require_path_has_prefix = __commonJS({
165
+ "node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js"(exports2) {
166
+ "use strict";
167
+ Object.defineProperty(exports2, "__esModule", {
168
+ value: true
169
+ });
170
+ Object.defineProperty(exports2, "pathHasPrefix", {
171
+ enumerable: true,
172
+ get: function() {
173
+ return pathHasPrefix;
174
+ }
175
+ });
176
+ var _parsepath = require_parse_path();
177
+ function pathHasPrefix(path, prefix) {
178
+ if (typeof path !== "string") {
179
+ return false;
180
+ }
181
+ const { pathname } = (0, _parsepath.parsePath)(path);
182
+ return pathname === prefix || pathname.startsWith(prefix + "/");
183
+ }
184
+ }
185
+ });
186
+
187
+ // node_modules/next/dist/shared/lib/router/utils/add-locale.js
188
+ var require_add_locale = __commonJS({
189
+ "node_modules/next/dist/shared/lib/router/utils/add-locale.js"(exports2) {
190
+ "use strict";
191
+ Object.defineProperty(exports2, "__esModule", {
192
+ value: true
193
+ });
194
+ Object.defineProperty(exports2, "addLocale", {
195
+ enumerable: true,
196
+ get: function() {
197
+ return addLocale;
198
+ }
199
+ });
200
+ var _addpathprefix = require_add_path_prefix();
201
+ var _pathhasprefix = require_path_has_prefix();
202
+ function addLocale(path, locale, defaultLocale, ignorePrefix) {
203
+ if (!locale || locale === defaultLocale)
204
+ return path;
205
+ const lower = path.toLowerCase();
206
+ if (!ignorePrefix) {
207
+ if ((0, _pathhasprefix.pathHasPrefix)(lower, "/api"))
208
+ return path;
209
+ if ((0, _pathhasprefix.pathHasPrefix)(lower, "/" + locale.toLowerCase()))
210
+ return path;
211
+ }
212
+ return (0, _addpathprefix.addPathPrefix)(path, "/" + locale);
213
+ }
214
+ }
215
+ });
216
+
217
+ // node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js
218
+ var require_format_next_pathname_info = __commonJS({
219
+ "node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js"(exports2) {
220
+ "use strict";
221
+ Object.defineProperty(exports2, "__esModule", {
222
+ value: true
223
+ });
224
+ Object.defineProperty(exports2, "formatNextPathnameInfo", {
225
+ enumerable: true,
226
+ get: function() {
227
+ return formatNextPathnameInfo;
228
+ }
229
+ });
230
+ var _removetrailingslash = require_remove_trailing_slash();
231
+ var _addpathprefix = require_add_path_prefix();
232
+ var _addpathsuffix = require_add_path_suffix();
233
+ var _addlocale = require_add_locale();
234
+ function formatNextPathnameInfo(info) {
235
+ let pathname = (0, _addlocale.addLocale)(info.pathname, info.locale, info.buildId ? void 0 : info.defaultLocale, info.ignorePrefix);
236
+ if (info.buildId || !info.trailingSlash) {
237
+ pathname = (0, _removetrailingslash.removeTrailingSlash)(pathname);
238
+ }
239
+ if (info.buildId) {
240
+ pathname = (0, _addpathsuffix.addPathSuffix)((0, _addpathprefix.addPathPrefix)(pathname, "/_next/data/" + info.buildId), info.pathname === "/" ? "index.json" : ".json");
241
+ }
242
+ pathname = (0, _addpathprefix.addPathPrefix)(pathname, info.basePath);
243
+ return !info.buildId && info.trailingSlash ? !pathname.endsWith("/") ? (0, _addpathsuffix.addPathSuffix)(pathname, "/") : pathname : (0, _removetrailingslash.removeTrailingSlash)(pathname);
244
+ }
245
+ }
246
+ });
247
+
248
+ // node_modules/next/dist/shared/lib/get-hostname.js
249
+ var require_get_hostname = __commonJS({
250
+ "node_modules/next/dist/shared/lib/get-hostname.js"(exports2) {
251
+ "use strict";
252
+ Object.defineProperty(exports2, "__esModule", {
253
+ value: true
254
+ });
255
+ Object.defineProperty(exports2, "getHostname", {
256
+ enumerable: true,
257
+ get: function() {
258
+ return getHostname;
259
+ }
260
+ });
261
+ function getHostname(parsed, headers) {
262
+ let hostname;
263
+ if ((headers == null ? void 0 : headers.host) && !Array.isArray(headers.host)) {
264
+ hostname = headers.host.toString().split(":", 1)[0];
265
+ } else if (parsed.hostname) {
266
+ hostname = parsed.hostname;
267
+ } else
268
+ return;
269
+ return hostname.toLowerCase();
270
+ }
271
+ }
272
+ });
273
+
274
+ // node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js
275
+ var require_normalize_locale_path = __commonJS({
276
+ "node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js"(exports2) {
277
+ "use strict";
278
+ Object.defineProperty(exports2, "__esModule", {
279
+ value: true
280
+ });
281
+ Object.defineProperty(exports2, "normalizeLocalePath", {
282
+ enumerable: true,
283
+ get: function() {
284
+ return normalizeLocalePath;
285
+ }
286
+ });
287
+ function normalizeLocalePath(pathname, locales) {
288
+ let detectedLocale;
289
+ const pathnameParts = pathname.split("/");
290
+ (locales || []).some((locale) => {
291
+ if (pathnameParts[1] && pathnameParts[1].toLowerCase() === locale.toLowerCase()) {
292
+ detectedLocale = locale;
293
+ pathnameParts.splice(1, 1);
294
+ pathname = pathnameParts.join("/") || "/";
295
+ return true;
296
+ }
297
+ return false;
298
+ });
299
+ return {
300
+ pathname,
301
+ detectedLocale
302
+ };
303
+ }
304
+ }
305
+ });
306
+
307
+ // node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js
308
+ var require_remove_path_prefix = __commonJS({
309
+ "node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js"(exports2) {
310
+ "use strict";
311
+ Object.defineProperty(exports2, "__esModule", {
312
+ value: true
313
+ });
314
+ Object.defineProperty(exports2, "removePathPrefix", {
315
+ enumerable: true,
316
+ get: function() {
317
+ return removePathPrefix;
318
+ }
319
+ });
320
+ var _pathhasprefix = require_path_has_prefix();
321
+ function removePathPrefix(path, prefix) {
322
+ if (!(0, _pathhasprefix.pathHasPrefix)(path, prefix)) {
323
+ return path;
324
+ }
325
+ const withoutPrefix = path.slice(prefix.length);
326
+ if (withoutPrefix.startsWith("/")) {
327
+ return withoutPrefix;
328
+ }
329
+ return "/" + withoutPrefix;
330
+ }
331
+ }
332
+ });
333
+
334
+ // node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js
335
+ var require_get_next_pathname_info = __commonJS({
336
+ "node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js"(exports2) {
337
+ "use strict";
338
+ Object.defineProperty(exports2, "__esModule", {
339
+ value: true
340
+ });
341
+ Object.defineProperty(exports2, "getNextPathnameInfo", {
342
+ enumerable: true,
343
+ get: function() {
344
+ return getNextPathnameInfo;
345
+ }
346
+ });
347
+ var _normalizelocalepath = require_normalize_locale_path();
348
+ var _removepathprefix = require_remove_path_prefix();
349
+ var _pathhasprefix = require_path_has_prefix();
350
+ function getNextPathnameInfo(pathname, options) {
351
+ var _options_nextConfig;
352
+ const { basePath, i18n, trailingSlash } = (_options_nextConfig = options.nextConfig) != null ? _options_nextConfig : {};
353
+ const info = {
354
+ pathname,
355
+ trailingSlash: pathname !== "/" ? pathname.endsWith("/") : trailingSlash
356
+ };
357
+ if (basePath && (0, _pathhasprefix.pathHasPrefix)(info.pathname, basePath)) {
358
+ info.pathname = (0, _removepathprefix.removePathPrefix)(info.pathname, basePath);
359
+ info.basePath = basePath;
360
+ }
361
+ let pathnameNoDataPrefix = info.pathname;
362
+ if (info.pathname.startsWith("/_next/data/") && info.pathname.endsWith(".json")) {
363
+ const paths = info.pathname.replace(/^\/_next\/data\//, "").replace(/\.json$/, "").split("/");
364
+ const buildId = paths[0];
365
+ info.buildId = buildId;
366
+ pathnameNoDataPrefix = paths[1] !== "index" ? "/" + paths.slice(1).join("/") : "/";
367
+ if (options.parseData === true) {
368
+ info.pathname = pathnameNoDataPrefix;
369
+ }
370
+ }
371
+ if (i18n) {
372
+ let result = options.i18nProvider ? options.i18nProvider.analyze(info.pathname) : (0, _normalizelocalepath.normalizeLocalePath)(info.pathname, i18n.locales);
373
+ info.locale = result.detectedLocale;
374
+ var _result_pathname;
375
+ info.pathname = (_result_pathname = result.pathname) != null ? _result_pathname : info.pathname;
376
+ if (!result.detectedLocale && info.buildId) {
377
+ result = options.i18nProvider ? options.i18nProvider.analyze(pathnameNoDataPrefix) : (0, _normalizelocalepath.normalizeLocalePath)(pathnameNoDataPrefix, i18n.locales);
378
+ if (result.detectedLocale) {
379
+ info.locale = result.detectedLocale;
380
+ }
381
+ }
382
+ }
383
+ return info;
384
+ }
385
+ }
386
+ });
387
+
388
+ // node_modules/next/dist/server/web/next-url.js
389
+ var require_next_url = __commonJS({
390
+ "node_modules/next/dist/server/web/next-url.js"(exports2) {
391
+ "use strict";
392
+ Object.defineProperty(exports2, "__esModule", {
393
+ value: true
394
+ });
395
+ Object.defineProperty(exports2, "NextURL", {
396
+ enumerable: true,
397
+ get: function() {
398
+ return NextURL;
399
+ }
400
+ });
401
+ var _detectdomainlocale = require_detect_domain_locale();
402
+ var _formatnextpathnameinfo = require_format_next_pathname_info();
403
+ var _gethostname = require_get_hostname();
404
+ var _getnextpathnameinfo = require_get_next_pathname_info();
405
+ var REGEX_LOCALHOST_HOSTNAME = /(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;
406
+ function parseURL(url, base) {
407
+ return new URL(String(url).replace(REGEX_LOCALHOST_HOSTNAME, "localhost"), base && String(base).replace(REGEX_LOCALHOST_HOSTNAME, "localhost"));
408
+ }
409
+ var Internal = Symbol("NextURLInternal");
410
+ var NextURL = class _NextURL {
411
+ constructor(input, baseOrOpts, opts) {
412
+ let base;
413
+ let options;
414
+ if (typeof baseOrOpts === "object" && "pathname" in baseOrOpts || typeof baseOrOpts === "string") {
415
+ base = baseOrOpts;
416
+ options = opts || {};
417
+ } else {
418
+ options = opts || baseOrOpts || {};
419
+ }
420
+ this[Internal] = {
421
+ url: parseURL(input, base ?? options.base),
422
+ options,
423
+ basePath: ""
424
+ };
425
+ this.analyze();
426
+ }
427
+ analyze() {
428
+ var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig, _this_Internal_domainLocale, _this_Internal_options_nextConfig_i18n1, _this_Internal_options_nextConfig1;
429
+ const info = (0, _getnextpathnameinfo.getNextPathnameInfo)(this[Internal].url.pathname, {
430
+ nextConfig: this[Internal].options.nextConfig,
431
+ parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,
432
+ i18nProvider: this[Internal].options.i18nProvider
433
+ });
434
+ const hostname = (0, _gethostname.getHostname)(this[Internal].url, this[Internal].options.headers);
435
+ this[Internal].domainLocale = this[Internal].options.i18nProvider ? this[Internal].options.i18nProvider.detectDomainLocale(hostname) : (0, _detectdomainlocale.detectDomainLocale)((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.domains, hostname);
436
+ const defaultLocale = ((_this_Internal_domainLocale = this[Internal].domainLocale) == null ? void 0 : _this_Internal_domainLocale.defaultLocale) || ((_this_Internal_options_nextConfig1 = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n1 = _this_Internal_options_nextConfig1.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n1.defaultLocale);
437
+ this[Internal].url.pathname = info.pathname;
438
+ this[Internal].defaultLocale = defaultLocale;
439
+ this[Internal].basePath = info.basePath ?? "";
440
+ this[Internal].buildId = info.buildId;
441
+ this[Internal].locale = info.locale ?? defaultLocale;
442
+ this[Internal].trailingSlash = info.trailingSlash;
443
+ }
444
+ formatPathname() {
445
+ return (0, _formatnextpathnameinfo.formatNextPathnameInfo)({
446
+ basePath: this[Internal].basePath,
447
+ buildId: this[Internal].buildId,
448
+ defaultLocale: !this[Internal].options.forceLocale ? this[Internal].defaultLocale : void 0,
449
+ locale: this[Internal].locale,
450
+ pathname: this[Internal].url.pathname,
451
+ trailingSlash: this[Internal].trailingSlash
452
+ });
453
+ }
454
+ formatSearch() {
455
+ return this[Internal].url.search;
456
+ }
457
+ get buildId() {
458
+ return this[Internal].buildId;
459
+ }
460
+ set buildId(buildId) {
461
+ this[Internal].buildId = buildId;
462
+ }
463
+ get locale() {
464
+ return this[Internal].locale ?? "";
465
+ }
466
+ set locale(locale) {
467
+ var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig;
468
+ if (!this[Internal].locale || !((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.locales.includes(locale))) {
469
+ throw new TypeError(`The NextURL configuration includes no locale "${locale}"`);
470
+ }
471
+ this[Internal].locale = locale;
472
+ }
473
+ get defaultLocale() {
474
+ return this[Internal].defaultLocale;
475
+ }
476
+ get domainLocale() {
477
+ return this[Internal].domainLocale;
478
+ }
479
+ get searchParams() {
480
+ return this[Internal].url.searchParams;
481
+ }
482
+ get host() {
483
+ return this[Internal].url.host;
484
+ }
485
+ set host(value) {
486
+ this[Internal].url.host = value;
487
+ }
488
+ get hostname() {
489
+ return this[Internal].url.hostname;
490
+ }
491
+ set hostname(value) {
492
+ this[Internal].url.hostname = value;
493
+ }
494
+ get port() {
495
+ return this[Internal].url.port;
496
+ }
497
+ set port(value) {
498
+ this[Internal].url.port = value;
499
+ }
500
+ get protocol() {
501
+ return this[Internal].url.protocol;
502
+ }
503
+ set protocol(value) {
504
+ this[Internal].url.protocol = value;
505
+ }
506
+ get href() {
507
+ const pathname = this.formatPathname();
508
+ const search = this.formatSearch();
509
+ return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`;
510
+ }
511
+ set href(url) {
512
+ this[Internal].url = parseURL(url);
513
+ this.analyze();
514
+ }
515
+ get origin() {
516
+ return this[Internal].url.origin;
517
+ }
518
+ get pathname() {
519
+ return this[Internal].url.pathname;
520
+ }
521
+ set pathname(value) {
522
+ this[Internal].url.pathname = value;
523
+ }
524
+ get hash() {
525
+ return this[Internal].url.hash;
526
+ }
527
+ set hash(value) {
528
+ this[Internal].url.hash = value;
529
+ }
530
+ get search() {
531
+ return this[Internal].url.search;
532
+ }
533
+ set search(value) {
534
+ this[Internal].url.search = value;
535
+ }
536
+ get password() {
537
+ return this[Internal].url.password;
538
+ }
539
+ set password(value) {
540
+ this[Internal].url.password = value;
541
+ }
542
+ get username() {
543
+ return this[Internal].url.username;
544
+ }
545
+ set username(value) {
546
+ this[Internal].url.username = value;
547
+ }
548
+ get basePath() {
549
+ return this[Internal].basePath;
550
+ }
551
+ set basePath(value) {
552
+ this[Internal].basePath = value.startsWith("/") ? value : `/${value}`;
553
+ }
554
+ toString() {
555
+ return this.href;
556
+ }
557
+ toJSON() {
558
+ return this.href;
559
+ }
560
+ [Symbol.for("edge-runtime.inspect.custom")]() {
561
+ return {
562
+ href: this.href,
563
+ origin: this.origin,
564
+ protocol: this.protocol,
565
+ username: this.username,
566
+ password: this.password,
567
+ host: this.host,
568
+ hostname: this.hostname,
569
+ port: this.port,
570
+ pathname: this.pathname,
571
+ search: this.search,
572
+ searchParams: this.searchParams,
573
+ hash: this.hash
574
+ };
575
+ }
576
+ clone() {
577
+ return new _NextURL(String(this), this[Internal].options);
578
+ }
579
+ };
580
+ }
581
+ });
582
+
583
+ // node_modules/next/dist/server/web/utils.js
584
+ var require_utils = __commonJS({
585
+ "node_modules/next/dist/server/web/utils.js"(exports2) {
586
+ "use strict";
587
+ Object.defineProperty(exports2, "__esModule", {
588
+ value: true
589
+ });
590
+ function _export(target, all) {
591
+ for (var name in all)
592
+ Object.defineProperty(target, name, {
593
+ enumerable: true,
594
+ get: all[name]
595
+ });
596
+ }
597
+ _export(exports2, {
598
+ fromNodeOutgoingHttpHeaders: function() {
599
+ return fromNodeOutgoingHttpHeaders;
600
+ },
601
+ splitCookiesString: function() {
602
+ return splitCookiesString;
603
+ },
604
+ toNodeOutgoingHttpHeaders: function() {
605
+ return toNodeOutgoingHttpHeaders;
606
+ },
607
+ validateURL: function() {
608
+ return validateURL;
609
+ }
610
+ });
611
+ function fromNodeOutgoingHttpHeaders(nodeHeaders) {
612
+ const headers = new Headers();
613
+ for (let [key, value] of Object.entries(nodeHeaders)) {
614
+ const values = Array.isArray(value) ? value : [
615
+ value
616
+ ];
617
+ for (let v of values) {
618
+ if (typeof v === "undefined")
619
+ continue;
620
+ if (typeof v === "number") {
621
+ v = v.toString();
622
+ }
623
+ headers.append(key, v);
624
+ }
625
+ }
626
+ return headers;
627
+ }
628
+ function splitCookiesString(cookiesString) {
629
+ var cookiesStrings = [];
630
+ var pos = 0;
631
+ var start;
632
+ var ch;
633
+ var lastComma;
634
+ var nextStart;
635
+ var cookiesSeparatorFound;
636
+ function skipWhitespace() {
637
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
638
+ pos += 1;
639
+ }
640
+ return pos < cookiesString.length;
641
+ }
642
+ function notSpecialChar() {
643
+ ch = cookiesString.charAt(pos);
644
+ return ch !== "=" && ch !== ";" && ch !== ",";
645
+ }
646
+ while (pos < cookiesString.length) {
647
+ start = pos;
648
+ cookiesSeparatorFound = false;
649
+ while (skipWhitespace()) {
650
+ ch = cookiesString.charAt(pos);
651
+ if (ch === ",") {
652
+ lastComma = pos;
653
+ pos += 1;
654
+ skipWhitespace();
655
+ nextStart = pos;
656
+ while (pos < cookiesString.length && notSpecialChar()) {
657
+ pos += 1;
658
+ }
659
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
660
+ cookiesSeparatorFound = true;
661
+ pos = nextStart;
662
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
663
+ start = pos;
664
+ } else {
665
+ pos = lastComma + 1;
666
+ }
667
+ } else {
668
+ pos += 1;
669
+ }
670
+ }
671
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
672
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
673
+ }
674
+ }
675
+ return cookiesStrings;
676
+ }
677
+ function toNodeOutgoingHttpHeaders(headers) {
678
+ const nodeHeaders = {};
679
+ const cookies = [];
680
+ if (headers) {
681
+ for (const [key, value] of headers.entries()) {
682
+ if (key.toLowerCase() === "set-cookie") {
683
+ cookies.push(...splitCookiesString(value));
684
+ nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies;
685
+ } else {
686
+ nodeHeaders[key] = value;
687
+ }
688
+ }
689
+ }
690
+ return nodeHeaders;
691
+ }
692
+ function validateURL(url) {
693
+ try {
694
+ return String(new URL(String(url)));
695
+ } catch (error) {
696
+ throw new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, {
697
+ cause: error
698
+ });
699
+ }
700
+ }
701
+ }
702
+ });
703
+
704
+ // node_modules/next/dist/server/web/error.js
705
+ var require_error = __commonJS({
706
+ "node_modules/next/dist/server/web/error.js"(exports2) {
707
+ "use strict";
708
+ Object.defineProperty(exports2, "__esModule", {
709
+ value: true
710
+ });
711
+ function _export(target, all) {
712
+ for (var name in all)
713
+ Object.defineProperty(target, name, {
714
+ enumerable: true,
715
+ get: all[name]
716
+ });
717
+ }
718
+ _export(exports2, {
719
+ PageSignatureError: function() {
720
+ return PageSignatureError;
721
+ },
722
+ RemovedPageError: function() {
723
+ return RemovedPageError;
724
+ },
725
+ RemovedUAError: function() {
726
+ return RemovedUAError;
727
+ }
728
+ });
729
+ var PageSignatureError = class extends Error {
730
+ constructor({ page }) {
731
+ super(`The middleware "${page}" accepts an async API directly with the form:
732
+
733
+ export function middleware(request, event) {
734
+ return NextResponse.redirect('/new-location')
735
+ }
736
+
737
+ Read more: https://nextjs.org/docs/messages/middleware-new-signature
738
+ `);
739
+ }
740
+ };
741
+ var RemovedPageError = class extends Error {
742
+ constructor() {
743
+ super(`The request.page has been deprecated in favour of \`URLPattern\`.
744
+ Read more: https://nextjs.org/docs/messages/middleware-request-page
745
+ `);
746
+ }
747
+ };
748
+ var RemovedUAError = class extends Error {
749
+ constructor() {
750
+ super(`The request.ua has been removed in favour of \`userAgent\` function.
751
+ Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
752
+ `);
753
+ }
754
+ };
755
+ }
756
+ });
757
+
758
+ // node_modules/next/dist/compiled/@edge-runtime/cookies/index.js
759
+ var require_cookies = __commonJS({
760
+ "node_modules/next/dist/compiled/@edge-runtime/cookies/index.js"(exports2, module2) {
761
+ "use strict";
762
+ var __defProp2 = Object.defineProperty;
763
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
764
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
765
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
766
+ var __export2 = (target, all) => {
767
+ for (var name in all)
768
+ __defProp2(target, name, { get: all[name], enumerable: true });
769
+ };
770
+ var __copyProps2 = (to, from, except, desc) => {
771
+ if (from && typeof from === "object" || typeof from === "function") {
772
+ for (let key of __getOwnPropNames2(from))
773
+ if (!__hasOwnProp2.call(to, key) && key !== except)
774
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
775
+ }
776
+ return to;
777
+ };
778
+ var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
779
+ var src_exports = {};
780
+ __export2(src_exports, {
781
+ RequestCookies: () => RequestCookies,
782
+ ResponseCookies: () => ResponseCookies,
783
+ parseCookie: () => parseCookie,
784
+ parseSetCookie: () => parseSetCookie,
785
+ stringifyCookie: () => stringifyCookie
786
+ });
787
+ module2.exports = __toCommonJS2(src_exports);
788
+ function stringifyCookie(c) {
789
+ var _a;
790
+ const attrs = [
791
+ "path" in c && c.path && `Path=${c.path}`,
792
+ "expires" in c && (c.expires || c.expires === 0) && `Expires=${(typeof c.expires === "number" ? new Date(c.expires) : c.expires).toUTCString()}`,
793
+ "maxAge" in c && typeof c.maxAge === "number" && `Max-Age=${c.maxAge}`,
794
+ "domain" in c && c.domain && `Domain=${c.domain}`,
795
+ "secure" in c && c.secure && "Secure",
796
+ "httpOnly" in c && c.httpOnly && "HttpOnly",
797
+ "sameSite" in c && c.sameSite && `SameSite=${c.sameSite}`,
798
+ "partitioned" in c && c.partitioned && "Partitioned",
799
+ "priority" in c && c.priority && `Priority=${c.priority}`
800
+ ].filter(Boolean);
801
+ const stringified = `${c.name}=${encodeURIComponent((_a = c.value) != null ? _a : "")}`;
802
+ return attrs.length === 0 ? stringified : `${stringified}; ${attrs.join("; ")}`;
803
+ }
804
+ function parseCookie(cookie) {
805
+ const map = /* @__PURE__ */ new Map();
806
+ for (const pair of cookie.split(/; */)) {
807
+ if (!pair)
808
+ continue;
809
+ const splitAt = pair.indexOf("=");
810
+ if (splitAt === -1) {
811
+ map.set(pair, "true");
812
+ continue;
813
+ }
814
+ const [key, value] = [pair.slice(0, splitAt), pair.slice(splitAt + 1)];
815
+ try {
816
+ map.set(key, decodeURIComponent(value != null ? value : "true"));
817
+ } catch {
818
+ }
819
+ }
820
+ return map;
821
+ }
822
+ function parseSetCookie(setCookie) {
823
+ if (!setCookie) {
824
+ return void 0;
825
+ }
826
+ const [[name, value], ...attributes] = parseCookie(setCookie);
827
+ const {
828
+ domain,
829
+ expires,
830
+ httponly,
831
+ maxage,
832
+ path,
833
+ samesite,
834
+ secure,
835
+ partitioned,
836
+ priority
837
+ } = Object.fromEntries(
838
+ attributes.map(([key, value2]) => [key.toLowerCase(), value2])
839
+ );
840
+ const cookie = {
841
+ name,
842
+ value: decodeURIComponent(value),
843
+ domain,
844
+ ...expires && { expires: new Date(expires) },
845
+ ...httponly && { httpOnly: true },
846
+ ...typeof maxage === "string" && { maxAge: Number(maxage) },
847
+ path,
848
+ ...samesite && { sameSite: parseSameSite(samesite) },
849
+ ...secure && { secure: true },
850
+ ...priority && { priority: parsePriority(priority) },
851
+ ...partitioned && { partitioned: true }
852
+ };
853
+ return compact(cookie);
854
+ }
855
+ function compact(t) {
856
+ const newT = {};
857
+ for (const key in t) {
858
+ if (t[key]) {
859
+ newT[key] = t[key];
860
+ }
861
+ }
862
+ return newT;
863
+ }
864
+ var SAME_SITE = ["strict", "lax", "none"];
865
+ function parseSameSite(string) {
866
+ string = string.toLowerCase();
867
+ return SAME_SITE.includes(string) ? string : void 0;
868
+ }
869
+ var PRIORITY = ["low", "medium", "high"];
870
+ function parsePriority(string) {
871
+ string = string.toLowerCase();
872
+ return PRIORITY.includes(string) ? string : void 0;
873
+ }
874
+ function splitCookiesString(cookiesString) {
875
+ if (!cookiesString)
876
+ return [];
877
+ var cookiesStrings = [];
878
+ var pos = 0;
879
+ var start;
880
+ var ch;
881
+ var lastComma;
882
+ var nextStart;
883
+ var cookiesSeparatorFound;
884
+ function skipWhitespace() {
885
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
886
+ pos += 1;
887
+ }
888
+ return pos < cookiesString.length;
889
+ }
890
+ function notSpecialChar() {
891
+ ch = cookiesString.charAt(pos);
892
+ return ch !== "=" && ch !== ";" && ch !== ",";
893
+ }
894
+ while (pos < cookiesString.length) {
895
+ start = pos;
896
+ cookiesSeparatorFound = false;
897
+ while (skipWhitespace()) {
898
+ ch = cookiesString.charAt(pos);
899
+ if (ch === ",") {
900
+ lastComma = pos;
901
+ pos += 1;
902
+ skipWhitespace();
903
+ nextStart = pos;
904
+ while (pos < cookiesString.length && notSpecialChar()) {
905
+ pos += 1;
906
+ }
907
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
908
+ cookiesSeparatorFound = true;
909
+ pos = nextStart;
910
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
911
+ start = pos;
912
+ } else {
913
+ pos = lastComma + 1;
914
+ }
915
+ } else {
916
+ pos += 1;
917
+ }
918
+ }
919
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
920
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
921
+ }
922
+ }
923
+ return cookiesStrings;
924
+ }
925
+ var RequestCookies = class {
926
+ constructor(requestHeaders) {
927
+ this._parsed = /* @__PURE__ */ new Map();
928
+ this._headers = requestHeaders;
929
+ const header = requestHeaders.get("cookie");
930
+ if (header) {
931
+ const parsed = parseCookie(header);
932
+ for (const [name, value] of parsed) {
933
+ this._parsed.set(name, { name, value });
934
+ }
935
+ }
936
+ }
937
+ [Symbol.iterator]() {
938
+ return this._parsed[Symbol.iterator]();
939
+ }
940
+ /**
941
+ * The amount of cookies received from the client
942
+ */
943
+ get size() {
944
+ return this._parsed.size;
945
+ }
946
+ get(...args) {
947
+ const name = typeof args[0] === "string" ? args[0] : args[0].name;
948
+ return this._parsed.get(name);
949
+ }
950
+ getAll(...args) {
951
+ var _a;
952
+ const all = Array.from(this._parsed);
953
+ if (!args.length) {
954
+ return all.map(([_, value]) => value);
955
+ }
956
+ const name = typeof args[0] === "string" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;
957
+ return all.filter(([n]) => n === name).map(([_, value]) => value);
958
+ }
959
+ has(name) {
960
+ return this._parsed.has(name);
961
+ }
962
+ set(...args) {
963
+ const [name, value] = args.length === 1 ? [args[0].name, args[0].value] : args;
964
+ const map = this._parsed;
965
+ map.set(name, { name, value });
966
+ this._headers.set(
967
+ "cookie",
968
+ Array.from(map).map(([_, value2]) => stringifyCookie(value2)).join("; ")
969
+ );
970
+ return this;
971
+ }
972
+ /**
973
+ * Delete the cookies matching the passed name or names in the request.
974
+ */
975
+ delete(names) {
976
+ const map = this._parsed;
977
+ const result = !Array.isArray(names) ? map.delete(names) : names.map((name) => map.delete(name));
978
+ this._headers.set(
979
+ "cookie",
980
+ Array.from(map).map(([_, value]) => stringifyCookie(value)).join("; ")
981
+ );
982
+ return result;
983
+ }
984
+ /**
985
+ * Delete all the cookies in the cookies in the request.
986
+ */
987
+ clear() {
988
+ this.delete(Array.from(this._parsed.keys()));
989
+ return this;
990
+ }
991
+ /**
992
+ * Format the cookies in the request as a string for logging
993
+ */
994
+ [Symbol.for("edge-runtime.inspect.custom")]() {
995
+ return `RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;
996
+ }
997
+ toString() {
998
+ return [...this._parsed.values()].map((v) => `${v.name}=${encodeURIComponent(v.value)}`).join("; ");
999
+ }
1000
+ };
1001
+ var ResponseCookies = class {
1002
+ constructor(responseHeaders) {
1003
+ this._parsed = /* @__PURE__ */ new Map();
1004
+ var _a, _b, _c;
1005
+ this._headers = responseHeaders;
1006
+ const setCookie = (_c = (_b = (_a = responseHeaders.getSetCookie) == null ? void 0 : _a.call(responseHeaders)) != null ? _b : responseHeaders.get("set-cookie")) != null ? _c : [];
1007
+ const cookieStrings = Array.isArray(setCookie) ? setCookie : splitCookiesString(setCookie);
1008
+ for (const cookieString of cookieStrings) {
1009
+ const parsed = parseSetCookie(cookieString);
1010
+ if (parsed)
1011
+ this._parsed.set(parsed.name, parsed);
1012
+ }
1013
+ }
1014
+ /**
1015
+ * {@link https://wicg.github.io/cookie-store/#CookieStore-get CookieStore#get} without the Promise.
1016
+ */
1017
+ get(...args) {
1018
+ const key = typeof args[0] === "string" ? args[0] : args[0].name;
1019
+ return this._parsed.get(key);
1020
+ }
1021
+ /**
1022
+ * {@link https://wicg.github.io/cookie-store/#CookieStore-getAll CookieStore#getAll} without the Promise.
1023
+ */
1024
+ getAll(...args) {
1025
+ var _a;
1026
+ const all = Array.from(this._parsed.values());
1027
+ if (!args.length) {
1028
+ return all;
1029
+ }
1030
+ const key = typeof args[0] === "string" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;
1031
+ return all.filter((c) => c.name === key);
1032
+ }
1033
+ has(name) {
1034
+ return this._parsed.has(name);
1035
+ }
1036
+ /**
1037
+ * {@link https://wicg.github.io/cookie-store/#CookieStore-set CookieStore#set} without the Promise.
1038
+ */
1039
+ set(...args) {
1040
+ const [name, value, cookie] = args.length === 1 ? [args[0].name, args[0].value, args[0]] : args;
1041
+ const map = this._parsed;
1042
+ map.set(name, normalizeCookie({ name, value, ...cookie }));
1043
+ replace(map, this._headers);
1044
+ return this;
1045
+ }
1046
+ /**
1047
+ * {@link https://wicg.github.io/cookie-store/#CookieStore-delete CookieStore#delete} without the Promise.
1048
+ */
1049
+ delete(...args) {
1050
+ const [name, path, domain] = typeof args[0] === "string" ? [args[0]] : [args[0].name, args[0].path, args[0].domain];
1051
+ return this.set({ name, path, domain, value: "", expires: /* @__PURE__ */ new Date(0) });
1052
+ }
1053
+ [Symbol.for("edge-runtime.inspect.custom")]() {
1054
+ return `ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`;
1055
+ }
1056
+ toString() {
1057
+ return [...this._parsed.values()].map(stringifyCookie).join("; ");
1058
+ }
1059
+ };
1060
+ function replace(bag, headers) {
1061
+ headers.delete("set-cookie");
1062
+ for (const [, value] of bag) {
1063
+ const serialized = stringifyCookie(value);
1064
+ headers.append("set-cookie", serialized);
1065
+ }
1066
+ }
1067
+ function normalizeCookie(cookie = { name: "", value: "" }) {
1068
+ if (typeof cookie.expires === "number") {
1069
+ cookie.expires = new Date(cookie.expires);
1070
+ }
1071
+ if (cookie.maxAge) {
1072
+ cookie.expires = new Date(Date.now() + cookie.maxAge * 1e3);
1073
+ }
1074
+ if (cookie.path === null || cookie.path === void 0) {
1075
+ cookie.path = "/";
1076
+ }
1077
+ return cookie;
1078
+ }
1079
+ }
1080
+ });
1081
+
1082
+ // node_modules/next/dist/server/web/spec-extension/cookies.js
1083
+ var require_cookies2 = __commonJS({
1084
+ "node_modules/next/dist/server/web/spec-extension/cookies.js"(exports2) {
1085
+ "use strict";
1086
+ Object.defineProperty(exports2, "__esModule", {
1087
+ value: true
1088
+ });
1089
+ function _export(target, all) {
1090
+ for (var name in all)
1091
+ Object.defineProperty(target, name, {
1092
+ enumerable: true,
1093
+ get: all[name]
1094
+ });
1095
+ }
1096
+ _export(exports2, {
1097
+ RequestCookies: function() {
1098
+ return _cookies.RequestCookies;
1099
+ },
1100
+ ResponseCookies: function() {
1101
+ return _cookies.ResponseCookies;
1102
+ }
1103
+ });
1104
+ var _cookies = require_cookies();
1105
+ }
1106
+ });
1107
+
1108
+ // node_modules/next/dist/server/web/spec-extension/request.js
1109
+ var require_request = __commonJS({
1110
+ "node_modules/next/dist/server/web/spec-extension/request.js"(exports2) {
1111
+ "use strict";
1112
+ Object.defineProperty(exports2, "__esModule", {
1113
+ value: true
1114
+ });
1115
+ function _export(target, all) {
1116
+ for (var name in all)
1117
+ Object.defineProperty(target, name, {
1118
+ enumerable: true,
1119
+ get: all[name]
1120
+ });
1121
+ }
1122
+ _export(exports2, {
1123
+ INTERNALS: function() {
1124
+ return INTERNALS;
1125
+ },
1126
+ NextRequest: function() {
1127
+ return NextRequest;
1128
+ }
1129
+ });
1130
+ var _nexturl = require_next_url();
1131
+ var _utils = require_utils();
1132
+ var _error = require_error();
1133
+ var _cookies = require_cookies2();
1134
+ var INTERNALS = Symbol("internal request");
1135
+ var NextRequest = class extends Request {
1136
+ constructor(input, init = {}) {
1137
+ const url = typeof input !== "string" && "url" in input ? input.url : String(input);
1138
+ (0, _utils.validateURL)(url);
1139
+ if (input instanceof Request)
1140
+ super(input, init);
1141
+ else
1142
+ super(url, init);
1143
+ const nextUrl = new _nexturl.NextURL(url, {
1144
+ headers: (0, _utils.toNodeOutgoingHttpHeaders)(this.headers),
1145
+ nextConfig: init.nextConfig
1146
+ });
1147
+ this[INTERNALS] = {
1148
+ cookies: new _cookies.RequestCookies(this.headers),
1149
+ geo: init.geo || {},
1150
+ ip: init.ip,
1151
+ nextUrl,
1152
+ url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? url : nextUrl.toString()
1153
+ };
1154
+ }
1155
+ [Symbol.for("edge-runtime.inspect.custom")]() {
1156
+ return {
1157
+ cookies: this.cookies,
1158
+ geo: this.geo,
1159
+ ip: this.ip,
1160
+ nextUrl: this.nextUrl,
1161
+ url: this.url,
1162
+ // rest of props come from Request
1163
+ bodyUsed: this.bodyUsed,
1164
+ cache: this.cache,
1165
+ credentials: this.credentials,
1166
+ destination: this.destination,
1167
+ headers: Object.fromEntries(this.headers),
1168
+ integrity: this.integrity,
1169
+ keepalive: this.keepalive,
1170
+ method: this.method,
1171
+ mode: this.mode,
1172
+ redirect: this.redirect,
1173
+ referrer: this.referrer,
1174
+ referrerPolicy: this.referrerPolicy,
1175
+ signal: this.signal
1176
+ };
1177
+ }
1178
+ get cookies() {
1179
+ return this[INTERNALS].cookies;
1180
+ }
1181
+ get geo() {
1182
+ return this[INTERNALS].geo;
1183
+ }
1184
+ get ip() {
1185
+ return this[INTERNALS].ip;
1186
+ }
1187
+ get nextUrl() {
1188
+ return this[INTERNALS].nextUrl;
1189
+ }
1190
+ /**
1191
+ * @deprecated
1192
+ * `page` has been deprecated in favour of `URLPattern`.
1193
+ * Read more: https://nextjs.org/docs/messages/middleware-request-page
1194
+ */
1195
+ get page() {
1196
+ throw new _error.RemovedPageError();
1197
+ }
1198
+ /**
1199
+ * @deprecated
1200
+ * `ua` has been removed in favour of \`userAgent\` function.
1201
+ * Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
1202
+ */
1203
+ get ua() {
1204
+ throw new _error.RemovedUAError();
1205
+ }
1206
+ get url() {
1207
+ return this[INTERNALS].url;
1208
+ }
1209
+ };
1210
+ }
1211
+ });
1212
+
1213
+ // node_modules/next/dist/server/web/spec-extension/response.js
1214
+ var require_response = __commonJS({
1215
+ "node_modules/next/dist/server/web/spec-extension/response.js"(exports2) {
1216
+ "use strict";
1217
+ Object.defineProperty(exports2, "__esModule", {
1218
+ value: true
1219
+ });
1220
+ Object.defineProperty(exports2, "NextResponse", {
1221
+ enumerable: true,
1222
+ get: function() {
1223
+ return NextResponse2;
1224
+ }
1225
+ });
1226
+ var _nexturl = require_next_url();
1227
+ var _utils = require_utils();
1228
+ var _cookies = require_cookies2();
1229
+ var INTERNALS = Symbol("internal response");
1230
+ var REDIRECTS = /* @__PURE__ */ new Set([
1231
+ 301,
1232
+ 302,
1233
+ 303,
1234
+ 307,
1235
+ 308
1236
+ ]);
1237
+ function handleMiddlewareField(init, headers) {
1238
+ var _init_request;
1239
+ if (init == null ? void 0 : (_init_request = init.request) == null ? void 0 : _init_request.headers) {
1240
+ if (!(init.request.headers instanceof Headers)) {
1241
+ throw new Error("request.headers must be an instance of Headers");
1242
+ }
1243
+ const keys = [];
1244
+ for (const [key, value] of init.request.headers) {
1245
+ headers.set("x-middleware-request-" + key, value);
1246
+ keys.push(key);
1247
+ }
1248
+ headers.set("x-middleware-override-headers", keys.join(","));
1249
+ }
1250
+ }
1251
+ var NextResponse2 = class _NextResponse extends Response {
1252
+ constructor(body, init = {}) {
1253
+ super(body, init);
1254
+ this[INTERNALS] = {
1255
+ cookies: new _cookies.ResponseCookies(this.headers),
1256
+ url: init.url ? new _nexturl.NextURL(init.url, {
1257
+ headers: (0, _utils.toNodeOutgoingHttpHeaders)(this.headers),
1258
+ nextConfig: init.nextConfig
1259
+ }) : void 0
1260
+ };
1261
+ }
1262
+ [Symbol.for("edge-runtime.inspect.custom")]() {
1263
+ return {
1264
+ cookies: this.cookies,
1265
+ url: this.url,
1266
+ // rest of props come from Response
1267
+ body: this.body,
1268
+ bodyUsed: this.bodyUsed,
1269
+ headers: Object.fromEntries(this.headers),
1270
+ ok: this.ok,
1271
+ redirected: this.redirected,
1272
+ status: this.status,
1273
+ statusText: this.statusText,
1274
+ type: this.type
1275
+ };
1276
+ }
1277
+ get cookies() {
1278
+ return this[INTERNALS].cookies;
1279
+ }
1280
+ static json(body, init) {
1281
+ const response = Response.json(body, init);
1282
+ return new _NextResponse(response.body, response);
1283
+ }
1284
+ static redirect(url, init) {
1285
+ const status = typeof init === "number" ? init : (init == null ? void 0 : init.status) ?? 307;
1286
+ if (!REDIRECTS.has(status)) {
1287
+ throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
1288
+ }
1289
+ const initObj = typeof init === "object" ? init : {};
1290
+ const headers = new Headers(initObj == null ? void 0 : initObj.headers);
1291
+ headers.set("Location", (0, _utils.validateURL)(url));
1292
+ return new _NextResponse(null, {
1293
+ ...initObj,
1294
+ headers,
1295
+ status
1296
+ });
1297
+ }
1298
+ static rewrite(destination, init) {
1299
+ const headers = new Headers(init == null ? void 0 : init.headers);
1300
+ headers.set("x-middleware-rewrite", (0, _utils.validateURL)(destination));
1301
+ handleMiddlewareField(init, headers);
1302
+ return new _NextResponse(null, {
1303
+ ...init,
1304
+ headers
1305
+ });
1306
+ }
1307
+ static next(init) {
1308
+ const headers = new Headers(init == null ? void 0 : init.headers);
1309
+ headers.set("x-middleware-next", "1");
1310
+ handleMiddlewareField(init, headers);
1311
+ return new _NextResponse(null, {
1312
+ ...init,
1313
+ headers
1314
+ });
1315
+ }
1316
+ };
1317
+ }
1318
+ });
1319
+
1320
+ // node_modules/next/dist/server/web/spec-extension/image-response.js
1321
+ var require_image_response = __commonJS({
1322
+ "node_modules/next/dist/server/web/spec-extension/image-response.js"(exports2) {
1323
+ "use strict";
1324
+ Object.defineProperty(exports2, "__esModule", {
1325
+ value: true
1326
+ });
1327
+ Object.defineProperty(exports2, "ImageResponse", {
1328
+ enumerable: true,
1329
+ get: function() {
1330
+ return ImageResponse;
1331
+ }
1332
+ });
1333
+ function ImageResponse() {
1334
+ throw new Error('ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead');
1335
+ }
1336
+ }
1337
+ });
1338
+
1339
+ // node_modules/next/dist/compiled/ua-parser-js/ua-parser.js
1340
+ var require_ua_parser = __commonJS({
1341
+ "node_modules/next/dist/compiled/ua-parser-js/ua-parser.js"(exports2, module2) {
1342
+ "use strict";
1343
+ (() => {
1344
+ var i = { 226: function(i2, e2) {
1345
+ (function(o2, a) {
1346
+ "use strict";
1347
+ var r = "1.0.35", t = "", n = "?", s = "function", b = "undefined", w = "object", l = "string", d = "major", c = "model", u = "name", p = "type", m = "vendor", f = "version", h = "architecture", v = "console", g = "mobile", k = "tablet", x = "smarttv", _ = "wearable", y = "embedded", q = 350;
1348
+ var T = "Amazon", S = "Apple", z = "ASUS", N = "BlackBerry", A = "Browser", C = "Chrome", E = "Edge", O = "Firefox", U = "Google", j = "Huawei", P = "LG", R = "Microsoft", M = "Motorola", B = "Opera", V = "Samsung", D = "Sharp", I = "Sony", W = "Viera", F = "Xiaomi", G = "Zebra", H = "Facebook", L = "Chromium OS", Z = "Mac OS";
1349
+ var extend = function(i3, e3) {
1350
+ var o3 = {};
1351
+ for (var a2 in i3) {
1352
+ if (e3[a2] && e3[a2].length % 2 === 0) {
1353
+ o3[a2] = e3[a2].concat(i3[a2]);
1354
+ } else {
1355
+ o3[a2] = i3[a2];
1356
+ }
1357
+ }
1358
+ return o3;
1359
+ }, enumerize = function(i3) {
1360
+ var e3 = {};
1361
+ for (var o3 = 0; o3 < i3.length; o3++) {
1362
+ e3[i3[o3].toUpperCase()] = i3[o3];
1363
+ }
1364
+ return e3;
1365
+ }, has = function(i3, e3) {
1366
+ return typeof i3 === l ? lowerize(e3).indexOf(lowerize(i3)) !== -1 : false;
1367
+ }, lowerize = function(i3) {
1368
+ return i3.toLowerCase();
1369
+ }, majorize = function(i3) {
1370
+ return typeof i3 === l ? i3.replace(/[^\d\.]/g, t).split(".")[0] : a;
1371
+ }, trim = function(i3, e3) {
1372
+ if (typeof i3 === l) {
1373
+ i3 = i3.replace(/^\s\s*/, t);
1374
+ return typeof e3 === b ? i3 : i3.substring(0, q);
1375
+ }
1376
+ };
1377
+ var rgxMapper = function(i3, e3) {
1378
+ var o3 = 0, r2, t2, n2, b2, l2, d2;
1379
+ while (o3 < e3.length && !l2) {
1380
+ var c2 = e3[o3], u2 = e3[o3 + 1];
1381
+ r2 = t2 = 0;
1382
+ while (r2 < c2.length && !l2) {
1383
+ if (!c2[r2]) {
1384
+ break;
1385
+ }
1386
+ l2 = c2[r2++].exec(i3);
1387
+ if (!!l2) {
1388
+ for (n2 = 0; n2 < u2.length; n2++) {
1389
+ d2 = l2[++t2];
1390
+ b2 = u2[n2];
1391
+ if (typeof b2 === w && b2.length > 0) {
1392
+ if (b2.length === 2) {
1393
+ if (typeof b2[1] == s) {
1394
+ this[b2[0]] = b2[1].call(this, d2);
1395
+ } else {
1396
+ this[b2[0]] = b2[1];
1397
+ }
1398
+ } else if (b2.length === 3) {
1399
+ if (typeof b2[1] === s && !(b2[1].exec && b2[1].test)) {
1400
+ this[b2[0]] = d2 ? b2[1].call(this, d2, b2[2]) : a;
1401
+ } else {
1402
+ this[b2[0]] = d2 ? d2.replace(b2[1], b2[2]) : a;
1403
+ }
1404
+ } else if (b2.length === 4) {
1405
+ this[b2[0]] = d2 ? b2[3].call(this, d2.replace(b2[1], b2[2])) : a;
1406
+ }
1407
+ } else {
1408
+ this[b2] = d2 ? d2 : a;
1409
+ }
1410
+ }
1411
+ }
1412
+ }
1413
+ o3 += 2;
1414
+ }
1415
+ }, strMapper = function(i3, e3) {
1416
+ for (var o3 in e3) {
1417
+ if (typeof e3[o3] === w && e3[o3].length > 0) {
1418
+ for (var r2 = 0; r2 < e3[o3].length; r2++) {
1419
+ if (has(e3[o3][r2], i3)) {
1420
+ return o3 === n ? a : o3;
1421
+ }
1422
+ }
1423
+ } else if (has(e3[o3], i3)) {
1424
+ return o3 === n ? a : o3;
1425
+ }
1426
+ }
1427
+ return i3;
1428
+ };
1429
+ var $ = { "1.0": "/8", 1.2: "/1", 1.3: "/3", "2.0": "/412", "2.0.2": "/416", "2.0.3": "/417", "2.0.4": "/419", "?": "/" }, X = { ME: "4.90", "NT 3.11": "NT3.51", "NT 4.0": "NT4.0", 2e3: "NT 5.0", XP: ["NT 5.1", "NT 5.2"], Vista: "NT 6.0", 7: "NT 6.1", 8: "NT 6.2", 8.1: "NT 6.3", 10: ["NT 6.4", "NT 10.0"], RT: "ARM" };
1430
+ var K = { browser: [[/\b(?:crmo|crios)\/([\w\.]+)/i], [f, [u, "Chrome"]], [/edg(?:e|ios|a)?\/([\w\.]+)/i], [f, [u, "Edge"]], [/(opera mini)\/([-\w\.]+)/i, /(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i, /(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i], [u, f], [/opios[\/ ]+([\w\.]+)/i], [f, [u, B + " Mini"]], [/\bopr\/([\w\.]+)/i], [f, [u, B]], [/(kindle)\/([\w\.]+)/i, /(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i, /(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i, /(ba?idubrowser)[\/ ]?([\w\.]+)/i, /(?:ms|\()(ie) ([\w\.]+)/i, /(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i, /(heytap|ovi)browser\/([\d\.]+)/i, /(weibo)__([\d\.]+)/i], [u, f], [/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i], [f, [u, "UC" + A]], [/microm.+\bqbcore\/([\w\.]+)/i, /\bqbcore\/([\w\.]+).+microm/i], [f, [u, "WeChat(Win) Desktop"]], [/micromessenger\/([\w\.]+)/i], [f, [u, "WeChat"]], [/konqueror\/([\w\.]+)/i], [f, [u, "Konqueror"]], [/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i], [f, [u, "IE"]], [/ya(?:search)?browser\/([\w\.]+)/i], [f, [u, "Yandex"]], [/(avast|avg)\/([\w\.]+)/i], [[u, /(.+)/, "$1 Secure " + A], f], [/\bfocus\/([\w\.]+)/i], [f, [u, O + " Focus"]], [/\bopt\/([\w\.]+)/i], [f, [u, B + " Touch"]], [/coc_coc\w+\/([\w\.]+)/i], [f, [u, "Coc Coc"]], [/dolfin\/([\w\.]+)/i], [f, [u, "Dolphin"]], [/coast\/([\w\.]+)/i], [f, [u, B + " Coast"]], [/miuibrowser\/([\w\.]+)/i], [f, [u, "MIUI " + A]], [/fxios\/([-\w\.]+)/i], [f, [u, O]], [/\bqihu|(qi?ho?o?|360)browser/i], [[u, "360 " + A]], [/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i], [[u, /(.+)/, "$1 " + A], f], [/(comodo_dragon)\/([\w\.]+)/i], [[u, /_/g, " "], f], [/(electron)\/([\w\.]+) safari/i, /(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i, /m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i], [u, f], [/(metasr)[\/ ]?([\w\.]+)/i, /(lbbrowser)/i, /\[(linkedin)app\]/i], [u], [/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i], [[u, H], f], [/(kakao(?:talk|story))[\/ ]([\w\.]+)/i, /(naver)\(.*?(\d+\.[\w\.]+).*\)/i, /safari (line)\/([\w\.]+)/i, /\b(line)\/([\w\.]+)\/iab/i, /(chromium|instagram)[\/ ]([-\w\.]+)/i], [u, f], [/\bgsa\/([\w\.]+) .*safari\//i], [f, [u, "GSA"]], [/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i], [f, [u, "TikTok"]], [/headlesschrome(?:\/([\w\.]+)| )/i], [f, [u, C + " Headless"]], [/ wv\).+(chrome)\/([\w\.]+)/i], [[u, C + " WebView"], f], [/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i], [f, [u, "Android " + A]], [/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i], [u, f], [/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i], [f, [u, "Mobile Safari"]], [/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i], [f, u], [/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i], [u, [f, strMapper, $]], [/(webkit|khtml)\/([\w\.]+)/i], [u, f], [/(navigator|netscape\d?)\/([-\w\.]+)/i], [[u, "Netscape"], f], [/mobile vr; rv:([\w\.]+)\).+firefox/i], [f, [u, O + " Reality"]], [/ekiohf.+(flow)\/([\w\.]+)/i, /(swiftfox)/i, /(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i, /(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i, /(firefox)\/([\w\.]+)/i, /(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i, /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i, /(links) \(([\w\.]+)/i, /panasonic;(viera)/i], [u, f], [/(cobalt)\/([\w\.]+)/i], [u, [f, /master.|lts./, ""]]], cpu: [[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i], [[h, "amd64"]], [/(ia32(?=;))/i], [[h, lowerize]], [/((?:i[346]|x)86)[;\)]/i], [[h, "ia32"]], [/\b(aarch64|arm(v?8e?l?|_?64))\b/i], [[h, "arm64"]], [/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i], [[h, "armhf"]], [/windows (ce|mobile); ppc;/i], [[h, "arm"]], [/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i], [[h, /ower/, t, lowerize]], [/(sun4\w)[;\)]/i], [[h, "sparc"]], [/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i], [[h, lowerize]]], device: [[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i], [c, [m, V], [p, k]], [/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i, /samsung[- ]([-\w]+)/i, /sec-(sgh\w+)/i], [c, [m, V], [p, g]], [/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i], [c, [m, S], [p, g]], [/\((ipad);[-\w\),; ]+apple/i, /applecoremedia\/[\w\.]+ \((ipad)/i, /\b(ipad)\d\d?,\d\d?[;\]].+ios/i], [c, [m, S], [p, k]], [/(macintosh);/i], [c, [m, S]], [/\b(sh-?[altvz]?\d\d[a-ekm]?)/i], [c, [m, D], [p, g]], [/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i], [c, [m, j], [p, k]], [/(?:huawei|honor)([-\w ]+)[;\)]/i, /\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i], [c, [m, j], [p, g]], [/\b(poco[\w ]+)(?: bui|\))/i, /\b; (\w+) build\/hm\1/i, /\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i, /\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i, /\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i], [[c, /_/g, " "], [m, F], [p, g]], [/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i], [[c, /_/g, " "], [m, F], [p, k]], [/; (\w+) bui.+ oppo/i, /\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i], [c, [m, "OPPO"], [p, g]], [/vivo (\w+)(?: bui|\))/i, /\b(v[12]\d{3}\w?[at])(?: bui|;)/i], [c, [m, "Vivo"], [p, g]], [/\b(rmx[12]\d{3})(?: bui|;|\))/i], [c, [m, "Realme"], [p, g]], [/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i, /\bmot(?:orola)?[- ](\w*)/i, /((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i], [c, [m, M], [p, g]], [/\b(mz60\d|xoom[2 ]{0,2}) build\//i], [c, [m, M], [p, k]], [/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i], [c, [m, P], [p, k]], [/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i, /\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i, /\blg-?([\d\w]+) bui/i], [c, [m, P], [p, g]], [/(ideatab[-\w ]+)/i, /lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i], [c, [m, "Lenovo"], [p, k]], [/(?:maemo|nokia).*(n900|lumia \d+)/i, /nokia[-_ ]?([-\w\.]*)/i], [[c, /_/g, " "], [m, "Nokia"], [p, g]], [/(pixel c)\b/i], [c, [m, U], [p, k]], [/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i], [c, [m, U], [p, g]], [/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i], [c, [m, I], [p, g]], [/sony tablet [ps]/i, /\b(?:sony)?sgp\w+(?: bui|\))/i], [[c, "Xperia Tablet"], [m, I], [p, k]], [/ (kb2005|in20[12]5|be20[12][59])\b/i, /(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i], [c, [m, "OnePlus"], [p, g]], [/(alexa)webm/i, /(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i, /(kf[a-z]+)( bui|\)).+silk\//i], [c, [m, T], [p, k]], [/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i], [[c, /(.+)/g, "Fire Phone $1"], [m, T], [p, g]], [/(playbook);[-\w\),; ]+(rim)/i], [c, m, [p, k]], [/\b((?:bb[a-f]|st[hv])100-\d)/i, /\(bb10; (\w+)/i], [c, [m, N], [p, g]], [/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i], [c, [m, z], [p, k]], [/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i], [c, [m, z], [p, g]], [/(nexus 9)/i], [c, [m, "HTC"], [p, k]], [/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i, /(zte)[- ]([\w ]+?)(?: bui|\/|\))/i, /(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i], [m, [c, /_/g, " "], [p, g]], [/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i], [c, [m, "Acer"], [p, k]], [/droid.+; (m[1-5] note) bui/i, /\bmz-([-\w]{2,})/i], [c, [m, "Meizu"], [p, g]], [/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i, /(hp) ([\w ]+\w)/i, /(asus)-?(\w+)/i, /(microsoft); (lumia[\w ]+)/i, /(lenovo)[-_ ]?([-\w]+)/i, /(jolla)/i, /(oppo) ?([\w ]+) bui/i], [m, c, [p, g]], [/(kobo)\s(ereader|touch)/i, /(archos) (gamepad2?)/i, /(hp).+(touchpad(?!.+tablet)|tablet)/i, /(kindle)\/([\w\.]+)/i, /(nook)[\w ]+build\/(\w+)/i, /(dell) (strea[kpr\d ]*[\dko])/i, /(le[- ]+pan)[- ]+(\w{1,9}) bui/i, /(trinity)[- ]*(t\d{3}) bui/i, /(gigaset)[- ]+(q\w{1,9}) bui/i, /(vodafone) ([\w ]+)(?:\)| bui)/i], [m, c, [p, k]], [/(surface duo)/i], [c, [m, R], [p, k]], [/droid [\d\.]+; (fp\du?)(?: b|\))/i], [c, [m, "Fairphone"], [p, g]], [/(u304aa)/i], [c, [m, "AT&T"], [p, g]], [/\bsie-(\w*)/i], [c, [m, "Siemens"], [p, g]], [/\b(rct\w+) b/i], [c, [m, "RCA"], [p, k]], [/\b(venue[\d ]{2,7}) b/i], [c, [m, "Dell"], [p, k]], [/\b(q(?:mv|ta)\w+) b/i], [c, [m, "Verizon"], [p, k]], [/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i], [c, [m, "Barnes & Noble"], [p, k]], [/\b(tm\d{3}\w+) b/i], [c, [m, "NuVision"], [p, k]], [/\b(k88) b/i], [c, [m, "ZTE"], [p, k]], [/\b(nx\d{3}j) b/i], [c, [m, "ZTE"], [p, g]], [/\b(gen\d{3}) b.+49h/i], [c, [m, "Swiss"], [p, g]], [/\b(zur\d{3}) b/i], [c, [m, "Swiss"], [p, k]], [/\b((zeki)?tb.*\b) b/i], [c, [m, "Zeki"], [p, k]], [/\b([yr]\d{2}) b/i, /\b(dragon[- ]+touch |dt)(\w{5}) b/i], [[m, "Dragon Touch"], c, [p, k]], [/\b(ns-?\w{0,9}) b/i], [c, [m, "Insignia"], [p, k]], [/\b((nxa|next)-?\w{0,9}) b/i], [c, [m, "NextBook"], [p, k]], [/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i], [[m, "Voice"], c, [p, g]], [/\b(lvtel\-)?(v1[12]) b/i], [[m, "LvTel"], c, [p, g]], [/\b(ph-1) /i], [c, [m, "Essential"], [p, g]], [/\b(v(100md|700na|7011|917g).*\b) b/i], [c, [m, "Envizen"], [p, k]], [/\b(trio[-\w\. ]+) b/i], [c, [m, "MachSpeed"], [p, k]], [/\btu_(1491) b/i], [c, [m, "Rotor"], [p, k]], [/(shield[\w ]+) b/i], [c, [m, "Nvidia"], [p, k]], [/(sprint) (\w+)/i], [m, c, [p, g]], [/(kin\.[onetw]{3})/i], [[c, /\./g, " "], [m, R], [p, g]], [/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i], [c, [m, G], [p, k]], [/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i], [c, [m, G], [p, g]], [/smart-tv.+(samsung)/i], [m, [p, x]], [/hbbtv.+maple;(\d+)/i], [[c, /^/, "SmartTV"], [m, V], [p, x]], [/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i], [[m, P], [p, x]], [/(apple) ?tv/i], [m, [c, S + " TV"], [p, x]], [/crkey/i], [[c, C + "cast"], [m, U], [p, x]], [/droid.+aft(\w)( bui|\))/i], [c, [m, T], [p, x]], [/\(dtv[\);].+(aquos)/i, /(aquos-tv[\w ]+)\)/i], [c, [m, D], [p, x]], [/(bravia[\w ]+)( bui|\))/i], [c, [m, I], [p, x]], [/(mitv-\w{5}) bui/i], [c, [m, F], [p, x]], [/Hbbtv.*(technisat) (.*);/i], [m, c, [p, x]], [/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i, /hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i], [[m, trim], [c, trim], [p, x]], [/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i], [[p, x]], [/(ouya)/i, /(nintendo) ([wids3utch]+)/i], [m, c, [p, v]], [/droid.+; (shield) bui/i], [c, [m, "Nvidia"], [p, v]], [/(playstation [345portablevi]+)/i], [c, [m, I], [p, v]], [/\b(xbox(?: one)?(?!; xbox))[\); ]/i], [c, [m, R], [p, v]], [/((pebble))app/i], [m, c, [p, _]], [/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i], [c, [m, S], [p, _]], [/droid.+; (glass) \d/i], [c, [m, U], [p, _]], [/droid.+; (wt63?0{2,3})\)/i], [c, [m, G], [p, _]], [/(quest( 2| pro)?)/i], [c, [m, H], [p, _]], [/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i], [m, [p, y]], [/(aeobc)\b/i], [c, [m, T], [p, y]], [/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i], [c, [p, g]], [/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i], [c, [p, k]], [/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i], [[p, k]], [/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i], [[p, g]], [/(android[-\w\. ]{0,9});.+buil/i], [c, [m, "Generic"]]], engine: [[/windows.+ edge\/([\w\.]+)/i], [f, [u, E + "HTML"]], [/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i], [f, [u, "Blink"]], [/(presto)\/([\w\.]+)/i, /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i, /ekioh(flow)\/([\w\.]+)/i, /(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i, /(icab)[\/ ]([23]\.[\d\.]+)/i, /\b(libweb)/i], [u, f], [/rv\:([\w\.]{1,9})\b.+(gecko)/i], [f, u]], os: [[/microsoft (windows) (vista|xp)/i], [u, f], [/(windows) nt 6\.2; (arm)/i, /(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i, /(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i], [u, [f, strMapper, X]], [/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i], [[u, "Windows"], [f, strMapper, X]], [/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i, /ios;fbsv\/([\d\.]+)/i, /cfnetwork\/.+darwin/i], [[f, /_/g, "."], [u, "iOS"]], [/(mac os x) ?([\w\. ]*)/i, /(macintosh|mac_powerpc\b)(?!.+haiku)/i], [[u, Z], [f, /_/g, "."]], [/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i], [f, u], [/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i, /(blackberry)\w*\/([\w\.]*)/i, /(tizen|kaios)[\/ ]([\w\.]+)/i, /\((series40);/i], [u, f], [/\(bb(10);/i], [f, [u, N]], [/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i], [f, [u, "Symbian"]], [/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i], [f, [u, O + " OS"]], [/web0s;.+rt(tv)/i, /\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i], [f, [u, "webOS"]], [/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i], [f, [u, "watchOS"]], [/crkey\/([\d\.]+)/i], [f, [u, C + "cast"]], [/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i], [[u, L], f], [/panasonic;(viera)/i, /(netrange)mmh/i, /(nettv)\/(\d+\.[\w\.]+)/i, /(nintendo|playstation) ([wids345portablevuch]+)/i, /(xbox); +xbox ([^\);]+)/i, /\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i, /(mint)[\/\(\) ]?(\w*)/i, /(mageia|vectorlinux)[; ]/i, /([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i, /(hurd|linux) ?([\w\.]*)/i, /(gnu) ?([\w\.]*)/i, /\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i, /(haiku) (\w+)/i], [u, f], [/(sunos) ?([\w\.\d]*)/i], [[u, "Solaris"], f], [/((?:open)?solaris)[-\/ ]?([\w\.]*)/i, /(aix) ((\d)(?=\.|\)| )[\w\.])*/i, /\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i, /(unix) ?([\w\.]*)/i], [u, f]] };
1431
+ var UAParser = function(i3, e3) {
1432
+ if (typeof i3 === w) {
1433
+ e3 = i3;
1434
+ i3 = a;
1435
+ }
1436
+ if (!(this instanceof UAParser)) {
1437
+ return new UAParser(i3, e3).getResult();
1438
+ }
1439
+ var r2 = typeof o2 !== b && o2.navigator ? o2.navigator : a;
1440
+ var n2 = i3 || (r2 && r2.userAgent ? r2.userAgent : t);
1441
+ var v2 = r2 && r2.userAgentData ? r2.userAgentData : a;
1442
+ var x2 = e3 ? extend(K, e3) : K;
1443
+ var _2 = r2 && r2.userAgent == n2;
1444
+ this.getBrowser = function() {
1445
+ var i4 = {};
1446
+ i4[u] = a;
1447
+ i4[f] = a;
1448
+ rgxMapper.call(i4, n2, x2.browser);
1449
+ i4[d] = majorize(i4[f]);
1450
+ if (_2 && r2 && r2.brave && typeof r2.brave.isBrave == s) {
1451
+ i4[u] = "Brave";
1452
+ }
1453
+ return i4;
1454
+ };
1455
+ this.getCPU = function() {
1456
+ var i4 = {};
1457
+ i4[h] = a;
1458
+ rgxMapper.call(i4, n2, x2.cpu);
1459
+ return i4;
1460
+ };
1461
+ this.getDevice = function() {
1462
+ var i4 = {};
1463
+ i4[m] = a;
1464
+ i4[c] = a;
1465
+ i4[p] = a;
1466
+ rgxMapper.call(i4, n2, x2.device);
1467
+ if (_2 && !i4[p] && v2 && v2.mobile) {
1468
+ i4[p] = g;
1469
+ }
1470
+ if (_2 && i4[c] == "Macintosh" && r2 && typeof r2.standalone !== b && r2.maxTouchPoints && r2.maxTouchPoints > 2) {
1471
+ i4[c] = "iPad";
1472
+ i4[p] = k;
1473
+ }
1474
+ return i4;
1475
+ };
1476
+ this.getEngine = function() {
1477
+ var i4 = {};
1478
+ i4[u] = a;
1479
+ i4[f] = a;
1480
+ rgxMapper.call(i4, n2, x2.engine);
1481
+ return i4;
1482
+ };
1483
+ this.getOS = function() {
1484
+ var i4 = {};
1485
+ i4[u] = a;
1486
+ i4[f] = a;
1487
+ rgxMapper.call(i4, n2, x2.os);
1488
+ if (_2 && !i4[u] && v2 && v2.platform != "Unknown") {
1489
+ i4[u] = v2.platform.replace(/chrome os/i, L).replace(/macos/i, Z);
1490
+ }
1491
+ return i4;
1492
+ };
1493
+ this.getResult = function() {
1494
+ return { ua: this.getUA(), browser: this.getBrowser(), engine: this.getEngine(), os: this.getOS(), device: this.getDevice(), cpu: this.getCPU() };
1495
+ };
1496
+ this.getUA = function() {
1497
+ return n2;
1498
+ };
1499
+ this.setUA = function(i4) {
1500
+ n2 = typeof i4 === l && i4.length > q ? trim(i4, q) : i4;
1501
+ return this;
1502
+ };
1503
+ this.setUA(n2);
1504
+ return this;
1505
+ };
1506
+ UAParser.VERSION = r;
1507
+ UAParser.BROWSER = enumerize([u, f, d]);
1508
+ UAParser.CPU = enumerize([h]);
1509
+ UAParser.DEVICE = enumerize([c, m, p, v, g, x, k, _, y]);
1510
+ UAParser.ENGINE = UAParser.OS = enumerize([u, f]);
1511
+ if (typeof e2 !== b) {
1512
+ if ("object" !== b && i2.exports) {
1513
+ e2 = i2.exports = UAParser;
1514
+ }
1515
+ e2.UAParser = UAParser;
1516
+ } else {
1517
+ if (typeof define === s && define.amd) {
1518
+ define(function() {
1519
+ return UAParser;
1520
+ });
1521
+ } else if (typeof o2 !== b) {
1522
+ o2.UAParser = UAParser;
1523
+ }
1524
+ }
1525
+ var Q = typeof o2 !== b && (o2.jQuery || o2.Zepto);
1526
+ if (Q && !Q.ua) {
1527
+ var Y = new UAParser();
1528
+ Q.ua = Y.getResult();
1529
+ Q.ua.get = function() {
1530
+ return Y.getUA();
1531
+ };
1532
+ Q.ua.set = function(i3) {
1533
+ Y.setUA(i3);
1534
+ var e3 = Y.getResult();
1535
+ for (var o3 in e3) {
1536
+ Q.ua[o3] = e3[o3];
1537
+ }
1538
+ };
1539
+ }
1540
+ })(typeof window === "object" ? window : this);
1541
+ } };
1542
+ var e = {};
1543
+ function __nccwpck_require__(o2) {
1544
+ var a = e[o2];
1545
+ if (a !== void 0) {
1546
+ return a.exports;
1547
+ }
1548
+ var r = e[o2] = { exports: {} };
1549
+ var t = true;
1550
+ try {
1551
+ i[o2].call(r.exports, r, r.exports, __nccwpck_require__);
1552
+ t = false;
1553
+ } finally {
1554
+ if (t)
1555
+ delete e[o2];
1556
+ }
1557
+ return r.exports;
1558
+ }
1559
+ if (typeof __nccwpck_require__ !== "undefined")
1560
+ __nccwpck_require__.ab = __dirname + "/";
1561
+ var o = __nccwpck_require__(226);
1562
+ module2.exports = o;
1563
+ })();
1564
+ }
1565
+ });
1566
+
1567
+ // node_modules/next/dist/server/web/spec-extension/user-agent.js
1568
+ var require_user_agent = __commonJS({
1569
+ "node_modules/next/dist/server/web/spec-extension/user-agent.js"(exports2) {
1570
+ "use strict";
1571
+ Object.defineProperty(exports2, "__esModule", {
1572
+ value: true
1573
+ });
1574
+ function _export(target, all) {
1575
+ for (var name in all)
1576
+ Object.defineProperty(target, name, {
1577
+ enumerable: true,
1578
+ get: all[name]
1579
+ });
1580
+ }
1581
+ _export(exports2, {
1582
+ isBot: function() {
1583
+ return isBot;
1584
+ },
1585
+ userAgent: function() {
1586
+ return userAgent;
1587
+ },
1588
+ userAgentFromString: function() {
1589
+ return userAgentFromString;
1590
+ }
1591
+ });
1592
+ var _uaparserjs = /* @__PURE__ */ _interop_require_default(require_ua_parser());
1593
+ function _interop_require_default(obj) {
1594
+ return obj && obj.__esModule ? obj : {
1595
+ default: obj
1596
+ };
1597
+ }
1598
+ function isBot(input) {
1599
+ return /Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(input);
1600
+ }
1601
+ function userAgentFromString(input) {
1602
+ return {
1603
+ ...(0, _uaparserjs.default)(input),
1604
+ isBot: input === void 0 ? false : isBot(input)
1605
+ };
1606
+ }
1607
+ function userAgent({ headers }) {
1608
+ return userAgentFromString(headers.get("user-agent") || void 0);
1609
+ }
1610
+ }
1611
+ });
1612
+
1613
+ // node_modules/next/dist/server/web/spec-extension/url-pattern.js
1614
+ var require_url_pattern = __commonJS({
1615
+ "node_modules/next/dist/server/web/spec-extension/url-pattern.js"(exports2) {
1616
+ "use strict";
1617
+ Object.defineProperty(exports2, "__esModule", {
1618
+ value: true
1619
+ });
1620
+ Object.defineProperty(exports2, "URLPattern", {
1621
+ enumerable: true,
1622
+ get: function() {
1623
+ return GlobalURLPattern;
1624
+ }
1625
+ });
1626
+ var GlobalURLPattern = (
1627
+ // @ts-expect-error: URLPattern is not available in Node.js
1628
+ typeof URLPattern === "undefined" ? void 0 : URLPattern
1629
+ );
1630
+ }
1631
+ });
1632
+
1633
+ // node_modules/next/server.js
1634
+ var require_server = __commonJS({
1635
+ "node_modules/next/server.js"(exports2, module2) {
1636
+ "use strict";
1637
+ var serverExports = {
1638
+ NextRequest: require_request().NextRequest,
1639
+ NextResponse: require_response().NextResponse,
1640
+ ImageResponse: require_image_response().ImageResponse,
1641
+ userAgentFromString: require_user_agent().userAgentFromString,
1642
+ userAgent: require_user_agent().userAgent,
1643
+ URLPattern: require_url_pattern().URLPattern
1644
+ };
1645
+ module2.exports = serverExports;
1646
+ exports2.NextRequest = serverExports.NextRequest;
1647
+ exports2.NextResponse = serverExports.NextResponse;
1648
+ exports2.ImageResponse = serverExports.ImageResponse;
1649
+ exports2.userAgentFromString = serverExports.userAgentFromString;
1650
+ exports2.userAgent = serverExports.userAgent;
1651
+ exports2.URLPattern = serverExports.URLPattern;
1652
+ }
1653
+ });
1654
+
1655
+ // platforms/nextjs.ts
1656
+ var nextjs_exports = {};
1657
+ __export(nextjs_exports, {
1658
+ serve: () => serve2,
1659
+ servePagesRouter: () => servePagesRouter,
1660
+ verifySignature: () => verifySignature,
1661
+ verifySignatureAppRouter: () => verifySignatureAppRouter,
1662
+ verifySignatureEdge: () => verifySignatureEdge
1663
+ });
1664
+ module.exports = __toCommonJS(nextjs_exports);
1665
+ var import_server = __toESM(require_server());
1666
+
1667
+ // src/receiver.ts
1668
+ var jose = __toESM(require("jose"));
1669
+ var import_crypto_js = __toESM(require("crypto-js"));
1670
+ var SignatureError = class extends Error {
1671
+ constructor(message) {
1672
+ super(message);
1673
+ this.name = "SignatureError";
1674
+ }
1675
+ };
1676
+ var Receiver = class {
1677
+ currentSigningKey;
1678
+ nextSigningKey;
1679
+ constructor(config) {
1680
+ this.currentSigningKey = config.currentSigningKey;
1681
+ this.nextSigningKey = config.nextSigningKey;
1682
+ }
1683
+ /**
1684
+ * Verify the signature of a request.
1685
+ *
1686
+ * Tries to verify the signature with the current signing key.
1687
+ * If that fails, maybe because you have rotated the keys recently, it will
1688
+ * try to verify the signature with the next signing key.
1689
+ *
1690
+ * If that fails, the signature is invalid and a `SignatureError` is thrown.
1691
+ */
1692
+ async verify(request) {
1693
+ const isValid = await this.verifyWithKey(this.currentSigningKey, request);
1694
+ if (isValid) {
1695
+ return true;
1696
+ }
1697
+ return this.verifyWithKey(this.nextSigningKey, request);
1698
+ }
1699
+ /**
1700
+ * Verify signature with a specific signing key
1701
+ */
1702
+ async verifyWithKey(key, request) {
1703
+ const jwt = await jose.jwtVerify(request.signature, new TextEncoder().encode(key), {
1704
+ issuer: "Upstash",
1705
+ clockTolerance: request.clockTolerance
1706
+ }).catch((error) => {
1707
+ throw new SignatureError(error.message);
1708
+ });
1709
+ const p = jwt.payload;
1710
+ if (request.url !== void 0 && p.sub !== request.url) {
1711
+ throw new SignatureError(`invalid subject: ${p.sub}, want: ${request.url}`);
1712
+ }
1713
+ const bodyHash = import_crypto_js.default.SHA256(request.body).toString(import_crypto_js.default.enc.Base64url);
1714
+ const padding = new RegExp(/=+$/);
1715
+ if (p.body.replace(padding, "") !== bodyHash.replace(padding, "")) {
1716
+ throw new SignatureError(`body hash does not match, want: ${p.body}, got: ${bodyHash}`);
1717
+ }
1718
+ return true;
1719
+ }
1720
+ };
1721
+
1722
+ // src/client/dlq.ts
1723
+ var DLQ = class {
1724
+ http;
1725
+ constructor(http) {
1726
+ this.http = http;
1727
+ }
1728
+ /**
1729
+ * List messages in the dlq
1730
+ */
1731
+ async listMessages(options) {
1732
+ const filterPayload = {
1733
+ ...options?.filter,
1734
+ topicName: options?.filter?.urlGroup
1735
+ };
1736
+ const messagesPayload = await this.http.request({
1737
+ method: "GET",
1738
+ path: ["v2", "dlq"],
1739
+ query: {
1740
+ cursor: options?.cursor,
1741
+ count: options?.count,
1742
+ ...filterPayload
1743
+ }
1744
+ });
1745
+ return {
1746
+ messages: messagesPayload.messages.map((message) => {
1747
+ return {
1748
+ ...message,
1749
+ urlGroup: message.topicName
1750
+ };
1751
+ }),
1752
+ cursor: messagesPayload.cursor
1753
+ };
1754
+ }
1755
+ /**
1756
+ * Remove a message from the dlq using it's `dlqId`
1757
+ */
1758
+ async delete(dlqMessageId) {
1759
+ return await this.http.request({
1760
+ method: "DELETE",
1761
+ path: ["v2", "dlq", dlqMessageId],
1762
+ parseResponseAsJson: false
1763
+ // there is no response
1764
+ });
1765
+ }
1766
+ /**
1767
+ * Remove multiple messages from the dlq using their `dlqId`s
1768
+ */
1769
+ async deleteMany(request) {
1770
+ return await this.http.request({
1771
+ method: "DELETE",
1772
+ path: ["v2", "dlq"],
1773
+ headers: { "Content-Type": "application/json" },
1774
+ body: JSON.stringify({ dlqIds: request.dlqIds })
1775
+ });
1776
+ }
1777
+ };
1778
+
1779
+ // src/client/error.ts
1780
+ var QstashError = class extends Error {
1781
+ constructor(message) {
1782
+ super(message);
1783
+ this.name = "QstashError";
1784
+ }
1785
+ };
1786
+ var QstashRatelimitError = class extends QstashError {
1787
+ limit;
1788
+ remaining;
1789
+ reset;
1790
+ constructor(args) {
1791
+ super(`Exceeded burst rate limit. ${JSON.stringify(args)} `);
1792
+ this.name = "QstashRatelimitError";
1793
+ this.limit = args.limit;
1794
+ this.remaining = args.remaining;
1795
+ this.reset = args.reset;
1796
+ }
1797
+ };
1798
+ var QstashChatRatelimitError = class extends QstashError {
1799
+ limitRequests;
1800
+ limitTokens;
1801
+ remainingRequests;
1802
+ remainingTokens;
1803
+ resetRequests;
1804
+ resetTokens;
1805
+ constructor(args) {
1806
+ super(`Exceeded chat rate limit. ${JSON.stringify(args)} `);
1807
+ this.limitRequests = args["limit-requests"];
1808
+ this.limitTokens = args["limit-tokens"];
1809
+ this.remainingRequests = args["remaining-requests"];
1810
+ this.remainingTokens = args["remaining-tokens"];
1811
+ this.resetRequests = args["reset-requests"];
1812
+ this.resetTokens = args["reset-tokens"];
1813
+ }
1814
+ };
1815
+ var QstashDailyRatelimitError = class extends QstashError {
1816
+ limit;
1817
+ remaining;
1818
+ reset;
1819
+ constructor(args) {
1820
+ super(`Exceeded daily rate limit. ${JSON.stringify(args)} `);
1821
+ this.limit = args.limit;
1822
+ this.remaining = args.remaining;
1823
+ this.reset = args.reset;
1824
+ this.name = "QstashChatRatelimitError";
1825
+ }
1826
+ };
1827
+ var QStashWorkflowError = class extends QstashError {
1828
+ constructor(message) {
1829
+ super(message);
1830
+ this.name = "QStashWorkflowError";
1831
+ }
1832
+ };
1833
+ var QStashWorkflowAbort = class extends Error {
1834
+ stepInfo;
1835
+ stepName;
1836
+ constructor(stepName, stepInfo) {
1837
+ super(
1838
+ `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}'.`
1839
+ );
1840
+ this.name = "QStashWorkflowAbort";
1841
+ this.stepName = stepName;
1842
+ this.stepInfo = stepInfo;
1843
+ }
1844
+ };
1845
+ var formatWorkflowError = (error) => {
1846
+ return error instanceof Error ? {
1847
+ error: error.name,
1848
+ message: error.message
1849
+ } : {
1850
+ error: "Error",
1851
+ message: "An error occured while executing workflow."
1852
+ };
1853
+ };
1854
+
1855
+ // src/client/http.ts
1856
+ var HttpClient = class {
1857
+ baseUrl;
1858
+ authorization;
1859
+ options;
1860
+ retry;
1861
+ constructor(config) {
1862
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
1863
+ this.authorization = config.authorization;
1864
+ this.retry = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1865
+ typeof config.retry === "boolean" && !config.retry ? {
1866
+ attempts: 1,
1867
+ backoff: () => 0
1868
+ } : {
1869
+ attempts: config.retry?.retries ? config.retry.retries + 1 : 5,
1870
+ backoff: config.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50)
1871
+ };
1872
+ }
1873
+ async request(request) {
1874
+ const { response } = await this.requestWithBackoff(request);
1875
+ if (request.parseResponseAsJson === false) {
1876
+ return void 0;
1877
+ }
1878
+ return await response.json();
1879
+ }
1880
+ async *requestStream(request) {
1881
+ const { response } = await this.requestWithBackoff(request);
1882
+ if (!response.body) {
1883
+ throw new Error("No response body");
1884
+ }
1885
+ const body = response.body;
1886
+ const reader = body.getReader();
1887
+ const decoder = new TextDecoder();
1888
+ try {
1889
+ while (true) {
1890
+ const { done, value } = await reader.read();
1891
+ if (done) {
1892
+ break;
1893
+ }
1894
+ const chunkText = decoder.decode(value, { stream: true });
1895
+ const chunks = chunkText.split("\n").filter(Boolean);
1896
+ for (const chunk of chunks) {
1897
+ if (chunk.startsWith("data: ")) {
1898
+ const data = chunk.slice(6);
1899
+ if (data === "[DONE]") {
1900
+ break;
1901
+ }
1902
+ yield JSON.parse(data);
1903
+ }
1904
+ }
1905
+ }
1906
+ } finally {
1907
+ await reader.cancel();
1908
+ }
1909
+ }
1910
+ requestWithBackoff = async (request) => {
1911
+ const [url, requestOptions] = this.processRequest(request);
1912
+ let response = void 0;
1913
+ let error = void 0;
1914
+ for (let index = 0; index < this.retry.attempts; index++) {
1915
+ try {
1916
+ response = await fetch(url.toString(), requestOptions);
1917
+ break;
1918
+ } catch (error_) {
1919
+ error = error_;
1920
+ await new Promise((r) => setTimeout(r, this.retry.backoff(index)));
1921
+ }
1922
+ }
1923
+ if (!response) {
1924
+ throw error ?? new Error("Exhausted all retries");
1925
+ }
1926
+ await this.checkResponse(response);
1927
+ return {
1928
+ response,
1929
+ error
1930
+ };
1931
+ };
1932
+ processRequest = (request) => {
1933
+ const headers = new Headers(request.headers);
1934
+ if (!headers.has("Authorization")) {
1935
+ headers.set("Authorization", this.authorization);
1936
+ }
1937
+ const requestOptions = {
1938
+ method: request.method,
1939
+ headers,
1940
+ body: request.body,
1941
+ keepalive: request.keepalive
1942
+ };
1943
+ const url = new URL([request.baseUrl ?? this.baseUrl, ...request.path].join("/"));
1944
+ if (request.query) {
1945
+ for (const [key, value] of Object.entries(request.query)) {
1946
+ if (value !== void 0) {
1947
+ url.searchParams.set(key, value.toString());
1948
+ }
1949
+ }
1950
+ }
1951
+ return [url.toString(), requestOptions];
1952
+ };
1953
+ async checkResponse(response) {
1954
+ if (response.status === 429) {
1955
+ if (response.headers.get("x-ratelimit-limit-requests")) {
1956
+ throw new QstashChatRatelimitError({
1957
+ "limit-requests": response.headers.get("x-ratelimit-limit-requests"),
1958
+ "limit-tokens": response.headers.get("x-ratelimit-limit-tokens"),
1959
+ "remaining-requests": response.headers.get("x-ratelimit-remaining-requests"),
1960
+ "remaining-tokens": response.headers.get("x-ratelimit-remaining-tokens"),
1961
+ "reset-requests": response.headers.get("x-ratelimit-reset-requests"),
1962
+ "reset-tokens": response.headers.get("x-ratelimit-reset-tokens")
1963
+ });
1964
+ } else if (response.headers.get("RateLimit-Limit")) {
1965
+ throw new QstashDailyRatelimitError({
1966
+ limit: response.headers.get("RateLimit-Limit"),
1967
+ remaining: response.headers.get("RateLimit-Remaining"),
1968
+ reset: response.headers.get("RateLimit-Reset")
1969
+ });
1970
+ }
1971
+ throw new QstashRatelimitError({
1972
+ limit: response.headers.get("Burst-RateLimit-Limit"),
1973
+ remaining: response.headers.get("Burst-RateLimit-Remaining"),
1974
+ reset: response.headers.get("Burst-RateLimit-Reset")
1975
+ });
1976
+ }
1977
+ if (response.status < 200 || response.status >= 300) {
1978
+ const body = await response.text();
1979
+ throw new QstashError(body.length > 0 ? body : `Error: status=${response.status}`);
1980
+ }
1981
+ }
1982
+ };
1983
+
1984
+ // src/client/llm/providers.ts
1985
+ var setupAnalytics = (analytics, providerApiKey, providerBaseUrl, provider) => {
1986
+ if (!analytics)
1987
+ return {};
1988
+ switch (analytics.name) {
1989
+ case "helicone": {
1990
+ switch (provider) {
1991
+ case "upstash": {
1992
+ return {
1993
+ baseURL: "https://qstash.helicone.ai/llm/v1/chat/completions",
1994
+ defaultHeaders: {
1995
+ "Helicone-Auth": `Bearer ${analytics.token}`,
1996
+ Authorization: `Bearer ${providerApiKey}`
1997
+ }
1998
+ };
1999
+ }
2000
+ default: {
2001
+ return {
2002
+ baseURL: "https://gateway.helicone.ai/v1/chat/completions",
2003
+ defaultHeaders: {
2004
+ "Helicone-Auth": `Bearer ${analytics.token}`,
2005
+ "Helicone-Target-Url": providerBaseUrl,
2006
+ Authorization: `Bearer ${providerApiKey}`
2007
+ }
2008
+ };
2009
+ }
2010
+ }
2011
+ }
2012
+ default: {
2013
+ throw new Error("Unknown analytics provider");
2014
+ }
2015
+ }
2016
+ };
2017
+
2018
+ // src/client/llm/chat.ts
2019
+ var Chat = class _Chat {
2020
+ http;
2021
+ token;
2022
+ constructor(http, token) {
2023
+ this.http = http;
2024
+ this.token = token;
2025
+ }
2026
+ static toChatRequest(request) {
2027
+ const messages = [];
2028
+ messages.push(
2029
+ { role: "system", content: request.system },
2030
+ { role: "user", content: request.user }
2031
+ );
2032
+ const chatRequest = { ...request, messages };
2033
+ return chatRequest;
2034
+ }
2035
+ /**
2036
+ * Calls the Upstash completions api given a ChatRequest.
2037
+ *
2038
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
2039
+ * if stream is enabled.
2040
+ *
2041
+ * @param request ChatRequest with messages
2042
+ * @returns Chat completion or stream
2043
+ */
2044
+ create = async (request) => {
2045
+ if (request.provider.owner != "upstash")
2046
+ return this.createThirdParty(request);
2047
+ const body = JSON.stringify(request);
2048
+ let baseUrl = void 0;
2049
+ let headers = {
2050
+ "Content-Type": "application/json",
2051
+ Authorization: `Bearer ${this.token}`,
2052
+ ..."stream" in request && request.stream ? {
2053
+ Connection: "keep-alive",
2054
+ Accept: "text/event-stream",
2055
+ "Cache-Control": "no-cache"
2056
+ } : {}
2057
+ };
2058
+ if (request.analytics) {
2059
+ const { baseURL, defaultHeaders } = setupAnalytics(
2060
+ { name: "helicone", token: request.analytics.token },
2061
+ this.getAuthorizationToken(),
2062
+ request.provider.baseUrl,
2063
+ "upstash"
2064
+ );
2065
+ headers = { ...headers, ...defaultHeaders };
2066
+ baseUrl = baseURL;
2067
+ }
2068
+ const path = request.analytics ? [] : ["llm", "v1", "chat", "completions"];
2069
+ return "stream" in request && request.stream ? this.http.requestStream({
2070
+ path,
2071
+ method: "POST",
2072
+ headers,
2073
+ baseUrl,
2074
+ body
2075
+ }) : this.http.request({
2076
+ path,
2077
+ method: "POST",
2078
+ headers,
2079
+ baseUrl,
2080
+ body
2081
+ });
2082
+ };
2083
+ /**
2084
+ * Calls the Upstash completions api given a ChatRequest.
2085
+ *
2086
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
2087
+ * if stream is enabled.
2088
+ *
2089
+ * @param request ChatRequest with messages
2090
+ * @returns Chat completion or stream
2091
+ */
2092
+ // eslint-disable-next-line @typescript-eslint/require-await
2093
+ createThirdParty = async (request) => {
2094
+ const { baseUrl, token, owner } = request.provider;
2095
+ if (owner === "upstash")
2096
+ throw new Error("Upstash is not 3rd party provider!");
2097
+ delete request.provider;
2098
+ delete request.system;
2099
+ const analytics = request.analytics;
2100
+ delete request.analytics;
2101
+ const body = JSON.stringify(request);
2102
+ const isAnalyticsEnabled = analytics?.name && analytics.token;
2103
+ const analyticsConfig = analytics?.name && analytics.token ? setupAnalytics({ name: analytics.name, token: analytics.token }, token, baseUrl, owner) : { defaultHeaders: void 0, baseURL: baseUrl };
2104
+ const isStream = "stream" in request && request.stream;
2105
+ const headers = {
2106
+ "Content-Type": "application/json",
2107
+ Authorization: `Bearer ${token}`,
2108
+ ...isStream ? {
2109
+ Connection: "keep-alive",
2110
+ Accept: "text/event-stream",
2111
+ "Cache-Control": "no-cache"
2112
+ } : {},
2113
+ ...analyticsConfig.defaultHeaders
2114
+ };
2115
+ const response = await this.http[isStream ? "requestStream" : "request"]({
2116
+ path: isAnalyticsEnabled ? [] : ["v1", "chat", "completions"],
2117
+ method: "POST",
2118
+ headers,
2119
+ body,
2120
+ baseUrl: analyticsConfig.baseURL
2121
+ });
2122
+ return response;
2123
+ };
2124
+ // Helper method to get the authorization token
2125
+ getAuthorizationToken() {
2126
+ const authHeader = String(this.http.authorization);
2127
+ const match = /Bearer (.+)/.exec(authHeader);
2128
+ if (!match) {
2129
+ throw new Error("Invalid authorization header format");
2130
+ }
2131
+ return match[1];
2132
+ }
2133
+ /**
2134
+ * Calls the Upstash completions api given a PromptRequest.
2135
+ *
2136
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
2137
+ * if stream is enabled.
2138
+ *
2139
+ * @param request PromptRequest with system and user messages.
2140
+ * Note that system parameter shouldn't be passed in the case of
2141
+ * mistralai/Mistral-7B-Instruct-v0.2 model.
2142
+ * @returns Chat completion or stream
2143
+ */
2144
+ prompt = async (request) => {
2145
+ const chatRequest = _Chat.toChatRequest(request);
2146
+ return this.create(chatRequest);
2147
+ };
2148
+ };
2149
+
2150
+ // src/client/llm/utils.ts
2151
+ function appendLLMOptionsIfNeeded(request, headers, http) {
2152
+ if (!request.api)
2153
+ return;
2154
+ const provider = request.api.provider;
2155
+ const analytics = request.api.analytics;
2156
+ if (provider?.owner === "upstash") {
2157
+ handleUpstashProvider(request, headers, http, analytics);
2158
+ return;
2159
+ }
2160
+ if (!("provider" in request.api))
2161
+ return;
2162
+ const { baseUrl, token } = validateProviderConfig(provider);
2163
+ const analyticsConfig = analytics ? setupAnalytics({ name: analytics.name, token: analytics.token }, token, baseUrl, "custom") : void 0;
2164
+ if (analyticsConfig) {
2165
+ setAnalyticsHeaders(headers, analyticsConfig);
2166
+ request.url = analyticsConfig.baseURL;
2167
+ } else {
2168
+ request.url = `${baseUrl}/v1/chat/completions`;
2169
+ headers.set("Authorization", `Bearer ${token}`);
2170
+ }
2171
+ }
2172
+ function handleUpstashProvider(request, headers, http, analytics) {
2173
+ if (analytics) {
2174
+ const analyticsConfig = setupAnalytics(
2175
+ { name: analytics.name, token: analytics.token },
2176
+ //@ts-expect-error hacky way to get bearer token
2177
+ String(http.authorization).split("Bearer ")[1],
2178
+ request.api?.provider?.baseUrl,
2179
+ "upstash"
2180
+ );
2181
+ setAnalyticsHeaders(headers, analyticsConfig);
2182
+ request.url = analyticsConfig.baseURL;
2183
+ } else {
2184
+ request.api = { name: "llm" };
2185
+ }
2186
+ }
2187
+ function validateProviderConfig(provider) {
2188
+ if (!provider?.baseUrl)
2189
+ throw new Error("baseUrl cannot be empty or undefined!");
2190
+ if (!provider.token)
2191
+ throw new Error("token cannot be empty or undefined!");
2192
+ return { baseUrl: provider.baseUrl, token: provider.token };
2193
+ }
2194
+ function setAnalyticsHeaders(headers, analyticsConfig) {
2195
+ headers.set("Helicone-Auth", analyticsConfig.defaultHeaders?.["Helicone-Auth"] ?? "");
2196
+ headers.set("Authorization", analyticsConfig.defaultHeaders?.Authorization ?? "");
2197
+ if (analyticsConfig.defaultHeaders?.["Helicone-Target-Url"]) {
2198
+ headers.set("Helicone-Target-Url", analyticsConfig.defaultHeaders["Helicone-Target-Url"]);
2199
+ }
2200
+ }
2201
+ function ensureCallbackPresent(request) {
2202
+ if (request.api?.name === "llm" && !request.callback) {
2203
+ throw new TypeError("Callback cannot be undefined when using LLM");
2204
+ }
2205
+ }
2206
+
2207
+ // src/client/messages.ts
2208
+ var Messages = class {
2209
+ http;
2210
+ constructor(http) {
2211
+ this.http = http;
2212
+ }
2213
+ /**
2214
+ * Get a message
2215
+ */
2216
+ async get(messageId) {
2217
+ const messagePayload = await this.http.request({
2218
+ method: "GET",
2219
+ path: ["v2", "messages", messageId]
2220
+ });
2221
+ const message = {
2222
+ ...messagePayload,
2223
+ urlGroup: messagePayload.topicName
2224
+ };
2225
+ return message;
2226
+ }
2227
+ /**
2228
+ * Cancel a message
2229
+ */
2230
+ async delete(messageId) {
2231
+ return await this.http.request({
2232
+ method: "DELETE",
2233
+ path: ["v2", "messages", messageId],
2234
+ parseResponseAsJson: false
2235
+ });
2236
+ }
2237
+ async deleteMany(messageIds) {
2238
+ const result = await this.http.request({
2239
+ method: "DELETE",
2240
+ path: ["v2", "messages"],
2241
+ headers: { "Content-Type": "application/json" },
2242
+ body: JSON.stringify({ messageIds })
2243
+ });
2244
+ return result.cancelled;
2245
+ }
2246
+ async deleteAll() {
2247
+ const result = await this.http.request({
2248
+ method: "DELETE",
2249
+ path: ["v2", "messages"]
2250
+ });
2251
+ return result.cancelled;
2252
+ }
2253
+ };
2254
+
2255
+ // src/client/utils.ts
2256
+ var isIgnoredHeader = (header) => {
2257
+ const lowerCaseHeader = header.toLowerCase();
2258
+ return lowerCaseHeader.startsWith("content-type") || lowerCaseHeader.startsWith("upstash-");
2259
+ };
2260
+ function prefixHeaders(headers) {
2261
+ const keysToBePrefixed = [...headers.keys()].filter((key) => !isIgnoredHeader(key));
2262
+ for (const key of keysToBePrefixed) {
2263
+ const value = headers.get(key);
2264
+ if (value !== null) {
2265
+ headers.set(`Upstash-Forward-${key}`, value);
2266
+ }
2267
+ headers.delete(key);
2268
+ }
2269
+ return headers;
2270
+ }
2271
+ function processHeaders(request) {
2272
+ const headers = prefixHeaders(new Headers(request.headers));
2273
+ headers.set("Upstash-Method", request.method ?? "POST");
2274
+ if (request.delay !== void 0) {
2275
+ if (typeof request.delay === "string") {
2276
+ headers.set("Upstash-Delay", request.delay);
2277
+ } else {
2278
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
2279
+ }
2280
+ }
2281
+ if (request.notBefore !== void 0) {
2282
+ headers.set("Upstash-Not-Before", request.notBefore.toFixed(0));
2283
+ }
2284
+ if (request.deduplicationId !== void 0) {
2285
+ headers.set("Upstash-Deduplication-Id", request.deduplicationId);
2286
+ }
2287
+ if (request.contentBasedDeduplication !== void 0) {
2288
+ headers.set("Upstash-Content-Based-Deduplication", "true");
2289
+ }
2290
+ if (request.retries !== void 0) {
2291
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
2292
+ }
2293
+ if (request.callback !== void 0) {
2294
+ headers.set("Upstash-Callback", request.callback);
2295
+ }
2296
+ if (request.failureCallback !== void 0) {
2297
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
2298
+ }
2299
+ if (request.timeout !== void 0) {
2300
+ if (typeof request.timeout === "string") {
2301
+ headers.set("Upstash-Timeout", request.timeout);
2302
+ } else {
2303
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
2304
+ }
2305
+ }
2306
+ return headers;
2307
+ }
2308
+ function getRequestPath(request) {
2309
+ return request.url ?? request.urlGroup ?? request.topic ?? `api/${request.api?.name}`;
2310
+ }
2311
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
2312
+ var NANOID_LENGTH = 21;
2313
+ function nanoid() {
2314
+ return [...crypto.getRandomValues(new Uint8Array(NANOID_LENGTH))].map((x) => NANOID_CHARS[x % NANOID_CHARS.length]).join("");
2315
+ }
2316
+ function decodeBase64(base64) {
2317
+ try {
2318
+ const binString = atob(base64);
2319
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
2320
+ return new TextDecoder().decode(intArray);
2321
+ } catch (error) {
2322
+ console.warn(
2323
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. Error: ${error}`
2324
+ );
2325
+ return atob(base64);
2326
+ }
2327
+ }
2328
+
2329
+ // src/client/queue.ts
2330
+ var Queue = class {
2331
+ http;
2332
+ queueName;
2333
+ constructor(http, queueName) {
2334
+ this.http = http;
2335
+ this.queueName = queueName;
2336
+ }
2337
+ /**
2338
+ * Create or update the queue
2339
+ */
2340
+ async upsert(request) {
2341
+ if (!this.queueName) {
2342
+ throw new Error("Please provide a queue name to the Queue constructor");
2343
+ }
2344
+ const body = {
2345
+ queueName: this.queueName,
2346
+ parallelism: request.parallelism ?? 1,
2347
+ paused: request.paused ?? false
2348
+ };
2349
+ await this.http.request({
2350
+ method: "POST",
2351
+ path: ["v2", "queues"],
2352
+ headers: {
2353
+ "Content-Type": "application/json"
2354
+ },
2355
+ body: JSON.stringify(body),
2356
+ parseResponseAsJson: false
2357
+ });
2358
+ }
2359
+ /**
2360
+ * Get the queue details
2361
+ */
2362
+ async get() {
2363
+ if (!this.queueName) {
2364
+ throw new Error("Please provide a queue name to the Queue constructor");
2365
+ }
2366
+ return await this.http.request({
2367
+ method: "GET",
2368
+ path: ["v2", "queues", this.queueName]
2369
+ });
2370
+ }
2371
+ /**
2372
+ * List queues
2373
+ */
2374
+ async list() {
2375
+ return await this.http.request({
2376
+ method: "GET",
2377
+ path: ["v2", "queues"]
2378
+ });
2379
+ }
2380
+ /**
2381
+ * Delete the queue
2382
+ */
2383
+ async delete() {
2384
+ if (!this.queueName) {
2385
+ throw new Error("Please provide a queue name to the Queue constructor");
2386
+ }
2387
+ await this.http.request({
2388
+ method: "DELETE",
2389
+ path: ["v2", "queues", this.queueName],
2390
+ parseResponseAsJson: false
2391
+ });
2392
+ }
2393
+ /**
2394
+ * Enqueue a message to a queue.
2395
+ */
2396
+ async enqueue(request) {
2397
+ if (!this.queueName) {
2398
+ throw new Error("Please provide a queue name to the Queue constructor");
2399
+ }
2400
+ const headers = processHeaders(request);
2401
+ const destination = getRequestPath(request);
2402
+ const response = await this.http.request({
2403
+ path: ["v2", "enqueue", this.queueName, destination],
2404
+ body: request.body,
2405
+ headers,
2406
+ method: "POST"
2407
+ });
2408
+ return response;
2409
+ }
2410
+ /**
2411
+ * Enqueue a message to a queue, serializing the body to JSON.
2412
+ */
2413
+ async enqueueJSON(request) {
2414
+ const headers = prefixHeaders(new Headers(request.headers));
2415
+ headers.set("Content-Type", "application/json");
2416
+ ensureCallbackPresent(request);
2417
+ appendLLMOptionsIfNeeded(request, headers, this.http);
2418
+ const response = await this.enqueue({
2419
+ ...request,
2420
+ body: JSON.stringify(request.body),
2421
+ headers
2422
+ });
2423
+ return response;
2424
+ }
2425
+ /**
2426
+ * Pauses the queue.
2427
+ *
2428
+ * A paused queue will not deliver messages until
2429
+ * it is resumed.
2430
+ */
2431
+ async pause() {
2432
+ if (!this.queueName) {
2433
+ throw new Error("Please provide a queue name to the Queue constructor");
2434
+ }
2435
+ await this.http.request({
2436
+ method: "POST",
2437
+ path: ["v2", "queues", this.queueName, "pause"],
2438
+ parseResponseAsJson: false
2439
+ });
2440
+ }
2441
+ /**
2442
+ * Resumes the queue.
2443
+ */
2444
+ async resume() {
2445
+ if (!this.queueName) {
2446
+ throw new Error("Please provide a queue name to the Queue constructor");
2447
+ }
2448
+ await this.http.request({
2449
+ method: "POST",
2450
+ path: ["v2", "queues", this.queueName, "resume"],
2451
+ parseResponseAsJson: false
2452
+ });
2453
+ }
2454
+ };
2455
+
2456
+ // src/client/schedules.ts
2457
+ var Schedules = class {
2458
+ http;
2459
+ constructor(http) {
2460
+ this.http = http;
2461
+ }
2462
+ /**
2463
+ * Create a schedule
2464
+ */
2465
+ async create(request) {
2466
+ const headers = prefixHeaders(new Headers(request.headers));
2467
+ if (!headers.has("Content-Type")) {
2468
+ headers.set("Content-Type", "application/json");
2469
+ }
2470
+ headers.set("Upstash-Cron", request.cron);
2471
+ if (request.method !== void 0) {
2472
+ headers.set("Upstash-Method", request.method);
2473
+ }
2474
+ if (request.delay !== void 0) {
2475
+ if (typeof request.delay === "string") {
2476
+ headers.set("Upstash-Delay", request.delay);
2477
+ } else {
2478
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
2479
+ }
2480
+ }
2481
+ if (request.retries !== void 0) {
2482
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
2483
+ }
2484
+ if (request.callback !== void 0) {
2485
+ headers.set("Upstash-Callback", request.callback);
2486
+ }
2487
+ if (request.failureCallback !== void 0) {
2488
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
2489
+ }
2490
+ if (request.timeout !== void 0) {
2491
+ if (typeof request.timeout === "string") {
2492
+ headers.set("Upstash-Timeout", request.timeout);
2493
+ } else {
2494
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
2495
+ }
2496
+ }
2497
+ if (request.scheduleId !== void 0) {
2498
+ headers.set("Upstash-Schedule-Id", request.scheduleId);
2499
+ }
2500
+ return await this.http.request({
2501
+ method: "POST",
2502
+ headers,
2503
+ path: ["v2", "schedules", request.destination],
2504
+ body: request.body
2505
+ });
2506
+ }
2507
+ /**
2508
+ * Get a schedule
2509
+ */
2510
+ async get(scheduleId) {
2511
+ return await this.http.request({
2512
+ method: "GET",
2513
+ path: ["v2", "schedules", scheduleId]
2514
+ });
2515
+ }
2516
+ /**
2517
+ * List your schedules
2518
+ */
2519
+ async list() {
2520
+ return await this.http.request({
2521
+ method: "GET",
2522
+ path: ["v2", "schedules"]
2523
+ });
2524
+ }
2525
+ /**
2526
+ * Delete a schedule
2527
+ */
2528
+ async delete(scheduleId) {
2529
+ return await this.http.request({
2530
+ method: "DELETE",
2531
+ path: ["v2", "schedules", scheduleId],
2532
+ parseResponseAsJson: false
2533
+ });
2534
+ }
2535
+ /**
2536
+ * Pauses the schedule.
2537
+ *
2538
+ * A paused schedule will not deliver messages until
2539
+ * it is resumed.
2540
+ */
2541
+ async pause({ schedule }) {
2542
+ await this.http.request({
2543
+ method: "PATCH",
2544
+ path: ["v2", "schedules", schedule, "pause"],
2545
+ parseResponseAsJson: false
2546
+ });
2547
+ }
2548
+ /**
2549
+ * Resumes the schedule.
2550
+ */
2551
+ async resume({ schedule }) {
2552
+ await this.http.request({
2553
+ method: "PATCH",
2554
+ path: ["v2", "schedules", schedule, "resume"],
2555
+ parseResponseAsJson: false
2556
+ });
2557
+ }
2558
+ };
2559
+
2560
+ // src/client/url-groups.ts
2561
+ var UrlGroups = class {
2562
+ http;
2563
+ constructor(http) {
2564
+ this.http = http;
2565
+ }
2566
+ /**
2567
+ * Create a new url group with the given name and endpoints
2568
+ */
2569
+ async addEndpoints(request) {
2570
+ await this.http.request({
2571
+ method: "POST",
2572
+ path: ["v2", "topics", request.name, "endpoints"],
2573
+ headers: { "Content-Type": "application/json" },
2574
+ body: JSON.stringify({ endpoints: request.endpoints }),
2575
+ parseResponseAsJson: false
2576
+ });
2577
+ }
2578
+ /**
2579
+ * Remove endpoints from a url group.
2580
+ */
2581
+ async removeEndpoints(request) {
2582
+ await this.http.request({
2583
+ method: "DELETE",
2584
+ path: ["v2", "topics", request.name, "endpoints"],
2585
+ headers: { "Content-Type": "application/json" },
2586
+ body: JSON.stringify({ endpoints: request.endpoints }),
2587
+ parseResponseAsJson: false
2588
+ });
2589
+ }
2590
+ /**
2591
+ * Get a list of all url groups.
2592
+ */
2593
+ async list() {
2594
+ return await this.http.request({
2595
+ method: "GET",
2596
+ path: ["v2", "topics"]
2597
+ });
2598
+ }
2599
+ /**
2600
+ * Get a single url group
2601
+ */
2602
+ async get(name) {
2603
+ return await this.http.request({
2604
+ method: "GET",
2605
+ path: ["v2", "topics", name]
2606
+ });
2607
+ }
2608
+ /**
2609
+ * Delete a url group
2610
+ */
2611
+ async delete(name) {
2612
+ return await this.http.request({
2613
+ method: "DELETE",
2614
+ path: ["v2", "topics", name],
2615
+ parseResponseAsJson: false
2616
+ });
2617
+ }
2618
+ };
2619
+
2620
+ // src/client/client.ts
2621
+ var Client = class {
2622
+ http;
2623
+ token;
2624
+ constructor(config) {
2625
+ this.http = new HttpClient({
2626
+ retry: config.retry,
2627
+ baseUrl: config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "https://qstash.upstash.io",
2628
+ authorization: `Bearer ${config.token}`
2629
+ });
2630
+ this.token = config.token;
2631
+ }
2632
+ /**
2633
+ * Access the urlGroup API.
2634
+ *
2635
+ * Create, read, update or delete urlGroups.
2636
+ */
2637
+ get urlGroups() {
2638
+ return new UrlGroups(this.http);
2639
+ }
2640
+ /**
2641
+ * Deprecated. Use urlGroups instead.
2642
+ *
2643
+ * Access the topic API.
2644
+ *
2645
+ * Create, read, update or delete topics.
2646
+ */
2647
+ get topics() {
2648
+ return this.urlGroups;
2649
+ }
2650
+ /**
2651
+ * Access the dlq API.
2652
+ *
2653
+ * List or remove messages from the DLQ.
2654
+ */
2655
+ get dlq() {
2656
+ return new DLQ(this.http);
2657
+ }
2658
+ /**
2659
+ * Access the message API.
2660
+ *
2661
+ * Read or cancel messages.
2662
+ */
2663
+ get messages() {
2664
+ return new Messages(this.http);
2665
+ }
2666
+ /**
2667
+ * Access the schedule API.
2668
+ *
2669
+ * Create, read or delete schedules.
2670
+ */
2671
+ get schedules() {
2672
+ return new Schedules(this.http);
2673
+ }
2674
+ /**
2675
+ * Access the workflow API.
2676
+ *
2677
+ * cancel workflows.
2678
+ */
2679
+ get workflow() {
2680
+ return new Workflow(this.http);
2681
+ }
2682
+ /**
2683
+ * Access the queue API.
2684
+ *
2685
+ * Create, read, update or delete queues.
2686
+ */
2687
+ queue(request) {
2688
+ return new Queue(this.http, request?.queueName);
2689
+ }
2690
+ /**
2691
+ * Access the Chat API
2692
+ *
2693
+ * Call the create or prompt methods
2694
+ */
2695
+ chat() {
2696
+ return new Chat(this.http, this.token);
2697
+ }
2698
+ async publish(request) {
2699
+ const headers = processHeaders(request);
2700
+ const response = await this.http.request({
2701
+ path: ["v2", "publish", getRequestPath(request)],
2702
+ body: request.body,
2703
+ headers,
2704
+ method: "POST"
2705
+ });
2706
+ return response;
2707
+ }
2708
+ /**
2709
+ * publishJSON is a utility wrapper around `publish` that automatically serializes the body
2710
+ * and sets the `Content-Type` header to `application/json`.
2711
+ */
2712
+ async publishJSON(request) {
2713
+ const headers = prefixHeaders(new Headers(request.headers));
2714
+ headers.set("Content-Type", "application/json");
2715
+ ensureCallbackPresent(request);
2716
+ appendLLMOptionsIfNeeded(request, headers, this.http);
2717
+ const response = await this.publish({
2718
+ ...request,
2719
+ headers,
2720
+ body: JSON.stringify(request.body)
2721
+ });
2722
+ return response;
2723
+ }
2724
+ /**
2725
+ * Batch publish messages to QStash.
2726
+ */
2727
+ async batch(request) {
2728
+ const messages = [];
2729
+ for (const message of request) {
2730
+ const headers = processHeaders(message);
2731
+ const headerEntries = Object.fromEntries(headers.entries());
2732
+ messages.push({
2733
+ destination: getRequestPath(message),
2734
+ headers: headerEntries,
2735
+ body: message.body,
2736
+ ...message.queueName && { queue: message.queueName }
2737
+ });
2738
+ }
2739
+ const response = await this.http.request({
2740
+ path: ["v2", "batch"],
2741
+ body: JSON.stringify(messages),
2742
+ headers: {
2743
+ "Content-Type": "application/json"
2744
+ },
2745
+ method: "POST"
2746
+ });
2747
+ const arrayResposne = Array.isArray(response) ? response : [response];
2748
+ return arrayResposne;
2749
+ }
2750
+ /**
2751
+ * Batch publish messages to QStash, serializing each body to JSON.
2752
+ */
2753
+ async batchJSON(request) {
2754
+ for (const message of request) {
2755
+ if ("body" in message) {
2756
+ message.body = JSON.stringify(message.body);
2757
+ }
2758
+ message.headers = new Headers(message.headers);
2759
+ ensureCallbackPresent(message);
2760
+ appendLLMOptionsIfNeeded(message, message.headers, this.http);
2761
+ message.headers.set("Content-Type", "application/json");
2762
+ }
2763
+ const response = await this.batch(request);
2764
+ return response;
2765
+ }
2766
+ /**
2767
+ * Retrieve your logs.
2768
+ *
2769
+ * The logs endpoint is paginated and returns only 100 logs at a time.
2770
+ * If you want to receive more logs, you can use the cursor to paginate.
2771
+ *
2772
+ * The cursor is a unix timestamp with millisecond precision
2773
+ *
2774
+ * @example
2775
+ * ```ts
2776
+ * let cursor = Date.now()
2777
+ * const logs: Log[] = []
2778
+ * while (cursor > 0) {
2779
+ * const res = await qstash.logs({ cursor })
2780
+ * logs.push(...res.logs)
2781
+ * cursor = res.cursor ?? 0
2782
+ * }
2783
+ * ```
2784
+ */
2785
+ async events(request) {
2786
+ const query = {};
2787
+ if (typeof request?.cursor === "number" && request.cursor > 0) {
2788
+ query.cursor = request.cursor.toString();
2789
+ } else if (typeof request?.cursor === "string" && request.cursor !== "") {
2790
+ query.cursor = request.cursor;
2791
+ }
2792
+ for (const [key, value] of Object.entries(request?.filter ?? {})) {
2793
+ if (typeof value === "number" && value < 0) {
2794
+ continue;
2795
+ }
2796
+ if (key === "urlGroup") {
2797
+ query.topicName = value.toString();
2798
+ } else if (typeof value !== "undefined") {
2799
+ query[key] = value.toString();
2800
+ }
2801
+ }
2802
+ const responsePayload = await this.http.request({
2803
+ path: ["v2", "events"],
2804
+ method: "GET",
2805
+ query
2806
+ });
2807
+ return {
2808
+ cursor: responsePayload.cursor,
2809
+ events: responsePayload.events.map((event) => {
2810
+ return {
2811
+ ...event,
2812
+ urlGroup: event.topicName
2813
+ };
2814
+ })
2815
+ };
2816
+ }
2817
+ };
2818
+
2819
+ // src/client/workflow/constants.ts
2820
+ var WORKFLOW_ID_HEADER = "Upstash-Workflow-RunId";
2821
+ var WORKFLOW_INIT_HEADER = "Upstash-Workflow-Init";
2822
+ var WORKFLOW_URL_HEADER = "Upstash-Workflow-Url";
2823
+ var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
2824
+ var WORKFLOW_PROTOCOL_VERSION = "1";
2825
+ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
2826
+ var DEFAULT_CONTENT_TYPE = "application/json";
2827
+ var NO_CONCURRENCY = 1;
2828
+ var DEFAULT_RETRIES = 3;
2829
+
2830
+ // node_modules/neverthrow/dist/index.es.js
2831
+ var defaultErrorConfig = {
2832
+ withStackTrace: false
2833
+ };
2834
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
2835
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
2836
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
2837
+ return {
2838
+ data,
2839
+ message,
2840
+ stack: maybeStack
2841
+ };
2842
+ };
2843
+ function __awaiter(thisArg, _arguments, P, generator) {
2844
+ function adopt(value) {
2845
+ return value instanceof P ? value : new P(function(resolve) {
2846
+ resolve(value);
2847
+ });
2848
+ }
2849
+ return new (P || (P = Promise))(function(resolve, reject) {
2850
+ function fulfilled(value) {
2851
+ try {
2852
+ step(generator.next(value));
2853
+ } catch (e) {
2854
+ reject(e);
2855
+ }
2856
+ }
2857
+ function rejected(value) {
2858
+ try {
2859
+ step(generator["throw"](value));
2860
+ } catch (e) {
2861
+ reject(e);
2862
+ }
2863
+ }
2864
+ function step(result) {
2865
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
2866
+ }
2867
+ step((generator = generator.apply(thisArg, [])).next());
2868
+ });
2869
+ }
2870
+ function __values(o) {
2871
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
2872
+ if (m)
2873
+ return m.call(o);
2874
+ if (o && typeof o.length === "number")
2875
+ return {
2876
+ next: function() {
2877
+ if (o && i >= o.length)
2878
+ o = void 0;
2879
+ return { value: o && o[i++], done: !o };
2880
+ }
2881
+ };
2882
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
2883
+ }
2884
+ function __await(v) {
2885
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
2886
+ }
2887
+ function __asyncGenerator(thisArg, _arguments, generator) {
2888
+ if (!Symbol.asyncIterator)
2889
+ throw new TypeError("Symbol.asyncIterator is not defined.");
2890
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
2891
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
2892
+ return this;
2893
+ }, i;
2894
+ function verb(n) {
2895
+ if (g[n])
2896
+ i[n] = function(v) {
2897
+ return new Promise(function(a, b) {
2898
+ q.push([n, v, a, b]) > 1 || resume(n, v);
2899
+ });
2900
+ };
2901
+ }
2902
+ function resume(n, v) {
2903
+ try {
2904
+ step(g[n](v));
2905
+ } catch (e) {
2906
+ settle(q[0][3], e);
2907
+ }
2908
+ }
2909
+ function step(r) {
2910
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
2911
+ }
2912
+ function fulfill(value) {
2913
+ resume("next", value);
2914
+ }
2915
+ function reject(value) {
2916
+ resume("throw", value);
2917
+ }
2918
+ function settle(f, v) {
2919
+ if (f(v), q.shift(), q.length)
2920
+ resume(q[0][0], q[0][1]);
2921
+ }
2922
+ }
2923
+ function __asyncDelegator(o) {
2924
+ var i, p;
2925
+ return i = {}, verb("next"), verb("throw", function(e) {
2926
+ throw e;
2927
+ }), verb("return"), i[Symbol.iterator] = function() {
2928
+ return this;
2929
+ }, i;
2930
+ function verb(n, f) {
2931
+ i[n] = o[n] ? function(v) {
2932
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
2933
+ } : f;
2934
+ }
2935
+ }
2936
+ function __asyncValues(o) {
2937
+ if (!Symbol.asyncIterator)
2938
+ throw new TypeError("Symbol.asyncIterator is not defined.");
2939
+ var m = o[Symbol.asyncIterator], i;
2940
+ 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() {
2941
+ return this;
2942
+ }, i);
2943
+ function verb(n) {
2944
+ i[n] = o[n] && function(v) {
2945
+ return new Promise(function(resolve, reject) {
2946
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
2947
+ });
2948
+ };
2949
+ }
2950
+ function settle(resolve, reject, d, v) {
2951
+ Promise.resolve(v).then(function(v2) {
2952
+ resolve({ value: v2, done: d });
2953
+ }, reject);
2954
+ }
2955
+ }
2956
+ var ResultAsync = class _ResultAsync {
2957
+ constructor(res) {
2958
+ this._promise = res;
2959
+ }
2960
+ static fromSafePromise(promise) {
2961
+ const newPromise = promise.then((value) => new Ok(value));
2962
+ return new _ResultAsync(newPromise);
2963
+ }
2964
+ static fromPromise(promise, errorFn) {
2965
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
2966
+ return new _ResultAsync(newPromise);
2967
+ }
2968
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2969
+ static fromThrowable(fn, errorFn) {
2970
+ return (...args) => {
2971
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
2972
+ try {
2973
+ return new Ok(yield fn(...args));
2974
+ } catch (error) {
2975
+ return new Err(errorFn ? errorFn(error) : error);
2976
+ }
2977
+ }))());
2978
+ };
2979
+ }
2980
+ static combine(asyncResultList) {
2981
+ return combineResultAsyncList(asyncResultList);
2982
+ }
2983
+ static combineWithAllErrors(asyncResultList) {
2984
+ return combineResultAsyncListWithAllErrors(asyncResultList);
2985
+ }
2986
+ map(f) {
2987
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
2988
+ if (res.isErr()) {
2989
+ return new Err(res.error);
2990
+ }
2991
+ return new Ok(yield f(res.value));
2992
+ })));
2993
+ }
2994
+ mapErr(f) {
2995
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
2996
+ if (res.isOk()) {
2997
+ return new Ok(res.value);
2998
+ }
2999
+ return new Err(yield f(res.error));
3000
+ })));
3001
+ }
3002
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
3003
+ andThen(f) {
3004
+ return new _ResultAsync(this._promise.then((res) => {
3005
+ if (res.isErr()) {
3006
+ return new Err(res.error);
3007
+ }
3008
+ const newValue = f(res.value);
3009
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
3010
+ }));
3011
+ }
3012
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
3013
+ orElse(f) {
3014
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
3015
+ if (res.isErr()) {
3016
+ return f(res.error);
3017
+ }
3018
+ return new Ok(res.value);
3019
+ })));
3020
+ }
3021
+ match(ok2, _err) {
3022
+ return this._promise.then((res) => res.match(ok2, _err));
3023
+ }
3024
+ unwrapOr(t) {
3025
+ return this._promise.then((res) => res.unwrapOr(t));
3026
+ }
3027
+ /**
3028
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
3029
+ */
3030
+ safeUnwrap() {
3031
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
3032
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
3033
+ });
3034
+ }
3035
+ // Makes ResultAsync implement PromiseLike<Result>
3036
+ then(successCallback, failureCallback) {
3037
+ return this._promise.then(successCallback, failureCallback);
3038
+ }
3039
+ };
3040
+ var errAsync = (err2) => new ResultAsync(Promise.resolve(new Err(err2)));
3041
+ var fromPromise = ResultAsync.fromPromise;
3042
+ var fromSafePromise = ResultAsync.fromSafePromise;
3043
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
3044
+ var combineResultList = (resultList) => {
3045
+ let acc = ok([]);
3046
+ for (const result of resultList) {
3047
+ if (result.isErr()) {
3048
+ acc = err(result.error);
3049
+ break;
3050
+ } else {
3051
+ acc.map((list) => list.push(result.value));
3052
+ }
3053
+ }
3054
+ return acc;
3055
+ };
3056
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
3057
+ var combineResultListWithAllErrors = (resultList) => {
3058
+ let acc = ok([]);
3059
+ for (const result of resultList) {
3060
+ if (result.isErr() && acc.isErr()) {
3061
+ acc.error.push(result.error);
3062
+ } else if (result.isErr() && acc.isOk()) {
3063
+ acc = err([result.error]);
3064
+ } else if (result.isOk() && acc.isOk()) {
3065
+ acc.value.push(result.value);
3066
+ }
3067
+ }
3068
+ return acc;
3069
+ };
3070
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
3071
+ var Result;
3072
+ (function(Result2) {
3073
+ function fromThrowable2(fn, errorFn) {
3074
+ return (...args) => {
3075
+ try {
3076
+ const result = fn(...args);
3077
+ return ok(result);
3078
+ } catch (e) {
3079
+ return err(errorFn ? errorFn(e) : e);
3080
+ }
3081
+ };
3082
+ }
3083
+ Result2.fromThrowable = fromThrowable2;
3084
+ function combine(resultList) {
3085
+ return combineResultList(resultList);
3086
+ }
3087
+ Result2.combine = combine;
3088
+ function combineWithAllErrors(resultList) {
3089
+ return combineResultListWithAllErrors(resultList);
3090
+ }
3091
+ Result2.combineWithAllErrors = combineWithAllErrors;
3092
+ })(Result || (Result = {}));
3093
+ var ok = (value) => new Ok(value);
3094
+ var err = (err2) => new Err(err2);
3095
+ var Ok = class {
3096
+ constructor(value) {
3097
+ this.value = value;
3098
+ }
3099
+ isOk() {
3100
+ return true;
3101
+ }
3102
+ isErr() {
3103
+ return !this.isOk();
3104
+ }
3105
+ map(f) {
3106
+ return ok(f(this.value));
3107
+ }
3108
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3109
+ mapErr(_f) {
3110
+ return ok(this.value);
3111
+ }
3112
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
3113
+ andThen(f) {
3114
+ return f(this.value);
3115
+ }
3116
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
3117
+ orElse(_f) {
3118
+ return ok(this.value);
3119
+ }
3120
+ asyncAndThen(f) {
3121
+ return f(this.value);
3122
+ }
3123
+ asyncMap(f) {
3124
+ return ResultAsync.fromSafePromise(f(this.value));
3125
+ }
3126
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3127
+ unwrapOr(_v) {
3128
+ return this.value;
3129
+ }
3130
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3131
+ match(ok2, _err) {
3132
+ return ok2(this.value);
3133
+ }
3134
+ safeUnwrap() {
3135
+ const value = this.value;
3136
+ return function* () {
3137
+ return value;
3138
+ }();
3139
+ }
3140
+ _unsafeUnwrap(_) {
3141
+ return this.value;
3142
+ }
3143
+ _unsafeUnwrapErr(config) {
3144
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
3145
+ }
3146
+ };
3147
+ var Err = class {
3148
+ constructor(error) {
3149
+ this.error = error;
3150
+ }
3151
+ isOk() {
3152
+ return false;
3153
+ }
3154
+ isErr() {
3155
+ return !this.isOk();
3156
+ }
3157
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3158
+ map(_f) {
3159
+ return err(this.error);
3160
+ }
3161
+ mapErr(f) {
3162
+ return err(f(this.error));
3163
+ }
3164
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
3165
+ andThen(_f) {
3166
+ return err(this.error);
3167
+ }
3168
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
3169
+ orElse(f) {
3170
+ return f(this.error);
3171
+ }
3172
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3173
+ asyncAndThen(_f) {
3174
+ return errAsync(this.error);
3175
+ }
3176
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3177
+ asyncMap(_f) {
3178
+ return errAsync(this.error);
3179
+ }
3180
+ unwrapOr(v) {
3181
+ return v;
3182
+ }
3183
+ match(_ok, err2) {
3184
+ return err2(this.error);
3185
+ }
3186
+ safeUnwrap() {
3187
+ const error = this.error;
3188
+ return function* () {
3189
+ yield err(error);
3190
+ throw new Error("Do not use this generator out of `safeTry`");
3191
+ }();
3192
+ }
3193
+ _unsafeUnwrap(config) {
3194
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
3195
+ }
3196
+ _unsafeUnwrapErr(_) {
3197
+ return this.error;
3198
+ }
3199
+ };
3200
+ var fromThrowable = Result.fromThrowable;
3201
+
3202
+ // src/client/workflow/types.ts
3203
+ var StepTypes = ["Initial", "Run", "SleepFor", "SleepUntil", "Call"];
3204
+
3205
+ // src/client/workflow/workflow-requests.ts
3206
+ var triggerFirstInvocation = async (workflowContext, retries, debug) => {
3207
+ const headers = getHeaders(
3208
+ "true",
3209
+ workflowContext.workflowRunId,
3210
+ workflowContext.url,
3211
+ workflowContext.headers,
3212
+ void 0,
3213
+ workflowContext.failureUrl,
3214
+ retries
3215
+ );
3216
+ await debug?.log("SUBMIT", "SUBMIT_FIRST_INVOCATION", {
3217
+ headers,
3218
+ requestPayload: workflowContext.requestPayload,
3219
+ url: workflowContext.url
3220
+ });
3221
+ try {
3222
+ await workflowContext.qstashClient.publishJSON({
3223
+ headers,
3224
+ method: "POST",
3225
+ body: workflowContext.requestPayload,
3226
+ url: workflowContext.url
3227
+ });
3228
+ return ok("success");
3229
+ } catch (error) {
3230
+ const error_ = error;
3231
+ return err(error_);
3232
+ }
3233
+ };
3234
+ var triggerRouteFunction = async ({
3235
+ onCleanup,
3236
+ onStep
3237
+ }) => {
3238
+ try {
3239
+ await onStep();
3240
+ await onCleanup();
3241
+ return ok("workflow-finished");
3242
+ } catch (error) {
3243
+ const error_ = error;
3244
+ return error_ instanceof QStashWorkflowAbort ? ok("step-finished") : err(error_);
3245
+ }
3246
+ };
3247
+ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
3248
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
3249
+ deletedWorkflowRunId: workflowContext.workflowRunId
3250
+ });
3251
+ const result = await workflowContext.qstashClient.http.request({
3252
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
3253
+ method: "DELETE",
3254
+ parseResponseAsJson: false
3255
+ });
3256
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", result);
3257
+ };
3258
+ var recreateUserHeaders = (headers) => {
3259
+ const filteredHeaders = new Headers();
3260
+ const pairs = headers.entries();
3261
+ for (const [header, value] of pairs) {
3262
+ const headerLowerCase = header.toLowerCase();
3263
+ if (!headerLowerCase.startsWith("upstash-workflow-") && !headerLowerCase.startsWith("x-vercel-") && !headerLowerCase.startsWith("x-forwarded-") && headerLowerCase !== "cf-connecting-ip") {
3264
+ filteredHeaders.append(header, value);
3265
+ }
3266
+ }
3267
+ return filteredHeaders;
3268
+ };
3269
+ var handleThirdPartyCallResult = async (request, requestPayload, client, workflowUrl, failureUrl, retries, debug) => {
3270
+ try {
3271
+ if (request.headers.get("Upstash-Workflow-Callback")) {
3272
+ const callbackMessage = JSON.parse(requestPayload);
3273
+ if (!(callbackMessage.status >= 200 && callbackMessage.status < 300)) {
3274
+ await debug?.log("WARN", "SUBMIT_THIRD_PARTY_RESULT", {
3275
+ status: callbackMessage.status,
3276
+ body: decodeBase64(callbackMessage.body)
3277
+ });
3278
+ console.warn(
3279
+ `Workflow Warning: "context.call" failed with status ${callbackMessage.status} and will retry (if there are retries remaining). Error Message:
3280
+ ${decodeBase64(callbackMessage.body)}`
3281
+ );
3282
+ return ok("call-will-retry");
3283
+ }
3284
+ const workflowRunId = request.headers.get(WORKFLOW_ID_HEADER);
3285
+ const stepIdString = request.headers.get("Upstash-Workflow-StepId");
3286
+ const stepName = request.headers.get("Upstash-Workflow-StepName");
3287
+ const stepType = request.headers.get("Upstash-Workflow-StepType");
3288
+ const concurrentString = request.headers.get("Upstash-Workflow-Concurrent");
3289
+ const contentType = request.headers.get("Upstash-Workflow-ContentType");
3290
+ if (!(workflowRunId && stepIdString && stepName && StepTypes.includes(stepType) && concurrentString && contentType)) {
3291
+ throw new Error(
3292
+ `Missing info in callback message source header: ${JSON.stringify({
3293
+ workflowRunId,
3294
+ stepIdString,
3295
+ stepName,
3296
+ stepType,
3297
+ concurrentString,
3298
+ contentType
3299
+ })}`
3300
+ );
3301
+ }
3302
+ const userHeaders = recreateUserHeaders(request.headers);
3303
+ const requestHeaders = getHeaders(
3304
+ "false",
3305
+ workflowRunId,
3306
+ workflowUrl,
3307
+ userHeaders,
3308
+ void 0,
3309
+ failureUrl,
3310
+ retries
3311
+ );
3312
+ const callResultStep = {
3313
+ stepId: Number(stepIdString),
3314
+ stepName,
3315
+ stepType,
3316
+ out: decodeBase64(callbackMessage.body),
3317
+ concurrent: Number(concurrentString)
3318
+ };
3319
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
3320
+ step: callResultStep,
3321
+ headers: requestHeaders,
3322
+ url: workflowUrl
3323
+ });
3324
+ const result = await client.publishJSON({
3325
+ headers: requestHeaders,
3326
+ method: "POST",
3327
+ body: callResultStep,
3328
+ url: workflowUrl
3329
+ });
3330
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
3331
+ messageId: result.messageId
3332
+ });
3333
+ return ok("is-call-return");
3334
+ } else {
3335
+ return ok("continue-workflow");
3336
+ }
3337
+ } catch (error) {
3338
+ const isCallReturn = request.headers.get("Upstash-Workflow-Callback");
3339
+ return err(
3340
+ new QStashWorkflowError(
3341
+ `Error when handling call return (isCallReturn=${isCallReturn}): ${error}`
3342
+ )
3343
+ );
3344
+ }
3345
+ };
3346
+ var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step, failureUrl, retries) => {
3347
+ const baseHeaders = {
3348
+ [WORKFLOW_INIT_HEADER]: initHeaderValue,
3349
+ [WORKFLOW_ID_HEADER]: workflowRunId,
3350
+ [WORKFLOW_URL_HEADER]: workflowUrl,
3351
+ [`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`]: WORKFLOW_PROTOCOL_VERSION,
3352
+ ...failureUrl ? {
3353
+ [`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`]: "true",
3354
+ "Upstash-Failure-Callback": failureUrl
3355
+ } : {},
3356
+ ...retries === void 0 ? {} : {
3357
+ "Upstash-Retries": retries.toString()
3358
+ }
3359
+ };
3360
+ if (userHeaders) {
3361
+ for (const header of userHeaders.keys()) {
3362
+ if (step?.callHeaders) {
3363
+ baseHeaders[`Upstash-Callback-Forward-${header}`] = userHeaders.get(header);
3364
+ } else {
3365
+ baseHeaders[`Upstash-Forward-${header}`] = userHeaders.get(header);
3366
+ }
3367
+ }
3368
+ }
3369
+ if (step?.callHeaders) {
3370
+ const forwardedHeaders = Object.fromEntries(
3371
+ Object.entries(step.callHeaders).map(([header, value]) => [
3372
+ `Upstash-Forward-${header}`,
3373
+ value
3374
+ ])
3375
+ );
3376
+ const contentType = step.callHeaders["Content-Type"];
3377
+ return {
3378
+ ...baseHeaders,
3379
+ ...forwardedHeaders,
3380
+ "Upstash-Callback": workflowUrl,
3381
+ "Upstash-Callback-Workflow-RunId": workflowRunId,
3382
+ "Upstash-Callback-Workflow-CallType": "fromCallback",
3383
+ "Upstash-Callback-Workflow-Init": "false",
3384
+ "Upstash-Callback-Workflow-Url": workflowUrl,
3385
+ "Upstash-Callback-Forward-Upstash-Workflow-Callback": "true",
3386
+ "Upstash-Callback-Forward-Upstash-Workflow-StepId": step.stepId.toString(),
3387
+ "Upstash-Callback-Forward-Upstash-Workflow-StepName": step.stepName,
3388
+ "Upstash-Callback-Forward-Upstash-Workflow-StepType": step.stepType,
3389
+ "Upstash-Callback-Forward-Upstash-Workflow-Concurrent": step.concurrent.toString(),
3390
+ "Upstash-Callback-Forward-Upstash-Workflow-ContentType": contentType ?? DEFAULT_CONTENT_TYPE,
3391
+ "Upstash-Workflow-CallType": "toCallback"
3392
+ };
3393
+ }
3394
+ return baseHeaders;
3395
+ };
3396
+ var verifyRequest = async (body, signature, verifier) => {
3397
+ if (!verifier) {
3398
+ return;
3399
+ }
3400
+ try {
3401
+ if (!signature) {
3402
+ throw new Error("`Upstash-Signature` header is not passed.");
3403
+ }
3404
+ const isValid = await verifier.verify({
3405
+ body,
3406
+ signature
3407
+ });
3408
+ if (!isValid) {
3409
+ throw new Error("Signature in `Upstash-Signature` header is not valid");
3410
+ }
3411
+ } catch (error) {
3412
+ throw new QStashWorkflowError(
3413
+ `Failed to verify that the Workflow request comes from QStash: ${error}
3414
+
3415
+ If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
3416
+
3417
+ If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
3418
+ );
3419
+ }
3420
+ };
3421
+
3422
+ // src/client/workflow/auto-executor.ts
3423
+ var AutoExecutor = class _AutoExecutor {
3424
+ context;
3425
+ promises = /* @__PURE__ */ new WeakMap();
3426
+ activeLazyStepList;
3427
+ debug;
3428
+ nonPlanStepCount;
3429
+ steps;
3430
+ indexInCurrentList = 0;
3431
+ stepCount = 0;
3432
+ planStepCount = 0;
3433
+ executingStep = false;
3434
+ constructor(context, steps, debug) {
3435
+ this.context = context;
3436
+ this.debug = debug;
3437
+ this.steps = steps;
3438
+ this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
3439
+ }
3440
+ /**
3441
+ * Adds the step function to the list of step functions to run in
3442
+ * parallel. After adding the function, defers the execution, so
3443
+ * that if there is another step function to be added, it's also
3444
+ * added.
3445
+ *
3446
+ * After all functions are added, list of functions are executed.
3447
+ * If there is a single function, it's executed by itself. If there
3448
+ * are multiple, they are run in parallel.
3449
+ *
3450
+ * If a function is already executing (this.executingStep), this
3451
+ * means that there is a nested step which is not allowed. In this
3452
+ * case, addStep throws QStashWorkflowError.
3453
+ *
3454
+ * @param stepInfo step plan to add
3455
+ * @returns result of the step function
3456
+ */
3457
+ async addStep(stepInfo) {
3458
+ if (this.executingStep) {
3459
+ throw new QStashWorkflowError(
3460
+ `A step can not be run inside another step. Tried to run '${stepInfo.stepName}' inside '${this.executingStep}'`
3461
+ );
3462
+ }
3463
+ this.stepCount += 1;
3464
+ const lazyStepList = this.activeLazyStepList ?? [];
3465
+ if (!this.activeLazyStepList) {
3466
+ this.activeLazyStepList = lazyStepList;
3467
+ this.indexInCurrentList = 0;
3468
+ }
3469
+ lazyStepList.push(stepInfo);
3470
+ const index = this.indexInCurrentList++;
3471
+ const requestComplete = this.deferExecution().then(async () => {
3472
+ if (!this.promises.has(lazyStepList)) {
3473
+ const promise2 = this.getExecutionPromise(lazyStepList);
3474
+ this.promises.set(lazyStepList, promise2);
3475
+ this.activeLazyStepList = void 0;
3476
+ this.planStepCount += lazyStepList.length > 1 ? lazyStepList.length : 0;
3477
+ }
3478
+ const promise = this.promises.get(lazyStepList);
3479
+ return promise;
3480
+ });
3481
+ const result = await requestComplete;
3482
+ return _AutoExecutor.getResult(lazyStepList, result, index);
3483
+ }
3484
+ /**
3485
+ * Wraps a step function to set this.executingStep to step name
3486
+ * before running and set this.executingStep to False after execution
3487
+ * ends.
3488
+ *
3489
+ * this.executingStep allows us to detect nested steps which are not
3490
+ * allowed.
3491
+ *
3492
+ * @param stepName name of the step being wrapped
3493
+ * @param stepFunction step function to wrap
3494
+ * @returns wrapped step function
3495
+ */
3496
+ wrapStep(stepName, stepFunction) {
3497
+ this.executingStep = stepName;
3498
+ const result = stepFunction();
3499
+ this.executingStep = false;
3500
+ return result;
3501
+ }
3502
+ /**
3503
+ * Executes a step:
3504
+ * - If the step result is available in the steps, returns the result
3505
+ * - If the result is not avaiable, runs the function
3506
+ * - Sends the result to QStash
3507
+ *
3508
+ * @param lazyStep lazy step to execute
3509
+ * @returns step result
3510
+ */
3511
+ async runSingle(lazyStep) {
3512
+ if (this.stepCount < this.nonPlanStepCount) {
3513
+ const step = this.steps[this.stepCount + this.planStepCount];
3514
+ validateStep(lazyStep, step);
3515
+ await this.debug?.log("INFO", "RUN_SINGLE", {
3516
+ fromRequest: true,
3517
+ step,
3518
+ stepCount: this.stepCount
3519
+ });
3520
+ return step.out;
3521
+ }
3522
+ const resultStep = await lazyStep.getResultStep(NO_CONCURRENCY, this.stepCount);
3523
+ await this.debug?.log("INFO", "RUN_SINGLE", {
3524
+ fromRequest: false,
3525
+ step: resultStep,
3526
+ stepCount: this.stepCount
3527
+ });
3528
+ await this.submitStepsToQStash([resultStep]);
3529
+ return resultStep.out;
3530
+ }
3531
+ /**
3532
+ * Runs steps in parallel.
3533
+ *
3534
+ * @param stepName parallel step name
3535
+ * @param stepFunctions list of async functions to run in parallel
3536
+ * @returns results of the functions run in parallel
3537
+ */
3538
+ async runParallel(parallelSteps) {
3539
+ const initialStepCount = this.stepCount - (parallelSteps.length - 1);
3540
+ const parallelCallState = this.getParallelCallState(parallelSteps.length, initialStepCount);
3541
+ const sortedSteps = sortSteps(this.steps);
3542
+ const plannedParallelStepCount = sortedSteps[initialStepCount + this.planStepCount]?.concurrent;
3543
+ if (parallelCallState !== "first" && plannedParallelStepCount !== parallelSteps.length) {
3544
+ throw new QStashWorkflowError(
3545
+ `Incompatible number of parallel steps when call state was '${parallelCallState}'. Expected ${parallelSteps.length}, got ${plannedParallelStepCount} from the request.`
3546
+ );
3547
+ }
3548
+ await this.debug?.log("INFO", "RUN_PARALLEL", {
3549
+ parallelCallState,
3550
+ initialStepCount,
3551
+ plannedParallelStepCount,
3552
+ stepCount: this.stepCount,
3553
+ planStepCount: this.planStepCount
3554
+ });
3555
+ switch (parallelCallState) {
3556
+ case "first": {
3557
+ const planSteps = parallelSteps.map(
3558
+ (parallelStep, index) => parallelStep.getPlanStep(parallelSteps.length, initialStepCount + index)
3559
+ );
3560
+ await this.submitStepsToQStash(planSteps);
3561
+ break;
3562
+ }
3563
+ case "partial": {
3564
+ const planStep = this.steps.at(-1);
3565
+ if (!planStep || planStep.targetStep === void 0) {
3566
+ throw new QStashWorkflowError(
3567
+ `There must be a last step and it should have targetStep larger than 0.Received: ${JSON.stringify(planStep)}`
3568
+ );
3569
+ }
3570
+ const stepIndex = planStep.targetStep - initialStepCount;
3571
+ validateStep(parallelSteps[stepIndex], planStep);
3572
+ try {
3573
+ const resultStep = await parallelSteps[stepIndex].getResultStep(
3574
+ parallelSteps.length,
3575
+ planStep.targetStep
3576
+ );
3577
+ await this.submitStepsToQStash([resultStep]);
3578
+ } catch (error) {
3579
+ if (error instanceof QStashWorkflowAbort) {
3580
+ throw error;
3581
+ }
3582
+ throw new QStashWorkflowError(
3583
+ `Error submitting steps to QStash in partial parallel step execution: ${error}`
3584
+ );
3585
+ }
3586
+ break;
3587
+ }
3588
+ case "discard": {
3589
+ throw new QStashWorkflowAbort("discarded parallel");
3590
+ }
3591
+ case "last": {
3592
+ const parallelResultSteps = sortedSteps.filter((step) => step.stepId >= initialStepCount).slice(0, parallelSteps.length);
3593
+ validateParallelSteps(parallelSteps, parallelResultSteps);
3594
+ return parallelResultSteps.map((step) => step.out);
3595
+ }
3596
+ }
3597
+ const fillValue = void 0;
3598
+ return Array.from({ length: parallelSteps.length }).fill(fillValue);
3599
+ }
3600
+ /**
3601
+ * Determines the parallel call state
3602
+ *
3603
+ * First filters the steps to get the steps which are after `initialStepCount` parameter.
3604
+ *
3605
+ * Depending on the remaining steps, decides the parallel state:
3606
+ * - "first": If there are no steps
3607
+ * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
3608
+ * because each step in a parallel execution will have 2 steps: a plan step and a result
3609
+ * step.
3610
+ * - "partial": If the last step is a plan step
3611
+ * - "discard": If the last step is not a plan step. This means that the parallel execution
3612
+ * is in progress (there are still steps to run) and one step has finished and submitted
3613
+ * its result to QStash
3614
+ *
3615
+ * @param parallelStepCount number of steps to run in parallel
3616
+ * @param initialStepCount steps after the parallel invocation
3617
+ * @returns parallel call state
3618
+ */
3619
+ getParallelCallState(parallelStepCount, initialStepCount) {
3620
+ const remainingSteps = this.steps.filter(
3621
+ (step) => (step.targetStep ?? step.stepId) >= initialStepCount
3622
+ );
3623
+ if (remainingSteps.length === 0) {
3624
+ return "first";
3625
+ } else if (remainingSteps.length >= 2 * parallelStepCount) {
3626
+ return "last";
3627
+ } else if (remainingSteps.at(-1)?.targetStep) {
3628
+ return "partial";
3629
+ } else {
3630
+ return "discard";
3631
+ }
3632
+ }
3633
+ /**
3634
+ * sends the steps to QStash as batch
3635
+ *
3636
+ * @param steps steps to send
3637
+ */
3638
+ async submitStepsToQStash(steps) {
3639
+ if (steps.length === 0) {
3640
+ throw new QStashWorkflowError(
3641
+ `Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
3642
+ );
3643
+ }
3644
+ await this.debug?.log("SUBMIT", "SUBMIT_STEP", { length: steps.length, steps });
3645
+ const result = await this.context.qstashClient.batchJSON(
3646
+ steps.map((singleStep) => {
3647
+ const headers = getHeaders(
3648
+ "false",
3649
+ this.context.workflowRunId,
3650
+ this.context.url,
3651
+ this.context.headers,
3652
+ singleStep,
3653
+ this.context.failureUrl,
3654
+ this.context.retries
3655
+ );
3656
+ const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
3657
+ return singleStep.callUrl ? (
3658
+ // if the step is a third party call, we call the third party
3659
+ // url (singleStep.callUrl) and pass information about the workflow
3660
+ // in the headers (handled in getHeaders). QStash makes the request
3661
+ // to callUrl and returns the result to Workflow endpoint.
3662
+ // handleThirdPartyCallResult method sends the result of the third
3663
+ // party call to QStash.
3664
+ {
3665
+ headers,
3666
+ method: singleStep.callMethod,
3667
+ body: singleStep.callBody,
3668
+ url: singleStep.callUrl
3669
+ }
3670
+ ) : (
3671
+ // if the step is not a third party call, we use workflow
3672
+ // endpoint (context.url) as URL when calling QStash. QStash
3673
+ // calls us back with the updated steps list.
3674
+ {
3675
+ headers,
3676
+ method: "POST",
3677
+ body: singleStep,
3678
+ url: this.context.url,
3679
+ notBefore: willWait ? singleStep.sleepUntil : void 0,
3680
+ delay: willWait ? singleStep.sleepFor : void 0
3681
+ }
3682
+ );
3683
+ })
3684
+ );
3685
+ await this.debug?.log("INFO", "SUBMIT_STEP", {
3686
+ messageIds: result.map((message) => {
3687
+ return {
3688
+ message: message.messageId
3689
+ };
3690
+ })
3691
+ });
3692
+ throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
3693
+ }
3694
+ /**
3695
+ * Get the promise by executing the lazt steps list. If there is a single
3696
+ * step, we call `runSingle`. Otherwise `runParallel` is called.
3697
+ *
3698
+ * @param lazyStepList steps list to execute
3699
+ * @returns promise corresponding to the execution
3700
+ */
3701
+ getExecutionPromise(lazyStepList) {
3702
+ return lazyStepList.length === 1 ? this.runSingle(lazyStepList[0]) : this.runParallel(lazyStepList);
3703
+ }
3704
+ /**
3705
+ * @param lazyStepList steps we executed
3706
+ * @param result result of the promise from `getExecutionPromise`
3707
+ * @param index index of the current step
3708
+ * @returns result[index] if lazyStepList > 1, otherwise result
3709
+ */
3710
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
3711
+ static getResult(lazyStepList, result, index) {
3712
+ if (lazyStepList.length === 1) {
3713
+ return result;
3714
+ } else if (Array.isArray(result) && lazyStepList.length === result.length && index < lazyStepList.length) {
3715
+ return result[index];
3716
+ } else {
3717
+ throw new QStashWorkflowError(
3718
+ `Unexpected parallel call result while executing step ${index}: '${result}'. Expected ${lazyStepList.length} many items`
3719
+ );
3720
+ }
3721
+ }
3722
+ async deferExecution() {
3723
+ await Promise.resolve();
3724
+ await Promise.resolve();
3725
+ }
3726
+ };
3727
+ var validateStep = (lazyStep, stepFromRequest) => {
3728
+ if (lazyStep.stepName !== stepFromRequest.stepName) {
3729
+ throw new QStashWorkflowError(
3730
+ `Incompatible step name. Expected '${lazyStep.stepName}', got '${stepFromRequest.stepName}' from the request`
3731
+ );
3732
+ }
3733
+ if (lazyStep.stepType !== stepFromRequest.stepType) {
3734
+ throw new QStashWorkflowError(
3735
+ `Incompatible step type. Expected '${lazyStep.stepType}', got '${stepFromRequest.stepType}' from the request`
3736
+ );
3737
+ }
3738
+ };
3739
+ var validateParallelSteps = (lazySteps, stepsFromRequest) => {
3740
+ try {
3741
+ for (const [index, stepFromRequest] of stepsFromRequest.entries()) {
3742
+ validateStep(lazySteps[index], stepFromRequest);
3743
+ }
3744
+ } catch (error) {
3745
+ if (error instanceof QStashWorkflowError) {
3746
+ const lazyStepNames = lazySteps.map((lazyStep) => lazyStep.stepName);
3747
+ const lazyStepTypes = lazySteps.map((lazyStep) => lazyStep.stepType);
3748
+ const requestStepNames = stepsFromRequest.map((step) => step.stepName);
3749
+ const requestStepTypes = stepsFromRequest.map((step) => step.stepType);
3750
+ throw new QStashWorkflowError(
3751
+ `Incompatible steps detected in parallel execution: ${error.message}
3752
+ > Step Names from the request: ${JSON.stringify(requestStepNames)}
3753
+ Step Types from the request: ${JSON.stringify(requestStepTypes)}
3754
+ > Step Names expected: ${JSON.stringify(lazyStepNames)}
3755
+ Step Types expected: ${JSON.stringify(lazyStepTypes)}`
3756
+ );
3757
+ }
3758
+ throw error;
3759
+ }
3760
+ };
3761
+ var sortSteps = (steps) => {
3762
+ const getStepId = (step) => step.targetStep ?? step.stepId;
3763
+ return steps.toSorted((step, stepOther) => getStepId(step) - getStepId(stepOther));
3764
+ };
3765
+
3766
+ // src/client/workflow/steps.ts
3767
+ var BaseLazyStep = class {
3768
+ stepName;
3769
+ // will be set in the subclasses
3770
+ constructor(stepName) {
3771
+ this.stepName = stepName;
3772
+ }
3773
+ };
3774
+ var LazyFunctionStep = class extends BaseLazyStep {
3775
+ stepFunction;
3776
+ stepType = "Run";
3777
+ constructor(stepName, stepFunction) {
3778
+ super(stepName);
3779
+ this.stepFunction = stepFunction;
3780
+ }
3781
+ getPlanStep(concurrent, targetStep) {
3782
+ {
3783
+ return {
3784
+ stepId: 0,
3785
+ stepName: this.stepName,
3786
+ stepType: this.stepType,
3787
+ concurrent,
3788
+ targetStep
3789
+ };
3790
+ }
3791
+ }
3792
+ async getResultStep(concurrent, stepId) {
3793
+ let result = this.stepFunction();
3794
+ if (result instanceof Promise) {
3795
+ result = await result;
3796
+ }
3797
+ return {
3798
+ stepId,
3799
+ stepName: this.stepName,
3800
+ stepType: this.stepType,
3801
+ out: result,
3802
+ concurrent
3803
+ };
3804
+ }
3805
+ };
3806
+ var LazySleepStep = class extends BaseLazyStep {
3807
+ sleep;
3808
+ stepType = "SleepFor";
3809
+ constructor(stepName, sleep) {
3810
+ super(stepName);
3811
+ this.sleep = sleep;
3812
+ }
3813
+ getPlanStep(concurrent, targetStep) {
3814
+ {
3815
+ return {
3816
+ stepId: 0,
3817
+ stepName: this.stepName,
3818
+ stepType: this.stepType,
3819
+ sleepFor: this.sleep,
3820
+ concurrent,
3821
+ targetStep
3822
+ };
3823
+ }
3824
+ }
3825
+ async getResultStep(concurrent, stepId) {
3826
+ return await Promise.resolve({
3827
+ stepId,
3828
+ stepName: this.stepName,
3829
+ stepType: this.stepType,
3830
+ sleepFor: this.sleep,
3831
+ concurrent
3832
+ });
3833
+ }
3834
+ };
3835
+ var LazySleepUntilStep = class extends BaseLazyStep {
3836
+ sleepUntil;
3837
+ stepType = "SleepUntil";
3838
+ constructor(stepName, sleepUntil) {
3839
+ super(stepName);
3840
+ this.sleepUntil = sleepUntil;
3841
+ }
3842
+ getPlanStep(concurrent, targetStep) {
3843
+ {
3844
+ return {
3845
+ stepId: 0,
3846
+ stepName: this.stepName,
3847
+ stepType: this.stepType,
3848
+ sleepUntil: this.sleepUntil,
3849
+ concurrent,
3850
+ targetStep
3851
+ };
3852
+ }
3853
+ }
3854
+ async getResultStep(concurrent, stepId) {
3855
+ return await Promise.resolve({
3856
+ stepId,
3857
+ stepName: this.stepName,
3858
+ stepType: this.stepType,
3859
+ sleepUntil: this.sleepUntil,
3860
+ concurrent
3861
+ });
3862
+ }
3863
+ };
3864
+ var LazyCallStep = class extends BaseLazyStep {
3865
+ url;
3866
+ method;
3867
+ body;
3868
+ headers;
3869
+ stepType = "Call";
3870
+ constructor(stepName, url, method, body, headers) {
3871
+ super(stepName);
3872
+ this.url = url;
3873
+ this.method = method;
3874
+ this.body = body;
3875
+ this.headers = headers;
3876
+ }
3877
+ getPlanStep(concurrent, targetStep) {
3878
+ {
3879
+ return {
3880
+ stepId: 0,
3881
+ stepName: this.stepName,
3882
+ stepType: this.stepType,
3883
+ concurrent,
3884
+ targetStep
3885
+ };
3886
+ }
3887
+ }
3888
+ async getResultStep(concurrent, stepId) {
3889
+ return await Promise.resolve({
3890
+ stepId,
3891
+ stepName: this.stepName,
3892
+ stepType: this.stepType,
3893
+ concurrent,
3894
+ callUrl: this.url,
3895
+ callMethod: this.method,
3896
+ callBody: this.body,
3897
+ callHeaders: this.headers
3898
+ });
3899
+ }
3900
+ };
3901
+
3902
+ // src/client/workflow/context.ts
3903
+ var WorkflowContext = class {
3904
+ executor;
3905
+ steps;
3906
+ /**
3907
+ * QStash client of the workflow
3908
+ *
3909
+ * Can be overwritten by passing `qstashClient` parameter in `serve`:
3910
+ *
3911
+ * ```ts
3912
+ * import { Client } from "@upstash/qstash"
3913
+ *
3914
+ * export const POST = serve(
3915
+ * async (context) => {
3916
+ * ...
3917
+ * },
3918
+ * {
3919
+ * qstashClient: new Client({...})
3920
+ * }
3921
+ * )
3922
+ * ```
3923
+ */
3924
+ qstashClient;
3925
+ /**
3926
+ * Run id of the workflow
3927
+ */
3928
+ workflowRunId;
3929
+ /**
3930
+ * URL of the workflow
3931
+ *
3932
+ * Can be overwritten by passing a `url` parameter in `serve`:
3933
+ *
3934
+ * ```ts
3935
+ * export const POST = serve(
3936
+ * async (context) => {
3937
+ * ...
3938
+ * },
3939
+ * {
3940
+ * url: "new-url-value"
3941
+ * }
3942
+ * )
3943
+ * ```
3944
+ */
3945
+ url;
3946
+ /**
3947
+ * URL to call in case of workflow failure with QStash failure callback
3948
+ *
3949
+ * https://upstash.com/docs/qstash/features/callbacks#what-is-a-failure-callback
3950
+ *
3951
+ * Can be overwritten by passing a `failureUrl` parameter in `serve`:
3952
+ *
3953
+ * ```ts
3954
+ * export const POST = serve(
3955
+ * async (context) => {
3956
+ * ...
3957
+ * },
3958
+ * {
3959
+ * failureUrl: "new-url-value"
3960
+ * }
3961
+ * )
3962
+ * ```
3963
+ */
3964
+ failureUrl;
3965
+ /**
3966
+ * Payload of the request which started the workflow.
3967
+ *
3968
+ * To specify its type, you can define `serve` as follows:
3969
+ *
3970
+ * ```ts
3971
+ * // set requestPayload type to MyPayload:
3972
+ * export const POST = serve<MyPayload>(
3973
+ * async (context) => {
3974
+ * ...
3975
+ * }
3976
+ * )
3977
+ * ```
3978
+ *
3979
+ * By default, `serve` tries to apply `JSON.parse` to the request payload.
3980
+ * If your payload is encoded in a format other than JSON, you can utilize
3981
+ * the `initialPayloadParser` parameter:
3982
+ *
3983
+ * ```ts
3984
+ * export const POST = serve<MyPayload>(
3985
+ * async (context) => {
3986
+ * ...
3987
+ * },
3988
+ * {
3989
+ * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
3990
+ * }
3991
+ * )
3992
+ * ```
3993
+ */
3994
+ requestPayload;
3995
+ /**
3996
+ * headers of the initial request
3997
+ */
3998
+ headers;
3999
+ /**
4000
+ * initial payload as a raw string
4001
+ */
4002
+ rawInitialPayload;
4003
+ /**
4004
+ * Map of environment variables and their values.
4005
+ *
4006
+ * Can be set using the `env` option of serve:
4007
+ *
4008
+ * ```ts
4009
+ * export const POST = serve<MyPayload>(
4010
+ * async (context) => {
4011
+ * const key = context.env["API_KEY"];
4012
+ * },
4013
+ * {
4014
+ * env: {
4015
+ * "API_KEY": "*****";
4016
+ * }
4017
+ * }
4018
+ * )
4019
+ * ```
4020
+ *
4021
+ * Default value is set to `process.env`.
4022
+ */
4023
+ env;
4024
+ /**
4025
+ * Number of retries
4026
+ */
4027
+ retries;
4028
+ constructor({
4029
+ qstashClient,
4030
+ workflowRunId,
4031
+ headers,
4032
+ steps,
4033
+ url,
4034
+ failureUrl,
4035
+ debug,
4036
+ initialPayload,
4037
+ rawInitialPayload,
4038
+ env,
4039
+ retries
4040
+ }) {
4041
+ this.qstashClient = qstashClient;
4042
+ this.workflowRunId = workflowRunId;
4043
+ this.steps = steps;
4044
+ this.url = url;
4045
+ this.failureUrl = failureUrl;
4046
+ this.headers = headers;
4047
+ this.requestPayload = initialPayload;
4048
+ this.rawInitialPayload = rawInitialPayload ?? JSON.stringify(this.requestPayload);
4049
+ this.env = env ?? {};
4050
+ this.retries = retries ?? DEFAULT_RETRIES;
4051
+ this.executor = new AutoExecutor(this, this.steps, debug);
4052
+ }
4053
+ /**
4054
+ * Executes a workflow step
4055
+ *
4056
+ * ```typescript
4057
+ * const result = await context.run("step 1", () => {
4058
+ * return "result"
4059
+ * })
4060
+ * ```
4061
+ *
4062
+ * Can also be called in parallel and the steps will be executed
4063
+ * simulatenously:
4064
+ *
4065
+ * ```typescript
4066
+ * const [result1, result2] = await Promise.all([
4067
+ * context.run("step 1", () => {
4068
+ * return "result1"
4069
+ * })
4070
+ * context.run("step 2", async () => {
4071
+ * return await fetchResults()
4072
+ * })
4073
+ * ])
4074
+ * ```
4075
+ *
4076
+ * @param stepName name of the step
4077
+ * @param stepFunction step function to be executed
4078
+ * @returns result of the step function
4079
+ */
4080
+ async run(stepName, stepFunction) {
4081
+ const wrappedStepFunction = () => this.executor.wrapStep(stepName, stepFunction);
4082
+ return this.addStep(new LazyFunctionStep(stepName, wrappedStepFunction));
4083
+ }
4084
+ /**
4085
+ * Stops the execution for the duration provided.
4086
+ *
4087
+ * @param stepName
4088
+ * @param duration sleep duration in seconds
4089
+ * @returns undefined
4090
+ */
4091
+ async sleep(stepName, duration) {
4092
+ await this.addStep(new LazySleepStep(stepName, duration));
4093
+ }
4094
+ /**
4095
+ * Stops the execution until the date time provided.
4096
+ *
4097
+ * @param stepName
4098
+ * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
4099
+ * as a Date object or a string (passed to `new Date(datetimeString)`)
4100
+ * @returns undefined
4101
+ */
4102
+ async sleepUntil(stepName, datetime) {
4103
+ let time;
4104
+ if (typeof datetime === "number") {
4105
+ time = datetime;
4106
+ } else {
4107
+ datetime = typeof datetime === "string" ? new Date(datetime) : datetime;
4108
+ time = Math.round(datetime.getTime() / 1e3);
4109
+ }
4110
+ await this.addStep(new LazySleepUntilStep(stepName, time));
4111
+ }
4112
+ /**
4113
+ * Makes a third party call through QStash in order to make a
4114
+ * network call without consuming any runtime.
4115
+ *
4116
+ * ```ts
4117
+ * const postResult = await context.call<string>(
4118
+ * "post call step",
4119
+ * `https://www.some-endpoint.com/api`,
4120
+ * "POST",
4121
+ * "my-payload"
4122
+ * );
4123
+ * ```
4124
+ *
4125
+ * tries to parse the result of the request as JSON. If it's
4126
+ * not a JSON which can be parsed, simply returns the response
4127
+ * body as it is.
4128
+ *
4129
+ * @param stepName
4130
+ * @param url url to call
4131
+ * @param method call method
4132
+ * @param body call body
4133
+ * @param headers call headers
4134
+ * @returns call result (parsed as JSON if possible)
4135
+ */
4136
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
4137
+ async call(stepName, url, method, body, headers) {
4138
+ const result = await this.addStep(
4139
+ new LazyCallStep(stepName, url, method, body, headers ?? {})
4140
+ );
4141
+ try {
4142
+ return JSON.parse(result);
4143
+ } catch {
4144
+ return result;
4145
+ }
4146
+ }
4147
+ /**
4148
+ * Adds steps to the executor. Needed so that it can be overwritten in
4149
+ * DisabledWorkflowContext.
4150
+ */
4151
+ async addStep(step) {
4152
+ return await this.executor.addStep(step);
4153
+ }
4154
+ };
4155
+ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
4156
+ static disabledMessage = "disabled-qstash-worklfow-run";
4157
+ /**
4158
+ * overwrite the WorkflowContext.addStep method to always raise QStashWorkflowAbort
4159
+ * error in order to stop the execution whenever we encounter a step.
4160
+ *
4161
+ * @param _step
4162
+ */
4163
+ // eslint-disable-next-line @typescript-eslint/require-await
4164
+ async addStep(_step) {
4165
+ throw new QStashWorkflowAbort(_DisabledWorkflowContext.disabledMessage);
4166
+ }
4167
+ /**
4168
+ * copies the passed context to create a DisabledWorkflowContext. Then, runs the
4169
+ * route function with the new context.
4170
+ *
4171
+ * - returns "run-ended" if there are no steps found or
4172
+ * if the auth failed and user called `return`
4173
+ * - returns "step-found" if DisabledWorkflowContext.addStep is called.
4174
+ * - if there is another error, returns the error.
4175
+ *
4176
+ * @param routeFunction
4177
+ */
4178
+ static async tryAuthentication(routeFunction, context) {
4179
+ const disabledContext = new _DisabledWorkflowContext({
4180
+ qstashClient: new Client({ baseUrl: "disabled-client", token: "disabled-client" }),
4181
+ workflowRunId: context.workflowRunId,
4182
+ headers: context.headers,
4183
+ steps: [],
4184
+ url: context.url,
4185
+ failureUrl: context.failureUrl,
4186
+ initialPayload: context.requestPayload,
4187
+ rawInitialPayload: context.rawInitialPayload,
4188
+ env: context.env,
4189
+ retries: context.retries
4190
+ });
4191
+ try {
4192
+ await routeFunction(disabledContext);
4193
+ } catch (error) {
4194
+ if (error instanceof QStashWorkflowAbort && error.stepName === this.disabledMessage) {
4195
+ return ok("step-found");
4196
+ }
4197
+ return err(error);
4198
+ }
4199
+ return ok("run-ended");
4200
+ }
4201
+ };
4202
+
4203
+ // src/client/workflow/logger.ts
4204
+ var LOG_LEVELS = ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
4205
+ var WorkflowLogger = class _WorkflowLogger {
4206
+ logs = [];
4207
+ options;
4208
+ workflowRunId = void 0;
4209
+ constructor(options) {
4210
+ this.options = options;
4211
+ }
4212
+ async log(level, eventType, details) {
4213
+ if (this.shouldLog(level)) {
4214
+ const timestamp = Date.now();
4215
+ const logEntry = {
4216
+ timestamp,
4217
+ workflowRunId: this.workflowRunId ?? "",
4218
+ logLevel: level,
4219
+ eventType,
4220
+ details
4221
+ };
4222
+ this.logs.push(logEntry);
4223
+ if (this.options.logOutput === "console") {
4224
+ this.writeToConsole(logEntry);
4225
+ }
4226
+ await new Promise((resolve) => setTimeout(resolve, 100));
4227
+ }
4228
+ }
4229
+ setWorkflowRunId(workflowRunId) {
4230
+ this.workflowRunId = workflowRunId;
4231
+ }
4232
+ writeToConsole(logEntry) {
4233
+ const JSON_SPACING = 2;
4234
+ console.log(JSON.stringify(logEntry, void 0, JSON_SPACING));
4235
+ }
4236
+ shouldLog(level) {
4237
+ return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(this.options.logLevel);
4238
+ }
4239
+ static getLogger(verbose) {
4240
+ if (typeof verbose === "object") {
4241
+ return verbose;
4242
+ } else {
4243
+ return verbose ? new _WorkflowLogger({
4244
+ logLevel: "INFO",
4245
+ logOutput: "console"
4246
+ }) : void 0;
4247
+ }
4248
+ }
4249
+ };
4250
+
4251
+ // src/client/workflow/workflow-parser.ts
4252
+ var getPayload = async (request) => {
4253
+ try {
4254
+ return await request.text();
4255
+ } catch {
4256
+ return;
4257
+ }
4258
+ };
4259
+ var parsePayload = (rawPayload) => {
4260
+ const [encodedInitialPayload, ...encodedSteps] = JSON.parse(rawPayload);
4261
+ const rawInitialPayload = decodeBase64(encodedInitialPayload.body);
4262
+ const initialStep = {
4263
+ stepId: 0,
4264
+ stepName: "init",
4265
+ stepType: "Initial",
4266
+ out: rawInitialPayload,
4267
+ concurrent: NO_CONCURRENCY
4268
+ };
4269
+ const stepsToDecode = encodedSteps.filter((step) => step.callType === "step");
4270
+ const otherSteps = stepsToDecode.map((rawStep) => {
4271
+ return JSON.parse(decodeBase64(rawStep.body));
4272
+ });
4273
+ const steps = [initialStep, ...otherSteps];
4274
+ return {
4275
+ rawInitialPayload,
4276
+ steps
4277
+ };
4278
+ };
4279
+ var deduplicateSteps = (steps) => {
4280
+ const targetStepIds = [];
4281
+ const stepIds = [];
4282
+ const deduplicatedSteps = [];
4283
+ for (const step of steps) {
4284
+ if (step.stepId === 0) {
4285
+ if (!targetStepIds.includes(step.targetStep ?? 0)) {
4286
+ deduplicatedSteps.push(step);
4287
+ targetStepIds.push(step.targetStep ?? 0);
4288
+ }
4289
+ } else {
4290
+ if (!stepIds.includes(step.stepId)) {
4291
+ deduplicatedSteps.push(step);
4292
+ stepIds.push(step.stepId);
4293
+ }
4294
+ }
4295
+ }
4296
+ return deduplicatedSteps;
4297
+ };
4298
+ var checkIfLastOneIsDuplicate = async (steps, debug) => {
4299
+ if (steps.length < 2) {
4300
+ return false;
4301
+ }
4302
+ const lastStep = steps.at(-1);
4303
+ const lastStepId = lastStep.stepId;
4304
+ const lastTargetStepId = lastStep.targetStep;
4305
+ for (let index = 0; index < steps.length - 1; index++) {
4306
+ const step = steps[index];
4307
+ if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
4308
+ 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.`;
4309
+ await debug?.log("WARN", "RESPONSE_DEFAULT", message);
4310
+ console.warn(message);
4311
+ return true;
4312
+ }
4313
+ }
4314
+ return false;
4315
+ };
4316
+ var validateRequest = (request) => {
4317
+ const versionHeader = request.headers.get(WORKFLOW_PROTOCOL_VERSION_HEADER);
4318
+ const isFirstInvocation = !versionHeader;
4319
+ if (!isFirstInvocation && versionHeader !== WORKFLOW_PROTOCOL_VERSION) {
4320
+ throw new QStashWorkflowError(
4321
+ `Incompatible workflow sdk protocol version. Expected ${WORKFLOW_PROTOCOL_VERSION}, got ${versionHeader} from the request.`
4322
+ );
4323
+ }
4324
+ const workflowRunId = isFirstInvocation ? `wfr_${nanoid()}` : request.headers.get(WORKFLOW_ID_HEADER) ?? "";
4325
+ if (workflowRunId.length === 0) {
4326
+ throw new QStashWorkflowError("Couldn't get workflow id from header");
4327
+ }
4328
+ return {
4329
+ isFirstInvocation,
4330
+ workflowRunId
4331
+ };
4332
+ };
4333
+ var parseRequest = async (requestPayload, isFirstInvocation, debug) => {
4334
+ if (isFirstInvocation) {
4335
+ return {
4336
+ rawInitialPayload: requestPayload ?? "",
4337
+ steps: [],
4338
+ isLastDuplicate: false
4339
+ };
4340
+ } else {
4341
+ if (!requestPayload) {
4342
+ throw new QStashWorkflowError("Only first call can have an empty body");
4343
+ }
4344
+ const { rawInitialPayload, steps } = parsePayload(requestPayload);
4345
+ const isLastDuplicate = await checkIfLastOneIsDuplicate(steps, debug);
4346
+ const deduplicatedSteps = deduplicateSteps(steps);
4347
+ return {
4348
+ rawInitialPayload,
4349
+ steps: deduplicatedSteps,
4350
+ isLastDuplicate
4351
+ };
4352
+ }
4353
+ };
4354
+ var handleFailure = async (request, requestPayload, qstashClient, initialPayloadParser, failureFunction, debug) => {
4355
+ if (request.headers.get(WORKFLOW_FAILURE_HEADER) !== "true") {
4356
+ return ok("not-failure-callback");
4357
+ }
4358
+ if (!failureFunction) {
4359
+ return err(
4360
+ new QStashWorkflowError(
4361
+ "Workflow endpoint is called to handle a failure, but a failureFunction is not provided in serve options. Either provide a failureUrl or a failureFunction."
4362
+ )
4363
+ );
4364
+ }
4365
+ try {
4366
+ const { status, header, body, url, sourceHeader, sourceBody, workflowRunId } = JSON.parse(
4367
+ requestPayload
4368
+ );
4369
+ const decodedBody = body ? decodeBase64(body) : "{}";
4370
+ const errorPayload = JSON.parse(decodedBody);
4371
+ const {
4372
+ rawInitialPayload,
4373
+ steps,
4374
+ isLastDuplicate: _isLastDuplicate
4375
+ } = await parseRequest(decodeBase64(sourceBody), false, debug);
4376
+ const workflowContext = new WorkflowContext({
4377
+ qstashClient,
4378
+ workflowRunId,
4379
+ initialPayload: initialPayloadParser(rawInitialPayload),
4380
+ rawInitialPayload,
4381
+ headers: recreateUserHeaders(new Headers(sourceHeader)),
4382
+ steps,
4383
+ url,
4384
+ failureUrl: url,
4385
+ debug
4386
+ });
4387
+ await failureFunction(workflowContext, status, errorPayload.message, header);
4388
+ } catch (error) {
4389
+ return err(error);
4390
+ }
4391
+ return ok("is-failure-callback");
4392
+ };
2
4393
 
4394
+ // src/client/workflow/serve.ts
4395
+ var processOptions = (options) => {
4396
+ const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
4397
+ const receiverEnvironmentVariablesSet = Boolean(
4398
+ environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
4399
+ );
4400
+ return {
4401
+ qstashClient: new Client({
4402
+ baseUrl: environment.QSTASH_URL,
4403
+ token: environment.QSTASH_TOKEN
4404
+ }),
4405
+ onStepFinish: (workflowRunId, _finishCondition) => new Response(JSON.stringify({ workflowRunId }), {
4406
+ status: 200
4407
+ }),
4408
+ initialPayloadParser: (initialRequest) => {
4409
+ if (!initialRequest) {
4410
+ return void 0;
4411
+ }
4412
+ try {
4413
+ return JSON.parse(initialRequest);
4414
+ } catch (error) {
4415
+ if (error instanceof SyntaxError) {
4416
+ return initialRequest;
4417
+ }
4418
+ throw error;
4419
+ }
4420
+ },
4421
+ receiver: receiverEnvironmentVariablesSet ? new Receiver({
4422
+ currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
4423
+ nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
4424
+ }) : void 0,
4425
+ baseUrl: environment.UPSTASH_WORKFLOW_URL,
4426
+ env: environment,
4427
+ retries: DEFAULT_RETRIES,
4428
+ ...options
4429
+ };
4430
+ };
4431
+ var serve = (routeFunction, options) => {
4432
+ const {
4433
+ qstashClient,
4434
+ onStepFinish,
4435
+ initialPayloadParser,
4436
+ url,
4437
+ verbose,
4438
+ receiver,
4439
+ failureUrl,
4440
+ failureFunction,
4441
+ baseUrl,
4442
+ env,
4443
+ retries
4444
+ } = processOptions(options);
4445
+ const debug = WorkflowLogger.getLogger(verbose);
4446
+ const handler = async (request) => {
4447
+ const initialWorkflowUrl = url ?? request.url;
4448
+ const workflowUrl = baseUrl ? initialWorkflowUrl.replace(/^(https?:\/\/[^/]+)(\/.*)?$/, (_, matchedBaseUrl, path) => {
4449
+ return baseUrl + (path || "");
4450
+ }) : initialWorkflowUrl;
4451
+ if (workflowUrl !== initialWorkflowUrl) {
4452
+ await debug?.log("WARN", "ENDPOINT_START", {
4453
+ warning: `QStash Workflow: replacing the base of the url with "${baseUrl}" and using it as workflow endpoint.`,
4454
+ originalURL: initialWorkflowUrl,
4455
+ updatedURL: workflowUrl
4456
+ });
4457
+ }
4458
+ const workflowFailureUrl = failureFunction ? workflowUrl : failureUrl;
4459
+ const requestPayload = await getPayload(request) ?? "";
4460
+ await verifyRequest(requestPayload, request.headers.get("upstash-signature"), receiver);
4461
+ await debug?.log("INFO", "ENDPOINT_START");
4462
+ const failureCheck = await handleFailure(
4463
+ request,
4464
+ requestPayload,
4465
+ qstashClient,
4466
+ initialPayloadParser,
4467
+ failureFunction
4468
+ );
4469
+ if (failureCheck.isErr()) {
4470
+ throw failureCheck.error;
4471
+ } else if (failureCheck.value === "is-failure-callback") {
4472
+ await debug?.log("WARN", "RESPONSE_DEFAULT", "failureFunction executed");
4473
+ return onStepFinish("no-workflow-id", "failure-callback");
4474
+ }
4475
+ const { isFirstInvocation, workflowRunId } = validateRequest(request);
4476
+ debug?.setWorkflowRunId(workflowRunId);
4477
+ const { rawInitialPayload, steps, isLastDuplicate } = await parseRequest(
4478
+ requestPayload,
4479
+ isFirstInvocation,
4480
+ debug
4481
+ );
4482
+ if (isLastDuplicate) {
4483
+ return onStepFinish("no-workflow-id", "duplicate-step");
4484
+ }
4485
+ const workflowContext = new WorkflowContext({
4486
+ qstashClient,
4487
+ workflowRunId,
4488
+ initialPayload: initialPayloadParser(rawInitialPayload),
4489
+ rawInitialPayload,
4490
+ headers: recreateUserHeaders(request.headers),
4491
+ steps,
4492
+ url: workflowUrl,
4493
+ failureUrl: workflowFailureUrl,
4494
+ debug,
4495
+ env
4496
+ });
4497
+ const authCheck = await DisabledWorkflowContext.tryAuthentication(
4498
+ routeFunction,
4499
+ workflowContext
4500
+ );
4501
+ if (authCheck.isErr()) {
4502
+ await debug?.log("ERROR", "ERROR", { error: authCheck.error.message });
4503
+ throw authCheck.error;
4504
+ } else if (authCheck.value === "run-ended") {
4505
+ return onStepFinish("no-workflow-id", "auth-fail");
4506
+ }
4507
+ const callReturnCheck = await handleThirdPartyCallResult(
4508
+ request,
4509
+ rawInitialPayload,
4510
+ qstashClient,
4511
+ workflowUrl,
4512
+ workflowFailureUrl,
4513
+ retries,
4514
+ debug
4515
+ );
4516
+ if (callReturnCheck.isErr()) {
4517
+ await debug?.log("ERROR", "SUBMIT_THIRD_PARTY_RESULT", {
4518
+ error: callReturnCheck.error.message
4519
+ });
4520
+ throw callReturnCheck.error;
4521
+ } else if (callReturnCheck.value === "continue-workflow") {
4522
+ const result = isFirstInvocation ? await triggerFirstInvocation(workflowContext, retries, debug) : await triggerRouteFunction({
4523
+ onStep: async () => routeFunction(workflowContext),
4524
+ onCleanup: async () => {
4525
+ await triggerWorkflowDelete(workflowContext, debug);
4526
+ }
4527
+ });
4528
+ if (result.isErr()) {
4529
+ await debug?.log("ERROR", "ERROR", { error: result.error.message });
4530
+ throw result.error;
4531
+ }
4532
+ await debug?.log("INFO", "RESPONSE_WORKFLOW");
4533
+ return onStepFinish(workflowContext.workflowRunId, "success");
4534
+ }
4535
+ await debug?.log("INFO", "RESPONSE_DEFAULT");
4536
+ return onStepFinish("no-workflow-id", "fromCallback");
4537
+ };
4538
+ return async (request) => {
4539
+ try {
4540
+ return await handler(request);
4541
+ } catch (error) {
4542
+ console.error(error);
4543
+ return new Response(JSON.stringify(formatWorkflowError(error)), { status: 500 });
4544
+ }
4545
+ };
4546
+ };
3
4547
 
4
- var _chunkR5CZPV7Hjs = require('./chunk-R5CZPV7H.js');
4548
+ // src/client/workflow/index.ts
4549
+ var Workflow = class {
4550
+ http;
4551
+ constructor(http) {
4552
+ this.http = http;
4553
+ }
4554
+ /**
4555
+ * Cancel an ongoing workflow
4556
+ *
4557
+ * @param workflowRunId run id of the workflow to delete
4558
+ * @returns true if workflow is succesfully deleted. Otherwise throws QStashError
4559
+ */
4560
+ async cancel(workflowRunId) {
4561
+ const result = await this.http.request({
4562
+ path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
4563
+ method: "DELETE",
4564
+ parseResponseAsJson: false
4565
+ });
4566
+ return result ?? true;
4567
+ }
4568
+ };
5
4569
 
6
4570
  // platforms/nextjs.ts
7
- var _server = require('next/server');
8
4571
  var BAD_REQUEST = 400;
9
4572
  function verifySignature(handler, config) {
10
- const currentSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _ => _.currentSigningKey]), () => ( process.env.QSTASH_CURRENT_SIGNING_KEY));
4573
+ const currentSigningKey = config?.currentSigningKey ?? process.env.QSTASH_CURRENT_SIGNING_KEY;
11
4574
  if (!currentSigningKey) {
12
4575
  throw new Error(
13
4576
  "currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY"
14
4577
  );
15
4578
  }
16
- const nextSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _2 => _2.nextSigningKey]), () => ( process.env.QSTASH_NEXT_SIGNING_KEY));
4579
+ const nextSigningKey = config?.nextSigningKey ?? process.env.QSTASH_NEXT_SIGNING_KEY;
17
4580
  if (!nextSigningKey) {
18
4581
  throw new Error(
19
4582
  "nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY"
20
4583
  );
21
4584
  }
22
- const receiver = new (0, _chunkR5CZPV7Hjs.Receiver)({
4585
+ const receiver = new Receiver({
23
4586
  currentSigningKey,
24
4587
  nextSigningKey
25
4588
  });
@@ -42,7 +4605,7 @@ function verifySignature(handler, config) {
42
4605
  const isValid = await receiver.verify({
43
4606
  signature,
44
4607
  body,
45
- clockTolerance: _optionalChain([config, 'optionalAccess', _3 => _3.clockTolerance])
4608
+ clockTolerance: config?.clockTolerance
46
4609
  });
47
4610
  if (!isValid) {
48
4611
  response.status(BAD_REQUEST);
@@ -52,26 +4615,26 @@ function verifySignature(handler, config) {
52
4615
  }
53
4616
  try {
54
4617
  request.body = request.headers["content-type"] === "application/json" ? JSON.parse(body) : body;
55
- } catch (e) {
4618
+ } catch {
56
4619
  request.body = body;
57
4620
  }
58
4621
  return handler(request, response);
59
4622
  };
60
4623
  }
61
4624
  function verifySignatureEdge(handler, config) {
62
- const currentSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _4 => _4.currentSigningKey]), () => ( process.env.QSTASH_CURRENT_SIGNING_KEY));
4625
+ const currentSigningKey = config?.currentSigningKey ?? process.env.QSTASH_CURRENT_SIGNING_KEY;
63
4626
  if (!currentSigningKey) {
64
4627
  throw new Error(
65
4628
  "currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY"
66
4629
  );
67
4630
  }
68
- const nextSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _5 => _5.nextSigningKey]), () => ( process.env.QSTASH_NEXT_SIGNING_KEY));
4631
+ const nextSigningKey = config?.nextSigningKey ?? process.env.QSTASH_NEXT_SIGNING_KEY;
69
4632
  if (!nextSigningKey) {
70
4633
  throw new Error(
71
4634
  "nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY"
72
4635
  );
73
4636
  }
74
- const receiver = new (0, _chunkR5CZPV7Hjs.Receiver)({
4637
+ const receiver = new Receiver({
75
4638
  currentSigningKey,
76
4639
  nextSigningKey
77
4640
  });
@@ -79,7 +4642,7 @@ function verifySignatureEdge(handler, config) {
79
4642
  const requestClone = request.clone();
80
4643
  const signature = request.headers.get("upstash-signature");
81
4644
  if (!signature) {
82
- return new (0, _server.NextResponse)(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
4645
+ return new import_server.NextResponse(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
83
4646
  status: 403
84
4647
  });
85
4648
  }
@@ -90,28 +4653,28 @@ function verifySignatureEdge(handler, config) {
90
4653
  const isValid = await receiver.verify({
91
4654
  signature,
92
4655
  body,
93
- clockTolerance: _optionalChain([config, 'optionalAccess', _6 => _6.clockTolerance])
4656
+ clockTolerance: config?.clockTolerance
94
4657
  });
95
4658
  if (!isValid) {
96
- return new (0, _server.NextResponse)(new TextEncoder().encode("invalid signature"), { status: 403 });
4659
+ return new import_server.NextResponse(new TextEncoder().encode("invalid signature"), { status: 403 });
97
4660
  }
98
4661
  return handler(request, nfe);
99
4662
  };
100
4663
  }
101
4664
  function verifySignatureAppRouter(handler, config) {
102
- const currentSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _7 => _7.currentSigningKey]), () => ( process.env.QSTASH_CURRENT_SIGNING_KEY));
4665
+ const currentSigningKey = config?.currentSigningKey ?? process.env.QSTASH_CURRENT_SIGNING_KEY;
103
4666
  if (!currentSigningKey) {
104
4667
  throw new Error(
105
4668
  "currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY"
106
4669
  );
107
4670
  }
108
- const nextSigningKey = _nullishCoalesce(_optionalChain([config, 'optionalAccess', _8 => _8.nextSigningKey]), () => ( process.env.QSTASH_NEXT_SIGNING_KEY));
4671
+ const nextSigningKey = config?.nextSigningKey ?? process.env.QSTASH_NEXT_SIGNING_KEY;
109
4672
  if (!nextSigningKey) {
110
4673
  throw new Error(
111
4674
  "nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY"
112
4675
  );
113
4676
  }
114
- const receiver = new (0, _chunkR5CZPV7Hjs.Receiver)({
4677
+ const receiver = new Receiver({
115
4678
  currentSigningKey,
116
4679
  nextSigningKey
117
4680
  });
@@ -119,7 +4682,7 @@ function verifySignatureAppRouter(handler, config) {
119
4682
  const requestClone = request.clone();
120
4683
  const signature = request.headers.get("upstash-signature");
121
4684
  if (!signature) {
122
- return new (0, _server.NextResponse)(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
4685
+ return new import_server.NextResponse(new TextEncoder().encode("`Upstash-Signature` header is missing"), {
123
4686
  status: 403
124
4687
  });
125
4688
  }
@@ -130,17 +4693,17 @@ function verifySignatureAppRouter(handler, config) {
130
4693
  const isValid = await receiver.verify({
131
4694
  signature,
132
4695
  body,
133
- clockTolerance: _optionalChain([config, 'optionalAccess', _9 => _9.clockTolerance])
4696
+ clockTolerance: config?.clockTolerance
134
4697
  });
135
4698
  if (!isValid) {
136
- return new (0, _server.NextResponse)(new TextEncoder().encode("invalid signature"), { status: 403 });
4699
+ return new import_server.NextResponse(new TextEncoder().encode("invalid signature"), { status: 403 });
137
4700
  }
138
4701
  return handler(request, params);
139
4702
  };
140
4703
  }
141
4704
  var serve2 = (routeFunction, options) => {
142
- const handler = _chunkR5CZPV7Hjs.serve.call(void 0, routeFunction, {
143
- onStepFinish: (workflowRunId) => new (0, _server.NextResponse)(JSON.stringify({ workflowRunId }), { status: 200 }),
4705
+ const handler = serve(routeFunction, {
4706
+ onStepFinish: (workflowRunId) => new import_server.NextResponse(JSON.stringify({ workflowRunId }), { status: 200 }),
144
4707
  ...options
145
4708
  });
146
4709
  return async (request) => {
@@ -148,9 +4711,9 @@ var serve2 = (routeFunction, options) => {
148
4711
  };
149
4712
  };
150
4713
  var servePagesRouter = (routeFunction, options) => {
151
- const handler = _chunkR5CZPV7Hjs.serve.call(void 0, routeFunction, options);
4714
+ const handler = serve(routeFunction, options);
152
4715
  return async (req, res) => {
153
- if (_optionalChain([req, 'access', _10 => _10.method, 'optionalAccess', _11 => _11.toUpperCase, 'call', _12 => _12()]) !== "POST") {
4716
+ if (req.method?.toUpperCase() !== "POST") {
154
4717
  res.status(405).json("Only POST requests are allowed in worklfows");
155
4718
  return;
156
4719
  } else if (!req.url) {
@@ -158,10 +4721,10 @@ var servePagesRouter = (routeFunction, options) => {
158
4721
  return;
159
4722
  }
160
4723
  const protocol = req.headers["x-forwarded-proto"];
161
- const baseUrl = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _13 => _13.baseUrl]), () => ( `${protocol}://${req.headers.host}`));
162
- const request = new Request(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _14 => _14.url]), () => ( `${baseUrl}${req.url}`)), {
4724
+ const baseUrl = options?.baseUrl ?? `${protocol}://${req.headers.host}`;
4725
+ const request = new Request(options?.url ?? `${baseUrl}${req.url}`, {
163
4726
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
164
- body: _nullishCoalesce(JSON.stringify(req.body), () => ( "")),
4727
+ body: JSON.stringify(req.body) ?? "",
165
4728
  headers: new Headers(req.headersDistinct),
166
4729
  method: "POST"
167
4730
  });
@@ -169,10 +4732,11 @@ var servePagesRouter = (routeFunction, options) => {
169
4732
  res.status(response.status).json(await response.json());
170
4733
  };
171
4734
  };
172
-
173
-
174
-
175
-
176
-
177
-
178
- exports.serve = serve2; exports.servePagesRouter = servePagesRouter; exports.verifySignature = verifySignature; exports.verifySignatureAppRouter = verifySignatureAppRouter; exports.verifySignatureEdge = verifySignatureEdge;
4735
+ // Annotate the CommonJS export names for ESM import in node:
4736
+ 0 && (module.exports = {
4737
+ serve,
4738
+ servePagesRouter,
4739
+ verifySignature,
4740
+ verifySignatureAppRouter,
4741
+ verifySignatureEdge
4742
+ });