@shopify/cli-kit 3.59.3 → 3.60.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.
@@ -16,7 +16,7 @@ module Extension
16
16
  SUPPORTED_BUCKETS = %w(assets blocks snippets locales)
17
17
  BUNDLE_SIZE_LIMIT = 10 * 1024 * 1024 # 10MB
18
18
  LIQUID_SIZE_LIMIT = 100 * 1024 # 100kb
19
- SUPPORTED_ASSET_EXTS = %w(.jpg .jpeg .js .css .png .svg)
19
+ SUPPORTED_ASSET_EXTS = %w(.jpg .jpeg .js .json .css .png .svg)
20
20
  SUPPORTED_LOCALE_EXTS = %w(.json)
21
21
 
22
22
  def create(directory_name, context, getting_started: false)
@@ -200,7 +200,7 @@ module ShopifyCLI
200
200
  +""
201
201
  end
202
202
 
203
- expected_session_cookie = "#{SESSION_COOKIE_NAME}=#{secure_session_id}"
203
+ expected_session_cookie = "#{SESSION_COOKIE_NAME}=#{secure_session_id};"
204
204
 
205
205
  unless cookie_header.include?(expected_session_cookie)
206
206
  if cookie_header.include?(SESSION_COOKIE_NAME)
@@ -43,24 +43,7 @@ module ShopifyCLI
43
43
 
44
44
  job_in_progress!
45
45
 
46
- input = {
47
- api_key: @project.app.api_key,
48
- registration_id: @project.registration_id,
49
- config: JSON.generate(@specification_handler.config(@ctx)),
50
- extension_context: @specification_handler.extension_context(@ctx),
51
- }
52
- response = ShopifyCLI::PartnersAPI.query(@ctx, "extension_update_draft", **input).dig(*RESPONSE_FIELD)
53
- user_errors = response.dig(USER_ERRORS_FIELD)
54
-
55
- if user_errors
56
- @ctx.puts(error_message(@project.title))
57
- error_files = erroneous_files(user_errors)
58
- print_items(error_files)
59
- else
60
- @ctx.puts(success_message(@project.title))
61
- print_items({}.freeze)
62
- ::Extension::Tasks::Converters::VersionConverter.from_hash(@ctx, response.dig(VERSION_FIELD))
63
- end
46
+ print_items({}.freeze)
64
47
 
65
48
  files = @syncer.pending_files.map(&:relative_path)
66
49
  # Notify changes after the sync is complete
@@ -17,7 +17,7 @@ module ShopifyCLI
17
17
  @env = env
18
18
  @env["PATH_INFO"] = PASSWORD_PAGE_PATH if redirect_to_password?(@env)
19
19
 
20
- return @app.call(@env) if password_page?(@env) || (storefront_session.nil? || secure_session.nil?)
20
+ return @app.call(@env) if password_page?(@env) || secure_session.nil?
21
21
 
22
22
  authenticate!
23
23
 
@@ -16,6 +16,7 @@ import { keypress } from '../../public/node/ui.js';
16
16
  import { getIdentityTokenInformation, getPartnersToken } from '../../public/node/environment.js';
17
17
  import { gql } from 'graphql-request';
18
18
  import { outputCompleted, outputInfo, outputWarn } from '@shopify/cli-kit/node/output';
19
+ import { isTruthy } from '@shopify/cli-kit/node/context/utilities';
19
20
  /**
20
21
  * This method ensures that we have a valid session to authenticate against the given applications using the provided scopes.
21
22
  *
@@ -144,6 +145,8 @@ async function executeCompleteFlow(applications, identityFqdn) {
144
145
  * @param partnersToken - Partners token.
145
146
  */
