@shopify/cli 3.84.1 → 3.85.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 (105) hide show
  1. package/README.md +1 -1
  2. package/dist/{chokidar-KCZH6DIC.js → chokidar-TTCYG5AA.js} +5 -5
  3. package/dist/{chokidar-XPSJ2FUJ.js → chokidar-XUA2BN3J.js} +5 -5
  4. package/dist/{chunk-TW3OHW6H.js → chunk-2IA24ROR.js} +10 -9
  5. package/dist/{chunk-R3FZ7BFA.js → chunk-2IEQZDJI.js} +3 -3
  6. package/dist/{chunk-77NCO4UD.js → chunk-47CMAYQE.js} +3 -3
  7. package/dist/{chunk-MCEP4L5M.js → chunk-4JN3JAPL.js} +3 -3
  8. package/dist/{chunk-JNDSQA4U.js → chunk-5FNCRAPA.js} +3 -3
  9. package/dist/{chunk-KS7CKFXX.js → chunk-76S5M67J.js} +7 -7
  10. package/dist/{chunk-PQCWFPSI.js → chunk-A26YXFMX.js} +8 -8
  11. package/dist/{chunk-JJH27HLJ.js → chunk-AJOVRT5K.js} +3 -3
  12. package/dist/{chunk-57KJCVB5.js → chunk-AJYT5DKD.js} +2 -2
  13. package/dist/{chunk-HMDWNGIV.js → chunk-AM4QB5OM.js} +206 -100
  14. package/dist/{chunk-SKEV2KRG.js → chunk-B36FYNEM.js} +664 -587
  15. package/dist/{chunk-JB4IBM6F.js → chunk-BB4VAGLH.js} +2 -2
  16. package/dist/{chunk-W5G2YPO2.js → chunk-BQ3PZIHZ.js} +7 -7
  17. package/dist/{chunk-GWETXJR2.js → chunk-C4XAKIGB.js} +8 -8
  18. package/dist/{chunk-2HA6WHOK.js → chunk-DJVJNSKZ.js} +2 -2
  19. package/dist/{chunk-IM2PF4V5.js → chunk-DKG2TMNN.js} +2 -2
  20. package/dist/{del-SAZHGAZZ.js → chunk-EFOOQV72.js} +17 -378
  21. package/dist/{chunk-3FBDJEGD.js → chunk-F7F4BQYW.js} +1824 -762
  22. package/dist/{chunk-66VZYBID.js → chunk-F7J5CUMZ.js} +4 -4
  23. package/dist/{chunk-IRF44N7J.js → chunk-G2VTHDI5.js} +42 -18
  24. package/dist/{chunk-2M63OZ6L.js → chunk-HNHQAN5R.js} +3 -3
  25. package/dist/chunk-IWFYXDPH.js +109 -0
  26. package/dist/{chunk-NBOUUR2C.js → chunk-JF6OJWJV.js} +3 -3
  27. package/dist/{chunk-Y4JV2C2F.js → chunk-JR35C77F.js} +3 -3
  28. package/dist/{chunk-K5XXB73S.js → chunk-K2VBTQSL.js} +187 -43
  29. package/dist/chunk-KU6FTMKN.js +87 -0
  30. package/dist/{chunk-MQQ5ZTSK.js → chunk-NYUWDGSK.js} +7 -7
  31. package/dist/{chunk-DVZ22YSP.js → chunk-PUO72IWW.js} +16 -20
  32. package/dist/{chunk-42TDSAFO.js → chunk-T3FBGLW4.js} +4 -4
  33. package/dist/{chunk-G5R6YD27.js → chunk-UATXMR5F.js} +2 -103
  34. package/dist/{chunk-4JIM2QT7.js → chunk-UGBL65P2.js} +4 -4
  35. package/dist/{chunk-QO4ILPU2.js → chunk-VELVK2EZ.js} +4 -4
  36. package/dist/{chunk-5G56F2K6.js → chunk-VLSFD7SJ.js} +19 -18
  37. package/dist/{chunk-FYGQPHYH.js → chunk-WRIQTRQE.js} +2 -2
  38. package/dist/{chunk-7AEOEVGT.js → chunk-XO7GQ2WG.js} +3 -3
  39. package/dist/{chunk-FUWTEDP2.js → chunk-XTCT7ABH.js} +16379 -5792
  40. package/dist/{chunk-N2463ZYG.js → chunk-Y4DWHLHN.js} +3 -3
  41. package/dist/{chunk-ES5N6OQW.js → chunk-Y7JIZJYE.js} +5 -5
  42. package/dist/{chunk-DNXNKHZO.js → chunk-Z7TXQNKI.js} +2 -2
  43. package/dist/chunk-ZAVXS5HH.js +4654 -0
  44. package/dist/{chunk-DSKW7GLZ.js → chunk-ZXKNRG53.js} +5 -5
  45. package/dist/cli/commands/auth/login.d.ts +8 -0
  46. package/dist/cli/commands/auth/login.js +28 -0
  47. package/dist/cli/commands/auth/login.test.js +53 -0
  48. package/dist/cli/commands/auth/logout.js +15 -17
  49. package/dist/cli/commands/auth/logout.test.js +20 -22
  50. package/dist/cli/commands/cache/clear.js +15 -16
  51. package/dist/cli/commands/debug/command-flags.js +15 -16
  52. package/dist/cli/commands/docs/generate.js +15 -16
  53. package/dist/cli/commands/docs/generate.test.js +21 -22
  54. package/dist/cli/commands/help.js +15 -16
  55. package/dist/cli/commands/kitchen-sink/async.js +16 -17
  56. package/dist/cli/commands/kitchen-sink/async.test.js +17 -18
  57. package/dist/cli/commands/kitchen-sink/index.js +18 -19
  58. package/dist/cli/commands/kitchen-sink/index.test.js +21 -22
  59. package/dist/cli/commands/kitchen-sink/prompts.js +16 -17
  60. package/dist/cli/commands/kitchen-sink/prompts.test.js +17 -18
  61. package/dist/cli/commands/kitchen-sink/static.js +16 -17
  62. package/dist/cli/commands/kitchen-sink/static.test.js +17 -18
  63. package/dist/cli/commands/notifications/generate.js +16 -17
  64. package/dist/cli/commands/notifications/list.js +16 -17
  65. package/dist/cli/commands/search.js +16 -17
  66. package/dist/cli/commands/upgrade.js +16 -17
  67. package/dist/cli/commands/upgrade.test.js +1 -1
  68. package/dist/cli/commands/version.js +16 -17
  69. package/dist/cli/commands/version.test.js +17 -18
  70. package/dist/cli/services/commands/notifications.js +11 -12
  71. package/dist/cli/services/commands/search.js +7 -8
  72. package/dist/cli/services/commands/search.test.js +8 -9
  73. package/dist/cli/services/commands/version.js +8 -9
  74. package/dist/cli/services/commands/version.test.js +10 -11
  75. package/dist/cli/services/kitchen-sink/async.js +7 -8
  76. package/dist/cli/services/kitchen-sink/prompts.js +7 -8
  77. package/dist/cli/services/kitchen-sink/static.js +7 -8
  78. package/dist/cli/services/upgrade.js +8 -9
  79. package/dist/cli/services/upgrade.test.js +12 -13
  80. package/dist/configs/all.yml +3 -0
  81. package/dist/configs/recommended.yml +3 -0
  82. package/dist/{custom-oclif-loader-LOMFS5PB.js → custom-oclif-loader-J2DN7UTY.js} +11 -12
  83. package/dist/data/objects.json +2 -2
  84. package/dist/data/shopify_system_translations.json +69 -22
  85. package/dist/data/tags.json +10 -10
  86. package/dist/del-DNZ7X2HW.js +377 -0
  87. package/dist/{error-handler-TQKQ3EAE.js → error-handler-JJ76ZQMC.js} +13 -14
  88. package/dist/hooks/postrun.js +13 -15
  89. package/dist/hooks/prerun.js +14 -15
  90. package/dist/index.d.ts +1 -1
  91. package/dist/index.js +7477 -5649
  92. package/dist/{lib-OSXFX3I2.js → lib-DEEC6IKU.js} +3 -4
  93. package/dist/{local-76WZCPFM.js → local-2JWTG2IJ.js} +7 -8
  94. package/dist/{morph-TYIH255V.js → morph-5D7H6MU2.js} +13 -11
  95. package/dist/{node-package-manager-OCGFQDFC.js → node-package-manager-YCQL3774.js} +8 -9
  96. package/dist/{npa-E675GQOI.js → npa-LHT53SWR.js} +3 -5
  97. package/dist/tsconfig.tsbuildinfo +1 -1
  98. package/dist/{ui-A52PK2HZ.js → ui-HITLA3H3.js} +9 -8
  99. package/dist/{workerd-PHNPZMMV.js → workerd-KHWXFNPK.js} +22 -22
  100. package/oclif.manifest.json +79 -9
  101. package/package.json +10 -10
  102. package/dist/chunk-CP3BRHWK.js +0 -33
  103. package/dist/chunk-EZQWZ57B.js +0 -53
  104. package/dist/chunk-T4K4LRMO.js +0 -1216
  105. package/dist/chunk-YQVYH3XF.js +0 -119
