@shopify/cli 3.73.1 → 3.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/assets/dev-console/extensions/dev-console/assets/{index-D7F9wNys.js → index-lyGm6l3x.js} +12 -12
  2. package/dist/assets/dev-console/index.html +2 -2
  3. package/dist/assets/speedscope/SourceCodePro-Regular.ttf.f546cbe0.woff2 +0 -0
  4. package/dist/assets/speedscope/demangle-cpp.1768f4cc.js +4 -0
  5. package/dist/assets/speedscope/favicon-16x16.f74b3187.png +0 -0
  6. package/dist/assets/speedscope/favicon-32x32.bc503437.png +0 -0
  7. package/dist/assets/speedscope/file-format-schema.json +324 -0
  8. package/dist/assets/speedscope/import.bcbb2033.js +123 -0
  9. package/dist/assets/speedscope/index.html +2 -0
  10. package/dist/assets/speedscope/perf-vertx-stacks-01-collapsed-all.2681da68.txt +199 -0
  11. package/dist/assets/speedscope/release.txt +3 -0
  12. package/dist/assets/speedscope/reset.8c46b7a1.css +2 -0
  13. package/dist/assets/speedscope/source-code-pro.52b1676f.css +2 -0
  14. package/dist/assets/speedscope/source-code-pro.LICENSE.md +93 -0
  15. package/dist/assets/speedscope/source-map.438fa06b.js +24 -0
  16. package/dist/assets/speedscope/speedscope.6f107512.js +193 -0
  17. package/dist/{chokidar-5LLC6S6D.js → chokidar-BLUAYFAB.js} +13 -1044
  18. package/dist/chokidar-OATAHMV6.js +1122 -0
  19. package/dist/{chunk-PWMEMGZN.js → chunk-2GCE2GUM.js} +3 -3
  20. package/dist/chunk-3I3GQNEW.js +95 -0
  21. package/dist/{chunk-OFYEMT6X.js → chunk-4QRIOWN3.js} +2 -2
  22. package/dist/{chunk-TIXENOYB.js → chunk-4W33LVQQ.js} +3 -3
  23. package/dist/{chunk-PVMQM44E.js → chunk-53WQGP7S.js} +4 -4
  24. package/dist/chunk-57Q6OQG4.js +111 -0
  25. package/dist/{chunk-MHUINF7I.js → chunk-5CLGH5PH.js} +2 -2
  26. package/dist/{chunk-CRHXI6PS.js → chunk-5DBS6QOU.js} +102 -638
  27. package/dist/{chunk-SNXQ36U2.js → chunk-5JC3BUPR.js} +3 -3
  28. package/dist/{chunk-3UQTWISO.js → chunk-5JWRABV2.js} +8 -8
  29. package/dist/{chunk-4SP4IRCQ.js → chunk-6JNRBEP6.js} +7 -9
  30. package/dist/{chunk-NHV2E73I.js → chunk-76NEANNG.js} +6442 -3165
  31. package/dist/{chunk-X4N2QZOS.js → chunk-7T4EKFVU.js} +16 -2
  32. package/dist/{chunk-I72O5WWR.js → chunk-ACIVN2Q4.js} +502 -699
  33. package/dist/{chunk-ZX3L2JKV.js → chunk-AKL7T64Q.js} +80 -133
  34. package/dist/{chunk-YVXC5Q6R.js → chunk-B27LGWRZ.js} +3 -3
  35. package/dist/{chunk-BUFIEXZ5.js → chunk-B3YWYURY.js} +701 -141
  36. package/dist/{chunk-X5WKMCE4.js → chunk-BWBSJLZN.js} +333 -156
  37. package/dist/{chunk-K7HGDAI4.js → chunk-CDBXAE2F.js} +20 -104
  38. package/dist/{chunk-SBPFWO4S.js → chunk-CDQA3SST.js} +56182 -37290
  39. package/dist/chunk-CP3BRHWK.js +33 -0
  40. package/dist/{chunk-RZOW7U2N.js → chunk-D5AR5HKB.js} +2 -2
  41. package/dist/chunk-EMPP4I5H.js +497 -0
  42. package/dist/{chunk-DZHO64DX.js → chunk-FCWD4NEK.js} +3 -3
  43. package/dist/{chunk-7JQIHXLD.js → chunk-FMXC2O6H.js} +2 -2
  44. package/dist/{chunk-P63UVLRS.js → chunk-GVMUVIT5.js} +7 -7
  45. package/dist/{chunk-KUM3DVPF.js → chunk-HMDWNGIV.js} +142 -471
  46. package/dist/{chunk-MJWFXPPX.js → chunk-I6YWZKVU.js} +2 -2
  47. package/dist/{chunk-MLL3JKVY.js → chunk-IYQNHNNP.js} +4 -4
  48. package/dist/{chunk-QIM24FVT.js → chunk-JWRRKMF2.js} +2 -2
  49. package/dist/{chunk-OXS42VB7.js → chunk-L3FVJFIT.js} +498 -412
  50. package/dist/{chunk-HIQDOFZI.js → chunk-LH6BHL6J.js} +3 -3
  51. package/dist/{chunk-OAZFIMJ3.js → chunk-LQ2ZKVR6.js} +45 -115
  52. package/dist/{chunk-4UAFBJXJ.js → chunk-MDJOXUMQ.js} +4 -4
  53. package/dist/{chunk-EKIVYQZC.js → chunk-MSBZRBI5.js} +4 -4
  54. package/dist/{chunk-3HBRMIPY.js → chunk-MW7RWHY5.js} +341 -211
  55. package/dist/{chunk-GLYEBL66.js → chunk-NUW6LQU4.js} +4 -4
  56. package/dist/{chunk-LPBV67AA.js → chunk-PMOQBQSE.js} +3 -3
  57. package/dist/{chunk-NQZUE7SY.js → chunk-QEUQO265.js} +5 -7
  58. package/dist/chunk-QRARFXIM.js +1137 -0
  59. package/dist/{chunk-KD7WMX4J.js → chunk-R7RENZQC.js} +3 -3
  60. package/dist/chunk-UB7RN523.js +15933 -0
  61. package/dist/{chunk-O72ZUVEA.js → chunk-VI4NVMJH.js} +2 -2
  62. package/dist/{chunk-RDZJQNFU.js → chunk-WBTJ7MQU.js} +3 -3
  63. package/dist/{chunk-CXHISGHD.js → chunk-WKO4CJCL.js} +5 -7
  64. package/dist/{chunk-6NZVGPSV.js → chunk-WNUVUNTL.js} +41 -23
  65. package/dist/{chunk-RBLSG22M.js → chunk-XBIDXV7B.js} +4 -4
  66. package/dist/{chunk-PBDGN4T2.js → chunk-XJNTFQIK.js} +5 -5
  67. package/dist/cli/commands/auth/logout.js +20 -19
  68. package/dist/cli/commands/auth/logout.test.js +22 -21
  69. package/dist/cli/commands/cache/clear.js +19 -18
  70. package/dist/cli/commands/debug/command-flags.js +19 -18
  71. package/dist/cli/commands/docs/generate.js +19 -18
  72. package/dist/cli/commands/docs/generate.test.js +20 -19
  73. package/dist/cli/commands/help.js +19 -18
  74. package/dist/cli/commands/kitchen-sink/async.js +20 -19
  75. package/dist/cli/commands/kitchen-sink/async.test.js +21 -20
  76. package/dist/cli/commands/kitchen-sink/index.js +22 -21
  77. package/dist/cli/commands/kitchen-sink/index.test.js +23 -22
  78. package/dist/cli/commands/kitchen-sink/prompts.js +20 -19
  79. package/dist/cli/commands/kitchen-sink/prompts.test.js +21 -20
  80. package/dist/cli/commands/kitchen-sink/static.js +20 -19
  81. package/dist/cli/commands/kitchen-sink/static.test.js +21 -20
  82. package/dist/cli/commands/notifications/generate.js +20 -19
  83. package/dist/cli/commands/notifications/list.js +20 -19
  84. package/dist/cli/commands/search.js +20 -19
  85. package/dist/cli/commands/upgrade.js +20 -19
  86. package/dist/cli/commands/upgrade.test.js +2 -1
  87. package/dist/cli/commands/version.js +20 -19
  88. package/dist/cli/commands/version.test.js +21 -20
  89. package/dist/cli/services/commands/notifications.js +14 -13
  90. package/dist/cli/services/commands/search.js +9 -8
  91. package/dist/cli/services/commands/search.test.js +10 -9
  92. package/dist/cli/services/commands/version.js +10 -9
  93. package/dist/cli/services/commands/version.test.js +12 -11
  94. package/dist/cli/services/kitchen-sink/async.js +9 -8
  95. package/dist/cli/services/kitchen-sink/prompts.js +9 -8
  96. package/dist/cli/services/kitchen-sink/static.js +9 -8
  97. package/dist/cli/services/upgrade.d.ts +0 -1
  98. package/dist/cli/services/upgrade.js +11 -10
  99. package/dist/cli/services/upgrade.test.js +14 -13
  100. package/dist/configs/all.yml +6 -0
  101. package/dist/configs/recommended.yml +6 -0
  102. package/dist/{custom-oclif-loader-L4JT3EUD.js → custom-oclif-loader-ZY5GUSB3.js} +9 -8
  103. package/dist/{del-P2RS6GN2.js → del-FBU5JYXS.js} +4 -4
  104. package/dist/{devtools-K7FXBBFZ.js → devtools-6LOQORRT.js} +2 -2
  105. package/dist/{error-handler-4CU3ZOV7.js → error-handler-YRN4E6SY.js} +17 -16
  106. package/dist/hooks/postrun.js +18 -16
  107. package/dist/hooks/prerun.js +15 -14
  108. package/dist/{http-proxy-FXWKYHZ3.js → http-proxy-L3MCJRQS.js} +3 -2
  109. package/dist/index.js +18723 -17426
  110. package/dist/lib-E2DSNKUX.js +13 -0
  111. package/dist/{local-2K66O4X2.js → local-VTZT5Q4L.js} +11 -10
  112. package/dist/{morph-OSHCID2F.js → morph-ACVSDUS7.js} +3 -3
  113. package/dist/{node-342GUJIM.js → node-ONVZF27D.js} +23 -20
  114. package/dist/{node-package-manager-RJSBCFD7.js → node-package-manager-BZNXJETD.js} +11 -10
  115. package/dist/{npa-TM76BGG3.js → npa-JAX2F6CO.js} +2 -2
  116. package/dist/out-AZBX4ITJ.js +7 -0
  117. package/dist/{path-2HZUSAGR.js → path-2K5HIMHZ.js} +3 -2
  118. package/dist/tsconfig.tsbuildinfo +1 -1
  119. package/dist/{ui-YBLW4B72.js → ui-3RKZNTJR.js} +9 -8
  120. package/dist/{workerd-5KR5CP5F.js → workerd-PSNADDQA.js} +23 -20
  121. package/oclif.manifest.json +103 -2
  122. package/package.json +9 -9
  123. package/LICENSE +0 -8
  124. package/dist/chunk-5YYJVU2L.js +0 -15746
  125. package/dist/chunk-HYVCBINV.js +0 -3811
  126. package/dist/lib-QZGSY5YB.js +0 -13
  127. package/dist/out-JR4DWQ2G.js +0 -7
  128. /package/dist/assets/dev-console/extensions/dev-console/assets/{index-Cgb-oKsM.css → index-n8yr6cxq.css} +0 -0
