@shopify/cli 3.63.2 → 3.64.1

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 (131) hide show
  1. package/dist/assets/cli-ruby/lib/shopify_cli/reporting_configuration_controller.rb +2 -37
  2. package/dist/assets/cli-ruby/lib/shopify_cli/theme/file.rb +5 -1
  3. package/dist/assets/dev-console/extensions/dev-console/assets/index-Cgb-oKsM.css +1 -0
  4. package/dist/assets/dev-console/extensions/dev-console/assets/{index-Dui3DO9f.js → index-D7F9wNys.js} +12 -12
  5. package/dist/assets/dev-console/index.html +2 -2
  6. package/dist/assets/hydrogen/starter/.graphqlrc.ts +27 -0
  7. package/dist/assets/hydrogen/starter/CHANGELOG.md +108 -6
  8. package/dist/assets/hydrogen/starter/app/components/AddToCartButton.tsx +37 -0
  9. package/dist/assets/hydrogen/starter/app/components/CartLineItem.tsx +150 -0
  10. package/dist/assets/hydrogen/starter/app/components/CartMain.tsx +68 -0
  11. package/dist/assets/hydrogen/starter/app/components/CartSummary.tsx +101 -0
  12. package/dist/assets/hydrogen/starter/app/components/Header.tsx +3 -3
  13. package/dist/assets/hydrogen/starter/app/components/PageLayout.tsx +2 -2
  14. package/dist/assets/hydrogen/starter/app/components/ProductForm.tsx +80 -0
  15. package/dist/assets/hydrogen/starter/app/components/ProductImage.tsx +23 -0
  16. package/dist/assets/hydrogen/starter/app/components/ProductPrice.tsx +27 -0
  17. package/dist/assets/hydrogen/starter/app/root.tsx +11 -17
  18. package/dist/assets/hydrogen/starter/app/routes/cart.tsx +1 -1
  19. package/dist/assets/hydrogen/starter/app/routes/products.$handle.tsx +51 -232
  20. package/dist/assets/hydrogen/starter/package.json +11 -11
  21. package/dist/assets/hydrogen/tailwind/package.json +1 -6
  22. package/dist/assets/hydrogen/tailwind/tailwind.css +6 -3
  23. package/dist/assets/hydrogen/vanilla-extract/package.json +2 -3
  24. package/dist/assets/hydrogen/virtual-routes/components/{Layout.jsx → PageLayout.jsx} +2 -2
  25. package/dist/assets/hydrogen/virtual-routes/virtual-root.jsx +8 -30
  26. package/dist/{chunk-YAYFJITA.js → chunk-2DXCIFDK.js} +3 -3
  27. package/dist/{chunk-EQR6CWKL.js → chunk-63D4EGTO.js} +3 -3
  28. package/dist/{chunk-EZYMDZPN.js → chunk-6PJAGL2L.js} +5 -5
  29. package/dist/{chunk-S4VBXFXP.js → chunk-7PVTYKQI.js} +220 -16
  30. package/dist/{chunk-IRWSC76I.js → chunk-7TIDA343.js} +3 -3
  31. package/dist/{chunk-NPLAQVTF.js → chunk-7W6SRTYP.js} +3 -3
  32. package/dist/{chunk-UJYIV6JP.js → chunk-ARCFCLME.js} +5 -5
  33. package/dist/{chunk-DIZHFZTJ.js → chunk-ATGUMSCJ.js} +4 -4
  34. package/dist/chunk-B3D5VLUA.js +12 -0
  35. package/dist/{chunk-UNPXLODI.js → chunk-B7RN7IRD.js} +3 -4
  36. package/dist/{chunk-5BLMIE7F.js → chunk-DX43V2L4.js} +4 -4
  37. package/dist/{chunk-6UDFXWNE.js → chunk-EJITPGUJ.js} +21 -4
  38. package/dist/chunk-FDLU3RD4.js +29 -0
  39. package/dist/{chunk-7OCUVNSF.js → chunk-H6AQTECB.js} +1485 -2977
  40. package/dist/{chunk-T54B5GJP.js → chunk-JNUJZFQL.js} +2 -2
  41. package/dist/{chunk-XER2L725.js → chunk-KUVX423E.js} +2 -2
  42. package/dist/{chunk-R5KML52V.js → chunk-KZTALMEV.js} +4 -4
  43. package/dist/{chunk-CM4H6QMH.js → chunk-M6KGRVDD.js} +3 -3
  44. package/dist/{chunk-3MDI6LZT.js → chunk-NLE3ZLU6.js} +905 -896
  45. package/dist/{chunk-WADS2TV5.js → chunk-NO7MYZEO.js} +5 -4
  46. package/dist/{chunk-LH533WG4.js → chunk-NPH2SXRO.js} +2 -2
  47. package/dist/{chunk-VZUWS5IH.js → chunk-OVWFZSJT.js} +3 -3
  48. package/dist/{chunk-UQUO22Q5.js → chunk-OXMHVKM3.js} +5 -5
  49. package/dist/{chunk-PNFEODLY.js → chunk-QNI6VLVR.js} +3 -3
  50. package/dist/{chunk-MCT2524Y.js → chunk-QYT42J3T.js} +4 -4
  51. package/dist/{chunk-VQTHQBEC.js → chunk-S3HWVIGJ.js} +9 -14
  52. package/dist/{chunk-23OKKZ5V.js → chunk-S7A7BHNA.js} +4 -4
  53. package/dist/{chunk-3TGMDPDI.js → chunk-SSAUIEBT.js} +2 -2
  54. package/dist/{chunk-YMPGWFWU.js → chunk-UQQI7TQG.js} +3 -3
  55. package/dist/{chunk-UZUD5DRI.js → chunk-UXA5YROL.js} +2 -2
  56. package/dist/{chunk-K3CVGV3F.js → chunk-V7NH4SZB.js} +3 -3
  57. package/dist/{chunk-7AVKIH7O.js → chunk-WVY52EEZ.js} +5 -5
  58. package/dist/{chunk-QEOBHRRQ.js → chunk-X3OUSYUQ.js} +17912 -17444
  59. package/dist/{chunk-EARPFFS7.js → chunk-XNCQBHNR.js} +241 -4
  60. package/dist/{chunk-EQPYUHNM.js → chunk-ZIGJPI5N.js} +1497 -112
  61. package/dist/{chunk-A2UVOX6O.js → chunk-ZKWHKX2C.js} +7066 -6051
  62. package/dist/{chunk-GPMHDCWK.js → chunk-ZRGD2HUL.js} +3 -3
  63. package/dist/{chunk-PQKGBYDC.js → chunk-ZVT2WZZF.js} +3 -3
  64. package/dist/cli/commands/auth/logout.js +14 -19
  65. package/dist/cli/commands/auth/logout.test.js +17 -21
  66. package/dist/cli/commands/debug/command-flags.js +11 -15
  67. package/dist/cli/commands/demo/catalog.js +13 -18
  68. package/dist/cli/commands/demo/generate-file.js +13 -18
  69. package/dist/cli/commands/demo/index.js +13 -18
  70. package/dist/cli/commands/demo/print-ai-prompt.js +13 -18
  71. package/dist/cli/commands/docs/generate.js +11 -15
  72. package/dist/cli/commands/docs/generate.test.js +11 -15
  73. package/dist/cli/commands/help.js +11 -15
  74. package/dist/cli/commands/kitchen-sink/async.js +12 -16
  75. package/dist/cli/commands/kitchen-sink/async.test.js +12 -16
  76. package/dist/cli/commands/kitchen-sink/index.js +14 -18
  77. package/dist/cli/commands/kitchen-sink/index.test.js +14 -18
  78. package/dist/cli/commands/kitchen-sink/prompts.js +12 -16
  79. package/dist/cli/commands/kitchen-sink/prompts.test.js +12 -16
  80. package/dist/cli/commands/kitchen-sink/static.js +12 -16
  81. package/dist/cli/commands/kitchen-sink/static.test.js +12 -16
  82. package/dist/cli/commands/search.js +12 -16
  83. package/dist/cli/commands/upgrade.js +11 -15
  84. package/dist/cli/commands/version.js +12 -16
  85. package/dist/cli/commands/version.test.js +12 -16
  86. package/dist/cli/services/commands/search.js +4 -4
  87. package/dist/cli/services/commands/search.test.js +4 -4
  88. package/dist/cli/services/commands/version.js +6 -7
  89. package/dist/cli/services/commands/version.test.js +7 -8
  90. package/dist/cli/services/demo.js +5 -6
  91. package/dist/cli/services/demo.test.js +5 -6
  92. package/dist/cli/services/kitchen-sink/async.js +4 -4
  93. package/dist/cli/services/kitchen-sink/prompts.js +4 -4
  94. package/dist/cli/services/kitchen-sink/static.js +4 -4
  95. package/dist/cli/services/upgrade.js +5 -6
  96. package/dist/cli/services/upgrade.test.js +7 -8
  97. package/dist/{constants-3CLHB4LQ.js → constants-EVER32LA.js} +3 -3
  98. package/dist/{custom-oclif-loader-D4H5EJW6.js → custom-oclif-loader-BQAFOUNG.js} +13 -6
  99. package/dist/{error-handler-HUI4HW3X.js → error-handler-S56KHSGD.js} +10 -8
  100. package/dist/hooks/postrun.js +12 -14
  101. package/dist/hooks/prerun.js +8 -11
  102. package/dist/index.js +7811 -7490
  103. package/dist/{local-7IRDZWLW.js → local-UQAQKOVL.js} +4 -4
  104. package/dist/{morph-6NYGHGNT.js → morph-DN4AZJZW.js} +9 -9
  105. package/dist/{node-UIH7JP3D.js → node-GZYZUMBW.js} +21 -19
  106. package/dist/{node-package-manager-2LWT2MNN.js → node-package-manager-AOVZD6TP.js} +5 -6
  107. package/dist/{path-JVVXOELJ.js → path-KUSF6CYC.js} +2 -2
  108. package/dist/{system-4HHX42JS.js → system-G7DVECOP.js} +4 -4
  109. package/dist/templates/ui-extensions/projects/web_pixel_extension/package.json.liquid +1 -1
  110. package/dist/tsconfig.tsbuildinfo +1 -1
  111. package/dist/{ui-NFBKMC4P.js → ui-2AOZFYFM.js} +4 -4
  112. package/dist/{workerd-4HFD3PS4.js → workerd-2MO23YDQ.js} +22 -19
  113. package/oclif.manifest.json +265 -4
  114. package/package.json +7 -10
  115. package/dist/assets/dev-console/extensions/dev-console/assets/index-Bi7y6lI5.css +0 -1
  116. package/dist/assets/hydrogen/css-modules/package.json +0 -6
  117. package/dist/assets/hydrogen/postcss/package.json +0 -10
  118. package/dist/assets/hydrogen/postcss/postcss.config.js +0 -8
  119. package/dist/assets/hydrogen/starter/.graphqlrc.yml +0 -12
  120. package/dist/assets/hydrogen/starter/app/components/Cart.tsx +0 -364
  121. package/dist/assets/hydrogen/tailwind/postcss.config.js +0 -10
  122. package/dist/assets/hydrogen/tailwind/tailwind.config.js +0 -8
  123. package/dist/chunk-4WBV3WP3.js +0 -221
  124. package/dist/chunk-OWICSMFV.js +0 -12
  125. package/dist/chunk-QCDYZY46.js +0 -1070
  126. package/dist/chunk-QEKTVN5A.js +0 -4385
  127. package/dist/chunk-QOUOFEGO.js +0 -35
  128. package/dist/chunk-WP234IUO.js +0 -265
  129. package/dist/chunk-XLPMGRR3.js +0 -496
  130. package/dist/chunk-XSKJYEAZ.js +0 -1453
  131. package/dist/error-handler-QDDLQDOJ.js +0 -43
