@shopify/cli 3.67.3 → 3.68.0

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.
Files changed (85) hide show
  1. package/dist/{chunk-7BK74JM2.js → chunk-4H7GRGC6.js} +3 -3
  2. package/dist/{chunk-OVBHC7XZ.js → chunk-5VZ6BLBM.js} +3 -3
  3. package/dist/{chunk-ESCACI7K.js → chunk-6IS7OFWG.js} +5 -5
  4. package/dist/{chunk-67E32Z72.js → chunk-7PUJMPXN.js} +5528 -17168
  5. package/dist/{chunk-XHO4O3WD.js → chunk-A3DV6VXO.js} +2 -2
  6. package/dist/{chunk-QQWDDZPJ.js → chunk-C4FBYE7F.js} +4 -4
  7. package/dist/{chunk-CL6KB3RG.js → chunk-D72SCNZ2.js} +6 -2
  8. package/dist/chunk-DD5ULVKP.js +103 -0
  9. package/dist/{chunk-FMTK2DLI.js → chunk-DMM6NVLV.js} +4 -4
  10. package/dist/{chunk-MP5JBUFB.js → chunk-E2OAY724.js} +2 -2
  11. package/dist/{chunk-YZHXAE4H.js → chunk-EUBA2XGP.js} +4 -4
  12. package/dist/{chunk-QK4M5NLW.js → chunk-FIAUTHMT.js} +2 -2
  13. package/dist/{chunk-SK3QXUXV.js → chunk-FKQTUQ3O.js} +4 -4
  14. package/dist/{chunk-Y6XYGV3K.js → chunk-G47SEBU3.js} +3 -3
  15. package/dist/{chunk-IVO3C5LM.js → chunk-GDKBDEZV.js} +3 -3
  16. package/dist/{chunk-UOH7XDLM.js → chunk-HTDUPJH5.js} +3 -3
  17. package/dist/{chunk-SAKJRSNZ.js → chunk-IL455HI5.js} +3 -3
  18. package/dist/{chunk-J44K26AK.js → chunk-INEJACZ7.js} +3 -3
  19. package/dist/{chunk-X2LIPDBQ.js → chunk-JAH3NBCG.js} +4 -4
  20. package/dist/{chunk-SERYSNVE.js → chunk-JAQZDU4S.js} +2 -2
  21. package/dist/{chunk-ADIIAXPI.js → chunk-JJOZP7G6.js} +3 -3
  22. package/dist/{chunk-UE5ILNA5.js → chunk-JR6ZN4TY.js} +4 -4
  23. package/dist/{chunk-5GMBDXCT.js → chunk-MXZ6B3TP.js} +2 -2
  24. package/dist/{chunk-EMUNMNK7.js → chunk-NCUKAORS.js} +6 -6
  25. package/dist/{chunk-NBY455BA.js → chunk-OBX5DIH4.js} +4 -4
  26. package/dist/{chunk-FPTBJGSU.js → chunk-QIBFYG6F.js} +3 -3
  27. package/dist/{chunk-NV2K2JNI.js → chunk-RUR45G5U.js} +15 -3
  28. package/dist/{chunk-VVCAHOHL.js → chunk-UCYJX4VB.js} +2 -2
  29. package/dist/{chunk-UI7DIACQ.js → chunk-VVY6VJR6.js} +2 -2
  30. package/dist/{chunk-AYJMV2UJ.js → chunk-WJBW5QHV.js} +2 -2
  31. package/dist/chunk-WUA6LTEH.js +15959 -0
  32. package/dist/{chunk-F2FF5RRS.js → chunk-XCGES3AJ.js} +3 -3
  33. package/dist/{chunk-GBZFBWCM.js → chunk-YKH4ILAB.js} +14 -12
  34. package/dist/{chunk-UTJGWPED.js → chunk-ZJZ3SGOJ.js} +2 -2
  35. package/dist/cli/commands/auth/logout.js +11 -12
  36. package/dist/cli/commands/auth/logout.test.js +12 -13
  37. package/dist/cli/commands/debug/command-flags.js +10 -9
  38. package/dist/cli/commands/demo/catalog.js +11 -11
  39. package/dist/cli/commands/demo/generate-file.js +11 -11
  40. package/dist/cli/commands/demo/index.js +11 -11
  41. package/dist/cli/commands/demo/print-ai-prompt.js +11 -11
  42. package/dist/cli/commands/docs/generate.js +10 -9
  43. package/dist/cli/commands/docs/generate.test.js +10 -9
  44. package/dist/cli/commands/help.js +10 -9
  45. package/dist/cli/commands/kitchen-sink/async.js +11 -10
  46. package/dist/cli/commands/kitchen-sink/async.test.js +11 -10
  47. package/dist/cli/commands/kitchen-sink/index.js +13 -12
  48. package/dist/cli/commands/kitchen-sink/index.test.js +13 -12
  49. package/dist/cli/commands/kitchen-sink/prompts.js +11 -10
  50. package/dist/cli/commands/kitchen-sink/prompts.test.js +11 -10
  51. package/dist/cli/commands/kitchen-sink/static.js +11 -10
  52. package/dist/cli/commands/kitchen-sink/static.test.js +11 -10
  53. package/dist/cli/commands/search.js +11 -10
  54. package/dist/cli/commands/upgrade.js +11 -10
  55. package/dist/cli/commands/version.js +11 -10
  56. package/dist/cli/commands/version.test.js +11 -10
  57. package/dist/cli/services/commands/search.js +2 -2
  58. package/dist/cli/services/commands/search.test.js +2 -2
  59. package/dist/cli/services/commands/version.js +3 -3
  60. package/dist/cli/services/commands/version.test.js +4 -4
  61. package/dist/cli/services/demo.js +2 -2
  62. package/dist/cli/services/demo.test.js +3 -3
  63. package/dist/cli/services/kitchen-sink/async.js +2 -2
  64. package/dist/cli/services/kitchen-sink/prompts.js +2 -2
  65. package/dist/cli/services/kitchen-sink/static.js +2 -2
  66. package/dist/cli/services/upgrade.js +3 -3
  67. package/dist/cli/services/upgrade.test.js +5 -5
  68. package/dist/{custom-oclif-loader-ROCHTOS5.js → custom-oclif-loader-Y5TLP3GI.js} +2 -2
  69. package/dist/{error-handler-GT7C27BQ.js → error-handler-EORUUIBK.js} +9 -8
  70. package/dist/hooks/postrun.js +9 -9
  71. package/dist/hooks/prerun.js +8 -6
  72. package/dist/index.d.ts +1 -0
  73. package/dist/index.js +500 -605
  74. package/dist/{local-T3UMODTX.js → local-4NQ3UGM2.js} +4 -2
  75. package/dist/{node-V2ZJPWY5.js → node-NWOSUD3V.js} +12 -13
  76. package/dist/{node-package-manager-PYU7QL5O.js → node-package-manager-D7JIOBLM.js} +5 -3
  77. package/dist/{system-CEM4NSPG.js → system-WDT2XUAD.js} +2 -2
  78. package/dist/tsconfig.tsbuildinfo +1 -1
  79. package/dist/{ui-KGCQLCOJ.js → ui-JUVEDXYN.js} +2 -2
  80. package/dist/{workerd-TOCBV52P.js → workerd-VWTWLJIV.js} +12 -13
  81. package/oclif.manifest.json +15 -52
  82. package/package.json +6 -6
  83. package/dist/chunk-3E44DPAU.js +0 -118
  84. package/dist/chunk-EMJI2MUZ.js +0 -4244
  85. package/dist/chunk-LCWH3FW5.js +0 -33
