@shopify/cli-kit 3.75.4 → 3.76.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 (54) hide show
  1. package/dist/cli/api/graphql/admin/generated/theme_create.d.ts +21 -0
  2. package/dist/cli/api/graphql/admin/generated/theme_create.js +85 -0
  3. package/dist/cli/api/graphql/admin/generated/theme_create.js.map +1 -0
  4. package/dist/private/node/api/graphql.d.ts +1 -0
  5. package/dist/private/node/api/graphql.js +34 -4
  6. package/dist/private/node/api/graphql.js.map +1 -1
  7. package/dist/private/node/conf-store.d.ts +6 -5
  8. package/dist/private/node/conf-store.js +1 -1
  9. package/dist/private/node/conf-store.js.map +1 -1
  10. package/dist/private/node/session/device-authorization.js +11 -3
  11. package/dist/private/node/session/device-authorization.js.map +1 -1
  12. package/dist/private/node/session/validate.js +0 -5
  13. package/dist/private/node/session/validate.js.map +1 -1
  14. package/dist/public/common/version.d.ts +1 -1
  15. package/dist/public/common/version.js +1 -1
  16. package/dist/public/common/version.js.map +1 -1
  17. package/dist/public/node/api/admin.js +3 -3
  18. package/dist/public/node/api/admin.js.map +1 -1
  19. package/dist/public/node/api/app-management.d.ts +3 -2
  20. package/dist/public/node/api/app-management.js +6 -1
  21. package/dist/public/node/api/app-management.js.map +1 -1
  22. package/dist/public/node/api/business-platform.d.ts +5 -3
  23. package/dist/public/node/api/business-platform.js +6 -2
  24. package/dist/public/node/api/business-platform.js.map +1 -1
  25. package/dist/public/node/api/graphql.d.ts +8 -0
  26. package/dist/public/node/api/graphql.js +19 -2
  27. package/dist/public/node/api/graphql.js.map +1 -1
  28. package/dist/public/node/api/partners.d.ts +3 -2
  29. package/dist/public/node/api/partners.js +3 -1
  30. package/dist/public/node/api/partners.js.map +1 -1
  31. package/dist/public/node/base-command.js +8 -5
  32. package/dist/public/node/base-command.js.map +1 -1
  33. package/dist/public/node/cli.js +5 -4
  34. package/dist/public/node/cli.js.map +1 -1
  35. package/dist/public/node/hooks/postrun.js +2 -1
  36. package/dist/public/node/hooks/postrun.js.map +1 -1
  37. package/dist/public/node/hooks/prerun.js +3 -0
  38. package/dist/public/node/hooks/prerun.js.map +1 -1
  39. package/dist/public/node/notifications-system.d.ts +15 -1
  40. package/dist/public/node/notifications-system.js +55 -11
  41. package/dist/public/node/notifications-system.js.map +1 -1
  42. package/dist/public/node/system.d.ts +3 -1
  43. package/dist/public/node/system.js +22 -3
  44. package/dist/public/node/system.js.map +1 -1
  45. package/dist/public/node/themes/api.d.ts +16 -1
  46. package/dist/public/node/themes/api.js +34 -114
  47. package/dist/public/node/themes/api.js.map +1 -1
  48. package/dist/public/node/themes/theme-manager.js +4 -4
  49. package/dist/public/node/themes/theme-manager.js.map +1 -1
  50. package/dist/tsconfig.tsbuildinfo +1 -1
  51. package/package.json +1 -2
  52. package/dist/private/node/session/identity-token-validation.d.ts +0 -1
  53. package/dist/private/node/session/identity-token-validation.js +0 -70
  54. package/dist/private/node/session/identity-token-validation.js.map +0 -1
@@ -166,11 +166,25 @@ export type Notifications = zod.infer<typeof NotificationsSchema>;
166
166
  */
167
167
  export declare function showNotificationsIfNeeded(currentSurfaces?: string[], environment?: NodeJS.ProcessEnv): Promise<void>;
168
168
  /**
169
- * Get notifications list from cache (refreshed every hour) or fetch it if not present.
169
+ * Get notifications list from cache, that is updated in the background from bin/fetch-notifications.json.
170
170
  *
171
171
  * @returns A Notifications object.
172
172
  */
173
173
  export declare function getNotifications(): Promise<Notifications>;
174
+ /**
175
+ * Fetch notifications from the CDN and chache them.
176
+ *
177
+ * @returns A string with the notifications.
178
+ */
179
+ export declare function fetchNotifications(): Promise<Notifications>;
180
+ /**
181
+ * Fetch notifications in background as a detached process.
182
+ *
183
+ * @param currentCommand - The current Shopify command being run.
184
+ * @param argv - The arguments passed to the current process.
185
+ * @param environment - Process environment variables.
186
+ */
187
+ export declare function fetchNotificationsInBackground(currentCommand: string, argv?: string[], environment?: NodeJS.ProcessEnv): void;
174
188
  /**
175
189
  * Filters notifications based on the version of the CLI.
176
190
  *
@@ -5,12 +5,13 @@ import { outputDebug } from './output.js';
5
5
  import { zod } from './schema.js';
6
6
  import { AbortSilentError } from './error.js';
7
7
  import { isTruthy } from './context/utilities.js';
8
+ import { exec } from './system.js';
8
9
  import { jsonOutputEnabled } from './environment.js';
9
10
  import { CLI_KIT_VERSION } from '../common/version.js';
10
- import { cacheRetrieve, cacheRetrieveOrRepopulate, cacheStore, } from '../../private/node/conf-store.js';
11
+ import { cacheRetrieve, cacheStore } from '../../private/node/conf-store.js';
11
12
  import { fetch } from '@shopify/cli-kit/node/http';
12
13
  const URL = 'https://cdn.shopify.com/static/cli/notifications.json';
13
- const CACHE_DURATION_IN_MS = 3600 * 1000;
14
+ const EMPTY_CACHE_MESSAGE = 'Cache is empty';
14
15
  function url() {
15
16
  return process.env.SHOPIFY_CLI_NOTIFICATIONS_URL ?? URL;
16
17
  }
@@ -44,7 +45,7 @@ const NotificationsSchema = zod.object({ notifications: zod.array(NotificationSc
44
45
  */