@@ -0,0 +1,1137 @@
1
+ import {
2
+ platformAndArch
3
+ } from "./chunk-4QRIOWN3.js";
4
+ import {
5
+ allAPIs,
6
+ buildHeaders,
7
+ shopifyFetch,
8
+ z
9
+ } from "./chunk-BWBSJLZN.js";
10
+ import {
11
+ cacheRetrieveOrRepopulate,
12
+ getPackageManager,
13
+ getSession,
14
+ packageManagerFromUserAgent,
15
+ removeSession,
16
+ setSession
17
+ } from "./chunk-ACIVN2Q4.js";
18
+ import {
19
+ AbortError,
20
+ BugError,
21
+ Environment,
22
+ FatalError,
23
+ addPublicMetadata,
24
+ addSensitiveMetadata,
25
+ ciPlatform,
26
+ cloudEnvironment,
27
+ currentProcessIsGlobal,
28
+ firstPartyDev,
29
+ getIdentityTokenInformation,
30
+ getPartnersToken,
31
+ hashString,
32
+ import_ts_error,
33
+ isAppManagementDisabled,
34
+ isCloudEnvironment,
35
+ isSpin,
36
+ isTTY,
37
+ keypress,
38
+ macAddress,
39
+ nonRandomUUID,
40
+ openURL,
41
+ outputCompleted,
42
+ outputContent,
43
+ outputDebug,
44
+ outputInfo,
45
+ outputToken,
46
+ serviceEnvironment,
47
+ sessionConstants,
48
+ spinFqdn,
49
+ themeKitAccessDomain,
50
+ themeToken
51
+ } from "./chunk-L3FVJFIT.js";
52
+ import {
53
+ cwd
54
+ } from "./chunk-57Q6OQG4.js";
55
+ import {
56
+ __commonJS,
57
+ __require,
58
+ __toESM,
59
+ init_cjs_shims
60
+ } from "./chunk-PKR7KJ6P.js";
61
+
62
+ // ../../node_modules/.pnpm/network-interfaces@1.1.0/node_modules/network-interfaces/index.js
63
+ var require_network_interfaces = __commonJS({
64
+ "../../node_modules/.pnpm/network-interfaces@1.1.0/node_modules/network-interfaces/index.js"(exports) {
65
+ "use strict";
66
+ init_cjs_shims();
67
+ var os2 = __require("os");
68
+ function isValid(address, options) {
69
+ return !(typeof options.internal == "boolean" && address.internal !== options.internal || options.ipVersion === 4 && address.family !== "IPv4" || options.ipVersion === 6 && address.family !== "IPv6");
70
+ }
71
+ function findAddresses(interfaceName, options = {}) {
72
+ let addresses = os2.networkInterfaces()[interfaceName];
73
+ if (!addresses)
74
+ throw new Error(`Network interface "${interfaceName}" does not exist`);
75
+ let result = [];
76
+ for (let address of addresses)
77
+ isValid(address, options) && result.push(address);
78
+ return result;
79
+ }
80
+ exports.toIp = function(interfaceName, options) {
81
+ let addresses = findAddresses(interfaceName, options);
82
+ if (addresses.length === 0)
83
+ throw new Error(`No suitable IP address found on interface "${interfaceName}"`);
84
+ return addresses[0].address;
85
+ };
86
+ exports.toIps = function(interfaceName, options) {
87
+ return findAddresses(interfaceName, options).map((address) => address.address);
88
+ };
89
+ exports.fromIp = function(ip, options) {
90
+ let interfaces = os2.networkInterfaces(), interfaceNames = Object.keys(interfaces);
91
+ for (let interfaceName of interfaceNames)
92
+ for (let address of interfaces[interfaceName])
93
+ if (address.address === ip && isValid(address, options))
94
+ return interfaceName;
95
+ throw new Error(`No suitable interfaces were found with IP address "${ip}"`);
96
+ };
97
+ exports.getInterface = function(options) {
98
+ let interfaces = os2.networkInterfaces(), interfaceNames = Object.keys(interfaces);
99
+ for (let interfaceName of interfaceNames)
100
+ if (findAddresses(interfaceName, options).length > 0)
101
+ return interfaceName;
102
+ throw new Error("No suitable interfaces were found");
103
+ };
104
+ exports.getInterfaces = function(options) {
105
+ let interfaces = os2.networkInterfaces(), interfaceNames = Object.keys(interfaces), result = [];
106
+ for (let interfaceName of interfaceNames)
107
+ findAddresses(interfaceName, options).length > 0 && result.push(interfaceName);
108
+ return result;
109
+ };
110
+ }
111
+ });
112
+
113
+ // ../cli-kit/dist/private/node/analytics.js
114
+ init_cjs_shims();
115
+
116
+ // ../cli-kit/dist/private/node/session.js
117
+ init_cjs_shims();
118
+
119
+ // ../cli-kit/dist/private/node/session/identity.js
120
+ init_cjs_shims();
121
+ function clientId() {
122
+ let environment = serviceEnvironment();
123
+ return environment === Environment.Local ? "e5380e02-312a-7408-5718-e07017e9cf52" : environment === Environment.Production ? "fbdb2649-e327-4907-8f67-908d24cfd7e3" : "e5380e02-312a-7408-5718-e07017e9cf52";
124
+ }
125
+ function applicationId(api) {
126
+ switch (api) {
127
+ case "admin": {
128
+ let environment = serviceEnvironment();
129
+ return environment === Environment.Local ? "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52" : environment === Environment.Production ? "7ee65a63608843c577db8b23c4d7316ea0a01bd2f7594f8a9c06ea668c1b775c" : "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52";
130
+ }
131
+ case "partners": {
132
+ let environment = serviceEnvironment();
133
+ return environment === Environment.Local ? "df89d73339ac3c6c5f0a98d9ca93260763e384d51d6038da129889c308973978" : environment === Environment.Production ? "271e16d403dfa18082ffb3d197bd2b5f4479c3fc32736d69296829cbb28d41a6" : "df89d73339ac3c6c5f0a98d9ca93260763e384d51d6038da129889c308973978";
134
+ }
135
+ case "storefront-renderer": {
136
+ let environment = serviceEnvironment();
137
+ return environment === Environment.Local ? "46f603de-894f-488d-9471-5b721280ff49" : environment === Environment.Production ? "ee139b3d-5861-4d45-b387-1bc3ada7811c" : "46f603de-894f-488d-9471-5b721280ff49";
138
+ }
139
+ case "business-platform": {
140
+ let environment = serviceEnvironment();
141
+ return environment === Environment.Local ? "ace6dc89-b526-456d-a942-4b8ef6acda4b" : environment === Environment.Production ? "32ff8ee5-82b8-4d93-9f8a-c6997cefb7dc" : "ace6dc89-b526-456d-a942-4b8ef6acda4b";
142
+ }
143
+ case "app-management":
144
+ return serviceEnvironment() === Environment.Production ? "7ee65a63608843c577db8b23c4d7316ea0a01bd2f7594f8a9c06ea668c1b775c" : "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52";
145
+ default:
146
+ throw new BugError(`Application id for API of type: ${api}`);
147
+ }
148
+ }
149
+
150
+ // ../cli-kit/dist/private/node/session/validate.js
151
+ init_cjs_shims();
152
+
153
+ // ../cli-kit/dist/private/node/session/schema.js
154
+ init_cjs_shims();
155
+ var DateSchema = z.preprocess((arg) => typeof arg == "string" || arg instanceof Date ? new Date(arg) : null, z.date()), IdentityTokenSchema = z.object({
156
+ accessToken: z.string(),
157
+ refreshToken: z.string(),
158
+ expiresAt: DateSchema,
159
+ scopes: z.array(z.string()),
160
+ userId: z.string()
161
+ }), ApplicationTokenSchema = z.object({
162
+ accessToken: z.string(),
163
+ expiresAt: DateSchema,
164
+ scopes: z.array(z.string())
165
+ }), SessionSchema = z.object({}).catchall(z.object({
166
+ /**
167
+ * It contains the identity token. Before usint it, we exchange it
168
+ * to get a token that we can use with different applications. The exchanged
169
+ * tokens for the applications are stored under applications.
170
+ */
171
+ identity: IdentityTokenSchema,
172
+ /**
173
+ * It contains exchanged tokens for the applications the CLI
174
+ * authenticates with. Tokens are scoped under the fqdn of the applications.
175
+ */
176
+ applications: z.object({}).catchall(ApplicationTokenSchema)
177
+ }));
178
+ function validateCachedIdentityTokenStructure(identityToken) {
179
+ return IdentityTokenSchema.safeParse(identityToken).success;
180
+ }
181
+
182
+ // ../cli-kit/dist/private/node/session/identity-token-validation.js
183
+ init_cjs_shims();
184
+
185
+ // ../cli-kit/dist/public/node/context/fqdn.js
186
+ init_cjs_shims();
187
+
188
+ // ../cli-kit/dist/public/node/vendor/dev_server/DevServer.js
189
+ init_cjs_shims();
190
+ var ni = __toESM(require_network_interfaces(), 1);
191
+ import fs from "fs";
192
+ import * as os from "os";
193
+ import { execSync } from "child_process";
194
+ var DevServerUtils = class _DevServerUtils {
195
+ static assertConnectable(name, addr, port) {
196
+ try {
197
+ execSync(`nc -z -v -w 1 ${addr} ${port}`, {
198
+ timeout: _DevServerUtils.CONNECT_TIMEOUT,
199
+ stdio: "ignore"
200
+ });
201
+ } catch {
202
+ throw new Error(`NET FAILED DevServer for '${name}' is not running on ${port} / ${addr}: \`dev up ${name}\` to start it.`);
203
+ }
204
+ }
205
+ static inferenceModeAndProjectIsEdition2016(name) {
206
+ try {
207
+ fs.accessSync(_DevServerUtils.INFERENCE_MODE_SENTINEL);
208
+ try {
209
+ return fs.accessSync(`/opt/nginx/etc/manifest/${name}/current/edition-2024`), !1;
210
+ } catch {
211
+ return !0;
212
+ }
213
+ } catch {
214
+ return !1;
215
+ }
216
+ }
217
+ static getIpFromHosts(hostname) {
218
+ try {
219
+ let lines = fs.readFileSync(_DevServerUtils.HOSTS_FILE, "utf8").split(/\r?\n/);
220
+ for (let line of lines) {
221
+ let matches = /^\s*?([^#]+?)\s+([^#]+?)$/.exec(line);
222
+ if (matches && matches.length === 3 && matches[2] === hostname)
223
+ return matches[1];
224
+ }
225
+ } catch (error) {
226
+ console.error("Error reading hosts file:", error);
227
+ }
228
+ throw new Error(`No IP found for hostname: ${hostname}`);
229
+ }
230
+ static getAddrPort2024(name) {
231
+ try {
232
+ let backendIp = _DevServerUtils.resolveBackendHost(name), interfaceName = ni.fromIp(backendIp, {
233
+ internal: !0,
234
+ ipVersion: 4
235
+ });
236
+ return [backendIp, _DevServerUtils.BACKEND_PORT];
237
+ } catch {
238
+ throw new Error(`DevServer for '${name}' is not running: \`dev up ${name}\` to start it.`);
239
+ }
240
+ }
241
+ static getAddrPort2016(name) {
242
+ try {
243
+ let portContent = fs.readFileSync(`${os.homedir()}/.local/run/services/${name}/server/port`, "utf-8");
244
+ return ["localhost", parseInt(portContent, 10)];
245
+ } catch {
246
+ throw new Error(`DevServer for '${name}' is not running: \`dev up ${name}\` to start it.`);
247
+ }
248
+ }
249
+ static resolveBackendHost(name) {
250
+ let host;
251
+ try {
252
+ host = fs.readlinkSync(`/opt/nginx/etc/manifest/${name}/current`);
253
+ } catch {
254
+ host = `${name}.root.shopify.dev.internal`;
255
+ }
256
+ try {
257
+ return _DevServerUtils.getIpFromHosts(host);
258
+ } catch {
259
+ return host;
260
+ }
261
+ }
262
+ };
263
+ DevServerUtils.INFERENCE_MODE_SENTINEL = "/opt/dev/misc/dev-server-inference-mode";
264
+ DevServerUtils.BACKEND_PORT = 8080;
265
+ DevServerUtils.CONNECT_TIMEOUT = 100;
266
+ DevServerUtils.HOSTS_FILE = "/etc/hosts";
267
+ var DevServer = class {
268
+ constructor(name) {
269
+ if (!process.env.SPIN && !process.env.USING_DEV)
270
+ throw new Error("DevServer is not supported in this environment");
271
+ if (name === "shopify")
272
+ throw new Error("Use DevServer.core for the 'shopify' project");
273
+ this.name = name;
274
+ }
275
+ url({ nonstandardHostPrefix } = {}) {
276
+ return `https://${this.host({ nonstandardHostPrefix })}`;
277
+ }
278
+ host({ nonstandardHostPrefix } = {}) {
279
+ let prefix = nonstandardHostPrefix || this.name;
280
+ if (process.env.SPIN === "1") {
281
+ let services = fs.readdirSync("/run/ports2").filter((file) => file.endsWith(`--${this.name}`));
282
+ if (services.length === 0)
283
+ throw new Error(`DevServer for '${this.name}' not present in this spin environment`);
284
+ let match = new RegExp(`^(.+)${this.name}$`).exec(services[0]), organization = match ? match[1] : "";
285
+ return `${organization !== "shopify--" ? `${organization}` : ""}${this.name}.${process.env.SPIN_FQDN}`;
286
+ } else return DevServerUtils.inferenceModeAndProjectIsEdition2016(this.name) ? (this.assertRunningLocally2016(), `${prefix}.myshopify.io`) : (this.assertRunningLocally2024(), `${prefix}.shop.dev`);
287
+ }
288
+ assertRunningLocally2024() {
289
+ let [addr, port] = DevServerUtils.getAddrPort2024(this.name);
290
+ DevServerUtils.assertConnectable(this.name, addr, port);
291
+ }
292
+ assertRunningLocally2016() {
293
+ let [addr, port] = DevServerUtils.getAddrPort2016(this.name);
294
+ DevServerUtils.assertConnectable(this.name, addr, port);
295
+ }
296
+ }, DevServerCore = class {
297
+ constructor() {
298
+ this.name = "shopify";
299
+ }
300
+ url(prefix) {
301
+ return `https://${this.host(prefix)}`;
302
+ }
303
+ host(prefix) {
304
+ if (process.env.SPIN === "1") {
305
+ if (!fs.readdirSync("/run/ports2").find((file) => file.endsWith(`--${this.name}`)))
306
+ throw new Error(`DevServer for '${this.name}' not present in this spin environment`);
307
+ return `${prefix}.${this.name}.${process.env.SPIN_FQDN}`;
308
+ } else return DevServerUtils.inferenceModeAndProjectIsEdition2016("shopify") ? (this.assertRunningLocally2016(), `${prefix}.myshopify.io`) : (this.assertRunningLocally2024(), `${prefix}.my.shop.dev`);
309
+ }
310
+ assertRunningLocally2024() {
311
+ let [addr, port] = DevServerUtils.getAddrPort2024("shopify");
312
+ DevServerUtils.assertConnectable("shopify", addr, port);
313
+ }
314
+ assertRunningLocally2016() {
315
+ let [addr, port] = DevServerUtils.getAddrPort2016("shopify");
316
+ DevServerUtils.assertConnectable("shopify", addr, port);
317
+ }
318
+ };
319
+
320
+ // ../cli-kit/dist/public/node/context/fqdn.js
321
+ var CouldntObtainPartnersSpinFQDNError = new AbortError("Couldn't obtain the Spin FQDN for Partners when the CLI is not running from a Spin environment."), CouldntObtainIdentitySpinFQDNError = new AbortError("Couldn't obtain the Spin FQDN for Identity when the CLI is not running from a Spin environment."), CouldntObtainShopifySpinFQDNError = new AbortError("Couldn't obtain the Spin FQDN for Shopify when the CLI is not running from a Spin environment."), NotProvidedStoreFQDNError = new AbortError("Couldn't obtain the Shopify FQDN because the store FQDN was not provided.");
322
+ async function partnersFqdn() {
323
+ let environment = serviceEnvironment(), productionFqdn = "partners.shopify.com";
324
+ switch (environment) {
325
+ case "local":
326
+ return new DevServer("partners").host();
327
+ case "spin":
328
+ return `partners.${await spinFqdn()}`;
329
+ default:
330
+ return productionFqdn;
331
+ }
332
+ }
333
+ async function appManagementFqdn() {
334
+ let environment = serviceEnvironment(), productionFqdn = "app.shopify.com";
335
+ switch (environment) {
336
+ case "local":
337
+ return new DevServerCore().host("app");
338
+ case "spin":
339
+ return `app.shopify.${await spinFqdn()}`;
340
+ default:
341
+ return productionFqdn;
342
+ }
343
+ }
344
+ async function developerDashboardFqdn() {
345
+ let environment = serviceEnvironment(), productionFqdn = "dev.shopify.com";
346
+ switch (environment) {
347
+ case "local":
348
+ return new DevServerCore().host("dev");
349
+ case "spin":
350
+ return `dev.shopify.${await spinFqdn()}`;
351
+ default:
352
+ return productionFqdn;
353
+ }
354
+ }
355
+ async function businessPlatformFqdn() {
356
+ let environment = serviceEnvironment(), productionFqdn = "destinations.shopifysvc.com";
357
+ switch (environment) {
358
+ case "local":
359
+ return new DevServer("business-platform").host();
360
+ case "spin":
361
+ return `business-platform.${await spinFqdn()}`;
362
+ default:
363
+ return productionFqdn;
364
+ }
365
+ }
366
+ async function identityFqdn() {
367
+ let environment = serviceEnvironment(), productionFqdn = "accounts.shopify.com";
368
+ switch (environment) {
369
+ case "local":
370
+ return new DevServer("identity").host();
371
+ case "spin":
372
+ return `identity.${await spinFqdn()}`;
373
+ default:
374
+ return productionFqdn;
375
+ }
376
+ }
377
+ async function normalizeStoreFqdn(store2) {
378
+ let storeFqdn = store2.replace(/^https?:\/\//, "").replace(/\/$/, ""), addDomain = async (storeFqdn2) => {
379
+ switch (serviceEnvironment()) {
380
+ case "local":
381
+ return new DevServerCore().host(storeFqdn2);
382
+ case "spin":
383
+ return `${storeFqdn2}.shopify.${await spinFqdn()}`;
384
+ default:
385
+ return `${storeFqdn2}.myshopify.com`;
386
+ }
387
+ };
388
+ return ((storeFqdn2) => storeFqdn2.includes(".myshopify.com") || storeFqdn2.includes("spin.dev") || storeFqdn2.includes("shopify.io") || storeFqdn2.includes(".shop.dev"))(storeFqdn) ? storeFqdn : addDomain(storeFqdn);
389
+ }
390
+
391
+ // ../cli-kit/dist/public/node/result.js
392
+ init_cjs_shims();
393
+ var ok = (value) => new Ok(value), err = (err2) => new Err(err2), Ok = class {
394
+ constructor(value) {
395
+ this.value = value;
396
+ }
397
+ /**
398
+ * Check if a `Result` is an `Err` inferring its type. `!isErr()` should be used before accessing the `value`
399
+ *
400
+ * @returns `false` as the `Resul` is `OK`
401
+ */
402
+ isErr() {
403
+ return !1;
404
+ }
405
+ /**
406
+ * Runs the `handler` method an return the same an unaltered copy of the `Result`. It could be used to log an
407
+ * output when the result is `Ok` without breaking the flow
408
+ *
409
+ * @param handler - method to be run when the result is `Ok`
410
+ * @returns a copy of the same `Result`
411
+ */
412
+ doOnOk(handler) {
413
+ return handler(this.value), ok(this.value);
414
+ }
415
+ /**
416
+ * A safe mode to throw the `error` of the `Result`
417
+ */
418
+ valueOrBug() {
419
+ return this.value;
420
+ }
421
+ /**
422
+ * Throws an abort error if the result doesn't represent a value.
423
+ */
424
+ valueOrAbort() {
425
+ return this.value;
426
+ }
427
+ /**
428
+ * Maps the value to another one with a different type. It leaves the `Error` type unaltered
429
+ *
430
+ * @param mapper - The mapper method to apply an `OK` value
431
+ * @returns a new result with the new mapped value
432
+ */
433
+ map(mapper) {
434
+ return ok(mapper(this.value));
435
+ }
436
+ /**
437
+ * Maps the error type to another one. It leaves the `Ok` type and value unaltered
438
+ *
439
+ * @param _mapper - This mapper method is not used for an `Ok` value
440
+ * @returns a new result with the new mapped error type and an value
441
+ */
442
+ mapError(_mapper) {
443
+ return ok(this.value);
444
+ }
445
+ }, Err = class {
446
+ // eslint-disable-next-line node/handle-callback-err
447
+ constructor(error) {
448
+ this.error = error;
449
+ }
450
+ /**
451
+ * Check if a `Result` is an `Err` inferring its type. `!isErr()` should be used before accessing the `value`
452
+ *
453
+ * @returns `false` as the `Resul` is `OK`
454
+ */
455
+ isErr() {
456
+ return !0;
457
+ }
458
+ /**
459
+ * Return an unaltered copy of the `Error` without doing anything.
460
+ *
461
+ * @param _handler - This handler method is not used for an `Error`
462
+ * @returns a copy of the same `Error`
463
+ */
464
+ doOnOk(_handler) {
465
+ return err(this.error);
466
+ }
467
+ /**
468
+ * A safe mode to throw the `error` of the `Result`
469
+ */
470
+ valueOrBug() {
471
+ throw this.error;
472
+ }
473
+ /**
474
+ * Throws an abort error if the result doesn't represent a value.
475
+ */
476
+ valueOrAbort() {
477
+ if (this.error instanceof FatalError)
478
+ throw this.error;
479
+ if (this.error instanceof import_ts_error.ExtendableError || this.error instanceof Error) {
480
+ let error = new AbortError(this.error.message);
481
+ throw error.stack = this.error.stack, error;
482
+ } else
483
+ throw new AbortError(`${this.error}`);
484
+ }
485
+ /**
486
+ * Maps the value type to another one. It leaves the `Error` unaltered
487
+ *
488
+ * @param _mapper - This mapper method is not used for an `Error` value
489
+ * @returns a new result with the new value type and an unaltered error
490
+ */
491
+ map(_mapper) {
492
+ return err(this.error);
493
+ }
494
+ /**
495
+ * Maps the error to another one with a different type. It leaves the value type unaltered
496
+ *
497
+ * @param mapper - The mapper method to apply an `Error` value
498
+ * @returns a new result with the new mapped error
499
+ */
500
+ mapError(mapper) {
501
+ return err(mapper(this.error));
502
+ }
503
+ };
504
+
505
+ // ../cli-kit/dist/private/node/session/identity-token-validation.js
506
+ async function validateIdentityToken(token) {
507
+ if (isSpin() && firstPartyDev())
508
+ return !0;
509
+ try {
510
+ return withIntrospectionURL(async (introspectionURL) => {
511
+ let options = {
512
+ method: "POST",
513
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
514
+ body: JSON.stringify({ token })
515
+ };
516
+ outputDebug(`Sending Identity Introspection request to URL: ${introspectionURL}`);
517
+ let response = await shopifyFetch(introspectionURL, options);
518
+ if (response.ok && response.headers.get("content-type")?.includes("json")) {
519
+ let json = await response.json();
520
+ return outputDebug(`The identity token is valid: ${json.valid}`), ok(json.valid);
521
+ } else {
522
+ if (response.status === 404 || response.status > 500)
523
+ return err(new AbortError(`The introspection endpoint returned a ${response.status}: ${introspectionURL}`));
524
+ {
525
+ let text = await response.text();
526
+ return outputDebug(`The Introspection request failed with:
527
+ - status: ${response.status}
528
+ - www-authenticate header: ${JSON.stringify(response.headers.get("www-authenticate"))}
529
+ - body: ${JSON.stringify(text)}`), ok(!1);
530
+ }
531
+ }
532
+ });
533
+ } catch (error) {
534
+ return outputDebug(`The identity token is invalid: ${error}`), !1;
535
+ }
536
+ }
537
+ async function withIntrospectionURL(fn) {
538
+ let cacheKey = `identity-introspection-url-${await identityFqdn()}`, introspectionURL = await cacheRetrieveOrRepopulate(cacheKey, getIntrospectionURL, 6048e5), result = await fn(introspectionURL);
539
+ if (result.isErr() && (introspectionURL = await cacheRetrieveOrRepopulate(cacheKey, getIntrospectionURL, 0), result = await fn(introspectionURL)), result.isErr())
540
+ throw result.error;
541
+ return result.value;
542
+ }
543
+ async function getIntrospectionURL() {
544
+ return (await (await shopifyFetch(`https://${await identityFqdn()}/.well-known/openid-configuration.json`)).json()).introspection_endpoint;
545
+ }
546
+
547
+ // ../cli-kit/dist/private/node/session/validate.js
548
+ function validateScopes(requestedScopes, identity) {
549
+ let currentScopes = identity.scopes;
550
+ return firstPartyDev() !== currentScopes.includes("employee") ? !1 : requestedScopes.every((scope) => currentScopes.includes(scope));
551
+ }
552
+ async function validateSession(scopes, applications, session) {
553
+ if (!session)
554
+ return "needs_full_auth";
555
+ let scopesAreValid = validateScopes(scopes, session.identity), identityIsValid = await validateIdentityToken(session.identity.accessToken);
556
+ if (!scopesAreValid)
557
+ return "needs_full_auth";
558
+ let tokensAreExpired = isTokenExpired(session.identity);
559
+ if (applications.partnersApi) {
560
+ let appId = applicationId("partners"), token = session.applications[appId];
561
+ tokensAreExpired = tokensAreExpired || isTokenExpired(token);
562
+ }
563
+ if (applications.appManagementApi) {
564
+ let appId = applicationId("app-management"), token = session.applications[appId];
565
+ tokensAreExpired = tokensAreExpired || isTokenExpired(token);
566
+ }
567
+ if (applications.storefrontRendererApi) {
568
+ let appId = applicationId("storefront-renderer"), token = session.applications[appId];
569
+ tokensAreExpired = tokensAreExpired || isTokenExpired(token);
570
+ }
571
+ if (applications.adminApi) {
572
+ let appId = applicationId("admin"), realAppId = `${applications.adminApi.storeFqdn}-${appId}`, token = session.applications[realAppId];
573
+ tokensAreExpired = tokensAreExpired || isTokenExpired(token);
574
+ }
575
+ return outputDebug(`
576
+ The validation of the token for application/identity completed with the following results:
577
+ - It's expired: ${tokensAreExpired}
578
+ - It's invalid in identity: ${!identityIsValid}
579
+ `), validateCachedIdentityTokenStructure(session.identity) ? tokensAreExpired ? "needs_refresh" : identityIsValid ? "ok" : "needs_full_auth" : "needs_full_auth";
580
+ }
581
+ function isTokenExpired(token) {
582
+ return token ? token.expiresAt < expireThreshold() : !0;
583
+ }
584
+ function expireThreshold() {
585
+ return new Date(Date.now() + sessionConstants.expirationTimeMarginInMinutes * 60 * 1e3);
586
+ }
587
+
588
+ // ../cli-kit/dist/private/node/session/scopes.js
589
+ init_cjs_shims();
590
+ function allDefaultScopes(extraScopes = []) {
591
+ let scopes = allAPIs.map((api) => defaultApiScopes(api)).flat();
592
+ return scopes = ["openid", ...scopes, ...extraScopes].map(scopeTransform), Array.from(new Set(scopes));
593
+ }
594
+ function apiScopes(api, extraScopes = []) {
595
+ let scopes = [...defaultApiScopes(api), ...extraScopes.map(scopeTransform)].map(scopeTransform);
596
+ return Array.from(new Set(scopes));
597
+ }
598
+ function defaultApiScopes(api) {
599
+ switch (api) {
600
+ case "admin":
601
+ return ["graphql", "themes", "collaborator"];
602
+ case "storefront-renderer":
603
+ return ["devtools"];
604
+ case "partners":
605
+ return ["cli"];
606
+ case "business-platform":
607
+ return ["destinations", "store-management"];
608
+ case "app-management":
609
+ return ["app-management"];
610
+ default:
611
+ throw new BugError(`Unknown API: ${api}`);
612
+ }
613
+ }
614
+ function scopeTransform(scope) {
615
+ switch (scope) {
616
+ case "graphql":
617
+ return "https://api.shopify.com/auth/shop.admin.graphql";
618
+ case "themes":
619
+ return "https://api.shopify.com/auth/shop.admin.themes";
620
+ case "collaborator":
621
+ return "https://api.shopify.com/auth/partners.collaborator-relationships.readonly";
622
+ case "cli":
623
+ return "https://api.shopify.com/auth/partners.app.cli.access";
624
+ case "devtools":
625
+ return "https://api.shopify.com/auth/shop.storefront-renderer.devtools";
626
+ case "destinations":
627
+ return "https://api.shopify.com/auth/destinations.readonly";
628
+ case "store-management":
629
+ return "https://api.shopify.com/auth/organization.store-management";
630
+ case "app-management":
631
+ return "https://api.shopify.com/auth/organization.apps.manage";
632
+ default:
633
+ return scope;
634
+ }
635
+ }
636
+
637
+ // ../cli-kit/dist/private/node/session/exchange.js
638
+ init_cjs_shims();
639
+
640
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/index.js
641
+ init_cjs_shims();
642
+
643
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/runtime/base64url.js
644
+ init_cjs_shims();
645
+ import { Buffer } from "node:buffer";
646
+
647
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/lib/buffer_utils.js
648
+ init_cjs_shims();
649
+ var encoder = new TextEncoder(), decoder = new TextDecoder(), MAX_INT32 = 2 ** 32;
650
+
651
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/runtime/base64url.js
652
+ function normalize(input) {
653
+ let encoded = input;
654
+ return encoded instanceof Uint8Array && (encoded = decoder.decode(encoded)), encoded;
655
+ }
656
+ var decode = (input) => new Uint8Array(Buffer.from(normalize(input), "base64url"));
657
+
658
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/errors.js
659
+ init_cjs_shims();
660
+ var JOSEError = class extends Error {
661
+ static code = "ERR_JOSE_GENERIC";
662
+ code = "ERR_JOSE_GENERIC";
663
+ constructor(message, options) {
664
+ super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
665
+ }
666
+ };
667
+ var JWTInvalid = class extends JOSEError {
668
+ static code = "ERR_JWT_INVALID";
669
+ code = "ERR_JWT_INVALID";
670
+ };
671
+
672
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/lib/is_object.js
673
+ init_cjs_shims();
674
+ function isObjectLike(value) {
675
+ return typeof value == "object" && value !== null;
676
+ }
677
+ function isObject(input) {
678
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]")
679
+ return !1;
680
+ if (Object.getPrototypeOf(input) === null)
681
+ return !0;
682
+ let proto = input;
683
+ for (; Object.getPrototypeOf(proto) !== null; )
684
+ proto = Object.getPrototypeOf(proto);
685
+ return Object.getPrototypeOf(input) === proto;
686
+ }
687
+
688
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/base64url.js
689
+ init_cjs_shims();
690
+ var decode2 = decode;
691
+
692
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/decode_jwt.js
693
+ init_cjs_shims();
694
+ function decodeJwt(jwt) {
695
+ if (typeof jwt != "string")
696
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
697
+ let { 1: payload, length } = jwt.split(".");
698
+ if (length === 5)
699
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
700
+ if (length !== 3)
701
+ throw new JWTInvalid("Invalid JWT");
702
+ if (!payload)
703
+ throw new JWTInvalid("JWTs must contain a payload");
704
+ let decoded;
705
+ try {
706
+ decoded = decode2(payload);
707
+ } catch {
708
+ throw new JWTInvalid("Failed to base64url decode the payload");
709
+ }
710
+ let result;
711
+ try {
712
+ result = JSON.parse(decoder.decode(decoded));
713
+ } catch {
714
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
715
+ }
716
+ if (!isObject(result))
717
+ throw new JWTInvalid("Invalid JWT Claims Set");
718
+ return result;
719
+ }
720
+
721
+ // ../cli-kit/dist/private/node/session/exchange.js
722
+ var InvalidGrantError = class extends import_ts_error.ExtendableError {
723
+ }, InvalidRequestError = class extends import_ts_error.ExtendableError {
724
+ }, InvalidTargetError = class extends AbortError {
725
+ };
726
+ async function exchangeAccessForApplicationTokens(identityToken, scopes, store2) {
727
+ let token = identityToken.accessToken, [partners, storefront, businessPlatform, admin, appManagement] = await Promise.all([
728
+ requestAppToken("partners", token, scopes.partners),
729
+ requestAppToken("storefront-renderer", token, scopes.storefront),
730
+ requestAppToken("business-platform", token, scopes.businessPlatform),
731
+ store2 ? requestAppToken("admin", token, scopes.admin, store2) : {},
732
+ isAppManagementDisabled() ? {} : requestAppToken("app-management", token, scopes.appManagement)
733
+ ]);
734
+ return {
735
+ ...partners,
736
+ ...storefront,
737
+ ...businessPlatform,
738
+ ...admin,
739
+ ...appManagement
740
+ };
741
+ }
742
+ async function refreshAccessToken(currentToken) {
743
+ let clientId2 = clientId(), params = {
744
+ grant_type: "refresh_token",
745
+ access_token: currentToken.accessToken,
746
+ refresh_token: currentToken.refreshToken,
747
+ client_id: clientId2
748
+ }, value = (await tokenRequest(params)).mapError(tokenRequestErrorHandler).valueOrBug();
749
+ return buildIdentityToken(value, currentToken.userId);
750
+ }
751
+ async function exchangeCustomPartnerToken(token) {
752
+ let appId = applicationId("partners");
753
+ try {
754
+ let accessToken = (await requestAppToken("partners", token, ["https://api.shopify.com/auth/partners.app.cli.access"]))[appId].accessToken, userId2 = nonRandomUUID(token);
755
+ return setLastSeenUserIdAfterAuth(userId2), setLastSeenAuthMethod("partners_token"), { accessToken, userId: userId2 };
756
+ } catch {
757
+ throw new AbortError("The custom token provided is invalid.", "Ensure the token is correct and not expired.");
758
+ }
759
+ }
760
+ async function exchangeDeviceCodeForAccessToken(deviceCode) {
761
+ let clientId2 = await clientId(), tokenResult = await tokenRequest({
762
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
763
+ device_code: deviceCode,
764
+ client_id: clientId2
765
+ });
766
+ if (tokenResult.isErr())
767
+ return err(tokenResult.error);
768
+ let identityToken = buildIdentityToken(tokenResult.value);
769
+ return ok(identityToken);
770
+ }
771
+ async function requestAppToken(api, token, scopes = [], store2) {
772
+ let appId = applicationId(api), params = {
773
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
774
+ requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
775
+ subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
776
+ client_id: await clientId(),
777
+ audience: appId,
778
+ scope: scopes.join(" "),
779
+ subject_token: token,
780
+ ...api === "admin" && { destination: `https://${store2}/admin` }
781
+ }, identifier = appId;
782
+ api === "admin" && store2 && (identifier = `${store2}-${appId}`);
783
+ let value = (await tokenRequest(params)).mapError(tokenRequestErrorHandler).valueOrBug(), appToken = buildApplicationToken(value);
784
+ return { [identifier]: appToken };
785
+ }
786
+ function tokenRequestErrorHandler(error) {
787
+ let invalidTargetErrorMessage = `You are not authorized to use the CLI to develop in the provided store.
788
+
789
+ You can't use Shopify CLI with development stores if you only have Partner staff member access. If you want to use Shopify CLI to work on a development store, then you should be the store owner or create a staff account on the store.
790
+
791
+ If you're the store owner, then you need to log in to the store directly using the store URL at least once before you log in using Shopify CLI.Logging in to the Shopify admin directly connects the development store with your Shopify login.`;
792
+ return error === "invalid_grant" ? new InvalidGrantError() : error === "invalid_request" ? new InvalidRequestError() : error === "invalid_target" ? new InvalidTargetError(invalidTargetErrorMessage) : new AbortError(error);
793
+ }
794
+ async function tokenRequest(params) {
795
+ let fqdn = await identityFqdn(), url = new URL(`https://${fqdn}/oauth/token`);
796
+ url.search = new URLSearchParams(Object.entries(params)).toString();
797
+ let res = await shopifyFetch(url.href, { method: "POST" }), payload = await res.json();
798
+ return res.ok ? ok(payload) : err(payload.error);
799
+ }
800
+ function buildIdentityToken(result, existingUserId) {
801
+ let userId2 = existingUserId ?? (result.id_token ? decodeJwt(result.id_token).sub : void 0);
802
+ if (!userId2)
803
+ throw new BugError("Error setting userId for session. No id_token or pre-existing user ID provided.");
804
+ return {
805
+ accessToken: result.access_token,
806
+ refreshToken: result.refresh_token,
807
+ expiresAt: new Date(Date.now() + result.expires_in * 1e3),
808
+ scopes: result.scope.split(" "),
809
+ userId: userId2
810
+ };
811
+ }
812
+ function buildApplicationToken(result) {
813
+ return {
814
+ accessToken: result.access_token,
815
+ expiresAt: new Date(Date.now() + result.expires_in * 1e3),
816
+ scopes: result.scope.split(" ")
817
+ };
818
+ }
819
+
820
+ // ../cli-kit/dist/private/node/session/store.js
821
+ init_cjs_shims();
822
+ async function store(session) {
823
+ let jsonSession = JSON.stringify(session);
824
+ setSession(jsonSession);
825
+ }
826
+ async function fetch() {
827
+ let content = getSession();
828
+ if (!content)
829
+ return;
830
+ let contentJson = JSON.parse(content), parsedSession = await SessionSchema.safeParseAsync(contentJson);
831
+ if (parsedSession.success)
832
+ return parsedSession.data;
833
+ await remove();
834
+ }
835
+ async function remove() {
836
+ removeSession();
837
+ }
838
+
839
+ // ../cli-kit/dist/private/node/session/device-authorization.js
840
+ init_cjs_shims();
841
+ async function requestDeviceAuthorization(scopes) {
842
+ let fqdn = await identityFqdn(), queryParams = { client_id: clientId(), scope: scopes.join(" ") }, url = `https://${fqdn}/oauth/device_authorization`, jsonResult = await (await shopifyFetch(url, {
843
+ method: "POST",
844
+ headers: { "Content-type": "application/x-www-form-urlencoded" },
845
+ body: convertRequestToParams(queryParams)
846
+ })).json();
847
+ if (outputDebug(outputContent`Received device authorization code: ${outputToken.json(jsonResult)}`), !jsonResult.device_code || !jsonResult.verification_uri_complete)
848
+ throw new BugError("Failed to start authorization process");
849
+ if (outputInfo(`
850
+ To run this command, log in to Shopify.`), !isTTY())
851
+ throw new AbortError("Authorization is required to continue, but the current environment does not support interactive prompts.", "To resolve this, specify credentials in your environment, or run the command in an interactive environment such as your local terminal.");
852
+ outputInfo(outputContent`User verification code: ${jsonResult.user_code}`);
853
+ let linkToken = outputToken.link(jsonResult.verification_uri_complete);
854
+ return isCloudEnvironment() ? outputInfo(outputContent`👉 Open this link to start the auth process: ${linkToken}`) : (outputInfo("\u{1F449} Press any key to open the login page on your browser"), await keypress(), await openURL(jsonResult.verification_uri_complete), outputInfo(outputContent`Opened link to start the auth process: ${linkToken}`)), {
855
+ deviceCode: jsonResult.device_code,
856
+ userCode: jsonResult.user_code,
857
+ verificationUri: jsonResult.verification_uri,
858
+ expiresIn: jsonResult.expires_in,
859
+ verificationUriComplete: jsonResult.verification_uri_complete,
860
+ interval: jsonResult.interval
861
+ };
862
+ }
863
+ async function pollForDeviceAuthorization(code, interval = 5) {
864
+ let currentIntervalInSeconds = interval;
865
+ return new Promise((resolve, reject) => {
866
+ let onPoll = async () => {
867
+ let result = await exchangeDeviceCodeForAccessToken(code);
868
+ if (!result.isErr()) {
869
+ resolve(result.value);
870
+ return;
871
+ }
872
+ let error = result.error ?? "unknown_failure";
873
+ switch (outputDebug(outputContent`Polling for device authorization... status: ${error}`), error) {
874
+ case "authorization_pending": {
875
+ startPolling();
876
+ return;
877
+ }
878
+ case "slow_down":
879
+ currentIntervalInSeconds += 5;
880
+ {
881
+ startPolling();
882
+ return;
883
+ }
884
+ case "access_denied":
885
+ case "expired_token":
886
+ case "unknown_failure":
887
+ reject(result);
888
+ }
889
+ }, startPolling = () => {
890
+ setTimeout(onPoll, currentIntervalInSeconds * 1e3);
891
+ };
892
+ startPolling();
893
+ });
894
+ }
895
+ function convertRequestToParams(queryParams) {
896
+ return Object.entries(queryParams).map(([key, value]) => value && `${key}=${value}`).filter((hasValue) => !!hasValue).join("&");
897
+ }
898
+
899
+ // ../cli-kit/dist/private/node/api/rest.js
900
+ init_cjs_shims();
901
+ function restRequestBody(requestBody) {
902
+ if (requestBody)
903
+ return JSON.stringify(requestBody);
904
+ }
905
+ function restRequestUrl(session, apiVersion, path, searchParams = {}) {
906
+ let url = new URL(isThemeAccessSession(session) ? `https://${themeKitAccessDomain}/cli/admin/api/${apiVersion}${path}.json` : `https://${session.storeFqdn}/admin/api/${apiVersion}${path}.json`);
907
+ return Object.entries(searchParams).forEach(([name, value]) => {
908
+ url.searchParams.set(name, value);
909
+ }), url.toString();
910
+ }
911
+ function restRequestHeaders(session) {
912
+ let store2 = session.storeFqdn, token = session.token, headers = buildHeaders(session.token);
913
+ return isThemeAccessSession(session) && (headers["X-Shopify-Shop"] = store2, headers["X-Shopify-Access-Token"] = token), headers;
914
+ }
915
+ function isThemeAccessSession(session) {
916
+ return session.token.startsWith("shptka_");
917
+ }
918
+
919
+ // ../cli-kit/dist/private/node/session.js
920
+ var userId, authMethod = "none";
921
+ async function getLastSeenUserIdAfterAuth() {
922
+ if (userId)
923
+ return userId;
924
+ let currentSession = await fetch() || {}, fqdn = await identityFqdn(), cachedUserId = currentSession[fqdn]?.identity.userId;
925
+ if (cachedUserId)
926
+ return cachedUserId;
927
+ let customToken = getPartnersToken() ?? themeToken();
928
+ return customToken ? nonRandomUUID(customToken) : "unknown";
929
+ }
930
+ function setLastSeenUserIdAfterAuth(id) {
931
+ userId = id;
932
+ }
933
+ async function getLastSeenAuthMethod() {
934
+ if (authMethod !== "none")
935
+ return authMethod;
936
+ let currentSession = await fetch() || {}, fqdn = await identityFqdn();
937
+ if (currentSession[fqdn]?.identity.userId)
938
+ return "device_auth";
939
+ if (getPartnersToken())
940
+ return "partners_token";
941
+ let themePassword = themeToken();
942
+ return themePassword ? isThemeAccessSession({ token: themePassword, storeFqdn: "" }) ? "theme_access_token" : "custom_app_token" : "none";
943
+ }
944
+ function setLastSeenAuthMethod(method) {
945
+ authMethod = method;
946
+ }
947
+ async function ensureAuthenticated(applications, _env, { forceRefresh = !1, noPrompt = !1 } = {}) {
948
+ let fqdn = await identityFqdn(), previousStoreFqdn = applications.adminApi?.storeFqdn;
949
+ if (previousStoreFqdn) {
950
+ let normalizedStoreName = await normalizeStoreFqdn(previousStoreFqdn);
951
+ previousStoreFqdn === applications.adminApi?.storeFqdn && (applications.adminApi.storeFqdn = normalizedStoreName);
952
+ }
953
+ let currentSession = await fetch() || {}, fqdnSession = currentSession[fqdn], scopes = getFlattenScopes(applications);
954
+ outputDebug(outputContent`Validating existing session against the scopes:
955
+ ${outputToken.json(scopes)}
956
+ For applications:
957
+ ${outputToken.json(applications)}
958
+ `);
959
+ let validationResult = await validateSession(scopes, applications, fqdnSession), newSession = {};
960
+ function throwOnNoPrompt() {
961
+ if (!(!noPrompt || isSpin() && firstPartyDev()))
962
+ throw new AbortError(`The currently available CLI credentials are invalid.
963
+
964
+ The CLI is currently unable to prompt for reauthentication.`, "Restart the CLI process you were running. If in an interactive terminal, you will be prompted to reauthenticate. If in a non-interactive terminal, ensure the correct credentials are available in the program environment.");
965
+ }
966
+ if (validationResult === "needs_full_auth")
967
+ throwOnNoPrompt(), outputDebug(outputContent`Initiating the full authentication flow...`), newSession = await executeCompleteFlow(applications, fqdn);
968
+ else if (validationResult === "needs_refresh" || forceRefresh) {
969
+ outputDebug(outputContent`The current session is valid but needs refresh. Refreshing...`);
970
+ try {
971
+ newSession = await refreshTokens(fqdnSession.identity, applications, fqdn);
972
+ } catch (error) {
973
+ if (error instanceof InvalidGrantError)
974
+ throwOnNoPrompt(), newSession = await executeCompleteFlow(applications, fqdn);
975
+ else throw error instanceof InvalidRequestError ? (await remove(), new AbortError(`
976
+ Error validating auth session`, "We've cleared the current session, please try again")) : error;
977
+ }
978
+ }
979
+ let completeSession = { ...currentSession, ...newSession };
980
+ Object.keys(newSession).length > 0 && await store(completeSession);
981
+ let tokens = await tokensFor(applications, completeSession, fqdn), envToken = getPartnersToken();
982
+ return envToken && applications.partnersApi && (tokens.partners = (await exchangeCustomPartnerToken(envToken)).accessToken), setLastSeenAuthMethod(envToken ? "partners_token" : "device_auth"), setLastSeenUserIdAfterAuth(tokens.userId), tokens;
983
+ }
984
+ async function executeCompleteFlow(applications, identityFqdn2) {
985
+ let scopes = getFlattenScopes(applications), exchangeScopes = getExchangeScopes(applications), store2 = applications.adminApi?.storeFqdn;
986
+ firstPartyDev() && (outputDebug(outputContent`Authenticating as Shopify Employee...`), scopes.push("employee"));
987
+ let identityToken, identityTokenInformation = getIdentityTokenInformation();
988
+ if (identityTokenInformation)
989
+ identityToken = buildIdentityTokenFromEnv(scopes, identityTokenInformation);
990
+ else {
991
+ outputDebug(outputContent`Requesting device authorization code...`);
992
+ let deviceAuth = await requestDeviceAuthorization(scopes);
993
+ outputDebug(outputContent`Starting polling for the identity token...`), identityToken = await pollForDeviceAuthorization(deviceAuth.deviceCode, deviceAuth.interval);
994
+ }
995
+ outputDebug(outputContent`CLI token received. Exchanging it for application tokens...`);
996
+ let result = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, store2), session = {
997
+ [identityFqdn2]: {
998
+ identity: identityToken,
999
+ applications: result
1000
+ }
1001
+ };
1002
+ return outputCompleted("Logged in."), session;
1003
+ }
1004
+ async function refreshTokens(token, applications, fqdn) {
1005
+ let identityToken = await refreshAccessToken(token), exchangeScopes = getExchangeScopes(applications), applicationTokens = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, applications.adminApi?.storeFqdn);
1006
+ return {
1007
+ [fqdn]: {
1008
+ identity: identityToken,
1009
+ applications: applicationTokens
1010
+ }
1011
+ };
1012
+ }
1013
+ async function tokensFor(applications, session, fqdn) {
1014
+ let fqdnSession = session[fqdn];
1015
+ if (!fqdnSession)
1016
+ throw new BugError("No session found after ensuring authenticated");
1017
+ let tokens = {
1018
+ userId: fqdnSession.identity.userId
1019
+ };
1020
+ if (applications.adminApi) {
1021
+ let appId = applicationId("admin"), realAppId = `${applications.adminApi.storeFqdn}-${appId}`, token = fqdnSession.applications[realAppId]?.accessToken;
1022
+ token && (tokens.admin = { token, storeFqdn: applications.adminApi.storeFqdn });
1023
+ }
1024
+ if (applications.partnersApi) {
1025
+ let appId = applicationId("partners");
1026
+ tokens.partners = fqdnSession.applications[appId]?.accessToken;
1027
+ }
1028
+ if (applications.storefrontRendererApi) {
1029
+ let appId = applicationId("storefront-renderer");
1030
+ tokens.storefront = fqdnSession.applications[appId]?.accessToken;
1031
+ }
1032
+ if (applications.businessPlatformApi) {
1033
+ let appId = applicationId("business-platform");
1034
+ tokens.businessPlatform = fqdnSession.applications[appId]?.accessToken;
1035
+ }
1036
+ if (applications.appManagementApi) {
1037
+ let appId = applicationId("app-management");
1038
+ tokens.appManagement = fqdnSession.applications[appId]?.accessToken;
1039
+ }
1040
+ return tokens;
1041
+ }
1042
+ function getFlattenScopes(apps) {
1043
+ let admin = apps.adminApi?.scopes || [], partner = apps.partnersApi?.scopes || [], storefront = apps.storefrontRendererApi?.scopes || [], businessPlatform = apps.businessPlatformApi?.scopes || [], appManagement = apps.appManagementApi?.scopes || [], requestedScopes = [...admin, ...partner, ...storefront, ...businessPlatform, ...appManagement];
1044
+ return allDefaultScopes(requestedScopes);
1045
+ }
1046
+ function getExchangeScopes(apps) {
1047
+ let adminScope = apps.adminApi?.scopes || [], partnerScope = apps.partnersApi?.scopes || [], storefrontScopes = apps.storefrontRendererApi?.scopes || [], businessPlatformScopes = apps.businessPlatformApi?.scopes || [], appManagementScopes = apps.appManagementApi?.scopes || [];
1048
+ return {
1049
+ admin: apiScopes("admin", adminScope),
1050
+ partners: apiScopes("partners", partnerScope),
1051
+ storefront: apiScopes("storefront-renderer", storefrontScopes),
1052
+ businessPlatform: apiScopes("business-platform", businessPlatformScopes),
1053
+ appManagement: apiScopes("app-management", appManagementScopes)
1054
+ };
1055
+ }
1056
+ function buildIdentityTokenFromEnv(scopes, identityTokenInformation) {
1057
+ return {
1058
+ ...identityTokenInformation,
1059
+ expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3),
1060
+ scopes
1061
+ };
1062
+ }
1063
+
1064
+ // ../cli-kit/dist/private/node/analytics.js
1065
+ async function startAnalytics({ commandContent, args, currentTime = (/* @__PURE__ */ new Date()).getTime(), commandClass }) {
1066
+ let startCommand = commandContent.command;
1067
+ commandClass && Object.prototype.hasOwnProperty.call(commandClass, "analyticsNameOverride") && (startCommand = commandClass.analyticsNameOverride() ?? commandContent.command);
1068
+ let pluginName = commandClass?.plugin?.name;
1069
+ commandClass && "customPluginName" in commandClass && (pluginName = commandClass.customPluginName), await addSensitiveMetadata(() => ({
1070
+ commandStartOptions: {
1071
+ startTime: currentTime,
1072
+ startCommand,
1073
+ startArgs: args
1074
+ }
1075
+ })), await addPublicMetadata(() => ({
1076
+ cmd_all_launcher: packageManagerFromUserAgent(),
1077
+ cmd_all_alias_used: commandContent.alias,
1078
+ cmd_all_topic: commandContent.topic,
1079
+ cmd_all_plugin: pluginName,
1080
+ cmd_all_force: flagIncluded("force", commandClass) ? args.includes("--force") : void 0
1081
+ }));
1082
+ }
1083
+ async function getEnvironmentData(config) {
1084
+ let ciplatform = ciPlatform(), pluginNames = getPluginNames(config), shopifyPlugins = pluginNames.filter((plugin) => plugin.startsWith("@shopify/")), { platform, arch } = platformAndArch();
1085
+ return {
1086
+ uname: `${platform} ${arch}`,
1087
+ env_ci: ciplatform.isCI,
1088
+ env_ci_platform: ciplatform.name,
1089
+ env_plugin_installed_any_custom: pluginNames.length !== shopifyPlugins.length,
1090
+ env_plugin_installed_shopify: JSON.stringify(shopifyPlugins),
1091
+ env_shell: config.shell,
1092
+ env_web_ide: cloudEnvironment().editor ? cloudEnvironment().platform : void 0,
1093
+ env_device_id: hashString(await macAddress()),
1094
+ env_cloud: cloudEnvironment().platform,
1095
+ env_package_manager: await getPackageManager(cwd()),
1096
+ env_is_global: currentProcessIsGlobal(),
1097
+ env_auth_method: await getLastSeenAuthMethod()
1098
+ };
1099
+ }
1100
+ async function getSensitiveEnvironmentData(config) {
1101
+ return {
1102
+ env_plugin_installed_all: JSON.stringify(getPluginNames(config))
1103
+ };
1104
+ }
1105
+ function getPluginNames(config) {
1106
+ return [...config.plugins.keys()].sort().filter((plugin) => !plugin.startsWith("@oclif/"));
1107
+ }
1108
+ function flagIncluded(flag, commandClass) {
1109
+ if (!commandClass)
1110
+ return !1;
1111
+ let commandFlags = commandClass.flags ?? {};
1112
+ return Object.keys(commandFlags).includes(flag);
1113
+ }
1114
+
1115
+ export {
1116
+ partnersFqdn,
1117
+ appManagementFqdn,
1118
+ developerDashboardFqdn,
1119
+ businessPlatformFqdn,
1120
+ normalizeStoreFqdn,
1121
+ ok,
1122
+ err,
1123
+ exchangeCustomPartnerToken,
1124
+ remove,
1125
+ restRequestBody,
1126
+ restRequestUrl,
1127
+ restRequestHeaders,
1128
+ isThemeAccessSession,
1129
+ getLastSeenUserIdAfterAuth,
1130
+ setLastSeenUserIdAfterAuth,
1131
+ setLastSeenAuthMethod,
1132
+ ensureAuthenticated,
1133
+ startAnalytics,
1134
+ getEnvironmentData,
1135
+ getSensitiveEnvironmentData
1136
+ };
1137
+ //# sourceMappingURL=chunk-QRARFXIM.js.map