@@ -1,4244 +0,0 @@
1
- import {
2
- setNextDeprecationDate
3
- } from "./chunk-LCWH3FW5.js";
4
- import {
5
- z
6
- } from "./chunk-NLUGD7PZ.js";
7
- import {
8
- ClientError,
9
- GraphQLClient,
10
- GraphQLClientError,
11
- RequestClientError,
12
- allAPIs,
13
- buildHeaders,
14
- getIdentityTokenInformation,
15
- getPartnersToken,
16
- gql,
17
- httpsAgent,
18
- resolveRequestDocument,
19
- retryAwareRequest,
20
- sanitizedHeadersOutput,
21
- shopifyFetch
22
- } from "./chunk-67E32Z72.js";
23
- import {
24
- base64URLEncode,
25
- nonRandomUUID,
26
- randomBytes,
27
- randomHex,
28
- sha256
29
- } from "./chunk-3E44DPAU.js";
30
- import {
31
- cacheRetrieveOrRepopulate,
32
- getCachedPartnerAccountStatus,
33
- getSession,
34
- removeSession,
35
- setCachedPartnerAccountStatus,
36
- setSession
37
- } from "./chunk-NV2K2JNI.js";
38
- import {
39
- AbortError,
40
- BugError,
41
- CancelExecution,
42
- Environment,
43
- FatalError,
44
- findPathUp,
45
- firstPartyDev,
46
- import_ts_error,
47
- isCloudEnvironment,
48
- isSpin,
49
- isTTY,
50
- isTruthy,
51
- keypress,
52
- openURL,
53
- outputCompleted,
54
- outputContent,
55
- outputDebug,
56
- outputInfo,
57
- outputToken,
58
- outputWarn,
59
- readFile,
60
- renderConfirmationPrompt,
61
- runWithTimer,
62
- serviceEnvironment,
63
- spinFqdn,
64
- stringifyMessage,
65
- useDeviceAuth
66
- } from "./chunk-CL6KB3RG.js";
67
- import {
68
- sessionConstants
69
- } from "./chunk-NZDBLGNM.js";
70
- import {
71
- moduleDirectory
72
- } from "./chunk-T2GATXSP.js";
73
- import {
74
- __commonJS,
75
- __require,
76
- __toESM,
77
- init_cjs_shims
78
- } from "./chunk-POZ5MGPT.js";
79
-
80
- // ../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/utils.js
81
- var require_utils = __commonJS({
82
- "../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/utils.js"(exports2, module2) {
83
- "use strict";
84
- init_cjs_shims();
85
- var cp = __require("child_process"), UNIT_MB = 1024 * 1024, utils = {
86
- /**
87
- * exec command with maxBuffer size
88
- */
89
- exec(cmd, callback) {
90
- cp.exec(cmd, {
91
- maxBuffer: 2 * UNIT_MB,
92
- windowsHide: !0
93
- }, callback);
94
- },
95
- /**
96
- * spawn command
97
- */
98
- spawn(cmd, args, options2) {
99
- return cp.spawn(cmd, args, options2);
100
- },
101
- /**
102
- * Strip top lines of text
103
- *
104
- * @param {String} text
105
- * @param {Number} num
106
- * @return {String}
107
- */
108
- stripLine(text, num) {
109
- let idx = 0;
110
- for (; num-- > 0; ) {
111
- let nIdx = text.indexOf(`
112
- `, idx);
113
- nIdx >= 0 && (idx = nIdx + 1);
114
- }
115
- return idx > 0 ? text.substring(idx) : text;
116
- },
117
- /**
118
- * Split string and stop at max parts
119
- *
120
- * @param {Number} line
121
- * @param {Number} max
122
- * @return {Array}
123
- */
124
- split(line, max) {
125
- let cols = line.trim().split(/\s+/);
126
- return cols.length > max && (cols[max - 1] = cols.slice(max - 1).join(" ")), cols;
127
- },
128
- /**
129
- * Extract columns from table text
130
- *
131
- * Example:
132
- *
133
- * ```
134
- * extractColumns(text, [0, 2], 3)
135
- * ```
136
- *
137
- * From:
138
- * ```
139
- * foo bar bar2
140
- * valx valy valz
141
- * ```
142
- *
143
- * To:
144
- * ```
145
- * [ ['foo', 'bar2'], ['valx', 'valz'] ]
146
- * ```
147
- *
148
- * @param {String} text raw table text
149
- * @param {Array} idxes the column index list to extract
150
- * @param {Number} max max column number of table
151
- * @return {Array}
152
- */
153
- extractColumns(text, idxes, max) {
154
- let lines = text.split(/(\r\n|\n|\r)/), columns = [];
155
- return max || (max = Math.max.apply(null, idxes) + 1), lines.forEach((line) => {
156
- let cols = utils.split(line, max), column = [];
157
- idxes.forEach((idx) => {
158
- column.push(cols[idx] || "");
159
- }), columns.push(column);
160
- }), columns;
161
- },
162
- /**
163
- * parse table text to array
164
- *
165
- * From:
166
- * ```
167
- * Header1 : foo
168
- * Header2 : bar
169
- * Header3 : val
170
- *
171
- * Header1 : foo2
172
- * Header2 : bar2
173
- * Header3 : val2
174
- * ```
175
- *
176
- * To:
177
- * ```
178
- * [{ Header1: 'foo', Header2: 'bar', Header3: 'val' }, ...]
179
- * ```
180
- *
181
- * @param {String} data raw table data
182
- * @return {Array}
183
- */
184
- parseTable(data) {
185
- let lines = data.split(/(\r\n\r\n|\r\n\n|\n\r\n)|\n\n/).filter((line) => line.trim().length > 0).map((e) => e.split(/(\r\n|\n|\r)/).filter((line) => line.trim().length > 0));
186
- return lines.forEach((line) => {
187
- for (let index = 0; line[index]; ) {
188
- let entry = line[index];
189
- entry.startsWith(" ") ? (line[index - 1] += entry.trimLeft(), line.splice(index, 1)) : index += 1;
190
- }
191
- }), lines.map((line) => {
192
- let row = {};
193
- return line.forEach((string) => {
194
- let splitterIndex = string.indexOf(":"), key = string.slice(0, splitterIndex).trim();
195
- row[key] = string.slice(splitterIndex + 1).trim();
196
- }), row;
197
- });
198
- }
199
- };
200
- module2.exports = utils;
201
- }
202
- });
203
-
204
- // ../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/find_pid.js
205
- var require_find_pid = __commonJS({
206
- "../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/find_pid.js"(exports2, module2) {
207
- "use strict";
208
- init_cjs_shims();
209
- var os = __require("os"), fs = __require("fs"), utils = require_utils(), ensureDir = (path) => new Promise((resolve, reject) => {
210
- fs.existsSync(path) ? resolve() : fs.mkdir(path, (err2) => {
211
- err2 ? reject(err2) : resolve();
212
- });
213
- }), finders = {
214
- darwin(port) {
215
- return new Promise((resolve, reject) => {
216
- utils.exec("netstat -anv -p TCP && netstat -anv -p UDP", function(err2, stdout, stderr) {
217
- if (err2)
218
- reject(err2);
219
- else {
220
- if (err2 = stderr.toString().trim(), err2) {
221
- reject(err2);
222
- return;
223
- }
224
- let data = utils.stripLine(stdout.toString(), 2), found = utils.extractColumns(data, [0, 3, 8], 10).filter((row) => !!String(row[0]).match(/^(udp|tcp)/)).find((row) => {
225
- let matches = String(row[1]).match(/\.(\d+)$/);
226
- if (matches && matches[1] === String(port))
227
- return !0;
228
- });
229
- found && found[2].length ? resolve(parseInt(found[2], 10)) : reject(new Error(`pid of port (${port}) not found`));
230
- }
231
- });
232
- });
233
- },
234
- freebsd: "darwin",
235
- sunos: "darwin",
236
- linux(port) {
237
- return new Promise((resolve, reject) => {
238
- let cmd = "netstat -tunlp";
239
- utils.exec(cmd, function(err2, stdout, stderr) {
240
- if (err2)
241
- reject(err2);
242
- else {
243
- let warn = stderr.toString().trim();
244
- warn && console.warn(warn);
245
- let data = utils.stripLine(stdout.toString(), 2), columns = utils.extractColumns(data, [3, 6], 7).find((column) => {
246
- let matches = String(column[0]).match(/:(\d+)$/);
247
- if (matches && matches[1] === String(port))
248
- return !0;
249
- });
250
- if (columns && columns[1]) {
251
- let pid = columns[1].split("/", 1)[0];
252
- pid.length ? resolve(parseInt(pid, 10)) : reject(new Error(`pid of port (${port}) not found`));
253
- } else
254
- reject(new Error(`pid of port (${port}) not found`));
255
- }
256
- });
257
- });
258
- },
259
- win32(port) {
260
- return new Promise((resolve, reject) => {
261
- utils.exec("netstat -ano", function(err2, stdout, stderr) {
262
- if (err2)
263
- reject(err2);
264
- else {
265
- if (err2 = stderr.toString().trim(), err2) {
266
- reject(err2);
267
- return;
268
- }
269
- let data = utils.stripLine(stdout.toString(), 4), columns = utils.extractColumns(data, [1, 4], 5).find((column) => {
270
- let matches = String(column[0]).match(/:(\d+)$/);
271
- if (matches && matches[1] === String(port))
272
- return !0;
273
- });
274
- columns && columns[1].length && parseInt(columns[1], 10) > 0 ? resolve(parseInt(columns[1], 10)) : reject(new Error(`pid of port (${port}) not found`));
275
- }
276
- });
277
- });
278
- },
279
- android(port) {
280
- return new Promise((resolve, reject) => {
281
- let dir = os.tmpdir() + "/.find-process", file = dir + "/" + process.pid, cmd = 'netstat -tunp >> "' + file + '"';
282
- ensureDir(dir).then(() => {
283
- utils.exec(cmd, () => {
284
- fs.readFile(file, "utf8", (err2, data) => {
285
- if (fs.unlink(file, () => {
286
- }), err2)
287
- reject(err2);
288
- else {
289
- data = utils.stripLine(data, 2);
290
- let columns = utils.extractColumns(data, [3, 6], 7).find((column) => {
291
- let matches = String(column[0]).match(/:(\d+)$/);
292
- if (matches && matches[1] === String(port))
293
- return !0;
294
- });
295
- if (columns && columns[1]) {
296
- let pid = columns[1].split("/", 1)[0];
297
- pid.length ? resolve(parseInt(pid, 10)) : reject(new Error(`pid of port (${port}) not found`));
298
- } else
299
- reject(new Error(`pid of port (${port}) not found`));
300
- }
301
- });
302
- });
303
- });
304
- });
305
- }
306
- };
307
- function findPidByPort(port) {
308
- let platform = process.platform;
309
- return new Promise((resolve, reject) => {
310
- if (!(platform in finders))
311
- return reject(new Error(`platform ${platform} is unsupported`));
312
- let findPid = finders[platform];
313
- typeof findPid == "string" && (findPid = finders[findPid]), findPid(port).then(resolve, reject);
314
- });
315
- }
316
- module2.exports = findPidByPort;
317
- }
318
- });
319
-
320
- // ../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/find_process.js
321
- var require_find_process = __commonJS({
322
- "../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/find_process.js"(exports2, module2) {
323
- "use strict";
324
- init_cjs_shims();
325
- var path = __require("path"), utils = require_utils();
326
- function matchName(text, name) {
327
- return name ? text && text.match ? text.match(name) : !1 : !0;
328
- }
329
- function fetchBin(cmd) {
330
- let pieces = cmd.split(path.sep), last = pieces[pieces.length - 1];
331
- last && (pieces[pieces.length - 1] = last.split(" ")[0]);
332
- let fixed = [];
333
- for (let part of pieces) {
334
- let optIdx = part.indexOf(" -");
335
- if (optIdx >= 0) {
336
- fixed.push(part.substring(0, optIdx).trim());
337
- break;
338
- } else if (part.endsWith(" ")) {
339
- fixed.push(part.trim());
340
- break;
341
- }
342
- fixed.push(part);
343
- }
344
- return fixed.join(path.sep);
345
- }
346
- function fetchName(fullpath) {
347
- if (process.platform === "darwin") {
348
- let idx = fullpath.indexOf(".app/");
349
- if (idx >= 0)
350
- return path.basename(fullpath.substring(0, idx));
351
- }
352
- return path.basename(fullpath);
353
- }
354
- var finders = {
355
- darwin(cond) {
356
- return new Promise((resolve, reject) => {
357
- let cmd;
358
- "pid" in cond ? cmd = `ps -p ${cond.pid} -ww -o pid,ppid,uid,gid,args` : cmd = "ps ax -ww -o pid,ppid,uid,gid,args", utils.exec(cmd, function(err2, stdout, stderr) {
359
- if (err2)
360
- "pid" in cond ? resolve([]) : reject(err2);
361
- else {
362
- if (err2 = stderr.toString().trim(), err2) {
363
- reject(err2);
364
- return;
365
- }
366
- let data = utils.stripLine(stdout.toString(), 1), list = utils.extractColumns(data, [0, 1, 2, 3, 4], 5).filter((column) => column[0] && cond.pid ? column[0] === String(cond.pid) : column[4] && cond.name ? matchName(column[4], cond.name) : !!column[0]).map((column) => {
367
- let cmd2 = String(column[4]), bin = fetchBin(cmd2);
368
- return {
369
- pid: parseInt(column[0], 10),
370
- ppid: parseInt(column[1], 10),
371
- uid: parseInt(column[2], 10),
372
- gid: parseInt(column[3], 10),
373
- name: fetchName(bin),
374
- bin,
375
- cmd: column[4]
376
- };
377
- });
378
- cond.strict && cond.name && (list = list.filter((item) => item.name === cond.name)), resolve(list);
379
- }
380
- });
381
- });
382
- },
383
- linux: "darwin",
384
- sunos: "darwin",
385
- freebsd: "darwin",
386
- win32(cond) {
387
- return new Promise((resolve, reject) => {
388
- let cmd = "Get-CimInstance -className win32_process | select Name,ProcessId,ParentProcessId,CommandLine,ExecutablePath", lines = [], proc = utils.spawn("powershell.exe", ["/c", cmd], { detached: !1, windowsHide: !0 });
389
- proc.stdout.on("data", (data) => {
390
- lines.push(data.toString());
391
- }), proc.on("close", (code) => {
392
- if (code !== 0)
393
- return reject(new Error("Command '" + cmd + "' terminated with code: " + code));
394
- let list = utils.parseTable(lines.join("")).filter((row) => {
395
- if ("pid" in cond)
396
- return row.ProcessId === String(cond.pid);
397
- if (cond.name) {
398
- let rowName = row.Name || "";
399
- return cond.strict ? rowName === cond.name || rowName.endsWith(".exe") && rowName.slice(0, -4) === cond.name : matchName(row.CommandLine || rowName, cond.name);
400
- } else
401
- return !0;
402
- }).map((row) => ({
403
- pid: parseInt(row.ProcessId, 10),
404
- ppid: parseInt(row.ParentProcessId, 10),
405
- // uid: void 0,
406
- // gid: void 0,
407
- bin: row.ExecutablePath,
408
- name: row.Name || "",
409
- cmd: row.CommandLine
410
- }));
411
- resolve(list);
412
- });
413
- });
414
- },
415
- android(cond) {
416
- return new Promise((resolve, reject) => {
417
- let cmd = "ps";
418
- utils.exec(cmd, function(err2, stdout, stderr) {
419
- if (err2)
420
- "pid" in cond ? resolve([]) : reject(err2);
421
- else {
422
- if (err2 = stderr.toString().trim(), err2) {
423
- reject(err2);
424
- return;
425
- }
426
- let data = utils.stripLine(stdout.toString(), 1), list = utils.extractColumns(data, [0, 3], 4).filter((column) => column[0] && cond.pid ? column[0] === String(cond.pid) : column[1] && cond.name ? matchName(column[1], cond.name) : !!column[0]).map((column) => {
427
- let cmd2 = String(column[1]), bin = fetchBin(cmd2);
428
- return {
429
- pid: parseInt(column[0], 10),
430
- // ppid: void 0,
431
- // uid: void 0,
432
- // gid: void 0,
433
- name: fetchName(bin),
434
- bin,
435
- cmd: cmd2
436
- };
437
- });
438
- cond.strict && cond.name && (list = list.filter((item) => item.name === cond.name)), resolve(list);
439
- }
440
- });
441
- });
442
- }
443
- };
444
- function findProcess2(cond) {
445
- let platform = process.platform;
446
- return new Promise((resolve, reject) => {
447
- if (!(platform in finders))
448
- return reject(new Error(`platform ${platform} is unsupported`));
449
- let find = finders[platform];
450
- typeof find == "string" && (find = finders[find]), find(cond).then(resolve, reject);
451
- });
452
- }
453
- module2.exports = findProcess2;
454
- }
455
- });
456
-
457
- // ../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/find.js
458
- var require_find = __commonJS({
459
- "../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/lib/find.js"(exports2, module2) {
460
- "use strict";
461
- init_cjs_shims();
462
- var findPid = require_find_pid(), findProcess2 = require_find_process(), findBy = {
463
- port(port, strict) {
464
- return findPid(port, strict).then((pid) => findBy.pid(pid, strict), () => []);
465
- },
466
- pid(pid, strict) {
467
- return findProcess2({
468
- pid,
469
- strict
470
- });
471
- },
472
- name(name, strict) {
473
- return findProcess2({
474
- name,
475
- strict
476
- });
477
- }
478
- };
479
- function find(by, value, strict) {
480
- return new Promise((resolve, reject) => {
481
- if (!(by in findBy))
482
- reject(new Error(`do not support find by "${by}"`));
483
- else {
484
- let isNumber = /^\d+$/.test(value);
485
- by === "pid" && !isNumber ? reject(new Error("pid must be a number")) : by === "port" && !isNumber ? reject(new Error("port must be a number")) : findBy[by](value, strict).then(resolve, reject);
486
- }
487
- });
488
- }
489
- module2.exports = find;
490
- }
491
- });
492
-
493
- // ../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/index.js
494
- var require_find_process2 = __commonJS({
495
- "../../node_modules/.pnpm/find-process@1.4.7/node_modules/find-process/index.js"(exports2, module2) {
496
- "use strict";
497
- init_cjs_shims();
498
- module2.exports = require_find();
499
- }
500
- });
501
-
502
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/parser.js
503
- var require_parser = __commonJS({
504
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/parser.js"(exports2) {
505
- "use strict";
506
- init_cjs_shims();
507
- exports2.load = function(received, defaults, onto = {}) {
508
- var k, ref, v;
509
- for (k in defaults)
510
- v = defaults[k], onto[k] = (ref = received[k]) != null ? ref : v;
511
- return onto;
512
- };
513
- exports2.overwrite = function(received, defaults, onto = {}) {
514
- var k, v;
515
- for (k in received)
516
- v = received[k], defaults[k] !== void 0 && (onto[k] = v);
517
- return onto;
518
- };
519
- }
520
- });
521
-
522
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/DLList.js
523
- var require_DLList = __commonJS({
524
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/DLList.js"(exports2, module2) {
525
- "use strict";
526
- init_cjs_shims();
527
- var DLList;
528
- DLList = class {
529
- constructor(incr, decr) {
530
- this.incr = incr, this.decr = decr, this._first = null, this._last = null, this.length = 0;
531
- }
532
- push(value) {
533
- var node;
534
- this.length++, typeof this.incr == "function" && this.incr(), node = {
535
- value,
536
- prev: this._last,
537
- next: null
538
- }, this._last != null ? (this._last.next = node, this._last = node) : this._first = this._last = node;
539
- }
540
- shift() {
541
- var value;
542
- if (this._first != null)
543
- return this.length--, typeof this.decr == "function" && this.decr(), value = this._first.value, (this._first = this._first.next) != null ? this._first.prev = null : this._last = null, value;
544
- }
545
- first() {
546
- if (this._first != null)
547
- return this._first.value;
548
- }
549
- getArray() {
550
- var node, ref, results;
551
- for (node = this._first, results = []; node != null; )
552
- results.push((ref = node, node = node.next, ref.value));
553
- return results;
554
- }
555
- forEachShift(cb) {
556
- var node;
557
- for (node = this.shift(); node != null; )
558
- cb(node), node = this.shift();
559
- }
560
- debug() {
561
- var node, ref, ref1, ref2, results;
562
- for (node = this._first, results = []; node != null; )
563
- results.push((ref = node, node = node.next, {
564
- value: ref.value,
565
- prev: (ref1 = ref.prev) != null ? ref1.value : void 0,
566
- next: (ref2 = ref.next) != null ? ref2.value : void 0
567
- }));
568
- return results;
569
- }
570
- };
571
- module2.exports = DLList;
572
- }
573
- });
574
-
575
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Events.js
576
- var require_Events = __commonJS({
577
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Events.js"(exports2, module2) {
578
- "use strict";
579
- init_cjs_shims();
580
- function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
581
- try {
582
- var info = gen[key](arg), value = info.value;
583
- } catch (error) {
584
- reject(error);
585
- return;
586
- }
587
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
588
- }
589
- function _asyncToGenerator2(fn) {
590
- return function() {
591
- var self = this, args = arguments;
592
- return new Promise(function(resolve, reject) {
593
- var gen = fn.apply(self, args);
594
- function _next(value) {
595
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
596
- }
597
- function _throw(err2) {
598
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err2);
599
- }
600
- _next(void 0);
601
- });
602
- };
603
- }
604
- var Events2;
605
- Events2 = class {
606
- constructor(instance) {
607
- if (this.instance = instance, this._events = {}, this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null)
608
- throw new Error("An Emitter already exists for this object");
609
- this.instance.on = (name, cb) => this._addListener(name, "many", cb), this.instance.once = (name, cb) => this._addListener(name, "once", cb), this.instance.removeAllListeners = (name = null) => name != null ? delete this._events[name] : this._events = {};
610
- }
611
- _addListener(name, status, cb) {
612
- var base;
613
- return (base = this._events)[name] == null && (base[name] = []), this._events[name].push({
614
- cb,
615
- status
616
- }), this.instance;
617
- }
618
- listenerCount(name) {
619
- return this._events[name] != null ? this._events[name].length : 0;
620
- }
621
- trigger(name, ...args) {
622
- var _this = this;
623
- return _asyncToGenerator2(function* () {
624
- var e, promises;
625
- try {
626
- return name !== "debug" && _this.trigger("debug", `Event triggered: ${name}`, args), _this._events[name] == null ? void 0 : (_this._events[name] = _this._events[name].filter(function(listener) {
627
- return listener.status !== "none";
628
- }), promises = _this._events[name].map(
629
- /* @__PURE__ */ function() {
630
- var _ref = _asyncToGenerator2(function* (listener) {
631
- var e2, returned;
632
- if (listener.status !== "none") {
633
- listener.status === "once" && (listener.status = "none");
634
- try {
635
- return returned = typeof listener.cb == "function" ? listener.cb(...args) : void 0, typeof returned?.then == "function" ? yield returned : returned;
636
- } catch (error) {
637
- return e2 = error, _this.trigger("error", e2), null;
638
- }
639
- }
640
- });
641
- return function(_x) {
642
- return _ref.apply(this, arguments);
643
- };
644
- }()
645
- ), (yield Promise.all(promises)).find(function(x) {
646
- return x != null;
647
- }));
648
- } catch (error) {
649
- return e = error, _this.trigger("error", e), null;
650
- }
651
- })();
652
- }
653
- };
654
- module2.exports = Events2;
655
- }
656
- });
657
-
658
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Queues.js
659
- var require_Queues = __commonJS({
660
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Queues.js"(exports2, module2) {
661
- "use strict";
662
- init_cjs_shims();
663
- var DLList, Events2, Queues;
664
- DLList = require_DLList();
665
- Events2 = require_Events();
666
- Queues = class {
667
- constructor(num_priorities) {
668
- var i;
669
- this.Events = new Events2(this), this._length = 0, this._lists = function() {
670
- var j, ref, results;
671
- for (results = [], i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j)
672
- results.push(new DLList(() => this.incr(), () => this.decr()));
673
- return results;
674
- }.call(this);
675
- }
676
- incr() {
677
- if (this._length++ === 0)
678
- return this.Events.trigger("leftzero");
679
- }
680
- decr() {
681
- if (--this._length === 0)
682
- return this.Events.trigger("zero");
683
- }
684
- push(job) {
685
- return this._lists[job.options.priority].push(job);
686
- }
687
- queued(priority) {
688
- return priority != null ? this._lists[priority].length : this._length;
689
- }
690
- shiftAll(fn) {
691
- return this._lists.forEach(function(list) {
692
- return list.forEachShift(fn);
693
- });
694
- }
695
- getFirst(arr = this._lists) {
696
- var j, len, list;
697
- for (j = 0, len = arr.length; j < len; j++)
698
- if (list = arr[j], list.length > 0)
699
- return list;
700
- return [];
701
- }
702
- shiftLastFrom(priority) {
703
- return this.getFirst(this._lists.slice(priority).reverse()).shift();
704
- }
705
- };
706
- module2.exports = Queues;
707
- }
708
- });
709
-
710
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/BottleneckError.js
711
- var require_BottleneckError = __commonJS({
712
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/BottleneckError.js"(exports2, module2) {
713
- "use strict";
714
- init_cjs_shims();
715
- var BottleneckError;
716
- BottleneckError = class extends Error {
717
- };
718
- module2.exports = BottleneckError;
719
- }
720
- });
721
-
722
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Job.js
723
- var require_Job = __commonJS({
724
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Job.js"(exports2, module2) {
725
- "use strict";
726
- init_cjs_shims();
727
- function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
728
- try {
729
- var info = gen[key](arg), value = info.value;
730
- } catch (error) {
731
- reject(error);
732
- return;
733
- }
734
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
735
- }
736
- function _asyncToGenerator2(fn) {
737
- return function() {
738
- var self = this, args = arguments;
739
- return new Promise(function(resolve, reject) {
740
- var gen = fn.apply(self, args);
741
- function _next(value) {
742
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
743
- }
744
- function _throw(err2) {
745
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err2);
746
- }
747
- _next(void 0);
748
- });
749
- };
750
- }
751
- var BottleneckError, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser2;
752
- NUM_PRIORITIES = 10;
753
- DEFAULT_PRIORITY = 5;
754
- parser2 = require_parser();
755
- BottleneckError = require_BottleneckError();
756
- Job = class {
757
- constructor(task, args, options2, jobDefaults, rejectOnDrop, Events2, _states, Promise2) {
758
- this.task = task, this.args = args, this.rejectOnDrop = rejectOnDrop, this.Events = Events2, this._states = _states, this.Promise = Promise2, this.options = parser2.load(options2, jobDefaults), this.options.priority = this._sanitizePriority(this.options.priority), this.options.id === jobDefaults.id && (this.options.id = `${this.options.id}-${this._randomIndex()}`), this.promise = new this.Promise((_resolve, _reject) => {
759
- this._resolve = _resolve, this._reject = _reject;
760
- }), this.retryCount = 0;
761
- }
762
- _sanitizePriority(priority) {
763
- var sProperty;
764
- return sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority, sProperty < 0 ? 0 : sProperty > NUM_PRIORITIES - 1 ? NUM_PRIORITIES - 1 : sProperty;
765
- }
766
- _randomIndex() {
767
- return Math.random().toString(36).slice(2);
768
- }
769
- doDrop({
770
- error,
771
- message = "This job has been dropped by Bottleneck"
772
- } = {}) {
773
- return this._states.remove(this.options.id) ? (this.rejectOnDrop && this._reject(error ?? new BottleneckError(message)), this.Events.trigger("dropped", {
774
- args: this.args,
775
- options: this.options,
776
- task: this.task,
777
- promise: this.promise
778
- }), !0) : !1;
779
- }
780
- _assertStatus(expected) {
781
- var status;
782
- if (status = this._states.jobStatus(this.options.id), !(status === expected || expected === "DONE" && status === null))
783
- throw new BottleneckError(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`);
784
- }
785
- doReceive() {
786
- return this._states.start(this.options.id), this.Events.trigger("received", {
787
- args: this.args,
788
- options: this.options
789
- });
790
- }
791
- doQueue(reachedHWM, blocked) {
792
- return this._assertStatus("RECEIVED"), this._states.next(this.options.id), this.Events.trigger("queued", {
793
- args: this.args,
794
- options: this.options,
795
- reachedHWM,
796
- blocked
797
- });
798
- }
799
- doRun() {
800
- return this.retryCount === 0 ? (this._assertStatus("QUEUED"), this._states.next(this.options.id)) : this._assertStatus("EXECUTING"), this.Events.trigger("scheduled", {
801
- args: this.args,
802
- options: this.options
803
- });
804
- }
805
- doExecute(chained, clearGlobalState, run, free) {
806
- var _this = this;
807
- return _asyncToGenerator2(function* () {
808
- var error, eventInfo, passed;
809
- _this.retryCount === 0 ? (_this._assertStatus("RUNNING"), _this._states.next(_this.options.id)) : _this._assertStatus("EXECUTING"), eventInfo = {
810
- args: _this.args,
811
- options: _this.options,
812
- retryCount: _this.retryCount
813
- }, _this.Events.trigger("executing", eventInfo);
814
- try {
815
- if (passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args), clearGlobalState())
816
- return _this.doDone(eventInfo), yield free(_this.options, eventInfo), _this._assertStatus("DONE"), _this._resolve(passed);
817
- } catch (error1) {
818
- return error = error1, _this._onFailure(error, eventInfo, clearGlobalState, run, free);
819
- }
820
- })();
821
- }
822
- doExpire(clearGlobalState, run, free) {
823
- var error, eventInfo;
824
- return this._states.jobStatus(this.options.id === "RUNNING") && this._states.next(this.options.id), this._assertStatus("EXECUTING"), eventInfo = {
825
- args: this.args,
826
- options: this.options,
827
- retryCount: this.retryCount
828
- }, error = new BottleneckError(`This job timed out after ${this.options.expiration} ms.`), this._onFailure(error, eventInfo, clearGlobalState, run, free);
829
- }
830
- _onFailure(error, eventInfo, clearGlobalState, run, free) {
831
- var _this2 = this;
832
- return _asyncToGenerator2(function* () {
833
- var retry, retryAfter;
834
- if (clearGlobalState())
835
- return retry = yield _this2.Events.trigger("failed", error, eventInfo), retry != null ? (retryAfter = ~~retry, _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo), _this2.retryCount++, run(retryAfter)) : (_this2.doDone(eventInfo), yield free(_this2.options, eventInfo), _this2._assertStatus("DONE"), _this2._reject(error));
836
- })();
837
- }
838
- doDone(eventInfo) {
839
- return this._assertStatus("EXECUTING"), this._states.next(this.options.id), this.Events.trigger("done", eventInfo);
840
- }
841
- };
842
- module2.exports = Job;
843
- }
844
- });
845
-
846
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/LocalDatastore.js
847
- var require_LocalDatastore = __commonJS({
848
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/LocalDatastore.js"(exports2, module2) {
849
- "use strict";
850
- init_cjs_shims();
851
- function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
852
- try {
853
- var info = gen[key](arg), value = info.value;
854
- } catch (error) {
855
- reject(error);
856
- return;
857
- }
858
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
859
- }
860
- function _asyncToGenerator2(fn) {
861
- return function() {
862
- var self = this, args = arguments;
863
- return new Promise(function(resolve, reject) {
864
- var gen = fn.apply(self, args);
865
- function _next(value) {
866
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
867
- }
868
- function _throw(err2) {
869
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err2);
870
- }
871
- _next(void 0);
872
- });
873
- };
874
- }
875
- var BottleneckError, LocalDatastore, parser2;
876
- parser2 = require_parser();
877
- BottleneckError = require_BottleneckError();
878
- LocalDatastore = class {
879
- constructor(instance, storeOptions, storeInstanceOptions) {
880
- this.instance = instance, this.storeOptions = storeOptions, this.clientId = this.instance._randomIndex(), parser2.load(storeInstanceOptions, storeInstanceOptions, this), this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(), this._running = 0, this._done = 0, this._unblockTime = 0, this.ready = this.Promise.resolve(), this.clients = {}, this._startHeartbeat();
881
- }
882
- _startHeartbeat() {
883
- var base;
884
- return this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null) ? typeof (base = this.heartbeat = setInterval(() => {
885
- var amount, incr, maximum, now, reservoir;
886
- if (now = Date.now(), this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval && (this._lastReservoirRefresh = now, this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount, this.instance._drainAll(this.computeCapacity())), this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) {
887
- var _this$storeOptions = this.storeOptions;
888
- if (amount = _this$storeOptions.reservoirIncreaseAmount, maximum = _this$storeOptions.reservoirIncreaseMaximum, reservoir = _this$storeOptions.reservoir, this._lastReservoirIncrease = now, incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount, incr > 0)
889
- return this.storeOptions.reservoir += incr, this.instance._drainAll(this.computeCapacity());
890
- }
891
- }, this.heartbeatInterval)).unref == "function" ? base.unref() : void 0 : clearInterval(this.heartbeat);
892
- }
893
- __publish__(message) {
894
- var _this = this;
895
- return _asyncToGenerator2(function* () {
896
- return yield _this.yieldLoop(), _this.instance.Events.trigger("message", message.toString());
897
- })();
898
- }
899
- __disconnect__(flush) {
900
- var _this2 = this;
901
- return _asyncToGenerator2(function* () {
902
- return yield _this2.yieldLoop(), clearInterval(_this2.heartbeat), _this2.Promise.resolve();
903
- })();
904
- }
905
- yieldLoop(t = 0) {
906
- return new this.Promise(function(resolve, reject) {
907
- return setTimeout(resolve, t);
908
- });
909
- }
910
- computePenalty() {
911
- var ref;
912
- return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5e3;
913
- }
914
- __updateSettings__(options2) {
915
- var _this3 = this;
916
- return _asyncToGenerator2(function* () {
917
- return yield _this3.yieldLoop(), parser2.overwrite(options2, options2, _this3.storeOptions), _this3._startHeartbeat(), _this3.instance._drainAll(_this3.computeCapacity()), !0;
918
- })();
919
- }
920
- __running__() {
921
- var _this4 = this;
922
- return _asyncToGenerator2(function* () {
923
- return yield _this4.yieldLoop(), _this4._running;
924
- })();
925
- }
926
- __queued__() {
927
- var _this5 = this;
928
- return _asyncToGenerator2(function* () {
929
- return yield _this5.yieldLoop(), _this5.instance.queued();
930
- })();
931
- }
932
- __done__() {
933
- var _this6 = this;
934
- return _asyncToGenerator2(function* () {
935
- return yield _this6.yieldLoop(), _this6._done;
936
- })();
937
- }
938
- __groupCheck__(time) {
939
- var _this7 = this;
940
- return _asyncToGenerator2(function* () {
941
- return yield _this7.yieldLoop(), _this7._nextRequest + _this7.timeout < time;
942
- })();
943
- }
944
- computeCapacity() {
945
- var maxConcurrent, reservoir, _this$storeOptions2 = this.storeOptions;
946
- return maxConcurrent = _this$storeOptions2.maxConcurrent, reservoir = _this$storeOptions2.reservoir, maxConcurrent != null && reservoir != null ? Math.min(maxConcurrent - this._running, reservoir) : maxConcurrent != null ? maxConcurrent - this._running : reservoir ?? null;
947
- }
948
- conditionsCheck(weight) {
949
- var capacity;
950
- return capacity = this.computeCapacity(), capacity == null || weight <= capacity;
951
- }
952
- __incrementReservoir__(incr) {
953
- var _this8 = this;
954
- return _asyncToGenerator2(function* () {
955
- var reservoir;
956
- return yield _this8.yieldLoop(), reservoir = _this8.storeOptions.reservoir += incr, _this8.instance._drainAll(_this8.computeCapacity()), reservoir;
957
- })();
958
- }
959
- __currentReservoir__() {
960
- var _this9 = this;
961
- return _asyncToGenerator2(function* () {
962
- return yield _this9.yieldLoop(), _this9.storeOptions.reservoir;
963
- })();
964
- }
965
- isBlocked(now) {
966
- return this._unblockTime >= now;
967
- }
968
- check(weight, now) {
969
- return this.conditionsCheck(weight) && this._nextRequest - now <= 0;
970
- }
971
- __check__(weight) {
972
- var _this10 = this;
973
- return _asyncToGenerator2(function* () {
974
- var now;
975
- return yield _this10.yieldLoop(), now = Date.now(), _this10.check(weight, now);
976
- })();
977
- }
978
- __register__(index, weight, expiration) {
979
- var _this11 = this;
980
- return _asyncToGenerator2(function* () {
981
- var now, wait;
982
- return yield _this11.yieldLoop(), now = Date.now(), _this11.conditionsCheck(weight) ? (_this11._running += weight, _this11.storeOptions.reservoir != null && (_this11.storeOptions.reservoir -= weight), wait = Math.max(_this11._nextRequest - now, 0), _this11._nextRequest = now + wait + _this11.storeOptions.minTime, {
983
- success: !0,
984
- wait,
985
- reservoir: _this11.storeOptions.reservoir
986
- }) : {
987
- success: !1
988
- };
989
- })();
990
- }
991
- strategyIsBlock() {
992
- return this.storeOptions.strategy === 3;
993
- }
994
- __submit__(queueLength, weight) {
995
- var _this12 = this;
996
- return _asyncToGenerator2(function* () {
997
- var blocked, now, reachedHWM;
998
- if (yield _this12.yieldLoop(), _this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent)
999
- throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`);
1000
- return now = Date.now(), reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now), blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)), blocked && (_this12._unblockTime = now + _this12.computePenalty(), _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime, _this12.instance._dropAllQueued()), {
1001
- reachedHWM,
1002
- blocked,
1003
- strategy: _this12.storeOptions.strategy
1004
- };
1005
- })();
1006
- }
1007
- __free__(index, weight) {
1008
- var _this13 = this;
1009
- return _asyncToGenerator2(function* () {
1010
- return yield _this13.yieldLoop(), _this13._running -= weight, _this13._done += weight, _this13.instance._drainAll(_this13.computeCapacity()), {
1011
- running: _this13._running
1012
- };
1013
- })();
1014
- }
1015
- };
1016
- module2.exports = LocalDatastore;
1017
- }
1018
- });
1019
-
1020
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/lua.json
1021
- var require_lua = __commonJS({
1022
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/lua.json"(exports2, module2) {
1023
- module2.exports = {
1024
- "blacklist_client.lua": `local blacklist = ARGV[num_static_argv + 1]
1025
-
1026
- if redis.call('zscore', client_last_seen_key, blacklist) then
1027
- redis.call('zadd', client_last_seen_key, 0, blacklist)
1028
- end
1029
-
1030
-
1031
- return {}
1032
- `,
1033
- "check.lua": `local weight = tonumber(ARGV[num_static_argv + 1])
1034
-
1035
- local capacity = process_tick(now, false)['capacity']
1036
- local nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))
1037
-
1038
- return conditions_check(capacity, weight) and nextRequest - now <= 0
1039
- `,
1040
- "conditions_check.lua": `local conditions_check = function (capacity, weight)
1041
- return capacity == nil or weight <= capacity
1042
- end
1043
- `,
1044
- "current_reservoir.lua": `return process_tick(now, false)['reservoir']
1045
- `,
1046
- "done.lua": `process_tick(now, false)
1047
-
1048
- return tonumber(redis.call('hget', settings_key, 'done'))
1049
- `,
1050
- "free.lua": `local index = ARGV[num_static_argv + 1]
1051
-
1052
- redis.call('zadd', job_expirations_key, 0, index)
1053
-
1054
- return process_tick(now, false)['running']
1055
- `,
1056
- "get_time.lua": `redis.replicate_commands()
1057
-
1058
- local get_time = function ()
1059
- local time = redis.call('time')
1060
-
1061
- return tonumber(time[1]..string.sub(time[2], 1, 3))
1062
- end
1063
- `,
1064
- "group_check.lua": `return not (redis.call('exists', settings_key) == 1)
1065
- `,
1066
- "heartbeat.lua": `process_tick(now, true)
1067
- `,
1068
- "increment_reservoir.lua": `local incr = tonumber(ARGV[num_static_argv + 1])
1069
-
1070
- redis.call('hincrby', settings_key, 'reservoir', incr)
1071
-
1072
- local reservoir = process_tick(now, true)['reservoir']
1073
-
1074
- local groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))
1075
- refresh_expiration(0, 0, groupTimeout)
1076
-
1077
- return reservoir
1078
- `,
1079
- "init.lua": `local clear = tonumber(ARGV[num_static_argv + 1])
1080
- local limiter_version = ARGV[num_static_argv + 2]
1081
- local num_local_argv = num_static_argv + 2
1082
-
1083
- if clear == 1 then
1084
- redis.call('del', unpack(KEYS))
1085
- end
1086
-
1087
- if redis.call('exists', settings_key) == 0 then
1088
- -- Create
1089
- local args = {'hmset', settings_key}
1090
-
1091
- for i = num_local_argv + 1, #ARGV do
1092
- table.insert(args, ARGV[i])
1093
- end
1094
-
1095
- redis.call(unpack(args))
1096
- redis.call('hmset', settings_key,
1097
- 'nextRequest', now,
1098
- 'lastReservoirRefresh', now,
1099
- 'lastReservoirIncrease', now,
1100
- 'running', 0,
1101
- 'done', 0,
1102
- 'unblockTime', 0,
1103
- 'capacityPriorityCounter', 0
1104
- )
1105
-
1106
- else
1107
- -- Apply migrations
1108
- local settings = redis.call('hmget', settings_key,
1109
- 'id',
1110
- 'version'
1111
- )
1112
- local id = settings[1]
1113
- local current_version = settings[2]
1114
-
1115
- if current_version ~= limiter_version then
1116
- local version_digits = {}
1117
- for k, v in string.gmatch(current_version, "([^.]+)") do
1118
- table.insert(version_digits, tonumber(k))
1119
- end
1120
-
1121
- -- 2.10.0
1122
- if version_digits[2] < 10 then
1123
- redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')
1124
- redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')
1125
- redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')
1126
- redis.call('hsetnx', settings_key, 'done', 0)
1127
- redis.call('hset', settings_key, 'version', '2.10.0')
1128
- end
1129
-
1130
- -- 2.11.1
1131
- if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then
1132
- if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then
1133
- redis.call('hmset', settings_key,
1134
- 'lastReservoirRefresh', now,
1135
- 'version', '2.11.1'
1136
- )
1137
- end
1138
- end
1139
-
1140
- -- 2.14.0
1141
- if version_digits[2] < 14 then
1142
- local old_running_key = 'b_'..id..'_running'
1143
- local old_executing_key = 'b_'..id..'_executing'
1144
-
1145
- if redis.call('exists', old_running_key) == 1 then
1146
- redis.call('rename', old_running_key, job_weights_key)
1147
- end
1148
- if redis.call('exists', old_executing_key) == 1 then
1149
- redis.call('rename', old_executing_key, job_expirations_key)
1150
- end
1151
- redis.call('hset', settings_key, 'version', '2.14.0')
1152
- end
1153
-
1154
- -- 2.15.2
1155
- if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then
1156
- redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)
1157
- redis.call('hset', settings_key, 'version', '2.15.2')
1158
- end
1159
-
1160
- -- 2.17.0
1161
- if version_digits[2] < 17 then
1162
- redis.call('hsetnx', settings_key, 'clientTimeout', 10000)
1163
- redis.call('hset', settings_key, 'version', '2.17.0')
1164
- end
1165
-
1166
- -- 2.18.0
1167
- if version_digits[2] < 18 then
1168
- redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')
1169
- redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')
1170
- redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')
1171
- redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)
1172
- redis.call('hset', settings_key, 'version', '2.18.0')
1173
- end
1174
-
1175
- end
1176
-
1177
- process_tick(now, false)
1178
- end
1179
-
1180
- local groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))
1181
- refresh_expiration(0, 0, groupTimeout)
1182
-
1183
- return {}
1184
- `,
1185
- "process_tick.lua": `local process_tick = function (now, always_publish)
1186
-
1187
- local compute_capacity = function (maxConcurrent, running, reservoir)
1188
- if maxConcurrent ~= nil and reservoir ~= nil then
1189
- return math.min((maxConcurrent - running), reservoir)
1190
- elseif maxConcurrent ~= nil then
1191
- return maxConcurrent - running
1192
- elseif reservoir ~= nil then
1193
- return reservoir
1194
- else
1195
- return nil
1196
- end
1197
- end
1198
-
1199
- local settings = redis.call('hmget', settings_key,
1200
- 'id',
1201
- 'maxConcurrent',
1202
- 'running',
1203
- 'reservoir',
1204
- 'reservoirRefreshInterval',
1205
- 'reservoirRefreshAmount',
1206
- 'lastReservoirRefresh',
1207
- 'reservoirIncreaseInterval',
1208
- 'reservoirIncreaseAmount',
1209
- 'reservoirIncreaseMaximum',
1210
- 'lastReservoirIncrease',
1211
- 'capacityPriorityCounter',
1212
- 'clientTimeout'
1213
- )
1214
- local id = settings[1]
1215
- local maxConcurrent = tonumber(settings[2])
1216
- local running = tonumber(settings[3])
1217
- local reservoir = tonumber(settings[4])
1218
- local reservoirRefreshInterval = tonumber(settings[5])
1219
- local reservoirRefreshAmount = tonumber(settings[6])
1220
- local lastReservoirRefresh = tonumber(settings[7])
1221
- local reservoirIncreaseInterval = tonumber(settings[8])
1222
- local reservoirIncreaseAmount = tonumber(settings[9])
1223
- local reservoirIncreaseMaximum = tonumber(settings[10])
1224
- local lastReservoirIncrease = tonumber(settings[11])
1225
- local capacityPriorityCounter = tonumber(settings[12])
1226
- local clientTimeout = tonumber(settings[13])
1227
-
1228
- local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)
1229
-
1230
- --
1231
- -- Process 'running' changes
1232
- --
1233
- local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)
1234
-
1235
- if #expired > 0 then
1236
- redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)
1237
-
1238
- local flush_batch = function (batch, acc)
1239
- local weights = redis.call('hmget', job_weights_key, unpack(batch))
1240
- redis.call('hdel', job_weights_key, unpack(batch))
1241
- local clients = redis.call('hmget', job_clients_key, unpack(batch))
1242
- redis.call('hdel', job_clients_key, unpack(batch))
1243
-
1244
- -- Calculate sum of removed weights
1245
- for i = 1, #weights do
1246
- acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)
1247
- end
1248
-
1249
- -- Calculate sum of removed weights by client
1250
- local client_weights = {}
1251
- for i = 1, #clients do
1252
- local removed = tonumber(weights[i]) or 0
1253
- if removed > 0 then
1254
- acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed
1255
- end
1256
- end
1257
- end
1258
-
1259
- local acc = {
1260
- ['total'] = 0,
1261
- ['client_weights'] = {}
1262
- }
1263
- local batch_size = 1000
1264
-
1265
- -- Compute changes to Zsets and apply changes to Hashes
1266
- for i = 1, #expired, batch_size do
1267
- local batch = {}
1268
- for j = i, math.min(i + batch_size - 1, #expired) do
1269
- table.insert(batch, expired[j])
1270
- end
1271
-
1272
- flush_batch(batch, acc)
1273
- end
1274
-
1275
- -- Apply changes to Zsets
1276
- if acc['total'] > 0 then
1277
- redis.call('hincrby', settings_key, 'done', acc['total'])
1278
- running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))
1279
- end
1280
-
1281
- for client, weight in pairs(acc['client_weights']) do
1282
- redis.call('zincrby', client_running_key, -weight, client)
1283
- end
1284
- end
1285
-
1286
- --
1287
- -- Process 'reservoir' changes
1288
- --
1289
- local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil
1290
- if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then
1291
- reservoir = reservoirRefreshAmount
1292
- redis.call('hmset', settings_key,
1293
- 'reservoir', reservoir,
1294
- 'lastReservoirRefresh', now
1295
- )
1296
- end
1297
-
1298
- local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil
1299
- if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then
1300
- local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)
1301
- local incr = reservoirIncreaseAmount * num_intervals
1302
- if reservoirIncreaseMaximum ~= nil then
1303
- incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))
1304
- end
1305
- if incr > 0 then
1306
- reservoir = (reservoir or 0) + incr
1307
- end
1308
- redis.call('hmset', settings_key,
1309
- 'reservoir', reservoir,
1310
- 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)
1311
- )
1312
- end
1313
-
1314
- --
1315
- -- Clear unresponsive clients
1316
- --
1317
- local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))
1318
- local unresponsive_lookup = {}
1319
- local terminated_clients = {}
1320
- for i = 1, #unresponsive do
1321
- unresponsive_lookup[unresponsive[i]] = true
1322
- if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then
1323
- table.insert(terminated_clients, unresponsive[i])
1324
- end
1325
- end
1326
- if #terminated_clients > 0 then
1327
- redis.call('zrem', client_running_key, unpack(terminated_clients))
1328
- redis.call('hdel', client_num_queued_key, unpack(terminated_clients))
1329
- redis.call('zrem', client_last_registered_key, unpack(terminated_clients))
1330
- redis.call('zrem', client_last_seen_key, unpack(terminated_clients))
1331
- end
1332
-
1333
- --
1334
- -- Broadcast capacity changes
1335
- --
1336
- local final_capacity = compute_capacity(maxConcurrent, running, reservoir)
1337
-
1338
- if always_publish or (initial_capacity ~= nil and final_capacity == nil) then
1339
- -- always_publish or was not unlimited, now unlimited
1340
- redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))
1341
-
1342
- elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then
1343
- -- capacity was increased
1344
- -- send the capacity message to the limiter having the lowest number of running jobs
1345
- -- the tiebreaker is the limiter having not registered a job in the longest time
1346
-
1347
- local lowest_concurrency_value = nil
1348
- local lowest_concurrency_clients = {}
1349
- local lowest_concurrency_last_registered = {}
1350
- local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')
1351
-
1352
- for i = 1, #client_concurrencies, 2 do
1353
- local client = client_concurrencies[i]
1354
- local concurrency = tonumber(client_concurrencies[i+1])
1355
-
1356
- if (
1357
- lowest_concurrency_value == nil or lowest_concurrency_value == concurrency
1358
- ) and (
1359
- not unresponsive_lookup[client]
1360
- ) and (
1361
- tonumber(redis.call('hget', client_num_queued_key, client)) > 0
1362
- ) then
1363
- lowest_concurrency_value = concurrency
1364
- table.insert(lowest_concurrency_clients, client)
1365
- local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))
1366
- table.insert(lowest_concurrency_last_registered, last_registered)
1367
- end
1368
- end
1369
-
1370
- if #lowest_concurrency_clients > 0 then
1371
- local position = 1
1372
- local earliest = lowest_concurrency_last_registered[1]
1373
-
1374
- for i,v in ipairs(lowest_concurrency_last_registered) do
1375
- if v < earliest then
1376
- position = i
1377
- earliest = v
1378
- end
1379
- end
1380
-
1381
- local next_client = lowest_concurrency_clients[position]
1382
- redis.call('publish', 'b_'..id,
1383
- 'capacity-priority:'..(final_capacity or '')..
1384
- ':'..next_client..
1385
- ':'..capacityPriorityCounter
1386
- )
1387
- redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')
1388
- else
1389
- redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))
1390
- end
1391
- end
1392
-
1393
- return {
1394
- ['capacity'] = final_capacity,
1395
- ['running'] = running,
1396
- ['reservoir'] = reservoir
1397
- }
1398
- end
1399
- `,
1400
- "queued.lua": `local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))
1401
- local valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')
1402
- local client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))
1403
-
1404
- local sum = 0
1405
- for i = 1, #client_queued do
1406
- sum = sum + tonumber(client_queued[i])
1407
- end
1408
-
1409
- return sum
1410
- `,
1411
- "refresh_expiration.lua": `local refresh_expiration = function (now, nextRequest, groupTimeout)
1412
-
1413
- if groupTimeout ~= nil then
1414
- local ttl = (nextRequest + groupTimeout) - now
1415
-
1416
- for i = 1, #KEYS do
1417
- redis.call('pexpire', KEYS[i], ttl)
1418
- end
1419
- end
1420
-
1421
- end
1422
- `,
1423
- "refs.lua": `local settings_key = KEYS[1]
1424
- local job_weights_key = KEYS[2]
1425
- local job_expirations_key = KEYS[3]
1426
- local job_clients_key = KEYS[4]
1427
- local client_running_key = KEYS[5]
1428
- local client_num_queued_key = KEYS[6]
1429
- local client_last_registered_key = KEYS[7]
1430
- local client_last_seen_key = KEYS[8]
1431
-
1432
- local now = tonumber(ARGV[1])
1433
- local client = ARGV[2]
1434
-
1435
- local num_static_argv = 2
1436
- `,
1437
- "register.lua": `local index = ARGV[num_static_argv + 1]
1438
- local weight = tonumber(ARGV[num_static_argv + 2])
1439
- local expiration = tonumber(ARGV[num_static_argv + 3])
1440
-
1441
- local state = process_tick(now, false)
1442
- local capacity = state['capacity']
1443
- local reservoir = state['reservoir']
1444
-
1445
- local settings = redis.call('hmget', settings_key,
1446
- 'nextRequest',
1447
- 'minTime',
1448
- 'groupTimeout'
1449
- )
1450
- local nextRequest = tonumber(settings[1])
1451
- local minTime = tonumber(settings[2])
1452
- local groupTimeout = tonumber(settings[3])
1453
-
1454
- if conditions_check(capacity, weight) then
1455
-
1456
- redis.call('hincrby', settings_key, 'running', weight)
1457
- redis.call('hset', job_weights_key, index, weight)
1458
- if expiration ~= nil then
1459
- redis.call('zadd', job_expirations_key, now + expiration, index)
1460
- end
1461
- redis.call('hset', job_clients_key, index, client)
1462
- redis.call('zincrby', client_running_key, weight, client)
1463
- redis.call('hincrby', client_num_queued_key, client, -1)
1464
- redis.call('zadd', client_last_registered_key, now, client)
1465
-
1466
- local wait = math.max(nextRequest - now, 0)
1467
- local newNextRequest = now + wait + minTime
1468
-
1469
- if reservoir == nil then
1470
- redis.call('hset', settings_key,
1471
- 'nextRequest', newNextRequest
1472
- )
1473
- else
1474
- reservoir = reservoir - weight
1475
- redis.call('hmset', settings_key,
1476
- 'reservoir', reservoir,
1477
- 'nextRequest', newNextRequest
1478
- )
1479
- end
1480
-
1481
- refresh_expiration(now, newNextRequest, groupTimeout)
1482
-
1483
- return {true, wait, reservoir}
1484
-
1485
- else
1486
- return {false}
1487
- end
1488
- `,
1489
- "register_client.lua": `local queued = tonumber(ARGV[num_static_argv + 1])
1490
-
1491
- -- Could have been re-registered concurrently
1492
- if not redis.call('zscore', client_last_seen_key, client) then
1493
- redis.call('zadd', client_running_key, 0, client)
1494
- redis.call('hset', client_num_queued_key, client, queued)
1495
- redis.call('zadd', client_last_registered_key, 0, client)
1496
- end
1497
-
1498
- redis.call('zadd', client_last_seen_key, now, client)
1499
-
1500
- return {}
1501
- `,
1502
- "running.lua": `return process_tick(now, false)['running']
1503
- `,
1504
- "submit.lua": `local queueLength = tonumber(ARGV[num_static_argv + 1])
1505
- local weight = tonumber(ARGV[num_static_argv + 2])
1506
-
1507
- local capacity = process_tick(now, false)['capacity']
1508
-
1509
- local settings = redis.call('hmget', settings_key,
1510
- 'id',
1511
- 'maxConcurrent',
1512
- 'highWater',
1513
- 'nextRequest',
1514
- 'strategy',
1515
- 'unblockTime',
1516
- 'penalty',
1517
- 'minTime',
1518
- 'groupTimeout'
1519
- )
1520
- local id = settings[1]
1521
- local maxConcurrent = tonumber(settings[2])
1522
- local highWater = tonumber(settings[3])
1523
- local nextRequest = tonumber(settings[4])
1524
- local strategy = tonumber(settings[5])
1525
- local unblockTime = tonumber(settings[6])
1526
- local penalty = tonumber(settings[7])
1527
- local minTime = tonumber(settings[8])
1528
- local groupTimeout = tonumber(settings[9])
1529
-
1530
- if maxConcurrent ~= nil and weight > maxConcurrent then
1531
- return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)
1532
- end
1533
-
1534
- local reachedHWM = (highWater ~= nil and queueLength == highWater
1535
- and not (
1536
- conditions_check(capacity, weight)
1537
- and nextRequest - now <= 0
1538
- )
1539
- )
1540
-
1541
- local blocked = strategy == 3 and (reachedHWM or unblockTime >= now)
1542
-
1543
- if blocked then
1544
- local computedPenalty = penalty
1545
- if computedPenalty == nil then
1546
- if minTime == 0 then
1547
- computedPenalty = 5000
1548
- else
1549
- computedPenalty = 15 * minTime
1550
- end
1551
- end
1552
-
1553
- local newNextRequest = now + computedPenalty + minTime
1554
-
1555
- redis.call('hmset', settings_key,
1556
- 'unblockTime', now + computedPenalty,
1557
- 'nextRequest', newNextRequest
1558
- )
1559
-
1560
- local clients_queued_reset = redis.call('hkeys', client_num_queued_key)
1561
- local queued_reset = {}
1562
- for i = 1, #clients_queued_reset do
1563
- table.insert(queued_reset, clients_queued_reset[i])
1564
- table.insert(queued_reset, 0)
1565
- end
1566
- redis.call('hmset', client_num_queued_key, unpack(queued_reset))
1567
-
1568
- redis.call('publish', 'b_'..id, 'blocked:')
1569
-
1570
- refresh_expiration(now, newNextRequest, groupTimeout)
1571
- end
1572
-
1573
- if not blocked and not reachedHWM then
1574
- redis.call('hincrby', client_num_queued_key, client, 1)
1575
- end
1576
-
1577
- return {reachedHWM, blocked, strategy}
1578
- `,
1579
- "update_settings.lua": `local args = {'hmset', settings_key}
1580
-
1581
- for i = num_static_argv + 1, #ARGV do
1582
- table.insert(args, ARGV[i])
1583
- end
1584
-
1585
- redis.call(unpack(args))
1586
-
1587
- process_tick(now, true)
1588
-
1589
- local groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))
1590
- refresh_expiration(0, 0, groupTimeout)
1591
-
1592
- return {}
1593
- `,
1594
- "validate_client.lua": `if not redis.call('zscore', client_last_seen_key, client) then
1595
- return redis.error_reply('UNKNOWN_CLIENT')
1596
- end
1597
-
1598
- redis.call('zadd', client_last_seen_key, now, client)
1599
- `,
1600
- "validate_keys.lua": `if not (redis.call('exists', settings_key) == 1) then
1601
- return redis.error_reply('SETTINGS_KEY_NOT_FOUND')
1602
- end
1603
- `
1604
- };
1605
- }
1606
- });
1607
-
1608
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Scripts.js
1609
- var require_Scripts = __commonJS({
1610
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Scripts.js"(exports2) {
1611
- "use strict";
1612
- init_cjs_shims();
1613
- var headers, lua, templates;
1614
- lua = require_lua();
1615
- headers = {
1616
- refs: lua["refs.lua"],
1617
- validate_keys: lua["validate_keys.lua"],
1618
- validate_client: lua["validate_client.lua"],
1619
- refresh_expiration: lua["refresh_expiration.lua"],
1620
- process_tick: lua["process_tick.lua"],
1621
- conditions_check: lua["conditions_check.lua"],
1622
- get_time: lua["get_time.lua"]
1623
- };
1624
- exports2.allKeys = function(id) {
1625
- return [
1626
- /*
1627
- HASH
1628
- */
1629
- `b_${id}_settings`,
1630
- /*
1631
- HASH
1632
- job index -> weight
1633
- */
1634
- `b_${id}_job_weights`,
1635
- /*
1636
- ZSET
1637
- job index -> expiration
1638
- */
1639
- `b_${id}_job_expirations`,
1640
- /*
1641
- HASH
1642
- job index -> client
1643
- */
1644
- `b_${id}_job_clients`,
1645
- /*
1646
- ZSET
1647
- client -> sum running
1648
- */
1649
- `b_${id}_client_running`,
1650
- /*
1651
- HASH
1652
- client -> num queued
1653
- */
1654
- `b_${id}_client_num_queued`,
1655
- /*
1656
- ZSET
1657
- client -> last job registered
1658
- */
1659
- `b_${id}_client_last_registered`,
1660
- /*
1661
- ZSET
1662
- client -> last seen
1663
- */
1664
- `b_${id}_client_last_seen`
1665
- ];
1666
- };
1667
- templates = {
1668
- init: {
1669
- keys: exports2.allKeys,
1670
- headers: ["process_tick"],
1671
- refresh_expiration: !0,
1672
- code: lua["init.lua"]
1673
- },
1674
- group_check: {
1675
- keys: exports2.allKeys,
1676
- headers: [],
1677
- refresh_expiration: !1,
1678
- code: lua["group_check.lua"]
1679
- },
1680
- register_client: {
1681
- keys: exports2.allKeys,
1682
- headers: ["validate_keys"],
1683
- refresh_expiration: !1,
1684
- code: lua["register_client.lua"]
1685
- },
1686
- blacklist_client: {
1687
- keys: exports2.allKeys,
1688
- headers: ["validate_keys", "validate_client"],
1689
- refresh_expiration: !1,
1690
- code: lua["blacklist_client.lua"]
1691
- },
1692
- heartbeat: {
1693
- keys: exports2.allKeys,
1694
- headers: ["validate_keys", "validate_client", "process_tick"],
1695
- refresh_expiration: !1,
1696
- code: lua["heartbeat.lua"]
1697
- },
1698
- update_settings: {
1699
- keys: exports2.allKeys,
1700
- headers: ["validate_keys", "validate_client", "process_tick"],
1701
- refresh_expiration: !0,
1702
- code: lua["update_settings.lua"]
1703
- },
1704
- running: {
1705
- keys: exports2.allKeys,
1706
- headers: ["validate_keys", "validate_client", "process_tick"],
1707
- refresh_expiration: !1,
1708
- code: lua["running.lua"]
1709
- },
1710
- queued: {
1711
- keys: exports2.allKeys,
1712
- headers: ["validate_keys", "validate_client"],
1713
- refresh_expiration: !1,
1714
- code: lua["queued.lua"]
1715
- },
1716
- done: {
1717
- keys: exports2.allKeys,
1718
- headers: ["validate_keys", "validate_client", "process_tick"],
1719
- refresh_expiration: !1,
1720
- code: lua["done.lua"]
1721
- },
1722
- check: {
1723
- keys: exports2.allKeys,
1724
- headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
1725
- refresh_expiration: !1,
1726
- code: lua["check.lua"]
1727
- },
1728
- submit: {
1729
- keys: exports2.allKeys,
1730
- headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
1731
- refresh_expiration: !0,
1732
- code: lua["submit.lua"]
1733
- },
1734
- register: {
1735
- keys: exports2.allKeys,
1736
- headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
1737
- refresh_expiration: !0,
1738
- code: lua["register.lua"]
1739
- },
1740
- free: {
1741
- keys: exports2.allKeys,
1742
- headers: ["validate_keys", "validate_client", "process_tick"],
1743
- refresh_expiration: !0,
1744
- code: lua["free.lua"]
1745
- },
1746
- current_reservoir: {
1747
- keys: exports2.allKeys,
1748
- headers: ["validate_keys", "validate_client", "process_tick"],
1749
- refresh_expiration: !1,
1750
- code: lua["current_reservoir.lua"]
1751
- },
1752
- increment_reservoir: {
1753
- keys: exports2.allKeys,
1754
- headers: ["validate_keys", "validate_client", "process_tick"],
1755
- refresh_expiration: !0,
1756
- code: lua["increment_reservoir.lua"]
1757
- }
1758
- };
1759
- exports2.names = Object.keys(templates);
1760
- exports2.keys = function(name, id) {
1761
- return templates[name].keys(id);
1762
- };
1763
- exports2.payload = function(name) {
1764
- var template;
1765
- return template = templates[name], Array.prototype.concat(headers.refs, template.headers.map(function(h) {
1766
- return headers[h];
1767
- }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join(`
1768
- `);
1769
- };
1770
- }
1771
- });
1772
-
1773
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/RedisConnection.js
1774
- var require_RedisConnection = __commonJS({
1775
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/RedisConnection.js"(exports, module) {
1776
- "use strict";
1777
- init_cjs_shims();
1778
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1779
- try {
1780
- var info = gen[key](arg), value = info.value;
1781
- } catch (error) {
1782
- reject(error);
1783
- return;
1784
- }
1785
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
1786
- }
1787
- function _asyncToGenerator(fn) {
1788
- return function() {
1789
- var self = this, args = arguments;
1790
- return new Promise(function(resolve, reject) {
1791
- var gen = fn.apply(self, args);
1792
- function _next(value) {
1793
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1794
- }
1795
- function _throw(err2) {
1796
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err2);
1797
- }
1798
- _next(void 0);
1799
- });
1800
- };
1801
- }
1802
- var Events, RedisConnection, Scripts, parser;
1803
- parser = require_parser();
1804
- Events = require_Events();
1805
- Scripts = require_Scripts();
1806
- RedisConnection = function() {
1807
- class RedisConnection {
1808
- constructor(options = {}) {
1809
- parser.load(options, this.defaults, this), this.Redis == null && (this.Redis = eval("require")("redis")), this.Events == null && (this.Events = new Events(this)), this.terminated = !1, this.client == null && (this.client = this.Redis.createClient(this.clientOptions)), this.subscriber = this.client.duplicate(), this.limiters = {}, this.shas = {}, this.ready = this.Promise.all([this._setup(this.client, !1), this._setup(this.subscriber, !0)]).then(() => this._loadScripts()).then(() => ({
1810
- client: this.client,
1811
- subscriber: this.subscriber
1812
- }));
1813
- }
1814
- _setup(client, sub) {
1815
- return client.setMaxListeners(0), new this.Promise((resolve, reject) => (client.on("error", (e) => this.Events.trigger("error", e)), sub && client.on("message", (channel, message) => {
1816
- var ref;
1817
- return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
1818
- }), client.ready ? resolve() : client.once("ready", resolve)));
1819
- }
1820
- _loadScript(name) {
1821
- return new this.Promise((resolve, reject) => {
1822
- var payload;
1823
- return payload = Scripts.payload(name), this.client.multi([["script", "load", payload]]).exec((err2, replies) => err2 != null ? reject(err2) : (this.shas[name] = replies[0], resolve(replies[0])));
1824
- });
1825
- }
1826
- _loadScripts() {
1827
- return this.Promise.all(Scripts.names.map((k) => this._loadScript(k)));
1828
- }
1829
- __runCommand__(cmd) {
1830
- var _this = this;
1831
- return _asyncToGenerator(function* () {
1832
- return yield _this.ready, new _this.Promise((resolve, reject) => _this.client.multi([cmd]).exec_atomic(function(err2, replies) {
1833
- return err2 != null ? reject(err2) : resolve(replies[0]);
1834
- }));
1835
- })();
1836
- }
1837
- __addLimiter__(instance) {
1838
- return this.Promise.all([instance.channel(), instance.channel_client()].map((channel) => new this.Promise((resolve, reject) => {
1839
- var handler;
1840
- return handler = (chan) => {
1841
- if (chan === channel)
1842
- return this.subscriber.removeListener("subscribe", handler), this.limiters[channel] = instance, resolve();
1843
- }, this.subscriber.on("subscribe", handler), this.subscriber.subscribe(channel);
1844
- })));
1845
- }
1846
- __removeLimiter__(instance) {
1847
- var _this2 = this;
1848
- return this.Promise.all([instance.channel(), instance.channel_client()].map(
1849
- /* @__PURE__ */ function() {
1850
- var _ref = _asyncToGenerator(function* (channel) {
1851
- return _this2.terminated || (yield new _this2.Promise((resolve, reject) => _this2.subscriber.unsubscribe(channel, function(err2, chan) {
1852
- if (err2 != null)
1853
- return reject(err2);
1854
- if (chan === channel)
1855
- return resolve();
1856
- }))), delete _this2.limiters[channel];
1857
- });
1858
- return function(_x) {
1859
- return _ref.apply(this, arguments);
1860
- };
1861
- }()
1862
- ));
1863
- }
1864
- __scriptArgs__(name, id, args, cb) {
1865
- var keys;
1866
- return keys = Scripts.keys(name, id), [this.shas[name], keys.length].concat(keys, args, cb);
1867
- }
1868
- __scriptFn__(name) {
1869
- return this.client.evalsha.bind(this.client);
1870
- }
1871
- disconnect(flush = !0) {
1872
- var i, k, len, ref;
1873
- for (ref = Object.keys(this.limiters), i = 0, len = ref.length; i < len; i++)
1874
- k = ref[i], clearInterval(this.limiters[k]._store.heartbeat);
1875
- return this.limiters = {}, this.terminated = !0, this.client.end(flush), this.subscriber.end(flush), this.Promise.resolve();
1876
- }
1877
- }
1878
- return RedisConnection.prototype.datastore = "redis", RedisConnection.prototype.defaults = {
1879
- Redis: null,
1880
- clientOptions: {},
1881
- client: null,
1882
- Promise,
1883
- Events: null
1884
- }, RedisConnection;
1885
- }.call(void 0);
1886
- module.exports = RedisConnection;
1887
- }
1888
- });
1889
-
1890
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/IORedisConnection.js
1891
- var require_IORedisConnection = __commonJS({
1892
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/IORedisConnection.js"(exports, module) {
1893
- "use strict";
1894
- init_cjs_shims();
1895
- function _slicedToArray(arr, i) {
1896
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
1897
- }
1898
- function _nonIterableRest() {
1899
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
1900
- }
1901
- function _iterableToArrayLimit(arr, i) {
1902
- var _arr = [], _n = !0, _d = !1, _e = void 0;
1903
- try {
1904
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), !(i && _arr.length === i)); _n = !0)
1905
- ;
1906
- } catch (err2) {
1907
- _d = !0, _e = err2;
1908
- } finally {
1909
- try {
1910
- !_n && _i.return != null && _i.return();
1911
- } finally {
1912
- if (_d)
1913
- throw _e;
1914
- }
1915
- }
1916
- return _arr;
1917
- }
1918
- function _arrayWithHoles(arr) {
1919
- if (Array.isArray(arr))
1920
- return arr;
1921
- }
1922
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1923
- try {
1924
- var info = gen[key](arg), value = info.value;
1925
- } catch (error) {
1926
- reject(error);
1927
- return;
1928
- }
1929
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
1930
- }
1931
- function _asyncToGenerator(fn) {
1932
- return function() {
1933
- var self = this, args = arguments;
1934
- return new Promise(function(resolve, reject) {
1935
- var gen = fn.apply(self, args);
1936
- function _next(value) {
1937
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1938
- }
1939
- function _throw(err2) {
1940
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err2);
1941
- }
1942
- _next(void 0);
1943
- });
1944
- };
1945
- }
1946
- var Events, IORedisConnection, Scripts, parser;
1947
- parser = require_parser();
1948
- Events = require_Events();
1949
- Scripts = require_Scripts();
1950
- IORedisConnection = function() {
1951
- class IORedisConnection {
1952
- constructor(options = {}) {
1953
- parser.load(options, this.defaults, this), this.Redis == null && (this.Redis = eval("require")("ioredis")), this.Events == null && (this.Events = new Events(this)), this.terminated = !1, this.clusterNodes != null ? (this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions), this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions)) : this.client != null && this.client.duplicate == null ? this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options) : (this.client == null && (this.client = new this.Redis(this.clientOptions)), this.subscriber = this.client.duplicate()), this.limiters = {}, this.ready = this.Promise.all([this._setup(this.client, !1), this._setup(this.subscriber, !0)]).then(() => (this._loadScripts(), {
1954
- client: this.client,
1955
- subscriber: this.subscriber
1956
- }));
1957
- }
1958
- _setup(client, sub) {
1959
- return client.setMaxListeners(0), new this.Promise((resolve, reject) => (client.on("error", (e) => this.Events.trigger("error", e)), sub && client.on("message", (channel, message) => {
1960
- var ref;
1961
- return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
1962
- }), client.status === "ready" ? resolve() : client.once("ready", resolve)));
1963
- }
1964
- _loadScripts() {
1965
- return Scripts.names.forEach((name) => this.client.defineCommand(name, {
1966
- lua: Scripts.payload(name)
1967
- }));
1968
- }
1969
- __runCommand__(cmd) {
1970
- var _this = this;
1971
- return _asyncToGenerator(function* () {
1972
- var _, deleted;
1973
- yield _this.ready;
1974
- var _ref = yield _this.client.pipeline([cmd]).exec(), _ref2 = _slicedToArray(_ref, 1), _ref2$ = _slicedToArray(_ref2[0], 2);
1975
- return _ = _ref2$[0], deleted = _ref2$[1], deleted;
1976
- })();
1977
- }
1978
- __addLimiter__(instance) {
1979
- return this.Promise.all([instance.channel(), instance.channel_client()].map((channel) => new this.Promise((resolve, reject) => this.subscriber.subscribe(channel, () => (this.limiters[channel] = instance, resolve())))));
1980
- }
1981
- __removeLimiter__(instance) {
1982
- var _this2 = this;
1983
- return [instance.channel(), instance.channel_client()].forEach(
1984
- /* @__PURE__ */ function() {
1985
- var _ref3 = _asyncToGenerator(function* (channel) {
1986
- return _this2.terminated || (yield _this2.subscriber.unsubscribe(channel)), delete _this2.limiters[channel];
1987
- });
1988
- return function(_x) {
1989
- return _ref3.apply(this, arguments);
1990
- };
1991
- }()
1992
- );
1993
- }
1994
- __scriptArgs__(name, id, args, cb) {
1995
- var keys;
1996
- return keys = Scripts.keys(name, id), [keys.length].concat(keys, args, cb);
1997
- }
1998
- __scriptFn__(name) {
1999
- return this.client[name].bind(this.client);
2000
- }
2001
- disconnect(flush = !0) {
2002
- var i, k, len, ref;
2003
- for (ref = Object.keys(this.limiters), i = 0, len = ref.length; i < len; i++)
2004
- k = ref[i], clearInterval(this.limiters[k]._store.heartbeat);
2005
- return this.limiters = {}, this.terminated = !0, flush ? this.Promise.all([this.client.quit(), this.subscriber.quit()]) : (this.client.disconnect(), this.subscriber.disconnect(), this.Promise.resolve());
2006
- }
2007
- }
2008
- return IORedisConnection.prototype.datastore = "ioredis", IORedisConnection.prototype.defaults = {
2009
- Redis: null,
2010
- clientOptions: {},
2011
- clusterNodes: null,
2012
- client: null,
2013
- Promise,
2014
- Events: null
2015
- }, IORedisConnection;
2016
- }.call(void 0);
2017
- module.exports = IORedisConnection;
2018
- }
2019
- });
2020
-
2021
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/RedisDatastore.js
2022
- var require_RedisDatastore = __commonJS({
2023
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/RedisDatastore.js"(exports2, module2) {
2024
- "use strict";
2025
- init_cjs_shims();
2026
- function _slicedToArray2(arr, i) {
2027
- return _arrayWithHoles2(arr) || _iterableToArrayLimit2(arr, i) || _nonIterableRest2();
2028
- }
2029
- function _nonIterableRest2() {
2030
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
2031
- }
2032
- function _iterableToArrayLimit2(arr, i) {
2033
- var _arr = [], _n = !0, _d = !1, _e = void 0;
2034
- try {
2035
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), !(i && _arr.length === i)); _n = !0)
2036
- ;
2037
- } catch (err2) {
2038
- _d = !0, _e = err2;
2039
- } finally {
2040
- try {
2041
- !_n && _i.return != null && _i.return();
2042
- } finally {
2043
- if (_d)
2044
- throw _e;
2045
- }
2046
- }
2047
- return _arr;
2048
- }
2049
- function _arrayWithHoles2(arr) {
2050
- if (Array.isArray(arr))
2051
- return arr;
2052
- }
2053
- function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
2054
- try {
2055
- var info = gen[key](arg), value = info.value;
2056
- } catch (error) {
2057
- reject(error);
2058
- return;
2059
- }
2060
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
2061
- }
2062
- function _asyncToGenerator2(fn) {
2063
- return function() {
2064
- var self = this, args = arguments;
2065
- return new Promise(function(resolve, reject) {
2066
- var gen = fn.apply(self, args);
2067
- function _next(value) {
2068
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
2069
- }
2070
- function _throw(err2) {
2071
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err2);
2072
- }
2073
- _next(void 0);
2074
- });
2075
- };
2076
- }
2077
- var BottleneckError, IORedisConnection2, RedisConnection2, RedisDatastore, parser2;
2078
- parser2 = require_parser();
2079
- BottleneckError = require_BottleneckError();
2080
- RedisConnection2 = require_RedisConnection();
2081
- IORedisConnection2 = require_IORedisConnection();
2082
- RedisDatastore = class {
2083
- constructor(instance, storeOptions, storeInstanceOptions) {
2084
- this.instance = instance, this.storeOptions = storeOptions, this.originalId = this.instance.id, this.clientId = this.instance._randomIndex(), parser2.load(storeInstanceOptions, storeInstanceOptions, this), this.clients = {}, this.capacityPriorityCounters = {}, this.sharedConnection = this.connection != null, this.connection == null && (this.connection = this.instance.datastore === "redis" ? new RedisConnection2({
2085
- Redis: this.Redis,
2086
- clientOptions: this.clientOptions,
2087
- Promise: this.Promise,
2088
- Events: this.instance.Events
2089
- }) : this.instance.datastore === "ioredis" ? new IORedisConnection2({
2090
- Redis: this.Redis,
2091
- clientOptions: this.clientOptions,
2092
- clusterNodes: this.clusterNodes,
2093
- Promise: this.Promise,
2094
- Events: this.instance.Events
2095
- }) : void 0), this.instance.connection = this.connection, this.instance.datastore = this.connection.datastore, this.ready = this.connection.ready.then((clients) => (this.clients = clients, this.runScript("init", this.prepareInitSettings(this.clearDatastore)))).then(() => this.connection.__addLimiter__(this.instance)).then(() => this.runScript("register_client", [this.instance.queued()])).then(() => {
2096
- var base;
2097
- return typeof (base = this.heartbeat = setInterval(() => this.runScript("heartbeat", []).catch((e) => this.instance.Events.trigger("error", e)), this.heartbeatInterval)).unref == "function" && base.unref(), this.clients;
2098
- });
2099
- }
2100
- __publish__(message) {
2101
- var _this = this;
2102
- return _asyncToGenerator2(function* () {
2103
- var client, _ref = yield _this.ready;
2104
- return client = _ref.client, client.publish(_this.instance.channel(), `message:${message.toString()}`);
2105
- })();
2106
- }
2107
- onMessage(channel, message) {
2108
- var _this2 = this;
2109
- return _asyncToGenerator2(function* () {
2110
- var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type;
2111
- try {
2112
- pos = message.indexOf(":");
2113
- var _ref2 = [message.slice(0, pos), message.slice(pos + 1)];
2114
- if (type = _ref2[0], data = _ref2[1], type === "capacity")
2115
- return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0);
2116
- if (type === "capacity-priority") {
2117
- var _data$split = data.split(":"), _data$split2 = _slicedToArray2(_data$split, 3);
2118
- return rawCapacity = _data$split2[0], priorityClient = _data$split2[1], counter = _data$split2[2], capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0, priorityClient === _this2.clientId ? (drained = yield _this2.instance._drainAll(capacity), newCapacity = capacity != null ? capacity - (drained || 0) : "", yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`)) : priorityClient === "" ? (clearTimeout(_this2.capacityPriorityCounters[counter]), delete _this2.capacityPriorityCounters[counter], _this2.instance._drainAll(capacity)) : _this2.capacityPriorityCounters[counter] = setTimeout(
2119
- /* @__PURE__ */ _asyncToGenerator2(function* () {
2120
- var e2;
2121
- try {
2122
- return delete _this2.capacityPriorityCounters[counter], yield _this2.runScript("blacklist_client", [priorityClient]), yield _this2.instance._drainAll(capacity);
2123
- } catch (error) {
2124
- return e2 = error, _this2.instance.Events.trigger("error", e2);
2125
- }
2126
- }),
2127
- 1e3
2128
- );
2129
- } else {
2130
- if (type === "message")
2131
- return _this2.instance.Events.trigger("message", data);
2132
- if (type === "blocked")
2133
- return yield _this2.instance._dropAllQueued();
2134
- }
2135
- } catch (error) {
2136
- return e = error, _this2.instance.Events.trigger("error", e);
2137
- }
2138
- })();
2139
- }
2140
- __disconnect__(flush) {
2141
- return clearInterval(this.heartbeat), this.sharedConnection ? this.connection.__removeLimiter__(this.instance) : this.connection.disconnect(flush);
2142
- }
2143
- runScript(name, args) {
2144
- var _this3 = this;
2145
- return _asyncToGenerator2(function* () {
2146
- return name === "init" || name === "register_client" || (yield _this3.ready), new _this3.Promise((resolve, reject) => {
2147
- var all_args, arr;
2148
- return all_args = [Date.now(), _this3.clientId].concat(args), _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args), arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function(err2, replies) {
2149
- return err2 != null ? reject(err2) : resolve(replies);
2150
- }), _this3.connection.__scriptFn__(name)(...arr);
2151
- }).catch((e) => e.message === "SETTINGS_KEY_NOT_FOUND" ? name === "heartbeat" ? _this3.Promise.resolve() : _this3.runScript("init", _this3.prepareInitSettings(!1)).then(() => _this3.runScript(name, args)) : e.message === "UNKNOWN_CLIENT" ? _this3.runScript("register_client", [_this3.instance.queued()]).then(() => _this3.runScript(name, args)) : _this3.Promise.reject(e));
2152
- })();
2153
- }
2154
- prepareArray(arr) {
2155
- var i, len, results, x;
2156
- for (results = [], i = 0, len = arr.length; i < len; i++)
2157
- x = arr[i], results.push(x != null ? x.toString() : "");
2158
- return results;
2159
- }
2160
- prepareObject(obj) {
2161
- var arr, k, v;
2162
- arr = [];
2163
- for (k in obj)
2164
- v = obj[k], arr.push(k, v != null ? v.toString() : "");
2165
- return arr;
2166
- }
2167
- prepareInitSettings(clear) {
2168
- var args;
2169
- return args = this.prepareObject(Object.assign({}, this.storeOptions, {
2170
- id: this.originalId,
2171
- version: this.instance.version,
2172
- groupTimeout: this.timeout,
2173
- clientTimeout: this.clientTimeout
2174
- })), args.unshift(clear ? 1 : 0, this.instance.version), args;
2175
- }
2176
- convertBool(b) {
2177
- return !!b;
2178
- }
2179
- __updateSettings__(options2) {
2180
- var _this4 = this;
2181
- return _asyncToGenerator2(function* () {
2182
- return yield _this4.runScript("update_settings", _this4.prepareObject(options2)), parser2.overwrite(options2, options2, _this4.storeOptions);
2183
- })();
2184
- }
2185
- __running__() {
2186
- return this.runScript("running", []);
2187
- }
2188
- __queued__() {
2189
- return this.runScript("queued", []);
2190
- }
2191
- __done__() {
2192
- return this.runScript("done", []);
2193
- }
2194
- __groupCheck__() {
2195
- var _this5 = this;
2196
- return _asyncToGenerator2(function* () {
2197
- return _this5.convertBool(yield _this5.runScript("group_check", []));
2198
- })();
2199
- }
2200
- __incrementReservoir__(incr) {
2201
- return this.runScript("increment_reservoir", [incr]);
2202
- }
2203
- __currentReservoir__() {
2204
- return this.runScript("current_reservoir", []);
2205
- }
2206
- __check__(weight) {
2207
- var _this6 = this;
2208
- return _asyncToGenerator2(function* () {
2209
- return _this6.convertBool(yield _this6.runScript("check", _this6.prepareArray([weight])));
2210
- })();
2211
- }
2212
- __register__(index, weight, expiration) {
2213
- var _this7 = this;
2214
- return _asyncToGenerator2(function* () {
2215
- var reservoir, success, wait, _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])), _ref5 = _slicedToArray2(_ref4, 3);
2216
- return success = _ref5[0], wait = _ref5[1], reservoir = _ref5[2], {
2217
- success: _this7.convertBool(success),
2218
- wait,
2219
- reservoir
2220
- };
2221
- })();
2222
- }
2223
- __submit__(queueLength, weight) {
2224
- var _this8 = this;
2225
- return _asyncToGenerator2(function* () {
2226
- var blocked, e, maxConcurrent, overweight, reachedHWM, strategy;
2227
- try {
2228
- var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])), _ref7 = _slicedToArray2(_ref6, 3);
2229
- return reachedHWM = _ref7[0], blocked = _ref7[1], strategy = _ref7[2], {
2230
- reachedHWM: _this8.convertBool(reachedHWM),
2231
- blocked: _this8.convertBool(blocked),
2232
- strategy
2233
- };
2234
- } catch (error) {
2235
- if (e = error, e.message.indexOf("OVERWEIGHT") === 0) {
2236
- var _e$message$split = e.message.split(":"), _e$message$split2 = _slicedToArray2(_e$message$split, 3);
2237
- throw overweight = _e$message$split2[0], weight = _e$message$split2[1], maxConcurrent = _e$message$split2[2], new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`);
2238
- } else
2239
- throw e;
2240
- }
2241
- })();
2242
- }
2243
- __free__(index, weight) {
2244
- var _this9 = this;
2245
- return _asyncToGenerator2(function* () {
2246
- var running;
2247
- return running = yield _this9.runScript("free", _this9.prepareArray([index])), {
2248
- running
2249
- };
2250
- })();
2251
- }
2252
- };
2253
- module2.exports = RedisDatastore;
2254
- }
2255
- });
2256
-
2257
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/States.js
2258
- var require_States = __commonJS({
2259
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/States.js"(exports2, module2) {
2260
- "use strict";
2261
- init_cjs_shims();
2262
- var BottleneckError, States;
2263
- BottleneckError = require_BottleneckError();
2264
- States = class {
2265
- constructor(status1) {
2266
- this.status = status1, this._jobs = {}, this.counts = this.status.map(function() {
2267
- return 0;
2268
- });
2269
- }
2270
- next(id) {
2271
- var current, next;
2272
- if (current = this._jobs[id], next = current + 1, current != null && next < this.status.length)
2273
- return this.counts[current]--, this.counts[next]++, this._jobs[id]++;
2274
- if (current != null)
2275
- return this.counts[current]--, delete this._jobs[id];
2276
- }
2277
- start(id) {
2278
- var initial;
2279
- return initial = 0, this._jobs[id] = initial, this.counts[initial]++;
2280
- }
2281
- remove(id) {
2282
- var current;
2283
- return current = this._jobs[id], current != null && (this.counts[current]--, delete this._jobs[id]), current != null;
2284
- }
2285
- jobStatus(id) {
2286
- var ref;
2287
- return (ref = this.status[this._jobs[id]]) != null ? ref : null;
2288
- }
2289
- statusJobs(status) {
2290
- var k, pos, ref, results, v;
2291
- if (status != null) {
2292
- if (pos = this.status.indexOf(status), pos < 0)
2293
- throw new BottleneckError(`status must be one of ${this.status.join(", ")}`);
2294
- ref = this._jobs, results = [];
2295
- for (k in ref)
2296
- v = ref[k], v === pos && results.push(k);
2297
- return results;
2298
- } else
2299
- return Object.keys(this._jobs);
2300
- }
2301
- statusCounts() {
2302
- return this.counts.reduce((acc, v, i) => (acc[this.status[i]] = v, acc), {});
2303
- }
2304
- };
2305
- module2.exports = States;
2306
- }
2307
- });
2308
-
2309
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Sync.js
2310
- var require_Sync = __commonJS({
2311
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Sync.js"(exports2, module2) {
2312
- "use strict";
2313
- init_cjs_shims();
2314
- function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
2315
- try {
2316
- var info = gen[key](arg), value = info.value;
2317
- } catch (error) {
2318
- reject(error);
2319
- return;
2320
- }
2321
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
2322
- }
2323
- function _asyncToGenerator2(fn) {
2324
- return function() {
2325
- var self = this, args = arguments;
2326
- return new Promise(function(resolve, reject) {
2327
- var gen = fn.apply(self, args);
2328
- function _next(value) {
2329
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
2330
- }
2331
- function _throw(err2) {
2332
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err2);
2333
- }
2334
- _next(void 0);
2335
- });
2336
- };
2337
- }
2338
- var DLList, Sync;
2339
- DLList = require_DLList();
2340
- Sync = class {
2341
- constructor(name, Promise2) {
2342
- this.schedule = this.schedule.bind(this), this.name = name, this.Promise = Promise2, this._running = 0, this._queue = new DLList();
2343
- }
2344
- isEmpty() {
2345
- return this._queue.length === 0;
2346
- }
2347
- _tryToRun() {
2348
- var _this = this;
2349
- return _asyncToGenerator2(function* () {
2350
- var args, cb, error, reject, resolve, returned, task;
2351
- if (_this._running < 1 && _this._queue.length > 0) {
2352
- _this._running++;
2353
- var _this$_queue$shift = _this._queue.shift();
2354
- return task = _this$_queue$shift.task, args = _this$_queue$shift.args, resolve = _this$_queue$shift.resolve, reject = _this$_queue$shift.reject, cb = yield _asyncToGenerator2(function* () {
2355
- try {
2356
- return returned = yield task(...args), function() {
2357
- return resolve(returned);
2358
- };
2359
- } catch (error1) {
2360
- return error = error1, function() {
2361
- return reject(error);
2362
- };
2363
- }
2364
- })(), _this._running--, _this._tryToRun(), cb();
2365
- }
2366
- })();
2367
- }
2368
- schedule(task, ...args) {
2369
- var promise, reject, resolve;
2370
- return resolve = reject = null, promise = new this.Promise(function(_resolve, _reject) {
2371
- return resolve = _resolve, reject = _reject;
2372
- }), this._queue.push({
2373
- task,
2374
- args,
2375
- resolve,
2376
- reject
2377
- }), this._tryToRun(), promise;
2378
- }
2379
- };
2380
- module2.exports = Sync;
2381
- }
2382
- });
2383
-
2384
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/version.json
2385
- var require_version = __commonJS({
2386
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/version.json"(exports2, module2) {
2387
- module2.exports = { version: "2.19.5" };
2388
- }
2389
- });
2390
-
2391
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Group.js
2392
- var require_Group = __commonJS({
2393
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Group.js"(exports2, module2) {
2394
- "use strict";
2395
- init_cjs_shims();
2396
- function _slicedToArray2(arr, i) {
2397
- return _arrayWithHoles2(arr) || _iterableToArrayLimit2(arr, i) || _nonIterableRest2();
2398
- }
2399
- function _nonIterableRest2() {
2400
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
2401
- }
2402
- function _iterableToArrayLimit2(arr, i) {
2403
- var _arr = [], _n = !0, _d = !1, _e = void 0;
2404
- try {
2405
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), !(i && _arr.length === i)); _n = !0)
2406
- ;
2407
- } catch (err2) {
2408
- _d = !0, _e = err2;
2409
- } finally {
2410
- try {
2411
- !_n && _i.return != null && _i.return();
2412
- } finally {
2413
- if (_d)
2414
- throw _e;
2415
- }
2416
- }
2417
- return _arr;
2418
- }
2419
- function _arrayWithHoles2(arr) {
2420
- if (Array.isArray(arr))
2421
- return arr;
2422
- }
2423
- function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
2424
- try {
2425
- var info = gen[key](arg), value = info.value;
2426
- } catch (error) {
2427
- reject(error);
2428
- return;
2429
- }
2430
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
2431
- }
2432
- function _asyncToGenerator2(fn) {
2433
- return function() {
2434
- var self = this, args = arguments;
2435
- return new Promise(function(resolve, reject) {
2436
- var gen = fn.apply(self, args);
2437
- function _next(value) {
2438
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
2439
- }
2440
- function _throw(err2) {
2441
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err2);
2442
- }
2443
- _next(void 0);
2444
- });
2445
- };
2446
- }
2447
- var Events2, Group, IORedisConnection2, RedisConnection2, Scripts2, parser2;
2448
- parser2 = require_parser();
2449
- Events2 = require_Events();
2450
- RedisConnection2 = require_RedisConnection();
2451
- IORedisConnection2 = require_IORedisConnection();
2452
- Scripts2 = require_Scripts();
2453
- Group = function() {
2454
- class Group2 {
2455
- constructor(limiterOptions = {}) {
2456
- this.deleteKey = this.deleteKey.bind(this), this.limiterOptions = limiterOptions, parser2.load(this.limiterOptions, this.defaults, this), this.Events = new Events2(this), this.instances = {}, this.Bottleneck = require_Bottleneck(), this._startAutoCleanup(), this.sharedConnection = this.connection != null, this.connection == null && (this.limiterOptions.datastore === "redis" ? this.connection = new RedisConnection2(Object.assign({}, this.limiterOptions, {
2457
- Events: this.Events
2458
- })) : this.limiterOptions.datastore === "ioredis" && (this.connection = new IORedisConnection2(Object.assign({}, this.limiterOptions, {
2459
- Events: this.Events
2460
- }))));
2461
- }
2462
- key(key = "") {
2463
- var ref;
2464
- return (ref = this.instances[key]) != null ? ref : (() => {
2465
- var limiter2;
2466
- return limiter2 = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, {
2467
- id: `${this.id}-${key}`,
2468
- timeout: this.timeout,
2469
- connection: this.connection
2470
- })), this.Events.trigger("created", limiter2, key), limiter2;
2471
- })();
2472
- }
2473
- deleteKey(key = "") {
2474
- var _this = this;
2475
- return _asyncToGenerator2(function* () {
2476
- var deleted, instance;
2477
- return instance = _this.instances[key], _this.connection && (deleted = yield _this.connection.__runCommand__(["del", ...Scripts2.allKeys(`${_this.id}-${key}`)])), instance != null && (delete _this.instances[key], yield instance.disconnect()), instance != null || deleted > 0;
2478
- })();
2479
- }
2480
- limiters() {
2481
- var k, ref, results, v;
2482
- ref = this.instances, results = [];
2483
- for (k in ref)
2484
- v = ref[k], results.push({
2485
- key: k,
2486
- limiter: v
2487
- });
2488
- return results;
2489
- }
2490
- keys() {
2491
- return Object.keys(this.instances);
2492
- }
2493
- clusterKeys() {
2494
- var _this2 = this;
2495
- return _asyncToGenerator2(function* () {
2496
- var cursor, end, found, i, k, keys, len, next, start;
2497
- if (_this2.connection == null)
2498
- return _this2.Promise.resolve(_this2.keys());
2499
- for (keys = [], cursor = null, start = `b_${_this2.id}-`.length, end = 9; cursor !== 0; ) {
2500
- var _ref = yield _this2.connection.__runCommand__(["scan", cursor ?? 0, "match", `b_${_this2.id}-*_settings`, "count", 1e4]), _ref2 = _slicedToArray2(_ref, 2);
2501
- for (next = _ref2[0], found = _ref2[1], cursor = ~~next, i = 0, len = found.length; i < len; i++)
2502
- k = found[i], keys.push(k.slice(start, -end));
2503
- }
2504
- return keys;
2505
- })();
2506
- }
2507
- _startAutoCleanup() {
2508
- var _this3 = this, base;
2509
- return clearInterval(this.interval), typeof (base = this.interval = setInterval(
2510
- /* @__PURE__ */ _asyncToGenerator2(function* () {
2511
- var e, k, ref, results, time, v;
2512
- time = Date.now(), ref = _this3.instances, results = [];
2513
- for (k in ref) {
2514
- v = ref[k];
2515
- try {
2516
- (yield v._store.__groupCheck__(time)) ? results.push(_this3.deleteKey(k)) : results.push(void 0);
2517
- } catch (error) {
2518
- e = error, results.push(v.Events.trigger("error", e));
2519
- }
2520
- }
2521
- return results;
2522
- }),
2523
- this.timeout / 2
2524
- )).unref == "function" ? base.unref() : void 0;
2525
- }
2526
- updateSettings(options2 = {}) {
2527
- if (parser2.overwrite(options2, this.defaults, this), parser2.overwrite(options2, options2, this.limiterOptions), options2.timeout != null)
2528
- return this._startAutoCleanup();
2529
- }
2530
- disconnect(flush = !0) {
2531
- var ref;
2532
- if (!this.sharedConnection)
2533
- return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
2534
- }
2535
- }
2536
- return Group2.prototype.defaults = {
2537
- timeout: 1e3 * 60 * 5,
2538
- connection: null,
2539
- Promise,
2540
- id: "group-key"
2541
- }, Group2;
2542
- }.call(void 0);
2543
- module2.exports = Group;
2544
- }
2545
- });
2546
-
2547
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Batcher.js
2548
- var require_Batcher = __commonJS({
2549
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Batcher.js"(exports2, module2) {
2550
- "use strict";
2551
- init_cjs_shims();
2552
- var Batcher, Events2, parser2;
2553
- parser2 = require_parser();
2554
- Events2 = require_Events();
2555
- Batcher = function() {
2556
- class Batcher2 {
2557
- constructor(options2 = {}) {
2558
- this.options = options2, parser2.load(this.options, this.defaults, this), this.Events = new Events2(this), this._arr = [], this._resetPromise(), this._lastFlush = Date.now();
2559
- }
2560
- _resetPromise() {
2561
- return this._promise = new this.Promise((res, rej) => this._resolve = res);
2562
- }
2563
- _flush() {
2564
- return clearTimeout(this._timeout), this._lastFlush = Date.now(), this._resolve(), this.Events.trigger("batch", this._arr), this._arr = [], this._resetPromise();
2565
- }
2566
- add(data) {
2567
- var ret;
2568
- return this._arr.push(data), ret = this._promise, this._arr.length === this.maxSize ? this._flush() : this.maxTime != null && this._arr.length === 1 && (this._timeout = setTimeout(() => this._flush(), this.maxTime)), ret;
2569
- }
2570
- }
2571
- return Batcher2.prototype.defaults = {
2572
- maxTime: null,
2573
- maxSize: null,
2574
- Promise
2575
- }, Batcher2;
2576
- }.call(void 0);
2577
- module2.exports = Batcher;
2578
- }
2579
- });
2580
-
2581
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Bottleneck.js
2582
- var require_Bottleneck = __commonJS({
2583
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/Bottleneck.js"(exports2, module2) {
2584
- "use strict";
2585
- init_cjs_shims();
2586
- function _slicedToArray2(arr, i) {
2587
- return _arrayWithHoles2(arr) || _iterableToArrayLimit2(arr, i) || _nonIterableRest2();
2588
- }
2589
- function _iterableToArrayLimit2(arr, i) {
2590
- var _arr = [], _n = !0, _d = !1, _e = void 0;
2591
- try {
2592
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), !(i && _arr.length === i)); _n = !0)
2593
- ;
2594
- } catch (err2) {
2595
- _d = !0, _e = err2;
2596
- } finally {
2597
- try {
2598
- !_n && _i.return != null && _i.return();
2599
- } finally {
2600
- if (_d)
2601
- throw _e;
2602
- }
2603
- }
2604
- return _arr;
2605
- }
2606
- function _toArray(arr) {
2607
- return _arrayWithHoles2(arr) || _iterableToArray(arr) || _nonIterableRest2();
2608
- }
2609
- function _nonIterableRest2() {
2610
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
2611
- }
2612
- function _iterableToArray(iter) {
2613
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]")
2614
- return Array.from(iter);
2615
- }
2616
- function _arrayWithHoles2(arr) {
2617
- if (Array.isArray(arr))
2618
- return arr;
2619
- }
2620
- function asyncGeneratorStep2(gen, resolve, reject, _next, _throw, key, arg) {
2621
- try {
2622
- var info = gen[key](arg), value = info.value;
2623
- } catch (error) {
2624
- reject(error);
2625
- return;
2626
- }
2627
- info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
2628
- }
2629
- function _asyncToGenerator2(fn) {
2630
- return function() {
2631
- var self = this, args = arguments;
2632
- return new Promise(function(resolve, reject) {
2633
- var gen = fn.apply(self, args);
2634
- function _next(value) {
2635
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "next", value);
2636
- }
2637
- function _throw(err2) {
2638
- asyncGeneratorStep2(gen, resolve, reject, _next, _throw, "throw", err2);
2639
- }
2640
- _next(void 0);
2641
- });
2642
- };
2643
- }
2644
- var Bottleneck2, DEFAULT_PRIORITY, Events2, Job, LocalDatastore, NUM_PRIORITIES, Queues, RedisDatastore, States, Sync, parser2, splice = [].splice;
2645
- NUM_PRIORITIES = 10;
2646
- DEFAULT_PRIORITY = 5;
2647
- parser2 = require_parser();
2648
- Queues = require_Queues();
2649
- Job = require_Job();
2650
- LocalDatastore = require_LocalDatastore();
2651
- RedisDatastore = require_RedisDatastore();
2652
- Events2 = require_Events();
2653
- States = require_States();
2654
- Sync = require_Sync();
2655
- Bottleneck2 = function() {
2656
- class Bottleneck3 {
2657
- constructor(options2 = {}, ...invalid) {
2658
- var storeInstanceOptions, storeOptions;
2659
- this._addToQueue = this._addToQueue.bind(this), this._validateOptions(options2, invalid), parser2.load(options2, this.instanceDefaults, this), this._queues = new Queues(NUM_PRIORITIES), this._scheduled = {}, this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])), this._limiter = null, this.Events = new Events2(this), this._submitLock = new Sync("submit", this.Promise), this._registerLock = new Sync("register", this.Promise), storeOptions = parser2.load(options2, this.storeDefaults, {}), this._store = function() {
2660
- if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null)
2661
- return storeInstanceOptions = parser2.load(options2, this.redisStoreDefaults, {}), new RedisDatastore(this, storeOptions, storeInstanceOptions);
2662
- if (this.datastore === "local")
2663
- return storeInstanceOptions = parser2.load(options2, this.localStoreDefaults, {}), new LocalDatastore(this, storeOptions, storeInstanceOptions);
2664
- throw new Bottleneck3.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`);
2665
- }.call(this), this._queues.on("leftzero", () => {
2666
- var ref;
2667
- return (ref = this._store.heartbeat) != null && typeof ref.ref == "function" ? ref.ref() : void 0;
2668
- }), this._queues.on("zero", () => {
2669
- var ref;
2670
- return (ref = this._store.heartbeat) != null && typeof ref.unref == "function" ? ref.unref() : void 0;
2671
- });
2672
- }
2673
- _validateOptions(options2, invalid) {
2674
- if (!(options2 != null && typeof options2 == "object" && invalid.length === 0))
2675
- throw new Bottleneck3.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.");
2676
- }
2677
- ready() {
2678
- return this._store.ready;
2679
- }
2680
- clients() {
2681
- return this._store.clients;
2682
- }
2683
- channel() {
2684
- return `b_${this.id}`;
2685
- }
2686
- channel_client() {
2687
- return `b_${this.id}_${this._store.clientId}`;
2688
- }
2689
- publish(message) {
2690
- return this._store.__publish__(message);
2691
- }
2692
- disconnect(flush = !0) {
2693
- return this._store.__disconnect__(flush);
2694
- }
2695
- chain(_limiter) {
2696
- return this._limiter = _limiter, this;
2697
- }
2698
- queued(priority) {
2699
- return this._queues.queued(priority);
2700
- }
2701
- clusterQueued() {
2702
- return this._store.__queued__();
2703
- }
2704
- empty() {
2705
- return this.queued() === 0 && this._submitLock.isEmpty();
2706
- }
2707
- running() {
2708
- return this._store.__running__();
2709
- }
2710
- done() {
2711
- return this._store.__done__();
2712
- }
2713
- jobStatus(id) {
2714
- return this._states.jobStatus(id);
2715
- }
2716
- jobs(status) {
2717
- return this._states.statusJobs(status);
2718
- }
2719
- counts() {
2720
- return this._states.statusCounts();
2721
- }
2722
- _randomIndex() {
2723
- return Math.random().toString(36).slice(2);
2724
- }
2725
- check(weight = 1) {
2726
- return this._store.__check__(weight);
2727
- }
2728
- _clearGlobalState(index) {
2729
- return this._scheduled[index] != null ? (clearTimeout(this._scheduled[index].expiration), delete this._scheduled[index], !0) : !1;
2730
- }
2731
- _free(index, job, options2, eventInfo) {
2732
- var _this = this;
2733
- return _asyncToGenerator2(function* () {
2734
- var e, running;
2735
- try {
2736
- var _ref = yield _this._store.__free__(index, options2.weight);
2737
- if (running = _ref.running, _this.Events.trigger("debug", `Freed ${options2.id}`, eventInfo), running === 0 && _this.empty())
2738
- return _this.Events.trigger("idle");
2739
- } catch (error1) {
2740
- return e = error1, _this.Events.trigger("error", e);
2741
- }
2742
- })();
2743
- }
2744
- _run(index, job, wait) {
2745
- var clearGlobalState, free, run;
2746
- return job.doRun(), clearGlobalState = this._clearGlobalState.bind(this, index), run = this._run.bind(this, index, job), free = this._free.bind(this, index, job), this._scheduled[index] = {
2747
- timeout: setTimeout(() => job.doExecute(this._limiter, clearGlobalState, run, free), wait),
2748
- expiration: job.options.expiration != null ? setTimeout(function() {
2749
- return job.doExpire(clearGlobalState, run, free);
2750
- }, wait + job.options.expiration) : void 0,
2751
- job
2752
- };
2753
- }
2754
- _drainOne(capacity) {
2755
- return this._registerLock.schedule(() => {
2756
- var args, index, next, options2, queue;
2757
- if (this.queued() === 0)
2758
- return this.Promise.resolve(null);
2759
- queue = this._queues.getFirst();
2760
- var _next2 = next = queue.first();
2761
- return options2 = _next2.options, args = _next2.args, capacity != null && options2.weight > capacity ? this.Promise.resolve(null) : (this.Events.trigger("debug", `Draining ${options2.id}`, {
2762
- args,
2763
- options: options2
2764
- }), index = this._randomIndex(), this._store.__register__(index, options2.weight, options2.expiration).then(({
2765
- success,
2766
- wait,
2767
- reservoir
2768
- }) => {
2769
- var empty;
2770
- return this.Events.trigger("debug", `Drained ${options2.id}`, {
2771
- success,
2772
- args,
2773
- options: options2
2774
- }), success ? (queue.shift(), empty = this.empty(), empty && this.Events.trigger("empty"), reservoir === 0 && this.Events.trigger("depleted", empty), this._run(index, next, wait), this.Promise.resolve(options2.weight)) : this.Promise.resolve(null);
2775
- }));
2776
- });
2777
- }
2778
- _drainAll(capacity, total = 0) {
2779
- return this._drainOne(capacity).then((drained) => {
2780
- var newCapacity;
2781
- return drained != null ? (newCapacity = capacity != null ? capacity - drained : capacity, this._drainAll(newCapacity, total + drained)) : this.Promise.resolve(total);
2782
- }).catch((e) => this.Events.trigger("error", e));
2783
- }
2784
- _dropAllQueued(message) {
2785
- return this._queues.shiftAll(function(job) {
2786
- return job.doDrop({
2787
- message
2788
- });
2789
- });
2790
- }
2791
- stop(options2 = {}) {
2792
- var done, waitForExecuting;
2793
- return options2 = parser2.load(options2, this.stopDefaults), waitForExecuting = (at) => {
2794
- var finished;
2795
- return finished = () => {
2796
- var counts;
2797
- return counts = this._states.counts, counts[0] + counts[1] + counts[2] + counts[3] === at;
2798
- }, new this.Promise((resolve, reject) => finished() ? resolve() : this.on("done", () => {
2799
- if (finished())
2800
- return this.removeAllListeners("done"), resolve();
2801
- }));
2802
- }, done = options2.dropWaitingJobs ? (this._run = function(index, next) {
2803
- return next.doDrop({
2804
- message: options2.dropErrorMessage
2805
- });
2806
- }, this._drainOne = () => this.Promise.resolve(null), this._registerLock.schedule(() => this._submitLock.schedule(() => {
2807
- var k, ref, v;
2808
- ref = this._scheduled;
2809
- for (k in ref)
2810
- v = ref[k], this.jobStatus(v.job.options.id) === "RUNNING" && (clearTimeout(v.timeout), clearTimeout(v.expiration), v.job.doDrop({
2811
- message: options2.dropErrorMessage
2812
- }));
2813
- return this._dropAllQueued(options2.dropErrorMessage), waitForExecuting(0);
2814
- }))) : this.schedule({
2815
- priority: NUM_PRIORITIES - 1,
2816
- weight: 0
2817
- }, () => waitForExecuting(1)), this._receive = function(job) {
2818
- return job._reject(new Bottleneck3.prototype.BottleneckError(options2.enqueueErrorMessage));
2819
- }, this.stop = () => this.Promise.reject(new Bottleneck3.prototype.BottleneckError("stop() has already been called")), done;
2820
- }
2821
- _addToQueue(job) {
2822
- var _this2 = this;
2823
- return _asyncToGenerator2(function* () {
2824
- var args, blocked, error, options2, reachedHWM, shifted, strategy;
2825
- args = job.args, options2 = job.options;
2826
- try {
2827
- var _ref2 = yield _this2._store.__submit__(_this2.queued(), options2.weight);
2828
- reachedHWM = _ref2.reachedHWM, blocked = _ref2.blocked, strategy = _ref2.strategy;
2829
- } catch (error1) {
2830
- return error = error1, _this2.Events.trigger("debug", `Could not queue ${options2.id}`, {
2831
- args,
2832
- options: options2,
2833
- error
2834
- }), job.doDrop({
2835
- error
2836
- }), !1;
2837
- }
2838
- return blocked ? (job.doDrop(), !0) : reachedHWM && (shifted = strategy === Bottleneck3.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options2.priority) : strategy === Bottleneck3.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options2.priority + 1) : strategy === Bottleneck3.prototype.strategy.OVERFLOW ? job : void 0, shifted?.doDrop(), shifted == null || strategy === Bottleneck3.prototype.strategy.OVERFLOW) ? (shifted == null && job.doDrop(), reachedHWM) : (job.doQueue(reachedHWM, blocked), _this2._queues.push(job), yield _this2._drainAll(), reachedHWM);
2839
- })();
2840
- }
2841
- _receive(job) {
2842
- return this._states.jobStatus(job.options.id) != null ? (job._reject(new Bottleneck3.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)), !1) : (job.doReceive(), this._submitLock.schedule(this._addToQueue, job));
2843
- }
2844
- submit(...args) {
2845
- var cb, fn, job, options2, ref, ref1, task;
2846
- if (typeof args[0] == "function") {
2847
- var _ref3, _ref4, _splice$call, _splice$call2;
2848
- ref = args, _ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray2(_splice$call, 1), cb = _splice$call2[0], options2 = parser2.load({}, this.jobDefaults);
2849
- } else {
2850
- var _ref5, _ref6, _splice$call3, _splice$call4;
2851
- ref1 = args, _ref5 = ref1, _ref6 = _toArray(_ref5), options2 = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray2(_splice$call3, 1), cb = _splice$call4[0], options2 = parser2.load(options2, this.jobDefaults);
2852
- }
2853
- return task = (...args2) => new this.Promise(function(resolve, reject) {
2854
- return fn(...args2, function(...args3) {
2855
- return (args3[0] != null ? reject : resolve)(args3);
2856
- });
2857
- }), job = new Job(task, args, options2, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise), job.promise.then(function(args2) {
2858
- return typeof cb == "function" ? cb(...args2) : void 0;
2859
- }).catch(function(args2) {
2860
- return Array.isArray(args2) ? typeof cb == "function" ? cb(...args2) : void 0 : typeof cb == "function" ? cb(args2) : void 0;
2861
- }), this._receive(job);
2862
- }
2863
- schedule(...args) {
2864
- var job, options2, task;
2865
- if (typeof args[0] == "function") {
2866
- var _args = args, _args2 = _toArray(_args);
2867
- task = _args2[0], args = _args2.slice(1), options2 = {};
2868
- } else {
2869
- var _args3 = args, _args4 = _toArray(_args3);
2870
- options2 = _args4[0], task = _args4[1], args = _args4.slice(2);
2871
- }
2872
- return job = new Job(task, args, options2, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise), this._receive(job), job.promise;
2873
- }
2874
- wrap(fn) {
2875
- var schedule, wrapped;
2876
- return schedule = this.schedule.bind(this), wrapped = function(...args) {
2877
- return schedule(fn.bind(this), ...args);
2878
- }, wrapped.withOptions = function(options2, ...args) {
2879
- return schedule(options2, fn, ...args);
2880
- }, wrapped;
2881
- }
2882
- updateSettings(options2 = {}) {
2883
- var _this3 = this;
2884
- return _asyncToGenerator2(function* () {
2885
- return yield _this3._store.__updateSettings__(parser2.overwrite(options2, _this3.storeDefaults)), parser2.overwrite(options2, _this3.instanceDefaults, _this3), _this3;
2886
- })();
2887
- }
2888
- currentReservoir() {
2889
- return this._store.__currentReservoir__();
2890
- }
2891
- incrementReservoir(incr = 0) {
2892
- return this._store.__incrementReservoir__(incr);
2893
- }
2894
- }
2895
- return Bottleneck3.default = Bottleneck3, Bottleneck3.Events = Events2, Bottleneck3.version = Bottleneck3.prototype.version = require_version().version, Bottleneck3.strategy = Bottleneck3.prototype.strategy = {
2896
- LEAK: 1,
2897
- OVERFLOW: 2,
2898
- OVERFLOW_PRIORITY: 4,
2899
- BLOCK: 3
2900
- }, Bottleneck3.BottleneckError = Bottleneck3.prototype.BottleneckError = require_BottleneckError(), Bottleneck3.Group = Bottleneck3.prototype.Group = require_Group(), Bottleneck3.RedisConnection = Bottleneck3.prototype.RedisConnection = require_RedisConnection(), Bottleneck3.IORedisConnection = Bottleneck3.prototype.IORedisConnection = require_IORedisConnection(), Bottleneck3.Batcher = Bottleneck3.prototype.Batcher = require_Batcher(), Bottleneck3.prototype.jobDefaults = {
2901
- priority: DEFAULT_PRIORITY,
2902
- weight: 1,
2903
- expiration: null,
2904
- id: "<no-id>"
2905
- }, Bottleneck3.prototype.storeDefaults = {
2906
- maxConcurrent: null,
2907
- minTime: 0,
2908
- highWater: null,
2909
- strategy: Bottleneck3.prototype.strategy.LEAK,
2910
- penalty: null,
2911
- reservoir: null,
2912
- reservoirRefreshInterval: null,
2913
- reservoirRefreshAmount: null,
2914
- reservoirIncreaseInterval: null,
2915
- reservoirIncreaseAmount: null,
2916
- reservoirIncreaseMaximum: null
2917
- }, Bottleneck3.prototype.localStoreDefaults = {
2918
- Promise,
2919
- timeout: null,
2920
- heartbeatInterval: 250
2921
- }, Bottleneck3.prototype.redisStoreDefaults = {
2922
- Promise,
2923
- timeout: null,
2924
- heartbeatInterval: 5e3,
2925
- clientTimeout: 1e4,
2926
- Redis: null,
2927
- clientOptions: {},
2928
- clusterNodes: null,
2929
- clearDatastore: !1,
2930
- connection: null
2931
- }, Bottleneck3.prototype.instanceDefaults = {
2932
- datastore: "local",
2933
- connection: null,
2934
- id: "<no-id>",
2935
- rejectOnDrop: !0,
2936
- trackDoneStatus: !1,
2937
- Promise
2938
- }, Bottleneck3.prototype.stopDefaults = {
2939
- enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
2940
- dropWaitingJobs: !0,
2941
- dropErrorMessage: "This limiter has been stopped."
2942
- }, Bottleneck3;
2943
- }.call(void 0);
2944
- module2.exports = Bottleneck2;
2945
- }
2946
- });
2947
-
2948
- // ../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/index.js
2949
- var require_lib = __commonJS({
2950
- "../../node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/lib/index.js"(exports2, module2) {
2951
- "use strict";
2952
- init_cjs_shims();
2953
- module2.exports = require_Bottleneck();
2954
- }
2955
- });
2956
-
2957
- // ../cli-kit/dist/public/node/session.js
2958
- init_cjs_shims();
2959
-
2960
- // ../cli-kit/dist/public/node/context/fqdn.js
2961
- init_cjs_shims();
2962
- var CouldntObtainPartnersSpinFQDNError = new AbortError("Couldn't obtain the Spin FQDN for Partners when the CLI is not running from a Spin environment."), CouldntObtainIdentitySpinFQDNError = new AbortError("Couldn't obtain the Spin FQDN for Identity when the CLI is not running from a Spin environment."), CouldntObtainShopifySpinFQDNError = new AbortError("Couldn't obtain the Spin FQDN for Shopify when the CLI is not running from a Spin environment."), NotProvidedStoreFQDNError = new AbortError("Couldn't obtain the Shopify FQDN because the store FQDN was not provided.");
2963
- async function partnersFqdn() {
2964
- let environment = serviceEnvironment(), productionFqdn = "partners.shopify.com";
2965
- switch (environment) {
2966
- case "local":
2967
- return "partners.myshopify.io";
2968
- case "spin":
2969
- return `partners.${await spinFqdn()}`;
2970
- default:
2971
- return productionFqdn;
2972
- }
2973
- }
2974
- async function appManagementFqdn() {
2975
- let environment = serviceEnvironment(), productionFqdn = "app.shopify.com";
2976
- switch (environment) {
2977
- case "local":
2978
- return "app.shopify.myshopify.io";
2979
- case "spin":
2980
- return `app.shopify.${await spinFqdn()}`;
2981
- default:
2982
- return productionFqdn;
2983
- }
2984
- }
2985
- async function developerDashboardFqdn() {
2986
- let environment = serviceEnvironment(), productionFqdn = "dev.shopify.com";
2987
- switch (environment) {
2988
- case "local":
2989
- return "dev.shopify.myshopify.io";
2990
- case "spin":
2991
- return `dev.shopify.${await spinFqdn()}`;
2992
- default:
2993
- return productionFqdn;
2994
- }
2995
- }
2996
- async function businessPlatformFqdn() {
2997
- let environment = serviceEnvironment(), productionFqdn = "destinations.shopifysvc.com";
2998
- switch (environment) {
2999
- case "local":
3000
- return "business-platform.myshopify.io";
3001
- case "spin":
3002
- return `business-platform.${await spinFqdn()}`;
3003
- default:
3004
- return productionFqdn;
3005
- }
3006
- }
3007
- async function identityFqdn() {
3008
- let environment = serviceEnvironment(), productionFqdn = "accounts.shopify.com";
3009
- switch (environment) {
3010
- case "local":
3011
- return "identity.myshopify.io";
3012
- case "spin":
3013
- return `identity.${await spinFqdn()}`;
3014
- default:
3015
- return productionFqdn;
3016
- }
3017
- }
3018
- async function normalizeStoreFqdn(store2) {
3019
- let storeFqdn = store2.replace(/^https?:\/\//, "").replace(/\/$/, ""), addDomain = async (storeFqdn2) => {
3020
- switch (serviceEnvironment()) {
3021
- case "local":
3022
- return `${storeFqdn2}.myshopify.io`;
3023
- case "spin":
3024
- return `${storeFqdn2}.shopify.${await spinFqdn()}`;
3025
- default:
3026
- return `${storeFqdn2}.myshopify.com`;
3027
- }
3028
- };
3029
- return ((storeFqdn2) => storeFqdn2.includes(".myshopify.com") || storeFqdn2.includes("spin.dev") || storeFqdn2.includes("shopify.io"))(storeFqdn) ? storeFqdn : addDomain(storeFqdn);
3030
- }
3031
-
3032
- // ../cli-kit/dist/private/node/session/store.js
3033
- init_cjs_shims();
3034
-
3035
- // ../cli-kit/dist/private/node/session/schema.js
3036
- init_cjs_shims();
3037
- var DateSchema = z.preprocess((arg) => typeof arg == "string" || arg instanceof Date ? new Date(arg) : null, z.date()), IdentityTokenSchema = z.object({
3038
- accessToken: z.string(),
3039
- refreshToken: z.string(),
3040
- expiresAt: DateSchema,
3041
- scopes: z.array(z.string()),
3042
- userId: z.string()
3043
- }), ApplicationTokenSchema = z.object({
3044
- accessToken: z.string(),
3045
- expiresAt: DateSchema,
3046
- scopes: z.array(z.string())
3047
- }), SessionSchema = z.object({}).catchall(z.object({
3048
- /**
3049
- * It contains the identity token. Before usint it, we exchange it
3050
- * to get a token that we can use with different applications. The exchanged
3051
- * tokens for the applications are stored under applications.
3052
- */
3053
- identity: IdentityTokenSchema,
3054
- /**
3055
- * It contains exchanged tokens for the applications the CLI
3056
- * authenticates with. Tokens are scoped under the fqdn of the applications.
3057
- */
3058
- applications: z.object({}).catchall(ApplicationTokenSchema)
3059
- }));
3060
- function validateCachedIdentityTokenStructure(identityToken) {
3061
- return IdentityTokenSchema.safeParse(identityToken).success;
3062
- }
3063
-
3064
- // ../cli-kit/dist/private/node/session/store.js
3065
- async function store(session) {
3066
- let jsonSession = JSON.stringify(session);
3067
- setSession(jsonSession);
3068
- }
3069
- async function fetch() {
3070
- let content = getSession();
3071
- if (!content)
3072
- return;
3073
- let contentJson = JSON.parse(content), parsedSession = await SessionSchema.safeParseAsync(contentJson);
3074
- if (parsedSession.success)
3075
- return parsedSession.data;
3076
- await remove();
3077
- }
3078
- async function remove() {
3079
- removeSession();
3080
- }
3081
-
3082
- // ../cli-kit/dist/private/node/session/exchange.js
3083
- init_cjs_shims();
3084
-
3085
- // ../cli-kit/dist/private/node/session/identity.js
3086
- init_cjs_shims();
3087
- function clientId() {
3088
- let environment = serviceEnvironment();
3089
- return environment === Environment.Local ? "e5380e02-312a-7408-5718-e07017e9cf52" : environment === Environment.Production ? "fbdb2649-e327-4907-8f67-908d24cfd7e3" : "e5380e02-312a-7408-5718-e07017e9cf52";
3090
- }
3091
- function applicationId(api) {
3092
- switch (api) {
3093
- case "admin": {
3094
- let environment = serviceEnvironment();
3095
- return environment === Environment.Local ? "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52" : environment === Environment.Production ? "7ee65a63608843c577db8b23c4d7316ea0a01bd2f7594f8a9c06ea668c1b775c" : "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52";
3096
- }
3097
- case "partners": {
3098
- let environment = serviceEnvironment();
3099
- return environment === Environment.Local ? "df89d73339ac3c6c5f0a98d9ca93260763e384d51d6038da129889c308973978" : environment === Environment.Production ? "271e16d403dfa18082ffb3d197bd2b5f4479c3fc32736d69296829cbb28d41a6" : "df89d73339ac3c6c5f0a98d9ca93260763e384d51d6038da129889c308973978";
3100
- }
3101
- case "storefront-renderer": {
3102
- let environment = serviceEnvironment();
3103
- return environment === Environment.Local ? "46f603de-894f-488d-9471-5b721280ff49" : environment === Environment.Production ? "ee139b3d-5861-4d45-b387-1bc3ada7811c" : "46f603de-894f-488d-9471-5b721280ff49";
3104
- }
3105
- case "business-platform": {
3106
- let environment = serviceEnvironment();
3107
- return environment === Environment.Local ? "ace6dc89-b526-456d-a942-4b8ef6acda4b" : environment === Environment.Production ? "32ff8ee5-82b8-4d93-9f8a-c6997cefb7dc" : "ace6dc89-b526-456d-a942-4b8ef6acda4b";
3108
- }
3109
- case "app-management":
3110
- return serviceEnvironment() === Environment.Production ? "7ee65a63608843c577db8b23c4d7316ea0a01bd2f7594f8a9c06ea668c1b775c" : "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52";
3111
- default:
3112
- throw new BugError(`Application id for API of type: ${api}`);
3113
- }
3114
- }
3115
-
3116
- // ../cli-kit/dist/public/node/result.js
3117
- init_cjs_shims();
3118
- var ok = (value) => new Ok(value), err = (err2) => new Err(err2), Ok = class {
3119
- constructor(value) {
3120
- this.value = value;
3121
- }
3122
- /**
3123
- * Check if a `Result` is an `Err` inferring its type. `!isErr()` should be used before accessing the `value`
3124
- *
3125
- * @returns `false` as the `Resul` is `OK`
3126
- */
3127
- isErr() {
3128
- return !1;
3129
- }
3130
- /**
3131
- * Runs the `handler` method an return the same an unaltered copy of the `Result`. It could be used to log an
3132
- * output when the result is `Ok` without breaking the flow
3133
- *
3134
- * @param handler - method to be run when the result is `Ok`
3135
- * @returns a copy of the same `Result`
3136
- */
3137
- doOnOk(handler) {
3138
- return handler(this.value), ok(this.value);
3139
- }
3140
- /**
3141
- * A safe mode to throw the `error` of the `Result`
3142
- */
3143
- valueOrBug() {
3144
- return this.value;
3145
- }
3146
- /**
3147
- * Throws an abort error if the result doesn't represent a value.
3148
- */
3149
- valueOrAbort() {
3150
- return this.value;
3151
- }
3152
- /**
3153
- * Maps the value to another one with a different type. It leaves the `Error` type unaltered
3154
- *
3155
- * @param mapper - The mapper method to apply an `OK` value
3156
- * @returns a new result with the new mapped value
3157
- */
3158
- map(mapper) {
3159
- return ok(mapper(this.value));
3160
- }
3161
- /**
3162
- * Maps the error type to another one. It leaves the `Ok` type and value unaltered
3163
- *
3164
- * @param _mapper - This mapper method is not used for an `Ok` value
3165
- * @returns a new result with the new mapped error type and an value
3166
- */
3167
- mapError(_mapper) {
3168
- return ok(this.value);
3169
- }
3170
- }, Err = class {
3171
- // eslint-disable-next-line node/handle-callback-err
3172
- constructor(error) {
3173
- this.error = error;
3174
- }
3175
- /**
3176
- * Check if a `Result` is an `Err` inferring its type. `!isErr()` should be used before accessing the `value`
3177
- *
3178
- * @returns `false` as the `Resul` is `OK`
3179
- */
3180
- isErr() {
3181
- return !0;
3182
- }
3183
- /**
3184
- * Return an unaltered copy of the `Error` without doing anything.
3185
- *
3186
- * @param _handler - This handler method is not used for an `Error`
3187
- * @returns a copy of the same `Error`
3188
- */
3189
- doOnOk(_handler) {
3190
- return err(this.error);
3191
- }
3192
- /**
3193
- * A safe mode to throw the `error` of the `Result`
3194
- */
3195
- valueOrBug() {
3196
- throw this.error;
3197
- }
3198
- /**
3199
- * Throws an abort error if the result doesn't represent a value.
3200
- */
3201
- valueOrAbort() {
3202
- if (this.error instanceof FatalError)
3203
- throw this.error;
3204
- if (this.error instanceof import_ts_error.ExtendableError || this.error instanceof Error) {
3205
- let error = new AbortError(this.error.message);
3206
- throw error.stack = this.error.stack, error;
3207
- } else
3208
- throw new AbortError(`${this.error}`);
3209
- }
3210
- /**
3211
- * Maps the value type to another one. It leaves the `Error` unaltered
3212
- *
3213
- * @param _mapper - This mapper method is not used for an `Error` value
3214
- * @returns a new result with the new value type and an unaltered error
3215
- */
3216
- map(_mapper) {
3217
- return err(this.error);
3218
- }
3219
- /**
3220
- * Maps the error to another one with a different type. It leaves the value type unaltered
3221
- *
3222
- * @param mapper - The mapper method to apply an `Error` value
3223
- * @returns a new result with the new mapped error
3224
- */
3225
- mapError(mapper) {
3226
- return err(mapper(this.error));
3227
- }
3228
- };
3229
-
3230
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/index.js
3231
- init_cjs_shims();
3232
-
3233
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/runtime/base64url.js
3234
- init_cjs_shims();
3235
- import { Buffer } from "node:buffer";
3236
-
3237
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/lib/buffer_utils.js
3238
- init_cjs_shims();
3239
- var encoder = new TextEncoder(), decoder = new TextDecoder(), MAX_INT32 = 2 ** 32;
3240
-
3241
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/runtime/base64url.js
3242
- function normalize(input) {
3243
- let encoded = input;
3244
- return encoded instanceof Uint8Array && (encoded = decoder.decode(encoded)), encoded;
3245
- }
3246
- var decode = (input) => new Uint8Array(Buffer.from(normalize(input), "base64"));
3247
-
3248
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/util/errors.js
3249
- init_cjs_shims();
3250
- var JOSEError = class extends Error {
3251
- static get code() {
3252
- return "ERR_JOSE_GENERIC";
3253
- }
3254
- code = "ERR_JOSE_GENERIC";
3255
- constructor(message) {
3256
- super(message), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
3257
- }
3258
- };
3259
- var JWTInvalid = class extends JOSEError {
3260
- static get code() {
3261
- return "ERR_JWT_INVALID";
3262
- }
3263
- code = "ERR_JWT_INVALID";
3264
- };
3265
- var JWKSMultipleMatchingKeys = class extends JOSEError {
3266
- [Symbol.asyncIterator];
3267
- static get code() {
3268
- return "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
3269
- }
3270
- code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
3271
- message = "multiple matching keys found in the JSON Web Key Set";
3272
- };
3273
-
3274
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/lib/is_object.js
3275
- init_cjs_shims();
3276
- function isObjectLike(value) {
3277
- return typeof value == "object" && value !== null;
3278
- }
3279
- function isObject(input) {
3280
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]")
3281
- return !1;
3282
- if (Object.getPrototypeOf(input) === null)
3283
- return !0;
3284
- let proto = input;
3285
- for (; Object.getPrototypeOf(proto) !== null; )
3286
- proto = Object.getPrototypeOf(proto);
3287
- return Object.getPrototypeOf(input) === proto;
3288
- }
3289
-
3290
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/util/base64url.js
3291
- init_cjs_shims();
3292
- var decode2 = decode;
3293
-
3294
- // ../../node_modules/.pnpm/jose@5.8.0/node_modules/jose/dist/node/esm/util/decode_jwt.js
3295
- init_cjs_shims();
3296
- function decodeJwt(jwt) {
3297
- if (typeof jwt != "string")
3298
- throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
3299
- let { 1: payload, length } = jwt.split(".");
3300
- if (length === 5)
3301
- throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
3302
- if (length !== 3)
3303
- throw new JWTInvalid("Invalid JWT");
3304
- if (!payload)
3305
- throw new JWTInvalid("JWTs must contain a payload");
3306
- let decoded;
3307
- try {
3308
- decoded = decode2(payload);
3309
- } catch {
3310
- throw new JWTInvalid("Failed to base64url decode the payload");
3311
- }
3312
- let result;
3313
- try {
3314
- result = JSON.parse(decoder.decode(decoded));
3315
- } catch {
3316
- throw new JWTInvalid("Failed to parse the decoded payload as JSON");
3317
- }
3318
- if (!isObject(result))
3319
- throw new JWTInvalid("Invalid JWT Claims Set");
3320
- return result;
3321
- }
3322
-
3323
- // ../cli-kit/dist/private/node/session/exchange.js
3324
- var InvalidGrantError = class extends import_ts_error.ExtendableError {
3325
- }, InvalidRequestError = class extends import_ts_error.ExtendableError {
3326
- }, InvalidTargetError = class extends AbortError {
3327
- };
3328
- async function exchangeCodeForAccessToken(codeData) {
3329
- let clientId2 = await clientId(), params = {
3330
- grant_type: "authorization_code",
3331
- code: codeData.code,
3332
- redirect_uri: "http://127.0.0.1:3456",
3333
- client_id: clientId2,
3334
- code_verifier: codeData.codeVerifier
3335
- }, value = (await tokenRequest(params)).mapError(tokenRequestErrorHandler).valueOrBug();
3336
- return buildIdentityToken(value);
3337
- }
3338
- async function exchangeAccessForApplicationTokens(identityToken, scopes, store2) {
3339
- let token = identityToken.accessToken, appManagementEnabled = isTruthy(process.env.USE_APP_MANAGEMENT_API), [partners, storefront, businessPlatform, admin, appManagement] = await Promise.all([
3340
- requestAppToken("partners", token, scopes.partners),
3341
- requestAppToken("storefront-renderer", token, scopes.storefront),
3342
- requestAppToken("business-platform", token, scopes.businessPlatform),
3343
- store2 ? requestAppToken("admin", token, scopes.admin, store2) : {},
3344
- appManagementEnabled ? requestAppToken("app-management", token, scopes.appManagement) : {}
3345
- ]);
3346
- return {
3347
- ...partners,
3348
- ...storefront,
3349
- ...businessPlatform,
3350
- ...admin,
3351
- ...appManagement
3352
- };
3353
- }
3354
- async function refreshAccessToken(currentToken) {
3355
- let clientId2 = clientId(), params = {
3356
- grant_type: "refresh_token",
3357
- access_token: currentToken.accessToken,
3358
- refresh_token: currentToken.refreshToken,
3359
- client_id: clientId2
3360
- }, value = (await tokenRequest(params)).mapError(tokenRequestErrorHandler).valueOrBug();
3361
- return buildIdentityToken(value, currentToken.userId);
3362
- }
3363
- async function exchangeCustomPartnerToken(token) {
3364
- let appId = applicationId("partners");
3365
- try {
3366
- return (await requestAppToken("partners", token, ["https://api.shopify.com/auth/partners.app.cli.access"]))[appId];
3367
- } catch {
3368
- throw new AbortError("The custom token provided is invalid.", "Ensure the token is correct and not expired.");
3369
- }
3370
- }
3371
- async function exchangeDeviceCodeForAccessToken(deviceCode) {
3372
- let clientId2 = await clientId(), tokenResult = await tokenRequest({
3373
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
3374
- device_code: deviceCode,
3375
- client_id: clientId2
3376
- });
3377
- if (tokenResult.isErr())
3378
- return err(tokenResult.error);
3379
- let identityToken = buildIdentityToken(tokenResult.value);
3380
- return ok(identityToken);
3381
- }
3382
- async function requestAppToken(api, token, scopes = [], store2) {
3383
- let appId = applicationId(api), params = {
3384
- grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
3385
- requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
3386
- subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
3387
- client_id: await clientId(),
3388
- audience: appId,
3389
- scope: scopes.join(" "),
3390
- subject_token: token,
3391
- ...api === "admin" && { destination: `https://${store2}/admin` }
3392
- }, identifier = appId;
3393
- api === "admin" && store2 && (identifier = `${store2}-${appId}`);
3394
- let value = (await tokenRequest(params)).mapError(tokenRequestErrorHandler).valueOrBug(), appToken = buildApplicationToken(value);
3395
- return { [identifier]: appToken };
3396
- }
3397
- function tokenRequestErrorHandler(error) {
3398
- let invalidTargetErrorMessage = `You are not authorized to use the CLI to develop in the provided store.
3399
-
3400
- You can't use Shopify CLI with development stores if you only have Partner staff member access. If you want to use Shopify CLI to work on a development store, then you should be the store owner or create a staff account on the store.
3401
-
3402
- If you're the store owner, then you need to log in to the store directly using the store URL at least once before you log in using Shopify CLI.Logging in to the Shopify admin directly connects the development store with your Shopify login.`;
3403
- return error === "invalid_grant" ? new InvalidGrantError() : error === "invalid_request" ? new InvalidRequestError() : error === "invalid_target" ? new InvalidTargetError(invalidTargetErrorMessage) : new AbortError(error);
3404
- }
3405
- async function tokenRequest(params) {
3406
- let fqdn = await identityFqdn(), url2 = new URL(`https://${fqdn}/oauth/token`);
3407
- url2.search = new URLSearchParams(Object.entries(params)).toString();
3408
- let res = await shopifyFetch(url2.href, { method: "POST" }), payload = await res.json();
3409
- return res.ok ? ok(payload) : err(payload.error);
3410
- }
3411
- function buildIdentityToken(result, existingUserId) {
3412
- let userId = existingUserId ?? (result.id_token ? decodeJwt(result.id_token).sub : void 0);
3413
- if (!userId)
3414
- throw new BugError("Error setting userId for session. No id_token or pre-existing user ID provided.");
3415
- return {
3416
- accessToken: result.access_token,
3417
- refreshToken: result.refresh_token,
3418
- expiresAt: new Date(Date.now() + result.expires_in * 1e3),
3419
- scopes: result.scope.split(" "),
3420
- userId
3421
- };
3422
- }
3423
- function buildApplicationToken(result) {
3424
- return {
3425
- accessToken: result.access_token,
3426
- expiresAt: new Date(Date.now() + result.expires_in * 1e3),
3427
- scopes: result.scope.split(" ")
3428
- };
3429
- }
3430
-
3431
- // ../cli-kit/dist/private/node/session.js
3432
- init_cjs_shims();
3433
-
3434
- // ../cli-kit/dist/private/node/session/validate.js
3435
- init_cjs_shims();
3436
-
3437
- // ../cli-kit/dist/private/node/session/identity-token-validation.js
3438
- init_cjs_shims();
3439
- async function validateIdentityToken(token) {
3440
- if (isSpin() && firstPartyDev())
3441
- return !0;
3442
- try {
3443
- return withIntrospectionURL(async (introspectionURL) => {
3444
- let options2 = {
3445
- method: "POST",
3446
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
3447
- body: JSON.stringify({ token })
3448
- };
3449
- outputDebug(`Sending Identity Introspection request to URL: ${introspectionURL}`);
3450
- let response = await shopifyFetch(introspectionURL, options2);
3451
- if (response.ok && response.headers.get("content-type")?.includes("json")) {
3452
- let json = await response.json();
3453
- return outputDebug(`The identity token is valid: ${json.valid}`), ok(json.valid);
3454
- } else {
3455
- if (response.status === 404 || response.status > 500)
3456
- return err(new AbortError(`The introspection endpoint returned a ${response.status}: ${introspectionURL}`));
3457
- {
3458
- let text = await response.text();
3459
- return outputDebug(`The Introspection request failed with:
3460
- - status: ${response.status}
3461
- - www-authenticate header: ${JSON.stringify(response.headers.get("www-authenticate"))}
3462
- - body: ${JSON.stringify(text)}`), ok(!1);
3463
- }
3464
- }
3465
- });
3466
- } catch (error) {
3467
- return outputDebug(`The identity token is invalid: ${error}`), !1;
3468
- }
3469
- }
3470
- async function withIntrospectionURL(fn) {
3471
- let cacheKey = `identity-introspection-url-${await identityFqdn()}`, introspectionURL = await cacheRetrieveOrRepopulate(cacheKey, getIntrospectionURL, 6048e5), result = await fn(introspectionURL);
3472
- if (result.isErr() && (introspectionURL = await cacheRetrieveOrRepopulate(cacheKey, getIntrospectionURL, 0), result = await fn(introspectionURL)), result.isErr())
3473
- throw result.error;
3474
- return result.value;
3475
- }
3476
- async function getIntrospectionURL() {
3477
- return (await (await shopifyFetch(`https://${await identityFqdn()}/.well-known/openid-configuration.json`)).json()).introspection_endpoint;
3478
- }
3479
-
3480
- // ../cli-kit/dist/private/node/session/validate.js
3481
- function validateScopes(requestedScopes, identity) {
3482
- let currentScopes = identity.scopes;
3483
- return firstPartyDev() !== currentScopes.includes("employee") ? !1 : requestedScopes.every((scope) => currentScopes.includes(scope));
3484
- }
3485
- async function validateSession(scopes, applications, session) {
3486
- if (!session)
3487
- return "needs_full_auth";
3488
- let scopesAreValid = validateScopes(scopes, session.identity), identityIsValid = await validateIdentityToken(session.identity.accessToken);
3489
- if (!scopesAreValid)
3490
- return "needs_full_auth";
3491
- let tokensAreExpired = isTokenExpired(session.identity);
3492
- if (applications.partnersApi) {
3493
- let appId = applicationId("partners"), token = session.applications[appId];
3494
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
3495
- }
3496
- if (applications.appManagementApi) {
3497
- let appId = applicationId("app-management"), token = session.applications[appId];
3498
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
3499
- }
3500
- if (applications.storefrontRendererApi) {
3501
- let appId = applicationId("storefront-renderer"), token = session.applications[appId];
3502
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
3503
- }
3504
- if (applications.adminApi) {
3505
- let appId = applicationId("admin"), realAppId = `${applications.adminApi.storeFqdn}-${appId}`, token = session.applications[realAppId];
3506
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
3507
- }
3508
- return outputDebug(`
3509
- The validation of the token for application/identity completed with the following results:
3510
- - It's expired: ${tokensAreExpired}
3511
- - It's invalid in identity: ${!identityIsValid}
3512
- `), validateCachedIdentityTokenStructure(session.identity) ? tokensAreExpired ? "needs_refresh" : identityIsValid ? "ok" : "needs_full_auth" : "needs_full_auth";
3513
- }
3514
- function isTokenExpired(token) {
3515
- return token ? token.expiresAt < expireThreshold() : !0;
3516
- }
3517
- function expireThreshold() {
3518
- return new Date(Date.now() + sessionConstants.expirationTimeMarginInMinutes * 60 * 1e3);
3519
- }
3520
-
3521
- // ../cli-kit/dist/private/node/session/scopes.js
3522
- init_cjs_shims();
3523
- function allDefaultScopes(extraScopes = [], systemEnvironment = process.env) {
3524
- let scopes = allAPIs.map((api) => defaultApiScopes(api, systemEnvironment)).flat();
3525
- return scopes = ["openid", ...scopes, ...extraScopes].map(scopeTransform), Array.from(new Set(scopes));
3526
- }
3527
- function apiScopes(api, extraScopes = [], systemEnvironment = process.env) {
3528
- let scopes = [...defaultApiScopes(api, systemEnvironment), ...extraScopes.map(scopeTransform)].map(scopeTransform);
3529
- return Array.from(new Set(scopes));
3530
- }
3531
- function defaultApiScopes(api, systemEnvironment = process.env) {
3532
- switch (api) {
3533
- case "admin":
3534
- return ["graphql", "themes", "collaborator"];
3535
- case "storefront-renderer":
3536
- return ["devtools"];
3537
- case "partners":
3538
- return ["cli"];
3539
- case "business-platform":
3540
- return isTruthy(systemEnvironment.USE_APP_MANAGEMENT_API) ? ["destinations", "store-management"] : ["destinations"];
3541
- case "app-management":
3542
- return isTruthy(systemEnvironment.USE_APP_MANAGEMENT_API) ? ["app-management"] : [];
3543
- default:
3544
- throw new BugError(`Unknown API: ${api}`);
3545
- }
3546
- }
3547
- function scopeTransform(scope) {
3548
- switch (scope) {
3549
- case "graphql":
3550
- return "https://api.shopify.com/auth/shop.admin.graphql";
3551
- case "themes":
3552
- return "https://api.shopify.com/auth/shop.admin.themes";
3553
- case "collaborator":
3554
- return "https://api.shopify.com/auth/partners.collaborator-relationships.readonly";
3555
- case "cli":
3556
- return "https://api.shopify.com/auth/partners.app.cli.access";
3557
- case "devtools":
3558
- return "https://api.shopify.com/auth/shop.storefront-renderer.devtools";
3559
- case "destinations":
3560
- return "https://api.shopify.com/auth/destinations.readonly";
3561
- case "store-management":
3562
- return "https://api.shopify.com/auth/organization.store-management";
3563
- case "app-management":
3564
- return "https://api.shopify.com/auth/organization.apps.manage";
3565
- default:
3566
- return scope;
3567
- }
3568
- }
3569
-
3570
- // ../cli-kit/dist/private/node/session/authorize.js
3571
- init_cjs_shims();
3572
-
3573
- // ../cli-kit/dist/private/node/session/redirect-listener.js
3574
- init_cjs_shims();
3575
-
3576
- // ../cli-kit/dist/private/node/session/post-auth.js
3577
- init_cjs_shims();
3578
- var HTMLFileNames = [
3579
- "empty-url.html",
3580
- "auth-error.html",
3581
- "missing-code.html",
3582
- "missing-state.html",
3583
- "success.html"
3584
- ], StylesheetFilename = "style.css", FaviconFileName = "favicon.svg", getFilePath = async (fileName) => {
3585
- let filePath = await findPathUp(`assets/${fileName}`, {
3586
- type: "file",
3587
- cwd: moduleDirectory(import.meta.url)
3588
- });
3589
- if (!filePath)
3590
- throw RedirectPageAssetNotFoundError();
3591
- return filePath;
3592
- }, getEmptyUrlHTML = async () => {
3593
- let filePath = await getFilePath(HTMLFileNames[0]);
3594
- return readFile(filePath);
3595
- }, getAuthErrorHTML = async () => {
3596
- let filePath = await getFilePath(HTMLFileNames[1]);
3597
- return readFile(filePath);
3598
- }, getMissingCodeHTML = async () => {
3599
- let filePath = await getFilePath(HTMLFileNames[2]);
3600
- return readFile(filePath);
3601
- }, getMissingStateHTML = async () => {
3602
- let filePath = await getFilePath(HTMLFileNames[3]);
3603
- return readFile(filePath);
3604
- }, getSuccessHTML = async () => {
3605
- let filePath = await getFilePath(HTMLFileNames[4]);
3606
- return readFile(filePath);
3607
- }, getStylesheet = async () => {
3608
- let filePath = await getFilePath(StylesheetFilename);
3609
- return readFile(filePath);
3610
- }, getFavicon = async () => {
3611
- let filePath = await getFilePath(FaviconFileName);
3612
- return readFile(filePath);
3613
- }, EmptyUrlString = "We received the authentication redirect but the URL is empty.", MissingCodeString = "The authentication can't continue because the redirect doesn't include the code.", MissingStateString = "The authentication can't continue because the redirect doesn't include the state.", RedirectPageAssetNotFoundError = () => new BugError("Redirect page asset not found");
3614
-
3615
- // ../cli-kit/dist/private/node/session/redirect-listener.js
3616
- import url from "url";
3617
- import { createServer } from "http";
3618
- var ResponseTimeoutSeconds = 10, ServerStopDelaySeconds = 0.5, RedirectListener = class _RedirectListener {
3619
- static createServer(callback) {
3620
- return createServer(async (request, response) => {
3621
- let requestUrl = request.url;
3622
- if (requestUrl?.includes("favicon")) {
3623
- let faviconFile = await getFavicon();
3624
- return response.setHeader("Content-Type", "image/svg+xml"), response.write(faviconFile), response.end(), {};
3625
- } else if (requestUrl === "/style.css") {
3626
- let stylesheetFile = await getStylesheet();
3627
- return response.setHeader("Content-Type", "text/css"), response.write(stylesheetFile), response.end(), {};
3628
- }
3629
- let respond = async (contents, error, state, code) => (response.setHeader("Content-Type", "text/html"), response.write(contents), response.end(), callback(error, state, code), {});
3630
- if (!requestUrl) {
3631
- let file2 = await getEmptyUrlHTML(), err2 = new BugError(EmptyUrlString);
3632
- return respond(file2, err2, void 0, void 0);
3633
- }
3634
- let queryObject = url.parse(requestUrl, !0).query;
3635
- if (queryObject.error && queryObject.error_description) {
3636
- let file2 = await getAuthErrorHTML(), err2 = new AbortError(`${queryObject.error_description}`);
3637
- return respond(file2, err2, void 0, void 0);
3638
- }
3639
- if (!queryObject.code) {
3640
- let file2 = await getMissingCodeHTML(), err2 = new BugError(MissingCodeString);
3641
- return respond(file2, err2, void 0, void 0);
3642
- }
3643
- if (!queryObject.state) {
3644
- let file2 = await getMissingStateHTML(), err2 = new BugError(MissingStateString);
3645
- return respond(file2, err2, void 0, void 0);
3646
- }
3647
- let file = await getSuccessHTML();
3648
- return respond(file, void 0, `${queryObject.code}`, `${queryObject.state}`);
3649
- });
3650
- }
3651
- constructor(options2) {
3652
- this.port = options2.port, this.host = options2.host, this.server = _RedirectListener.createServer(options2.callback);
3653
- }
3654
- start() {
3655
- this.server.listen({ port: this.port, host: this.host }, () => {
3656
- });
3657
- }
3658
- async stop() {
3659
- await this.server.close();
3660
- }
3661
- };
3662
- async function listenRedirect(host, port, url2) {
3663
- return await new Promise((resolve, reject) => {
3664
- let timeout = setTimeout(() => {
3665
- outputInfo(outputContent`${`
3666
- Auto-open timed out. Open the login page: `}${outputToken.link("Log in to Shopify Partners", url2)}\n`);
3667
- }, ResponseTimeoutSeconds * 1e3), callback = (error, code, state) => {
3668
- clearTimeout(timeout), setTimeout(() => {
3669
- redirectListener.stop(), error ? reject(error) : resolve({ code, state });
3670
- }, ServerStopDelaySeconds * 1e3);
3671
- }, redirectListener = new RedirectListener({ host, port, callback });
3672
- redirectListener.start();
3673
- });
3674
- }
3675
-
3676
- // ../../node_modules/.pnpm/get-port-please@3.0.1/node_modules/get-port-please/dist/index.mjs
3677
- init_cjs_shims();
3678
- import { createServer as createServer2 } from "node:net";
3679
- import { networkInterfaces } from "node:os";
3680
- var unsafePorts = /* @__PURE__ */ new Set([
3681
- 1,
3682
- 7,
3683
- 9,
3684
- 11,
3685
- 13,
3686
- 15,
3687
- 17,
3688
- 19,
3689
- 20,
3690
- 21,
3691
- 22,
3692
- 23,
3693
- 25,
3694
- 37,
3695
- 42,
3696
- 43,
3697
- 53,
3698
- 69,
3699
- 77,
3700
- 79,
3701
- 87,
3702
- 95,
3703
- 101,
3704
- 102,
3705
- 103,
3706
- 104,
3707
- 109,
3708
- 110,
3709
- 111,
3710
- 113,
3711
- 115,
3712
- 117,
3713
- 119,
3714
- 123,
3715
- 135,
3716
- 137,
3717
- 139,
3718
- 143,
3719
- 161,
3720
- 179,
3721
- 389,
3722
- 427,
3723
- 465,
3724
- 512,
3725
- 513,
3726
- 514,
3727
- 515,
3728
- 526,
3729
- 530,
3730
- 531,
3731
- 532,
3732
- 540,
3733
- 548,
3734
- 554,
3735
- 556,
3736
- 563,
3737
- 587,
3738
- 601,
3739
- 636,
3740
- 989,
3741
- 990,
3742
- 993,
3743
- 995,
3744
- 1719,
3745
- 1720,
3746
- 1723,
3747
- 2049,
3748
- 3659,
3749
- 4045,
3750
- 5060,
3751
- 5061,
3752
- 6e3,
3753
- 6566,
3754
- 6665,
3755
- 6666,
3756
- 6667,
3757
- 6668,
3758
- 6669,
3759
- 6697,
3760
- 10080
3761
- ]);
3762
- function isUnsafePort(port) {
3763
- return unsafePorts.has(port);
3764
- }
3765
- function isSafePort(port) {
3766
- return !isUnsafePort(port);
3767
- }
3768
- function log(...arguments_) {
3769
- console.log("[get-port]", ...arguments_);
3770
- }
3771
- async function getRandomPort(host) {
3772
- let port = await checkPort(0, host);
3773
- if (port === !1)
3774
- throw new Error("Unable to obtain an available random port number!");
3775
- return port;
3776
- }
3777
- async function checkPort(port, host = process.env.HOST, _verbose) {
3778
- if (host || (host = getLocalHosts([void 0, "0.0.0.0"])), !Array.isArray(host))
3779
- return _checkPort(port, host);
3780
- for (let _host of host) {
3781
- let _port = await _checkPort(port, _host);
3782
- if (_port === !1)
3783
- return port < 1024 && _verbose && log("Unable to listen to priviliged port:", `${_host}:${port}`), !1;
3784
- port === 0 && _port !== 0 && (port = _port);
3785
- }
3786
- return port;
3787
- }
3788
- function _checkPort(port, host) {
3789
- return new Promise((resolve) => {
3790
- let server = createServer2();
3791
- server.unref(), server.on("error", (error) => {
3792
- error.code === "EINVAL" || error.code === "EADDRNOTAVAIL" ? resolve(port !== 0 && isSafePort(port) && port) : resolve(!1);
3793
- }), server.listen({ port, host }, () => {
3794
- let { port: port2 } = server.address();
3795
- server.close(() => {
3796
- resolve(isSafePort(port2) && port2);
3797
- });
3798
- });
3799
- });
3800
- }
3801
- function getLocalHosts(additional) {
3802
- let hosts = new Set(additional);
3803
- for (let _interface of Object.values(networkInterfaces()))
3804
- for (let config of _interface || [])
3805
- hosts.add(config.address);
3806
- return [...hosts];
3807
- }
3808
-
3809
- // ../cli-kit/dist/private/node/session/authorize.js
3810
- var import_find_process = __toESM(require_find_process2(), 1);
3811
- async function authorize(scopes, state = randomHex(30)) {
3812
- let host = "127.0.0.1", redirectUri = `http://${host}:3456`, fqdn = await identityFqdn(), identityClientId = clientId();
3813
- await validateRedirectionPortAvailability(3456);
3814
- let url2 = `http://${fqdn}/oauth/authorize`, { codeVerifier, codeChallenge } = generateRandomChallengePair(), params = {
3815
- client_id: identityClientId,
3816
- scope: scopes.join(" "),
3817
- redirect_uri: redirectUri,
3818
- state,
3819
- response_type: "code",
3820
- code_challenge_method: "S256",
3821
- code_challenge: codeChallenge
3822
- };
3823
- return outputInfo(`
3824
- To run this command, log in to Shopify.`), outputInfo("\u{1F449} Press any key to open the login page on your browser"), await keypress(), url2 = `${url2}?${new URLSearchParams(params).toString()}`, await openURL(url2), runWithTimer("cmd_all_timing_prompts_ms")(async () => {
3825
- let result = await listenRedirect(host, 3456, url2);
3826
- if (result.state !== state)
3827
- throw new AbortError("The state received from the authentication doesn't match the one that initiated the authentication process.");
3828
- return { code: result.code, codeVerifier };
3829
- });
3830
- }
3831
- function generateRandomChallengePair() {
3832
- let codeVerifier = base64URLEncode(randomBytes(32)), codeChallenge = base64URLEncode(sha256(codeVerifier));
3833
- return { codeVerifier, codeChallenge };
3834
- }
3835
- async function validateRedirectionPortAvailability(port) {
3836
- let { killPortProcess } = await import("./lib-H3ZZGS7I.js");
3837
- if (!await checkPort(port))
3838
- if (await terminateBlockingPortProcessPrompt(port, "Authentication"))
3839
- await killPortProcess(port);
3840
- else
3841
- throw new CancelExecution();
3842
- }
3843
- async function terminateBlockingPortProcessPrompt(port, stepDescription) {
3844
- let processInfo = await (0, import_find_process.default)("port", port), formattedProcessName = processInfo && processInfo.length > 0 && processInfo[0]?.name ? ` (${processInfo[0].name})` : "";
3845
- return renderConfirmationPrompt({
3846
- message: `${stepDescription} requires a port ${port} that's unavailable because it's running another process${formattedProcessName}. Terminate that process?`,
3847
- confirmationMessage: "Yes, terminate process in order to log in now",
3848
- cancellationMessage: "No, cancel command and try later"
3849
- });
3850
- }
3851
-
3852
- // ../cli-kit/dist/private/node/session/device-authorization.js
3853
- init_cjs_shims();
3854
- async function requestDeviceAuthorization(scopes) {
3855
- let fqdn = await identityFqdn(), queryParams = { client_id: clientId(), scope: scopes.join(" ") }, url2 = `https://${fqdn}/oauth/device_authorization`, jsonResult = await (await shopifyFetch(url2, {
3856
- method: "POST",
3857
- headers: { "Content-type": "application/x-www-form-urlencoded" },
3858
- body: convertRequestToParams(queryParams)
3859
- })).json();
3860
- if (outputDebug(outputContent`Received device authorization code: ${outputToken.json(jsonResult)}`), !jsonResult.device_code || !jsonResult.verification_uri_complete)
3861
- throw new BugError("Failed to start authorization process");
3862
- if (outputInfo(`
3863
- To run this command, log in to Shopify.`), !isTTY())
3864
- throw new AbortError("Authorization is required to continue, but the current environment does not support interactive prompts.", "To resolve this, specify credentials in your environment, or run the command in an interactive environment such as your local terminal.");
3865
- outputInfo(outputContent`User verification code: ${jsonResult.user_code}`);
3866
- let linkToken = outputToken.link(jsonResult.verification_uri_complete);
3867
- return isCloudEnvironment() ? outputInfo(outputContent`👉 Open this link to start the auth process: ${linkToken}`) : (outputInfo("\u{1F449} Press any key to open the login page on your browser"), await keypress(), await openURL(jsonResult.verification_uri_complete), outputInfo(outputContent`Opened link to start the auth process: ${linkToken}`)), {
3868
- deviceCode: jsonResult.device_code,
3869
- userCode: jsonResult.user_code,
3870
- verificationUri: jsonResult.verification_uri,
3871
- expiresIn: jsonResult.expires_in,
3872
- verificationUriComplete: jsonResult.verification_uri_complete,
3873
- interval: jsonResult.interval
3874
- };
3875
- }
3876
- async function pollForDeviceAuthorization(code, interval = 5) {
3877
- let currentIntervalInSeconds = interval;
3878
- return new Promise((resolve, reject) => {
3879
- let onPoll = async () => {
3880
- let result = await exchangeDeviceCodeForAccessToken(code);
3881
- if (!result.isErr())
3882
- return resolve(result.value);
3883
- let error = result.error ?? "unknown_failure";
3884
- switch (outputDebug(outputContent`Polling for device authorization... status: ${error}`), error) {
3885
- case "authorization_pending":
3886
- return startPolling();
3887
- case "slow_down":
3888
- return currentIntervalInSeconds += 5, startPolling();
3889
- case "access_denied":
3890
- case "expired_token":
3891
- case "unknown_failure":
3892
- return reject(result);
3893
- }
3894
- }, startPolling = () => {
3895
- setTimeout(onPoll, currentIntervalInSeconds * 1e3);
3896
- };
3897
- startPolling();
3898
- });
3899
- }
3900
- function convertRequestToParams(queryParams) {
3901
- return Object.entries(queryParams).map(([key, value]) => value && `${key}=${value}`).filter((hasValue) => !!hasValue).join("&");
3902
- }
3903
-
3904
- // ../cli-kit/dist/public/node/api/partners.js
3905
- init_cjs_shims();
3906
-
3907
- // ../cli-kit/dist/public/node/api/graphql.js
3908
- init_cjs_shims();
3909
-
3910
- // ../cli-kit/dist/private/node/api/graphql.js
3911
- init_cjs_shims();
3912
- function debugLogRequestInfo(api, query, variables, headers = {}) {
3913
- outputDebug(outputContent`Sending ${outputToken.json(api)} GraphQL request:
3914
- ${outputToken.raw(query.toString().trim())}
3915
- ${variables ? `
3916
- With variables:
3917
- ${sanitizeVariables(variables)}
3918
- ` : ""}
3919
- With request headers:
3920
- ${sanitizedHeadersOutput(headers)}
3921
- `);
3922
- }
3923
- function sanitizeVariables(variables) {
3924
- let result = { ...variables };
3925
- return "apiKey" in result && (result.apiKey = "*****"), JSON.stringify(result, null, 2);
3926
- }
3927
- function errorHandler(api) {
3928
- return (error, requestId) => {
3929
- if (error instanceof ClientError) {
3930
- let { status } = error.response, errorMessage = stringifyMessage(outputContent`
3931
- The ${outputToken.raw(api)} GraphQL API responded unsuccessfully with${status === 200 ? "" : ` the HTTP status ${status} and`} errors:
3932
-
3933
- ${outputToken.json(error.response.errors)}
3934
- `);
3935
- requestId && (errorMessage += `
3936
- Request ID: ${requestId}
3937
- `);
3938
- let mappedError;
3939
- return status < 500 ? mappedError = new GraphQLClientError(errorMessage, status, error.response.errors) : mappedError = new AbortError(errorMessage), mappedError.stack = error.stack, mappedError;
3940
- } else
3941
- return error;
3942
- };
3943
- }
3944
-
3945
- // ../cli-kit/dist/public/node/api/graphql.js
3946
- async function performGraphQLRequest(options2) {
3947
- let { token, addedHeaders, queryAsString, variables, api, url: url2, responseOptions } = options2, headers = {
3948
- ...addedHeaders,
3949
- ...buildHeaders(token)
3950
- };
3951
- debugLogRequestInfo(api, queryAsString, variables, headers);
3952
- let clientOptions = { agent: await httpsAgent(), headers }, client = new GraphQLClient(url2, clientOptions);
3953
- return runWithTimer("cmd_all_timing_network_ms")(async () => {
3954
- let response = await retryAwareRequest({ request: () => client.rawRequest(queryAsString, variables), url: url2 }, responseOptions?.handleErrors === !1 ? void 0 : errorHandler(api));
3955
- return responseOptions?.onResponse && responseOptions.onResponse(response), response.data;
3956
- });
3957
- }
3958
- async function graphqlRequest(options2) {
3959
- return performGraphQLRequest({
3960
- ...options2,
3961
- queryAsString: options2.query
3962
- });
3963
- }
3964
- async function graphqlRequestDoc(options2) {
3965
- return performGraphQLRequest({
3966
- ...options2,
3967
- queryAsString: resolveRequestDocument(options2.query).query
3968
- });
3969
- }
3970
-
3971
- // ../cli-kit/dist/public/node/api/partners.js
3972
- var import_bottleneck = __toESM(require_lib(), 1), limiter = new import_bottleneck.default({
3973
- minTime: 150,
3974
- maxConcurrent: 10
3975
- });
3976
- async function setupRequest(token) {
3977
- let api = "Partners", url2 = `https://${await partnersFqdn()}/api/cli/graphql`;
3978
- return {
3979
- token,
3980
- api,
3981
- url: url2,
3982
- responseOptions: { onResponse: handleDeprecations }
3983
- };
3984
- }
3985
- async function partnersRequest(query, token, variables) {
3986
- let opts = await setupRequest(token);
3987
- return limiter.schedule(() => graphqlRequest({
3988
- ...opts,
3989
- query,
3990
- variables
3991
- }));
3992
- }
3993
- async function partnersRequestDoc(query, token, variables) {
3994
- let opts = await setupRequest(token);
3995
- return limiter.schedule(() => graphqlRequestDoc({
3996
- ...opts,
3997
- query,
3998
- variables
3999
- }));
4000
- }
4001
- function handleDeprecations(response) {
4002
- if (!response.extensions)
4003
- return;
4004
- let deprecationDates = [];
4005
- for (let deprecation of response.extensions.deprecations)
4006
- deprecation.supportedUntilDate && deprecationDates.push(new Date(deprecation.supportedUntilDate));
4007
- setNextDeprecationDate(deprecationDates);
4008
- }
4009
-
4010
- // ../cli-kit/dist/private/node/session.js
4011
- async function ensureAuthenticated(applications, _env, { forceRefresh = !1, noPrompt = !1 } = {}) {
4012
- let fqdn = await identityFqdn(), previousStoreFqdn = applications.adminApi?.storeFqdn;
4013
- if (previousStoreFqdn) {
4014
- let normalizedStoreName = await normalizeStoreFqdn(previousStoreFqdn);
4015
- previousStoreFqdn === applications.adminApi?.storeFqdn && (applications.adminApi.storeFqdn = normalizedStoreName);
4016
- }
4017
- let currentSession = await fetch() || {}, fqdnSession = currentSession[fqdn], scopes = getFlattenScopes(applications);
4018
- outputDebug(outputContent`Validating existing session against the scopes:
4019
- ${outputToken.json(scopes)}
4020
- For applications:
4021
- ${outputToken.json(applications)}
4022
- `);
4023
- let validationResult = await validateSession(scopes, applications, fqdnSession), newSession = {};
4024
- function throwOnNoPrompt() {
4025
- if (!(!noPrompt || isSpin() && firstPartyDev()))
4026
- throw new AbortError(`The currently available CLI credentials are invalid.
4027
-
4028
- The CLI is currently unable to prompt for reauthentication.`, "Restart the CLI process you were running. If in an interactive terminal, you will be prompted to reauthenticate. If in a non-interactive terminal, ensure the correct credentials are available in the program environment.");
4029
- }
4030
- if (validationResult === "needs_full_auth")
4031
- throwOnNoPrompt(), outputDebug(outputContent`Initiating the full authentication flow...`), newSession = await executeCompleteFlow(applications, fqdn);
4032
- else if (validationResult === "needs_refresh" || forceRefresh) {
4033
- outputDebug(outputContent`The current session is valid but needs refresh. Refreshing...`);
4034
- try {
4035
- newSession = await refreshTokens(fqdnSession.identity, applications, fqdn);
4036
- } catch (error) {
4037
- if (error instanceof InvalidGrantError)
4038
- throwOnNoPrompt(), newSession = await executeCompleteFlow(applications, fqdn);
4039
- else
4040
- throw error instanceof InvalidRequestError ? (await remove(), new AbortError(`
4041
- Error validating auth session`, "We've cleared the current session, please try again")) : error;
4042
- }
4043
- }
4044
- let completeSession = { ...currentSession, ...newSession };
4045
- Object.keys(newSession).length > 0 && await store(completeSession);
4046
- let tokens = await tokensFor(applications, completeSession, fqdn), envToken = getPartnersToken();
4047
- return envToken && applications.partnersApi && (tokens.partners = (await exchangeCustomPartnerToken(envToken)).accessToken), !envToken && tokens.partners && await ensureUserHasPartnerAccount(tokens.partners, tokens.userId), tokens;
4048
- }
4049
- async function executeCompleteFlow(applications, identityFqdn2) {
4050
- let scopes = getFlattenScopes(applications), exchangeScopes = getExchangeScopes(applications), store2 = applications.adminApi?.storeFqdn;
4051
- firstPartyDev() && (outputDebug(outputContent`Authenticating as Shopify Employee...`), scopes.push("employee"));
4052
- let identityToken, identityTokenInformation = getIdentityTokenInformation();
4053
- if (identityTokenInformation)
4054
- identityToken = buildIdentityTokenFromEnv(scopes, identityTokenInformation);
4055
- else if (useDeviceAuth()) {
4056
- outputDebug(outputContent`Requesting device authorization code...`);
4057
- let deviceAuth = await requestDeviceAuthorization(scopes);
4058
- outputDebug(outputContent`Starting polling for the identity token...`), identityToken = await pollForDeviceAuthorization(deviceAuth.deviceCode, deviceAuth.interval);
4059
- } else {
4060
- outputDebug(outputContent`Authorizing through Identity's website...`);
4061
- let code = await authorize(scopes);
4062
- outputDebug(outputContent`Authorization code received. Exchanging it for a CLI token...`), identityToken = await exchangeCodeForAccessToken(code);
4063
- }
4064
- outputDebug(outputContent`CLI token received. Exchanging it for application tokens...`);
4065
- let result = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, store2), session = {
4066
- [identityFqdn2]: {
4067
- identity: identityToken,
4068
- applications: result
4069
- }
4070
- };
4071
- return outputCompleted("Logged in."), session;
4072
- }
4073
- async function ensureUserHasPartnerAccount(partnersToken, userId) {
4074
- if (!isTruthy(process.env.USE_APP_MANAGEMENT_API) && (outputDebug(outputContent`Verifying that the user has a Partner organization`), !await hasPartnerAccount(partnersToken, userId) && (outputInfo(`
4075
- A Shopify Partners organization is needed to proceed.`), outputInfo("\u{1F449} Press any key to create one"), await keypress(), await openURL(`https://${await partnersFqdn()}/signup`), outputInfo(outputContent`👉 Press any key when you have ${outputToken.cyan("created the organization")}`), outputWarn(outputContent`Make sure you've confirmed your Shopify and the Partner organization from the email`), await keypress(), !await hasPartnerAccount(partnersToken, userId))))
4076
- throw new AbortError("Couldn't find your Shopify Partners organization", "Have you confirmed your accounts from the emails you received?");
4077
- }
4078
- var getFirstOrganization = gql`
4079
- {
4080
- organizations(first: 1) {
4081
- nodes {
4082
- id
4083
- }
4084
- }
4085
- }
4086
- `;
4087
- async function hasPartnerAccount(partnersToken, userId) {
4088
- let cacheKey = userId ?? partnersToken;
4089
- if (getCachedPartnerAccountStatus(cacheKey))
4090
- return outputDebug("Confirmed partner account exists from cache"), !0;
4091
- try {
4092
- return await partnersRequest(getFirstOrganization, partnersToken), setCachedPartnerAccountStatus(cacheKey), !0;
4093
- } catch (error) {
4094
- return !(error instanceof RequestClientError && error.statusCode === 404);
4095
- }
4096
- }
4097
- async function refreshTokens(token, applications, fqdn) {
4098
- let identityToken = await refreshAccessToken(token), exchangeScopes = getExchangeScopes(applications), applicationTokens = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, applications.adminApi?.storeFqdn);
4099
- return {
4100
- [fqdn]: {
4101
- identity: identityToken,
4102
- applications: applicationTokens
4103
- }
4104
- };
4105
- }
4106
- async function tokensFor(applications, session, fqdn) {
4107
- let fqdnSession = session[fqdn];
4108
- if (!fqdnSession)
4109
- throw new BugError("No session found after ensuring authenticated");
4110
- let tokens = {
4111
- userId: fqdnSession.identity.userId
4112
- };
4113
- if (applications.adminApi) {
4114
- let appId = applicationId("admin"), realAppId = `${applications.adminApi.storeFqdn}-${appId}`, token = fqdnSession.applications[realAppId]?.accessToken;
4115
- token && (tokens.admin = { token, storeFqdn: applications.adminApi.storeFqdn });
4116
- }
4117
- if (applications.partnersApi) {
4118
- let appId = applicationId("partners");
4119
- tokens.partners = fqdnSession.applications[appId]?.accessToken;
4120
- }
4121
- if (applications.storefrontRendererApi) {
4122
- let appId = applicationId("storefront-renderer");
4123
- tokens.storefront = fqdnSession.applications[appId]?.accessToken;
4124
- }
4125
- if (applications.businessPlatformApi) {
4126
- let appId = applicationId("business-platform");
4127
- tokens.businessPlatform = fqdnSession.applications[appId]?.accessToken;
4128
- }
4129
- if (applications.appManagementApi) {
4130
- let appId = applicationId("app-management");
4131
- tokens.appManagement = fqdnSession.applications[appId]?.accessToken;
4132
- }
4133
- return tokens;
4134
- }
4135
- function getFlattenScopes(apps) {
4136
- let admin = apps.adminApi?.scopes || [], partner = apps.partnersApi?.scopes || [], storefront = apps.storefrontRendererApi?.scopes || [], businessPlatform = apps.businessPlatformApi?.scopes || [], appManagement = apps.appManagementApi?.scopes || [], requestedScopes = [...admin, ...partner, ...storefront, ...businessPlatform, ...appManagement];
4137
- return allDefaultScopes(requestedScopes);
4138
- }
4139
- function getExchangeScopes(apps) {
4140
- let adminScope = apps.adminApi?.scopes || [], partnerScope = apps.partnersApi?.scopes || [], storefrontScopes = apps.storefrontRendererApi?.scopes || [], businessPlatformScopes = apps.businessPlatformApi?.scopes || [], appManagementScopes = apps.appManagementApi?.scopes || [];
4141
- return {
4142
- admin: apiScopes("admin", adminScope),
4143
- partners: apiScopes("partners", partnerScope),
4144
- storefront: apiScopes("storefront-renderer", storefrontScopes),
4145
- businessPlatform: apiScopes("business-platform", businessPlatformScopes),
4146
- appManagement: apiScopes("app-management", appManagementScopes)
4147
- };
4148
- }
4149
- function buildIdentityTokenFromEnv(scopes, identityTokenInformation) {
4150
- return {
4151
- ...identityTokenInformation,
4152
- expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3),
4153
- scopes
4154
- };
4155
- }
4156
-
4157
- // ../cli-kit/dist/public/node/session.js
4158
- async function ensureAuthenticatedPartners(scopes = [], env = process.env, options2 = {}) {
4159
- outputDebug(outputContent`Ensuring that the user is authenticated with the Partners API with the following scopes:
4160
- ${outputToken.json(scopes)}
4161
- `);
4162
- let envToken = getPartnersToken();
4163
- if (envToken)
4164
- return { token: (await exchangeCustomPartnerToken(envToken)).accessToken, userId: nonRandomUUID(envToken) };
4165
- let tokens = await ensureAuthenticated({ partnersApi: { scopes } }, env, options2);
4166
- if (!tokens.partners)
4167
- throw new BugError("No partners token found after ensuring authenticated");
4168
- return { token: tokens.partners, userId: tokens.userId };
4169
- }
4170
- async function ensureAuthenticatedAppManagement(scopes = [], env = process.env, options2 = {}) {
4171
- outputDebug(outputContent`Ensuring that the user is authenticated with the App Management API with the following scopes:
4172
- ${outputToken.json(scopes)}
4173
- `);
4174
- let tokens = await ensureAuthenticated({ appManagementApi: { scopes } }, env, options2);
4175
- if (!tokens)
4176
- throw new BugError("No App Management token found after ensuring authenticated");
4177
- return { token: tokens.appManagement, userId: tokens.userId };
4178
- }
4179
- async function ensureAuthenticatedStorefront(scopes = [], password = void 0, forceRefresh = !1) {
4180
- if (password)
4181
- return password;
4182
- outputDebug(outputContent`Ensuring that the user is authenticated with the Storefront API with the following scopes:
4183
- ${outputToken.json(scopes)}
4184
- `);
4185
- let tokens = await ensureAuthenticated({ storefrontRendererApi: { scopes } }, process.env, { forceRefresh });
4186
- if (!tokens.storefront)
4187
- throw new BugError("No storefront token found after ensuring authenticated");
4188
- return tokens.storefront;
4189
- }
4190
- async function ensureAuthenticatedAdmin(store2, scopes = [], forceRefresh = !1, options2 = {}) {
4191
- outputDebug(outputContent`Ensuring that the user is authenticated with the Admin API with the following scopes for the store ${outputToken.raw(store2)}:
4192
- ${outputToken.json(scopes)}
4193
- `);
4194
- let tokens = await ensureAuthenticated({ adminApi: { scopes, storeFqdn: store2 } }, process.env, {
4195
- forceRefresh,
4196
- ...options2
4197
- });
4198
- if (!tokens.admin)
4199
- throw new BugError("No admin token found after ensuring authenticated");
4200
- return tokens.admin;
4201
- }
4202
- async function ensureAuthenticatedThemes(store2, password, scopes = [], forceRefresh = !1) {
4203
- return outputDebug(outputContent`Ensuring that the user is authenticated with the Theme API with the following scopes:
4204
- ${outputToken.json(scopes)}
4205
- `), password ? { token: password, storeFqdn: await normalizeStoreFqdn(store2) } : ensureAuthenticatedAdmin(store2, scopes, forceRefresh);
4206
- }
4207
- async function ensureAuthenticatedBusinessPlatform(scopes = []) {
4208
- outputDebug(outputContent`Ensuring that the user is authenticated with the Business Platform API with the following scopes:
4209
- ${outputToken.json(scopes)}
4210
- `);
4211
- let tokens = await ensureAuthenticated({ businessPlatformApi: { scopes } }, process.env);
4212
- if (!tokens.businessPlatform)
4213
- throw new BugError("No business-platform token found after ensuring authenticated");
4214
- return tokens.businessPlatform;
4215
- }
4216
- function logout() {
4217
- return remove();
4218
- }
4219
-
4220
- export {
4221
- partnersFqdn,
4222
- appManagementFqdn,
4223
- developerDashboardFqdn,
4224
- businessPlatformFqdn,
4225
- normalizeStoreFqdn,
4226
- ok,
4227
- err,
4228
- getRandomPort,
4229
- checkPort,
4230
- graphqlRequest,
4231
- graphqlRequestDoc,
4232
- require_lib,
4233
- partnersRequest,
4234
- partnersRequestDoc,
4235
- handleDeprecations,
4236
- ensureAuthenticatedPartners,
4237
- ensureAuthenticatedAppManagement,
4238
- ensureAuthenticatedStorefront,
4239
- ensureAuthenticatedAdmin,
4240
- ensureAuthenticatedThemes,
4241
- ensureAuthenticatedBusinessPlatform,
4242
- logout
4243
- };
4244
- //# sourceMappingURL=chunk-EMJI2MUZ.js.map