45
46
  export async function showNotificationsIfNeeded(currentSurfaces, environment = process.env) {
46
47
  try {
47
- if (skipNotifications(environment))
48
+ if (skipNotifications(environment) || jsonOutputEnabled(environment))
48
49
  return;
49
50
  const notifications = await getNotifications();
50
51
  const commandId = getCurrentCommandId();
@@ -58,13 +59,15 @@ export async function showNotificationsIfNeeded(currentSurfaces, environment = p
58
59
  throw new AbortSilentError();
59
60
  const errorMessage = `Error retrieving notifications: ${error.message}`;
60
61
  outputDebug(errorMessage);
62
+ if (error.message === EMPTY_CACHE_MESSAGE)
63
+ return;
61
64
  // This is very prone to becoming a circular dependency, so we import it dynamically
62
65
  const { sendErrorToBugsnag } = await import('./error-handler.js');
63
66
  await sendErrorToBugsnag(errorMessage, 'unexpected_error');
64
67
  }
65
68
  }
66
- function skipNotifications(environment) {
67
- return isTruthy(environment.CI) || isTruthy(environment.SHOPIFY_UNIT_TEST) || jsonOutputEnabled(environment);
69
+ function skipNotifications(environment = process.env) {
70
+ return isTruthy(environment.CI) || isTruthy(environment.SHOPIFY_UNIT_TEST);
68
71
  }
69
72
  /**
70
73
  * Renders the first 2 notifications to the user.
@@ -96,25 +99,66 @@ async function renderNotifications(notifications) {
96
99
  });
97
100
  }
98
101
  /**
99
- * Get notifications list from cache (refreshed every hour) or fetch it if not present.
102
+ * Get notifications list from cache, that is updated in the background from bin/fetch-notifications.json.
100
103
  *
101
104
  * @returns A Notifications object.
102
105
  */
103
106
  export async function getNotifications() {
104
107
  const cacheKey = `notifications-${url()}`;
105
- const rawNotifications = await cacheRetrieveOrRepopulate(cacheKey, fetchNotifications, CACHE_DURATION_IN_MS);
108
+ const rawNotifications = cacheRetrieve(cacheKey)?.value;
109
+ if (!rawNotifications)
110
+ throw new Error(EMPTY_CACHE_MESSAGE);
106
111
  const notifications = JSON.parse(rawNotifications);
107
112
  return NotificationsSchema.parse(notifications);
108
113
  }
109
114
  /**
110
- * Fetch notifications from GitHub.
115
+ * Fetch notifications from the CDN and chache them.
116
+ *
117
+ * @returns A string with the notifications.
111
118
  */
112
- async function fetchNotifications() {
113
- outputDebug(`No cached notifications found. Fetching them...`);
119
+ export async function fetchNotifications() {
120
+ outputDebug(`Fetching notifications...`);
114
121
  const response = await fetch(url(), { signal: AbortSignal.timeout(3 * 1000) });
115
122
  if (response.status !== 200)
116
123
  throw new Error(`Failed to fetch notifications: ${response.statusText}`);
117
- return response.text();
124
+ const rawNotifications = await response.text();
125
+ const notifications = JSON.parse(rawNotifications);
126
+ const result = NotificationsSchema.parse(notifications);
127
+ await cacheNotifications(rawNotifications);
128
+ return result;
129
+ }
130
+ /**
131
+ * Store the notifications in the cache.
132
+ *
133
+ * @param notifications - String with the notifications to cache.
134
+ * @returns A Notifications object.
135
+ */
136
+ async function cacheNotifications(notifications) {
137
+ cacheStore(`notifications-${url()}`, notifications);
138
+ outputDebug(`Notifications from ${url()} stored in the cache`);
139
+ }
140
+ /**
141
+ * Fetch notifications in background as a detached process.
142
+ *
143
+ * @param currentCommand - The current Shopify command being run.
144
+ * @param argv - The arguments passed to the current process.
145
+ * @param environment - Process environment variables.
146
+ */
147
+ export function fetchNotificationsInBackground(currentCommand, argv = process.argv, environment = process.env) {
148
+ if (skipNotifications(environment))
149
+ return;
150
+ let command = 'shopify';
151
+ const args = ['notifications', 'list'];
152
+ // Run the Shopify command the same way as the current execution when it's not the global installation
153
+ if (argv[0] && argv[0] !== 'shopify') {
154
+ command = argv[0];
155
+ const indexValue = currentCommand.split(':')[0] ?? '';
156
+ const index = argv.indexOf(indexValue);
157
+ if (index > 0)
158
+ args.unshift(...argv.slice(1, index));
159
+ }
160
+ // eslint-disable-next-line no-void
161
+ void exec(command, args, { background: true, env: { ...process.env, SHOPIFY_CLI_NO_ANALYTICS: '1' } });
118
162
  }
119
163
  /**
120
164
  * Filters notifications based on the version of the CLI.
@@ -1 +1 @@
1
- {"version":3,"file":"notifications-system.js","sourceRoot":"","sources":["../../../src/public/node/notifications-system.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,gBAAgB,EAAC,MAAM,2BAA2B,CAAA;AAC1D,OAAO,EAAC,WAAW,EAAE,UAAU,EAAE,aAAa,EAAC,MAAM,SAAS,CAAA;AAC9D,OAAO,EAAC,mBAAmB,EAAC,MAAM,qBAAqB,CAAA;AACvD,OAAO,EAAC,WAAW,EAAC,MAAM,aAAa,CAAA;AACvC,OAAO,EAAC,GAAG,EAAC,MAAM,aAAa,CAAA;AAC/B,OAAO,EAAC,gBAAgB,EAAC,MAAM,YAAY,CAAA;AAC3C,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,iBAAiB,EAAC,MAAM,kBAAkB,CAAA;AAClD,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAGL,aAAa,EACb,yBAAyB,EACzB,UAAU,GACX,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAC,KAAK,EAAC,MAAM,4BAA4B,CAAA;AAEhD,MAAM,GAAG,G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IAC3E,IAAI,YAAY,CAAC,SAAS,KAAK,MAAM;QAAE,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;IACrE,IAAI,YAAY,CAAC,SAAS,KAAK,YAAY;QAAE,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAA;IAC5E,IAAI,YAAY,CAAC,SAAS,KAAK,aAAa;QAAE,OAAO,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;IAC9E,IAAI,YAAY,CAAC,OAAO;QAAE,OAAO,CAAC,IAAI,CAAC,aAAa,YAAY,CAAC,OAAO,EAAE,CAAC,CAAA;IAC3E,IAAI,YAAY,CAAC,QAAQ;QAAE,OAAO,CAAC,IAAI,CAAC,cAAc,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IACzF,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAC3B,CAAC","sourcesContent":["import {versionSatisfies} from './node-package-manager.js'\nimport {renderError, renderInfo, renderWarning} from './ui.js'\nimport {getCurrentCommandId} from './global-context.js'\nimport {outputDebug} from './output.js'\nimport {zod} from './schema.js'\nimport {AbortSilentError} from './error.js'\nimport {isTruthy} from './context/utilities.js'\nimport {jsonOutputEnabled} from './environment.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {\n NotificationKey,\n NotificationsKey,\n cacheRetrieve,\n cacheRetrieveOrRepopulate,\n cacheStore,\n} from '../../private/node/conf-store.js'\nimport {fetch} from '@shopify/cli-kit/node/http'\n\nconst URL = 'https://cdn.shopify.com/static/cli/notifications.json'\nconst CACHE_DURATION_IN_MS = 3600 * 1000\n\nfunction url(): string {\n return process.env.SHOPIFY_CLI_NOTIFICATIONS_URL ?? URL\n}\n\nconst NotificationSchema = zod.object({\n id: zod.string(),\n message: zod.string(),\n type: zod.enum(['info', 'warning', 'error']),\n frequency: zod.enum(['always', 'once', 'once_a_day', 'once_a_week']),\n ownerChannel: zod.string(),\n cta: zod\n .object({\n label: zod.string(),\n url: zod.string().url(),\n })\n .optional(),\n title: zod.string().optional(),\n minVersion: zod.string().optional(),\n maxVersion: zod.string().optional(),\n minDate: zod.string().optional(),\n maxDate: zod.string().optional(),\n commands: zod.array(zod.string()).optional(),\n surface: zod.string().optional(),\n})\nexport type Notification = zod.infer<typeof NotificationSchema>\n\nconst NotificationsSchema = zod.object({notifications: zod.array(NotificationSchema)})\nexport type Notifications = zod.infer<typeof NotificationsSchema>\n\n/**\n * Shows notifications to the user if they meet the criteria specified in the notifications.json file.\n *\n * @param currentSurfaces - The surfaces present in the current project (usually for app extensions).\n * @param environment - Process environment variables.\n * @returns - A promise that resolves when the notifications have been shown.\n */\nexport async function showNotificationsIfNeeded(\n currentSurfaces?: string[],\n environment: NodeJS.ProcessEnv = process.env,\n): Promise<void> {\n try {\n if (skipNotifications(environment)) return\n\n const notifications = await getNotifications()\n const commandId = getCurrentCommandId()\n const notificationsToShow = filterNotifications(notifications.notifications, commandId, currentSurfaces)\n outputDebug(`Notifications to show: ${notificationsToShow.length}`)\n await renderNotifications(notificationsToShow)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message === 'abort') throw new AbortSilentError()\n const errorMessage = `Error retrieving notifications: ${error.message}`\n outputDebug(errorMessage)\n // This is very prone to becoming a circular dependency, so we import it dynamically\n const {sendErrorToBugsnag} = await import('./error-handler.js')\n await sendErrorToBugsnag(errorMessage, 'unexpected_error')\n }\n}\n\nfunction skipNotifications(environment: NodeJS.ProcessEnv): boolean {\n return isTruthy(environment.CI) || isTruthy(environment.SHOPIFY_UNIT_TEST) || jsonOutputEnabled(environment)\n}\n\n/**\n * Renders the first 2 notifications to the user.\n *\n * @param notifications - The notifications to render.\n */\nasync function renderNotifications(notifications: Notification[]) {\n notifications.slice(0, 2).forEach((notification) => {\n const content = {\n headline: notification.title,\n body: notification.message.replaceAll('\\\\n', '\\n'),\n link: notification.cta,\n }\n switch (notification.type) {\n case 'info': {\n renderInfo(content)\n break\n }\n case 'warning': {\n renderWarning(content)\n break\n }\n case 'error': {\n renderError(content)\n throw new Error('abort')\n }\n }\n cacheStore(`notification-${notification.id}`, new Date().getTime().toString())\n })\n}\n\n/**\n * Get notifications list from cache (refreshed every hour) or fetch it if not present.\n *\n * @returns A Notifications object.\n */\nexport async function getNotifications(): Promise<Notifications> {\n const cacheKey: NotificationsKey = `notifications-${url()}`\n const rawNotifications = await cacheRetrieveOrRepopulate(cacheKey, fetchNotifications, CACHE_DURATION_IN_MS)\n const notifications: object = JSON.parse(rawNotifications)\n return NotificationsSchema.parse(notifications)\n}\n\n/**\n * Fetch notifications from GitHub.\n */\nasync function fetchNotifications(): Promise<string> {\n outputDebug(`No cached notifications found. Fetching them...`)\n const response = await fetch(url(), {signal: AbortSignal.timeout(3 * 1000)})\n if (response.status !== 200) throw new Error(`Failed to fetch notifications: ${response.statusText}`)\n return response.text() as unknown as string\n}\n\n/**\n * Filters notifications based on the version of the CLI.\n *\n * @param notifications - The notifications to filter.\n * @param commandId - The command ID to filter by.\n * @param currentSurfaces - The surfaces present in the current project (usually for app extensions).\n * @param today - The current date.\n * @param currentVersion - The current version of the CLI.\n * @returns - The filtered notifications.\n */\nexport function filterNotifications(\n notifications: Notification[],\n commandId: string,\n currentSurfaces?: string[],\n today: Date = new Date(new Date().setUTCHours(0, 0, 0, 0)),\n currentVersion: string = CLI_KIT_VERSION,\n): Notification[] {\n return notifications\n .filter((notification) => filterByVersion(notification, currentVersion))\n .filter((notifications) => filterByDate(notifications, today))\n .filter((notification) => filterByCommand(notification, commandId))\n .filter((notification) => filterBySurface(notification, commandId, currentSurfaces))\n .filter((notification) => filterByFrequency(notification))\n}\n\n/**\n * Filters notifications based on the version of the CLI.\n *\n * @param notification - The notification to filter.\n * @param currentVersion - The current version of the CLI.\n */\nfunction filterByVersion(notification: Notification, currentVersion: string) {\n const minVersion = !notification.minVersion || versionSatisfies(currentVersion, `>=${notification.minVersion}`)\n const maxVersion = !notification.maxVersion || versionSatisfies(currentVersion, `<=${notification.maxVersion}`)\n return minVersion && maxVersion\n}\n\n/**\n * Filters notifications based on the date.\n *\n * @param notification - The notification to filter.\n * @param today - The current date.\n */\nfunction filterByDate(notification: Notification, today: Date) {\n const minDate = !notification.minDate || new Date(notification.minDate) <= today\n const maxDate = !notification.maxDate || new Date(notification.maxDate) >= today\n return minDate && maxDate\n}\n\n/**\n * Filters notifications based on the command ID.\n *\n * @param notification - The notification to filter.\n * @param commandId - The command ID to filter by.\n * @returns - A boolean indicating whether the notification should be shown.\n */\nfunction filterByCommand(notification: Notification, commandId: string) {\n if (commandId === '') return true\n return !notification.commands || notification.commands.includes(commandId)\n}\n\n/**\n * Filters notifications based on the surface.\n *\n * @param notification - The notification to filter.\n * @param commandId - The command id.\n * @param surfacesFromContext - The surfaces present in the current project (usually for app extensions).\n * @returns - A boolean indicating whether the notification should be shown.\n */\nfunction filterBySurface(notification: Notification, commandId: string, surfacesFromContext?: string[]) {\n const surfaceFromCommand = commandId.split(':')[0] ?? 'all'\n const notificationSurface = notification.surface ?? 'all'\n\n if (surfacesFromContext) return surfacesFromContext.includes(notificationSurface)\n\n return notificationSurface === surfaceFromCommand || notificationSurface === 'all'\n}\n\n/**\n * Filters notifications based on the frequency.\n *\n * @param notification - The notification to filter.\n * @returns - A boolean indicating whether the notification should be shown.\n */\nfunction filterByFrequency(notification: Notification): boolean {\n if (!notification.frequency) return true\n const cacheKey: NotificationKey = `notification-${notification.id}`\n const lastShown = cacheRetrieve(cacheKey)?.value as unknown as string\n if (!lastShown) return true\n\n switch (notification.frequency) {\n case 'always': {\n return true\n }\n case 'once': {\n return false\n }\n case 'once_a_day': {\n return new Date().getTime() - Number(lastShown) > 24 * 3600 * 1000\n }\n case 'once_a_week': {\n return new Date().getTime() - Number(lastShown) > 7 * 24 * 3600 * 1000\n }\n }\n}\n\n/**\n * Returns a string with the filters from a notification, one by line.\n *\n * @param notification - The notification to get the filters from.\n * @returns A string with human-readable filters from the notification.\n */\nexport function stringifyFilters(notification: Notification): string {\n const filters = []\n if (notification.minDate) filters.push(`from ${notification.minDate}`)\n if (notification.maxDate) filters.push(`to ${notification.maxDate}`)\n if (notification.minVersion) filters.push(`from v${notification.minVersion}`)\n if (notification.maxVersion) filters.push(`to v${notification.maxVersion}`)\n if (notification.frequency === 'once') filters.push('show only once')\n if (notification.frequency === 'once_a_day') filters.push('show once a day')\n if (notification.frequency === 'once_a_week') filters.push('show once a week')\n if (notification.surface) filters.push(`surface = ${notification.surface}`)\n if (notification.commands) filters.push(`commands = ${notification.commands.join(', ')}`)\n return filters.join('\\n')\n}\n"]}
1
+ {"version":3,"file":"notifications-system.js","sourceRoot":"","sources":["../../../src/public/node/notifications-system.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,gBAAgB,EAAC,MAAM,2BAA2B,CAAA;AAC1D,OAAO,EAAC,WAAW,EAAE,UAAU,EAAE,aAAa,EAAC,MAAM,SAAS,CAAA;AAC9D,OAAO,EAAC,mBAAmB,EAAC,MAAM,qBAAqB,CAAA;AACvD,OAAO,EAAC,WAAW,EAAC,MAAM,aAAa,CAAA;AACvC,OAAO,EAAC,GAAG,EAAC,MAAM,aAAa,CAAA;AAC/B,OAAO,EAAC,gBAAgB,EAAC,MAAM,YAAY,CAAA;AAC3C,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,IAAI,EAAC,MAAM,aAAa,CAAA;AAChC,OAAO,EAAC,iBAAiB,EAAC,MAAM,kBAAkB,CAAA;AAClD,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAAoC,aAAa,EAAE,UAAU,EAAC,MAAM,kCAAkC,CAAA;AAC7G,OAAO,EAAC,KAAK,EAAC,MAAM,4BAA4B,CAAA;AAEhD,MAAM,GAAG,GAAG,uDAAuD,CAAA;AACnE,MAAM,mBAAmB,GAAG,gBAAgB,CAAA;AAE5C,SAAS,GAAG;IACV,OAAO,OAAO,C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C,SAAS,YAAY,CAAC,UAAU,EAAE,CAAC,CAAA;IAC7E,IAAI,YAAY,CAAC,UAAU;QAAE,OAAO,CAAC,IAAI,CAAC,OAAO,YAAY,CAAC,UAAU,EAAE,CAAC,CAAA;IAC3E,IAAI,YAAY,CAAC,SAAS,KAAK,MAAM;QAAE,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;IACrE,IAAI,YAAY,CAAC,SAAS,KAAK,YAAY;QAAE,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAA;IAC5E,IAAI,YAAY,CAAC,SAAS,KAAK,aAAa;QAAE,OAAO,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;IAC9E,IAAI,YAAY,CAAC,OAAO;QAAE,OAAO,CAAC,IAAI,CAAC,aAAa,YAAY,CAAC,OAAO,EAAE,CAAC,CAAA;IAC3E,IAAI,YAAY,CAAC,QAAQ;QAAE,OAAO,CAAC,IAAI,CAAC,cAAc,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IACzF,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAC3B,CAAC","sourcesContent":["import {versionSatisfies} from './node-package-manager.js'\nimport {renderError, renderInfo, renderWarning} from './ui.js'\nimport {getCurrentCommandId} from './global-context.js'\nimport {outputDebug} from './output.js'\nimport {zod} from './schema.js'\nimport {AbortSilentError} from './error.js'\nimport {isTruthy} from './context/utilities.js'\nimport {exec} from './system.js'\nimport {jsonOutputEnabled} from './environment.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {NotificationKey, NotificationsKey, cacheRetrieve, cacheStore} from '../../private/node/conf-store.js'\nimport {fetch} from '@shopify/cli-kit/node/http'\n\nconst URL = 'https://cdn.shopify.com/static/cli/notifications.json'\nconst EMPTY_CACHE_MESSAGE = 'Cache is empty'\n\nfunction url(): string {\n return process.env.SHOPIFY_CLI_NOTIFICATIONS_URL ?? URL\n}\n\nconst NotificationSchema = zod.object({\n id: zod.string(),\n message: zod.string(),\n type: zod.enum(['info', 'warning', 'error']),\n frequency: zod.enum(['always', 'once', 'once_a_day', 'once_a_week']),\n ownerChannel: zod.string(),\n cta: zod\n .object({\n label: zod.string(),\n url: zod.string().url(),\n })\n .optional(),\n title: zod.string().optional(),\n minVersion: zod.string().optional(),\n maxVersion: zod.string().optional(),\n minDate: zod.string().optional(),\n maxDate: zod.string().optional(),\n commands: zod.array(zod.string()).optional(),\n surface: zod.string().optional(),\n})\nexport type Notification = zod.infer<typeof NotificationSchema>\n\nconst NotificationsSchema = zod.object({notifications: zod.array(NotificationSchema)})\nexport type Notifications = zod.infer<typeof NotificationsSchema>\n\n/**\n * Shows notifications to the user if they meet the criteria specified in the notifications.json file.\n *\n * @param currentSurfaces - The surfaces present in the current project (usually for app extensions).\n * @param environment - Process environment variables.\n * @returns - A promise that resolves when the notifications have been shown.\n */\nexport async function showNotificationsIfNeeded(\n currentSurfaces?: string[],\n environment: NodeJS.ProcessEnv = process.env,\n): Promise<void> {\n try {\n if (skipNotifications(environment) || jsonOutputEnabled(environment)) return\n\n const notifications = await getNotifications()\n const commandId = getCurrentCommandId()\n const notificationsToShow = filterNotifications(notifications.notifications, commandId, currentSurfaces)\n outputDebug(`Notifications to show: ${notificationsToShow.length}`)\n await renderNotifications(notificationsToShow)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message === 'abort') throw new AbortSilentError()\n const errorMessage = `Error retrieving notifications: ${error.message}`\n outputDebug(errorMessage)\n if (error.message === EMPTY_CACHE_MESSAGE) return\n // This is very prone to becoming a circular dependency, so we import it dynamically\n const {sendErrorToBugsnag} = await import('./error-handler.js')\n await sendErrorToBugsnag(errorMessage, 'unexpected_error')\n }\n}\n\nfunction skipNotifications(environment: NodeJS.ProcessEnv = process.env): boolean {\n return isTruthy(environment.CI) || isTruthy(environment.SHOPIFY_UNIT_TEST)\n}\n\n/**\n * Renders the first 2 notifications to the user.\n *\n * @param notifications - The notifications to render.\n */\nasync function renderNotifications(notifications: Notification[]) {\n notifications.slice(0, 2).forEach((notification) => {\n const content = {\n headline: notification.title,\n body: notification.message.replaceAll('\\\\n', '\\n'),\n link: notification.cta,\n }\n switch (notification.type) {\n case 'info': {\n renderInfo(content)\n break\n }\n case 'warning': {\n renderWarning(content)\n break\n }\n case 'error': {\n renderError(content)\n throw new Error('abort')\n }\n }\n cacheStore(`notification-${notification.id}`, new Date().getTime().toString())\n })\n}\n\n/**\n * Get notifications list from cache, that is updated in the background from bin/fetch-notifications.json.\n *\n * @returns A Notifications object.\n */\nexport async function getNotifications(): Promise<Notifications> {\n const cacheKey: NotificationsKey = `notifications-${url()}`\n const rawNotifications = cacheRetrieve(cacheKey)?.value as unknown as string\n if (!rawNotifications) throw new Error(EMPTY_CACHE_MESSAGE)\n const notifications: object = JSON.parse(rawNotifications)\n return NotificationsSchema.parse(notifications)\n}\n\n/**\n * Fetch notifications from the CDN and chache them.\n *\n * @returns A string with the notifications.\n */\nexport async function fetchNotifications(): Promise<Notifications> {\n outputDebug(`Fetching notifications...`)\n const response = await fetch(url(), {signal: AbortSignal.timeout(3 * 1000)})\n if (response.status !== 200) throw new Error(`Failed to fetch notifications: ${response.statusText}`)\n const rawNotifications = await response.text()\n const notifications: object = JSON.parse(rawNotifications)\n const result = NotificationsSchema.parse(notifications)\n await cacheNotifications(rawNotifications)\n return result\n}\n\n/**\n * Store the notifications in the cache.\n *\n * @param notifications - String with the notifications to cache.\n * @returns A Notifications object.\n */\nasync function cacheNotifications(notifications: string): Promise<void> {\n cacheStore(`notifications-${url()}`, notifications)\n outputDebug(`Notifications from ${url()} stored in the cache`)\n}\n\n/**\n * Fetch notifications in background as a detached process.\n *\n * @param currentCommand - The current Shopify command being run.\n * @param argv - The arguments passed to the current process.\n * @param environment - Process environment variables.\n */\nexport function fetchNotificationsInBackground(\n currentCommand: string,\n argv = process.argv,\n environment: NodeJS.ProcessEnv = process.env,\n): void {\n if (skipNotifications(environment)) return\n\n let command = 'shopify'\n const args = ['notifications', 'list']\n // Run the Shopify command the same way as the current execution when it's not the global installation\n if (argv[0] && argv[0] !== 'shopify') {\n command = argv[0]\n const indexValue = currentCommand.split(':')[0] ?? ''\n const index = argv.indexOf(indexValue)\n if (index > 0) args.unshift(...argv.slice(1, index))\n }\n // eslint-disable-next-line no-void\n void exec(command, args, {background: true, env: {...process.env, SHOPIFY_CLI_NO_ANALYTICS: '1'}})\n}\n\n/**\n * Filters notifications based on the version of the CLI.\n *\n * @param notifications - The notifications to filter.\n * @param commandId - The command ID to filter by.\n * @param currentSurfaces - The surfaces present in the current project (usually for app extensions).\n * @param today - The current date.\n * @param currentVersion - The current version of the CLI.\n * @returns - The filtered notifications.\n */\nexport function filterNotifications(\n notifications: Notification[],\n commandId: string,\n currentSurfaces?: string[],\n today: Date = new Date(new Date().setUTCHours(0, 0, 0, 0)),\n currentVersion: string = CLI_KIT_VERSION,\n): Notification[] {\n return notifications\n .filter((notification) => filterByVersion(notification, currentVersion))\n .filter((notifications) => filterByDate(notifications, today))\n .filter((notification) => filterByCommand(notification, commandId))\n .filter((notification) => filterBySurface(notification, commandId, currentSurfaces))\n .filter((notification) => filterByFrequency(notification))\n}\n\n/**\n * Filters notifications based on the version of the CLI.\n *\n * @param notification - The notification to filter.\n * @param currentVersion - The current version of the CLI.\n */\nfunction filterByVersion(notification: Notification, currentVersion: string) {\n const minVersion = !notification.minVersion || versionSatisfies(currentVersion, `>=${notification.minVersion}`)\n const maxVersion = !notification.maxVersion || versionSatisfies(currentVersion, `<=${notification.maxVersion}`)\n return minVersion && maxVersion\n}\n\n/**\n * Filters notifications based on the date.\n *\n * @param notification - The notification to filter.\n * @param today - The current date.\n */\nfunction filterByDate(notification: Notification, today: Date) {\n const minDate = !notification.minDate || new Date(notification.minDate) <= today\n const maxDate = !notification.maxDate || new Date(notification.maxDate) >= today\n return minDate && maxDate\n}\n\n/**\n * Filters notifications based on the command ID.\n *\n * @param notification - The notification to filter.\n * @param commandId - The command ID to filter by.\n * @returns - A boolean indicating whether the notification should be shown.\n */\nfunction filterByCommand(notification: Notification, commandId: string) {\n if (commandId === '') return true\n return !notification.commands || notification.commands.includes(commandId)\n}\n\n/**\n * Filters notifications based on the surface.\n *\n * @param notification - The notification to filter.\n * @param commandId - The command id.\n * @param surfacesFromContext - The surfaces present in the current project (usually for app extensions).\n * @returns - A boolean indicating whether the notification should be shown.\n */\nfunction filterBySurface(notification: Notification, commandId: string, surfacesFromContext?: string[]) {\n const surfaceFromCommand = commandId.split(':')[0] ?? 'all'\n const notificationSurface = notification.surface ?? 'all'\n\n if (surfacesFromContext) return surfacesFromContext.includes(notificationSurface)\n\n return notificationSurface === surfaceFromCommand || notificationSurface === 'all'\n}\n\n/**\n * Filters notifications based on the frequency.\n *\n * @param notification - The notification to filter.\n * @returns - A boolean indicating whether the notification should be shown.\n */\nfunction filterByFrequency(notification: Notification): boolean {\n if (!notification.frequency) return true\n const cacheKey: NotificationKey = `notification-${notification.id}`\n const lastShown = cacheRetrieve(cacheKey)?.value as unknown as string\n if (!lastShown) return true\n\n switch (notification.frequency) {\n case 'always': {\n return true\n }\n case 'once': {\n return false\n }\n case 'once_a_day': {\n return new Date().getTime() - Number(lastShown) > 24 * 3600 * 1000\n }\n case 'once_a_week': {\n return new Date().getTime() - Number(lastShown) > 7 * 24 * 3600 * 1000\n }\n }\n}\n\n/**\n * Returns a string with the filters from a notification, one by line.\n *\n * @param notification - The notification to get the filters from.\n * @returns A string with human-readable filters from the notification.\n */\nexport function stringifyFilters(notification: Notification): string {\n const filters = []\n if (notification.minDate) filters.push(`from ${notification.minDate}`)\n if (notification.maxDate) filters.push(`to ${notification.maxDate}`)\n if (notification.minVersion) filters.push(`from v${notification.minVersion}`)\n if (notification.maxVersion) filters.push(`to v${notification.maxVersion}`)\n if (notification.frequency === 'once') filters.push('show only once')\n if (notification.frequency === 'once_a_day') filters.push('show once a day')\n if (notification.frequency === 'once_a_week') filters.push('show once a week')\n if (notification.surface) filters.push(`surface = ${notification.surface}`)\n if (notification.commands) filters.push(`commands = ${notification.commands.join(', ')}`)\n return filters.join('\\n')\n}\n"]}
@@ -12,13 +12,15 @@ export interface ExecOptions {
12
12
  input?: string;
13
13
  signal?: AbortSignal;
14
14
  externalErrorHandler?: (error: unknown) => Promise<void>;
15
+ background?: boolean;
15
16
  }
16
17
  /**
17
18
  * Opens a URL in the user's default browser.
18
19
  *
19
20
  * @param url - URL to open.
21
+ * @returns A promise that resolves true if the URL was opened successfully, false otherwise.
20
22
  */
21
- export declare function openURL(url: string): Promise<void>;
23
+ export declare function openURL(url: string): Promise<boolean>;
22
24
  /**
23
25
  * Runs a command asynchronously, aggregates the stdout data, and returns it.
24
26
  *
@@ -3,6 +3,7 @@ import { cwd, dirname } from './path.js';
3
3
  import { treeKill } from './tree-kill.js';
4
4
  import { isTruthy } from './context/utilities.js';
5
5
  import { renderWarning } from './ui.js';
6
+ import { platformAndArch } from './os.js';
6
7
  import { shouldDisplayColors, outputDebug } from '../../public/node/output.js';
7
8
  import { execa } from 'execa';
8
9
  import which from 'which';
@@ -11,10 +12,18 @@ import { delimiter } from 'pathe';
11
12
  * Opens a URL in the user's default browser.
12
13
  *
13
14
  * @param url - URL to open.
15
+ * @returns A promise that resolves true if the URL was opened successfully, false otherwise.
14
16
  */
15
17
  export async function openURL(url) {
16
18
  const externalOpen = await import('open');
17
- await externalOpen.default(url);
19
+ try {
20
+ await externalOpen.default(url);
21
+ return true;
22
+ // eslint-disable-next-line no-catch-all/no-catch-all
23
+ }
24
+ catch (error) {
25
+ return false;
26
+ }
18
27
  }
19
28
  /**
20
29
  * Runs a command asynchronously, aggregates the stdout data, and returns it.
@@ -36,7 +45,15 @@ export async function captureOutput(command, args, options) {
36
45
  * @param options - Optional settings for how to run the command.
37
46
  */
38
47
  export async function exec(command, args, options) {
48
+ if (options) {
49
+ // Windows opens a new console window when running a command in the background, so we disable it.
50
+ const runningOnWindows = platformAndArch().platform === 'windows';
51
+ options.background = runningOnWindows ? false : options.background;
52
+ }
39
53
  const commandProcess = buildExec(command, args, options);
54
+ if (options?.background) {
55
+ commandProcess.unref();
56
+ }
40
57
  if (options?.stderr && options.stderr !== 'inherit') {
41
58
  commandProcess.stderr?.pipe(options.stderr, { end: false });
42
59
  }
@@ -90,16 +107,18 @@ function buildExec(command, args, options) {
90
107
  env,
91
108
  cwd: executionCwd,
92
109
  input: options?.input,
93
- stdio: options?.stdio,
110
+ stdio: options?.background ? 'ignore' : options?.stdio,
94
111
  stdin: options?.stdin,
95
112
  stdout: options?.stdout === 'inherit' ? 'inherit' : undefined,
96
113
  stderr: options?.stderr === 'inherit' ? 'inherit' : undefined,
97
114
  // Setting this to false makes it possible to kill the main process
98
115
  // and all its sub-processes with Ctrl+C on Windows
99
116
  windowsHide: false,
117
+ detached: options?.background,
118
+ cleanup: !options?.background,
100
119
  });
101
120
  outputDebug(`
102
- Running system process:
121
+ Running system process${options?.background ? ' in background' : ''}:
103
122
  · Command: ${command} ${args.join(' ')}
104
123
  · Working directory: ${executionCwd}
105
124
  `);
@@ -1 +1 @@
1
- {"version":3,"file":"system.js","sourceRoot":"","sources":["../../../src/public/node/system.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,UAAU,EAAE,aAAa,EAAC,MAAM,YAAY,CAAA;AACpD,OAAO,EAAC,GAAG,EAAE,OAAO,EAAC,MAAM,WAAW,CAAA;AACtC,OAAO,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,aAAa,EAAC,MAAM,SAAS,CAAA;AACrC,OAAO,EAAC,mBAAmB,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AAC5E,OAAO,EAAC,KAAK,EAAoB,MAAM,OAAO,CAAA;AAC9C,OAAO,KAAK,MAAM,OAAO,CAAA;AACzB,OAAO,EAAC,SAAS,EAAC,MAAM,OAAO,CAAA;AAgB/B;;;;GAIG;AAC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C;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB;IACvC,IAAI,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;QAC7B,OAAO,KAAK,CAAA;IACd,CAAC;IACD,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC7D,CAAC","sourcesContent":["import {AbortSignal} from './abort.js'\nimport {AbortError, ExternalError} from './error.js'\nimport {cwd, dirname} from './path.js'\nimport {treeKill} from './tree-kill.js'\nimport {isTruthy} from './context/utilities.js'\nimport {renderWarning} from './ui.js'\nimport {shouldDisplayColors, outputDebug} from '../../public/node/output.js'\nimport {execa, ExecaChildProcess} from 'execa'\nimport which from 'which'\nimport {delimiter} from 'pathe'\nimport type {Writable, Readable} from 'stream'\n\nexport interface ExecOptions {\n cwd?: string\n env?: {[key: string]: string | undefined}\n stdin?: Readable | 'inherit'\n stdout?: Writable | 'inherit'\n stderr?: Writable | 'inherit'\n stdio?: 'inherit'\n input?: string\n signal?: AbortSignal\n // Custom handler if process exits with a non-zero code\n externalErrorHandler?: (error: unknown) => Promise<void>\n}\n\n/**\n * Opens a URL in the user's default browser.\n *\n * @param url - URL to open.\n */\nexport async function openURL(url: string): Promise<void> {\n const externalOpen = await import('open')\n await externalOpen.default(url)\n}\n\n/**\n * Runs a command asynchronously, aggregates the stdout data, and returns it.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise that resolves with the aggregatted stdout of the command.\n */\nexport async function captureOutput(command: string, args: string[], options?: ExecOptions): Promise<string> {\n const result = await buildExec(command, args, options)\n return result.stdout\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n */\nexport async function exec(command: string, args: string[], options?: ExecOptions): Promise<void> {\n const commandProcess = buildExec(command, args, options)\n if (options?.stderr && options.stderr !== 'inherit') {\n commandProcess.stderr?.pipe(options.stderr, {end: false})\n }\n if (options?.stdout && options.stdout !== 'inherit') {\n commandProcess.stdout?.pipe(options.stdout, {end: false})\n }\n let aborted = false\n options?.signal?.addEventListener('abort', () => {\n const pid = commandProcess.pid\n if (pid) {\n outputDebug(`Killing process ${pid}: ${command} ${args.join(' ')}`)\n aborted = true\n treeKill(pid, 'SIGTERM')\n }\n })\n try {\n await commandProcess\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (processError: any) {\n // Windows will throw an error whenever the process is killed, no matter the reason.\n // The aborted flag tell use that we killed it, so we can ignore the error.\n if (aborted) return\n if (options?.externalErrorHandler) {\n await options.externalErrorHandler(processError)\n } else {\n const abortError = new ExternalError(processError.message, command, args)\n abortError.stack = processError.stack\n throw abortError\n }\n }\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise for a result with stdout and stderr properties.\n */\nfunction buildExec(command: string, args: string[], options?: ExecOptions): ExecaChildProcess {\n const env = options?.env ?? process.env\n if (shouldDisplayColors()) {\n env.FORCE_COLOR = '1'\n }\n const executionCwd = options?.cwd ?? cwd()\n checkCommandSafety(command, {cwd: executionCwd})\n const commandProcess = execa(command, args, {\n env,\n cwd: executionCwd,\n input: options?.input,\n stdio: options?.stdio,\n stdin: options?.stdin,\n stdout: options?.stdout === 'inherit' ? 'inherit' : undefined,\n stderr: options?.stderr === 'inherit' ? 'inherit' : undefined,\n // Setting this to false makes it possible to kill the main process\n // and all its sub-processes with Ctrl+C on Windows\n windowsHide: false,\n })\n outputDebug(`\nRunning system process:\n · Command: ${command} ${args.join(' ')}\n · Working directory: ${executionCwd}\n`)\n return commandProcess\n}\n\nfunction checkCommandSafety(command: string, _options: {cwd: string}): void {\n const pathIncludingLocal = `${_options.cwd}${delimiter}${process.env.PATH}`\n const commandPath = which.sync(command, {\n nothrow: true,\n path: pathIncludingLocal,\n })\n if (commandPath && dirname(commandPath) === _options.cwd) {\n const headline = ['Skipped run of unsecure binary', {command}, 'found in the current directory.']\n const body = 'Please remove that file or review your current PATH.'\n renderWarning({headline, body})\n throw new AbortError(headline, body)\n }\n}\n\n/**\n * Waits for a given number of seconds.\n *\n * @param seconds - Number of seconds to wait.\n * @returns A Promise resolving after the number of seconds.\n */\nexport async function sleep(seconds: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, 1000 * seconds)\n })\n}\n\n/**\n * Check if the standard input and output streams support prompting.\n *\n * @returns True if the standard input and output streams support prompting.\n */\nexport function terminalSupportsPrompting(): boolean {\n if (isTruthy(process.env.CI)) {\n return false\n }\n return Boolean(process.stdin.isTTY && process.stdout.isTTY)\n}\n"]}
1
+ {"version":3,"file":"system.js","sourceRoot":"","sources":["../../../src/public/node/system.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,UAAU,EAAE,aAAa,EAAC,MAAM,YAAY,CAAA;AACpD,OAAO,EAAC,GAAG,EAAE,OAAO,EAAC,MAAM,WAAW,CAAA;AACtC,OAAO,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,aAAa,EAAC,MAAM,SAAS,CAAA;AACrC,OAAO,EAAC,eAAe,EAAC,MAAM,SAAS,CAAA;AACvC,OAAO,EAAC,mBAAmB,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AAC5E,OAAO,EAAC,KAAK,EAAoB,MAAM,OAAO,CAAA;AAC9C,OAAO,KAAK,MAAM,OAAO,CAAA;AACzB,OAAO,EAAC,SAAS,EAAC,MAAM,OAAO,CAAA;AAkB/B;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,GAAW;IACvC,MAAM,YAAY,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAA;IACzC,IAAI,CAAC;QAC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AC,WAAW,CAAC,KAAK,QAAQ,CAAC,GAAG,EAAE,CAAC;QACzD,MAAM,QAAQ,GAAG,CAAC,gCAAgC,EAAE,EAAC,OAAO,EAAC,EAAE,iCAAiC,CAAC,CAAA;QACjG,MAAM,IAAI,GAAG,sDAAsD,CAAA;QACnE,aAAa,CAAC,EAAC,QAAQ,EAAE,IAAI,EAAC,CAAC,CAAA;QAC/B,MAAM,IAAI,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;IACtC,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,KAAK,CAAC,OAAe;IACzC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,UAAU,CAAC,OAAO,EAAE,IAAI,GAAG,OAAO,CAAC,CAAA;IACrC,CAAC,CAAC,CAAA;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB;IACvC,IAAI,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;QAC7B,OAAO,KAAK,CAAA;IACd,CAAC;IACD,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC7D,CAAC","sourcesContent":["import {AbortSignal} from './abort.js'\nimport {AbortError, ExternalError} from './error.js'\nimport {cwd, dirname} from './path.js'\nimport {treeKill} from './tree-kill.js'\nimport {isTruthy} from './context/utilities.js'\nimport {renderWarning} from './ui.js'\nimport {platformAndArch} from './os.js'\nimport {shouldDisplayColors, outputDebug} from '../../public/node/output.js'\nimport {execa, ExecaChildProcess} from 'execa'\nimport which from 'which'\nimport {delimiter} from 'pathe'\nimport type {Writable, Readable} from 'stream'\n\nexport interface ExecOptions {\n cwd?: string\n env?: {[key: string]: string | undefined}\n stdin?: Readable | 'inherit'\n stdout?: Writable | 'inherit'\n stderr?: Writable | 'inherit'\n stdio?: 'inherit'\n input?: string\n signal?: AbortSignal\n // Custom handler if process exits with a non-zero code\n externalErrorHandler?: (error: unknown) => Promise<void>\n // Ignored on Windows\n background?: boolean\n}\n\n/**\n * Opens a URL in the user's default browser.\n *\n * @param url - URL to open.\n * @returns A promise that resolves true if the URL was opened successfully, false otherwise.\n */\nexport async function openURL(url: string): Promise<boolean> {\n const externalOpen = await import('open')\n try {\n await externalOpen.default(url)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n return false\n }\n}\n\n/**\n * Runs a command asynchronously, aggregates the stdout data, and returns it.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise that resolves with the aggregatted stdout of the command.\n */\nexport async function captureOutput(command: string, args: string[], options?: ExecOptions): Promise<string> {\n const result = await buildExec(command, args, options)\n return result.stdout\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n */\nexport async function exec(command: string, args: string[], options?: ExecOptions): Promise<void> {\n if (options) {\n // Windows opens a new console window when running a command in the background, so we disable it.\n const runningOnWindows = platformAndArch().platform === 'windows'\n options.background = runningOnWindows ? false : options.background\n }\n\n const commandProcess = buildExec(command, args, options)\n\n if (options?.background) {\n commandProcess.unref()\n }\n\n if (options?.stderr && options.stderr !== 'inherit') {\n commandProcess.stderr?.pipe(options.stderr, {end: false})\n }\n if (options?.stdout && options.stdout !== 'inherit') {\n commandProcess.stdout?.pipe(options.stdout, {end: false})\n }\n let aborted = false\n options?.signal?.addEventListener('abort', () => {\n const pid = commandProcess.pid\n if (pid) {\n outputDebug(`Killing process ${pid}: ${command} ${args.join(' ')}`)\n aborted = true\n treeKill(pid, 'SIGTERM')\n }\n })\n try {\n await commandProcess\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (processError: any) {\n // Windows will throw an error whenever the process is killed, no matter the reason.\n // The aborted flag tell use that we killed it, so we can ignore the error.\n if (aborted) return\n if (options?.externalErrorHandler) {\n await options.externalErrorHandler(processError)\n } else {\n const abortError = new ExternalError(processError.message, command, args)\n abortError.stack = processError.stack\n throw abortError\n }\n }\n}\n\n/**\n * Runs a command asynchronously.\n *\n * @param command - Command to be executed.\n * @param args - Arguments to pass to the command.\n * @param options - Optional settings for how to run the command.\n * @returns A promise for a result with stdout and stderr properties.\n */\nfunction buildExec(command: string, args: string[], options?: ExecOptions): ExecaChildProcess {\n const env = options?.env ?? process.env\n if (shouldDisplayColors()) {\n env.FORCE_COLOR = '1'\n }\n const executionCwd = options?.cwd ?? cwd()\n checkCommandSafety(command, {cwd: executionCwd})\n const commandProcess = execa(command, args, {\n env,\n cwd: executionCwd,\n input: options?.input,\n stdio: options?.background ? 'ignore' : options?.stdio,\n stdin: options?.stdin,\n stdout: options?.stdout === 'inherit' ? 'inherit' : undefined,\n stderr: options?.stderr === 'inherit' ? 'inherit' : undefined,\n // Setting this to false makes it possible to kill the main process\n // and all its sub-processes with Ctrl+C on Windows\n windowsHide: false,\n detached: options?.background,\n cleanup: !options?.background,\n })\n outputDebug(`\nRunning system process${options?.background ? ' in background' : ''}:\n · Command: ${command} ${args.join(' ')}\n · Working directory: ${executionCwd}\n`)\n return commandProcess\n}\n\nfunction checkCommandSafety(command: string, _options: {cwd: string}): void {\n const pathIncludingLocal = `${_options.cwd}${delimiter}${process.env.PATH}`\n const commandPath = which.sync(command, {\n nothrow: true,\n path: pathIncludingLocal,\n })\n if (commandPath && dirname(commandPath) === _options.cwd) {\n const headline = ['Skipped run of unsecure binary', {command}, 'found in the current directory.']\n const body = 'Please remove that file or review your current PATH.'\n renderWarning({headline, body})\n throw new AbortError(headline, body)\n }\n}\n\n/**\n * Waits for a given number of seconds.\n *\n * @param seconds - Number of seconds to wait.\n * @returns A Promise resolving after the number of seconds.\n */\nexport async function sleep(seconds: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, 1000 * seconds)\n })\n}\n\n/**\n * Check if the standard input and output streams support prompting.\n *\n * @returns True if the standard input and output streams support prompting.\n */\nexport function terminalSupportsPrompting(): boolean {\n if (isTruthy(process.env.CI)) {\n return false\n }\n return Boolean(process.stdin.isTTY && process.stdout.isTTY)\n}\n"]}
@@ -5,7 +5,7 @@ export type ThemeParams = Partial<Pick<Theme, 'name' | 'role' | 'processing' | '
5
5
  export type AssetParams = Pick<ThemeAsset, 'key'> & Partial<Pick<ThemeAsset, 'value' | 'attachment'>>;
6
6
  export declare function fetchTheme(id: number, session: AdminSession): Promise<Theme | undefined>;
7
7
  export declare function fetchThemes(session: AdminSession): Promise<Theme[]>;
8
- export declare function createTheme(params: ThemeParams, session: AdminSession): Promise<Theme | undefined>;
8
+ export declare function themeCreate(params: ThemeParams, session: AdminSession): Promise<Theme | undefined>;
9
9
  export declare function fetchThemeAssets(id: number, filenames: Key[], session: AdminSession): Promise<ThemeAsset[]>;
10
10
  export declare function deleteThemeAssets(id: number, filenames: Key[], session: AdminSession): Promise<Result[]>;
11
11
  export declare function bulkUploadThemeAssets(id: number, assets: AssetParams[], session: AdminSession): Promise<Result[]>;
@@ -24,3 +24,18 @@ export declare function metafieldDefinitionsByOwnerType(type: MetafieldOwnerType
24
24
  };
25
25
  }[]>;
26
26
  export declare function passwordProtected(session: AdminSession): Promise<boolean>;
27
+ type OnlineStoreThemeFileBody = {
28
+ __typename: 'OnlineStoreThemeFileBodyBase64';
29
+ contentBase64: string;
30
+ } | {
31
+ __typename: 'OnlineStoreThemeFileBodyText';
32
+ content: string;
33
+ } | {
34
+ __typename: 'OnlineStoreThemeFileBodyUrl';
35
+ url: string;
36
+ };
37
+ export declare function parseThemeFileContent(body: OnlineStoreThemeFileBody): Promise<{
38
+ value?: string;
39
+ attachment?: string;
40
+ }>;
41
+ export {};
@@ -1,9 +1,8 @@
1
- import { storeAdminUrl } from './urls.js';
2
- import { composeThemeGid, parseGid } from './utils.js';
3
- import * as throttler from '../api/rest-api-throttler.js';
1
+ import { composeThemeGid, parseGid, DEVELOPMENT_THEME_ROLE } from './utils.js';
4
2
  import { ThemeUpdate } from '../../../cli/api/graphql/admin/generated/theme_update.js';
5
3
  import { ThemeDelete } from '../../../cli/api/graphql/admin/generated/theme_delete.js';
6
4
  import { ThemePublish } from '../../../cli/api/graphql/admin/generated/theme_publish.js';
5
+ import { ThemeCreate } from '../../../cli/api/graphql/admin/generated/theme_create.js';
7
6
  import { GetThemeFileBodies } from '../../../cli/api/graphql/admin/generated/get_theme_file_bodies.js';
8
7
  import { GetThemeFileChecksums } from '../../../cli/api/graphql/admin/generated/get_theme_file_checksums.js';
9
8
  import { ThemeFilesUpsert, } from '../../../cli/api/graphql/admin/generated/theme_files_upsert.js';
@@ -12,12 +11,12 @@ import { MetafieldDefinitionsByOwnerType } from '../../../cli/api/graphql/admin/
12
11
  import { GetThemes } from '../../../cli/api/graphql/admin/generated/get_themes.js';
13
12
  import { GetTheme } from '../../../cli/api/graphql/admin/generated/get_theme.js';
14
13
  import { OnlineStorePasswordProtection } from '../../../cli/api/graphql/admin/generated/online_store_password_protection.js';
15
- import { restRequest, adminRequestDoc } from '@shopify/cli-kit/node/api/admin';
14
+ import { adminRequestDoc } from '@shopify/cli-kit/node/api/admin';
16
15
  import { AbortError } from '@shopify/cli-kit/node/error';
17
16
  import { buildTheme } from '@shopify/cli-kit/node/themes/factories';
18
17
  import { Operation } from '@shopify/cli-kit/node/themes/types';
19
18
  import { outputDebug } from '@shopify/cli-kit/node/output';
20
- import { sleep } from '@shopify/cli-kit/node/system';
19
+ const SkeletonThemeCdn = 'https://cdn.shopify.com/static/online-store/theme-skeleton.zip';
21
20
  export async function fetchTheme(id, session) {
22
21
  const gid = composeThemeGid(id);
23
22
  try {
@@ -72,17 +71,29 @@ export async function fetchThemes(session) {
72
71
  after = pageInfo.endCursor;
73
72
  }
74
73
  }
75
- export async function createTheme(params, session) {
76
- const response = await request('POST', '/themes', session, { theme: { ...params } });
77
- if (!params.src) {
78
- const minimumThemeAssets = [
79
- { key: 'config/settings_schema.json', value: '[]' },
80
- { key: 'layout/password.liquid', value: '{{ content_for_header }}{{ content_for_layout }}' },
81
- { key: 'layout/theme.liquid', value: '{{ content_for_header }}{{ content_for_layout }}' },
82
- ];
83
- await bulkUploadThemeAssets(response.json.theme.id, minimumThemeAssets, session);
74
+ export async function themeCreate(params, session) {
75
+ const themeSource = params.src ?? SkeletonThemeCdn;
76
+ const { themeCreate } = await adminRequestDoc(ThemeCreate, session, {
77
+ name: params.name ?? '',
78
+ source: themeSource,
79
+ role: (params.role ?? DEVELOPMENT_THEME_ROLE).toUpperCase(),
80
+ }, '2025-04');
81
+ if (!themeCreate) {
82
+ unexpectedGraphQLError('Failed to create theme');
84
83
  }
85
- return buildTheme({ ...response.json.theme, createdAtRuntime: true });
84
+ const { theme, userErrors } = themeCreate;
85
+ if (userErrors.length) {
86
+ const userErrors = themeCreate.userErrors.map((error) => error.message).join(', ');
87
+ throw new AbortError(userErrors);
88
+ }
89
+ if (!theme) {
90
+ unexpectedGraphQLError('Failed to create theme');
91
+ }
92
+ return buildTheme({
93
+ id: parseGid(theme.id),
94
+ name: theme.name,
95
+ role: theme.role.toLowerCase(),
96
+ });
86
97
  }
87
98
  export async function fetchThemeAssets(id, filenames, session) {
88
99
  const assets = [];
@@ -102,11 +113,12 @@ export async function fetchThemeAssets(id, filenames, session) {
102
113
  assets.push(
103
114
  // eslint-disable-next-line no-await-in-loop
104
115
  ...(await Promise.all(nodes.map(async (file) => {
105
- const content = await parseThemeFileContent(file.body);
116
+ const { attachment, value } = await parseThemeFileContent(file.body);
106
117
  return {
118
+ attachment,
107
119
  key: file.filename,
108
120
  checksum: file.checksumMd5,
109
- value: content,
121
+ value,
110
122
  };
111
123
  }))));
112
124
  if (!pageInfo.hasNextPage) {
@@ -323,115 +335,23 @@ export async function passwordProtected(session) {
323
335
  const { passwordProtection } = onlineStore;
324
336
  return passwordProtection.enabled;
325
337
  }
326
- async function request(method, path, session, params, searchParams = {}, retries = 1) {
327
- const response = await throttler.throttle(() => restRequest(method, path, session, params, searchParams));
328
- const status = response.status;
329
- throttler.updateApiCallLimitFromResponse(response);
330
- switch (true) {
331
- case status >= 200 && status <= 399:
332
- // Returns the successful reponse
333
- return response;
334
- case status === 404:
335
- // Defer the decision when a resource is not found
336
- return response;
337
- case status === 429:
338
- // Retry following the "retry-after" header
339
- return throttler.delayAwareRetry(response, () => request(method, path, session, params, searchParams));
340
- case status === 403:
341
- return handleForbiddenError(response, session);
342
- case status === 401:
343
- /**
344
- * We need to resolve the call to the refresh function at runtime to
345
- * avoid a circular reference.
346
- *
347
- * This won't be necessary when https://github.com/Shopify/cli/issues/4769
348
- * gets resolved, and this condition must be removed then.
349
- */
350
- if ('refresh' in session) {
351
- const refresh = session.refresh;
352
- await refresh();
353
- }
354
- // Retry 401 errors to be resilient to authentication errors.
355
- return handleRetriableError({
356
- path,
357
- retries,
358
- retry: () => {
359
- return request(method, path, session, params, searchParams, retries + 1);
360
- },
361
- fail: () => {
362
- throw new AbortError(`[${status}] API request unauthorized error`);
363
- },
364
- });
365
- case status === 422:
366
- throw new AbortError(`[${status}] API request unprocessable content: ${errors(response)}`);
367
- case status >= 400 && status <= 499:
368
- throw new AbortError(`[${status}] API request client error`);
369
- case status >= 500 && status <= 599:
370
- // Retry 500-family of errors as that may solve the issue (especially in 503 errors)
371
- return handleRetriableError({
372
- path,
373
- retries,
374
- retry: () => {
375
- return request(method, path, session, params, searchParams, retries + 1);
376
- },
377
- fail: () => {
378
- throw new AbortError(`[${status}] API request server error`);
379
- },
380
- });
381
- default:
382
- throw new AbortError(`[${status}] API request unexpected error`);
383
- }
384
- }
385
- function handleForbiddenError(response, session) {
386
- const store = session.storeFqdn;
387
- const adminUrl = storeAdminUrl(session);
388
- const error = errorMessage(response);
389
- if (error.match(/Cannot delete generated asset/) !== null) {
390
- throw new AbortError(error);
391
- }
392
- throw new AbortError(`You are not authorized to edit themes on "${store}".`, "You can't use Shopify CLI with development stores if you only have Partner staff " +
393
- 'member access. If you want to use Shopify CLI to work on a development store, then ' +
394
- 'you should be the store owner or create a staff account on the store.' +
395
- '\n\n' +
396
- "If you're the store owner, then you need to log in to the store directly using the " +
397
- `store URL at least once (for example, using "${adminUrl}") before you log in using ` +
398
- 'Shopify CLI. Logging in to the Shopify admin directly connects the development ' +
399
- 'store with your Shopify login.');
400
- }
401
- function errors(response) {
402
- return JSON.stringify(response.json?.errors);
403
- }
404
- function errorMessage(response) {
405
- const message = response.json?.message;
406
- if (typeof message === 'string') {
407
- return message;
408
- }
409
- return '';
410
- }
411
338
  function unexpectedGraphQLError(message) {
412
339
  throw new AbortError(message);
413
340
  }
414
- async function handleRetriableError({ path, retries, retry, fail }) {
415
- if (retries >= 3) {
416
- fail();
417
- }
418
- outputDebug(`[${retries}] Retrying '${path}' request...`);
419
- await sleep(0.2);
420
- return retry();
421
- }
422
341
  function themeGid(id) {
423
342
  return `gid://shopify/OnlineStoreTheme/${id}`;
424
343
  }
425
- async function parseThemeFileContent(body) {
344
+ export async function parseThemeFileContent(body) {
426
345
  switch (body.__typename) {
427
346
  case 'OnlineStoreThemeFileBodyText':
428
- return body.content;
347
+ return { value: body.content };
429
348
  case 'OnlineStoreThemeFileBodyBase64':
430
- return Buffer.from(body.contentBase64, 'base64').toString();
349
+ return { attachment: body.contentBase64 };
431
350
  case 'OnlineStoreThemeFileBodyUrl':
432
351
  try {
433
352
  const response = await fetch(body.url);
434
- return await response.text();
353
+ const arrayBuffer = await response.arrayBuffer();
354
+ return { attachment: Buffer.from(arrayBuffer).toString('base64') };
435
355
  }
436
356
  catch (error) {
437
357
  // Raise error if we can't download the file