{"version":3,"file":"ShopifyProvider.mjs","names":[],"sources":["../../src/ShopifyProvider.tsx"],"sourcesContent":["import {createContext, useContext, useMemo, type ReactNode} from 'react';\nimport type {LanguageCode, CountryCode} from './storefront-api-types.js';\nimport {SFAPI_VERSION} from './storefront-api-constants.js';\nimport {getPublicTokenHeadersRaw} from './storefront-client.js';\n\nexport const defaultShopifyContext: ShopifyContextValue = {\n  storeDomain: 'test',\n  storefrontToken: 'abc123',\n  storefrontApiVersion: SFAPI_VERSION,\n  countryIsoCode: 'US',\n  languageIsoCode: 'EN',\n  getStorefrontApiUrl() {\n    return '';\n  },\n  getPublicTokenHeaders() {\n    return {};\n  },\n  getShopifyDomain() {\n    return '';\n  },\n};\n\nconst ShopifyContext = createContext<ShopifyContextValue>(\n  defaultShopifyContext,\n);\n\n/**\n * Hydrogen server sets this server timing key when the SFAPI proxy is enabled.\n * Read it automatically in the browser for apps using frontend cart in full-stack Hydrogen,\n * but don't export this utility yet since we don't want to make this a public convention.\n */\nfunction isSfapiProxyEnabled() {\n  if (typeof window === 'undefined') return false;\n\n  try {\n    const navigationEntry = window.performance?.getEntriesByType?.(\n      'navigation',\n    )[0] as PerformanceNavigationTiming;\n\n    return !!navigationEntry?.serverTiming?.some(\n      (entry) => entry.name === '_sfapi_proxy',\n    );\n  } catch (e) {\n    return false;\n  }\n}\n\n/**\n * The `<ShopifyProvider/>` component enables use of the `useShop()` hook. The component should wrap your app.\n * @publicDocs\n */\nexport function ShopifyProvider({\n  children,\n  ...shopifyConfig\n}: ShopifyProviderProps): JSX.Element {\n  if (\n    !shopifyConfig.countryIsoCode ||\n    !shopifyConfig.languageIsoCode ||\n    !shopifyConfig.storeDomain ||\n    !shopifyConfig.storefrontToken ||\n    !shopifyConfig.storefrontApiVersion\n  ) {\n    throw new Error(\n      `Please provide the necessary props to '<ShopifyProvider/>'`,\n    );\n  }\n\n  if (shopifyConfig.storefrontApiVersion !== SFAPI_VERSION) {\n    console.warn(\n      `<ShopifyProvider/>: This version of Hydrogen React is built for Shopify's Storefront API version ${SFAPI_VERSION}, but it looks like you're using version ${shopifyConfig.storefrontApiVersion}. There may be issues or bugs if you use a mismatched version of Hydrogen React and the Storefront API.`,\n    );\n  }\n\n  const finalConfig = useMemo<ShopifyContextValue>(() => {\n    const sameDomainForStorefrontApi =\n      shopifyConfig.sameDomainForStorefrontApi ?? isSfapiProxyEnabled();\n\n    function getShopifyDomain(overrideProps?: {storeDomain?: string}): string {\n      const domain = overrideProps?.storeDomain ?? shopifyConfig.storeDomain;\n      return domain.includes('://') ? domain : `https://${domain}`;\n    }\n\n    return {\n      ...shopifyConfig,\n      sameDomainForStorefrontApi,\n      getPublicTokenHeaders(overrideProps): Record<string, string> {\n        return getPublicTokenHeadersRaw(\n          overrideProps.contentType,\n          shopifyConfig.storefrontApiVersion,\n          overrideProps.storefrontToken ?? shopifyConfig.storefrontToken,\n        );\n      },\n      getShopifyDomain,\n      getStorefrontApiUrl(overrideProps): string {\n        const finalDomainUrl =\n          sameDomainForStorefrontApi && typeof window !== 'undefined'\n            ? window.location.origin\n            : getShopifyDomain({\n                storeDomain:\n                  overrideProps?.storeDomain ?? shopifyConfig.storeDomain,\n              });\n\n        return `${finalDomainUrl}${\n          finalDomainUrl.endsWith('/') ? '' : '/'\n        }api/${\n          overrideProps?.storefrontApiVersion ??\n          shopifyConfig.storefrontApiVersion\n        }/graphql.json`;\n      },\n    };\n  }, [shopifyConfig]);\n\n  return (\n    <ShopifyContext.Provider value={finalConfig}>\n      {children}\n    </ShopifyContext.Provider>\n  );\n}\n\n/**\n * Provides access to the `shopifyConfig` prop of `<ShopifyProvider/>`. Must be a descendent of `<ShopifyProvider/>`.\n * @publicDocs\n */\nexport function useShop(): ShopifyContextValue {\n  const shopContext = useContext(ShopifyContext);\n  if (!shopContext) {\n    throw new Error(`'useShop()' must be a descendent of <ShopifyProvider/>`);\n  }\n  return shopContext;\n}\n\nexport interface ShopifyProviderBase {\n  /** The globally-unique identifier for the Shop */\n  storefrontId?: string;\n  /** The full domain of your Shopify storefront URL (eg: the complete string of `{subdomain}.myshopify.com`). */\n  storeDomain: string;\n  /** The Storefront API public access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n  storefrontToken: string;\n  /** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details.  */\n  storefrontApiVersion: string;\n  /**\n   * The code designating a country, which generally follows ISO 3166-1 alpha-2 guidelines. If a territory doesn't have a country code value in the `CountryCode` enum, it might be considered a subdivision of another country. For example, the territories associated with Spain are represented by the country code `ES`, and the territories associated with the United States of America are represented by the country code `US`.\n   */\n  countryIsoCode: CountryCode;\n  /**\n   * `ISO 369` language codes supported by Shopify.\n   */\n  languageIsoCode: LanguageCode;\n  /**\n   * Uses the current window.location.origin for Storefront API requests.\n   * This requires setting up a proxy for Storefront API requests in your domain.\n   */\n  sameDomainForStorefrontApi?: boolean;\n}\n\n/**\n * Shopify-specific values that are used in various Hydrogen React components and hooks.\n */\nexport interface ShopifyProviderProps extends ShopifyProviderBase {\n  /** React children to render. */\n  children?: ReactNode;\n}\n\nexport interface ShopifyContextValue\n  extends ShopifyProviderBase, ShopifyContextReturn {}\n\ntype ShopifyContextReturn = {\n  /**\n   * Creates the fully-qualified URL to your store's GraphQL endpoint.\n   *\n   * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n   *\n   * - `storeDomain`\n   * - `storefrontApiVersion`\n   */\n  getStorefrontApiUrl: (props?: GetStorefrontApiUrlProps) => string;\n  /**\n   * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This uses the public Storefront API token.\n   *\n   * By default, it will use the config you passed in when creating `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n   *\n   * - `contentType`\n   * - `storefrontToken`\n   *\n   */\n  getPublicTokenHeaders: (\n    props: GetPublicTokenHeadersProps,\n  ) => Record<string, string>;\n  /**\n   * Creates the fully-qualified URL to your myshopify.com domain.\n   *\n   * By default, it will use the config you passed in when calling `<ShopifyProvider/>`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n   *\n   * - `storeDomain`\n   */\n  getShopifyDomain: (props?: GetShopifyDomainProps) => string;\n};\n\ntype GetStorefrontApiUrlProps = {\n  /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n  storeDomain?: string;\n  /** The Storefront API version. This should almost always be the same as the version Hydrogen-UI was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */\n  storefrontApiVersion?: string;\n};\n\ntype GetPublicTokenHeadersProps = {\n  /**\n   * Customizes which `\"content-type\"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `\"json\"`. When fetching with a `body` that is a plain string, use `\"graphql\"`. Defaults to `\"json\"`\n   */\n  contentType: 'json' | 'graphql';\n  /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n  storefrontToken?: string;\n};\n\ntype GetShopifyDomainProps = {storeDomain?: string};\n"],"mappings":";;;;;AAKA,IAAa,wBAA6C;CACxD,aAAa;CACb,iBAAiB;CACjB,sBAAsB;CACtB,gBAAgB;CAChB,iBAAiB;CACjB,sBAAsB;AACpB,SAAO;;CAET,wBAAwB;AACtB,SAAO,EAAE;;CAEX,mBAAmB;AACjB,SAAO;;CAEV;AAED,IAAM,iBAAiB,cACrB,sBACD;;;;;;AAOD,SAAS,sBAAsB;AAC7B,KAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,KAAI;AAKF,SAAO,CAAC,EAJgB,OAAO,aAAa,mBAC1C,aACD,CAAC,KAEwB,cAAc,MACrC,UAAU,MAAM,SAAS,eAC3B;UACM,GAAG;AACV,SAAO;;;;;;;AAQX,SAAgB,gBAAgB,EAC9B,UACA,GAAG,iBACiC;AACpC,KACE,CAAC,cAAc,kBACf,CAAC,cA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