146
147
  async function ensureUserHasPartnerAccount(partnersToken) {
148
+ if (isTruthy(process.env.USE_SHOPIFY_DEVELOPERS_CLIENT))
149
+ return;
147
150
  outputDebug(outputContent `Verifying that the user has a Partner organization`);
148
151
  if (!(await hasPartnerAccount(partnersToken))) {
149
152
  outputInfo(`\nA Shopify Partners organization is needed to proceed.`);
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/private/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAA;AACrD,OAAO,EAAC,gBAAgB,EAAE,SAAS,EAAC,MAAM,qBAAqB,CAAA;AAC/D,OAAO,EACL,kCAAkC,EAClC,0BAA0B,EAC1B,0BAA0B,EAE1B,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAC,SAAS,EAAC,MAAM,wBAAwB,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AAqB,EAAE,gBAAgB,CAAC;QAC9D,gBAAgB,EAAE,SAAS,CAAC,mBAAmB,EAAE,sBAAsB,CAAC;KACzE,CAAA;AACH,CAAC;AAED,SAAS,yBAAyB,CAChC,MAAgB,EAChB,wBAAqE;IAErE,OAAO;QACL,GAAG,wBAAwB;QAC3B,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QAC1D,MAAM;KACP,CAAA;AACH,CAAC","sourcesContent":["import {applicationId} from './session/identity.js'\nimport {validateSession} from './session/validate.js'\nimport {allDefaultScopes, apiScopes} from './session/scopes.js'\nimport {\n exchangeAccessForApplicationTokens,\n exchangeCodeForAccessToken,\n exchangeCustomPartnerToken,\n ExchangeScopes,\n refreshAccessToken,\n InvalidGrantError,\n InvalidRequestError,\n} from './session/exchange.js'\nimport {authorize} from './session/authorize.js'\nimport {IdentityToken, Session} from './session/schema.js'\nimport * as secureStore from './session/store.js'\nimport {pollForDeviceAuthorization, requestDeviceAuthorization} from './session/device-authorization.js'\nimport {RequestClientError} from './api/headers.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {firstPartyDev, useDeviceAuth} from '../../public/node/context/local.js'\nimport {AbortError, BugError} from '../../public/node/error.js'\nimport {partnersRequest} from '../../public/node/api/partners.js'\nimport {normalizeStoreFqdn, partnersFqdn, identityFqdn} from '../../public/node/context/fqdn.js'\nimport {openURL} from '../../public/node/system.js'\nimport {keypress} from '../../public/node/ui.js'\nimport {getIdentityTokenInformation, getPartnersToken} from '../../public/node/environment.js'\nimport {gql} from 'graphql-request'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {outputCompleted, outputInfo, outputWarn} from '@shopify/cli-kit/node/output'\n\n/**\n * A scope supported by the Shopify Admin API.\n */\ntype AdminAPIScope = 'graphql' | 'themes' | 'collaborator' | string\n\n/**\n * It represents the options to authenticate against the Shopify Admin API.\n */\n\ninterface AdminAPIOAuthOptions {\n /** Store to request permissions for. */\n storeFqdn: string\n /** List of scopes to request permissions for. */\n scopes: AdminAPIScope[]\n}\n\n/**\n * A scope supported by the Partners API.\n */\ntype PartnersAPIScope = 'cli' | string\ninterface PartnersAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: PartnersAPIScope[]\n}\n\n/**\n * A scope supported by the Storefront Renderer API.\n */\ntype StorefrontRendererScope = 'devtools' | string\ninterface StorefrontRendererAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: StorefrontRendererScope[]\n}\n\ntype BusinessPlatformScope = 'destinations' | string\ninterface BusinessPlatformAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: BusinessPlatformScope[]\n}\n\n/**\n * It represents the authentication requirements and\n * is the input necessary to trigger the authentication\n * flow.\n */\nexport interface OAuthApplications {\n adminApi?: AdminAPIOAuthOptions\n storefrontRendererApi?: StorefrontRendererAPIOAuthOptions\n partnersApi?: PartnersAPIOAuthOptions\n businessPlatformApi?: BusinessPlatformAPIOAuthOptions\n}\n\nexport interface OAuthSession {\n admin?: AdminSession\n partners?: string\n storefront?: string\n businessPlatform?: string\n}\n\n/**\n * This method ensures that we have a valid session to authenticate against the given applications using the provided scopes.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param _env - Optional environment variables to use.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns An instance with the access tokens organized by application.\n */\nexport async function ensureAuthenticated(\n applications: OAuthApplications,\n _env?: NodeJS.ProcessEnv,\n {forceRefresh = false, noPrompt = false}: {forceRefresh?: boolean; noPrompt?: boolean} = {},\n): Promise<OAuthSession> {\n const fqdn = await identityFqdn()\n\n const previousStoreFqdn = applications.adminApi?.storeFqdn\n if (previousStoreFqdn) {\n const normalizedStoreName = await normalizeStoreFqdn(previousStoreFqdn)\n if (previousStoreFqdn === applications.adminApi?.storeFqdn) {\n applications.adminApi.storeFqdn = normalizedStoreName\n }\n }\n\n const currentSession = (await secureStore.fetch()) || {}\n const fqdnSession = currentSession[fqdn]!\n const scopes = getFlattenScopes(applications)\n\n outputDebug(outputContent`Validating existing session against the scopes:\n${outputToken.json(scopes)}\nFor applications:\n${outputToken.json(applications)}\n`)\n const validationResult = await validateSession(scopes, applications, fqdnSession)\n\n let newSession = {}\n\n function throwOnNoPrompt() {\n if (!noPrompt) return\n throw new AbortError(\n `The currently available CLI credentials are invalid.\n\nThe CLI is currently unable to prompt for reauthentication.`,\n '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.',\n )\n }\n\n if (validationResult === 'needs_full_auth') {\n throwOnNoPrompt()\n outputDebug(outputContent`Initiating the full authentication flow...`)\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (validationResult === 'needs_refresh' || forceRefresh) {\n outputDebug(outputContent`The current session is valid but needs refresh. Refreshing...`)\n try {\n newSession = await refreshTokens(fqdnSession.identity, applications, fqdn)\n } catch (error) {\n if (error instanceof InvalidGrantError) {\n throwOnNoPrompt()\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (error instanceof InvalidRequestError) {\n await secureStore.remove()\n throw new AbortError('\\nError validating auth session', \"We've cleared the current session, please try again\")\n } else {\n throw error\n }\n }\n }\n\n const completeSession: Session = {...currentSession, ...newSession}\n // Save the new session info if it has changed\n if (Object.keys(newSession).length > 0) await secureStore.store(completeSession)\n const tokens = await tokensFor(applications, completeSession, fqdn)\n\n // Overwrite partners token if using a custom CLI Token\n const envToken = getPartnersToken()\n if (envToken && applications.partnersApi) {\n tokens.partners = (await exchangeCustomPartnerToken(envToken)).accessToken\n }\n if (!envToken && tokens.partners) {\n await ensureUserHasPartnerAccount(tokens.partners)\n }\n\n return tokens\n}\n\n/**\n * Execute the full authentication flow.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param identityFqdn - The identity FQDN.\n */\nasync function executeCompleteFlow(applications: OAuthApplications, identityFqdn: string): Promise<Session> {\n const scopes = getFlattenScopes(applications)\n const exchangeScopes = getExchangeScopes(applications)\n const store = applications.adminApi?.storeFqdn\n if (firstPartyDev()) {\n outputDebug(outputContent`Authenticating as Shopify Employee...`)\n scopes.push('employee')\n }\n\n let identityToken: IdentityToken\n const identityTokenInformation = getIdentityTokenInformation()\n if (identityTokenInformation) {\n identityToken = buildIdentityTokenFromEnv(scopes, identityTokenInformation)\n } else if (useDeviceAuth()) {\n // Request a device code to authorize without a browser redirect.\n outputDebug(outputContent`Requesting device authorization code...`)\n const deviceAuth = await requestDeviceAuthorization(scopes)\n\n // Poll for the identity token\n outputDebug(outputContent`Starting polling for the identity token...`)\n identityToken = await pollForDeviceAuthorization(deviceAuth.deviceCode, deviceAuth.interval)\n } else {\n // Authorize user via browser\n outputDebug(outputContent`Authorizing through Identity's website...`)\n const code = await authorize(scopes)\n\n // Exchange code for identity token\n outputDebug(outputContent`Authorization code received. Exchanging it for a CLI token...`)\n identityToken = await exchangeCodeForAccessToken(code)\n }\n\n // Exchange identity token for application tokens\n outputDebug(outputContent`CLI token received. Exchanging it for application tokens...`)\n const result = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, store)\n\n const session: Session = {\n [identityFqdn]: {\n identity: identityToken,\n applications: result,\n },\n }\n\n outputCompleted('Logged in.')\n\n return session\n}\n\n/**\n * If the user creates an account from the Identity website, the created\n * account won't get a Partner organization created. We need to detect that\n * and take the user to create a partner organization.\n *\n * @param partnersToken - Partners token.\n */\nasync function ensureUserHasPartnerAccount(partnersToken: string) {\n outputDebug(outputContent`Verifying that the user has a Partner organization`)\n if (!(await hasPartnerAccount(partnersToken))) {\n outputInfo(`\\nA Shopify Partners organization is needed to proceed.`)\n outputInfo(`👉 Press any key to create one`)\n await keypress()\n await openURL(`https://${await partnersFqdn()}/signup`)\n outputInfo(outputContent`👉 Press any key when you have ${outputToken.cyan('created the organization')}`)\n outputWarn(outputContent`Make sure you've confirmed your Shopify and the Partner organization from the email`)\n await keypress()\n if (!(await hasPartnerAccount(partnersToken))) {\n throw new AbortError(\n `Couldn't find your Shopify Partners organization`,\n `Have you confirmed your accounts from the emails you received?`,\n )\n }\n }\n}\n\nconst getFirstOrganization = gql`\n {\n organizations(first: 1) {\n nodes {\n id\n }\n }\n }\n`\n\n/**\n * Validate if the current token is valid for partners API.\n *\n * @param partnersToken - Partners token.\n * @returns A promise that resolves to true if the token is valid for partners API.\n */\nasync function hasPartnerAccount(partnersToken: string): Promise<boolean> {\n try {\n await partnersRequest(getFirstOrganization, partnersToken)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n if (error instanceof RequestClientError && error.statusCode === 404) {\n return false\n } else {\n return true\n }\n }\n}\n\n/**\n * Refresh the tokens for a given session.\n *\n * @param token - Identity token.\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param fqdn - The identity FQDN.\n */\nasync function refreshTokens(token: IdentityToken, applications: OAuthApplications, fqdn: string): Promise<Session> {\n // Refresh Identity Token\n const identityToken = await refreshAccessToken(token)\n // Exchange new identity token for application tokens\n const exchangeScopes = getExchangeScopes(applications)\n const applicationTokens = await exchangeAccessForApplicationTokens(\n identityToken,\n exchangeScopes,\n applications.adminApi?.storeFqdn,\n )\n\n return {\n [fqdn]: {\n identity: identityToken,\n applications: applicationTokens,\n },\n }\n}\n\n/**\n * Get the application tokens for a given session.\n *\n * @param applications - An object containing the applications we need the tokens for.\n * @param session - The current session.\n * @param fqdn - The identity FQDN.\n */\nasync function tokensFor(applications: OAuthApplications, session: Session, fqdn: string): Promise<OAuthSession> {\n const fqdnSession = session[fqdn]\n if (!fqdnSession) {\n throw new BugError('No session found after ensuring authenticated')\n }\n const tokens: OAuthSession = {}\n if (applications.adminApi) {\n const appId = applicationId('admin')\n const realAppId = `${applications.adminApi.storeFqdn}-${appId}`\n const token = fqdnSession.applications[realAppId]?.accessToken\n if (token) {\n tokens.admin = {token, storeFqdn: applications.adminApi.storeFqdn}\n }\n }\n\n if (applications.partnersApi) {\n const appId = applicationId('partners')\n tokens.partners = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.storefrontRendererApi) {\n const appId = applicationId('storefront-renderer')\n tokens.storefront = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.businessPlatformApi) {\n const appId = applicationId('business-platform')\n tokens.businessPlatform = fqdnSession.applications[appId]?.accessToken\n }\n\n return tokens\n}\n\n// Scope Helpers\n/**\n * Get a flattened array of scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns A flattened array of scopes.\n */\nfunction getFlattenScopes(apps: OAuthApplications): string[] {\n const admin = apps.adminApi?.scopes || []\n const partner = apps.partnersApi?.scopes || []\n const storefront = apps.storefrontRendererApi?.scopes || []\n const businessPlatform = apps.businessPlatformApi?.scopes || []\n const requestedScopes = [...admin, ...partner, ...storefront, ...businessPlatform]\n return allDefaultScopes(requestedScopes)\n}\n\n/**\n * Get the scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns An object containing the scopes for each application.\n */\nfunction getExchangeScopes(apps: OAuthApplications): ExchangeScopes {\n const adminScope = apps.adminApi?.scopes || []\n const partnerScope = apps.partnersApi?.scopes || []\n const storefrontScopes = apps.storefrontRendererApi?.scopes || []\n const businessPlatformScopes = apps.businessPlatformApi?.scopes || []\n return {\n admin: apiScopes('admin', adminScope),\n partners: apiScopes('partners', partnerScope),\n storefront: apiScopes('storefront-renderer', storefrontScopes),\n businessPlatform: apiScopes('business-platform', businessPlatformScopes),\n }\n}\n\nfunction buildIdentityTokenFromEnv(\n scopes: string[],\n identityTokenInformation: {accessToken: string; refreshToken: string},\n) {\n return {\n ...identityTokenInformation,\n expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),\n scopes,\n }\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/private/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAC,eAAe,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EAAE,CAAA;IAC9C,MAAM,YAAY,GAAG,IAAI,CAAC,WAAW,EAAE,MAAM,IAAI,EAAE,CAAA;IACnD,MAAM,gBAAgB,GAAG,IAAI,CAAC,qBAAqB,EAAE,MAAM,IAAI,EAAE,CAAA;IACjE,MAAM,sBAAsB,GAAG,IAAI,CAAC,mBAAmB,EAAE,MAAM,IAAI,EAAE,CAAA;IACrE,OAAO;QACL,KAAK,EAAE,SAAS,CAAC,OAAO,EAAE,UAAU,CAAC;QACrC,QAAQ,EAAE,SAAS,CAAC,UAAU,EAAE,YAAY,CAAC;QAC7C,UAAU,EAAE,SAAS,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;QAC9D,gBAAgB,EAAE,SAAS,CAAC,mBAAmB,EAAE,sBAAsB,CAAC;KACzE,CAAA;AACH,CAAC;AAED,SAAS,yBAAyB,CAChC,MAAgB,EAChB,wBAAqE;IAErE,OAAO;QACL,GAAG,wBAAwB;QAC3B,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QAC1D,MAAM;KACP,CAAA;AACH,CAAC","sourcesContent":["import {applicationId} from './session/identity.js'\nimport {validateSession} from './session/validate.js'\nimport {allDefaultScopes, apiScopes} from './session/scopes.js'\nimport {\n exchangeAccessForApplicationTokens,\n exchangeCodeForAccessToken,\n exchangeCustomPartnerToken,\n ExchangeScopes,\n refreshAccessToken,\n InvalidGrantError,\n InvalidRequestError,\n} from './session/exchange.js'\nimport {authorize} from './session/authorize.js'\nimport {IdentityToken, Session} from './session/schema.js'\nimport * as secureStore from './session/store.js'\nimport {pollForDeviceAuthorization, requestDeviceAuthorization} from './session/device-authorization.js'\nimport {RequestClientError} from './api/headers.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {firstPartyDev, useDeviceAuth} from '../../public/node/context/local.js'\nimport {AbortError, BugError} from '../../public/node/error.js'\nimport {partnersRequest} from '../../public/node/api/partners.js'\nimport {normalizeStoreFqdn, partnersFqdn, identityFqdn} from '../../public/node/context/fqdn.js'\nimport {openURL} from '../../public/node/system.js'\nimport {keypress} from '../../public/node/ui.js'\nimport {getIdentityTokenInformation, getPartnersToken} from '../../public/node/environment.js'\nimport {gql} from 'graphql-request'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {outputCompleted, outputInfo, outputWarn} from '@shopify/cli-kit/node/output'\nimport {isTruthy} from '@shopify/cli-kit/node/context/utilities'\n\n/**\n * A scope supported by the Shopify Admin API.\n */\ntype AdminAPIScope = 'graphql' | 'themes' | 'collaborator' | string\n\n/**\n * It represents the options to authenticate against the Shopify Admin API.\n */\n\ninterface AdminAPIOAuthOptions {\n /** Store to request permissions for. */\n storeFqdn: string\n /** List of scopes to request permissions for. */\n scopes: AdminAPIScope[]\n}\n\n/**\n * A scope supported by the Partners API.\n */\ntype PartnersAPIScope = 'cli' | string\ninterface PartnersAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: PartnersAPIScope[]\n}\n\n/**\n * A scope supported by the Storefront Renderer API.\n */\ntype StorefrontRendererScope = 'devtools' | string\ninterface StorefrontRendererAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: StorefrontRendererScope[]\n}\n\ntype BusinessPlatformScope = 'destinations' | string\ninterface BusinessPlatformAPIOAuthOptions {\n /** List of scopes to request permissions for. */\n scopes: BusinessPlatformScope[]\n}\n\n/**\n * It represents the authentication requirements and\n * is the input necessary to trigger the authentication\n * flow.\n */\nexport interface OAuthApplications {\n adminApi?: AdminAPIOAuthOptions\n storefrontRendererApi?: StorefrontRendererAPIOAuthOptions\n partnersApi?: PartnersAPIOAuthOptions\n businessPlatformApi?: BusinessPlatformAPIOAuthOptions\n}\n\nexport interface OAuthSession {\n admin?: AdminSession\n partners?: string\n storefront?: string\n businessPlatform?: string\n}\n\n/**\n * This method ensures that we have a valid session to authenticate against the given applications using the provided scopes.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param _env - Optional environment variables to use.\n * @param forceRefresh - Optional flag to force a refresh of the token.\n * @returns An instance with the access tokens organized by application.\n */\nexport async function ensureAuthenticated(\n applications: OAuthApplications,\n _env?: NodeJS.ProcessEnv,\n {forceRefresh = false, noPrompt = false}: {forceRefresh?: boolean; noPrompt?: boolean} = {},\n): Promise<OAuthSession> {\n const fqdn = await identityFqdn()\n\n const previousStoreFqdn = applications.adminApi?.storeFqdn\n if (previousStoreFqdn) {\n const normalizedStoreName = await normalizeStoreFqdn(previousStoreFqdn)\n if (previousStoreFqdn === applications.adminApi?.storeFqdn) {\n applications.adminApi.storeFqdn = normalizedStoreName\n }\n }\n\n const currentSession = (await secureStore.fetch()) || {}\n const fqdnSession = currentSession[fqdn]!\n const scopes = getFlattenScopes(applications)\n\n outputDebug(outputContent`Validating existing session against the scopes:\n${outputToken.json(scopes)}\nFor applications:\n${outputToken.json(applications)}\n`)\n const validationResult = await validateSession(scopes, applications, fqdnSession)\n\n let newSession = {}\n\n function throwOnNoPrompt() {\n if (!noPrompt) return\n throw new AbortError(\n `The currently available CLI credentials are invalid.\n\nThe CLI is currently unable to prompt for reauthentication.`,\n '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.',\n )\n }\n\n if (validationResult === 'needs_full_auth') {\n throwOnNoPrompt()\n outputDebug(outputContent`Initiating the full authentication flow...`)\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (validationResult === 'needs_refresh' || forceRefresh) {\n outputDebug(outputContent`The current session is valid but needs refresh. Refreshing...`)\n try {\n newSession = await refreshTokens(fqdnSession.identity, applications, fqdn)\n } catch (error) {\n if (error instanceof InvalidGrantError) {\n throwOnNoPrompt()\n newSession = await executeCompleteFlow(applications, fqdn)\n } else if (error instanceof InvalidRequestError) {\n await secureStore.remove()\n throw new AbortError('\\nError validating auth session', \"We've cleared the current session, please try again\")\n } else {\n throw error\n }\n }\n }\n\n const completeSession: Session = {...currentSession, ...newSession}\n // Save the new session info if it has changed\n if (Object.keys(newSession).length > 0) await secureStore.store(completeSession)\n const tokens = await tokensFor(applications, completeSession, fqdn)\n\n // Overwrite partners token if using a custom CLI Token\n const envToken = getPartnersToken()\n if (envToken && applications.partnersApi) {\n tokens.partners = (await exchangeCustomPartnerToken(envToken)).accessToken\n }\n if (!envToken && tokens.partners) {\n await ensureUserHasPartnerAccount(tokens.partners)\n }\n\n return tokens\n}\n\n/**\n * Execute the full authentication flow.\n *\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param identityFqdn - The identity FQDN.\n */\nasync function executeCompleteFlow(applications: OAuthApplications, identityFqdn: string): Promise<Session> {\n const scopes = getFlattenScopes(applications)\n const exchangeScopes = getExchangeScopes(applications)\n const store = applications.adminApi?.storeFqdn\n if (firstPartyDev()) {\n outputDebug(outputContent`Authenticating as Shopify Employee...`)\n scopes.push('employee')\n }\n\n let identityToken: IdentityToken\n const identityTokenInformation = getIdentityTokenInformation()\n if (identityTokenInformation) {\n identityToken = buildIdentityTokenFromEnv(scopes, identityTokenInformation)\n } else if (useDeviceAuth()) {\n // Request a device code to authorize without a browser redirect.\n outputDebug(outputContent`Requesting device authorization code...`)\n const deviceAuth = await requestDeviceAuthorization(scopes)\n\n // Poll for the identity token\n outputDebug(outputContent`Starting polling for the identity token...`)\n identityToken = await pollForDeviceAuthorization(deviceAuth.deviceCode, deviceAuth.interval)\n } else {\n // Authorize user via browser\n outputDebug(outputContent`Authorizing through Identity's website...`)\n const code = await authorize(scopes)\n\n // Exchange code for identity token\n outputDebug(outputContent`Authorization code received. Exchanging it for a CLI token...`)\n identityToken = await exchangeCodeForAccessToken(code)\n }\n\n // Exchange identity token for application tokens\n outputDebug(outputContent`CLI token received. Exchanging it for application tokens...`)\n const result = await exchangeAccessForApplicationTokens(identityToken, exchangeScopes, store)\n\n const session: Session = {\n [identityFqdn]: {\n identity: identityToken,\n applications: result,\n },\n }\n\n outputCompleted('Logged in.')\n\n return session\n}\n\n/**\n * If the user creates an account from the Identity website, the created\n * account won't get a Partner organization created. We need to detect that\n * and take the user to create a partner organization.\n *\n * @param partnersToken - Partners token.\n */\nasync function ensureUserHasPartnerAccount(partnersToken: string) {\n if (isTruthy(process.env.USE_SHOPIFY_DEVELOPERS_CLIENT)) return\n\n outputDebug(outputContent`Verifying that the user has a Partner organization`)\n if (!(await hasPartnerAccount(partnersToken))) {\n outputInfo(`\\nA Shopify Partners organization is needed to proceed.`)\n outputInfo(`👉 Press any key to create one`)\n await keypress()\n await openURL(`https://${await partnersFqdn()}/signup`)\n outputInfo(outputContent`👉 Press any key when you have ${outputToken.cyan('created the organization')}`)\n outputWarn(outputContent`Make sure you've confirmed your Shopify and the Partner organization from the email`)\n await keypress()\n if (!(await hasPartnerAccount(partnersToken))) {\n throw new AbortError(\n `Couldn't find your Shopify Partners organization`,\n `Have you confirmed your accounts from the emails you received?`,\n )\n }\n }\n}\n\nconst getFirstOrganization = gql`\n {\n organizations(first: 1) {\n nodes {\n id\n }\n }\n }\n`\n\n/**\n * Validate if the current token is valid for partners API.\n *\n * @param partnersToken - Partners token.\n * @returns A promise that resolves to true if the token is valid for partners API.\n */\nasync function hasPartnerAccount(partnersToken: string): Promise<boolean> {\n try {\n await partnersRequest(getFirstOrganization, partnersToken)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n if (error instanceof RequestClientError && error.statusCode === 404) {\n return false\n } else {\n return true\n }\n }\n}\n\n/**\n * Refresh the tokens for a given session.\n *\n * @param token - Identity token.\n * @param applications - An object containing the applications we need to be authenticated with.\n * @param fqdn - The identity FQDN.\n */\nasync function refreshTokens(token: IdentityToken, applications: OAuthApplications, fqdn: string): Promise<Session> {\n // Refresh Identity Token\n const identityToken = await refreshAccessToken(token)\n // Exchange new identity token for application tokens\n const exchangeScopes = getExchangeScopes(applications)\n const applicationTokens = await exchangeAccessForApplicationTokens(\n identityToken,\n exchangeScopes,\n applications.adminApi?.storeFqdn,\n )\n\n return {\n [fqdn]: {\n identity: identityToken,\n applications: applicationTokens,\n },\n }\n}\n\n/**\n * Get the application tokens for a given session.\n *\n * @param applications - An object containing the applications we need the tokens for.\n * @param session - The current session.\n * @param fqdn - The identity FQDN.\n */\nasync function tokensFor(applications: OAuthApplications, session: Session, fqdn: string): Promise<OAuthSession> {\n const fqdnSession = session[fqdn]\n if (!fqdnSession) {\n throw new BugError('No session found after ensuring authenticated')\n }\n const tokens: OAuthSession = {}\n if (applications.adminApi) {\n const appId = applicationId('admin')\n const realAppId = `${applications.adminApi.storeFqdn}-${appId}`\n const token = fqdnSession.applications[realAppId]?.accessToken\n if (token) {\n tokens.admin = {token, storeFqdn: applications.adminApi.storeFqdn}\n }\n }\n\n if (applications.partnersApi) {\n const appId = applicationId('partners')\n tokens.partners = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.storefrontRendererApi) {\n const appId = applicationId('storefront-renderer')\n tokens.storefront = fqdnSession.applications[appId]?.accessToken\n }\n\n if (applications.businessPlatformApi) {\n const appId = applicationId('business-platform')\n tokens.businessPlatform = fqdnSession.applications[appId]?.accessToken\n }\n\n return tokens\n}\n\n// Scope Helpers\n/**\n * Get a flattened array of scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns A flattened array of scopes.\n */\nfunction getFlattenScopes(apps: OAuthApplications): string[] {\n const admin = apps.adminApi?.scopes || []\n const partner = apps.partnersApi?.scopes || []\n const storefront = apps.storefrontRendererApi?.scopes || []\n const businessPlatform = apps.businessPlatformApi?.scopes || []\n const requestedScopes = [...admin, ...partner, ...storefront, ...businessPlatform]\n return allDefaultScopes(requestedScopes)\n}\n\n/**\n * Get the scopes for the given applications.\n *\n * @param apps - An object containing the applications we need the scopes for.\n * @returns An object containing the scopes for each application.\n */\nfunction getExchangeScopes(apps: OAuthApplications): ExchangeScopes {\n const adminScope = apps.adminApi?.scopes || []\n const partnerScope = apps.partnersApi?.scopes || []\n const storefrontScopes = apps.storefrontRendererApi?.scopes || []\n const businessPlatformScopes = apps.businessPlatformApi?.scopes || []\n return {\n admin: apiScopes('admin', adminScope),\n partners: apiScopes('partners', partnerScope),\n storefront: apiScopes('storefront-renderer', storefrontScopes),\n businessPlatform: apiScopes('business-platform', businessPlatformScopes),\n }\n}\n\nfunction buildIdentityTokenFromEnv(\n scopes: string[],\n identityTokenInformation: {accessToken: string; refreshToken: string},\n) {\n return {\n ...identityTokenInformation,\n expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),\n scopes,\n }\n}\n"]}
@@ -1 +1 @@
1
- export declare const CLI_KIT_VERSION = "3.59.3";
1
+ export declare const CLI_KIT_VERSION = "3.60.0";
@@ -1,2 +1,2 @@
1
- export const CLI_KIT_VERSION = '3.59.3';
1
+ export const CLI_KIT_VERSION = '3.60.0';
2
2
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/public/common/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAA","sourcesContent":["export const CLI_KIT_VERSION = '3.59.3'\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/public/common/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAA","sourcesContent":["export const CLI_KIT_VERSION = '3.60.0'\n"]}
@@ -69,8 +69,9 @@ async function buildPayload({ config, errorMessage, exitMode }) {
69
69
  }
70
70
  const { startCommand, startArgs, startTime } = commandStartOptions;
71
71
  const currentTime = new Date().getTime();
72
- const { '@shopify/app': appPublic, ...otherPluginsPublic } = await fanoutHooks(config, 'public_command_metadata', {});
73
- const { '@shopify/app': appSensitive, ...otherPluginsSensitive } = await fanoutHooks(config, 'sensitive_command_metadata', {});
72
+ // All bundled plugins appear as `@shopify/cli` in the payload
73
+ const { '@shopify/cli': internalPluginsPublic, ...externalPluginsPublic } = await fanoutHooks(config, 'public_command_metadata', {});
74
+ const { '@shopify/cli': internalPluginsSensitive, ...externalPluginsSensitive } = await fanoutHooks(config, 'sensitive_command_metadata', {});
74
75
  const environmentData = await getEnvironmentData(config);
75
76
  const sensitiveEnvironmentData = await getSensitiveEnvironmentData(config);
76
77
  const publicMetadata = metadata.getAllPublicMetadata();
@@ -97,7 +98,7 @@ async function buildPayload({ config, errorMessage, exitMode }) {
97
98
  node_version: process.version.replace('v', ''),
98
99
  is_employee: await isShopify(),
99
100
  ...environmentData,
100
- ...appPublic,
101
+ ...internalPluginsPublic,
101
102
  ...publicMetadata,
102
103
  cmd_all_timing_active_ms: totalTimeWithoutSubtimers,
103
104
  cmd_all_exit: exitMode,
@@ -106,14 +107,14 @@ async function buildPayload({ config, errorMessage, exitMode }) {
106
107
  args: startArgs.join(' '),
107
108
  cmd_all_environment_flags: environmentFlags,
108
109
  error_message: errorMessage,
109
- ...appSensitive,
110
+ ...internalPluginsSensitive,
110
111
  ...sensitiveEnvironmentData,
111
112
  metadata: JSON.stringify({
112
113
  ...sensitiveMetadata,
113
114
  extraPublic: {
114
- ...otherPluginsPublic,
115
+ ...externalPluginsPublic,
115
116
  },
116
- extraSensitive: { ...otherPluginsSensitive },
117
+ extraSensitive: { ...externalPluginsSensitive },
117
118
  }),
118
119
  },
119
120
  };
@@ -1 +1 @@
1
- {"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../src/public/node/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,WAAW,EAAC,MAAM,WAAW,CAAA;AAChD,OAAO,EAAC,kBAAkB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,SAAS,EAAC,MAAM,oBAAoB,CAAA;AACrG,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,EAAC,oBAAoB,EAAE,sBAAsB,EAAC,MAAM,eAAe,CAAA;AAC1E,OAAO,EAAC,WAAW,EAAC,MAAM,cAAc,CAAA;AAExC,OAAO,EAAC,aAAa,EAAE,WA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C,sBAAsB,CAAC,CAAA;AAC3C,CAAC","sourcesContent":["import {version as rubyVersion} from './ruby.js'\nimport {alwaysLogAnalytics, alwaysLogMetrics, analyticsDisabled, isShopify} from './context/local.js'\nimport * as metadata from './metadata.js'\nimport {publishMonorailEvent, MONORAIL_COMMAND_TOPIC} from './monorail.js'\nimport {fanoutHooks} from './plugins.js'\n\nimport {outputContent, outputDebug, outputToken} from '../../public/node/output.js'\nimport {getEnvironmentData, getSensitiveEnvironmentData} from '../../private/node/analytics.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {recordMetrics} from '../../private/node/otel-metrics.js'\nimport {Interfaces} from '@oclif/core'\n\nexport type CommandExitMode =\n // The command completed successfully\n | 'ok'\n // The command exited for some unexpected reason -- i.e. a bug\n | 'unexpected_error'\n // The command exited with an error, but its one we expect and doesn't point to a bug -- i.e. malformed config files\n | 'expected_error'\n\ninterface ReportAnalyticsEventOptions {\n config: Interfaces.Config\n errorMessage?: string\n exitMode: CommandExitMode\n}\n\n/**\n * Report an analytics event, sending it off to Monorail -- Shopify's internal analytics service.\n *\n * The payload for an event includes both generic data, and data gathered from installed plug-ins.\n *\n */\nexport async function reportAnalyticsEvent(options: ReportAnalyticsEventOptions): Promise<void> {\n try {\n const payload = await buildPayload(options)\n if (payload === undefined) {\n // Nothing to log\n return\n }\n\n const skipMonorailAnalytics = !alwaysLogAnalytics() && analyticsDisabled()\n const skipMetricAnalytics = !alwaysLogMetrics() && analyticsDisabled()\n if (skipMonorailAnalytics || skipMetricAnalytics) {\n outputDebug(outputContent`Skipping command analytics, payload: ${outputToken.json(payload)}`)\n }\n\n const doMonorail = async () => {\n if (skipMonorailAnalytics) {\n return\n }\n const response = await publishMonorailEvent(MONORAIL_COMMAND_TOPIC, payload.public, payload.sensitive)\n if (response.type === 'error') {\n outputDebug(response.message)\n }\n }\n const doOpenTelemetry = async () => {\n const active = payload.public.cmd_all_timing_active_ms || 0\n const network = payload.public.cmd_all_timing_network_ms || 0\n const prompt = payload.public.cmd_all_timing_prompts_ms || 0\n\n return recordMetrics(\n {\n skipMetricAnalytics,\n cliVersion: payload.public.cli_version,\n owningPlugin: payload.public.cmd_all_plugin || '@shopify/cli',\n command: payload.public.command,\n exitMode: options.exitMode,\n },\n {\n active,\n network,\n prompt,\n },\n )\n }\n await Promise.all([doMonorail(), doOpenTelemetry()])\n\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n let message = 'Failed to report usage analytics'\n if (error instanceof Error) {\n message = message.concat(`: ${error.message}`)\n }\n outputDebug(message)\n }\n}\n\nasync function buildPayload({config, errorMessage, exitMode}: ReportAnalyticsEventOptions) {\n const {commandStartOptions, environmentFlags, ...sensitiveMetadata} = metadata.getAllSensitiveMetadata()\n if (commandStartOptions === undefined) {\n outputDebug('Unable to log analytics event - no information on executed command')\n return\n }\n const {startCommand, startArgs, startTime} = commandStartOptions\n const currentTime = new Date().getTime()\n\n const {'@shopify/app': appPublic, ...otherPluginsPublic} = await fanoutHooks(config, 'public_command_metadata', {})\n const {'@shopify/app': appSensitive, ...otherPluginsSensitive} = await fanoutHooks(\n config,\n 'sensitive_command_metadata',\n {},\n )\n\n const environmentData = await getEnvironmentData(config)\n const sensitiveEnvironmentData = await getSensitiveEnvironmentData(config)\n const publicMetadata = metadata.getAllPublicMetadata()\n\n // Automatically calculate the total time spent in the command, excluding time spent in subtimers.\n const subTimers = ['cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'] as const\n const totalTimeFromSubtimers = subTimers.reduce((total, timer) => {\n const value = publicMetadata[timer]\n if (value !== undefined) {\n return total + value\n }\n return total\n }, 0)\n const wallClockElapsed = currentTime - startTime\n const totalTimeWithoutSubtimers = wallClockElapsed - totalTimeFromSubtimers\n\n let payload = {\n public: {\n command: startCommand,\n time_start: startTime,\n time_end: currentTime,\n total_time: wallClockElapsed,\n success: exitMode === 'ok' && errorMessage === undefined,\n cli_version: CLI_KIT_VERSION,\n ruby_version: (await rubyVersion()) || '',\n node_version: process.version.replace('v', ''),\n is_employee: await isShopify(),\n ...environmentData,\n ...appPublic,\n ...publicMetadata,\n cmd_all_timing_active_ms: totalTimeWithoutSubtimers,\n cmd_all_exit: exitMode,\n },\n sensitive: {\n args: startArgs.join(' '),\n cmd_all_environment_flags: environmentFlags,\n error_message: errorMessage,\n ...appSensitive,\n ...sensitiveEnvironmentData,\n metadata: JSON.stringify({\n ...sensitiveMetadata,\n extraPublic: {\n ...otherPluginsPublic,\n },\n extraSensitive: {...otherPluginsSensitive},\n }),\n },\n }\n\n // round down timing metrics\n const timingMetrics = ['cmd_all_timing_active_ms', 'cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'] as const\n timingMetrics.forEach((metric) => {\n const current = payload.public[metric]\n if (current !== undefined) {\n payload.public[metric] = Math.floor(current)\n }\n })\n\n // strip undefined fields -- they make up the majority of payloads due to wide metadata structure.\n payload = JSON.parse(JSON.stringify(payload))\n\n return sanitizePayload(payload)\n}\n\nfunction sanitizePayload<T>(payload: T): T {\n const payloadString = JSON.stringify(payload)\n // Remove Theme Access passwords from the payload\n const sanitizedPayloadString = payloadString.replace(/shptka_\\w*/g, '*****')\n return JSON.parse(sanitizedPayloadString)\n}\n"]}
1
+ {"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../src/public/node/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,WAAW,EAAC,MAAM,WAAW,CAAA;AAChD,OAAO,EAAC,kBAAkB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,SAAS,EAAC,MAAM,oBAAoB,CAAA;AACrG,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAA;AACzC,OAAO,EAAC,oBAAoB,EAAE,sBAAsB,EAAC,MAAM,eAAe,CAAA;AAC1E,OAAO,EAAC,WAAW,EAAC,MAAM,cAAc,CAAA;AAExC,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAC,kBAAkB,E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["import {version as rubyVersion} from './ruby.js'\nimport {alwaysLogAnalytics, alwaysLogMetrics, analyticsDisabled, isShopify} from './context/local.js'\nimport * as metadata from './metadata.js'\nimport {publishMonorailEvent, MONORAIL_COMMAND_TOPIC} from './monorail.js'\nimport {fanoutHooks} from './plugins.js'\n\nimport {outputContent, outputDebug, outputToken} from '../../public/node/output.js'\nimport {getEnvironmentData, getSensitiveEnvironmentData} from '../../private/node/analytics.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {recordMetrics} from '../../private/node/otel-metrics.js'\nimport {Interfaces} from '@oclif/core'\n\nexport type CommandExitMode =\n // The command completed successfully\n | 'ok'\n // The command exited for some unexpected reason -- i.e. a bug\n | 'unexpected_error'\n // The command exited with an error, but its one we expect and doesn't point to a bug -- i.e. malformed config files\n | 'expected_error'\n\ninterface ReportAnalyticsEventOptions {\n config: Interfaces.Config\n errorMessage?: string\n exitMode: CommandExitMode\n}\n\n/**\n * Report an analytics event, sending it off to Monorail -- Shopify's internal analytics service.\n *\n * The payload for an event includes both generic data, and data gathered from installed plug-ins.\n *\n */\nexport async function reportAnalyticsEvent(options: ReportAnalyticsEventOptions): Promise<void> {\n try {\n const payload = await buildPayload(options)\n if (payload === undefined) {\n // Nothing to log\n return\n }\n\n const skipMonorailAnalytics = !alwaysLogAnalytics() && analyticsDisabled()\n const skipMetricAnalytics = !alwaysLogMetrics() && analyticsDisabled()\n if (skipMonorailAnalytics || skipMetricAnalytics) {\n outputDebug(outputContent`Skipping command analytics, payload: ${outputToken.json(payload)}`)\n }\n\n const doMonorail = async () => {\n if (skipMonorailAnalytics) {\n return\n }\n const response = await publishMonorailEvent(MONORAIL_COMMAND_TOPIC, payload.public, payload.sensitive)\n if (response.type === 'error') {\n outputDebug(response.message)\n }\n }\n const doOpenTelemetry = async () => {\n const active = payload.public.cmd_all_timing_active_ms || 0\n const network = payload.public.cmd_all_timing_network_ms || 0\n const prompt = payload.public.cmd_all_timing_prompts_ms || 0\n\n return recordMetrics(\n {\n skipMetricAnalytics,\n cliVersion: payload.public.cli_version,\n owningPlugin: payload.public.cmd_all_plugin || '@shopify/cli',\n command: payload.public.command,\n exitMode: options.exitMode,\n },\n {\n active,\n network,\n prompt,\n },\n )\n }\n await Promise.all([doMonorail(), doOpenTelemetry()])\n\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n let message = 'Failed to report usage analytics'\n if (error instanceof Error) {\n message = message.concat(`: ${error.message}`)\n }\n outputDebug(message)\n }\n}\n\nasync function buildPayload({config, errorMessage, exitMode}: ReportAnalyticsEventOptions) {\n const {commandStartOptions, environmentFlags, ...sensitiveMetadata} = metadata.getAllSensitiveMetadata()\n if (commandStartOptions === undefined) {\n outputDebug('Unable to log analytics event - no information on executed command')\n return\n }\n const {startCommand, startArgs, startTime} = commandStartOptions\n const currentTime = new Date().getTime()\n\n // All bundled plugins appear as `@shopify/cli` in the payload\n const {'@shopify/cli': internalPluginsPublic, ...externalPluginsPublic} = await fanoutHooks(\n config,\n 'public_command_metadata',\n {},\n )\n const {'@shopify/cli': internalPluginsSensitive, ...externalPluginsSensitive} = await fanoutHooks(\n config,\n 'sensitive_command_metadata',\n {},\n )\n\n const environmentData = await getEnvironmentData(config)\n const sensitiveEnvironmentData = await getSensitiveEnvironmentData(config)\n const publicMetadata = metadata.getAllPublicMetadata()\n\n // Automatically calculate the total time spent in the command, excluding time spent in subtimers.\n const subTimers = ['cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'] as const\n const totalTimeFromSubtimers = subTimers.reduce((total, timer) => {\n const value = publicMetadata[timer]\n if (value !== undefined) {\n return total + value\n }\n return total\n }, 0)\n const wallClockElapsed = currentTime - startTime\n const totalTimeWithoutSubtimers = wallClockElapsed - totalTimeFromSubtimers\n\n let payload = {\n public: {\n command: startCommand,\n time_start: startTime,\n time_end: currentTime,\n total_time: wallClockElapsed,\n success: exitMode === 'ok' && errorMessage === undefined,\n cli_version: CLI_KIT_VERSION,\n ruby_version: (await rubyVersion()) || '',\n node_version: process.version.replace('v', ''),\n is_employee: await isShopify(),\n ...environmentData,\n ...internalPluginsPublic,\n ...publicMetadata,\n cmd_all_timing_active_ms: totalTimeWithoutSubtimers,\n cmd_all_exit: exitMode,\n },\n sensitive: {\n args: startArgs.join(' '),\n cmd_all_environment_flags: environmentFlags,\n error_message: errorMessage,\n ...internalPluginsSensitive,\n ...sensitiveEnvironmentData,\n metadata: JSON.stringify({\n ...sensitiveMetadata,\n extraPublic: {\n ...externalPluginsPublic,\n },\n extraSensitive: {...externalPluginsSensitive},\n }),\n },\n }\n\n // round down timing metrics\n const timingMetrics = ['cmd_all_timing_active_ms', 'cmd_all_timing_network_ms', 'cmd_all_timing_prompts_ms'] as const\n timingMetrics.forEach((metric) => {\n const current = payload.public[metric]\n if (current !== undefined) {\n payload.public[metric] = Math.floor(current)\n }\n })\n\n // strip undefined fields -- they make up the majority of payloads due to wide metadata structure.\n payload = JSON.parse(JSON.stringify(payload))\n\n return sanitizePayload(payload)\n}\n\nfunction sanitizePayload<T>(payload: T): T {\n const payloadString = JSON.stringify(payload)\n // Remove Theme Access passwords from the payload\n const sanitizedPayloadString = payloadString.replace(/shptka_\\w*/g, '*****')\n return JSON.parse(sanitizedPayloadString)\n}\n"]}
@@ -34,6 +34,9 @@ export async function deleteThemeAsset(id, key, session) {
34
34
  }
35
35
  export async function bulkUploadThemeAssets(id, assets, session) {
36
36
  const response = await request('PUT', `/themes/${id}/assets/bulk`, session, { assets });
37
+ if (response.status !== 207) {
38
+ throw new AbortError('Upload failed, could not reach the server');
39
+ }
37
40
  return buildBulkUploadResults(response.json.results, assets);
38
41
  }
39
42
  export async function fetchChecksums(id, session) {
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../../../../src/public/node/themes/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,WAAW,CAAA;AACvC,OAAO,KAAK,SAAS,MAAM,sDAAsD,CAAA;AACjF,OAAO,EAAC,YAAY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,CAAC,CAAA;QAC9D,KAAK,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG;YACjC,MAAM,IAAI,UAAU,CAAC,IAAI,MAAM,4BAA4B,CAAC,CAAA;QAC9D;YACE,MAAM,IAAI,UAAU,CAAC,IAAI,MAAM,gCAAgC,CAAC,CAAA;KACnE;AACH,CAAC;AAED,SAAS,oBAAoB,CAAC,OAAqB;IACjD,MAAM,KAAK,GAAG,OAAO,CAAC,SAAS,CAAA;IAC/B,MAAM,QAAQ,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;IAEvC,MAAM,IAAI,UAAU,CAClB,6CAA6C,KAAK,IAAI,EACtD,mFAAmF;QACjF,qFAAqF;QACrF,uEAAuE;QACvE,MAAM;QACN,qFAAqF;QACrF,gDAAgD,QAAQ,6BAA6B;QACrF,iFAAiF;QACjF,gCAAgC,CACnC,CAAA;AACH,CAAC;AAED,SAAS,MAAM,CAAC,QAAsB;IACpC,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;AAC9C,CAAC","sourcesContent":["import {storeAdminUrl} from './urls.js'\nimport * as throttler from '../../../private/node/themes/themes-api/throttler.js'\nimport {apiCallLimit, retryAfter} from '../../../private/node/themes/themes-api/headers.js'\nimport {retry} from '../../../private/node/themes/themes-api/retry.js'\nimport {restRequest, RestResponse} from '@shopify/cli-kit/node/api/admin'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {AbortError} from '@shopify/cli-kit/node/error'\nimport {\n buildBulkUploadResults,\n buildChecksum,\n buildTheme,\n buildThemeAsset,\n} from '@shopify/cli-kit/node/themes/factories'\nimport {Result, Checksum, Key, Theme, ThemeAsset} from '@shopify/cli-kit/node/themes/types'\n\nexport type ThemeParams = Partial<Pick<Theme, 'name' | 'role' | 'processing'>>\nexport type AssetParams = Pick<ThemeAsset, 'key'> & Partial<Pick<ThemeAsset, 'value' | 'attachment'>>\n\nexport async function fetchTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('GET', `/themes/${id}`, session, undefined, {fields: 'id,name,role,processing'})\n return buildTheme(response.json.theme)\n}\n\nexport async function fetchThemes(session: AdminSession): Promise<Theme[]> {\n const response = await request('GET', '/themes', session, undefined, {fields: 'id,name,role,processing'})\n const themes = response.json?.themes\n if (themes?.length > 0) return themes.map(buildTheme)\n return []\n}\n\nexport async function createTheme(params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('POST', '/themes', session, {theme: {...params}})\n return buildTheme({...response.json.theme, createdAtRuntime: true})\n}\n\nexport async function fetchThemeAsset(id: number, key: Key, session: AdminSession): Promise<ThemeAsset | undefined> {\n const response = await request('GET', `/themes/${id}/assets`, session, undefined, {\n 'asset[key]': key,\n })\n return buildThemeAsset(response.json.asset)\n}\n\nexport async function deleteThemeAsset(id: number, key: Key, session: AdminSession): Promise<boolean> {\n const response = await request('DELETE', `/themes/${id}/assets`, session, undefined, {\n 'asset[key]': key,\n })\n return Boolean(response.json.message)\n}\n\nexport async function bulkUploadThemeAssets(\n id: number,\n assets: AssetParams[],\n session: AdminSession,\n): Promise<Result[]> {\n const response = await request('PUT', `/themes/${id}/assets/bulk`, session, {assets})\n return buildBulkUploadResults(response.json.results, assets)\n}\n\nexport async function fetchChecksums(id: number, session: AdminSession): Promise<Checksum[]> {\n const response = await request('GET', `/themes/${id}/assets`, session, undefined, {fields: 'key,checksum'})\n const assets = response.json.assets\n\n if (assets?.length > 0) return assets.map(buildChecksum)\n\n return []\n}\n\ninterface UpgradeThemeOptions {\n fromTheme: number\n toTheme: number\n script?: string\n session: AdminSession\n}\n\nexport async function upgradeTheme(upgradeOptions: UpgradeThemeOptions): Promise<Theme | undefined> {\n const {fromTheme, toTheme, session, script} = upgradeOptions\n const params = {from_theme: fromTheme, to_theme: toTheme, ...(script && {script})}\n const response = await request('POST', `/themes`, session, params)\n return buildTheme(response.json.theme)\n}\n\nexport async function updateTheme(id: number, params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('PUT', `/themes/${id}`, session, {theme: {id, ...params}})\n return buildTheme(response.json.theme)\n}\n\nexport async function publishTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n return updateTheme(id, {role: 'main'}, session)\n}\n\nexport async function deleteTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('DELETE', `/themes/${id}`, session)\n return buildTheme(response.json.theme)\n}\n\nasync function request<T>(\n method: string,\n path: string,\n session: AdminSession,\n params?: T,\n searchParams: {[name: string]: string} = {},\n): Promise<RestResponse> {\n const response = await throttler.throttle(() => restRequest(method, path, session, params, searchParams))\n\n const status = response.status\n const callLimit = apiCallLimit(response)\n\n throttler.updateApiCallLimit(callLimit)\n\n switch (true) {\n case status >= 200 && status <= 399:\n // Returns the successful reponse\n return response\n case status === 404:\n // Defer the decision when a resource is not found\n return response\n case status === 429:\n // Retry following the \"retry-after\" header\n return retry(() => request(method, path, session, params, searchParams), retryAfter(response))\n case status === 403:\n return handleForbiddenError(session)\n case status === 401:\n throw new AbortError(`[${status}] API request unauthorized error`)\n case status === 422:\n throw new AbortError(`[${status}] API request unprocessable content: ${errors(response)}`)\n case status >= 400 && status <= 499:\n throw new AbortError(`[${status}] API request client error`)\n case status >= 500 && status <= 599:\n throw new AbortError(`[${status}] API request server error`)\n default:\n throw new AbortError(`[${status}] API request unexpected error`)\n }\n}\n\nfunction handleForbiddenError(session: AdminSession): never {\n const store = session.storeFqdn\n const adminUrl = storeAdminUrl(session)\n\n throw new AbortError(\n `You are not authorized to edit themes on \"${store}\".`,\n \"You can't use Shopify CLI with development stores if you only have Partner staff \" +\n 'member access. If you want to use Shopify CLI to work on a development store, then ' +\n 'you should be the store owner or create a staff account on the store.' +\n '\\n\\n' +\n \"If you're the store owner, then you need to log in to the store directly using the \" +\n `store URL at least once (for example, using \"${adminUrl}\") before you log in using ` +\n 'Shopify CLI. Logging in to the Shopify admin directly connects the development ' +\n 'store with your Shopify login.',\n )\n}\n\nfunction errors(response: RestResponse) {\n return JSON.stringify(response.json?.errors)\n}\n"]}
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../../../src/public/node/themes/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,WAAW,CAAA;AACvC,OAAO,KAAK,SAAS,MAAM,sDAAsD,CAAA;AACjF,OAAO,EAAC,YAAY,EAAE,UAAU,EAAC,MAAM,oDAAoD,CAAA;AAC3F,OAAO,EAAC,KAAK,EAAC,MAAM,kDAAkD,CAAA;AACtE,OAAO,EAAC,WAAW,EAAe,MAAM,iCAAiC,CAAA;AAEzE,OAAO,EAAC,UAAU,EAAC,MAAM,6BAA6B,CAAA;AACtD,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,UAAU,EACV,eAAe,GAChB,MAAM,wCAAwC,CAAA;AAM/C,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,EAAU,EAAE,OAAqB;IAChE,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,EAAC,MAAM,EAAE,yBAAyB,EAAC,CAAC,CAAA;IAC/G,OAAO,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;AACxC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAAqB;IACrD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,EAAC,MAAM,EAAE,yBAAyB,EAAC,CAAC,CAAA;IACzG,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACpC,IAAI,MAAM,EAAE,MAAM,GAAG,CAAC;QAAE,OAAO,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAA;IACrD,OAAO,EAAE,CAAA;AACX,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,MAAmB,EA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,OAAO,CAAC,CAAA;QACtC,KAAK,MAAM,KAAK,GAAG;YACjB,MAAM,IAAI,UAAU,CAAC,IAAI,MAAM,kCAAkC,CAAC,CAAA;QACpE,KAAK,MAAM,KAAK,GAAG;YACjB,MAAM,IAAI,UAAU,CAAC,IAAI,MAAM,wCAAwC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;QAC5F,KAAK,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG;YACjC,MAAM,IAAI,UAAU,CAAC,IAAI,MAAM,4BAA4B,CAAC,CAAA;QAC9D,KAAK,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG;YACjC,MAAM,IAAI,UAAU,CAAC,IAAI,MAAM,4BAA4B,CAAC,CAAA;QAC9D;YACE,MAAM,IAAI,UAAU,CAAC,IAAI,MAAM,gCAAgC,CAAC,CAAA;KACnE;AACH,CAAC;AAED,SAAS,oBAAoB,CAAC,OAAqB;IACjD,MAAM,KAAK,GAAG,OAAO,CAAC,SAAS,CAAA;IAC/B,MAAM,QAAQ,GAAG,aAAa,CAAC,OAAO,CAAC,CAAA;IAEvC,MAAM,IAAI,UAAU,CAClB,6CAA6C,KAAK,IAAI,EACtD,mFAAmF;QACjF,qFAAqF;QACrF,uEAAuE;QACvE,MAAM;QACN,qFAAqF;QACrF,gDAAgD,QAAQ,6BAA6B;QACrF,iFAAiF;QACjF,gCAAgC,CACnC,CAAA;AACH,CAAC;AAED,SAAS,MAAM,CAAC,QAAsB;IACpC,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;AAC9C,CAAC","sourcesContent":["import {storeAdminUrl} from './urls.js'\nimport * as throttler from '../../../private/node/themes/themes-api/throttler.js'\nimport {apiCallLimit, retryAfter} from '../../../private/node/themes/themes-api/headers.js'\nimport {retry} from '../../../private/node/themes/themes-api/retry.js'\nimport {restRequest, RestResponse} from '@shopify/cli-kit/node/api/admin'\nimport {AdminSession} from '@shopify/cli-kit/node/session'\nimport {AbortError} from '@shopify/cli-kit/node/error'\nimport {\n buildBulkUploadResults,\n buildChecksum,\n buildTheme,\n buildThemeAsset,\n} from '@shopify/cli-kit/node/themes/factories'\nimport {Result, Checksum, Key, Theme, ThemeAsset} from '@shopify/cli-kit/node/themes/types'\n\nexport type ThemeParams = Partial<Pick<Theme, 'name' | 'role' | 'processing'>>\nexport type AssetParams = Pick<ThemeAsset, 'key'> & Partial<Pick<ThemeAsset, 'value' | 'attachment'>>\n\nexport async function fetchTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('GET', `/themes/${id}`, session, undefined, {fields: 'id,name,role,processing'})\n return buildTheme(response.json.theme)\n}\n\nexport async function fetchThemes(session: AdminSession): Promise<Theme[]> {\n const response = await request('GET', '/themes', session, undefined, {fields: 'id,name,role,processing'})\n const themes = response.json?.themes\n if (themes?.length > 0) return themes.map(buildTheme)\n return []\n}\n\nexport async function createTheme(params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('POST', '/themes', session, {theme: {...params}})\n return buildTheme({...response.json.theme, createdAtRuntime: true})\n}\n\nexport async function fetchThemeAsset(id: number, key: Key, session: AdminSession): Promise<ThemeAsset | undefined> {\n const response = await request('GET', `/themes/${id}/assets`, session, undefined, {\n 'asset[key]': key,\n })\n return buildThemeAsset(response.json.asset)\n}\n\nexport async function deleteThemeAsset(id: number, key: Key, session: AdminSession): Promise<boolean> {\n const response = await request('DELETE', `/themes/${id}/assets`, session, undefined, {\n 'asset[key]': key,\n })\n return Boolean(response.json.message)\n}\n\nexport async function bulkUploadThemeAssets(\n id: number,\n assets: AssetParams[],\n session: AdminSession,\n): Promise<Result[]> {\n const response = await request('PUT', `/themes/${id}/assets/bulk`, session, {assets})\n if (response.status !== 207) {\n throw new AbortError('Upload failed, could not reach the server')\n }\n return buildBulkUploadResults(response.json.results, assets)\n}\n\nexport async function fetchChecksums(id: number, session: AdminSession): Promise<Checksum[]> {\n const response = await request('GET', `/themes/${id}/assets`, session, undefined, {fields: 'key,checksum'})\n const assets = response.json.assets\n\n if (assets?.length > 0) return assets.map(buildChecksum)\n\n return []\n}\n\ninterface UpgradeThemeOptions {\n fromTheme: number\n toTheme: number\n script?: string\n session: AdminSession\n}\n\nexport async function upgradeTheme(upgradeOptions: UpgradeThemeOptions): Promise<Theme | undefined> {\n const {fromTheme, toTheme, session, script} = upgradeOptions\n const params = {from_theme: fromTheme, to_theme: toTheme, ...(script && {script})}\n const response = await request('POST', `/themes`, session, params)\n return buildTheme(response.json.theme)\n}\n\nexport async function updateTheme(id: number, params: ThemeParams, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('PUT', `/themes/${id}`, session, {theme: {id, ...params}})\n return buildTheme(response.json.theme)\n}\n\nexport async function publishTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n return updateTheme(id, {role: 'main'}, session)\n}\n\nexport async function deleteTheme(id: number, session: AdminSession): Promise<Theme | undefined> {\n const response = await request('DELETE', `/themes/${id}`, session)\n return buildTheme(response.json.theme)\n}\n\nasync function request<T>(\n method: string,\n path: string,\n session: AdminSession,\n params?: T,\n searchParams: {[name: string]: string} = {},\n): Promise<RestResponse> {\n const response = await throttler.throttle(() => restRequest(method, path, session, params, searchParams))\n\n const status = response.status\n const callLimit = apiCallLimit(response)\n\n throttler.updateApiCallLimit(callLimit)\n\n switch (true) {\n case status >= 200 && status <= 399:\n // Returns the successful reponse\n return response\n case status === 404:\n // Defer the decision when a resource is not found\n return response\n case status === 429:\n // Retry following the \"retry-after\" header\n return retry(() => request(method, path, session, params, searchParams), retryAfter(response))\n case status === 403:\n return handleForbiddenError(session)\n case status === 401:\n throw new AbortError(`[${status}] API request unauthorized error`)\n case status === 422:\n throw new AbortError(`[${status}] API request unprocessable content: ${errors(response)}`)\n case status >= 400 && status <= 499:\n throw new AbortError(`[${status}] API request client error`)\n case status >= 500 && status <= 599:\n throw new AbortError(`[${status}] API request server error`)\n default:\n throw new AbortError(`[${status}] API request unexpected error`)\n }\n}\n\nfunction handleForbiddenError(session: AdminSession): never {\n const store = session.storeFqdn\n const adminUrl = storeAdminUrl(session)\n\n throw new AbortError(\n `You are not authorized to edit themes on \"${store}\".`,\n \"You can't use Shopify CLI with development stores if you only have Partner staff \" +\n 'member access. If you want to use Shopify CLI to work on a development store, then ' +\n 'you should be the store owner or create a staff account on the store.' +\n '\\n\\n' +\n \"If you're the store owner, then you need to log in to the store directly using the \" +\n `store URL at least once (for example, using \"${adminUrl}\") before you log in using ` +\n 'Shopify CLI. Logging in to the Shopify admin directly connects the development ' +\n 'store with your Shopify login.',\n )\n}\n\nfunction errors(response: RestResponse) {\n return JSON.stringify(response.json?.errors)\n}\n"]}
@@ -26,19 +26,17 @@ export function buildThemeAsset(asset) {
26
26
  return { key, checksum, attachment, value };
27
27
  }
28
28
  export function buildBulkUploadResults(bulkUploadResponse, assets) {
29
- const results = [];
30
- if (!bulkUploadResponse)
31
- return results;
32
- bulkUploadResponse.forEach((bulkUpload, index) => {
33
- const asset = assets[index];
34
- results.push({
35
- key: asset?.key || '',
29
+ if (!bulkUploadResponse) {
30
+ return [];
31
+ }
32
+ return bulkUploadResponse.map((bulkUpload, index) => {
33
+ return {
34
+ key: assets[index].key,
36
35
  success: bulkUpload.code === 200,
37
36
  errors: bulkUpload.body.errors || {},
38
37
  asset: bulkUpload.body.asset,
39
38
  operation: Operation.Upload,
40
- });
39
+ };
41
40
  });
42
- return results;
43
41
  }
44
42
  //# sourceMappingURL=factories.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"factories.js","sourceRoot":"","sources":["../../../../src/public/node/themes/factories.ts"],"names":[],"mappings":"AACA,OAAO,EAAsC,SAAS,EAAC,MAAM,oCAAoC,CAAA;AAsBjG,MAAM,UAAU,UAAU,CAAC,SAA+B;IACxD,IAAI,CAAC,SAAS;QAAE,OAAM;IAEtB,SAAS,CAAC,UAAU,KAApB,SAAS,CAAC,UAAU,GAAK,KAAK,EAAA;IAC9B,SAAS,CAAC,gBAAg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,CAAC,IAAI,CAAC,KAAK;YAC5B,SAAS,EAAE,SAAS,CAAC,MAAM;SAC5B,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IACF,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["import {AssetParams} from './api.js'\nimport {Result, Checksum, Theme, ThemeAsset, Operation} from '@shopify/cli-kit/node/themes/types'\n\ninterface RemoteThemeResponse {\n id: number\n name: string\n role: string\n createdAtRuntime?: boolean\n processing?: boolean\n}\n\ninterface RemoteAssetResponse {\n key: string\n checksum: string\n attachment: string\n value: string\n}\n\nexport interface RemoteBulkUploadResponse {\n body: {asset?: RemoteAssetResponse; errors?: {asset: string[]}}\n code: number\n}\n\nexport function buildTheme(themeJson?: RemoteThemeResponse): Theme | undefined {\n if (!themeJson) return\n\n themeJson.processing ??= false\n themeJson.createdAtRuntime ??= false\n\n const {id, name, role, processing, createdAtRuntime} = themeJson\n\n return {\n id,\n name,\n processing,\n createdAtRuntime,\n role: role === 'main' ? 'live' : role,\n }\n}\n\nexport function buildChecksum(asset?: RemoteAssetResponse): Checksum | undefined {\n if (!asset) return\n\n const {key, checksum} = asset\n return {key, checksum}\n}\n\nexport function buildThemeAsset(asset?: RemoteAssetResponse): ThemeAsset | undefined {\n if (!asset) return\n\n const {key, checksum, attachment, value} = asset\n return {key, checksum, attachment, value}\n}\n\nexport function buildBulkUploadResults(\n bulkUploadResponse: RemoteBulkUploadResponse[],\n assets: AssetParams[],\n): Result[] {\n const results: Result[] = []\n if (!bulkUploadResponse) return results\n\n bulkUploadResponse.forEach((bulkUpload, index) => {\n const asset = assets[index]\n results.push({\n key: asset?.key || '',\n success: bulkUpload.code === 200,\n errors: bulkUpload.body.errors || {},\n asset: bulkUpload.body.asset,\n operation: Operation.Upload,\n })\n })\n return results\n}\n"]}
1
+ {"version":3,"file":"factories.js","sourceRoot":"","sources":["../../../../src/public/node/themes/factories.ts"],"names":[],"mappings":"AACA,OAAO,EAAsC,SAAS,EAAC,MAAM,oCAAoC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;YAChC,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE;YACpC,KAAK,EAAE,UAAU,CAAC,IAAI,CAAC,KAAK;YAC5B,SAAS,EAAE,SAAS,CAAC,MAAM;SAC5B,CAAA;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {AssetParams} from './api.js'\nimport {Result, Checksum, Theme, ThemeAsset, Operation} from '@shopify/cli-kit/node/themes/types'\n\ninterface RemoteThemeResponse {\n id: number\n name: string\n role: string\n createdAtRuntime?: boolean\n processing?: boolean\n}\n\ninterface RemoteAssetResponse {\n key: string\n checksum: string\n attachment: string\n value: string\n}\n\nexport interface RemoteBulkUploadResponse {\n body: {asset?: RemoteAssetResponse; errors?: {asset: string[]}}\n code: number\n}\n\nexport function buildTheme(themeJson?: RemoteThemeResponse): Theme | undefined {\n if (!themeJson) return\n\n themeJson.processing ??= false\n themeJson.createdAtRuntime ??= false\n\n const {id, name, role, processing, createdAtRuntime} = themeJson\n\n return {\n id,\n name,\n processing,\n createdAtRuntime,\n role: role === 'main' ? 'live' : role,\n }\n}\n\nexport function buildChecksum(asset?: RemoteAssetResponse): Checksum | undefined {\n if (!asset) return\n\n const {key, checksum} = asset\n return {key, checksum}\n}\n\nexport function buildThemeAsset(asset?: RemoteAssetResponse): ThemeAsset | undefined {\n if (!asset) return\n\n const {key, checksum, attachment, value} = asset\n return {key, checksum, attachment, value}\n}\n\nexport function buildBulkUploadResults(\n bulkUploadResponse: RemoteBulkUploadResponse[],\n assets: AssetParams[],\n): Result[] {\n if (!bulkUploadResponse) {\n return []\n }\n\n return bulkUploadResponse.map((bulkUpload, index) => {\n return {\n key: assets[index]!.key,\n success: bulkUpload.code === 200,\n errors: bulkUpload.body.errors || {},\n asset: bulkUpload.body.asset,\n operation: Operation.Upload,\n }\n })\n}\n"]}