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