@@ -1,1216 +0,0 @@
1
- import {
2
- allAPIs,
3
- blockPartnersAccess,
4
- getIdentityTokenInformation,
5
- getPartnersToken,
6
- hashString,
7
- nonRandomUUID,
8
- shopifyFetch,
9
- z
10
- } from "./chunk-DVZ22YSP.js";
11
- import {
12
- getPackageManager,
13
- getSession,
14
- packageManagerFromUserAgent,
15
- removeSession,
16
- setSession
17
- } from "./chunk-IRF44N7J.js";
18
- import {
19
- AbortError,
20
- BugError,
21
- Environment,
22
- FatalError,
23
- addPublicMetadata,
24
- addSensitiveMetadata,
25
- ciPlatform,
26
- cloudEnvironment,
27
- currentProcessIsGlobal,
28
- firstPartyDev,
29
- import_ts_error,
30
- isCI,
31
- isCloudEnvironment,
32
- isSpin,
33
- isTTY,
34
- isWsl,
35
- keypress,
36
- macAddress,
37
- openURL,
38
- outputCompleted,
39
- outputContent,
40
- outputDebug,
41
- outputInfo,
42
- outputToken,
43
- platformAndArch,
44
- serviceEnvironment,
45
- sessionConstants,
46
- spinFqdn,
47
- themeToken
48
- } from "./chunk-SKEV2KRG.js";
49
- import {
50
- cwd
51
- } from "./chunk-EG6MBBEN.js";
52
- import {
53
- __commonJS,
54
- __require,
55
- __toESM,
56
- init_cjs_shims
57
- } from "./chunk-PKR7KJ6P.js";
58
-
59
- // ../../node_modules/.pnpm/network-interfaces@1.1.0/node_modules/network-interfaces/index.js
60
- var require_network_interfaces = __commonJS({
61
- "../../node_modules/.pnpm/network-interfaces@1.1.0/node_modules/network-interfaces/index.js"(exports) {
62
- "use strict";
63
- init_cjs_shims();
64
- var os2 = __require("os");
65
- function isValid(address, options) {
66
- return !(typeof options.internal == "boolean" && address.internal !== options.internal || options.ipVersion === 4 && address.family !== "IPv4" || options.ipVersion === 6 && address.family !== "IPv6");
67
- }
68
- function findAddresses(interfaceName, options = {}) {
69
- let addresses = os2.networkInterfaces()[interfaceName];
70
- if (!addresses)
71
- throw new Error(`Network interface "${interfaceName}" does not exist`);
72
- let result = [];
73
- for (let address of addresses)
74
- isValid(address, options) && result.push(address);
75
- return result;
76
- }
77
- exports.toIp = function(interfaceName, options) {
78
- let addresses = findAddresses(interfaceName, options);
79
- if (addresses.length === 0)
80
- throw new Error(`No suitable IP address found on interface "${interfaceName}"`);
81
- return addresses[0].address;
82
- };
83
- exports.toIps = function(interfaceName, options) {
84
- return findAddresses(interfaceName, options).map((address) => address.address);
85
- };
86
- exports.fromIp = function(ip, options) {
87
- let interfaces = os2.networkInterfaces(), interfaceNames = Object.keys(interfaces);
88
- for (let interfaceName of interfaceNames)
89
- for (let address of interfaces[interfaceName])
90
- if (address.address === ip && isValid(address, options))
91
- return interfaceName;
92
- throw new Error(`No suitable interfaces were found with IP address "${ip}"`);
93
- };
94
- exports.getInterface = function(options) {
95
- let interfaces = os2.networkInterfaces(), interfaceNames = Object.keys(interfaces);
96
- for (let interfaceName of interfaceNames)
97
- if (findAddresses(interfaceName, options).length > 0)
98
- return interfaceName;
99
- throw new Error("No suitable interfaces were found");
100
- };
101
- exports.getInterfaces = function(options) {
102
- let interfaces = os2.networkInterfaces(), interfaceNames = Object.keys(interfaces), result = [];
103
- for (let interfaceName of interfaceNames)
104
- findAddresses(interfaceName, options).length > 0 && result.push(interfaceName);
105
- return result;
106
- };
107
- }
108
- });
109
-
110
- // ../cli-kit/dist/private/node/analytics.js
111
- init_cjs_shims();
112
-
113
- // ../cli-kit/dist/private/node/session.js
114
- init_cjs_shims();
115
-
116
- // ../cli-kit/dist/private/node/session/identity.js
117
- init_cjs_shims();
118
- function clientId() {
119
- let environment = serviceEnvironment();
120
- return environment === Environment.Local ? "e5380e02-312a-7408-5718-e07017e9cf52" : environment === Environment.Production ? "fbdb2649-e327-4907-8f67-908d24cfd7e3" : "e5380e02-312a-7408-5718-e07017e9cf52";
121
- }
122
- function applicationId(api) {
123
- switch (api) {
124
- case "admin": {
125
- let environment = serviceEnvironment();
126
- return environment === Environment.Local ? "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52" : environment === Environment.Production ? "7ee65a63608843c577db8b23c4d7316ea0a01bd2f7594f8a9c06ea668c1b775c" : "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52";
127
- }
128
- case "partners": {
129
- let environment = serviceEnvironment();
130
- return environment === Environment.Local ? "df89d73339ac3c6c5f0a98d9ca93260763e384d51d6038da129889c308973978" : environment === Environment.Production ? "271e16d403dfa18082ffb3d197bd2b5f4479c3fc32736d69296829cbb28d41a6" : "df89d73339ac3c6c5f0a98d9ca93260763e384d51d6038da129889c308973978";
131
- }
132
- case "storefront-renderer": {
133
- let environment = serviceEnvironment();
134
- return environment === Environment.Local ? "46f603de-894f-488d-9471-5b721280ff49" : environment === Environment.Production ? "ee139b3d-5861-4d45-b387-1bc3ada7811c" : "46f603de-894f-488d-9471-5b721280ff49";
135
- }
136
- case "business-platform": {
137
- let environment = serviceEnvironment();
138
- return environment === Environment.Local ? "ace6dc89-b526-456d-a942-4b8ef6acda4b" : environment === Environment.Production ? "32ff8ee5-82b8-4d93-9f8a-c6997cefb7dc" : "ace6dc89-b526-456d-a942-4b8ef6acda4b";
139
- }
140
- case "app-management":
141
- return serviceEnvironment() === Environment.Production ? "7ee65a63608843c577db8b23c4d7316ea0a01bd2f7594f8a9c06ea668c1b775c" : "e92482cebb9bfb9fb5a0199cc770fde3de6c8d16b798ee73e36c9d815e070e52";
142
- default:
143
- throw new BugError(`Application id for API of type: ${api}`);
144
- }
145
- }
146
-
147
- // ../cli-kit/dist/private/node/session/validate.js
148
- init_cjs_shims();
149
-
150
- // ../cli-kit/dist/private/node/session/schema.js
151
- init_cjs_shims();
152
- var DateSchema = z.preprocess((arg) => typeof arg == "string" || arg instanceof Date ? new Date(arg) : null, z.date()), IdentityTokenSchema = z.object({
153
- accessToken: z.string(),
154
- refreshToken: z.string(),
155
- expiresAt: DateSchema,
156
- scopes: z.array(z.string()),
157
- userId: z.string()
158
- }), ApplicationTokenSchema = z.object({
159
- accessToken: z.string(),
160
- expiresAt: DateSchema,
161
- scopes: z.array(z.string())
162
- }), SessionSchema = z.object({}).catchall(z.object({
163
- /**
164
- * It contains the identity token. Before usint it, we exchange it
165
- * to get a token that we can use with different applications. The exchanged
166
- * tokens for the applications are stored under applications.
167
- */
168
- identity: IdentityTokenSchema,
169
- /**
170
- * It contains exchanged tokens for the applications the CLI
171
- * authenticates with. Tokens are scoped under the fqdn of the applications.
172
- */
173
- applications: z.object({}).catchall(ApplicationTokenSchema)
174
- }));
175
- function validateCachedIdentityTokenStructure(identityToken) {
176
- return IdentityTokenSchema.safeParse(identityToken).success;
177
- }
178
-
179
- // ../cli-kit/dist/private/node/session/validate.js
180
- function validateScopes(requestedScopes, identity) {
181
- let currentScopes = identity.scopes;
182
- return firstPartyDev() !== currentScopes.includes("employee") ? !1 : requestedScopes.every((scope) => currentScopes.includes(scope));
183
- }
184
- async function validateSession(scopes, applications, session) {
185
- if (!session || !validateScopes(scopes, session.identity))
186
- return "needs_full_auth";
187
- let tokensAreExpired = isTokenExpired(session.identity);
188
- if (applications.partnersApi) {
189
- let appId = applicationId("partners"), token = session.applications[appId];
190
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
191
- }
192
- if (applications.appManagementApi) {
193
- let appId = applicationId("app-management"), token = session.applications[appId];
194
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
195
- }
196
- if (applications.storefrontRendererApi) {
197
- let appId = applicationId("storefront-renderer"), token = session.applications[appId];
198
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
199
- }
200
- if (applications.adminApi) {
201
- let appId = applicationId("admin"), realAppId = `${applications.adminApi.storeFqdn}-${appId}`, token = session.applications[realAppId];
202
- tokensAreExpired = tokensAreExpired || isTokenExpired(token);
203
- }
204
- return outputDebug(`- Token validation -> It's expired: ${tokensAreExpired}`), validateCachedIdentityTokenStructure(session.identity) ? tokensAreExpired ? "needs_refresh" : "ok" : "needs_full_auth";
205
- }
206
- function isTokenExpired(token) {
207
- return token ? token.expiresAt < expireThreshold() : !0;
208
- }
209
- function expireThreshold() {
210
- return new Date(Date.now() + sessionConstants.expirationTimeMarginInMinutes * 60 * 1e3);
211
- }
212
-
213
- // ../cli-kit/dist/private/node/session/scopes.js
214
- init_cjs_shims();
215
- function allDefaultScopes(extraScopes = []) {
216
- let scopes = allAPIs.map((api) => defaultApiScopes(api)).flat();
217
- return scopes = ["openid", ...scopes, ...extraScopes].map(scopeTransform), Array.from(new Set(scopes));
218
- }
219
- function apiScopes(api, extraScopes = []) {
220
- let scopes = [...defaultApiScopes(api), ...extraScopes.map(scopeTransform)].map(scopeTransform);
221
- return Array.from(new Set(scopes));
222
- }
223
- function tokenExchangeScopes(api) {
224
- switch (api) {
225
- case "partners":
226
- return [scopeTransform("cli")];
227
- case "app-management":
228
- return [scopeTransform("app-management")];
229
- case "business-platform":
230
- return [scopeTransform("destinations")];
231
- default:
232
- throw new BugError(`API not supported for token exchange: ${api}`);
233
- }
234
- }
235
- function defaultApiScopes(api) {
236
- switch (api) {
237
- case "admin":
238
- return ["graphql", "themes", "collaborator"];
239
- case "storefront-renderer":
240
- return ["devtools"];
241
- case "partners":
242
- return ["cli"];
243
- case "business-platform":
244
- return ["destinations", "store-management", "on-demand-user-access"];
245
- case "app-management":
246
- return ["app-management"];
247
- default:
248
- throw new BugError(`Unknown API: ${api}`);
249
- }
250
- }
251
- function scopeTransform(scope) {
252
- switch (scope) {
253
- case "graphql":
254
- return "https://api.shopify.com/auth/shop.admin.graphql";
255
- case "themes":
256
- return "https://api.shopify.com/auth/shop.admin.themes";
257
- case "collaborator":
258
- return "https://api.shopify.com/auth/partners.collaborator-relationships.readonly";
259
- case "cli":
260
- return "https://api.shopify.com/auth/partners.app.cli.access";
261
- case "devtools":
262
- return "https://api.shopify.com/auth/shop.storefront-renderer.devtools";
263
- case "destinations":
264
- return "https://api.shopify.com/auth/destinations.readonly";
265
- case "store-management":
266
- return "https://api.shopify.com/auth/organization.store-management";
267
- case "on-demand-user-access":
268
- return "https://api.shopify.com/auth/organization.on-demand-user-access";
269
- case "app-management":
270
- return "https://api.shopify.com/auth/organization.apps.manage";
271
- default:
272
- return scope;
273
- }
274
- }
275
-
276
- // ../cli-kit/dist/private/node/session/exchange.js
277
- init_cjs_shims();
278
-
279
- // ../cli-kit/dist/public/node/context/fqdn.js
280
- init_cjs_shims();
281
-
282
- // ../cli-kit/dist/public/node/vendor/dev_server/index.js
283
- init_cjs_shims();
284
-
285
- // ../cli-kit/dist/public/node/vendor/dev_server/env.js
286
- init_cjs_shims();
287
- var isDevServerEnvironment = process.env.USING_DEV === "1" || process.env.SPIN === "1";
288
- function assertCompatibleEnvironment() {
289
- if (!isDevServerEnvironment)
290
- throw new Error("DevServer is not supported in this environment");
291
- }
292
-
293
- // ../cli-kit/dist/public/node/vendor/dev_server/dev-server.js
294
- init_cjs_shims();
295
- import fs5 from "node:fs";
296
-
297
- // ../cli-kit/dist/public/node/vendor/dev_server/dev-server-2024.js
298
- init_cjs_shims();
299
- var ni = __toESM(require_network_interfaces(), 1);
300
- import fs2 from "node:fs";
301
-
302
- // ../cli-kit/dist/public/node/vendor/dev_server/network/index.js
303
- init_cjs_shims();
304
- import { spawnSync } from "node:child_process";
305
-
306
- // ../cli-kit/dist/public/node/vendor/dev_server/network/host.js
307
- init_cjs_shims();
308
- import fs from "node:fs";
309
- var HOSTS_FILE = "/etc/hosts", hostToIpCache = {}, lastModifiedTime = 0;
310
- function loadHostsFile() {
311
- try {
312
- let modifiedTime = fs.statSync(HOSTS_FILE).mtimeMs;
313
- if (modifiedTime === lastModifiedTime)
314
- return;
315
- let lines = fs.readFileSync(HOSTS_FILE, "utf8").split(/\r?\n/);
316
- hostToIpCache = {};
317
- for (let line of lines) {
318
- if (line.trim().startsWith("#") || line.trim() === "")
319
- continue;
320
- let matches = /^\s*(?<ipAddress>[^\s#]+)\s+(?<matchedHostName>[^\s#]+)\s*(#.*)?$/.exec(line);
321
- if (matches && matches.groups) {
322
- let { ipAddress, matchedHostName } = matches.groups;
323
- matchedHostName && ipAddress && (hostToIpCache[matchedHostName] = ipAddress);
324
- }
325
- }
326
- lastModifiedTime = modifiedTime;
327
- } catch (error) {
328
- console.log("Error reading hosts file:", error);
329
- }
330
- }
331
- function getIpFromHosts(hostname) {
332
- loadHostsFile();
333
- let ipAddress = hostToIpCache[hostname];
334
- if (ipAddress)
335
- return ipAddress;
336
- throw new Error(`No IP found for hostname: ${hostname}`);
337
- }
338
-
339
- // ../cli-kit/dist/public/node/vendor/dev_server/network/index.js
340
- var DEFAULT_CONNECT_TIMEOUT = 100, checkPort;
341
- function assertConnectable(options) {
342
- checkPort || (checkPort = getCheckPortHelper());
343
- let { port, addr, timeout = DEFAULT_CONNECT_TIMEOUT } = options;
344
- try {
345
- if (!checkPort(addr === "localhost" ? "127.0.0.1" : addr, port, timeout))
346
- throw new Error(`DevServer for '${options.projectName}' is not running on ${port} / ${addr}: \`dev up ${options.projectName}\` to start it.`);
347
- } catch (err2) {
348
- throw new Error(`DevServer check for '${options.projectName}' on ${port} / ${addr} failed (${err2})`);
349
- }
350
- }
351
- function getCheckPortHelper() {
352
- return fallbackCheckPort;
353
- }
354
- function fallbackCheckPort(address, port, timeout) {
355
- return spawnSync("nc", ["-z", "-w", "1", address, port.toString()], {
356
- timeout,
357
- stdio: "ignore"
358
- }).status === 0;
359
- }
360
-
361
- // ../cli-kit/dist/public/node/vendor/dev_server/dev-server-2024.js
362
- var NON_SHOP_PREFIXES = ["app", "dev", "shopify"], BACKEND_PORT = 8080;
363
- function createServer(projectName) {
364
- return {
365
- host: (options = {}) => host(projectName, options),
366
- url: (options = {}) => url(projectName, options)
367
- };
368
- }
369
- function host(projectName, options = {}) {
370
- assertCompatibleEnvironment(), (assertRunningOverride || assertRunning2024)(projectName);
371
- let prefix = (options.nonstandardHostPrefix || projectName).replace(/_/g, "-");
372
- if (projectName === "shopify") {
373
- if (prefix.endsWith("-dev-api"))
374
- return `${prefix.replace("-dev-api", "")}.dev-api.shop.dev`;
375
- if (!NON_SHOP_PREFIXES.includes(prefix))
376
- return `${prefix}.my.shop.dev`;
377
- }
378
- return `${prefix}.shop.dev`;
379
- }
380
- function url(projectName, options = {}) {
381
- return `https://${host(projectName, options)}`;
382
- }
383
- function assertRunning2024(projectName) {
384
- assertConnectable({
385
- projectName,
386
- addr: getBackendIp(projectName),
387
- port: BACKEND_PORT
388
- });
389
- }
390
- function getBackendIp(projectName) {
391
- try {
392
- let backendIp = resolveBackendHost(projectName);
393
- return ni.fromIp(backendIp, { internal: !0, ipVersion: 4 }), backendIp;
394
- } catch {
395
- throw new Error(`DevServer for '${projectName}' is not running: \`dev up ${projectName}\` to start it.`);
396
- }
397
- }
398
- function resolveBackendHost(name) {
399
- let host4;
400
- try {
401
- host4 = fs2.readlinkSync(`/opt/nginx/etc/manifest/${name}/current`);
402
- } catch {
403
- host4 = `${name}.root.shopify.dev.internal`;
404
- }
405
- try {
406
- return getIpFromHosts(host4);
407
- } catch {
408
- return host4;
409
- }
410
- }
411
- var assertRunningOverride;
412
-
413
- // ../cli-kit/dist/public/node/vendor/dev_server/dev-server-2016.js
414
- init_cjs_shims();
415
- import fs3 from "fs";
416
- import * as os from "node:os";
417
- function createServer2(projectName) {
418
- return {
419
- host: (options = {}) => host2(projectName, options),
420
- url: (options = {}) => url2(projectName, options)
421
- };
422
- }
423
- function host2(projectName, options = {}) {
424
- return assertCompatibleEnvironment(), (assertRunningOverride2 || assertRunning2016)(projectName), `${options.nonstandardHostPrefix || projectName}.myshopify.io`;
425
- }
426
- function url2(projectName, options = {}) {
427
- return `https://${host2(projectName, options)}`;
428
- }
429
- function assertRunning2016(projectName) {
430
- let [addr, port] = getAddrPort(projectName);
431
- assertConnectable({ projectName, addr, port });
432
- }
433
- function getAddrPort(name) {
434
- try {
435
- let portContent = fs3.readFileSync(`${os.homedir()}/.local/run/services/${name}/server/port`, "utf-8");
436
- return ["localhost", parseInt(portContent, 10)];
437
- } catch {
438
- throw new Error(`DevServer for '${name}' is not running: \`dev up ${name}\` to start it.`);
439
- }
440
- }
441
- var assertRunningOverride2;
442
-
443
- // ../cli-kit/dist/public/node/vendor/dev_server/dev-server-spin.js
444
- init_cjs_shims();
445
- import fs4 from "node:fs";
446
- function createServer3(projectName) {
447
- return {
448
- host: (options = {}) => host3(projectName, options),
449
- url: (options = {}) => url3(projectName, options)
450
- };
451
- }
452
- function host3(projectName, { nonstandardHostPrefix } = {}) {
453
- assertCompatibleEnvironment();
454
- let services = fs4.readdirSync("/run/ports2").filter((file) => file.endsWith(`--${projectName}`));
455
- if (services.length === 0)
456
- throw new Error(`DevServer for '${projectName}' not present in this spin environment`);
457
- if (projectName === "shopify")
458
- return `${nonstandardHostPrefix?.replace(/[-_]dev[-_]api$/, "")}.${projectName}.${process.env.SPIN_FQDN}`;
459
- let match = new RegExp(`^(.+)${projectName}$`).exec(services[0]), organization = match ? match[1] : "";
460
- return `${organization === "shopify--" ? "" : `${organization}`}${projectName}.${process.env.SPIN_FQDN}`;
461
- }
462
- function url3(projectName, options = {}) {
463
- return `https://${host3(projectName, options)}`;
464
- }
465
-
466
- // ../cli-kit/dist/public/node/vendor/dev_server/dev-server.js
467
- var DevServer = class {
468
- constructor(projectName) {
469
- if (this.projectName = projectName, projectName === "shopify")
470
- throw new Error("Use `import {DevServerCore}` for the 'shopify' project");
471
- this.serverImpl = inferProjectServer(projectName);
472
- }
473
- host(options) {
474
- return this.serverImpl.host(options);
475
- }
476
- url(options) {
477
- return this.serverImpl.url(options);
478
- }
479
- }, DevServerCore = class {
480
- constructor() {
481
- this.serverImpl = inferProjectServer("shopify");
482
- }
483
- host(prefix) {
484
- return this.serverImpl.host({ nonstandardHostPrefix: prefix });
485
- }
486
- url(prefix) {
487
- return this.serverImpl.url({ nonstandardHostPrefix: prefix });
488
- }
489
- }, INFERENCE_MODE_SENTINEL = "/opt/dev/misc/dev-server-inference-mode";
490
- function inferProjectServer(projectName) {
491
- return process.env.SPIN === "1" ? createServer3(projectName) : inferenceModeAndProjectIsEdition2016(projectName) ? createServer2(projectName) : createServer(projectName);
492
- }
493
- function inferenceModeAndProjectIsEdition2016(projectName) {
494
- try {
495
- fs5.accessSync(INFERENCE_MODE_SENTINEL);
496
- try {
497
- return fs5.accessSync(`/opt/nginx/etc/manifest/${projectName}/current/edition-2024`), !1;
498
- } catch {
499
- return !0;
500
- }
501
- } catch {
502
- return !1;
503
- }
504
- }
505
-
506
- // ../cli-kit/dist/public/node/context/fqdn.js
507
- 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.");
508
- async function partnersFqdn() {
509
- if (blockPartnersAccess())
510
- throw new BugError("Partners API is blocked by the SHOPIFY_CLI_NEVER_USE_PARTNERS_API environment variable.");
511
- let environment = serviceEnvironment(), productionFqdn = "partners.shopify.com";
512
- switch (environment) {
513
- case "local":
514
- return new DevServer("partners").host();
515
- case "spin":
516
- return `partners.${await spinFqdn()}`;
517
- default:
518
- return productionFqdn;
519
- }
520
- }
521
- async function adminFqdn() {
522
- let environment = serviceEnvironment(), productionFqdn = "admin.shopify.com";
523
- switch (environment) {
524
- case "local":
525
- return new DevServerCore().host("admin");
526
- case "spin":
527
- return `admin.shopify.${await spinFqdn()}`;
528
- default:
529
- return productionFqdn;
530
- }
531
- }
532
- async function appManagementFqdn() {
533
- let environment = serviceEnvironment(), productionFqdn = "app.shopify.com";
534
- switch (environment) {
535
- case "local":
536
- return new DevServerCore().host("app");
537
- case "spin":
538
- return `app.shopify.${await spinFqdn()}`;
539
- default:
540
- return productionFqdn;
541
- }
542
- }
543
- async function appDevFqdn(storeFqdn) {
544
- switch (serviceEnvironment()) {
545
- case "local":
546
- return new DevServerCore().host("app");
547
- default:
548
- return storeFqdn;
549
- }
550
- }
551
- async function developerDashboardFqdn() {
552
- let environment = serviceEnvironment(), productionFqdn = "dev.shopify.com";
553
- switch (environment) {
554
- case "local":
555
- return new DevServerCore().host("dev");
556
- case "spin":
557
- return `dev.shopify.${await spinFqdn()}`;
558
- default:
559
- return productionFqdn;
560
- }
561
- }
562
- async function businessPlatformFqdn() {
563
- let environment = serviceEnvironment(), productionFqdn = "destinations.shopifysvc.com";
564
- switch (environment) {
565
- case "local":
566
- return new DevServer("business-platform").host();
567
- case "spin":
568
- return `business-platform.${await spinFqdn()}`;
569
- default:
570
- return productionFqdn;
571
- }
572
- }
573
- async function identityFqdn() {
574
- let environment = serviceEnvironment(), productionFqdn = "accounts.shopify.com";
575
- switch (environment) {
576
- case "local":
577
- return new DevServer("identity").host();
578
- case "spin":
579
- return `identity.${await spinFqdn()}`;
580
- default:
581
- return productionFqdn;
582
- }
583
- }
584
- async function normalizeStoreFqdn(store2) {
585
- let storeFqdn = store2.replace(/^https?:\/\//, "").replace(/\/$/, ""), addDomain = async (storeFqdn2) => {
586
- switch (serviceEnvironment()) {
587
- case "local":
588
- return new DevServerCore().host(storeFqdn2);
589
- case "spin":
590
- return `${storeFqdn2}.shopify.${await spinFqdn()}`;
591
- default:
592
- return `${storeFqdn2}.myshopify.com`;
593
- }
594
- };
595
- return ((storeFqdn2) => storeFqdn2.includes(".myshopify.com") || storeFqdn2.includes("spin.dev") || storeFqdn2.includes("shopify.io") || storeFqdn2.includes(".shop.dev"))(storeFqdn) ? storeFqdn : addDomain(storeFqdn);
596
- }
597
-
598
- // ../cli-kit/dist/public/node/result.js
599
- init_cjs_shims();
600
- var ok = (value) => new Ok(value), err = (err2) => new Err(err2), Ok = class {
601
- constructor(value) {
602
- this.value = value;
603
- }
604
- /**
605
- * Check if a `Result` is an `Err` inferring its type. `!isErr()` should be used before accessing the `value`
606
- *
607
- * @returns `false` as the `Resul` is `OK`
608
- */
609
- isErr() {
610
- return !1;
611
- }
612
- /**
613
- * Runs the `handler` method an return the same an unaltered copy of the `Result`. It could be used to log an
614
- * output when the result is `Ok` without breaking the flow
615
- *
616
- * @param handler - method to be run when the result is `Ok`
617
- * @returns a copy of the same `Result`
618
- */
619
- doOnOk(handler) {
620
- return handler(this.value), ok(this.value);
621
- }
622
- /**
623
- * A safe mode to throw the `error` of the `Result`
624
- */
625
- valueOrBug() {
626
- return this.value;
627
- }
628
- /**
629
- * Throws an abort error if the result doesn't represent a value.
630
- */
631
- valueOrAbort() {
632
- return this.value;
633
- }
634
- /**
635
- * Maps the value to another one with a different type. It leaves the `Error` type unaltered
636
- *
637
- * @param mapper - The mapper method to apply an `OK` value
638
- * @returns a new result with the new mapped value
639
- */
640
- map(mapper) {
641
- return ok(mapper(this.value));
642
- }
643
- /**
644
- * Maps the error type to another one. It leaves the `Ok` type and value unaltered
645
- *
646
- * @param _mapper - This mapper method is not used for an `Ok` value
647
- * @returns a new result with the new mapped error type and an value
648
- */
649
- mapError(_mapper) {
650
- return ok(this.value);
651
- }
652
- }, Err = class {
653
- // eslint-disable-next-line node/handle-callback-err
654
- constructor(error) {
655
- this.error = error;
656
- }
657
- /**
658
- * Check if a `Result` is an `Err` inferring its type. `!isErr()` should be used before accessing the `value`
659
- *
660
- * @returns `false` as the `Resul` is `OK`
661
- */
662
- isErr() {
663
- return !0;
664
- }
665
- /**
666
- * Return an unaltered copy of the `Error` without doing anything.
667
- *
668
- * @param _handler - This handler method is not used for an `Error`
669
- * @returns a copy of the same `Error`
670
- */
671
- doOnOk(_handler) {
672
- return err(this.error);
673
- }
674
- /**
675
- * A safe mode to throw the `error` of the `Result`
676
- */
677
- valueOrBug() {
678
- throw this.error;
679
- }
680
- /**
681
- * Throws an abort error if the result doesn't represent a value.
682
- */
683
- valueOrAbort() {
684
- if (this.error instanceof FatalError)
685
- throw this.error;
686
- if (this.error instanceof import_ts_error.ExtendableError || this.error instanceof Error) {
687
- let error = new AbortError(this.error.message);
688
- throw error.stack = this.error.stack, error;
689
- } else
690
- throw new AbortError(`${this.error}`);
691
- }
692
- /**
693
- * Maps the value type to another one. It leaves the `Error` unaltered
694
- *
695
- * @param _mapper - This mapper method is not used for an `Error` value
696
- * @returns a new result with the new value type and an unaltered error
697
- */
698
- map(_mapper) {
699
- return err(this.error);
700
- }
701
- /**
702
- * Maps the error to another one with a different type. It leaves the value type unaltered
703
- *
704
- * @param mapper - The mapper method to apply an `Error` value
705
- * @returns a new result with the new mapped error
706
- */
707
- mapError(mapper) {
708
- return err(mapper(this.error));
709
- }
710
- };
711
-
712
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/index.js
713
- init_cjs_shims();
714
-
715
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/runtime/base64url.js
716
- init_cjs_shims();
717
- import { Buffer } from "node:buffer";
718
-
719
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/lib/buffer_utils.js
720
- init_cjs_shims();
721
- var encoder = new TextEncoder(), decoder = new TextDecoder(), MAX_INT32 = 2 ** 32;
722
-
723
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/runtime/base64url.js
724
- function normalize(input) {
725
- let encoded = input;
726
- return encoded instanceof Uint8Array && (encoded = decoder.decode(encoded)), encoded;
727
- }
728
- var decode = (input) => new Uint8Array(Buffer.from(normalize(input), "base64url"));
729
-
730
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/errors.js
731
- init_cjs_shims();
732
- var JOSEError = class extends Error {
733
- static code = "ERR_JOSE_GENERIC";
734
- code = "ERR_JOSE_GENERIC";
735
- constructor(message, options) {
736
- super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
737
- }
738
- };
739
- var JWTInvalid = class extends JOSEError {
740
- static code = "ERR_JWT_INVALID";
741
- code = "ERR_JWT_INVALID";
742
- };
743
-
744
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/lib/is_object.js
745
- init_cjs_shims();
746
- function isObjectLike(value) {
747
- return typeof value == "object" && value !== null;
748
- }
749
- function isObject(input) {
750
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]")
751
- return !1;
752
- if (Object.getPrototypeOf(input) === null)
753
- return !0;
754
- let proto = input;
755
- for (; Object.getPrototypeOf(proto) !== null; )
756
- proto = Object.getPrototypeOf(proto);
757
- return Object.getPrototypeOf(input) === proto;
758
- }
759
-
760
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/base64url.js
761
- init_cjs_shims();
762
- var decode2 = decode;
763
-
764
- // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/decode_jwt.js
765
- init_cjs_shims();
766
- function decodeJwt(jwt) {
767
- if (typeof jwt != "string")
768
- throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
769
- let { 1: payload, length } = jwt.split(".");
770
- if (length === 5)
771
- throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
772
- if (length !== 3)
773
- throw new JWTInvalid("Invalid JWT");
774
- if (!payload)
775
- throw new JWTInvalid("JWTs must contain a payload");
776
- let decoded;
777
- try {
778
- decoded = decode2(payload);
779
- } catch {
780
- throw new JWTInvalid("Failed to base64url decode the payload");
781
- }
782
- let result;
783
- try {
784
- result = JSON.parse(decoder.decode(decoded));
785
- } catch {
786
- throw new JWTInvalid("Failed to parse the decoded payload as JSON");
787
- }
788
- if (!isObject(result))
789
- throw new JWTInvalid("Invalid JWT Claims Set");
790
- return result;
791
- }
792
-
793
- // ../cli-kit/dist/private/node/session/exchange.js
794
- var InvalidGrantError = class extends import_ts_error.ExtendableError {
795
- }, InvalidRequestError = class extends import_ts_error.ExtendableError {
796
- }, InvalidTargetError = class extends AbortError {
797
- };
798
- async function exchangeAccessForApplicationTokens(identityToken, scopes, store2) {
799
- let token = identityToken.accessToken, [partners, storefront, businessPlatform, admin, appManagement] = await Promise.all([
800
- requestAppToken("partners", token, scopes.partners),
801
- requestAppToken("storefront-renderer", token, scopes.storefront),
802
- requestAppToken("business-platform", token, scopes.businessPlatform),
803
- store2 ? requestAppToken("admin", token, scopes.admin, store2) : {},
804
- requestAppToken("app-management", token, scopes.appManagement)
805
- ]);
806
- return {
807
- ...partners,
808
- ...storefront,
809
- ...businessPlatform,
810
- ...admin,
811
- ...appManagement
812
- };
813
- }
814
- async function refreshAccessToken(currentToken) {
815
- let clientId2 = clientId(), params = {
816
- grant_type: "refresh_token",
817
- access_token: currentToken.accessToken,
818
- refresh_token: currentToken.refreshToken,
819
- client_id: clientId2
820
- }, value = (await tokenRequest(params)).mapError(tokenRequestErrorHandler).valueOrBug();
821
- return buildIdentityToken(value, currentToken.userId);
822
- }
823
- async function exchangeCliTokenForAccessToken(apiName, token, scopes) {
824
- let appId = applicationId(apiName);
825
- try {
826
- let accessToken = (await requestAppToken(apiName, token, scopes))[appId].accessToken, userId2 = nonRandomUUID(token);
827
- return setLastSeenUserIdAfterAuth(userId2), setLastSeenAuthMethod("partners_token"), { accessToken, userId: userId2 };
828
- } catch {
829
- let prettyName = apiName.replace(/-/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
830
- throw new AbortError(`The custom token provided can't be used for the ${prettyName} API.`, "Ensure the token is correct and not expired.");
831
- }
832
- }
833
- async function exchangeCustomPartnerToken(token) {
834
- return exchangeCliTokenForAccessToken("partners", token, tokenExchangeScopes("partners"));
835
- }
836
- async function exchangeCliTokenForAppManagementAccessToken(token) {
837
- return exchangeCliTokenForAccessToken("app-management", token, tokenExchangeScopes("app-management"));
838
- }
839
- async function exchangeCliTokenForBusinessPlatformAccessToken(token) {
840
- return exchangeCliTokenForAccessToken("business-platform", token, tokenExchangeScopes("business-platform"));
841
- }
842
- async function exchangeDeviceCodeForAccessToken(deviceCode) {
843
- let clientId2 = await clientId(), tokenResult = await tokenRequest({
844
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
845
- device_code: deviceCode,
846
- client_id: clientId2
847
- });
848
- if (tokenResult.isErr())
849
- return err(tokenResult.error.error);
850
- let identityToken = buildIdentityToken(tokenResult.value);
851
- return ok(identityToken);
852
- }
853
- async function requestAppToken(api, token, scopes = [], store2) {
854
- let appId = applicationId(api), params = {
855
- grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
856
- requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
857
- subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
858
- client_id: await clientId(),
859
- audience: appId,
860
- scope: scopes.join(" "),
861
- subject_token: token,
862
- ...api === "admin" && { destination: `https://${store2}/admin`, store: store2 }
863
- }, identifier = appId;
864
- api === "admin" && store2 && (identifier = `${store2}-${appId}`);
865
- let value = (await tokenRequest(params)).mapError(tokenRequestErrorHandler).valueOrBug(), appToken = buildApplicationToken(value);
866
- return { [identifier]: appToken };
867
- }
868
- function tokenRequestErrorHandler({ error, store: store2 }) {
869
- let invalidTargetErrorMessage = `You are not authorized to use the CLI to develop in the provided store${store2 ? `: ${store2}` : "."}`;
870
- return error === "invalid_grant" ? new InvalidGrantError() : error === "invalid_request" ? new InvalidRequestError() : error === "invalid_target" ? new InvalidTargetError(invalidTargetErrorMessage, "", [
871
- "Ensure you have logged in to the store using the Shopify admin at least once.",
872
- "Ensure you are the store owner, or have a staff account if you are attempting to log in to a development store.",
873
- "Ensure you are using the permanent store domain, not a vanity domain."
874
- ]) : new AbortError(error);
875
- }
876
- async function tokenRequest(params) {
877
- let fqdn = await identityFqdn(), url4 = new URL(`https://${fqdn}/oauth/token`);
878
- url4.search = new URLSearchParams(Object.entries(params)).toString();
879
- let res = await shopifyFetch(url4.href, { method: "POST" }), payload = await res.json();
880
- return res.ok ? ok(payload) : err({ error: payload.error, store: params.store });
881
- }
882
- function buildIdentityToken(result, existingUserId) {
883
- let userId2 = existingUserId ?? (result.id_token ? decodeJwt(result.id_token).sub : void 0);
884
- if (!userId2)
885
- throw new BugError("Error setting userId for session. No id_token or pre-existing user ID provided.");
886
- return {
887
- accessToken: result.access_token,
888
- refreshToken: result.refresh_token,
889
- expiresAt: new Date(Date.now() + result.expires_in * 1e3),
890
- scopes: result.scope.split(" "),
891
- userId: userId2
892
- };
893
- }
894
- function buildApplicationToken(result) {
895
- return {
896
- accessToken: result.access_token,
897
- expiresAt: new Date(Date.now() + result.expires_in * 1e3),
898
- scopes: result.scope.split(" ")
899
- };
900
- }
901
-
902
- // ../cli-kit/dist/private/node/session/store.js
903
- init_cjs_shims();
904
- async function store(session) {
905
- let jsonSession = JSON.stringify(session);
906
- setSession(jsonSession);
907
- }
908
- async function fetch() {
909
- let content = getSession();
910
- if (!content)
911
- return;
912
- let contentJson = JSON.parse(content), parsedSession = await SessionSchema.safeParseAsync(contentJson);
913
- if (parsedSession.success)
914
- return parsedSession.data;
915
- await remove();
916
- }
917
- async function remove() {
918
- removeSession();
919
- }
920
-
921
- // ../cli-kit/dist/private/node/session/device-authorization.js
922
- init_cjs_shims();
923
- async function requestDeviceAuthorization(scopes) {
924
- let fqdn = await identityFqdn(), queryParams = { client_id: clientId(), scope: scopes.join(" ") }, url4 = `https://${fqdn}/oauth/device_authorization`, response = await shopifyFetch(url4, {
925
- method: "POST",
926
- headers: { "Content-type": "application/x-www-form-urlencoded" },
927
- body: convertRequestToParams(queryParams)
928
- }), jsonResult;
929
- try {
930
- jsonResult = await response.json();
931
- } catch {
932
- throw new BugError("Received unexpected response from the authorization service. If this issue persists, please contact support at https://help.shopify.com");
933
- }
934
- if (outputDebug(outputContent`Received device authorization code: ${outputToken.json(jsonResult)}`), !jsonResult.device_code || !jsonResult.verification_uri_complete)
935
- throw new BugError("Failed to start authorization process");
936
- if (outputInfo(`
937
- To run this command, log in to Shopify.`), isCI())
938
- 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.");
939
- outputInfo(outputContent`User verification code: ${jsonResult.user_code}`);
940
- let linkToken = outputToken.link(jsonResult.verification_uri_complete), cloudMessage = () => {
941
- outputInfo(outputContent`👉 Open this link to start the auth process: ${linkToken}`);
942
- };
943
- return isCloudEnvironment() || !isTTY() ? cloudMessage() : (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}`) : cloudMessage()), {
944
- deviceCode: jsonResult.device_code,
945
- userCode: jsonResult.user_code,
946
- verificationUri: jsonResult.verification_uri,
947
- expiresIn: jsonResult.expires_in,
948
- verificationUriComplete: jsonResult.verification_uri_complete,
949
- interval: jsonResult.interval
950
- };
951
- }
952
- async function pollForDeviceAuthorization(code, interval = 5) {
953
- let currentIntervalInSeconds = interval;
954
- return new Promise((resolve, reject) => {
955
- let onPoll = async () => {
956
- let result = await exchangeDeviceCodeForAccessToken(code);
957
- if (!result.isErr()) {
958
- resolve(result.value);
959
- return;
960
- }
961
- let error = result.error ?? "unknown_failure";
962
- switch (outputDebug(outputContent`Polling for device authorization... status: ${error}`), error) {
963
- case "authorization_pending": {
964
- startPolling();
965
- return;
966
- }
967
- case "slow_down":
968
- currentIntervalInSeconds += 5;
969
- {
970
- startPolling();
971
- return;
972
- }
973
- case "access_denied":
974
- case "expired_token":
975
- case "unknown_failure":
976
- reject(result);
977
- }
978
- }, startPolling = () => {
979
- setTimeout(onPoll, currentIntervalInSeconds * 1e3);
980
- };
981
- startPolling();
982
- });
983
- }
984
- function convertRequestToParams(queryParams) {
985
- return Object.entries(queryParams).map(([key, value]) => value && `${key}=${value}`).filter((hasValue) => !!hasValue).join("&");
986
- }
987
-
988
- // ../cli-kit/dist/private/node/api/rest.js
989
- init_cjs_shims();
990
- function isThemeAccessSession(session) {
991
- return session.token.startsWith("shptka_");
992
- }
993
-
994
- // ../cli-kit/dist/private/node/session.js
995
- var userId, authMethod = "none";
996
- async function getLastSeenUserIdAfterAuth() {
997
- if (userId)
998
- return userId;
999
- let currentSession = await fetch() || {}, fqdn = await identityFqdn(), cachedUserId = currentSession[fqdn]?.identity.userId;
1000
- if (cachedUserId)
1001
- return cachedUserId;
1002
- let customToken = getPartnersToken() ?? themeToken();
1003
- return customToken ? nonRandomUUID(customToken) : "unknown";
1004
- }
1005
- function setLastSeenUserIdAfterAuth(id) {
1006
- userId = id;
1007
- }
1008
- async function getLastSeenAuthMethod() {
1009
- if (authMethod !== "none")
1010
- return authMethod;
1011
- let currentSession = await fetch() || {}, fqdn = await identityFqdn();
1012
- if (currentSession[fqdn]?.identity.userId)
1013
- return "device_auth";
1014
- if (getPartnersToken())
1015
- return "partners_token";
1016
- let themePassword = themeToken();
1017
- return themePassword ? isThemeAccessSession({ token: themePassword, storeFqdn: "" }) ? "theme_access_token" : "custom_app_token" : "none";
1018
- }
1019
- function setLastSeenAuthMethod(method) {
1020
- authMethod = method;
1021
- }
1022
- async function ensureAuthenticated(applications, _env, { forceRefresh = !1, noPrompt = !1 } = {}) {
1023
- let fqdn = await identityFqdn(), previousStoreFqdn = applications.adminApi?.storeFqdn;
1024
- if (previousStoreFqdn) {
1025
- let normalizedStoreName = await normalizeStoreFqdn(previousStoreFqdn);
1026
- previousStoreFqdn === applications.adminApi?.storeFqdn && (applications.adminApi.storeFqdn = normalizedStoreName);
1027
- }
1028
- let currentSession = await fetch() || {}, fqdnSession = currentSession[fqdn], scopes = getFlattenScopes(applications);
1029
- outputDebug(outputContent`Validating existing session against the scopes:
1030
- ${outputToken.json(scopes)}
1031
- For applications:
1032
- ${outputToken.json(applications)}
1033
- `);
1034
- let validationResult = await validateSession(scopes, applications, fqdnSession), newSession = {};
1035
- function throwOnNoPrompt() {
1036
- if (!(!noPrompt || isSpin() && firstPartyDev()))
1037
- throw new AbortError(`The currently available CLI credentials are invalid.
1038
-
1039
- 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.");
1040
- }
1041
- if (validationResult === "needs_full_auth")
1042
- throwOnNoPrompt(), outputDebug(outputContent`Initiating the full authentication flow...`), newSession = await executeCompleteFlow(applications, fqdn);
1043
- else if (validationResult === "needs_refresh" || forceRefresh) {
1044
- outputDebug(outputContent`The current session is valid but needs refresh. Refreshing...`);
1045
- try {
1046
- newSession = await refreshTokens(fqdnSession.identity, applications, fqdn);
1047
- } catch (error) {
1048
- if (error instanceof InvalidGrantError)
1049
- throwOnNoPrompt(), newSession = await executeCompleteFlow(applications, fqdn);
1050
- else throw error instanceof InvalidRequestError ? (await remove(), new AbortError(`
1051
- Error validating auth session`, "We've cleared the current session, please try again")) : error;
1052
- }
1053
- }
1054
- let completeSession = { ...currentSession, ...newSession };
1055
- Object.keys(newSession).length > 0 && await store(completeSession);
1056
- let tokens = await tokensFor(applications, completeSession, fqdn), envToken = getPartnersToken();
1057
- return envToken && applications.partnersApi && (tokens.partners = (await exchangeCustomPartnerToken(envToken)).accessToken), setLastSeenAuthMethod(envToken ? "partners_token" : "device_auth"), setLastSeenUserIdAfterAuth(tokens.userId), tokens;
1058
- }
1059
- async function executeCompleteFlow(applications, identityFqdn2) {
1060
- let scopes = getFlattenScopes(applications), exchangeScopes = getExchangeScopes(applications), store2 = applications.adminApi?.storeFqdn;
1061
- firstPartyDev() && (outputDebug(outputContent`Authenticating as Shopify Employee...`), scopes.push("employee"));
1062
- let identityToken, identityTokenInformation = getIdentityTokenInformation();
1063
- if (identityTokenInformation)
1064
- identityToken = buildIdentityTokenFromEnv(scopes, identityTokenInformation);
1065
- else {
1066
- outputDebug(outputContent`Requesting device authorization code...`);
1067
- let deviceAuth = await requestDeviceAuthorization(scopes);
1068
- outputDebug(outputContent`Starting polling for the identity token...`), identityToken = await pollForDeviceAuthorization(deviceAuth.deviceCode, deviceAuth.interval);
1069
- }
1070
- outputDebug(outputContent`CLI token received. Exchanging it for application tokens...`);
1071
- let result = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, store2), session = {
1072
- [identityFqdn2]: {
1073
- identity: identityToken,
1074
- applications: result
1075
- }
1076
- };
1077
- return outputCompleted("Logged in."), session;
1078
- }
1079
- async function refreshTokens(token, applications, fqdn) {
1080
- let identityToken = await refreshAccessToken(token), exchangeScopes = getExchangeScopes(applications), applicationTokens = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, applications.adminApi?.storeFqdn);
1081
- return {
1082
- [fqdn]: {
1083
- identity: identityToken,
1084
- applications: applicationTokens
1085
- }
1086
- };
1087
- }
1088
- async function tokensFor(applications, session, fqdn) {
1089
- let fqdnSession = session[fqdn];
1090
- if (!fqdnSession)
1091
- throw new BugError("No session found after ensuring authenticated");
1092
- let tokens = {
1093
- userId: fqdnSession.identity.userId
1094
- };
1095
- if (applications.adminApi) {
1096
- let appId = applicationId("admin"), realAppId = `${applications.adminApi.storeFqdn}-${appId}`, token = fqdnSession.applications[realAppId]?.accessToken;
1097
- token && (tokens.admin = { token, storeFqdn: applications.adminApi.storeFqdn });
1098
- }
1099
- if (applications.partnersApi) {
1100
- let appId = applicationId("partners");
1101
- tokens.partners = fqdnSession.applications[appId]?.accessToken;
1102
- }
1103
- if (applications.storefrontRendererApi) {
1104
- let appId = applicationId("storefront-renderer");
1105
- tokens.storefront = fqdnSession.applications[appId]?.accessToken;
1106
- }
1107
- if (applications.businessPlatformApi) {
1108
- let appId = applicationId("business-platform");
1109
- tokens.businessPlatform = fqdnSession.applications[appId]?.accessToken;
1110
- }
1111
- if (applications.appManagementApi) {
1112
- let appId = applicationId("app-management");
1113
- tokens.appManagement = fqdnSession.applications[appId]?.accessToken;
1114
- }
1115
- return tokens;
1116
- }
1117
- function getFlattenScopes(apps) {
1118
- 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];
1119
- return allDefaultScopes(requestedScopes);
1120
- }
1121
- function getExchangeScopes(apps) {
1122
- let adminScope = apps.adminApi?.scopes || [], partnerScope = apps.partnersApi?.scopes || [], storefrontScopes = apps.storefrontRendererApi?.scopes || [], businessPlatformScopes = apps.businessPlatformApi?.scopes || [], appManagementScopes = apps.appManagementApi?.scopes || [];
1123
- return {
1124
- admin: apiScopes("admin", adminScope),
1125
- partners: apiScopes("partners", partnerScope),
1126
- storefront: apiScopes("storefront-renderer", storefrontScopes),
1127
- businessPlatform: apiScopes("business-platform", businessPlatformScopes),
1128
- appManagement: apiScopes("app-management", appManagementScopes)
1129
- };
1130
- }
1131
- function buildIdentityTokenFromEnv(scopes, identityTokenInformation) {
1132
- return {
1133
- ...identityTokenInformation,
1134
- expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3),
1135
- scopes
1136
- };
1137
- }
1138
-
1139
- // ../cli-kit/dist/private/node/analytics.js
1140
- async function startAnalytics({ commandContent, args, currentTime = (/* @__PURE__ */ new Date()).getTime(), commandClass }) {
1141
- let startCommand = commandContent.command;
1142
- commandClass && Object.prototype.hasOwnProperty.call(commandClass, "analyticsNameOverride") && (startCommand = commandClass.analyticsNameOverride() ?? commandContent.command);
1143
- let pluginName = commandClass?.plugin?.name;
1144
- commandClass && "customPluginName" in commandClass && (pluginName = commandClass.customPluginName), await addSensitiveMetadata(() => ({
1145
- commandStartOptions: {
1146
- startTime: currentTime,
1147
- startCommand,
1148
- startArgs: args
1149
- }
1150
- })), await addPublicMetadata(() => ({
1151
- cmd_all_launcher: packageManagerFromUserAgent(),
1152
- cmd_all_alias_used: commandContent.alias,
1153
- cmd_all_topic: commandContent.topic,
1154
- cmd_all_plugin: pluginName,
1155
- cmd_all_force: flagIncluded("force", commandClass) ? args.includes("--force") : void 0
1156
- }));
1157
- }
1158
- async function getEnvironmentData(config) {
1159
- let ciplatform = ciPlatform(), pluginNames = getPluginNames(config), shopifyPlugins = pluginNames.filter((plugin) => plugin.startsWith("@shopify/")), { platform, arch } = platformAndArch();
1160
- return {
1161
- uname: `${platform} ${arch}`,
1162
- env_ci: ciplatform.isCI,
1163
- env_ci_platform: ciplatform.name,
1164
- env_plugin_installed_any_custom: pluginNames.length !== shopifyPlugins.length,
1165
- env_plugin_installed_shopify: JSON.stringify(shopifyPlugins),
1166
- env_shell: config.shell,
1167
- env_web_ide: cloudEnvironment().editor ? cloudEnvironment().platform : void 0,
1168
- env_device_id: hashString(await macAddress()),
1169
- env_cloud: cloudEnvironment().platform,
1170
- env_package_manager: await getPackageManager(cwd()),
1171
- env_is_global: currentProcessIsGlobal(),
1172
- env_auth_method: await getLastSeenAuthMethod(),
1173
- env_is_wsl: await isWsl(),
1174
- env_build_repository: "Shopify/cli"
1175
- };
1176
- }
1177
- async function getSensitiveEnvironmentData(config) {
1178
- return {
1179
- env_plugin_installed_all: JSON.stringify(getPluginNames(config))
1180
- };
1181
- }
1182
- function getPluginNames(config) {
1183
- return [...config.plugins.keys()].sort().filter((plugin) => !plugin.startsWith("@oclif/"));
1184
- }
1185
- function flagIncluded(flag, commandClass) {
1186
- if (!commandClass)
1187
- return !1;
1188
- let commandFlags = commandClass.flags ?? {};
1189
- return Object.keys(commandFlags).includes(flag);
1190
- }
1191
-
1192
- export {
1193
- DevServerCore,
1194
- partnersFqdn,
1195
- adminFqdn,
1196
- appManagementFqdn,
1197
- appDevFqdn,
1198
- developerDashboardFqdn,
1199
- businessPlatformFqdn,
1200
- normalizeStoreFqdn,
1201
- ok,
1202
- err,
1203
- exchangeCustomPartnerToken,
1204
- exchangeCliTokenForAppManagementAccessToken,
1205
- exchangeCliTokenForBusinessPlatformAccessToken,
1206
- remove,
1207
- isThemeAccessSession,
1208
- getLastSeenUserIdAfterAuth,
1209
- setLastSeenUserIdAfterAuth,
1210
- setLastSeenAuthMethod,
1211
- ensureAuthenticated,
1212
- startAnalytics,
1213
- getEnvironmentData,
1214
- getSensitiveEnvironmentData
1215
- };
1216
- //# sourceMappingURL=chunk-T4K4LRMO.js.map