@@ -1,4385 +0,0 @@
1
- import {
2
- require_notifier
3
- } from "./chunk-S4VBXFXP.js";
4
- import {
5
- ClientError,
6
- fetch,
7
- require_form_data,
8
- require_src,
9
- require_src2,
10
- require_src3,
11
- require_src4,
12
- require_src5,
13
- require_src6
14
- } from "./chunk-A2UVOX6O.js";
15
- import {
16
- Conf,
17
- latestVersion
18
- } from "./chunk-QEOBHRRQ.js";
19
- import {
20
- require_semver
21
- } from "./chunk-PRJ3U7MR.js";
22
- import {
23
- Box_default,
24
- Text,
25
- ansi_escapes_default,
26
- ciPlatform,
27
- cloudEnvironment,
28
- colorJson,
29
- copy,
30
- currentProcessIsGlobal,
31
- ensureFile,
32
- execa,
33
- execaSync,
34
- figures_default,
35
- findUp,
36
- isInteractive,
37
- macAddress,
38
- measure_element_default,
39
- move,
40
- outputContent,
41
- outputDebug,
42
- remove,
43
- render_default,
44
- require_cjs,
45
- require_debounce,
46
- require_difference,
47
- require_dist,
48
- require_gradient_string,
49
- require_macaddress,
50
- require_memoize,
51
- require_node_abort_controller,
52
- require_react,
53
- require_sortBy,
54
- require_stacktracey,
55
- require_supports_hyperlinks,
56
- require_uniqBy,
57
- source_default,
58
- stripAnsi,
59
- terminalLink,
60
- use_app_default,
61
- use_input_default,
62
- use_stdin_default,
63
- use_stdout_default
64
- } from "./chunk-3MDI6LZT.js";
65
- import {
66
- envPaths
67
- } from "./chunk-WADS2TV5.js";
68
- import {
69
- require_lib
70
- } from "./chunk-GEN4RXTD.js";
71
- import {
72
- cwd,
73
- require_commondir
74
- } from "./chunk-UNPXLODI.js";
75
- import {
76
- basename,
77
- dirname,
78
- extname,
79
- isAbsolute,
80
- join,
81
- normalize,
82
- relative,
83
- resolve
84
- } from "./chunk-T5LLJYYS.js";
85
- import {
86
- __toESM,
87
- init_cjs_shims
88
- } from "./chunk-ZPL24Y2D.js";
89
-
90
- // ../cli-kit/dist/public/node/error-handler.js
91
- init_cjs_shims();
92
-
93
- // ../cli-kit/dist/public/node/analytics.js
94
- init_cjs_shims();
95
-
96
- // ../cli-kit/dist/public/node/ruby.js
97
- init_cjs_shims();
98
-
99
- // ../cli-kit/dist/public/node/os.js
100
- init_cjs_shims();
101
-
102
- // ../cli-kit/dist/public/node/output.js
103
- init_cjs_shims();
104
-
105
- // ../cli-kit/dist/public/node/context/local.js
106
- init_cjs_shims();
107
-
108
- // ../cli-kit/dist/public/node/context/spin.js
109
- init_cjs_shims();
110
-
111
- // ../cli-kit/dist/public/node/context/utilities.js
112
- init_cjs_shims();
113
- function isTruthy(variable) {
114
- if (!variable) {
115
- return false;
116
- }
117
- return ["1", "true", "TRUE", "yes", "YES"].includes(variable);
118
- }
119
-
120
- // ../cli-kit/dist/public/node/fs.js
121
- init_cjs_shims();
122
-
123
- // ../cli-kit/dist/public/node/path.js
124
- init_cjs_shims();
125
- var import_commondir = __toESM(require_commondir(), 1);
126
- import { fileURLToPath } from "url";
127
- function joinPath(...paths) {
128
- return join(...paths);
129
- }
130
- function normalizePath(path) {
131
- return normalize(path);
132
- }
133
- function resolvePath(...paths) {
134
- return resolve(...paths);
135
- }
136
- function relativePath(from, to) {
137
- return relative(from, to);
138
- }
139
- function isAbsolutePath(path) {
140
- return isAbsolute(path);
141
- }
142
- function dirname2(path) {
143
- return dirname(path);
144
- }
145
- function basename2(path, ext) {
146
- return basename(path, ext);
147
- }
148
- function extname2(path) {
149
- return extname(path);
150
- }
151
- function relativizePath(path, dir = cwd2()) {
152
- const result = (0, import_commondir.default)([path, dir]);
153
- const relativePath2 = relative(dir, path);
154
- const relativeComponents = relativePath2.split("/").filter((component) => component === "..").length;
155
- if (result === "/" || relativePath2 === "" || relativeComponents > 2) {
156
- return path;
157
- } else {
158
- return relativePath2;
159
- }
160
- }
161
- function moduleDirectory(moduleURL) {
162
- return dirname2(fileURLToPath(moduleURL));
163
- }
164
- function cwd2() {
165
- return normalize(process.env.INIT_CWD ? process.env.INIT_CWD : process.cwd());
166
- }
167
- function sniffForPath(argv = process.argv) {
168
- const pathFlagIndex = argv.indexOf("--path");
169
- if (pathFlagIndex === -1) {
170
- const pathArg = argv.find((arg) => arg.startsWith("--path="));
171
- return pathArg?.split("=")[1];
172
- }
173
- const pathFlag = argv[pathFlagIndex + 1];
174
- if (!pathFlag || pathFlag.startsWith("-"))
175
- return;
176
- return pathFlag;
177
- }
178
-
179
- // ../cli-kit/dist/public/common/string.js
180
- init_cjs_shims();
181
-
182
- // ../cli-kit/dist/public/common/array.js
183
- init_cjs_shims();
184
- var import_uniqBy = __toESM(require_uniqBy(), 1);
185
- var import_difference = __toESM(require_difference(), 1);
186
-
187
- // ../cli-kit/dist/public/common/string.js
188
- var import_change_case = __toESM(require_dist(), 1);
189
- function capitalize(str) {
190
- return str.substring(0, 1).toUpperCase() + str.substring(1);
191
- }
192
- function pluralize(items, plural, singular, none) {
193
- if (items.length === 1) {
194
- return singular(items[0]);
195
- }
196
- if (items.length > 1) {
197
- return plural(items);
198
- }
199
- if (none) {
200
- return none();
201
- }
202
- return "";
203
- }
204
- function linesToColumns(lines) {
205
- const widths = [];
206
- for (let i = 0; lines[0] && i < lines[0].length; i++) {
207
- const columnRows = lines.map((line) => line[i]);
208
- widths.push(Math.max(...columnRows.map((row) => unstyled(row).length)));
209
- }
210
- const paddedLines = lines.map((line) => {
211
- return line.map((col, index) => {
212
- return `${col}${" ".repeat(widths[index] - unstyled(col).length)}`;
213
- }).join(" ").trimEnd();
214
- }).join("\n");
215
- return paddedLines;
216
- }
217
- function camelize(input) {
218
- return (0, import_change_case.camelCase)(input);
219
- }
220
- function hyphenate(input) {
221
- return (0, import_change_case.paramCase)(input);
222
- }
223
- function underscore(input) {
224
- return (0, import_change_case.snakeCase)(input);
225
- }
226
-
227
- // ../cli-kit/dist/public/node/fs.js
228
- import { mkdirSync as fsMkdirSync, readFileSync as fsReadFileSync, writeFileSync as fsWriteFileSync, appendFileSync as fsAppendFileSync, statSync as fsStatSync, createReadStream as fsCreateReadStream, createWriteStream as fsCreateWriteStream, constants as fsConstants, existsSync as fsFileExistsSync, unlinkSync as fsUnlinkSync } from "fs";
229
- import { mkdir as fsMkdir, writeFile as fsWriteFile, readFile as fsReadFile, realpath as fsRealPath, appendFile as fsAppendFile, mkdtemp as fsMkdtemp, stat as fsStat, lstat as fsLstat, chmod as fsChmod, access as fsAccess, rename as fsRename } from "fs/promises";
230
- async function readFile(path, options = { encoding: "utf8" }) {
231
- outputDebug2(outputContent2`Reading the content of file at ${outputToken.path(path)}...`);
232
- return fsReadFile(path, options);
233
- }
234
- function readFileSync(path) {
235
- outputDebug2(outputContent2`Sync-reading the content of file at ${outputToken.path(path)}...`);
236
- return fsReadFileSync(path);
237
- }
238
- async function copyFile(from, to) {
239
- outputDebug2(outputContent2`Copying file from ${outputToken.path(from)} to ${outputToken.path(to)}...`);
240
- await copy(from, to);
241
- }
242
- async function touchFile(path) {
243
- outputDebug2(outputContent2`Creating an empty file at ${outputToken.path(path)}...`);
244
- await ensureFile(path);
245
- }
246
- async function writeFile(path, data, options = { encoding: "utf8" }) {
247
- outputDebug2(outputContent2`Writing some content to file at ${outputToken.path(path)}...`);
248
- await fsWriteFile(path, data, options);
249
- }
250
- async function mkdir(path) {
251
- outputDebug2(outputContent2`Creating directory at ${outputToken.path(path)}...`);
252
- await fsMkdir(path, { recursive: true });
253
- }
254
- async function removeFile(path) {
255
- outputDebug2(outputContent2`Removing file at ${outputToken.path(path)}...`);
256
- await remove(path);
257
- }
258
- async function rmdir(path, options = {}) {
259
- const { default: del } = await import("./del-KSMMBLCD.js");
260
- outputDebug2(outputContent2`Removing directory at ${outputToken.path(path)}...`);
261
- await del(path, { force: options.force });
262
- }
263
- async function isDirectory(path) {
264
- outputDebug2(outputContent2`Checking if ${outputToken.path(path)} is a directory...`);
265
- return (await fsLstat(path)).isDirectory();
266
- }
267
- async function fileSize(path) {
268
- outputDebug2(outputContent2`Getting the size of file file at ${outputToken.path(path)}...`);
269
- return (await fsStat(path)).size;
270
- }
271
- function fileSizeSync(path) {
272
- outputDebug2(outputContent2`Sync-getting the size of file file at ${outputToken.path(path)}...`);
273
- return fsStatSync(path).size;
274
- }
275
- function createFileReadStream(path, options) {
276
- return fsCreateReadStream(path, options);
277
- }
278
- async function moveFile(src, dest, options = {}) {
279
- await move(src, dest, options);
280
- }
281
- async function fileExists(path) {
282
- try {
283
- await fsAccess(path);
284
- return true;
285
- } catch {
286
- return false;
287
- }
288
- }
289
- async function glob(pattern, options) {
290
- const { default: fastGlob } = await import("./out-AS7GH6TC.js");
291
- let overridenOptions = options;
292
- if (options?.dot == null) {
293
- overridenOptions = { ...options, dot: true };
294
- }
295
- return fastGlob(pattern, overridenOptions);
296
- }
297
- async function findPathUp(matcher, options) {
298
- const got = await findUp(matcher, options);
299
- return got ? normalizePath(got) : void 0;
300
- }
301
-
302
- // ../cli-kit/dist/private/node/constants.js
303
- init_cjs_shims();
304
- var identifier = "shopify-cli";
305
- var cacheFolder = () => {
306
- if (process.env.XDG_CACHE_HOME)
307
- return process.env.XDG_CACHE_HOME;
308
- return envPaths(identifier).cache;
309
- };
310
- var environmentVariables = {
311
- alwaysLogAnalytics: "SHOPIFY_CLI_ALWAYS_LOG_ANALYTICS",
312
- alwaysLogMetrics: "SHOPIFY_CLI_ALWAYS_LOG_METRICS",
313
- deviceAuth: "SHOPIFY_CLI_DEVICE_AUTH",
314
- enableCliRedirect: "SHOPIFY_CLI_ENABLE_CLI_REDIRECT",
315
- env: "SHOPIFY_CLI_ENV",
316
- firstPartyDev: "SHOPIFY_CLI_1P_DEV",
317
- noAnalytics: "SHOPIFY_CLI_NO_ANALYTICS",
318
- partnersToken: "SHOPIFY_CLI_PARTNERS_TOKEN",
319
- runAsUser: "SHOPIFY_RUN_AS_USER",
320
- serviceEnv: "SHOPIFY_SERVICE_ENV",
321
- skipCliRedirect: "SHOPIFY_CLI_SKIP_CLI_REDIRECT",
322
- spinInstance: "SPIN_INSTANCE",
323
- themeToken: "SHOPIFY_CLI_THEME_TOKEN",
324
- unitTest: "SHOPIFY_UNIT_TEST",
325
- verbose: "SHOPIFY_FLAG_VERBOSE",
326
- noThemeBundling: "SHOPIFY_CLI_NO_THEME_BUNDLING",
327
- bundledThemeCLI: "SHOPIFY_CLI_BUNDLED_THEME_CLI",
328
- // Variables to detect if the CLI is running in a cloud environment
329
- codespaces: "CODESPACES",
330
- codespaceName: "CODESPACE_NAME",
331
- codespacePortForwardingDomain: "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN",
332
- gitpod: "GITPOD_WORKSPACE_URL",
333
- cloudShell: "CLOUD_SHELL",
334
- spin: "SPIN",
335
- spinAppPort: "SERVER_PORT",
336
- spinAppHost: "SPIN_APP_HOST",
337
- organization: "SHOPIFY_CLI_ORGANIZATION",
338
- identityToken: "SHOPIFY_CLI_IDENTITY_TOKEN",
339
- refreshToken: "SHOPIFY_CLI_REFRESH_TOKEN",
340
- otelURL: "SHOPIFY_CLI_OTEL_EXPORTER_OTLP_ENDPOINT",
341
- themeKitAccessDomain: "SHOPIFY_CLI_THEME_KIT_ACCESS_DOMAIN"
342
- };
343
- var pathConstants = {
344
- executables: {
345
- dev: "/opt/dev/bin/dev"
346
- },
347
- directories: {
348
- cache: {
349
- path: () => {
350
- return cacheFolder();
351
- },
352
- vendor: {
353
- path: () => {
354
- return joinPath(cacheFolder(), "vendor");
355
- },
356
- binaries: () => {
357
- return joinPath(cacheFolder(), "vendor", "binaries");
358
- }
359
- }
360
- }
361
- }
362
- };
363
- var sessionConstants = {
364
- expirationTimeMarginInMinutes: 4
365
- };
366
- var bugsnagApiKey = "9e1e6889176fd0c795d5c659225e0fae";
367
-
368
- // ../cli-kit/dist/public/node/system.js
369
- init_cjs_shims();
370
-
371
- // ../cli-kit/dist/public/node/error.js
372
- init_cjs_shims();
373
-
374
- // ../cli-kit/dist/public/node/ui.js
375
- init_cjs_shims();
376
-
377
- // ../cli-kit/dist/public/node/abort.js
378
- init_cjs_shims();
379
- var import_node_abort_controller = __toESM(require_node_abort_controller(), 1);
380
- var AbortController = class extends import_node_abort_controller.AbortController {
381
- };
382
-
383
- // ../cli-kit/dist/public/node/metadata.js
384
- init_cjs_shims();
385
- import { performance } from "node:perf_hooks";
386
- function getMetadataErrorHandlingStrategy() {
387
- if (isUnitTest()) {
388
- return "bubble";
389
- }
390
- return "mute-and-report";
391
- }
392
- function createRuntimeMetadataContainer(defaultPublicMetadata = {}) {
393
- const raw = {
394
- sensitive: {},
395
- public: {
396
- ...defaultPublicMetadata
397
- }
398
- };
399
- const addPublic = (data) => {
400
- Object.assign(raw.public, data);
401
- };
402
- const addSensitive = (data) => {
403
- Object.assign(raw.sensitive, data);
404
- };
405
- const addMetadata = async (addFn, getFn, onError) => {
406
- const errorHandling = onError === "auto" ? getMetadataErrorHandlingStrategy() : onError;
407
- const getAndSet = async () => {
408
- const data = await getFn();
409
- addFn(data);
410
- };
411
- if (errorHandling === "bubble") {
412
- await getAndSet();
413
- } else {
414
- try {
415
- await getAndSet();
416
- } catch (error) {
417
- const { sendErrorToBugsnag: sendErrorToBugsnag2 } = await import("./error-handler-HUI4HW3X.js");
418
- await sendErrorToBugsnag2(error, "unexpected_error");
419
- }
420
- }
421
- };
422
- const durationStack = [];
423
- return {
424
- getAllPublicMetadata: () => {
425
- return { ...raw.public };
426
- },
427
- getAllSensitiveMetadata: () => {
428
- return { ...raw.sensitive };
429
- },
430
- addPublicMetadata: async (getData, onError = "auto") => {
431
- return addMetadata(addPublic, getData, onError);
432
- },
433
- addSensitiveMetadata: async (getData, onError = "auto") => {
434
- return addMetadata(addSensitive, getData, onError);
435
- },
436
- runWithTimer: (field) => {
437
- return async (fn) => {
438
- durationStack.push(0);
439
- const start = performance.now();
440
- try {
441
- const result = await fn();
442
- return result;
443
- } finally {
444
- let end = performance.now();
445
- end = Math.max(start, end);
446
- const wallClockDuration = Math.max(end - start, 0);
447
- const childDurations = durationStack.pop();
448
- const duration = Math.max(wallClockDuration - childDurations, 0);
449
- if (durationStack.length > 0) {
450
- durationStack[durationStack.length - 1] += wallClockDuration;
451
- }
452
- performance.measure(`${field}#measurable`, {
453
- start,
454
- duration
455
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
456
- });
457
- performance.measure(`${field}#wall`, {
458
- start,
459
- end
460
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
461
- });
462
- let currentValue = raw.public[field] || 0;
463
- currentValue += duration;
464
- raw.public[field] = currentValue;
465
- }
466
- };
467
- }
468
- };
469
- }
470
- var coreData = createRuntimeMetadataContainer({ cmd_all_timing_network_ms: 0, cmd_all_timing_prompts_ms: 0 });
471
- var { getAllPublicMetadata, getAllSensitiveMetadata, addPublicMetadata, addSensitiveMetadata, runWithTimer } = coreData;
472
-
473
- // ../cli-kit/dist/private/node/ui/components/ConcurrentOutput.js
474
- init_cjs_shims();
475
-
476
- // ../cli-kit/dist/private/node/demo-recorder.js
477
- init_cjs_shims();
478
- var DemoRecorder = class {
479
- constructor() {
480
- this.recorded = [];
481
- this.sleepStart = Date.now();
482
- this.command = ["shopify", ...process.argv.slice(2)].join(" ");
483
- }
484
- addEvent({ type, properties }) {
485
- if (type === "taskbar") {
486
- this.resetSleep();
487
- } else {
488
- this.addSleep();
489
- }
490
- this.recorded.push({ type, properties: JSON.parse(JSON.stringify(properties)) });
491
- this.sleepStart = Date.now();
492
- }
493
- recordedEventsJson() {
494
- return JSON.stringify({
495
- command: this.command,
496
- steps: this.withFormattedConcurrent(this.recorded)
497
- }, null, 2);
498
- }
499
- addSleep() {
500
- const duration = (Date.now() - this.sleepStart) / 1e3;
501
- this.sleepStart = Date.now();
502
- if (duration > 0.1) {
503
- this.recorded.push({ type: "sleep", properties: { duration } });
504
- }
505
- }
506
- resetSleep() {
507
- this.sleepStart = Date.now();
508
- }
509
- addOrUpdateConcurrentOutput({ prefix, index, output }) {
510
- let last = this.recorded[this.recorded.length - 1];
511
- if (last?.type === "concurrent") {
512
- this.resetSleep();
513
- } else {
514
- const eventProperties = {
515
- type: "concurrent",
516
- properties: { processes: [], concurrencyStart: Date.now() }
517
- };
518
- this.addEvent(eventProperties);
519
- last = this.recorded[this.recorded.length - 1];
520
- }
521
- const { processes } = last.properties;
522
- while (processes.length <= index) {
523
- processes.push({ prefix: "", steps: [] });
524
- }
525
- processes[index].prefix = prefix;
526
- processes[index].steps.push({ timestamp: Date.now(), endMessage: output });
527
- }
528
- withFormattedConcurrent(recorded) {
529
- return recorded.map((event) => {
530
- if (event.type === "concurrent") {
531
- const { processes, footer, concurrencyStart } = event.properties;
532
- const formatted = processes.map(({ prefix, steps }) => {
533
- let mostRecentTimestamp = concurrencyStart;
534
- const formattedSteps = steps.map(({ timestamp, endMessage }) => {
535
- const duration = (timestamp - mostRecentTimestamp) / 1e3;
536
- mostRecentTimestamp = timestamp;
537
- return { duration, endMessage };
538
- });
539
- return { prefix, steps: formattedSteps };
540
- });
541
- return { type: "concurrent", properties: { footer, processes: formatted } };
542
- }
543
- return event;
544
- });
545
- }
546
- };
547
- var NoopDemoRecorder = class {
548
- addEvent(_event) {
549
- }
550
- recordedEventsJson() {
551
- return JSON.stringify({ steps: [] }, null, 2);
552
- }
553
- addSleep() {
554
- }
555
- resetSleep() {
556
- }
557
- addOrUpdateConcurrentOutput(..._args) {
558
- }
559
- };
560
- var _instance;
561
- function ensureInstance() {
562
- if (!_instance) {
563
- if (isRecording()) {
564
- _instance = new DemoRecorder();
565
- } else {
566
- _instance = new NoopDemoRecorder();
567
- }
568
- }
569
- }
570
- function recordUIEvent(event) {
571
- ensureInstance();
572
- _instance.addEvent(event);
573
- }
574
- function resetRecordedSleep() {
575
- ensureInstance();
576
- _instance.resetSleep();
577
- }
578
- function printEventsJson() {
579
- if (isRecording()) {
580
- ensureInstance();
581
- _instance.addSleep();
582
- console.log(_instance.recordedEventsJson());
583
- }
584
- }
585
- function isRecording() {
586
- return isTruthy(process.env.RECORD_DEMO);
587
- }
588
-
589
- // ../cli-kit/dist/private/node/ui/components/ConcurrentOutput.js
590
- var import_react = __toESM(require_react(), 1);
591
- import { AsyncLocalStorage } from "node:async_hooks";
592
- var outputContextStore = new AsyncLocalStorage();
593
-
594
- // ../cli-kit/dist/private/node/ui.js
595
- init_cjs_shims();
596
-
597
- // ../cli-kit/dist/public/node/tree-kill.js
598
- init_cjs_shims();
599
- import { exec, spawn } from "child_process";
600
- function treeKill(pid = process.pid, killSignal = "SIGTERM", killRoot = true, callback) {
601
- const after = callback ?? ((error) => {
602
- if (error)
603
- outputDebug2(`Failed to kill process ${pid}: ${error}`);
604
- });
605
- printEventsJson();
606
- adaptedTreeKill(pid, killSignal, killRoot, after);
607
- }
608
- function adaptedTreeKill(pid, killSignal, killRoot, callback) {
609
- const rootPid = typeof pid === "number" ? pid.toString() : pid;
610
- if (Number.isNaN(rootPid)) {
611
- if (callback) {
612
- return callback(new Error("pid must be a number"));
613
- } else {
614
- throw new Error("pid must be a number");
615
- }
616
- }
617
- const tree = {};
618
- tree[rootPid] = [];
619
- const pidsToProcess = /* @__PURE__ */ new Set();
620
- pidsToProcess.add(rootPid);
621
- switch (process.platform) {
622
- case "win32":
623
- exec(`taskkill /pid ${pid} /T /F`, callback);
624
- break;
625
- case "darwin":
626
- buildProcessTree(rootPid, tree, pidsToProcess, function(parentPid) {
627
- return spawn("pgrep", ["-lfP", parentPid]);
628
- }, function() {
629
- killAll(tree, killSignal, rootPid, killRoot, callback);
630
- });
631
- break;
632
- default:
633
- buildProcessTree(rootPid, tree, pidsToProcess, function(parentPid) {
634
- return spawn("ps", ["-o", "pid command", "--no-headers", "--ppid", parentPid]);
635
- }, function() {
636
- killAll(tree, killSignal, rootPid, killRoot, callback);
637
- });
638
- break;
639
- }
640
- }
641
- function killAll(tree, killSignal, rootPid, killRoot, callback) {
642
- const killed = /* @__PURE__ */ new Set();
643
- try {
644
- Object.keys(tree).forEach(function(pid) {
645
- tree[pid].forEach(function(pidpid) {
646
- if (!killed.has(pidpid)) {
647
- killPid(pidpid, killSignal);
648
- killed.add(pidpid);
649
- }
650
- });
651
- if (pid === rootPid && killRoot && !killed.has(pid)) {
652
- killPid(pid, killSignal);
653
- killed.add(pid);
654
- }
655
- });
656
- } catch (err) {
657
- if (callback) {
658
- return callback(err);
659
- } else {
660
- throw err;
661
- }
662
- }
663
- if (callback) {
664
- return callback();
665
- }
666
- }
667
- function killPid(pid, killSignal) {
668
- try {
669
- process.kill(parseInt(pid, 10), killSignal);
670
- } catch (err) {
671
- if (err.code !== "ESRCH")
672
- throw err;
673
- }
674
- }
675
- function buildProcessTree(parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
676
- const ps = spawnChildProcessesList(parentPid);
677
- let allData = "";
678
- ps.stdout?.on("data", function(data) {
679
- const dataStr = data.toString("ascii");
680
- allData += dataStr;
681
- });
682
- const onClose = (code) => {
683
- pidsToProcess.delete(parentPid);
684
- if (code !== 0) {
685
- if (pidsToProcess.size === 0) {
686
- return cb();
687
- }
688
- return;
689
- }
690
- allData.trim().split("\n").forEach(function(line) {
691
- const match = line.match(/^(\d+)\s(.*)$/);
692
- if (match) {
693
- const pid = match[1];
694
- const cmd = match[2];
695
- tree[parentPid].push(pid);
696
- tree[pid] = [];
697
- outputDebug2(`Killing process ${pid}: ${cmd}`);
698
- pidsToProcess.add(pid);
699
- buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
700
- }
701
- });
702
- };
703
- ps.on("close", onClose);
704
- }
705
-
706
- // ../cli-kit/dist/private/node/ui.js
707
- import { EventEmitter } from "events";
708
- function renderOnce(element, { logLevel = "info", logger = consoleLog, renderOptions }) {
709
- const { output, unmount } = renderString(element, renderOptions);
710
- if (output) {
711
- if (isUnitTest())
712
- collectLog(logLevel, output);
713
- outputWhereAppropriate(logLevel, logger, output, { skipUIEvent: true });
714
- }
715
- unmount();
716
- return output;
717
- }
718
- async function render(element, options) {
719
- const { waitUntilExit } = render_default(element, options);
720
- await waitUntilExit();
721
- return new Promise((resolve2) => setImmediate(resolve2));
722
- }
723
- var Stdout = class extends EventEmitter {
724
- constructor(options) {
725
- super();
726
- this.frames = [];
727
- this.write = (frame) => {
728
- this.frames.push(frame);
729
- this._lastFrame = frame;
730
- };
731
- this.lastFrame = () => {
732
- return this._lastFrame;
733
- };
734
- this.columns = options.columns ?? 80;
735
- this.rows = options.rows ?? 80;
736
- }
737
- };
738
- var renderString = (element, renderOptions) => {
739
- const columns = isUnitTest() ? 80 : process.stdout.columns;
740
- const stdout = renderOptions?.stdout ?? new Stdout({ columns });
741
- const instance2 = render_default(element, {
742
- stdout,
743
- debug: true,
744
- exitOnCtrlC: false,
745
- patchConsole: false
746
- });
747
- return {
748
- output: stdout.lastFrame(),
749
- unmount: instance2.unmount
750
- };
751
- };
752
- function handleCtrlC(input, key, exit = () => treeKill(process.pid, "SIGINT")) {
753
- if (input === "c" && key.ctrl) {
754
- exit();
755
- }
756
- }
757
-
758
- // ../cli-kit/dist/private/node/ui/alert.js
759
- init_cjs_shims();
760
-
761
- // ../cli-kit/dist/private/node/ui/components/Alert.js
762
- init_cjs_shims();
763
-
764
- // ../cli-kit/dist/private/node/ui/components/Banner.js
765
- init_cjs_shims();
766
-
767
- // ../cli-kit/dist/private/node/ui/hooks/use-layout.js
768
- init_cjs_shims();
769
- var import_react2 = __toESM(require_react(), 1);
770
- var MIN_FULL_WIDTH = 20;
771
- var MIN_FRACTION_WIDTH = 80;
772
- function useLayout() {
773
- const { stdout } = use_stdout_default();
774
- const [layout, setLayout] = (0, import_react2.useState)(calculateLayout(stdout));
775
- (0, import_react2.useLayoutEffect)(() => {
776
- if (!stdout) {
777
- return;
778
- }
779
- function onResize() {
780
- setLayout(calculateLayout(stdout));
781
- }
782
- stdout.on("resize", onResize);
783
- return () => {
784
- stdout.off("resize", onResize);
785
- };
786
- }, []);
787
- return layout;
788
- }
789
- function calculateLayout(stdout) {
790
- let fullWidth = stdout?.columns ?? MIN_FRACTION_WIDTH;
791
- let oneThird = fullWidth;
792
- let twoThirds = fullWidth;
793
- if (fullWidth <= MIN_FULL_WIDTH) {
794
- fullWidth = MIN_FULL_WIDTH;
795
- oneThird = MIN_FULL_WIDTH;
796
- twoThirds = MIN_FULL_WIDTH;
797
- } else if (fullWidth > MIN_FRACTION_WIDTH) {
798
- oneThird = column({ fullWidth, fraction: [1, 3], minWidth: MIN_FRACTION_WIDTH });
799
- twoThirds = column({ fullWidth, fraction: [2, 3], minWidth: MIN_FRACTION_WIDTH });
800
- }
801
- return {
802
- fullWidth,
803
- oneThird,
804
- twoThirds
805
- };
806
- }
807
- function column({ fullWidth, fraction, minWidth }) {
808
- const fractionedWidth = Math.floor(fullWidth / fraction[1] * fraction[0]);
809
- if (fractionedWidth < minWidth) {
810
- return minWidth;
811
- } else {
812
- return fractionedWidth;
813
- }
814
- }
815
-
816
- // ../cli-kit/dist/private/node/ui/contexts/LinksContext.js
817
- init_cjs_shims();
818
- var import_react3 = __toESM(require_react(), 1);
819
- var LinksContext = import_react3.default.createContext(null);
820
-
821
- // ../cli-kit/dist/private/node/ui/components/Banner.js
822
- var import_react4 = __toESM(require_react(), 1);
823
- function typeToColor(type) {
824
- return {
825
- success: "green",
826
- error: "red",
827
- warning: "yellow",
828
- info: "dim",
829
- external_error: "red"
830
- }[type];
831
- }
832
- var Footnotes = () => {
833
- const linksContext = (0, import_react4.useContext)(LinksContext);
834
- if (linksContext === null || linksContext.links.current === null) {
835
- return null;
836
- }
837
- const links = linksContext.links.current;
838
- const linkIds = Object.keys(links);
839
- return linkIds.length > 0 ? import_react4.default.createElement(Box_default, { marginBottom: 1, marginTop: -1, flexDirection: "column" }, linkIds.map((id) => import_react4.default.createElement(Text, { key: id }, `[${id}] ${links[id]?.url}`))) : null;
840
- };
841
- var BoxWithBorder = ({ type, children }) => {
842
- const { twoThirds } = useLayout();
843
- const links = (0, import_react4.useRef)({});
844
- return import_react4.default.createElement(
845
- LinksContext.Provider,
846
- { value: {
847
- links,
848
- addLink: (label, url2) => {
849
- const id = Object.keys(links.current).find((id2) => links.current[id2].url === url2);
850
- if (id) {
851
- return id;
852
- }
853
- const newId = (Object.keys(links.current).length + 1).toString();
854
- links.current = {
855
- ...links.current,
856
- [newId]: { label, url: url2 }
857
- };
858
- return newId;
859
- }
860
- } },
861
- import_react4.default.createElement(
862
- Box_default,
863
- { width: twoThirds, marginBottom: 1, borderStyle: "round", flexDirection: "column", borderColor: typeToColor(type) },
864
- import_react4.default.createElement(
865
- Box_default,
866
- { marginTop: -1, marginLeft: 1 },
867
- import_react4.default.createElement(Text, null, ` ${type.replace(/_/g, " ")} `)
868
- ),
869
- import_react4.default.createElement(Box_default, { flexDirection: "column", paddingY: 1, paddingX: 2, gap: 1 }, children)
870
- ),
871
- import_react4.default.createElement(Footnotes, null)
872
- );
873
- };
874
- var BoxWithTopBottomLines = ({ type, children }) => {
875
- const { twoThirds } = useLayout();
876
- let topLineAfterTypeLength = twoThirds - 2 - type.length - 2;
877
- if (topLineAfterTypeLength < 0)
878
- topLineAfterTypeLength = 0;
879
- return import_react4.default.createElement(
880
- Box_default,
881
- { flexDirection: "column", marginBottom: 1, gap: 1 },
882
- import_react4.default.createElement(
883
- Text,
884
- null,
885
- import_react4.default.createElement(Text, { color: typeToColor(type) }, "\u2500".repeat(2)),
886
- import_react4.default.createElement(Text, null, ` ${type.replace(/_/g, " ")} `),
887
- import_react4.default.createElement(Text, { color: typeToColor(type) }, "\u2500".repeat(topLineAfterTypeLength))
888
- ),
889
- children,
890
- import_react4.default.createElement(Text, { color: typeToColor(type) }, "\u2500".repeat(twoThirds))
891
- );
892
- };
893
- var Banner = ({ children, ...props }) => {
894
- if (props.type === "external_error") {
895
- return import_react4.default.createElement(BoxWithTopBottomLines, props, children);
896
- } else {
897
- return import_react4.default.createElement(BoxWithBorder, props, children);
898
- }
899
- };
900
-
901
- // ../cli-kit/dist/private/node/ui/components/Link.js
902
- init_cjs_shims();
903
- var import_react5 = __toESM(require_react(), 1);
904
- var import_supports_hyperlinks = __toESM(require_supports_hyperlinks(), 1);
905
- function link(label, url2, linksContext) {
906
- if (!import_supports_hyperlinks.default.stdout) {
907
- if (linksContext === null) {
908
- return label ? `${label} ${source_default.dim(`( ${url2} )`)}` : url2;
909
- }
910
- const linkId = linksContext.addLink(label, url2);
911
- return `${label ?? url2} [${linkId}]`;
912
- }
913
- return ansi_escapes_default.link(label ?? url2, url2);
914
- }
915
- var Link = ({ label, url: url2 }) => {
916
- const linksContext = (0, import_react5.useContext)(LinksContext);
917
- return import_react5.default.createElement(Text, null, link(label, url2, linksContext));
918
- };
919
-
920
- // ../cli-kit/dist/private/node/ui/components/List.js
921
- init_cjs_shims();
922
-
923
- // ../cli-kit/dist/private/node/ui/components/TokenizedText.js
924
- init_cjs_shims();
925
-
926
- // ../cli-kit/dist/private/node/ui/components/Command.js
927
- init_cjs_shims();
928
- var import_react6 = __toESM(require_react(), 1);
929
- var Command = ({ command }) => {
930
- return import_react6.default.createElement(
931
- Text,
932
- { color: "magentaBright" },
933
- "`",
934
- command,
935
- "`"
936
- );
937
- };
938
-
939
- // ../cli-kit/dist/private/node/ui/components/UserInput.js
940
- init_cjs_shims();
941
- var import_react7 = __toESM(require_react(), 1);
942
- var UserInput = ({ userInput }) => {
943
- return import_react7.default.createElement(Text, { color: "cyan" }, userInput);
944
- };
945
-
946
- // ../cli-kit/dist/private/node/ui/components/FilePath.js
947
- init_cjs_shims();
948
- var import_react8 = __toESM(require_react(), 1);
949
- var FilePath = ({ filePath }) => {
950
- return import_react8.default.createElement(Text, { italic: true }, filePath);
951
- };
952
-
953
- // ../cli-kit/dist/private/node/ui/components/Subdued.js
954
- init_cjs_shims();
955
- var import_react9 = __toESM(require_react(), 1);
956
- var Subdued = ({ subdued }) => {
957
- return import_react9.default.createElement(Text, { dimColor: true }, subdued);
958
- };
959
-
960
- // ../cli-kit/dist/private/node/ui/components/TokenizedText.js
961
- var import_react10 = __toESM(require_react(), 1);
962
- function tokenToBlock(token) {
963
- return {
964
- display: typeof token !== "string" && "list" in token ? "block" : "inline",
965
- value: token
966
- };
967
- }
968
- function tokenItemToString(token) {
969
- if (typeof token === "string") {
970
- return token;
971
- } else if ("command" in token) {
972
- return token.command;
973
- } else if ("link" in token) {
974
- return token.link.label || token.link.url;
975
- } else if ("char" in token) {
976
- return token.char;
977
- } else if ("userInput" in token) {
978
- return token.userInput;
979
- } else if ("subdued" in token) {
980
- return token.subdued;
981
- } else if ("filePath" in token) {
982
- return token.filePath;
983
- } else if ("list" in token) {
984
- return token.list.items.map(tokenItemToString).join(" ");
985
- } else if ("bold" in token) {
986
- return token.bold;
987
- } else if ("info" in token) {
988
- return token.info;
989
- } else if ("warn" in token) {
990
- return token.warn;
991
- } else if ("error" in token) {
992
- return token.error;
993
- } else {
994
- return token.map((item, index) => {
995
- if (index !== 0 && !(typeof item !== "string" && "char" in item)) {
996
- return ` ${tokenItemToString(item)}`;
997
- } else {
998
- return tokenItemToString(item);
999
- }
1000
- }).join("");
1001
- }
1002
- }
1003
- function appendToTokenItem(token, suffix) {
1004
- return Array.isArray(token) ? [...token, { char: suffix }] : [token, { char: suffix }];
1005
- }
1006
- function splitByDisplayType(acc, item) {
1007
- if (item.display === "block") {
1008
- acc.push([item]);
1009
- } else {
1010
- const last = acc[acc.length - 1];
1011
- if (last && last[0].display === "inline") {
1012
- last.push(item);
1013
- } else {
1014
- acc.push([item]);
1015
- }
1016
- }
1017
- return acc;
1018
- }
1019
- var InlineBlocks = ({ blocks }) => {
1020
- return import_react10.default.createElement(Text, null, blocks.map((block, blockIndex) => import_react10.default.createElement(
1021
- Text,
1022
- { key: blockIndex },
1023
- blockIndex !== 0 && !(typeof block.value !== "string" && "char" in block.value) && import_react10.default.createElement(Text, null, " "),
1024
- import_react10.default.createElement(TokenizedText, { item: block.value })
1025
- )));
1026
- };
1027
- var TokenizedText = ({ item }) => {
1028
- if (typeof item === "string") {
1029
- return import_react10.default.createElement(Text, null, item);
1030
- } else if ("command" in item) {
1031
- return import_react10.default.createElement(Command, { command: item.command });
1032
- } else if ("link" in item) {
1033
- return import_react10.default.createElement(Link, { ...item.link });
1034
- } else if ("char" in item) {
1035
- return import_react10.default.createElement(Text, null, item.char[0]);
1036
- } else if ("userInput" in item) {
1037
- return import_react10.default.createElement(UserInput, { userInput: item.userInput });
1038
- } else if ("subdued" in item) {
1039
- return import_react10.default.createElement(Subdued, { subdued: item.subdued });
1040
- } else if ("filePath" in item) {
1041
- return import_react10.default.createElement(FilePath, { filePath: item.filePath });
1042
- } else if ("list" in item) {
1043
- return import_react10.default.createElement(List, { ...item.list });
1044
- } else if ("bold" in item) {
1045
- return import_react10.default.createElement(Text, { bold: true }, item.bold);
1046
- } else if ("info" in item) {
1047
- return import_react10.default.createElement(Text, { color: "blue" }, item.info);
1048
- } else if ("warn" in item) {
1049
- return import_react10.default.createElement(Text, { color: "yellow" }, item.warn);
1050
- } else if ("error" in item) {
1051
- return import_react10.default.createElement(Text, { color: "red" }, item.error);
1052
- } else {
1053
- const groupedItems = item.map(tokenToBlock).reduce(splitByDisplayType, []);
1054
- return groupedItems.length === 1 && groupedItems[0].every((item2) => item2.display === "inline") ? import_react10.default.createElement(InlineBlocks, { blocks: groupedItems[0] }) : import_react10.default.createElement(Box_default, { flexDirection: "column" }, groupedItems.map((items, groupIndex) => {
1055
- if (items[0].display === "inline") {
1056
- return import_react10.default.createElement(InlineBlocks, { blocks: items, key: groupIndex });
1057
- } else {
1058
- return import_react10.default.createElement(List, { key: groupIndex, ...items[0].value.list });
1059
- }
1060
- }));
1061
- }
1062
- };
1063
-
1064
- // ../cli-kit/dist/private/node/ui/components/List.js
1065
- var import_react11 = __toESM(require_react(), 1);
1066
- var DOT = "\u2022";
1067
- var List = ({ title, items, margin = true, ordered = false, color, bullet = DOT }) => {
1068
- function isCustomListItem(item) {
1069
- return item.item !== void 0;
1070
- }
1071
- function resolveListItem(item, index) {
1072
- const resolvedItem = {
1073
- index,
1074
- color,
1075
- bullet,
1076
- ordered,
1077
- item
1078
- };
1079
- return isCustomListItem(item) ? {
1080
- ...resolvedItem,
1081
- ...item
1082
- } : resolvedItem;
1083
- }
1084
- const ListItem = ({ item, color: color2, bullet: bullet2, index, ordered: ordered2 }) => {
1085
- return import_react11.default.createElement(
1086
- Box_default,
1087
- { key: index, marginLeft: margin ? 2 : 0 },
1088
- import_react11.default.createElement(Text, { color: color2 }, `${ordered2 ? `${index + 1}.` : bullet2}`),
1089
- import_react11.default.createElement(
1090
- Box_default,
1091
- { flexGrow: 1, marginLeft: 1 },
1092
- import_react11.default.createElement(
1093
- Text,
1094
- { color: color2 },
1095
- import_react11.default.createElement(TokenizedText, { item })
1096
- )
1097
- )
1098
- );
1099
- };
1100
- return import_react11.default.createElement(
1101
- Box_default,
1102
- { flexDirection: "column" },
1103
- title ? import_react11.default.createElement(
1104
- Text,
1105
- { color },
1106
- import_react11.default.createElement(TokenizedText, { item: title })
1107
- ) : null,
1108
- items.map(resolveListItem).map(({ index, item, color: color2, bullet: bullet2, ordered: ordered2 }) => import_react11.default.createElement(ListItem, { key: index, item, color: color2, bullet: bullet2, index, ordered: ordered2 }))
1109
- );
1110
- };
1111
-
1112
- // ../cli-kit/dist/private/node/ui/components/Alert.js
1113
- var import_react12 = __toESM(require_react(), 1);
1114
- var Alert = ({ type, headline, body, nextSteps, reference, link: link2, customSections, orderedNextSteps = false }) => {
1115
- return import_react12.default.createElement(
1116
- Banner,
1117
- { type },
1118
- headline ? import_react12.default.createElement(
1119
- Text,
1120
- { bold: true },
1121
- import_react12.default.createElement(TokenizedText, { item: headline })
1122
- ) : null,
1123
- body ? import_react12.default.createElement(TokenizedText, { item: body }) : null,
1124
- nextSteps && nextSteps.length > 0 ? import_react12.default.createElement(List, { title: "Next steps", items: nextSteps, ordered: orderedNextSteps }) : null,
1125
- reference && reference.length > 0 ? import_react12.default.createElement(List, { title: "Reference", items: reference }) : null,
1126
- link2 ? import_react12.default.createElement(Link, { url: link2.url, label: link2.label }) : null,
1127
- customSections && customSections.length > 0 ? import_react12.default.createElement(Box_default, { flexDirection: "column", gap: 1 }, customSections.map((section, index) => import_react12.default.createElement(
1128
- Box_default,
1129
- { key: index, flexDirection: "column" },
1130
- section.title ? import_react12.default.createElement(Text, { bold: true }, section.title) : null,
1131
- import_react12.default.createElement(TokenizedText, { item: section.body })
1132
- ))) : null
1133
- );
1134
- };
1135
-
1136
- // ../cli-kit/dist/private/node/ui/alert.js
1137
- var import_react13 = __toESM(require_react(), 1);
1138
- var typeToLogLevel = {
1139
- info: "info",
1140
- warning: "warn",
1141
- success: "info",
1142
- error: "error"
1143
- };
1144
- var typeToLogger = {
1145
- info: consoleLog,
1146
- warning: consoleWarn,
1147
- success: consoleLog,
1148
- error: consoleError
1149
- };
1150
- function alert({ type, headline, body, nextSteps, reference, link: link2, customSections, orderedNextSteps = false, renderOptions }) {
1151
- const { type: alertType, ...eventProps } = arguments[0];
1152
- recordUIEvent({ type, properties: eventProps });
1153
- return renderOnce(import_react13.default.createElement(Alert, { type, headline, body, nextSteps, reference, link: link2, orderedNextSteps, customSections }), { logLevel: typeToLogLevel[type], logger: typeToLogger[type], renderOptions });
1154
- }
1155
-
1156
- // ../cli-kit/dist/private/node/ui/components/FatalError.js
1157
- init_cjs_shims();
1158
- var import_react14 = __toESM(require_react(), 1);
1159
- var import_stacktracey = __toESM(require_stacktracey(), 1);
1160
- var FatalError = ({ error }) => {
1161
- let stack;
1162
- let tool;
1163
- if (error instanceof BugError) {
1164
- stack = new import_stacktracey.default(error);
1165
- stack.items.forEach((item) => {
1166
- item.file = cleanSingleStackTracePath(item.file);
1167
- });
1168
- stack = stack.withSources();
1169
- stack = stack.filter((entry) => {
1170
- return !entry.file.includes("@oclif/core");
1171
- }).map((item) => {
1172
- const fileShortComponents = item.fileShort.split("packages/");
1173
- item.fileShort = fileShortComponents.length === 2 ? fileShortComponents[1] : fileShortComponents[0];
1174
- return item;
1175
- });
1176
- }
1177
- if (error instanceof ExternalError) {
1178
- tool = `${error.command} ${error.args.join(" ")}`;
1179
- }
1180
- return import_react14.default.createElement(
1181
- Banner,
1182
- { type: tool ? "external_error" : "error" },
1183
- tool ? import_react14.default.createElement(
1184
- Text,
1185
- null,
1186
- "Error coming from ",
1187
- import_react14.default.createElement(Command, { command: tool })
1188
- ) : null,
1189
- error.formattedMessage ? import_react14.default.createElement(TokenizedText, { item: error.formattedMessage }) : import_react14.default.createElement(Text, null, error.message),
1190
- error.tryMessage ? import_react14.default.createElement(TokenizedText, { item: error.tryMessage }) : null,
1191
- error.nextSteps && error.nextSteps.length > 0 ? import_react14.default.createElement(List, { title: "Next steps", items: error.nextSteps }) : null,
1192
- error.customSections && error.customSections.length > 0 ? import_react14.default.createElement(Box_default, { flexDirection: "column", gap: 1 }, error.customSections.map((section, index) => import_react14.default.createElement(
1193
- Box_default,
1194
- { key: index, flexDirection: "column" },
1195
- section.title ? import_react14.default.createElement(Text, { bold: true }, section.title) : null,
1196
- import_react14.default.createElement(TokenizedText, { item: section.body })
1197
- ))) : null,
1198
- stack && stack.items.length !== 0 ? import_react14.default.createElement(
1199
- Box_default,
1200
- { flexDirection: "column" },
1201
- import_react14.default.createElement(Text, null, "To investigate the issue, examine this stack trace:"),
1202
- stack.items.map((item, index) => import_react14.default.createElement(
1203
- Box_default,
1204
- { flexDirection: "column", key: index, paddingLeft: 2 },
1205
- import_react14.default.createElement(
1206
- Text,
1207
- null,
1208
- "at",
1209
- item.calleeShort ? import_react14.default.createElement(Text, { color: "yellow" }, ` ${item.calleeShort}`) : null,
1210
- item.fileShort ? ` (${item.fileShort}:${item.line})` : null
1211
- ),
1212
- import_react14.default.createElement(
1213
- Box_default,
1214
- { paddingLeft: 2 },
1215
- import_react14.default.createElement(Text, { dimColor: true }, item.sourceLine?.trim())
1216
- )
1217
- ))
1218
- ) : null
1219
- );
1220
- };
1221
-
1222
- // ../cli-kit/dist/private/node/ui/components/Table/Table.js
1223
- init_cjs_shims();
1224
-
1225
- // ../cli-kit/dist/private/node/ui/components/Table/Row.js
1226
- init_cjs_shims();
1227
- var import_react15 = __toESM(require_react(), 1);
1228
-
1229
- // ../cli-kit/dist/private/node/ui/components/Table/Table.js
1230
- var import_react16 = __toESM(require_react(), 1);
1231
-
1232
- // ../cli-kit/dist/private/node/ui/components/DangerousConfirmationPrompt.js
1233
- init_cjs_shims();
1234
-
1235
- // ../cli-kit/dist/private/node/ui/components/TextInput.js
1236
- init_cjs_shims();
1237
- var import_react17 = __toESM(require_react(), 1);
1238
- var TextInput = ({ value: originalValue, defaultValue = "", onChange, placeholder = "", noColor = !shouldDisplayColors(), color = noColor ? void 0 : "cyan", password = false, focus = true }) => {
1239
- const [cursorOffset, setCursorOffset] = (0, import_react17.useState)((originalValue || "").length);
1240
- (0, import_react17.useEffect)(() => {
1241
- setCursorOffset((previousOffset) => {
1242
- const newValue = originalValue || "";
1243
- if (previousOffset > newValue.length - 1) {
1244
- return newValue.length;
1245
- }
1246
- return previousOffset;
1247
- });
1248
- }, [originalValue]);
1249
- const value = password ? "*".repeat(originalValue.length) : originalValue;
1250
- let renderedValue;
1251
- const renderPlaceholder = (value2) => {
1252
- return source_default.inverse(value2[0]) + source_default.dim(value2.slice(1));
1253
- };
1254
- const cursorChar = figures_default.square;
1255
- const defaultCursor = import_react17.default.createElement(Text, { backgroundColor: color }, cursorChar);
1256
- const placeholderText = defaultValue.length > 0 ? defaultValue : placeholder.length > 0 ? placeholder : "";
1257
- const renderedPlaceholder = placeholderText.length > 0 ? renderPlaceholder(placeholderText) : defaultCursor;
1258
- renderedValue = value.split("").map((char, index) => {
1259
- if (index === cursorOffset) {
1260
- return noColor ? cursorChar : source_default.inverse(char);
1261
- } else {
1262
- return char;
1263
- }
1264
- }).join("");
1265
- if (cursorOffset === value.length) {
1266
- renderedValue = import_react17.default.createElement(
1267
- Text,
1268
- null,
1269
- renderedValue,
1270
- defaultCursor
1271
- );
1272
- }
1273
- use_input_default((input, key) => {
1274
- if (key.upArrow || key.downArrow || key.ctrl && input === "c" || key.shift && key.tab || key.return) {
1275
- return;
1276
- } else if (key.tab) {
1277
- if (originalValue.length === 0 && placeholderText) {
1278
- onChange(placeholderText);
1279
- setCursorOffset(placeholderText.length);
1280
- return;
1281
- }
1282
- }
1283
- let nextCursorOffset = cursorOffset;
1284
- let nextValue = originalValue;
1285
- if (key.leftArrow) {
1286
- if (cursorOffset > 0) {
1287
- nextCursorOffset--;
1288
- }
1289
- } else if (key.rightArrow) {
1290
- if (cursorOffset < originalValue.length) {
1291
- nextCursorOffset++;
1292
- }
1293
- } else if (key.backspace || key.delete) {
1294
- if (cursorOffset > 0) {
1295
- nextValue = originalValue.slice(0, cursorOffset - 1) + originalValue.slice(cursorOffset, originalValue.length);
1296
- nextCursorOffset--;
1297
- }
1298
- } else {
1299
- nextValue = originalValue.slice(0, cursorOffset) + input + originalValue.slice(cursorOffset, originalValue.length);
1300
- nextCursorOffset += input.length;
1301
- }
1302
- setCursorOffset(nextCursorOffset);
1303
- if (nextValue !== originalValue) {
1304
- onChange(nextValue);
1305
- }
1306
- }, { isActive: focus });
1307
- return import_react17.default.createElement(Text, { color }, value.length > 0 ? renderedValue : renderedPlaceholder);
1308
- };
1309
-
1310
- // ../cli-kit/dist/private/node/ui/components/Prompts/InfoTable.js
1311
- init_cjs_shims();
1312
- var import_react18 = __toESM(require_react(), 1);
1313
- var InfoTable = ({ table }) => {
1314
- const sections = Array.isArray(table) ? table : Object.keys(table).map((header) => ({
1315
- header,
1316
- items: table[header],
1317
- color: void 0,
1318
- helperText: void 0,
1319
- bullet: void 0,
1320
- emptyItemsText: void 0
1321
- }));
1322
- const headerColumnWidth = Math.max(...sections.map((section) => {
1323
- return Math.max(...section.header.split("\n").map((line) => {
1324
- return line.length;
1325
- }));
1326
- }));
1327
- return import_react18.default.createElement(Box_default, { flexDirection: "column" }, sections.map((section, index) => import_react18.default.createElement(
1328
- Box_default,
1329
- { key: index, marginBottom: index === sections.length - 1 ? 0 : 1, flexDirection: "column" },
1330
- section.header.length > 0 && import_react18.default.createElement(
1331
- Box_default,
1332
- { width: headerColumnWidth + 1 },
1333
- import_react18.default.createElement(Text, { color: section.color, bold: true }, capitalize(section.header))
1334
- ),
1335
- import_react18.default.createElement(
1336
- Box_default,
1337
- { flexGrow: 1, flexDirection: "column", gap: 1 },
1338
- section.emptyItemsText && section.items.length === 0 ? import_react18.default.createElement(
1339
- Text,
1340
- { color: section.color },
1341
- import_react18.default.createElement(TokenizedText, { item: { subdued: section.emptyItemsText } })
1342
- ) : import_react18.default.createElement(List, { margin: false, items: section.items, color: section.color, bullet: section.bullet }),
1343
- section.helperText ? import_react18.default.createElement(Text, { color: section.color }, section.helperText) : null
1344
- )
1345
- )));
1346
- };
1347
-
1348
- // ../cli-kit/dist/private/node/ui/utilities.js
1349
- init_cjs_shims();
1350
- function messageWithPunctuation(message) {
1351
- const messageToString = tokenItemToString(message);
1352
- return messageToString.endsWith("?") || messageToString.endsWith(":") || messageToString.endsWith(".") ? message : appendToTokenItem(message, ":");
1353
- }
1354
-
1355
- // ../cli-kit/dist/private/node/ui/hooks/use-abort-signal.js
1356
- init_cjs_shims();
1357
- var import_react19 = __toESM(require_react(), 1);
1358
- var noop = () => Promise.resolve();
1359
- function useAbortSignal(abortSignal, onAbort = noop) {
1360
- const { exit: unmountInk } = use_app_default();
1361
- const [isAborted, setIsAborted] = (0, import_react19.useState)(false);
1362
- (0, import_react19.useLayoutEffect)(() => {
1363
- abortSignal?.addEventListener("abort", () => {
1364
- const abortWithError = abortSignal?.reason.message === "AbortError" ? void 0 : abortSignal?.reason;
1365
- onAbort(abortWithError).then(() => {
1366
- setIsAborted(true);
1367
- unmountInk(abortWithError);
1368
- }).catch(() => {
1369
- });
1370
- });
1371
- }, []);
1372
- return { isAborted };
1373
- }
1374
-
1375
- // ../cli-kit/dist/private/node/ui/hooks/use-prompt.js
1376
- init_cjs_shims();
1377
- var import_react20 = __toESM(require_react(), 1);
1378
- var PromptState;
1379
- (function(PromptState2) {
1380
- PromptState2["Idle"] = "idle";
1381
- PromptState2["Loading"] = "loading";
1382
- PromptState2["Submitted"] = "submitted";
1383
- PromptState2["Error"] = "error";
1384
- PromptState2["Cancelled"] = "cancelled";
1385
- })(PromptState || (PromptState = {}));
1386
- function usePrompt({ initialAnswer }) {
1387
- const [promptState, setPromptState] = (0, import_react20.useState)(PromptState.Idle);
1388
- const [answer, setAnswer] = (0, import_react20.useState)(initialAnswer);
1389
- return {
1390
- promptState,
1391
- setPromptState,
1392
- answer,
1393
- setAnswer
1394
- };
1395
- }
1396
-
1397
- // ../cli-kit/dist/private/node/ui/components/DangerousConfirmationPrompt.js
1398
- var import_react21 = __toESM(require_react(), 1);
1399
-
1400
- // ../cli-kit/dist/private/node/ui/components/SelectPrompt.js
1401
- init_cjs_shims();
1402
-
1403
- // ../cli-kit/dist/private/node/ui/components/SelectInput.js
1404
- init_cjs_shims();
1405
-
1406
- // ../cli-kit/dist/private/node/ui/components/Scrollbar.js
1407
- init_cjs_shims();
1408
- var import_react22 = __toESM(require_react(), 1);
1409
- var BACKGROUND_CHAR = "\u2502";
1410
- var SCROLLBOX_CHAR = "\u2551";
1411
- var Scrollbar = ({ containerHeight, visibleListSectionLength, fullListLength, visibleFromIndex, noColor = !shouldDisplayColors() }) => {
1412
- const displayArrows = containerHeight >= 4 && noColor;
1413
- const visibleToIndex = visibleFromIndex + visibleListSectionLength - 1;
1414
- const fullHeight = displayArrows ? containerHeight - 2 : containerHeight;
1415
- const scrollboxHeight = Math.min(fullHeight - 1, Math.ceil(Math.min(1, visibleListSectionLength / fullListLength) * fullHeight));
1416
- let topBuffer;
1417
- if (visibleToIndex >= fullListLength - 1) {
1418
- topBuffer = fullHeight - scrollboxHeight;
1419
- } else {
1420
- const scrollingLength = fullHeight - scrollboxHeight;
1421
- const scrollableIncrements = fullListLength - visibleListSectionLength;
1422
- topBuffer = Math.max(
1423
- // Never go negative, that causes errors!
1424
- 0,
1425
- Math.min(
1426
- // Never have more buffer than filling in all spaces above the scrollbox
1427
- fullHeight - scrollboxHeight,
1428
- Math.round(visibleFromIndex / scrollableIncrements * scrollingLength)
1429
- )
1430
- );
1431
- }
1432
- const bottomBuffer = fullHeight - scrollboxHeight - topBuffer;
1433
- const backgroundChar = noColor ? BACKGROUND_CHAR : " ";
1434
- const scrollboxChar = noColor ? SCROLLBOX_CHAR : " ";
1435
- const bgColor = noColor ? void 0 : "gray";
1436
- const scrollboxColor = noColor ? void 0 : "cyan";
1437
- return import_react22.default.createElement(
1438
- Box_default,
1439
- { flexDirection: "column" },
1440
- displayArrows ? import_react22.default.createElement(Text, null, "\u25B3") : null,
1441
- import_react22.default.createElement(
1442
- Box_default,
1443
- { width: 1 },
1444
- import_react22.default.createElement(Text, { backgroundColor: bgColor }, backgroundChar.repeat(topBuffer))
1445
- ),
1446
- import_react22.default.createElement(
1447
- Box_default,
1448
- { width: 1 },
1449
- import_react22.default.createElement(Text, { backgroundColor: scrollboxColor }, scrollboxChar.repeat(scrollboxHeight))
1450
- ),
1451
- import_react22.default.createElement(
1452
- Box_default,
1453
- { width: 1 },
1454
- import_react22.default.createElement(Text, { backgroundColor: bgColor }, backgroundChar.repeat(bottomBuffer))
1455
- ),
1456
- displayArrows ? import_react22.default.createElement(Text, null, "\u25BD") : null
1457
- );
1458
- };
1459
-
1460
- // ../cli-kit/dist/private/node/ui/hooks/use-select-state.js
1461
- init_cjs_shims();
1462
- var import_react23 = __toESM(require_react(), 1);
1463
- import { isDeepStrictEqual } from "node:util";
1464
- var OptionMap = class extends Map {
1465
- constructor(options) {
1466
- const items = [];
1467
- let firstItem;
1468
- let previous;
1469
- let index = 0;
1470
- for (const option of options) {
1471
- const item = {
1472
- ...option,
1473
- previous,
1474
- next: void 0,
1475
- index
1476
- };
1477
- if (previous) {
1478
- previous.next = item;
1479
- }
1480
- if (!firstItem) {
1481
- firstItem = item;
1482
- }
1483
- items.push([option.value, item]);
1484
- index++;
1485
- previous = item;
1486
- }
1487
- super(items);
1488
- this.first = firstItem;
1489
- }
1490
- };
1491
- var reducer = (state, action) => {
1492
- switch (action.type) {
1493
- case "select-next-option": {
1494
- if (typeof state.value === "undefined") {
1495
- return state;
1496
- }
1497
- const item = state.optionMap.get(state.value);
1498
- if (!item) {
1499
- return state;
1500
- }
1501
- let next = item.next;
1502
- while (next && next.disabled) {
1503
- next = next.next;
1504
- }
1505
- if (!next) {
1506
- return state;
1507
- }
1508
- const needsToScroll = next.index > state.visibleToIndex;
1509
- if (!needsToScroll) {
1510
- return {
1511
- ...state,
1512
- value: next.value
1513
- };
1514
- }
1515
- const nextVisibleToIndex = next.index;
1516
- const nextVisibleFromIndex = nextVisibleToIndex - state.visibleOptionCount + 1;
1517
- return {
1518
- ...state,
1519
- value: next.value,
1520
- visibleFromIndex: nextVisibleFromIndex,
1521
- visibleToIndex: nextVisibleToIndex,
1522
- previousValue: state.value
1523
- };
1524
- }
1525
- case "select-previous-option": {
1526
- if (typeof state.value === "undefined") {
1527
- return state;
1528
- }
1529
- const item = state.optionMap.get(state.value);
1530
- if (!item) {
1531
- return state;
1532
- }
1533
- let previous = item.previous;
1534
- while (previous && previous.disabled) {
1535
- previous = previous.previous;
1536
- }
1537
- if (!previous) {
1538
- return state;
1539
- }
1540
- const needsToScroll = previous.index < state.visibleFromIndex;
1541
- if (!needsToScroll) {
1542
- return {
1543
- ...state,
1544
- value: previous.value
1545
- };
1546
- }
1547
- const nextVisibleFromIndex = previous.index;
1548
- const nextVisibleToIndex = nextVisibleFromIndex + state.visibleOptionCount - 1;
1549
- return {
1550
- ...state,
1551
- value: previous.value,
1552
- visibleFromIndex: nextVisibleFromIndex,
1553
- visibleToIndex: nextVisibleToIndex,
1554
- previousValue: state.value
1555
- };
1556
- }
1557
- case "select-option": {
1558
- const item = state.optionMap.get(action.option.value);
1559
- if (!item) {
1560
- return state;
1561
- }
1562
- return {
1563
- ...state,
1564
- value: item.value,
1565
- previousValue: state.value
1566
- };
1567
- }
1568
- case "reset": {
1569
- return action.state;
1570
- }
1571
- default: {
1572
- return state;
1573
- }
1574
- }
1575
- };
1576
- var createDefaultState = ({ visibleOptionCount: customVisibleOptionCount, defaultValue, options }) => {
1577
- const visibleOptionCount = typeof customVisibleOptionCount === "number" ? Math.min(customVisibleOptionCount, options.length) : options.length;
1578
- const optionMap = new OptionMap(options);
1579
- const defaultOption = typeof defaultValue === "undefined" ? void 0 : optionMap.get(defaultValue);
1580
- let option = defaultOption && !defaultOption.disabled ? defaultOption : optionMap.first;
1581
- while (option && option.disabled) {
1582
- option = option.next;
1583
- }
1584
- return {
1585
- optionMap,
1586
- visibleOptionCount,
1587
- visibleFromIndex: 0,
1588
- visibleToIndex: visibleOptionCount - 1,
1589
- value: option?.value,
1590
- previousValue: option?.value
1591
- };
1592
- };
1593
- var useSelectState = ({ visibleOptionCount, options, defaultValue }) => {
1594
- const [state, dispatch] = (0, import_react23.useReducer)(reducer, { visibleOptionCount, defaultValue, options }, createDefaultState);
1595
- const [lastOptions, setLastOptions] = (0, import_react23.useState)(options);
1596
- const [lastVisibleOptionCount, setLastVisibleOptionCount] = (0, import_react23.useState)(visibleOptionCount);
1597
- if (options !== lastOptions && !isDeepStrictEqual(options, lastOptions)) {
1598
- dispatch({
1599
- type: "reset",
1600
- state: createDefaultState({ visibleOptionCount, defaultValue, options })
1601
- });
1602
- setLastOptions(options);
1603
- }
1604
- if (visibleOptionCount !== lastVisibleOptionCount) {
1605
- dispatch({
1606
- type: "reset",
1607
- state: createDefaultState({ visibleOptionCount, defaultValue, options })
1608
- });
1609
- setLastVisibleOptionCount(visibleOptionCount);
1610
- }
1611
- const selectNextOption = (0, import_react23.useCallback)(() => {
1612
- dispatch({
1613
- type: "select-next-option"
1614
- });
1615
- }, []);
1616
- const selectPreviousOption = (0, import_react23.useCallback)(() => {
1617
- dispatch({
1618
- type: "select-previous-option"
1619
- });
1620
- }, []);
1621
- const selectOption = (0, import_react23.useCallback)(({ option }) => {
1622
- dispatch({
1623
- type: "select-option",
1624
- option
1625
- });
1626
- }, []);
1627
- const visibleOptions = (0, import_react23.useMemo)(() => {
1628
- return options.slice(state.visibleFromIndex);
1629
- }, [options, state.visibleFromIndex]);
1630
- return {
1631
- visibleFromIndex: state.visibleFromIndex,
1632
- visibleToIndex: state.visibleToIndex,
1633
- value: state.value,
1634
- visibleOptions,
1635
- selectNextOption,
1636
- selectPreviousOption,
1637
- selectOption,
1638
- previousValue: state.previousValue
1639
- };
1640
- };
1641
-
1642
- // ../cli-kit/dist/private/node/ui/components/SelectInput.js
1643
- var import_react24 = __toESM(require_react(), 1);
1644
- var import_sortBy = __toESM(require_sortBy(), 1);
1645
- function highlightedLabel(label, term) {
1646
- if (!term) {
1647
- return label;
1648
- }
1649
- const regex = new RegExp(term, "i");
1650
- return label.replace(regex, (match) => {
1651
- return source_default.bold(match);
1652
- });
1653
- }
1654
- function validateKeys(items) {
1655
- if (items.some((item) => (item.key?.length ?? 0) > 1)) {
1656
- throw new Error("SelectInput: Keys must be a single character");
1657
- }
1658
- if (!items.every((item) => typeof item.key !== "undefined" && item.key.length > 0)) {
1659
- throw new Error("SelectInput: All items must have keys if one does");
1660
- }
1661
- }
1662
- function Item({ item, previousItem, isSelected, highlightedTerm, enableShortcuts, items, hasAnyGroup, index }) {
1663
- const label = highlightedLabel(item.label, highlightedTerm);
1664
- let title;
1665
- let labelColor;
1666
- if (isSelected) {
1667
- labelColor = "cyan";
1668
- } else if (item.disabled) {
1669
- labelColor = "dim";
1670
- }
1671
- if (typeof previousItem === "undefined" || item.group !== previousItem.group) {
1672
- title = item.group ?? (hasAnyGroup ? "Other" : void 0);
1673
- }
1674
- const showKey = enableShortcuts && item.key && item.key.length > 0;
1675
- return import_react24.default.createElement(
1676
- Box_default,
1677
- { key: index, flexDirection: "column", marginTop: items.indexOf(item) !== 0 && title ? 1 : 0, minHeight: title ? 2 : 1 },
1678
- title ? import_react24.default.createElement(
1679
- Box_default,
1680
- { marginLeft: 3 },
1681
- import_react24.default.createElement(Text, { bold: true }, title)
1682
- ) : null,
1683
- import_react24.default.createElement(
1684
- Box_default,
1685
- { key: index, marginLeft: hasAnyGroup ? 3 : 0 },
1686
- import_react24.default.createElement(Box_default, { marginRight: 2 }, isSelected ? import_react24.default.createElement(Text, { color: "cyan" }, `>`) : import_react24.default.createElement(Text, null, " ")),
1687
- import_react24.default.createElement(Text, { color: labelColor }, showKey ? `(${item.key}) ${label}` : label)
1688
- )
1689
- );
1690
- }
1691
- var MAX_AVAILABLE_LINES = 25;
1692
- function SelectInputInner({ items: rawItems, initialItems = rawItems, onChange, enableShortcuts = true, focus = true, emptyMessage = "No items to select.", defaultValue, highlightedTerm, loading = false, errorMessage, hasMorePages = false, morePagesMessage, availableLines = MAX_AVAILABLE_LINES, onSubmit, inputFixedAreaRef }, ref) {
1693
- let noItems = false;
1694
- if (rawItems.length === 0) {
1695
- rawItems = [{ label: emptyMessage, value: null, disabled: true }];
1696
- noItems = true;
1697
- }
1698
- const hasAnyGroup = rawItems.some((item) => typeof item.group !== "undefined");
1699
- const items = (0, import_sortBy.default)(rawItems, "group");
1700
- const itemsHaveKeys = items.some((item) => typeof item.key !== "undefined" && item.key.length > 0);
1701
- if (itemsHaveKeys)
1702
- validateKeys(items);
1703
- const availableLinesToUse = Math.min(availableLines, MAX_AVAILABLE_LINES);
1704
- function maximumLinesLostToGroups(items2) {
1705
- const numberOfGroups = new Set(items2.map((item) => item.group).filter((group) => group)).size;
1706
- const maxVisibleGroups = Math.ceil(Math.min((availableLinesToUse + 1) / 3, numberOfGroups + 1));
1707
- return numberOfGroups > 0 ? (maxVisibleGroups - 1) * 2 + 1 : 0;
1708
- }
1709
- const maxLinesLostToGroups = maximumLinesLostToGroups(items);
1710
- const limit = Math.max(2, availableLinesToUse - maxLinesLostToGroups);
1711
- const hasLimit = items.length > limit;
1712
- const state = useSelectState({
1713
- visibleOptionCount: limit,
1714
- options: items,
1715
- defaultValue
1716
- });
1717
- (0, import_react24.useEffect)(() => {
1718
- if (typeof state.value !== "undefined" && state.previousValue !== state.value) {
1719
- onChange?.(items.find((item) => item.value === state.value));
1720
- }
1721
- }, [state.previousValue, state.value, items, onChange]);
1722
- const handleArrows = (key) => {
1723
- if (key.upArrow) {
1724
- state.selectPreviousOption();
1725
- } else if (key.downArrow) {
1726
- state.selectNextOption();
1727
- }
1728
- };
1729
- const handleShortcuts = (0, import_react24.useCallback)((input) => {
1730
- if (state.visibleOptions.map((item) => item.key).includes(input)) {
1731
- const itemWithKey = state.visibleOptions.find((item2) => item2.key === input);
1732
- const item = items.find((item2) => item2.value === itemWithKey?.value);
1733
- if (itemWithKey && !itemWithKey.disabled) {
1734
- if (onSubmit && item) {
1735
- onSubmit(item);
1736
- }
1737
- state.selectOption({ option: itemWithKey });
1738
- }
1739
- }
1740
- }, [items, onSubmit, state]);
1741
- use_input_default((input, key) => {
1742
- handleCtrlC(input, key);
1743
- if (typeof state.value !== "undefined" && key.return) {
1744
- const item = items.find((item2) => item2.value === state.value);
1745
- if (item && onSubmit) {
1746
- onSubmit(item);
1747
- }
1748
- }
1749
- if (enableShortcuts && input.length > 0 && Object.values(key).every((value) => value === false)) {
1750
- handleShortcuts(input);
1751
- } else {
1752
- handleArrows(key);
1753
- }
1754
- }, { isActive: focus });
1755
- const { twoThirds } = useLayout();
1756
- if (loading) {
1757
- return import_react24.default.createElement(
1758
- Box_default,
1759
- { marginLeft: 3 },
1760
- import_react24.default.createElement(Text, { dimColor: true }, "Loading...")
1761
- );
1762
- } else if (errorMessage && errorMessage.length > 0) {
1763
- return import_react24.default.createElement(
1764
- Box_default,
1765
- { marginLeft: 3 },
1766
- import_react24.default.createElement(Text, { color: "red" }, errorMessage)
1767
- );
1768
- } else {
1769
- const optionsHeight = initialItems.length + maximumLinesLostToGroups(initialItems);
1770
- const minHeight = hasAnyGroup ? 5 : 2;
1771
- const sectionHeight = Math.max(minHeight, Math.min(availableLinesToUse, optionsHeight));
1772
- return import_react24.default.createElement(
1773
- Box_default,
1774
- { flexDirection: "column", ref, gap: 1, width: twoThirds },
1775
- import_react24.default.createElement(
1776
- Box_default,
1777
- { flexDirection: "row", height: sectionHeight, width: "100%" },
1778
- import_react24.default.createElement(Box_default, { flexDirection: "column", overflowY: "hidden", flexGrow: 1 }, state.visibleOptions.map((item, index) => import_react24.default.createElement(Item, { key: index, item, previousItem: state.visibleOptions[index - 1], highlightedTerm, isSelected: item.value === state.value, items: state.visibleOptions, enableShortcuts, hasAnyGroup, index }))),
1779
- hasLimit ? import_react24.default.createElement(Scrollbar, { containerHeight: sectionHeight, visibleListSectionLength: limit, fullListLength: items.length, visibleFromIndex: state.visibleFromIndex }) : null
1780
- ),
1781
- import_react24.default.createElement(Box_default, { ref: inputFixedAreaRef }, noItems ? import_react24.default.createElement(
1782
- Box_default,
1783
- { marginLeft: 3 },
1784
- import_react24.default.createElement(Text, { dimColor: true }, "Try again with a different keyword.")
1785
- ) : import_react24.default.createElement(
1786
- Box_default,
1787
- { marginLeft: 3, flexDirection: "column" },
1788
- import_react24.default.createElement(Text, { dimColor: true }, `Press ${figures_default.arrowUp}${figures_default.arrowDown} arrows to select, enter ${itemsHaveKeys ? "or a shortcut " : ""}to confirm.`),
1789
- hasMorePages ? import_react24.default.createElement(
1790
- Text,
1791
- null,
1792
- import_react24.default.createElement(
1793
- Text,
1794
- { bold: true },
1795
- "1-",
1796
- items.length,
1797
- " of many"
1798
- ),
1799
- morePagesMessage ? ` ${morePagesMessage}` : null
1800
- ) : null
1801
- ))
1802
- );
1803
- }
1804
- }
1805
- var SelectInput = (0, import_react24.forwardRef)(SelectInputInner);
1806
-
1807
- // ../cli-kit/dist/private/node/ui/components/Prompts/PromptLayout.js
1808
- init_cjs_shims();
1809
-
1810
- // ../cli-kit/dist/private/node/ui/components/Prompts/InfoMessage.js
1811
- init_cjs_shims();
1812
- var import_react25 = __toESM(require_react(), 1);
1813
- var InfoMessage = ({ message: { title: { color, text: title }, body } }) => {
1814
- return import_react25.default.createElement(
1815
- Box_default,
1816
- { flexDirection: "column", gap: 1 },
1817
- import_react25.default.createElement(
1818
- Text,
1819
- { color },
1820
- import_react25.default.createElement(TokenizedText, { item: title })
1821
- ),
1822
- import_react25.default.createElement(TokenizedText, { item: body })
1823
- );
1824
- };
1825
-
1826
- // ../cli-kit/dist/private/node/ui/components/Prompts/PromptLayout.js
1827
- var import_react26 = __toESM(require_react(), 1);
1828
- var PromptLayout = ({ message, infoTable, abortSignal, infoMessage, header, state, input, submittedAnswerLabel }) => {
1829
- const { stdout } = use_stdout_default();
1830
- const [wrapperHeight, setWrapperHeight] = (0, import_react26.useState)(0);
1831
- const [promptAreaHeight, setPromptAreaHeight] = (0, import_react26.useState)(0);
1832
- const [inputFixedAreaHeight, setInputFixedAreaHeight] = (0, import_react26.useState)(0);
1833
- const currentAvailableLines = stdout.rows - promptAreaHeight - inputFixedAreaHeight;
1834
- const [availableLines, setAvailableLines] = (0, import_react26.useState)(currentAvailableLines);
1835
- const wrapperRef = (0, import_react26.useCallback)((node) => {
1836
- if (node !== null) {
1837
- const { height } = measure_element_default(node);
1838
- if (wrapperHeight !== height) {
1839
- setWrapperHeight(height);
1840
- }
1841
- }
1842
- }, [wrapperHeight]);
1843
- const promptAreaRef = (0, import_react26.useCallback)((node) => {
1844
- if (node !== null) {
1845
- const { height } = measure_element_default(node);
1846
- setPromptAreaHeight(height);
1847
- }
1848
- }, []);
1849
- const inputFixedAreaRef = (0, import_react26.useCallback)((node) => {
1850
- if (node !== null) {
1851
- const { height } = measure_element_default(node);
1852
- setInputFixedAreaHeight(height + 3);
1853
- }
1854
- }, []);
1855
- const inputComponent = (0, import_react26.cloneElement)(input, { availableLines, inputFixedAreaRef });
1856
- (0, import_react26.useLayoutEffect)(() => {
1857
- function onResize() {
1858
- const newAvailableLines = stdout.rows - promptAreaHeight - inputFixedAreaHeight;
1859
- if (newAvailableLines !== availableLines) {
1860
- setAvailableLines(newAvailableLines);
1861
- }
1862
- }
1863
- onResize();
1864
- stdout.on("resize", onResize);
1865
- return () => {
1866
- stdout.off("resize", onResize);
1867
- };
1868
- }, [wrapperHeight, promptAreaHeight, stdout, availableLines, inputFixedAreaHeight]);
1869
- const { isAborted } = useAbortSignal(abortSignal);
1870
- const showInfoTable = infoTable && Object.keys(infoTable).length > 0;
1871
- return isAborted ? null : import_react26.default.createElement(
1872
- Box_default,
1873
- { flexDirection: "column", marginBottom: 1, ref: wrapperRef },
1874
- import_react26.default.createElement(
1875
- Box_default,
1876
- { ref: promptAreaRef, flexDirection: "column" },
1877
- import_react26.default.createElement(
1878
- Box_default,
1879
- null,
1880
- import_react26.default.createElement(
1881
- Box_default,
1882
- { marginRight: 2 },
1883
- import_react26.default.createElement(Text, null, "?")
1884
- ),
1885
- import_react26.default.createElement(TokenizedText, { item: messageWithPunctuation(message) }),
1886
- header
1887
- ),
1888
- (showInfoTable || infoMessage) && state !== PromptState.Submitted ? import_react26.default.createElement(
1889
- Box_default,
1890
- { marginTop: 1, marginLeft: 3, paddingLeft: 2, borderStyle: "bold", borderLeft: true, borderRight: false, borderTop: false, borderBottom: false, flexDirection: "column", gap: 1 },
1891
- infoMessage ? import_react26.default.createElement(InfoMessage, { message: infoMessage }) : null,
1892
- showInfoTable ? import_react26.default.createElement(InfoTable, { table: infoTable }) : null
1893
- ) : null
1894
- ),
1895
- state === PromptState.Submitted && submittedAnswerLabel ? import_react26.default.createElement(
1896
- Box_default,
1897
- null,
1898
- import_react26.default.createElement(
1899
- Box_default,
1900
- { marginRight: 2 },
1901
- import_react26.default.createElement(Text, { color: "cyan" }, figures_default.tick)
1902
- ),
1903
- import_react26.default.createElement(Text, { color: "cyan" }, submittedAnswerLabel)
1904
- ) : import_react26.default.createElement(Box_default, { marginTop: 1 }, inputComponent)
1905
- );
1906
- };
1907
-
1908
- // ../cli-kit/dist/private/node/ui/components/SelectPrompt.js
1909
- var import_react27 = __toESM(require_react(), 1);
1910
- function SelectPrompt({ message, choices, infoTable, infoMessage, onSubmit, defaultValue, abortSignal }) {
1911
- if (choices.length === 0) {
1912
- throw new Error("SelectPrompt requires at least one choice");
1913
- }
1914
- const { exit: unmountInk } = use_app_default();
1915
- const { promptState, setPromptState, answer, setAnswer } = usePrompt({
1916
- initialAnswer: void 0
1917
- });
1918
- const submitAnswer = (0, import_react27.useCallback)((answer2) => {
1919
- setAnswer(answer2);
1920
- setPromptState(PromptState.Submitted);
1921
- }, [setAnswer, setPromptState]);
1922
- (0, import_react27.useEffect)(() => {
1923
- if (promptState === PromptState.Submitted && answer) {
1924
- unmountInk();
1925
- onSubmit(answer.value);
1926
- }
1927
- }, [answer, onSubmit, promptState, unmountInk]);
1928
- return import_react27.default.createElement(PromptLayout, { message, state: promptState, submittedAnswerLabel: answer?.label, infoTable, infoMessage, abortSignal, input: import_react27.default.createElement(SelectInput, { defaultValue, items: choices, onSubmit: submitAnswer }) });
1929
- }
1930
-
1931
- // ../cli-kit/dist/private/node/ui/components/Tasks.js
1932
- init_cjs_shims();
1933
-
1934
- // ../cli-kit/dist/private/node/ui/components/TextAnimation.js
1935
- init_cjs_shims();
1936
- var import_react28 = __toESM(require_react(), 1);
1937
- var import_gradient_string = __toESM(require_gradient_string(), 1);
1938
- function rainbow(text, frame) {
1939
- const hue = 5 * frame;
1940
- const leftColor = { h: hue % 360, s: 0.8, v: 1 };
1941
- const rightColor = { h: (hue + 1) % 360, s: 0.8, v: 1 };
1942
- return (0, import_gradient_string.default)(leftColor, rightColor)(text, { interpolation: "hsv", hsvSpin: "long" });
1943
- }
1944
- var TextAnimation = (0, import_react28.memo)(({ text }) => {
1945
- const frame = (0, import_react28.useRef)(0);
1946
- const [renderedFrame, setRenderedFrame] = (0, import_react28.useState)(text);
1947
- const timeout = (0, import_react28.useRef)();
1948
- const renderAnimation = (0, import_react28.useCallback)(() => {
1949
- const newFrame = frame.current + 1;
1950
- frame.current = newFrame;
1951
- setRenderedFrame(rainbow(text, frame.current));
1952
- timeout.current = setTimeout(() => {
1953
- renderAnimation();
1954
- }, 35);
1955
- }, [text]);
1956
- (0, import_react28.useLayoutEffect)(() => {
1957
- renderAnimation();
1958
- return () => {
1959
- clearTimeout(timeout.current);
1960
- };
1961
- }, [renderAnimation]);
1962
- return import_react28.default.createElement(Text, null, renderedFrame);
1963
- });
1964
- TextAnimation.displayName = "TextAnimation";
1965
-
1966
- // ../cli-kit/dist/private/node/ui/hooks/use-async-and-unmount.js
1967
- init_cjs_shims();
1968
- var import_react29 = __toESM(require_react(), 1);
1969
- function useAsyncAndUnmount(asyncFunction, { onFulfilled = () => {
1970
- }, onRejected = () => {
1971
- } } = {}) {
1972
- const { exit: unmountInk } = use_app_default();
1973
- (0, import_react29.useEffect)(() => {
1974
- asyncFunction().then(() => {
1975
- onFulfilled();
1976
- unmountInk();
1977
- }).catch((error) => {
1978
- onRejected(error);
1979
- unmountInk(error);
1980
- });
1981
- }, []);
1982
- }
1983
-
1984
- // ../cli-kit/dist/private/node/ui/components/Tasks.js
1985
- var import_react30 = __toESM(require_react(), 1);
1986
- var loadingBarChar = "\u2580";
1987
- var TasksState;
1988
- (function(TasksState2) {
1989
- TasksState2["Loading"] = "loading";
1990
- TasksState2["Success"] = "success";
1991
- TasksState2["Failure"] = "failure";
1992
- })(TasksState || (TasksState = {}));
1993
- async function runTask(task, ctx) {
1994
- task.retryCount = 0;
1995
- task.errors = [];
1996
- const retry = task?.retry && task?.retry > 0 ? task.retry + 1 : 1;
1997
- for (let retries = 1; retries <= retry; retries++) {
1998
- try {
1999
- if (task.skip?.(ctx)) {
2000
- return;
2001
- }
2002
- return await task.task(ctx, task);
2003
- } catch (error) {
2004
- if (retries === retry) {
2005
- throw error;
2006
- } else {
2007
- task.errors.push(error);
2008
- task.retryCount = retries;
2009
- }
2010
- }
2011
- }
2012
- }
2013
- var noop2 = () => {
2014
- };
2015
- function Tasks({ tasks, silent = isUnitTest(), onComplete = noop2, abortSignal }) {
2016
- const { twoThirds } = useLayout();
2017
- const loadingBar = new Array(twoThirds).fill(loadingBarChar).join("");
2018
- const [currentTask, setCurrentTask] = (0, import_react30.useState)(tasks[0]);
2019
- const [state, setState] = (0, import_react30.useState)(TasksState.Loading);
2020
- const ctx = (0, import_react30.useRef)({});
2021
- const { isRawModeSupported } = use_stdin_default();
2022
- const runTasks = async () => {
2023
- for (const task of tasks) {
2024
- setCurrentTask(task);
2025
- const subTasks = await runTask(task, ctx.current);
2026
- if (Array.isArray(subTasks) && subTasks.length > 0 && subTasks.every((task2) => "task" in task2)) {
2027
- for (const subTask of subTasks) {
2028
- setCurrentTask(subTask);
2029
- await runTask(subTask, ctx.current);
2030
- }
2031
- }
2032
- }
2033
- };
2034
- useAsyncAndUnmount(runTasks, {
2035
- onFulfilled: () => {
2036
- setState(TasksState.Success);
2037
- onComplete(ctx.current);
2038
- },
2039
- onRejected: () => {
2040
- setState(TasksState.Failure);
2041
- }
2042
- });
2043
- use_input_default((input, key) => {
2044
- handleCtrlC(input, key);
2045
- if (key.return) {
2046
- return null;
2047
- }
2048
- }, { isActive: Boolean(isRawModeSupported) });
2049
- const { isAborted } = useAbortSignal(abortSignal);
2050
- if (silent) {
2051
- return null;
2052
- }
2053
- return state === TasksState.Loading && !isAborted ? import_react30.default.createElement(
2054
- Box_default,
2055
- { flexDirection: "column" },
2056
- import_react30.default.createElement(TextAnimation, { text: loadingBar }),
2057
- import_react30.default.createElement(
2058
- Text,
2059
- null,
2060
- currentTask.title,
2061
- " ..."
2062
- )
2063
- ) : null;
2064
- }
2065
-
2066
- // ../cli-kit/dist/private/node/ui/components/TextPrompt.js
2067
- init_cjs_shims();
2068
- var import_react31 = __toESM(require_react(), 1);
2069
- var TextPrompt = ({ message, onSubmit, validate, defaultValue = "", password = false, allowEmpty = false, emptyDisplayedValue = "(empty)", abortSignal, preview, initialAnswer = "" }) => {
2070
- if (password && defaultValue) {
2071
- throw new Error("Can't use defaultValue with password");
2072
- }
2073
- const validateAnswer = (0, import_react31.useCallback)((value) => {
2074
- if (validate) {
2075
- return validate(value);
2076
- }
2077
- if (value.length === 0 && !allowEmpty)
2078
- return "Type an answer to the prompt.";
2079
- return void 0;
2080
- }, [allowEmpty, validate]);
2081
- const { oneThird } = useLayout();
2082
- const { promptState, setPromptState, answer, setAnswer } = usePrompt({
2083
- initialAnswer
2084
- });
2085
- const answerOrDefault = answer.length > 0 ? answer : defaultValue;
2086
- const displayEmptyValue = answerOrDefault === "";
2087
- const displayedAnswer = displayEmptyValue ? emptyDisplayedValue : answerOrDefault;
2088
- const { exit: unmountInk } = use_app_default();
2089
- const [error, setError] = (0, import_react31.useState)(void 0);
2090
- const color = promptState === PromptState.Error ? "red" : "cyan";
2091
- const underline = new Array(oneThird - 3).fill("\u2594");
2092
- const { isAborted } = useAbortSignal(abortSignal);
2093
- use_input_default((input, key) => {
2094
- handleCtrlC(input, key);
2095
- if (key.return) {
2096
- const error2 = validateAnswer(answerOrDefault);
2097
- if (error2) {
2098
- setPromptState(PromptState.Error);
2099
- setError(error2);
2100
- } else {
2101
- setPromptState(PromptState.Submitted);
2102
- }
2103
- }
2104
- });
2105
- (0, import_react31.useEffect)(() => {
2106
- if (promptState === PromptState.Submitted) {
2107
- onSubmit(answerOrDefault);
2108
- unmountInk();
2109
- }
2110
- }, [answerOrDefault, onSubmit, promptState, unmountInk]);
2111
- return isAborted ? null : import_react31.default.createElement(
2112
- Box_default,
2113
- { flexDirection: "column", marginBottom: 1, width: oneThird },
2114
- import_react31.default.createElement(
2115
- Box_default,
2116
- null,
2117
- import_react31.default.createElement(
2118
- Box_default,
2119
- { marginRight: 2 },
2120
- import_react31.default.createElement(Text, null, "?")
2121
- ),
2122
- import_react31.default.createElement(TokenizedText, { item: messageWithPunctuation(message) })
2123
- ),
2124
- promptState === PromptState.Submitted ? import_react31.default.createElement(
2125
- Box_default,
2126
- null,
2127
- import_react31.default.createElement(
2128
- Box_default,
2129
- { marginRight: 2 },
2130
- import_react31.default.createElement(Text, { color: "cyan" }, figures_default.tick)
2131
- ),
2132
- import_react31.default.createElement(
2133
- Box_default,
2134
- { flexGrow: 1 },
2135
- import_react31.default.createElement(Text, { color: "cyan", dimColor: displayEmptyValue }, password ? "*".repeat(answer.length) : displayedAnswer)
2136
- )
2137
- ) : import_react31.default.createElement(
2138
- Box_default,
2139
- { flexDirection: "column" },
2140
- import_react31.default.createElement(
2141
- Box_default,
2142
- null,
2143
- import_react31.default.createElement(
2144
- Box_default,
2145
- { marginRight: 2 },
2146
- import_react31.default.createElement(Text, { color }, `>`)
2147
- ),
2148
- import_react31.default.createElement(
2149
- Box_default,
2150
- { flexGrow: 1 },
2151
- import_react31.default.createElement(TextInput, { value: answer, onChange: (answer2) => {
2152
- setAnswer(answer2);
2153
- setPromptState(PromptState.Idle);
2154
- }, defaultValue, color, password })
2155
- )
2156
- ),
2157
- import_react31.default.createElement(
2158
- Box_default,
2159
- { marginLeft: 3 },
2160
- import_react31.default.createElement(Text, { color }, underline)
2161
- ),
2162
- promptState === PromptState.Error ? import_react31.default.createElement(
2163
- Box_default,
2164
- { marginLeft: 3 },
2165
- import_react31.default.createElement(Text, { color }, error)
2166
- ) : null,
2167
- promptState !== PromptState.Error && preview ? import_react31.default.createElement(
2168
- Box_default,
2169
- { marginLeft: 3 },
2170
- import_react31.default.createElement(TokenizedText, { item: preview(answerOrDefault) })
2171
- ) : null
2172
- )
2173
- );
2174
- };
2175
-
2176
- // ../cli-kit/dist/private/node/ui/components/AutocompletePrompt.js
2177
- init_cjs_shims();
2178
-
2179
- // ../cli-kit/dist/public/common/function.js
2180
- init_cjs_shims();
2181
- var import_memoize = __toESM(require_memoize(), 1);
2182
- var import_debounce = __toESM(require_debounce(), 1);
2183
-
2184
- // ../cli-kit/dist/private/node/ui/components/AutocompletePrompt.js
2185
- var import_react32 = __toESM(require_react(), 1);
2186
-
2187
- // ../cli-kit/dist/public/node/ui.js
2188
- var import_react33 = __toESM(require_react(), 1);
2189
- var defaultUIDebugOptions = {
2190
- skipTTYCheck: false
2191
- };
2192
- function renderInfo(options) {
2193
- return alert({ ...options, type: "info" });
2194
- }
2195
- function renderSuccess(options) {
2196
- return alert({ ...options, type: "success" });
2197
- }
2198
- function renderWarning(options) {
2199
- return alert({ ...options, type: "warning" });
2200
- }
2201
- function renderFatalError(error, { renderOptions } = {}) {
2202
- recordUIEvent({
2203
- type: "fatalError",
2204
- properties: { ...error, errorType: error.type === FatalErrorType.Bug ? "bug" : "abort" }
2205
- });
2206
- return renderOnce(import_react33.default.createElement(FatalError, { error }), { logLevel: "error", logger: consoleError, renderOptions });
2207
- }
2208
- async function renderSelectPrompt({ renderOptions, isConfirmationPrompt, ...props }, uiDebugOptions = defaultUIDebugOptions) {
2209
- throwInNonTTY({ message: props.message, stdin: renderOptions?.stdin }, uiDebugOptions);
2210
- if (!isConfirmationPrompt) {
2211
- recordUIEvent({ type: "selectPrompt", properties: { renderOptions, ...props } });
2212
- }
2213
- return runWithTimer("cmd_all_timing_prompts_ms")(async () => {
2214
- let selectedValue;
2215
- try {
2216
- await render(import_react33.default.createElement(SelectPrompt, { ...props, onSubmit: (value) => {
2217
- selectedValue = value;
2218
- } }), {
2219
- ...renderOptions,
2220
- exitOnCtrlC: false
2221
- });
2222
- return selectedValue;
2223
- } finally {
2224
- resetRecordedSleep();
2225
- }
2226
- });
2227
- }
2228
- async function renderConfirmationPrompt({ message, infoTable, confirmationMessage = "Yes, confirm", cancellationMessage = "No, cancel", renderOptions, defaultValue = true, abortSignal, infoMessage }) {
2229
- recordUIEvent({ type: "confirmationPrompt", properties: arguments[0] });
2230
- const choices = [
2231
- {
2232
- label: confirmationMessage,
2233
- value: true,
2234
- key: "y"
2235
- },
2236
- {
2237
- label: cancellationMessage,
2238
- value: false,
2239
- key: "n"
2240
- }
2241
- ];
2242
- return renderSelectPrompt({
2243
- choices,
2244
- message,
2245
- infoTable,
2246
- renderOptions,
2247
- defaultValue,
2248
- isConfirmationPrompt: true,
2249
- abortSignal,
2250
- infoMessage
2251
- });
2252
- }
2253
- async function renderTasks(tasks, { renderOptions } = {}) {
2254
- recordUIEvent({
2255
- type: "taskbar",
2256
- properties: {
2257
- // Rather than timing exactly, pretend each step takes 2 seconds. This
2258
- // should be easy to tweak manually.
2259
- steps: tasks.map((task) => {
2260
- return { title: task.title, duration: 2 };
2261
- })
2262
- }
2263
- });
2264
- return new Promise((resolve2, reject) => {
2265
- render(import_react33.default.createElement(Tasks, { tasks, onComplete: resolve2 }), {
2266
- ...renderOptions,
2267
- exitOnCtrlC: false
2268
- }).then(() => resetRecordedSleep()).catch(reject);
2269
- });
2270
- }
2271
- async function renderTextPrompt({ renderOptions, ...props }, uiDebugOptions = defaultUIDebugOptions) {
2272
- throwInNonTTY({ message: props.message, stdin: renderOptions?.stdin }, uiDebugOptions);
2273
- recordUIEvent({ type: "textPrompt", properties: arguments[0] });
2274
- return runWithTimer("cmd_all_timing_prompts_ms")(async () => {
2275
- let enteredText = "";
2276
- try {
2277
- await render(import_react33.default.createElement(TextPrompt, { ...props, onSubmit: (value) => {
2278
- enteredText = value;
2279
- } }), {
2280
- ...renderOptions,
2281
- exitOnCtrlC: false
2282
- });
2283
- return enteredText;
2284
- } finally {
2285
- resetRecordedSleep();
2286
- }
2287
- });
2288
- }
2289
- var keypress = async (stdin = process.stdin, uiDebugOptions = defaultUIDebugOptions) => {
2290
- throwInNonTTY({ message: "Press any key" }, uiDebugOptions);
2291
- return runWithTimer("cmd_all_timing_prompts_ms")(() => {
2292
- return new Promise((resolve2, reject) => {
2293
- const handler2 = (buffer) => {
2294
- stdin.setRawMode(false);
2295
- const bytes = Array.from(buffer);
2296
- if (bytes.length && bytes[0] === 3) {
2297
- outputDebug2("Canceled keypress, User pressed CTRL+C");
2298
- reject(new AbortSilentError());
2299
- }
2300
- stdin.unref();
2301
- process.nextTick(resolve2);
2302
- };
2303
- stdin.setRawMode(true);
2304
- stdin.once("data", handler2);
2305
- stdin.ref();
2306
- });
2307
- });
2308
- };
2309
- function isTTY({ stdin = void 0, uiDebugOptions = defaultUIDebugOptions }) {
2310
- return Boolean(uiDebugOptions.skipTTYCheck || stdin || terminalSupportsRawMode());
2311
- }
2312
- function throwInNonTTY({ message, stdin = void 0 }, uiDebugOptions) {
2313
- if (isTTY({ stdin, uiDebugOptions }))
2314
- return;
2315
- const promptText = tokenItemToString(message);
2316
- const errorMessage = `Failed to prompt:
2317
-
2318
- ${outputContent2`${outputToken.cyan(promptText)}`.value}
2319
-
2320
- This usually happens when running a command non-interactively, for example in a CI environment, or when piping input from another process.`;
2321
- throw new AbortError(errorMessage, "To resolve this, specify the option in the command, or run the command in an interactive environment such as your local terminal.");
2322
- }
2323
-
2324
- // ../cli-kit/dist/public/node/error.js
2325
- var import_core = __toESM(require_lib(), 1);
2326
- var import_ts_error = __toESM(require_cjs(), 1);
2327
- var FatalErrorType;
2328
- (function(FatalErrorType2) {
2329
- FatalErrorType2[FatalErrorType2["Abort"] = 0] = "Abort";
2330
- FatalErrorType2[FatalErrorType2["AbortSilent"] = 1] = "AbortSilent";
2331
- FatalErrorType2[FatalErrorType2["Bug"] = 2] = "Bug";
2332
- })(FatalErrorType || (FatalErrorType = {}));
2333
- var CancelExecution = class extends Error {
2334
- };
2335
- var FatalError2 = class extends Error {
2336
- /**
2337
- * Creates a new FatalError error.
2338
- *
2339
- * @param message - The error message.
2340
- * @param type - The type of fatal error.
2341
- * @param tryMessage - The message that recommends next steps to the user.
2342
- * You can pass a string a {@link TokenizedString} or a {@link TokenItem}
2343
- * if you need to style the message inside the error Banner component.
2344
- * @param nextSteps - Message to show as "next steps" with suggestions to solve the issue.
2345
- * @param customSections - Custom sections to show in the error banner. To be used if nextSteps is not enough.
2346
- */
2347
- constructor(message, type, tryMessage = null, nextSteps, customSections) {
2348
- const messageIsOutputMessage = typeof message === "string" || "value" in message;
2349
- super(messageIsOutputMessage ? stringifyMessage(message) : tokenItemToString(message));
2350
- if (tryMessage) {
2351
- if (tryMessage instanceof TokenizedString) {
2352
- this.tryMessage = stringifyMessage(tryMessage);
2353
- } else {
2354
- this.tryMessage = tryMessage;
2355
- }
2356
- } else {
2357
- this.tryMessage = null;
2358
- }
2359
- this.type = type;
2360
- this.nextSteps = nextSteps;
2361
- this.customSections = customSections;
2362
- this.skipOclifErrorHandling = true;
2363
- if (!messageIsOutputMessage) {
2364
- this.formattedMessage = message;
2365
- }
2366
- }
2367
- };
2368
- var AbortError = class extends FatalError2 {
2369
- constructor(message, tryMessage = null, nextSteps, customSections) {
2370
- super(message, FatalErrorType.Abort, tryMessage, nextSteps, customSections);
2371
- }
2372
- };
2373
- var ExternalError = class extends FatalError2 {
2374
- constructor(message, command, args, tryMessage = null) {
2375
- super(message, FatalErrorType.Abort, tryMessage);
2376
- this.command = command;
2377
- this.args = args;
2378
- }
2379
- };
2380
- var AbortSilentError = class extends FatalError2 {
2381
- constructor() {
2382
- super("", FatalErrorType.AbortSilent);
2383
- }
2384
- };
2385
- var BugError = class extends FatalError2 {
2386
- constructor(message, tryMessage = null) {
2387
- super(message, FatalErrorType.Bug, tryMessage);
2388
- }
2389
- };
2390
- async function handler(error) {
2391
- let fatal;
2392
- if (isFatal(error)) {
2393
- fatal = error;
2394
- } else if (typeof error === "string") {
2395
- fatal = new BugError(error);
2396
- } else if (error instanceof Error) {
2397
- fatal = new BugError(error.message);
2398
- fatal.stack = error.stack;
2399
- } else {
2400
- const maybeError = error;
2401
- fatal = new BugError(maybeError?.message ?? "Unknown error");
2402
- if (maybeError?.stack) {
2403
- fatal.stack = maybeError?.stack;
2404
- }
2405
- }
2406
- renderFatalError(fatal);
2407
- return Promise.resolve(error);
2408
- }
2409
- function errorMapper(error) {
2410
- if (error instanceof import_core.Errors.CLIError) {
2411
- const mappedError = new AbortError(error.message);
2412
- mappedError.stack = error.stack;
2413
- return Promise.resolve(mappedError);
2414
- } else {
2415
- return Promise.resolve(error);
2416
- }
2417
- }
2418
- function isFatal(error) {
2419
- try {
2420
- return Object.prototype.hasOwnProperty.call(error, "type");
2421
- } catch {
2422
- return false;
2423
- }
2424
- }
2425
- function shouldReportError(error) {
2426
- if (!isFatal(error)) {
2427
- return true;
2428
- }
2429
- if (error.type === FatalErrorType.Bug) {
2430
- return true;
2431
- }
2432
- return false;
2433
- }
2434
- function cleanSingleStackTracePath(filePath) {
2435
- return normalizePath(filePath).replace("file:/", "/").replace(/^\/?[A-Z]:/, "");
2436
- }
2437
-
2438
- // ../cli-kit/dist/public/node/system.js
2439
- async function openURL(url2) {
2440
- const externalOpen = await import("./open-JRS7RW22.js");
2441
- await externalOpen.default(url2);
2442
- }
2443
- async function captureOutput(command, args, options) {
2444
- const result = await buildExec(command, args, options);
2445
- return result.stdout;
2446
- }
2447
- async function exec2(command, args, options) {
2448
- const commandProcess = buildExec(command, args, options);
2449
- if (options?.stderr && options.stderr !== "inherit") {
2450
- commandProcess.stderr?.pipe(options.stderr, { end: false });
2451
- }
2452
- if (options?.stdout && options.stdout !== "inherit") {
2453
- commandProcess.stdout?.pipe(options.stdout, { end: false });
2454
- }
2455
- let aborted = false;
2456
- options?.signal?.addEventListener("abort", () => {
2457
- const pid = commandProcess.pid;
2458
- if (pid) {
2459
- outputDebug2(`Killing process ${pid}: ${command} ${args.join(" ")}`);
2460
- aborted = true;
2461
- treeKill(pid, "SIGTERM");
2462
- }
2463
- });
2464
- try {
2465
- await commandProcess;
2466
- } catch (processError) {
2467
- if (aborted)
2468
- return;
2469
- if (options?.externalErrorHandler) {
2470
- await options?.externalErrorHandler(processError);
2471
- } else {
2472
- const abortError = new ExternalError(processError.message, command, args);
2473
- abortError.stack = processError.stack;
2474
- throw abortError;
2475
- }
2476
- }
2477
- }
2478
- function buildExec(command, args, options) {
2479
- const env = options?.env ?? process.env;
2480
- if (shouldDisplayColors()) {
2481
- env.FORCE_COLOR = "1";
2482
- }
2483
- const commandProcess = execa(command, args, {
2484
- env,
2485
- cwd: options?.cwd,
2486
- input: options?.input,
2487
- stdio: options?.stdio,
2488
- stdin: options?.stdin,
2489
- stdout: options?.stdout === "inherit" ? "inherit" : void 0,
2490
- stderr: options?.stderr === "inherit" ? "inherit" : void 0,
2491
- // Setting this to false makes it possible to kill the main process
2492
- // and all its sub-processes with Ctrl+C on Windows
2493
- windowsHide: false
2494
- });
2495
- outputDebug2(`
2496
- Running system process:
2497
- \xB7 Command: ${command} ${args.join(" ")}
2498
- \xB7 Working directory: ${options?.cwd ?? cwd2()}
2499
- `);
2500
- return commandProcess;
2501
- }
2502
- function terminalSupportsRawMode(stdin, env = process.env) {
2503
- if (isTruthy(env.CI)) {
2504
- return false;
2505
- }
2506
- if (stdin)
2507
- return Boolean(stdin.isTTY);
2508
- return process.stdin.isTTY;
2509
- }
2510
-
2511
- // ../cli-kit/dist/private/node/context/spin-cache.js
2512
- init_cjs_shims();
2513
- var cachedSpinFQDN;
2514
- function getCachedSpinFqdn() {
2515
- return cachedSpinFQDN;
2516
- }
2517
- function setCachedSpinFqdn(fqdn) {
2518
- cachedSpinFQDN = fqdn;
2519
- }
2520
-
2521
- // ../cli-kit/dist/private/node/context/service.js
2522
- init_cjs_shims();
2523
- var Environment;
2524
- (function(Environment2) {
2525
- Environment2["Local"] = "local";
2526
- Environment2["Production"] = "production";
2527
- Environment2["Spin"] = "spin";
2528
- })(Environment || (Environment = {}));
2529
- function serviceEnvironment(env = process.env) {
2530
- const value = env[environmentVariables.serviceEnv];
2531
- if (value === "local") {
2532
- return Environment.Local;
2533
- } else if (value === "spin" || isSpin(env)) {
2534
- return Environment.Spin;
2535
- } else {
2536
- return Environment.Production;
2537
- }
2538
- }
2539
-
2540
- // ../cli-kit/dist/public/node/context/spin.js
2541
- var SpinInstanceNotFoundMessages = (spinInstance, error) => {
2542
- const errorMessage = outputContent2`${outputToken.genericShellCommand(`spin`)} yielded the following error trying to obtain the fully qualified domain name of the Spin instance:
2543
- ${error}
2544
- `;
2545
- let nextSteps;
2546
- if (spinInstance) {
2547
- nextSteps = `Make sure ${spinInstance} is the instance name and not a fully qualified domain name`;
2548
- }
2549
- return { errorMessage, nextSteps };
2550
- };
2551
- var spinFqdnFilePath = "/etc/spin/machine/fqdn";
2552
- async function spinFqdn(env = process.env) {
2553
- let spinFqdn2 = getCachedSpinFqdn();
2554
- if (spinFqdn2)
2555
- return spinFqdn2;
2556
- if (await fileExists(spinFqdnFilePath)) {
2557
- spinFqdn2 = await readFileSync(spinFqdnFilePath).toString();
2558
- } else {
2559
- const spinInstance = await instance(env);
2560
- const showResponse = await show(spinInstance, env);
2561
- spinFqdn2 = showResponse.fqdn;
2562
- }
2563
- setCachedSpinFqdn(spinFqdn2);
2564
- return spinFqdn2;
2565
- }
2566
- async function show(spinInstance, env = process.env) {
2567
- const latest = spinInstance === void 0;
2568
- const args = latest ? ["show", "--latest", "--json"] : ["show", "--json"];
2569
- const output = await captureOutput("spin", args, { env });
2570
- const json = JSON.parse(output);
2571
- if (json.error) {
2572
- const { errorMessage, nextSteps } = SpinInstanceNotFoundMessages(spinInstance, json.error);
2573
- throw new AbortError(errorMessage, nextSteps);
2574
- } else {
2575
- return json;
2576
- }
2577
- }
2578
- function isSpin(env = process.env) {
2579
- return isTruthy(env[environmentVariables.spin]);
2580
- }
2581
- function instance(env = process.env) {
2582
- return env[environmentVariables.spinInstance];
2583
- }
2584
- function isSpinEnvironment(env = process.env) {
2585
- return serviceEnvironment(env) === Environment.Spin;
2586
- }
2587
-
2588
- // ../cli-kit/dist/private/node/context/utilities.js
2589
- init_cjs_shims();
2590
- function isSet(variable) {
2591
- if (variable === void 0 || variable.trim() === "") {
2592
- return false;
2593
- }
2594
- return true;
2595
- }
2596
- function getCIMetadata(envName, envs) {
2597
- switch (envName) {
2598
- case "bitbucket":
2599
- return {
2600
- branch: envs.BITBUCKET_BRANCH,
2601
- build: envs.BITBUCKET_BUILD_NUMBER,
2602
- commitSha: envs.BITBUCKET_COMMIT,
2603
- run: envs.BITBUCKET_BUILD_NUMBER,
2604
- url: `https://bitbucket.org/${envs.BITBUCKET_WORKSPACE}/${envs.BITBUCKET_REPO_SLUG}/pipelines/results/${envs.BITBUCKET_BUILD_NUMBER}`
2605
- };
2606
- case "circleci":
2607
- return {
2608
- actor: envs.CIRCLE_USERNAME,
2609
- branch: envs.CIRCLE_BRANCH,
2610
- build: envs.CIRCLE_BUILD_NUM,
2611
- commitSha: envs.CIRCLE_SHA1,
2612
- run: envs.CIRCLE_WORKFLOW_ID,
2613
- url: envs.CIRCLE_BUILD_URL
2614
- };
2615
- case "github":
2616
- return {
2617
- actor: envs.GITHUB_ACTOR,
2618
- attempt: envs.GITHUB_RUN_ATTEMPT,
2619
- branch: envs.GITHUB_REF_NAME,
2620
- build: envs.GITHUB_RUN_ID,
2621
- commitSha: envs.GITHUB_SHA,
2622
- run: envs.GITHUB_RUN_ID,
2623
- runNumber: envs.GITHUB_RUN_NUMBER,
2624
- url: `${envs.GITHUB_SERVER_URL}/${envs.GITHUB_REPOSITORY}/actions/runs/${envs.GITHUB_RUN_ID}`
2625
- };
2626
- case "gitlab":
2627
- return {
2628
- actor: envs.GITLAB_USER_LOGIN,
2629
- branch: envs.CI_COMMIT_REF_NAME,
2630
- build: envs.CI_PIPELINE_ID,
2631
- commitSha: envs.CI_COMMIT_SHA,
2632
- commitMessage: envs.CI_COMMIT_MESSAGE,
2633
- run: envs.CI_RUNNER_ID,
2634
- url: envs.CI_PIPELINE_URL
2635
- };
2636
- case "buildkite":
2637
- return {
2638
- branch: envs.BUILDKITE_BRANCH,
2639
- build: envs.BUILDKITE_BUILD_NUMBER,
2640
- commitSha: envs.BUILDKITE_COMMIT,
2641
- commitMessage: envs.BUILDKITE_MESSAGE,
2642
- run: envs.BUILDKITE_BUILD_NUMBER,
2643
- url: envs.BUILDKITE_BUILD_URL
2644
- };
2645
- default:
2646
- return {};
2647
- }
2648
- }
2649
-
2650
- // ../cli-kit/dist/public/node/context/local.js
2651
- var import_macaddress = __toESM(require_macaddress(), 1);
2652
- function isTerminalInteractive() {
2653
- return isInteractive();
2654
- }
2655
- function isDevelopment(env = process.env) {
2656
- return env[environmentVariables.env] === "development";
2657
- }
2658
- function isVerbose(env = process.env) {
2659
- return isTruthy(env[environmentVariables.verbose]) || process.argv.includes("--verbose");
2660
- }
2661
- async function isShopify(env = process.env) {
2662
- if (Object.prototype.hasOwnProperty.call(env, environmentVariables.runAsUser)) {
2663
- return !isTruthy(env[environmentVariables.runAsUser]);
2664
- }
2665
- const devInstalled = await fileExists(pathConstants.executables.dev);
2666
- return devInstalled || isSpin(env);
2667
- }
2668
- function isUnitTest(env = process.env) {
2669
- return isTruthy(env[environmentVariables.unitTest]);
2670
- }
2671
- function analyticsDisabled(env = process.env) {
2672
- return isTruthy(env[environmentVariables.noAnalytics]) || isDevelopment(env);
2673
- }
2674
- function alwaysLogAnalytics(env = process.env) {
2675
- return isTruthy(env[environmentVariables.alwaysLogAnalytics]);
2676
- }
2677
- function alwaysLogMetrics(env = process.env) {
2678
- return isTruthy(env[environmentVariables.alwaysLogMetrics]);
2679
- }
2680
- function firstPartyDev(env = process.env) {
2681
- return isTruthy(env[environmentVariables.firstPartyDev]);
2682
- }
2683
- function useDeviceAuth(env = process.env) {
2684
- return isTruthy(env[environmentVariables.deviceAuth]) || isCloudEnvironment(env);
2685
- }
2686
- function isCloudEnvironment(env = process.env) {
2687
- return cloudEnvironment2(env).platform !== "localhost";
2688
- }
2689
- function cloudEnvironment2(env = process.env) {
2690
- if (isSet(env[environmentVariables.codespaces])) {
2691
- return { platform: "codespaces", editor: true };
2692
- }
2693
- if (isSet(env[environmentVariables.gitpod])) {
2694
- return { platform: "gitpod", editor: true };
2695
- }
2696
- if (isSet(env[environmentVariables.cloudShell])) {
2697
- return { platform: "cloudShell", editor: true };
2698
- }
2699
- if (isSpin(env)) {
2700
- return { platform: "spin", editor: false };
2701
- }
2702
- return { platform: "localhost", editor: false };
2703
- }
2704
- async function hasGit() {
2705
- try {
2706
- await exec2("git", ["--version"]);
2707
- return true;
2708
- } catch {
2709
- return false;
2710
- }
2711
- }
2712
- function ciPlatform2(env = process.env) {
2713
- if (isTruthy(env.CI)) {
2714
- let name = "unknown";
2715
- if (isSet(env.BITBUCKET_BUILD_NUMBER)) {
2716
- name = "bitbucket";
2717
- } else if (isTruthy(env.CIRCLECI)) {
2718
- name = "circleci";
2719
- } else if (isSet(env.GITHUB_ACTION)) {
2720
- name = "github";
2721
- } else if (isTruthy(env.GITLAB_CI)) {
2722
- name = "gitlab";
2723
- } else if (isSet(env.BUILDKITE)) {
2724
- name = "buildkite";
2725
- }
2726
- return {
2727
- isCI: true,
2728
- name,
2729
- metadata: getCIMetadata(name, env)
2730
- };
2731
- }
2732
- return {
2733
- isCI: false
2734
- };
2735
- }
2736
- function opentelemetryDomain(env = process.env) {
2737
- if (isSet(env[environmentVariables.otelURL])) {
2738
- return env[environmentVariables.otelURL];
2739
- }
2740
- return "https://otlp-http-production-cli.shopifysvc.com";
2741
- }
2742
-
2743
- // ../cli-kit/dist/public/node/is-global.js
2744
- init_cjs_shims();
2745
- var _isGlobal;
2746
- function currentProcessIsGlobal2(argv = process.argv) {
2747
- if (_isGlobal !== void 0 && !isUnitTest())
2748
- return _isGlobal;
2749
- const path = sniffForPath() ?? cwd2();
2750
- const npmPrefix = execaSync("npm", ["prefix"], { cwd: path }).stdout.trim();
2751
- const binDir = argv[1] ?? "";
2752
- const isLocal = binDir.startsWith(npmPrefix.trim());
2753
- _isGlobal = !isLocal;
2754
- return _isGlobal;
2755
- }
2756
- function inferPackageManagerForGlobalCLI(argv = process.argv) {
2757
- if (!currentProcessIsGlobal2(argv))
2758
- return "unknown";
2759
- const processArgv = argv[1] ?? "";
2760
- if (processArgv.includes("yarn"))
2761
- return "yarn";
2762
- if (processArgv.includes("pnpm"))
2763
- return "pnpm";
2764
- if (processArgv.includes("bun"))
2765
- return "bun";
2766
- return "npm";
2767
- }
2768
-
2769
- // ../cli-kit/dist/public/node/colors.js
2770
- init_cjs_shims();
2771
-
2772
- // ../cli-kit/dist/private/node/content-tokens.js
2773
- init_cjs_shims();
2774
- var ContentToken = class {
2775
- constructor(value) {
2776
- this.value = value;
2777
- }
2778
- };
2779
- var RawContentToken = class extends ContentToken {
2780
- output() {
2781
- return this.value;
2782
- }
2783
- };
2784
- var LinkContentToken = class extends ContentToken {
2785
- constructor(value, link2, fallback) {
2786
- super(value);
2787
- this.link = link2;
2788
- this.fallback = fallback;
2789
- }
2790
- output() {
2791
- const text = source_default.green(stringifyMessage(this.value));
2792
- const url2 = this.link ?? "";
2793
- return terminalLink(text, url2, { fallback: () => this.fallback ?? `${text} ( ${url2} )` });
2794
- }
2795
- };
2796
- var CommandContentToken = class extends ContentToken {
2797
- output() {
2798
- return `\`${source_default.magentaBright(stringifyMessage(this.value))}\``;
2799
- }
2800
- };
2801
- var JsonContentToken = class extends ContentToken {
2802
- output() {
2803
- try {
2804
- return colorJson(stringifyMessage(this.value) ?? {});
2805
- } catch (_) {
2806
- return JSON.stringify(stringifyMessage(this.value) ?? {}, null, 2);
2807
- }
2808
- }
2809
- };
2810
- var LinesDiffContentToken = class extends ContentToken {
2811
- output() {
2812
- return this.value.map((part) => {
2813
- if (part.added) {
2814
- return part.value.split(/\n/).filter((line) => line !== "").map((line) => {
2815
- return source_default.green(`+ ${line}
2816
- `);
2817
- });
2818
- } else if (part.removed) {
2819
- return part.value.split(/\n/).filter((line) => line !== "").map((line) => {
2820
- return source_default.magenta(`- ${line}
2821
- `);
2822
- });
2823
- } else {
2824
- return part.value;
2825
- }
2826
- }).flat();
2827
- }
2828
- };
2829
- var ColorContentToken = class extends ContentToken {
2830
- constructor(value, color) {
2831
- super(value);
2832
- this.color = color;
2833
- }
2834
- output() {
2835
- return this.color(stringifyMessage(this.value));
2836
- }
2837
- };
2838
- var ErrorContentToken = class extends ContentToken {
2839
- output() {
2840
- return source_default.bold.redBright(stringifyMessage(this.value));
2841
- }
2842
- };
2843
- var PathContentToken = class extends ContentToken {
2844
- output() {
2845
- return relativizePath(stringifyMessage(this.value));
2846
- }
2847
- };
2848
- var HeadingContentToken = class extends ContentToken {
2849
- output() {
2850
- return source_default.bold.underline(stringifyMessage(this.value));
2851
- }
2852
- };
2853
- var SubHeadingContentToken = class extends ContentToken {
2854
- output() {
2855
- return source_default.underline(stringifyMessage(this.value));
2856
- }
2857
- };
2858
- var ItalicContentToken = class extends ContentToken {
2859
- output() {
2860
- return source_default.italic(stringifyMessage(this.value));
2861
- }
2862
- };
2863
-
2864
- // ../cli-kit/dist/public/node/output.js
2865
- import { Writable } from "stream";
2866
- var TokenizedString = class {
2867
- constructor(value) {
2868
- this.value = value;
2869
- }
2870
- };
2871
- var outputToken = {
2872
- raw(value) {
2873
- return new RawContentToken(value);
2874
- },
2875
- genericShellCommand(value) {
2876
- return new CommandContentToken(value);
2877
- },
2878
- json(value) {
2879
- return new JsonContentToken(value);
2880
- },
2881
- path(value) {
2882
- return new PathContentToken(value);
2883
- },
2884
- link(value, link2, fallback) {
2885
- return new LinkContentToken(value, link2, fallback);
2886
- },
2887
- heading(value) {
2888
- return new HeadingContentToken(value);
2889
- },
2890
- subheading(value) {
2891
- return new SubHeadingContentToken(value);
2892
- },
2893
- italic(value) {
2894
- return new ItalicContentToken(value);
2895
- },
2896
- errorText(value) {
2897
- return new ErrorContentToken(value);
2898
- },
2899
- cyan(value) {
2900
- return new ColorContentToken(value, source_default.cyan);
2901
- },
2902
- yellow(value) {
2903
- return new ColorContentToken(value, source_default.yellow);
2904
- },
2905
- magenta(value) {
2906
- return new ColorContentToken(value, source_default.magenta);
2907
- },
2908
- green(value) {
2909
- return new ColorContentToken(value, source_default.green);
2910
- },
2911
- gray(value) {
2912
- return new ColorContentToken(value, source_default.gray);
2913
- },
2914
- packagejsonScript(packageManager, scriptName, ...scriptArgs) {
2915
- return new CommandContentToken(formatPackageManagerCommand(packageManager, scriptName, ...scriptArgs));
2916
- },
2917
- successIcon() {
2918
- return new ColorContentToken("\u2714", source_default.green);
2919
- },
2920
- failIcon() {
2921
- return new ErrorContentToken("\u2716");
2922
- },
2923
- linesDiff(value) {
2924
- return new LinesDiffContentToken(value);
2925
- }
2926
- };
2927
- function formatPackageManagerCommand(packageManager, scriptName, ...scriptArgs) {
2928
- if (currentProcessIsGlobal2()) {
2929
- return [scriptName, ...scriptArgs].join(" ");
2930
- }
2931
- switch (packageManager) {
2932
- case "pnpm":
2933
- case "bun":
2934
- case "yarn": {
2935
- const pieces = [packageManager, scriptName, ...scriptArgs];
2936
- return pieces.join(" ");
2937
- }
2938
- case "npm": {
2939
- const pieces = ["npm", "run", scriptName];
2940
- if (scriptArgs.length > 0) {
2941
- pieces.push("--");
2942
- pieces.push(...scriptArgs);
2943
- }
2944
- return pieces.join(" ");
2945
- }
2946
- case "unknown": {
2947
- const pieces = [scriptName, ...scriptArgs];
2948
- return pieces.join(" ");
2949
- }
2950
- }
2951
- }
2952
- function outputContent2(strings, ...keys) {
2953
- let output = ``;
2954
- strings.forEach((string, i) => {
2955
- output += string;
2956
- if (i >= keys.length) {
2957
- return;
2958
- }
2959
- const token = keys[i];
2960
- if (typeof token === "string") {
2961
- output += token;
2962
- } else {
2963
- const enumTokenOutput = token.output();
2964
- if (Array.isArray(enumTokenOutput)) {
2965
- enumTokenOutput.forEach((line) => {
2966
- output += line;
2967
- });
2968
- } else {
2969
- output += enumTokenOutput;
2970
- }
2971
- }
2972
- });
2973
- return new TokenizedString(output);
2974
- }
2975
- function logLevelValue(level) {
2976
- switch (level) {
2977
- case "trace":
2978
- return 10;
2979
- case "debug":
2980
- return 20;
2981
- case "info":
2982
- return 30;
2983
- case "warn":
2984
- return 40;
2985
- case "error":
2986
- return 50;
2987
- case "fatal":
2988
- return 60;
2989
- default:
2990
- return 30;
2991
- }
2992
- }
2993
- function currentLogLevel() {
2994
- if (isVerbose()) {
2995
- return "debug";
2996
- } else {
2997
- return "info";
2998
- }
2999
- }
3000
- function shouldOutput(logLevel) {
3001
- if (isUnitTest()) {
3002
- return false;
3003
- }
3004
- const currentLogLevelValue = logLevelValue(currentLogLevel());
3005
- const messageLogLevelValue = logLevelValue(logLevel);
3006
- return messageLogLevelValue >= currentLogLevelValue;
3007
- }
3008
- var collectedLogs = {};
3009
- function collectLog(key, content) {
3010
- const output = collectedLogs.output ?? [];
3011
- const data = collectedLogs[key] ?? [];
3012
- data.push(stripAnsi(stringifyMessage(content) ?? ""));
3013
- output.push(stripAnsi(stringifyMessage(content) ?? ""));
3014
- collectedLogs[key] = data;
3015
- collectedLogs.output = output;
3016
- }
3017
- function outputInfo(content, logger = consoleLog) {
3018
- const message = stringifyMessage(content);
3019
- if (isUnitTest())
3020
- collectLog("info", content);
3021
- outputWhereAppropriate("info", logger, message);
3022
- }
3023
- function outputSuccess(content, logger = consoleLog) {
3024
- const message = source_default.bold(`\u2705 Success! ${stringifyMessage(content)}.`);
3025
- if (isUnitTest())
3026
- collectLog("success", content);
3027
- outputWhereAppropriate("info", logger, message);
3028
- }
3029
- function outputCompleted(content, logger = consoleLog) {
3030
- const message = `${source_default.green("\u2714")} ${stringifyMessage(content)}`;
3031
- if (isUnitTest())
3032
- collectLog("completed", content);
3033
- outputWhereAppropriate("info", logger, message);
3034
- }
3035
- function outputDebug2(content, logger = consoleLog) {
3036
- if (isUnitTest())
3037
- collectLog("debug", content);
3038
- const message = source_default.gray(stringifyMessage(content));
3039
- outputWhereAppropriate("debug", logger, `${(/* @__PURE__ */ new Date()).toISOString()}: ${message}`);
3040
- }
3041
- function outputWarn(content, logger = consoleWarn) {
3042
- if (isUnitTest())
3043
- collectLog("warn", content);
3044
- const message = source_default.yellow(stringifyMessage(content));
3045
- outputWhereAppropriate("warn", logger, message);
3046
- }
3047
- function outputNewline() {
3048
- console.log();
3049
- }
3050
- function stringifyMessage(message) {
3051
- if (message instanceof TokenizedString) {
3052
- return message.value;
3053
- } else {
3054
- return message;
3055
- }
3056
- }
3057
- function consoleLog(message) {
3058
- console.log(withOrWithoutStyle(message));
3059
- }
3060
- function consoleError(message) {
3061
- console.error(withOrWithoutStyle(message));
3062
- }
3063
- function consoleWarn(message) {
3064
- console.warn(withOrWithoutStyle(message));
3065
- }
3066
- function outputWhereAppropriate(logLevel, logger, message, options = { skipUIEvent: false }) {
3067
- if (shouldOutput(logLevel)) {
3068
- if (logger instanceof Writable) {
3069
- logger.write(message);
3070
- } else {
3071
- logger(message, logLevel);
3072
- }
3073
- if (!options?.skipUIEvent)
3074
- recordUIEvent({ type: "output", properties: { content: message } });
3075
- }
3076
- }
3077
- function withOrWithoutStyle(message) {
3078
- if (shouldDisplayColors()) {
3079
- return message;
3080
- } else {
3081
- return unstyled(message);
3082
- }
3083
- }
3084
- function unstyled(message) {
3085
- return stripAnsi(message);
3086
- }
3087
- function shouldDisplayColors(_process = process) {
3088
- const { env, stdout } = _process;
3089
- if (Object.hasOwnProperty.call(env, "FORCE_COLOR")) {
3090
- return isTruthy(env.FORCE_COLOR);
3091
- } else {
3092
- return Boolean(stdout.isTTY);
3093
- }
3094
- }
3095
-
3096
- // ../cli-kit/dist/public/node/os.js
3097
- function platformAndArch(platform = process.platform, arch = process.arch) {
3098
- let archString;
3099
- if (arch === "x64") {
3100
- archString = "amd64";
3101
- } else if (arch === "ia32") {
3102
- archString = "386";
3103
- } else {
3104
- archString = arch;
3105
- }
3106
- const platformString = platform.match(/^win.+/) ? "windows" : platform;
3107
- return { platform: platformString, arch: archString };
3108
- }
3109
-
3110
- // ../cli-kit/dist/public/node/environment.js
3111
- init_cjs_shims();
3112
- function getEnvironmentVariables() {
3113
- return process.env;
3114
- }
3115
- function getPartnersToken() {
3116
- return getEnvironmentVariables()[environmentVariables.partnersToken];
3117
- }
3118
- function getIdentityTokenInformation() {
3119
- const identityToken = getEnvironmentVariables()[environmentVariables.identityToken];
3120
- const refreshToken = getEnvironmentVariables()[environmentVariables.refreshToken];
3121
- if (!identityToken || !refreshToken)
3122
- return void 0;
3123
- return {
3124
- accessToken: identityToken,
3125
- refreshToken
3126
- };
3127
- }
3128
-
3129
- // ../cli-kit/dist/public/common/version.js
3130
- init_cjs_shims();
3131
- var CLI_KIT_VERSION = "3.63.2";
3132
-
3133
- // ../cli-kit/dist/public/node/ruby.js
3134
- var import_semver = __toESM(require_semver(), 1);
3135
- async function version() {
3136
- const parseOutput = (version2) => version2.match(/ruby (\d+\.\d+\.\d+)/)?.[1];
3137
- return captureOutput(rubyExecutable(), ["-v"]).then(parseOutput).catch(() => void 0);
3138
- }
3139
- function getRubyBinDir() {
3140
- return getEnvironmentVariables().SHOPIFY_RUBY_BINDIR;
3141
- }
3142
- function rubyExecutable() {
3143
- const rubyBinDir = getRubyBinDir();
3144
- return rubyBinDir ? joinPath(rubyBinDir, "ruby") : "ruby";
3145
- }
3146
-
3147
- // ../cli-kit/dist/public/node/monorail.js
3148
- init_cjs_shims();
3149
-
3150
- // ../cli-kit/dist/public/node/http.js
3151
- init_cjs_shims();
3152
-
3153
- // ../cli-kit/dist/private/node/api/headers.js
3154
- init_cjs_shims();
3155
- import https from "https";
3156
- var RequestClientError = class extends import_ts_error.ExtendableError {
3157
- constructor(message, statusCode) {
3158
- super(message);
3159
- this.statusCode = statusCode;
3160
- }
3161
- };
3162
- var GraphQLClientError = class extends RequestClientError {
3163
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3164
- constructor(message, statusCode, errors) {
3165
- super(message, statusCode);
3166
- this.errors = errors;
3167
- this.stack = void 0;
3168
- }
3169
- };
3170
- function sanitizedHeadersOutput(headers) {
3171
- const sanitized = {};
3172
- const keywords = ["token", "authorization", "subject_token"];
3173
- Object.keys(headers).forEach((header) => {
3174
- if (keywords.find((keyword) => header.toLocaleLowerCase().includes(keyword)) === void 0) {
3175
- sanitized[header] = headers[header];
3176
- }
3177
- });
3178
- return Object.keys(sanitized).map((header) => {
3179
- return ` - ${header}: ${sanitized[header]}`;
3180
- }).join("\n");
3181
- }
3182
- function buildHeaders(token) {
3183
- const userAgent = `Shopify CLI; v=${CLI_KIT_VERSION}`;
3184
- const headers = {
3185
- "User-Agent": userAgent,
3186
- "Keep-Alive": "timeout=30",
3187
- // 'Sec-CH-UA': secCHUA, This header requires the Git sha.
3188
- "Sec-CH-UA-PLATFORM": process.platform,
3189
- "Content-Type": "application/json",
3190
- ...firstPartyDev() && { "X-Shopify-Cli-Employee": "1" }
3191
- };
3192
- if (token) {
3193
- const authString = token.match(/^shp(at|ua|ca)/) ? token : `Bearer ${token}`;
3194
- headers["authorization"] = authString;
3195
- headers["X-Shopify-Access-Token"] = authString;
3196
- }
3197
- return headers;
3198
- }
3199
- async function httpsAgent() {
3200
- return new https.Agent({
3201
- rejectUnauthorized: await shouldRejectUnauthorizedRequests(),
3202
- keepAlive: true
3203
- });
3204
- }
3205
- async function shouldRejectUnauthorizedRequests() {
3206
- return await serviceEnvironment() !== Environment.Spin;
3207
- }
3208
-
3209
- // ../cli-kit/dist/private/node/api/urls.js
3210
- init_cjs_shims();
3211
- function sanitizeURL(url2) {
3212
- const parsedUrl = new URL(url2);
3213
- if (parsedUrl.searchParams.has("subject_token")) {
3214
- parsedUrl.searchParams.set("subject_token", "****");
3215
- }
3216
- if (parsedUrl.searchParams.has("token")) {
3217
- parsedUrl.searchParams.set("token", "****");
3218
- }
3219
- return parsedUrl.toString();
3220
- }
3221
-
3222
- // ../cli-kit/dist/private/node/api.js
3223
- init_cjs_shims();
3224
- import { performance as performance2 } from "perf_hooks";
3225
- var allAPIs = ["admin", "storefront-renderer", "partners", "business-platform", "app-management"];
3226
- var interestingResponseHeaders = /* @__PURE__ */ new Set(["cache-control", "content-type", "etag", "x-request-id"]);
3227
- async function debugLogResponseInfo({ request, url: url2 }, errorHandler2) {
3228
- const t0 = performance2.now();
3229
- const responseHeaders = {};
3230
- let response = {};
3231
- try {
3232
- response = await request;
3233
- response.headers.forEach((value, key) => {
3234
- if (interestingResponseHeaders.has(key))
3235
- responseHeaders[key] = value;
3236
- });
3237
- } catch (err) {
3238
- if (err instanceof ClientError) {
3239
- if (err.response?.headers) {
3240
- for (const [key, value] of err.response?.headers) {
3241
- if (interestingResponseHeaders.has(key))
3242
- responseHeaders[key] = value;
3243
- }
3244
- }
3245
- }
3246
- if (errorHandler2) {
3247
- throw errorHandler2(err, responseHeaders["x-request-id"]);
3248
- } else {
3249
- throw err;
3250
- }
3251
- } finally {
3252
- const t1 = performance2.now();
3253
- outputDebug(`Request to ${sanitizeURL(url2)} completed in ${Math.round(t1 - t0)} ms
3254
- With response headers:
3255
- ${sanitizedHeadersOutput(responseHeaders)}
3256
- `);
3257
- }
3258
- return response;
3259
- }
3260
-
3261
- // ../cli-kit/dist/public/node/http.js
3262
- var import_form_data = __toESM(require_form_data(), 1);
3263
- function formData() {
3264
- return new import_form_data.default();
3265
- }
3266
- async function fetch2(url2, init) {
3267
- return runWithTimer("cmd_all_timing_network_ms")(() => debugLogResponseInfo({ url: url2.toString(), request: fetch(url2, init) }));
3268
- }
3269
- async function shopifyFetch(url2, init) {
3270
- const sanitizedUrl = sanitizeURL(url2.toString());
3271
- const options = {
3272
- ...init ?? {},
3273
- headers: {
3274
- ...await buildHeaders(),
3275
- ...init?.headers ?? {}
3276
- }
3277
- };
3278
- outputDebug2(outputContent2`Sending ${options.method ?? "GET"} request to URL ${sanitizedUrl}
3279
- With request headers:
3280
- ${sanitizedHeadersOutput(options?.headers ?? {})}
3281
- `);
3282
- return runWithTimer("cmd_all_timing_network_ms")(async () => {
3283
- return debugLogResponseInfo({ url: url2.toString(), request: fetch(url2, { ...init, agent: await httpsAgent() }) });
3284
- });
3285
- }
3286
-
3287
- // ../cli-kit/dist/public/node/monorail.js
3288
- var url = "https://monorail-edge.shopifysvc.com/v1/produce";
3289
- var MONORAIL_COMMAND_TOPIC = "app_cli3_command/1.12";
3290
- var publishedCommandNames = /* @__PURE__ */ new Set();
3291
- async function publishMonorailEvent(schemaId, publicData, sensitiveData) {
3292
- const commandName = publicData.command;
3293
- if (commandName && typeof commandName === "string") {
3294
- if (publishedCommandNames.has(commandName)) {
3295
- return { type: "ok" };
3296
- }
3297
- publishedCommandNames.add(commandName);
3298
- }
3299
- try {
3300
- const currentTime = (/* @__PURE__ */ new Date()).getTime();
3301
- const payload = { ...publicData, ...sensitiveData };
3302
- const body = JSON.stringify({ schema_id: schemaId, payload });
3303
- const headers = buildHeaders2(currentTime);
3304
- const response = await fetch2(url, { method: "POST", body, headers });
3305
- if (response.status === 200) {
3306
- outputDebug2(outputContent2`Analytics event sent: ${outputToken.json(sanitizePayload(payload))}`);
3307
- return { type: "ok" };
3308
- } else {
3309
- outputDebug2(`Failed to report usage analytics: ${response.statusText}`);
3310
- return { type: "error", message: response.statusText };
3311
- }
3312
- } catch (error) {
3313
- let message = "Failed to report usage analytics";
3314
- if (error instanceof Error) {
3315
- message = message.concat(`: ${error.message}`);
3316
- }
3317
- outputDebug2(message);
3318
- return { type: "error", message };
3319
- }
3320
- }
3321
- function sanitizePayload(payload) {
3322
- const result = { ...payload };
3323
- if ("api_key" in result) {
3324
- result.api_key = "****";
3325
- }
3326
- return result;
3327
- }
3328
- var buildHeaders2 = (currentTime) => {
3329
- return {
3330
- "Content-Type": "application/json; charset=utf-8",
3331
- "X-Monorail-Edge-Event-Created-At-Ms": currentTime.toString(),
3332
- "X-Monorail-Edge-Event-Sent-At-Ms": currentTime.toString()
3333
- };
3334
- };
3335
-
3336
- // ../cli-kit/dist/public/node/plugins.js
3337
- init_cjs_shims();
3338
- async function fanoutHooks(config, event, options, timeout) {
3339
- const res = await config.runHook(event, options, timeout);
3340
- return Object.fromEntries(res.successes.map(({ result, plugin }) => [plugin.name, result]));
3341
- }
3342
-
3343
- // ../cli-kit/dist/private/node/analytics.js
3344
- init_cjs_shims();
3345
-
3346
- // ../cli-kit/dist/public/node/crypto.js
3347
- init_cjs_shims();
3348
- import crypto from "crypto";
3349
- function randomHex(size) {
3350
- return crypto.randomBytes(size).toString("hex");
3351
- }
3352
- function base64URLEncode(str) {
3353
- return str.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/[=]/g, "");
3354
- }
3355
- function sha256(str) {
3356
- return crypto.createHash("sha256").update(str).digest();
3357
- }
3358
- function hashString(str) {
3359
- return crypto.createHash("sha1").update(str).digest("hex");
3360
- }
3361
- function fileHash(buff) {
3362
- return crypto.createHash("md5").update(buff).digest("hex");
3363
- }
3364
- function randomBytes(size) {
3365
- return crypto.randomBytes(size);
3366
- }
3367
-
3368
- // ../cli-kit/dist/public/node/node-package-manager.js
3369
- init_cjs_shims();
3370
-
3371
- // ../cli-kit/dist/private/node/conf-store.js
3372
- init_cjs_shims();
3373
-
3374
- // ../cli-kit/dist/public/node/local-storage.js
3375
- init_cjs_shims();
3376
- var LocalStorage = class {
3377
- constructor(options) {
3378
- this.config = new Conf(options);
3379
- }
3380
- /**
3381
- * Get a value from the local storage.
3382
- *
3383
- * @param key - The key to get.
3384
- * @returns The value.
3385
- */
3386
- get(key) {
3387
- return this.config.get(key);
3388
- }
3389
- /**
3390
- * Set a value in the local storage.
3391
- *
3392
- * @param key - The key to set.
3393
- * @param value - The value to set.
3394
- */
3395
- set(key, value) {
3396
- this.config.set(key, value);
3397
- }
3398
- /**
3399
- * Delete a value from the local storage.
3400
- *
3401
- * @param key - The key to delete.
3402
- */
3403
- delete(key) {
3404
- this.config.delete(key);
3405
- }
3406
- /**
3407
- * Clear the local storage (delete all values).
3408
- */
3409
- clear() {
3410
- this.config.clear();
3411
- }
3412
- };
3413
-
3414
- // ../cli-kit/dist/private/node/conf-store.js
3415
- var _instance2;
3416
- function cliKitStore() {
3417
- if (!_instance2) {
3418
- _instance2 = new LocalStorage({ projectName: "shopify-cli-kit" });
3419
- }
3420
- return _instance2;
3421
- }
3422
- function getSession(config = cliKitStore()) {
3423
- outputDebug(outputContent`Getting session store...`);
3424
- return config.get("sessionStore");
3425
- }
3426
- function setSession(session, config = cliKitStore()) {
3427
- outputDebug(outputContent`Setting session store...`);
3428
- config.set("sessionStore", session);
3429
- }
3430
- function removeSession(config = cliKitStore()) {
3431
- outputDebug(outputContent`Removing session store...`);
3432
- config.delete("sessionStore");
3433
- }
3434
- async function cacheRetrieveOrRepopulate(key, fn, timeout, config = cliKitStore()) {
3435
- const cache = config.get("cache") || {};
3436
- const cached = cache[key];
3437
- if (cached?.value !== void 0 && (timeout === void 0 || Date.now() - cached.timestamp < timeout)) {
3438
- return cached.value;
3439
- }
3440
- const value = await fn();
3441
- cache[key] = { value, timestamp: Date.now() };
3442
- config.set("cache", cache);
3443
- return value;
3444
- }
3445
-
3446
- // ../cli-kit/dist/public/node/node-package-manager.js
3447
- var import_semver2 = __toESM(require_semver(), 1);
3448
- var yarnLockfile = "yarn.lock";
3449
- var pnpmLockfile = "pnpm-lock.yaml";
3450
- var bunLockfile = "bun.lockb";
3451
- var PackageJsonNotFoundError = class extends AbortError {
3452
- constructor(directory) {
3453
- super(outputContent2`The directory ${outputToken.path(directory)} doesn't have a package.json.`);
3454
- }
3455
- };
3456
- var FindUpAndReadPackageJsonNotFoundError = class extends BugError {
3457
- constructor(directory) {
3458
- super(outputContent2`Couldn't find a a package.json traversing directories from ${outputToken.path(directory)}`);
3459
- }
3460
- };
3461
- function packageManagerFromUserAgent(env = process.env) {
3462
- if (env.npm_config_user_agent?.includes("yarn")) {
3463
- return "yarn";
3464
- } else if (env.npm_config_user_agent?.includes("pnpm")) {
3465
- return "pnpm";
3466
- } else if (env.npm_config_user_agent?.includes("bun")) {
3467
- return "bun";
3468
- } else if (env.npm_config_user_agent?.includes("npm")) {
3469
- return "npm";
3470
- }
3471
- return "unknown";
3472
- }
3473
- async function getPackageManager(fromDirectory) {
3474
- const directory = await captureOutput("npm", ["prefix"], { cwd: fromDirectory });
3475
- outputDebug2(outputContent2`Obtaining the dependency manager in directory ${outputToken.path(directory)}...`);
3476
- const packageJson = joinPath(directory, "package.json");
3477
- if (!await fileExists(packageJson)) {
3478
- return packageManagerFromUserAgent();
3479
- }
3480
- const yarnLockPath = joinPath(directory, yarnLockfile);
3481
- const pnpmLockPath = joinPath(directory, pnpmLockfile);
3482
- const bunLockPath = joinPath(directory, bunLockfile);
3483
- if (await fileExists(yarnLockPath)) {
3484
- return "yarn";
3485
- } else if (await fileExists(pnpmLockPath)) {
3486
- return "pnpm";
3487
- } else if (await fileExists(bunLockPath)) {
3488
- return "bun";
3489
- } else {
3490
- return "npm";
3491
- }
3492
- }
3493
- async function installNodeModules(options) {
3494
- const execOptions = {
3495
- cwd: options.directory,
3496
- stdin: void 0,
3497
- stdout: options.stdout,
3498
- stderr: options.stderr,
3499
- signal: options.signal
3500
- };
3501
- let args = ["install"];
3502
- if (options.args) {
3503
- args = args.concat(options.args);
3504
- }
3505
- await runWithTimer("cmd_all_timing_network_ms")(async () => {
3506
- await exec2(options.packageManager, args, execOptions);
3507
- });
3508
- }
3509
- async function getDependencies(packageJsonPath) {
3510
- const packageJsonContent = await readAndParsePackageJson(packageJsonPath);
3511
- const dependencies = packageJsonContent.dependencies ?? {};
3512
- const devDependencies = packageJsonContent.devDependencies ?? {};
3513
- return { ...dependencies, ...devDependencies };
3514
- }
3515
- async function checkForNewVersion(dependency, currentVersion, { cacheExpiryInHours = 0 } = {}) {
3516
- const getLatestVersion = async () => {
3517
- outputDebug2(outputContent2`Checking if there's a version of ${dependency} newer than ${currentVersion}`);
3518
- return getLatestNPMPackageVersion(dependency);
3519
- };
3520
- const cacheKey = `npm-package-${dependency}`;
3521
- let lastVersion;
3522
- try {
3523
- lastVersion = await cacheRetrieveOrRepopulate(cacheKey, getLatestVersion, cacheExpiryInHours * 24 * 1e3);
3524
- } catch (error) {
3525
- return void 0;
3526
- }
3527
- if (lastVersion && new import_semver2.SemVer(currentVersion).compare(lastVersion) < 0) {
3528
- return lastVersion;
3529
- } else {
3530
- return void 0;
3531
- }
3532
- }
3533
- async function readAndParsePackageJson(packageJsonPath) {
3534
- if (!await fileExists(packageJsonPath)) {
3535
- throw new PackageJsonNotFoundError(dirname2(packageJsonPath));
3536
- }
3537
- return JSON.parse(await readFile(packageJsonPath));
3538
- }
3539
- async function findUpAndReadPackageJson(fromDirectory) {
3540
- const packageJsonPath = await findPathUp("package.json", { cwd: fromDirectory, type: "file" });
3541
- if (packageJsonPath) {
3542
- const packageJson = JSON.parse(await readFile(packageJsonPath));
3543
- return { path: packageJsonPath, content: packageJson };
3544
- } else {
3545
- throw new FindUpAndReadPackageJsonNotFoundError(fromDirectory);
3546
- }
3547
- }
3548
- async function getLatestNPMPackageVersion(name) {
3549
- outputDebug2(outputContent2`Getting the latest version of NPM package: ${outputToken.raw(name)}`);
3550
- return runWithTimer("cmd_all_timing_network_ms")(() => {
3551
- return latestVersion(name);
3552
- });
3553
- }
3554
- async function writePackageJSON(directory, packageJSON) {
3555
- outputDebug2(outputContent2`JSON-encoding and writing content to package.json at ${outputToken.path(directory)}...`);
3556
- const packagePath = joinPath(directory, "package.json");
3557
- await writeFile(packagePath, JSON.stringify(packageJSON, null, 2));
3558
- }
3559
-
3560
- // ../cli-kit/dist/private/node/analytics.js
3561
- async function getEnvironmentData(config) {
3562
- const ciplatform = ciPlatform();
3563
- const pluginNames = getPluginNames(config);
3564
- const shopifyPlugins = pluginNames.filter((plugin) => plugin.startsWith("@shopify/"));
3565
- const { platform, arch } = platformAndArch();
3566
- return {
3567
- uname: `${platform} ${arch}`,
3568
- env_ci: ciplatform.isCI,
3569
- env_ci_platform: ciplatform.name,
3570
- env_plugin_installed_any_custom: pluginNames.length !== shopifyPlugins.length,
3571
- env_plugin_installed_shopify: JSON.stringify(shopifyPlugins),
3572
- env_shell: config.shell,
3573
- env_web_ide: cloudEnvironment().editor ? cloudEnvironment().platform : void 0,
3574
- env_device_id: hashString(await macAddress()),
3575
- env_cloud: cloudEnvironment().platform,
3576
- env_package_manager: await getPackageManager(cwd()),
3577
- env_is_global: currentProcessIsGlobal()
3578
- };
3579
- }
3580
- async function getSensitiveEnvironmentData(config) {
3581
- return {
3582
- env_plugin_installed_all: JSON.stringify(getPluginNames(config))
3583
- };
3584
- }
3585
- function getPluginNames(config) {
3586
- const pluginNames = [...config.plugins.keys()];
3587
- return pluginNames.sort().filter((plugin) => !plugin.startsWith("@oclif/"));
3588
- }
3589
-
3590
- // ../cli-kit/dist/private/node/otel-metrics.js
3591
- init_cjs_shims();
3592
-
3593
- // ../cli-kit/dist/public/node/vendor/otel-js/service/types.js
3594
- init_cjs_shims();
3595
- var MetricInstrumentType;
3596
- (function(MetricInstrumentType2) {
3597
- MetricInstrumentType2["Histogram"] = "Histogram";
3598
- MetricInstrumentType2["Counter"] = "Counter";
3599
- MetricInstrumentType2["UpDownCounter"] = "UpDownCounter";
3600
- })(MetricInstrumentType || (MetricInstrumentType = {}));
3601
-
3602
- // ../cli-kit/dist/public/node/vendor/otel-js/service/DefaultOtelService/DefaultOtelService.js
3603
- init_cjs_shims();
3604
-
3605
- // ../cli-kit/dist/public/node/vendor/otel-js/service/DefaultOtelService/DefaultMeterProvider.js
3606
- init_cjs_shims();
3607
-
3608
- // ../cli-kit/dist/public/node/vendor/otel-js/export/InstantaneousMetricReader.js
3609
- init_cjs_shims();
3610
- var import_sdk_metrics = __toESM(require_src5(), 1);
3611
- var import_core2 = __toESM(require_src3(), 1);
3612
- var import_api2 = __toESM(require_src(), 1);
3613
-
3614
- // ../cli-kit/dist/public/node/vendor/otel-js/utils/throttle.js
3615
- init_cjs_shims();
3616
- function throttle(func, wait, { leading = true, trailing = true } = {}) {
3617
- let lastArgs;
3618
- let result;
3619
- let context;
3620
- let timeout = null;
3621
- let previous = 0;
3622
- function later() {
3623
- previous = leading === false ? 0 : Date.now();
3624
- timeout = null;
3625
- if (lastArgs) {
3626
- result = func.apply(context, lastArgs);
3627
- }
3628
- context = null;
3629
- lastArgs = null;
3630
- }
3631
- return function(...args) {
3632
- const now = Date.now();
3633
- if (!previous && leading === false)
3634
- previous = now;
3635
- const remaining = wait - (now - previous);
3636
- context = this;
3637
- lastArgs = args;
3638
- if (remaining <= 0 || remaining > wait) {
3639
- if (timeout) {
3640
- clearTimeout(timeout);
3641
- timeout = null;
3642
- }
3643
- previous = now;
3644
- if (lastArgs) {
3645
- result = func.apply(context, lastArgs);
3646
- }
3647
- context = null;
3648
- lastArgs = null;
3649
- } else if (!timeout && trailing !== false) {
3650
- timeout = setTimeout(later, remaining);
3651
- }
3652
- return result;
3653
- };
3654
- }
3655
-
3656
- // ../cli-kit/dist/public/node/vendor/otel-js/export/InstantaneousMetricReader.js
3657
- var InstantaneousMetricReader = class extends import_sdk_metrics.MetricReader {
3658
- constructor({ exporter, throttleLimit }) {
3659
- super({
3660
- aggregationSelector: exporter.selectAggregation?.bind(exporter),
3661
- aggregationTemporalitySelector: exporter.selectAggregationTemporality?.bind(exporter)
3662
- });
3663
- this._exporter = exporter;
3664
- this.onForceFlush = throttle(
3665
- // eslint-disable-next-line @typescript-eslint/unbound-method
3666
- this.onForceFlush,
3667
- throttleLimit
3668
- );
3669
- }
3670
- async onForceFlush() {
3671
- const { resourceMetrics, errors } = await this.collect({});
3672
- if (errors.length > 0) {
3673
- import_api2.diag.error("PeriodicExportingMetricReader: metrics collection errors", ...errors);
3674
- }
3675
- return new Promise((resolve2, reject) => {
3676
- this._exporter.export(resourceMetrics, (result) => {
3677
- if (result.code === import_core2.ExportResultCode.SUCCESS) {
3678
- resolve2();
3679
- } else {
3680
- reject(result.error ?? new Error(`InstantaneousMetricReader: metrics export failed (error ${result.error})`));
3681
- }
3682
- });
3683
- });
3684
- }
3685
- async onShutdown() {
3686
- await this._exporter.shutdown();
3687
- }
3688
- };
3689
-
3690
- // ../cli-kit/dist/public/node/vendor/otel-js/service/DefaultOtelService/DefaultMeterProvider.js
3691
- var import_exporter_metrics_otlp_http = __toESM(require_src6(), 1);
3692
- var import_resources = __toESM(require_src4(), 1);
3693
- var import_sdk_metrics2 = __toESM(require_src5(), 1);
3694
- var import_semantic_conventions = __toESM(require_src2(), 1);
3695
- var DefaultMeterProvider = class extends import_sdk_metrics2.MeterProvider {
3696
- constructor({ serviceName, env, throttleLimit, useXhr, otelEndpoint }) {
3697
- super({
3698
- resource: new import_resources.Resource({
3699
- [import_semantic_conventions.SemanticResourceAttributes.SERVICE_NAME]: serviceName
3700
- })
3701
- });
3702
- const opts = {
3703
- // url: OTEL_ENDPOINTS[env as Environment] || OTEL_ENDPOINTS.local,
3704
- // CLI addition
3705
- url: otelEndpoint,
3706
- temporalityPreference: import_sdk_metrics2.AggregationTemporality.DELTA
3707
- };
3708
- if (useXhr) {
3709
- opts.headers = {};
3710
- }
3711
- const exporter = new import_exporter_metrics_otlp_http.OTLPMetricExporter(opts);
3712
- this.addMetricReader(new InstantaneousMetricReader({
3713
- exporter,
3714
- throttleLimit
3715
- }));
3716
- if (env === "dev") {
3717
- this.addMetricReader(new InstantaneousMetricReader({
3718
- exporter: new import_sdk_metrics2.ConsoleMetricExporter(),
3719
- throttleLimit
3720
- }));
3721
- }
3722
- }
3723
- };
3724
-
3725
- // ../cli-kit/dist/public/node/vendor/otel-js/service/BaseOtelService/BaseOtelService.js
3726
- init_cjs_shims();
3727
- var import_sdk_metrics3 = __toESM(require_src5(), 1);
3728
-
3729
- // ../cli-kit/dist/public/node/vendor/otel-js/utils/validators.js
3730
- init_cjs_shims();
3731
- var import_api3 = __toESM(require_src(), 1);
3732
- var validMetricRegex = new RegExp("[^a-zA-Z_][^a-zA-Z0-9_]*");
3733
- function isValidMetricName(value) {
3734
- if (validMetricRegex.test(value)) {
3735
- import_api3.diag.warn(`Metric name ${value} contains invalid characters and will be dropped.
3736
- Service Names and metric names must conform to the following regex %c[a-zA-Z_][a-zA-Z0-9_]*`, "color:red");
3737
- return false;
3738
- }
3739
- return true;
3740
- }
3741
-
3742
- // ../cli-kit/dist/public/node/vendor/otel-js/service/BaseOtelService/BaseOtelService.js
3743
- var instrumentationScope = "opentelemetry-js-shopify-web";
3744
- var BaseOtelService = class {
3745
- /**
3746
- * Bootstraps an Otel exporter which can send Otel metrics to a dedicated Shopify supported collector endpoint.
3747
- */
3748
- constructor({ serviceName, prefixMetric = false, metrics = {}, onRecord, meterProvider }) {
3749
- this.metrics = /* @__PURE__ */ new Map();
3750
- this.recordListeners = /* @__PURE__ */ new Set();
3751
- if (!serviceName) {
3752
- throw new Error("Service name is required.");
3753
- }
3754
- this.serviceName = serviceName;
3755
- this.prefixMetric = prefixMetric;
3756
- if (onRecord)
3757
- this.addOnRecord(onRecord);
3758
- if (!meterProvider) {
3759
- throw new Error("MeterProvider is required.");
3760
- }
3761
- this.meterProvider = meterProvider;
3762
- this.register(metrics);
3763
- }
3764
- getMeterProvider() {
3765
- return this.meterProvider;
3766
- }
3767
- addView(viewOptions) {
3768
- ;
3769
- this.meterProvider._sharedState?.viewRegistry?.addView?.(new import_sdk_metrics3.View(viewOptions));
3770
- }
3771
- record(metricName, value, labels) {
3772
- const recordMetric = this.metrics.get(metricName);
3773
- if (!recordMetric) {
3774
- throw new Error(`Service ${this.serviceName} has no metrics registered for name: ${metricName}. Can't record value for unknown metric.`);
3775
- }
3776
- recordMetric(value, labels);
3777
- }
3778
- registerMetric(metricName, { type, ...options }) {
3779
- if (this.metrics.has(metricName)) {
3780
- return;
3781
- }
3782
- const meter = this.meterProvider.getMeter(instrumentationScope);
3783
- const name = this.prefixMetric ? `${this.serviceName}_${metricName}` : metricName;
3784
- if (!isValidMetricName(name)) {
3785
- return;
3786
- }
3787
- const createInstrument = () => {
3788
- switch (type) {
3789
- case MetricInstrumentType.Counter:
3790
- return meter.createCounter(name, options);
3791
- case MetricInstrumentType.UpDownCounter:
3792
- return meter.createUpDownCounter(name, options);
3793
- case MetricInstrumentType.Histogram: {
3794
- if ("boundaries" in options) {
3795
- this.addView({
3796
- instrumentName: name,
3797
- aggregation: new import_sdk_metrics3.ExplicitBucketHistogramAggregation(options.boundaries, true)
3798
- });
3799
- }
3800
- return meter.createHistogram(name, options);
3801
- }
3802
- }
3803
- };
3804
- this.metrics.set(metricName, (firstValue, firstLabels) => {
3805
- const instrument = createInstrument();
3806
- const record = (value, labels) => {
3807
- const [finalValue, finalLabels] = this.notifyRecordListeners(
3808
- metricName,
3809
- value,
3810
- // ensures an new object is created so we don't mutate the original
3811
- { ...labels }
3812
- );
3813
- if ("record" in instrument) {
3814
- instrument.record(finalValue, finalLabels);
3815
- } else {
3816
- instrument.add(finalValue, finalLabels);
3817
- }
3818
- this.meterProvider.forceFlush({});
3819
- };
3820
- record(firstValue, firstLabels);
3821
- this.metrics.set(metricName, record);
3822
- });
3823
- }
3824
- register(metrics) {
3825
- Object.entries(metrics).forEach(([metricName, options]) => {
3826
- this.registerMetric(metricName, options);
3827
- });
3828
- }
3829
- addOnRecord(onRecord) {
3830
- this.recordListeners.add(onRecord);
3831
- return () => {
3832
- this.recordListeners.delete(onRecord);
3833
- };
3834
- }
3835
- removeOnRecord(onRecord) {
3836
- this.recordListeners.delete(onRecord);
3837
- }
3838
- shutdown() {
3839
- this.metrics.clear();
3840
- this.recordListeners.clear();
3841
- return this.meterProvider.shutdown();
3842
- }
3843
- notifyRecordListeners(metricName, initialValue, initialLabels) {
3844
- return Array.from(this.recordListeners).reduce((recordArgs, listener) => {
3845
- return listener(metricName, ...recordArgs) || recordArgs;
3846
- }, [initialValue, initialLabels]);
3847
- }
3848
- };
3849
-
3850
- // ../cli-kit/dist/public/node/vendor/otel-js/service/DefaultOtelService/DefaultOtelService.js
3851
- var import_api4 = __toESM(require_src(), 1);
3852
- var DefaultOtelService = class extends BaseOtelService {
3853
- /**
3854
- * Bootstraps an Otel exporter which can send Otel metrics to a dedicated Shopify supported collector endpoint.
3855
- */
3856
- constructor({
3857
- throttleLimit = 5e3,
3858
- env = "local",
3859
- serviceName,
3860
- prefixMetric = false,
3861
- metrics = {},
3862
- onRecord,
3863
- meterProvider,
3864
- useXhr = false,
3865
- // CLI addition
3866
- otelEndpoint
3867
- }) {
3868
- import_api4.diag.setLogger(new import_api4.DiagConsoleLogger(), ["production", "staging"].includes(env) ? import_api4.DiagLogLevel.ERROR : import_api4.DiagLogLevel.INFO);
3869
- super({
3870
- serviceName,
3871
- meterProvider: meterProvider ?? new DefaultMeterProvider({
3872
- serviceName,
3873
- env,
3874
- throttleLimit,
3875
- useXhr,
3876
- // CLI addition
3877
- otelEndpoint
3878
- }),
3879
- prefixMetric,
3880
- metrics,
3881
- onRecord
3882
- });
3883
- }
3884
- shutdown() {
3885
- import_api4.diag.disable();
3886
- return super.shutdown();
3887
- }
3888
- };
3889
-
3890
- // ../cli-kit/dist/private/node/otel-metrics.js
3891
- var import_api5 = __toESM(require_src(), 1);
3892
- var Name;
3893
- (function(Name2) {
3894
- Name2["Counter"] = "cli_commands_total";
3895
- Name2["Duration"] = "cli_commands_duration_ms";
3896
- Name2["Elapsed"] = "cli_commands_wall_clock_elapsed_ms";
3897
- })(Name || (Name = {}));
3898
- async function recordMetrics(options, timing, recorderFactory = createMetricRecorder) {
3899
- const recorder = recorderFactory({
3900
- skipMetricAnalytics: options.skipMetricAnalytics,
3901
- otelOptions: defaultOtelOptions()
3902
- });
3903
- let regularisedCliVersion = options.cliVersion;
3904
- if (options.cliVersion.includes("nightly")) {
3905
- regularisedCliVersion = "nightly";
3906
- } else if (options.cliVersion.includes("pre")) {
3907
- regularisedCliVersion = "pre";
3908
- }
3909
- const labels = {
3910
- exit: options.exitMode,
3911
- job: `${options.owningPlugin}::${options.command}`,
3912
- cli_version: regularisedCliVersion
3913
- };
3914
- recordCommandCounter(recorder, labels);
3915
- recordCommandTiming(recorder, labels, timing);
3916
- }
3917
- function defaultOtelOptions() {
3918
- return {
3919
- serviceName: "shopify-cli",
3920
- throttleLimit: 1e3,
3921
- prefixMetric: false,
3922
- metrics: {
3923
- [Name.Counter]: {
3924
- type: MetricInstrumentType.Counter,
3925
- description: "Total number of CLI commands executed",
3926
- valueType: import_api5.ValueType.INT
3927
- },
3928
- [Name.Duration]: {
3929
- type: MetricInstrumentType.Histogram,
3930
- description: "Total time spent in execution of CLI commands. Does not include time spent waiting for network, prompts, etc.",
3931
- valueType: import_api5.ValueType.INT,
3932
- boundaries: [0, 100, 250, 500, 1e3, 2e3, 5e3, 1e4, 2e4, 5e4]
3933
- },
3934
- [Name.Elapsed]: {
3935
- type: MetricInstrumentType.Histogram,
3936
- description: "Total time elapsed from start to finish of CLI commands. Includes time spent waiting for network, prompts, etc.",
3937
- valueType: import_api5.ValueType.INT,
3938
- boundaries: [0, 100, 250, 500, 1e3, 2e3, 5e3, 1e4, 2e4, 5e4]
3939
- }
3940
- }
3941
- };
3942
- }
3943
- function createMetricRecorder(options) {
3944
- let recorder = "console";
3945
- if (!(options.skipMetricAnalytics || isUnitTest() || isSpinEnvironment())) {
3946
- recorder = {
3947
- type: "otel",
3948
- otel: globalOtelService(options)
3949
- };
3950
- }
3951
- return recorder;
3952
- }
3953
- var _otelService;
3954
- function globalOtelService(options) {
3955
- if (!_otelService) {
3956
- _otelService = new DefaultOtelService({
3957
- ...options.otelOptions,
3958
- env: void 0,
3959
- otelEndpoint: `${opentelemetryDomain()}/v1/metrics`
3960
- });
3961
- }
3962
- return _otelService;
3963
- }
3964
- function recordCommandCounter(recorder, labels) {
3965
- if (recorder === "console") {
3966
- outputDebug2(outputContent2`[OTEL] record ${Name.Counter} counter ${outputToken.json({ labels })}`);
3967
- return;
3968
- }
3969
- recorder.otel.record(Name.Counter, 1, labels);
3970
- }
3971
- function recordCommandTiming(recorder, labels, timing) {
3972
- if (recorder === "console") {
3973
- outputDebug2(outputContent2`[OTEL] record ${Name.Duration} histogram ${timing.active.toString()}ms ${outputToken.json({
3974
- labels
3975
- })}`);
3976
- outputDebug2(outputContent2`[OTEL] record ${Name.Elapsed} histogram stage="active" ${timing.active.toString()}ms`);
3977
- outputDebug2(outputContent2`[OTEL] record ${Name.Elapsed} histogram stage="network" ${timing.network.toString()}ms`);
3978
- outputDebug2(outputContent2`[OTEL] record ${Name.Elapsed} histogram stage="prompt" ${timing.prompt.toString()}ms`);
3979
- return;
3980
- }
3981
- if (timing.active > 0) {
3982
- recorder.otel.record(Name.Duration, timing.active, labels);
3983
- recorder.otel.record(Name.Elapsed, timing.active, { ...labels, stage: "active" });
3984
- }
3985
- if (timing.network > 0) {
3986
- recorder.otel.record(Name.Elapsed, timing.network, { ...labels, stage: "network" });
3987
- }
3988
- if (timing.prompt > 0) {
3989
- recorder.otel.record(Name.Elapsed, timing.prompt, { ...labels, stage: "prompt" });
3990
- }
3991
- }
3992
-
3993
- // ../cli-kit/dist/public/node/analytics.js
3994
- async function reportAnalyticsEvent(options) {
3995
- try {
3996
- const payload = await buildPayload(options);
3997
- if (payload === void 0) {
3998
- return;
3999
- }
4000
- const skipMonorailAnalytics = !alwaysLogAnalytics() && analyticsDisabled();
4001
- const skipMetricAnalytics = !alwaysLogMetrics() && analyticsDisabled();
4002
- if (skipMonorailAnalytics || skipMetricAnalytics) {
4003
- outputDebug2(outputContent2`Skipping command analytics, payload: ${outputToken.json(payload)}`);
4004
- }
4005
- const doMonorail = async () => {
4006
- if (skipMonorailAnalytics) {
4007
- return;
4008
- }
4009
- const response = await publishMonorailEvent(MONORAIL_COMMAND_TOPIC, payload.public, payload.sensitive);
4010
- if (response.type === "error") {
4011
- outputDebug2(response.message);
4012
- }
4013
- };
4014
- const doOpenTelemetry = async () => {
4015
- const active = payload.public.cmd_all_timing_active_ms || 0;
4016
- const network = payload.public.cmd_all_timing_network_ms || 0;
4017
- const prompt = payload.public.cmd_all_timing_prompts_ms || 0;
4018
- return recordMetrics({
4019
- skipMetricAnalytics,
4020
- cliVersion: payload.public.cli_version,
4021
- owningPlugin: payload.public.cmd_all_plugin || "@shopify/cli",
4022
- command: payload.public.command,
4023
- exitMode: options.exitMode
4024
- }, {
4025
- active,
4026
- network,
4027
- prompt
4028
- });
4029
- };
4030
- await Promise.all([doMonorail(), doOpenTelemetry()]);
4031
- } catch (error) {
4032
- let message = "Failed to report usage analytics";
4033
- if (error instanceof Error) {
4034
- message = message.concat(`: ${error.message}`);
4035
- }
4036
- outputDebug2(message);
4037
- }
4038
- }
4039
- async function buildPayload({ config, errorMessage, exitMode }) {
4040
- const { commandStartOptions, environmentFlags, ...sensitiveMetadata } = getAllSensitiveMetadata();
4041
- if (commandStartOptions === void 0) {
4042
- outputDebug2("Unable to log analytics event - no information on executed command");
4043
- return;
4044
- }
4045
- const { startCommand, startArgs, startTime } = commandStartOptions;
4046
- const currentTime = (/* @__PURE__ */ new Date()).getTime();
4047
- const { "@shopify/cli": internalPluginsPublic, ...externalPluginsPublic } = await fanoutHooks(config, "public_command_metadata", {});
4048
- const { "@shopify/cli": internalPluginsSensitive, ...externalPluginsSensitive } = await fanoutHooks(config, "sensitive_command_metadata", {});
4049
- const environmentData = await getEnvironmentData(config);
4050
- const sensitiveEnvironmentData = await getSensitiveEnvironmentData(config);
4051
- const publicMetadata = getAllPublicMetadata();
4052
- const subTimers = ["cmd_all_timing_network_ms", "cmd_all_timing_prompts_ms"];
4053
- const totalTimeFromSubtimers = subTimers.reduce((total, timer) => {
4054
- const value = publicMetadata[timer];
4055
- if (value !== void 0) {
4056
- return total + value;
4057
- }
4058
- return total;
4059
- }, 0);
4060
- const wallClockElapsed = currentTime - startTime;
4061
- const totalTimeWithoutSubtimers = wallClockElapsed - totalTimeFromSubtimers;
4062
- let payload = {
4063
- public: {
4064
- command: startCommand,
4065
- time_start: startTime,
4066
- time_end: currentTime,
4067
- total_time: wallClockElapsed,
4068
- success: exitMode === "ok" && errorMessage === void 0,
4069
- cli_version: CLI_KIT_VERSION,
4070
- ruby_version: await version() || "",
4071
- node_version: process.version.replace("v", ""),
4072
- is_employee: await isShopify(),
4073
- ...environmentData,
4074
- ...internalPluginsPublic,
4075
- ...publicMetadata,
4076
- cmd_all_timing_active_ms: totalTimeWithoutSubtimers,
4077
- cmd_all_exit: exitMode
4078
- },
4079
- sensitive: {
4080
- args: startArgs.join(" "),
4081
- cmd_all_environment_flags: environmentFlags,
4082
- error_message: errorMessage,
4083
- ...internalPluginsSensitive,
4084
- ...sensitiveEnvironmentData,
4085
- metadata: JSON.stringify({
4086
- ...sensitiveMetadata,
4087
- extraPublic: {
4088
- ...externalPluginsPublic
4089
- },
4090
- extraSensitive: { ...externalPluginsSensitive }
4091
- })
4092
- }
4093
- };
4094
- const timingMetrics = ["cmd_all_timing_active_ms", "cmd_all_timing_network_ms", "cmd_all_timing_prompts_ms"];
4095
- timingMetrics.forEach((metric) => {
4096
- const current = payload.public[metric];
4097
- if (current !== void 0) {
4098
- payload.public[metric] = Math.floor(current);
4099
- }
4100
- });
4101
- payload = JSON.parse(JSON.stringify(payload));
4102
- return sanitizePayload2(payload);
4103
- }
4104
- function sanitizePayload2(payload) {
4105
- const payloadString = JSON.stringify(payload);
4106
- const sanitizedPayloadString = payloadString.replace(/shptka_\w*/g, "*****");
4107
- return JSON.parse(sanitizedPayloadString);
4108
- }
4109
-
4110
- // ../cli-kit/dist/public/node/error-handler.js
4111
- var import_core3 = __toESM(require_lib(), 1);
4112
- var import_stacktracey2 = __toESM(require_stacktracey(), 1);
4113
- var import_js = __toESM(require_notifier(), 1);
4114
- import { realpath } from "fs/promises";
4115
- async function errorHandler(error, config) {
4116
- if (error instanceof CancelExecution) {
4117
- if (error.message && error.message !== "") {
4118
- outputInfo(`\u2728 ${error.message}`);
4119
- }
4120
- } else if (error instanceof AbortSilentError) {
4121
- printEventsJson();
4122
- } else {
4123
- return errorMapper(error).then((error2) => {
4124
- return handler(error2);
4125
- }).then((mappedError) => {
4126
- printEventsJson();
4127
- return reportError(mappedError, config);
4128
- });
4129
- }
4130
- }
4131
- var reportError = async (error, config) => {
4132
- let exitMode = "expected_error";
4133
- if (shouldReportError(error))
4134
- exitMode = "unexpected_error";
4135
- if (config !== void 0) {
4136
- await reportAnalyticsEvent({ config, errorMessage: error instanceof Error ? error.message : void 0, exitMode });
4137
- }
4138
- await sendErrorToBugsnag(error, exitMode);
4139
- };
4140
- async function sendErrorToBugsnag(error, exitMode) {
4141
- if (import_core3.settings.debug) {
4142
- outputDebug2(`Skipping Bugsnag report`);
4143
- return { reported: false, error, unhandled: void 0 };
4144
- }
4145
- const unhandled = exitMode === "unexpected_error";
4146
- let reportableError;
4147
- let stacktrace;
4148
- let report = false;
4149
- if (error instanceof Error) {
4150
- report = true;
4151
- reportableError = new Error(error.message);
4152
- stacktrace = error.stack;
4153
- } else if (typeof error === "string" && error.trim().length !== 0) {
4154
- report = true;
4155
- reportableError = new Error(error);
4156
- stacktrace = reportableError.stack;
4157
- } else {
4158
- report = false;
4159
- reportableError = new Error("Unknown error");
4160
- }
4161
- const formattedStacktrace = new import_stacktracey2.default(stacktrace ?? "").clean().items.map((item) => {
4162
- const filePath = cleanSingleStackTracePath(item.file);
4163
- return ` at ${item.callee} (${filePath}:${item.line}:${item.column})`;
4164
- }).join("\n");
4165
- reportableError.stack = `Error: ${reportableError.message}
4166
- ${formattedStacktrace}`;
4167
- if (report) {
4168
- initializeBugsnag();
4169
- await new Promise((resolve2, reject) => {
4170
- outputDebug2(`Reporting ${unhandled ? "unhandled" : "handled"} error to Bugsnag: ${reportableError.message}`);
4171
- const eventHandler = (event) => {
4172
- event.severity = "error";
4173
- event.unhandled = unhandled;
4174
- };
4175
- const errorHandler2 = (error2) => {
4176
- if (error2) {
4177
- reject(error2);
4178
- } else {
4179
- resolve2(reportableError);
4180
- }
4181
- };
4182
- import_js.default.notify(reportableError, eventHandler, errorHandler2);
4183
- });
4184
- }
4185
- return { error: reportableError, reported: report, unhandled };
4186
- }
4187
- function cleanStackFrameFilePath({ currentFilePath, projectRoot, pluginLocations }) {
4188
- const fullLocation = isAbsolutePath(currentFilePath) ? currentFilePath : joinPath(projectRoot, currentFilePath);
4189
- const matchingPluginPath = pluginLocations.filter(({ pluginPath }) => fullLocation.indexOf(pluginPath) === 0)[0];
4190
- if (matchingPluginPath !== void 0) {
4191
- return joinPath(matchingPluginPath.name, relativePath(matchingPluginPath.pluginPath, fullLocation));
4192
- }
4193
- return currentFilePath.replace(/.*node_modules\//, "");
4194
- }
4195
- async function registerCleanBugsnagErrorsFromWithinPlugins(config) {
4196
- const bugsnagConfigProjectRoot = import_js.default?._client?._config?.projectRoot ?? cwd2();
4197
- const projectRoot = normalizePath(bugsnagConfigProjectRoot);
4198
- const pluginLocations = await Promise.all([...config.plugins].map(async ([_, plugin]) => {
4199
- const followSymlinks = await realpath(plugin.root);
4200
- return { name: plugin.name, pluginPath: normalizePath(followSymlinks) };
4201
- }));
4202
- initializeBugsnag();
4203
- import_js.default.addOnError(async (event) => {
4204
- event.errors.forEach((error) => {
4205
- error.stacktrace.forEach((stackFrame) => {
4206
- stackFrame.file = cleanStackFrameFilePath({ currentFilePath: stackFrame.file, projectRoot, pluginLocations });
4207
- });
4208
- });
4209
- try {
4210
- await addBugsnagMetadata(event, config);
4211
- } catch (metadataError) {
4212
- outputDebug2(`There was an error adding metadata to the Bugsnag report; Ignoring and carrying on ${metadataError}`);
4213
- }
4214
- });
4215
- }
4216
- async function addBugsnagMetadata(event, config) {
4217
- const publicData = getAllPublicMetadata();
4218
- const { commandStartOptions } = getAllSensitiveMetadata();
4219
- const { startCommand } = commandStartOptions ?? {};
4220
- const { "@shopify/app": appPublic, ...otherPluginsPublic } = await fanoutHooks(config, "public_command_metadata", {});
4221
- const environment = await getEnvironmentData(config);
4222
- const allMetadata = {
4223
- command: startCommand,
4224
- ...appPublic,
4225
- ...publicData,
4226
- ...environment,
4227
- pluginData: otherPluginsPublic
4228
- };
4229
- const appData = {};
4230
- const commandData = {};
4231
- const environmentData = {};
4232
- const miscData = {};
4233
- const appKeys = ["api_key", "partner_id", "project_type"];
4234
- const commandKeys = ["command"];
4235
- const environmentKeys = ["cli_version", "node_version", "ruby_version", "uname"];
4236
- Object.entries(allMetadata).forEach(([key, value]) => {
4237
- if (key.startsWith("app_") || appKeys.includes(key)) {
4238
- appData[key] = value;
4239
- } else if (key.startsWith("cmd_") || commandKeys.includes(key)) {
4240
- commandData[key] = value;
4241
- } else if (key.startsWith("env_") || environmentKeys) {
4242
- environmentData[key] = value;
4243
- } else {
4244
- miscData[key] = value;
4245
- }
4246
- });
4247
- const bugsnagMetadata = {
4248
- "Shopify App": appData,
4249
- Command: commandData,
4250
- Environment: environmentData,
4251
- Misc: miscData
4252
- };
4253
- Object.entries(bugsnagMetadata).forEach(([section, values]) => {
4254
- event.addMetadata(section, values);
4255
- });
4256
- }
4257
- function initializeBugsnag() {
4258
- if (import_js.default.isStarted()) {
4259
- return;
4260
- }
4261
- import_js.default.start({
4262
- appType: "node",
4263
- apiKey: bugsnagApiKey,
4264
- logger: null,
4265
- appVersion: CLI_KIT_VERSION,
4266
- autoTrackSessions: false,
4267
- autoDetectErrors: false
4268
- });
4269
- }
4270
-
4271
- export {
4272
- isTruthy,
4273
- joinPath,
4274
- resolvePath,
4275
- relativePath,
4276
- dirname2 as dirname,
4277
- basename2 as basename,
4278
- extname2 as extname,
4279
- relativizePath,
4280
- moduleDirectory,
4281
- cwd2 as cwd,
4282
- capitalize,
4283
- pluralize,
4284
- linesToColumns,
4285
- camelize,
4286
- hyphenate,
4287
- underscore,
4288
- readFile,
4289
- readFileSync,
4290
- copyFile,
4291
- touchFile,
4292
- writeFile,
4293
- mkdir,
4294
- removeFile,
4295
- rmdir,
4296
- isDirectory,
4297
- fileSize,
4298
- fileSizeSync,
4299
- createFileReadStream,
4300
- moveFile,
4301
- fileExists,
4302
- glob,
4303
- findPathUp,
4304
- sessionConstants,
4305
- AbortController,
4306
- addPublicMetadata,
4307
- addSensitiveMetadata,
4308
- runWithTimer,
4309
- renderInfo,
4310
- renderSuccess,
4311
- renderWarning,
4312
- renderFatalError,
4313
- renderSelectPrompt,
4314
- renderConfirmationPrompt,
4315
- renderTasks,
4316
- renderTextPrompt,
4317
- keypress,
4318
- CancelExecution,
4319
- FatalError2 as FatalError,
4320
- AbortError,
4321
- BugError,
4322
- import_ts_error,
4323
- openURL,
4324
- terminalSupportsRawMode,
4325
- Environment,
4326
- serviceEnvironment,
4327
- spinFqdn,
4328
- isSpinEnvironment,
4329
- isTerminalInteractive,
4330
- isDevelopment,
4331
- firstPartyDev,
4332
- useDeviceAuth,
4333
- hasGit,
4334
- ciPlatform2 as ciPlatform,
4335
- currentProcessIsGlobal2 as currentProcessIsGlobal,
4336
- inferPackageManagerForGlobalCLI,
4337
- outputToken,
4338
- formatPackageManagerCommand,
4339
- outputContent2 as outputContent,
4340
- collectLog,
4341
- outputInfo,
4342
- outputSuccess,
4343
- outputCompleted,
4344
- outputDebug2 as outputDebug,
4345
- outputWarn,
4346
- outputNewline,
4347
- stringifyMessage,
4348
- getPartnersToken,
4349
- getIdentityTokenInformation,
4350
- RequestClientError,
4351
- GraphQLClientError,
4352
- sanitizedHeadersOutput,
4353
- buildHeaders,
4354
- httpsAgent,
4355
- allAPIs,
4356
- debugLogResponseInfo,
4357
- formData,
4358
- fetch2 as fetch,
4359
- shopifyFetch,
4360
- fanoutHooks,
4361
- randomHex,
4362
- base64URLEncode,
4363
- sha256,
4364
- hashString,
4365
- fileHash,
4366
- randomBytes,
4367
- getSession,
4368
- setSession,
4369
- removeSession,
4370
- cacheRetrieveOrRepopulate,
4371
- packageManagerFromUserAgent,
4372
- getPackageManager,
4373
- installNodeModules,
4374
- getDependencies,
4375
- checkForNewVersion,
4376
- readAndParsePackageJson,
4377
- findUpAndReadPackageJson,
4378
- writePackageJSON,
4379
- errorHandler,
4380
- sendErrorToBugsnag,
4381
- cleanStackFrameFilePath,
4382
- registerCleanBugsnagErrorsFromWithinPlugins,
4383
- addBugsnagMetadata
4384
- };
4385
- //# sourceMappingURL=chunk-QEKTVN5A.js.map