@shopify/hydrogen-react 2025.10.0 → 2026.1.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.
- package/customer-account.schema.json +1 -1
- package/dist/browser-dev/CartLineProvider.mjs.map +1 -1
- package/dist/browser-dev/CartProvider.mjs.map +1 -1
- package/dist/browser-dev/Image.mjs.map +1 -1
- package/dist/browser-dev/ModelViewer.mjs.map +1 -1
- package/dist/browser-dev/Money.mjs.map +1 -1
- package/dist/browser-dev/Video.mjs.map +1 -1
- package/dist/browser-dev/cart-queries.mjs +1 -1
- package/dist/browser-dev/cart-queries.mjs.map +1 -1
- package/dist/browser-dev/codegen.helpers.mjs.map +1 -1
- package/dist/browser-dev/optionValueDecoder.mjs.map +1 -1
- package/dist/browser-dev/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/browser-dev/storefront-api-constants.mjs +1 -1
- package/dist/browser-dev/storefront-api-constants.mjs.map +1 -1
- package/dist/browser-dev/storefront-client.mjs +0 -1
- package/dist/browser-dev/storefront-client.mjs.map +1 -1
- package/dist/browser-dev/useCartAPIStateMachine.mjs.map +1 -1
- package/dist/browser-dev/useCartActions.mjs.map +1 -1
- package/dist/browser-dev/useMoney.mjs.map +1 -1
- package/dist/browser-prod/CartLineProvider.mjs.map +1 -1
- package/dist/browser-prod/CartProvider.mjs.map +1 -1
- package/dist/browser-prod/Image.mjs.map +1 -1
- package/dist/browser-prod/ModelViewer.mjs.map +1 -1
- package/dist/browser-prod/Money.mjs.map +1 -1
- package/dist/browser-prod/Video.mjs.map +1 -1
- package/dist/browser-prod/cart-queries.mjs +1 -1
- package/dist/browser-prod/cart-queries.mjs.map +1 -1
- package/dist/browser-prod/codegen.helpers.mjs.map +1 -1
- package/dist/browser-prod/optionValueDecoder.mjs.map +1 -1
- package/dist/browser-prod/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/browser-prod/storefront-api-constants.mjs +1 -1
- package/dist/browser-prod/storefront-api-constants.mjs.map +1 -1
- package/dist/browser-prod/storefront-client.mjs +0 -1
- package/dist/browser-prod/storefront-client.mjs.map +1 -1
- package/dist/browser-prod/useCartAPIStateMachine.mjs.map +1 -1
- package/dist/browser-prod/useCartActions.mjs.map +1 -1
- package/dist/browser-prod/useMoney.mjs.map +1 -1
- package/dist/node-dev/CartLineProvider.js.map +1 -1
- package/dist/node-dev/CartLineProvider.mjs.map +1 -1
- package/dist/node-dev/CartProvider.js.map +1 -1
- package/dist/node-dev/CartProvider.mjs.map +1 -1
- package/dist/node-dev/Image.js.map +1 -1
- package/dist/node-dev/Image.mjs.map +1 -1
- package/dist/node-dev/ModelViewer.js.map +1 -1
- package/dist/node-dev/ModelViewer.mjs.map +1 -1
- package/dist/node-dev/Money.js.map +1 -1
- package/dist/node-dev/Money.mjs.map +1 -1
- package/dist/node-dev/Video.js.map +1 -1
- package/dist/node-dev/Video.mjs.map +1 -1
- package/dist/node-dev/cart-queries.js +1 -1
- package/dist/node-dev/cart-queries.js.map +1 -1
- package/dist/node-dev/cart-queries.mjs +1 -1
- package/dist/node-dev/cart-queries.mjs.map +1 -1
- package/dist/node-dev/codegen.helpers.js.map +1 -1
- package/dist/node-dev/codegen.helpers.mjs.map +1 -1
- package/dist/node-dev/optionValueDecoder.js.map +1 -1
- package/dist/node-dev/optionValueDecoder.mjs.map +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.json.js +1 -1
- package/dist/node-dev/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/node-dev/storefront-api-constants.js +1 -1
- package/dist/node-dev/storefront-api-constants.js.map +1 -1
- package/dist/node-dev/storefront-api-constants.mjs +1 -1
- package/dist/node-dev/storefront-api-constants.mjs.map +1 -1
- package/dist/node-dev/storefront-client.js +0 -1
- package/dist/node-dev/storefront-client.js.map +1 -1
- package/dist/node-dev/storefront-client.mjs +0 -1
- package/dist/node-dev/storefront-client.mjs.map +1 -1
- package/dist/node-dev/useCartAPIStateMachine.js.map +1 -1
- package/dist/node-dev/useCartAPIStateMachine.mjs.map +1 -1
- package/dist/node-dev/useCartActions.js.map +1 -1
- package/dist/node-dev/useCartActions.mjs.map +1 -1
- package/dist/node-dev/useMoney.js.map +1 -1
- package/dist/node-dev/useMoney.mjs.map +1 -1
- package/dist/node-prod/CartLineProvider.js.map +1 -1
- package/dist/node-prod/CartLineProvider.mjs.map +1 -1
- package/dist/node-prod/CartProvider.js.map +1 -1
- package/dist/node-prod/CartProvider.mjs.map +1 -1
- package/dist/node-prod/Image.js.map +1 -1
- package/dist/node-prod/Image.mjs.map +1 -1
- package/dist/node-prod/ModelViewer.js.map +1 -1
- package/dist/node-prod/ModelViewer.mjs.map +1 -1
- package/dist/node-prod/Money.js.map +1 -1
- package/dist/node-prod/Money.mjs.map +1 -1
- package/dist/node-prod/Video.js.map +1 -1
- package/dist/node-prod/Video.mjs.map +1 -1
- package/dist/node-prod/cart-queries.js +1 -1
- package/dist/node-prod/cart-queries.js.map +1 -1
- package/dist/node-prod/cart-queries.mjs +1 -1
- package/dist/node-prod/cart-queries.mjs.map +1 -1
- package/dist/node-prod/codegen.helpers.js.map +1 -1
- package/dist/node-prod/codegen.helpers.mjs.map +1 -1
- package/dist/node-prod/optionValueDecoder.js.map +1 -1
- package/dist/node-prod/optionValueDecoder.mjs.map +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.json.js +1 -1
- package/dist/node-prod/packages/hydrogen-react/package.json.mjs +1 -1
- package/dist/node-prod/storefront-api-constants.js +1 -1
- package/dist/node-prod/storefront-api-constants.js.map +1 -1
- package/dist/node-prod/storefront-api-constants.mjs +1 -1
- package/dist/node-prod/storefront-api-constants.mjs.map +1 -1
- package/dist/node-prod/storefront-client.js +0 -1
- package/dist/node-prod/storefront-client.js.map +1 -1
- package/dist/node-prod/storefront-client.mjs +0 -1
- package/dist/node-prod/storefront-client.mjs.map +1 -1
- package/dist/node-prod/useCartAPIStateMachine.js.map +1 -1
- package/dist/node-prod/useCartAPIStateMachine.mjs.map +1 -1
- package/dist/node-prod/useCartActions.js.map +1 -1
- package/dist/node-prod/useCartActions.mjs.map +1 -1
- package/dist/node-prod/useMoney.js.map +1 -1
- package/dist/node-prod/useMoney.mjs.map +1 -1
- package/dist/types/CartLineProvider.d.ts +1 -1
- package/dist/types/CartProvider.d.ts +2 -2
- package/dist/types/Image.d.ts +1 -1
- package/dist/types/ModelViewer.d.ts +1 -1
- package/dist/types/Money.d.ts +4 -4
- package/dist/types/Video.d.ts +1 -1
- package/dist/types/codegen.helpers.d.ts +2 -2
- package/dist/types/customer-account-api-types.d.ts +643 -8
- package/dist/types/optionValueDecoder.d.ts +2 -2
- package/dist/types/storefront-api-constants.d.ts +1 -1
- package/dist/types/storefront-api-types.d.ts +48 -4
- package/dist/types/useCartAPIStateMachine.d.ts +2 -2
- package/dist/types/useCartActions.d.ts +2 -2
- package/dist/types/useMoney.d.ts +2 -2
- package/dist/umd/hydrogen-react.dev.js +3 -4
- package/dist/umd/hydrogen-react.dev.js.map +1 -1
- package/dist/umd/hydrogen-react.prod.js +9 -9
- package/dist/umd/hydrogen-react.prod.js.map +1 -1
- package/package.json +1 -1
- package/storefront.schema.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: 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 * 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 * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\nconst MOCK_SHOP_DOMAIN = 'mock.shop';\nconst isMockShop = (domain: string): boolean =>\n domain.includes(MOCK_SHOP_DOMAIN);\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient({\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n}: StorefrontClientProps): StorefrontClientReturn {\n if (!storeDomain) {\n if (__HYDROGEN_DEV__) {\n storeDomain = MOCK_SHOP_DOMAIN;\n warnOnce(\n `storeDomain missing, defaulting to ${MOCK_SHOP_DOMAIN}`,\n 'info',\n );\n } else {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client in production.`,\n );\n }\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received version: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (\n __HYDROGEN_DEV__ &&\n !privateStorefrontToken &&\n !globalThis.document &&\n !isMockShop(storeDomain)\n ) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n if (isMockShop(domain)) return apiUrl;\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst warnOnce = (string: string, type: 'warn' | 'info' = 'warn'): void => {\n if (!warnings.has(string)) {\n console[type](`[h2:${type}:createStorefrontClient] ` + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\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 `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\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 calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAmBA,MAAM,mBAAmB;AACzB,MAAM,aAAa,CAAC,WAClB,OAAO,SAAS,gBAAgB;AAO3B,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AA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A0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAA;AAAA,MAAC;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAC3D,UACE,CAAC,yBACD,EAAC,+CAAe,0BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEA,YAAM,oBACJ,+CAAe,gBAAe,eAAe;AAE/C,aAAO;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEO,SAAS,yBACd,aACA,sBACA,aAOA;AACA,SAAO;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe,IAAA;AACrB,MAAM,kBAAkB;AACxB,MAAM,WAAW,CAAC,QAAgB,OAAwB,WAAiB;AACzE,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,IAAI,EAAE,OAAO,IAAI,8BAA8B,MAAM;AAC7D,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
1
|
+
{"version":3,"file":"storefront-client.mjs","sources":["../../src/storefront-client.ts"],"sourcesContent":["import {SFAPI_VERSION} from './storefront-api-constants.js';\n\nexport type StorefrontClientProps = {\n /** The host name of the domain (eg: `{shop}.myshopify.com`). */\n storeDomain?: string;\n /** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */\n privateStorefrontToken?: string;\n /** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */\n publicStorefrontToken?: 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 * 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 * Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`\n */\n contentType?: 'json' | 'graphql';\n};\n\nconst MOCK_SHOP_DOMAIN = 'mock.shop';\nconst isMockShop = (domain: string): boolean =>\n domain.includes(MOCK_SHOP_DOMAIN);\n\n/**\n * The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API.\n *\n * When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.\n */\nexport function createStorefrontClient({\n storeDomain,\n privateStorefrontToken,\n publicStorefrontToken,\n storefrontApiVersion = SFAPI_VERSION,\n contentType,\n}: StorefrontClientProps): StorefrontClientReturn {\n if (!storeDomain) {\n if (__HYDROGEN_DEV__) {\n storeDomain = MOCK_SHOP_DOMAIN;\n warnOnce(\n `storeDomain missing, defaulting to ${MOCK_SHOP_DOMAIN}`,\n 'info',\n );\n } else {\n throw new Error(\n H2_PREFIX_ERROR +\n `\\`storeDomain\\` is required when creating a new Storefront client in production.`,\n );\n }\n }\n\n if (storefrontApiVersion !== SFAPI_VERSION) {\n warnOnce(\n `The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +\n `\\nYou may run into unexpected errors if these versions don't match. Received version: \"${storefrontApiVersion}\"; expected version \"${SFAPI_VERSION}\"`,\n );\n }\n\n // only warn if not in a browser environment\n if (\n __HYDROGEN_DEV__ &&\n !privateStorefrontToken &&\n !globalThis.document &&\n !isMockShop(storeDomain)\n ) {\n warnOnce(\n `Using a private storefront token is recommended for server environments.` +\n `\\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,\n );\n }\n\n // only warn if in a browser environment and you're using the privateStorefrontToken\n if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {\n warnOnce(\n 'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +\n '\\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',\n );\n }\n\n const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (\n overrideProps,\n ) => {\n const domain = overrideProps?.storeDomain ?? storeDomain;\n return domain.includes('://') ? domain : `https://${domain}`;\n };\n\n return {\n getShopifyDomain,\n getStorefrontApiUrl(overrideProps): string {\n const domain = getShopifyDomain(overrideProps);\n const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');\n\n return `${apiUrl}/${\n overrideProps?.storefrontApiVersion ?? storefrontApiVersion\n }/graphql.json`;\n },\n getPrivateTokenHeaders(overrideProps): Record<string, string> {\n if (\n !privateStorefrontToken &&\n !overrideProps?.privateStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',\n );\n }\n\n if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {\n warnOnce(\n 'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',\n );\n }\n\n const finalContentType = overrideProps?.contentType ?? contentType;\n\n return {\n // default to json\n 'content-type':\n finalContentType === 'graphql'\n ? 'application/graphql'\n : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'Shopify-Storefront-Private-Token':\n overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',\n ...(overrideProps?.buyerIp\n ? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}\n : {}),\n };\n },\n getPublicTokenHeaders(overrideProps): Record<string, string> {\n if (\n !publicStorefrontToken &&\n !overrideProps?.publicStorefrontToken &&\n !isMockShop(storeDomain)\n ) {\n throw new Error(\n H2_PREFIX_ERROR +\n 'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',\n );\n }\n\n const finalContentType =\n overrideProps?.contentType ?? contentType ?? 'json';\n\n return getPublicTokenHeadersRaw(\n finalContentType,\n storefrontApiVersion,\n overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',\n );\n },\n };\n}\n\nexport function getPublicTokenHeadersRaw(\n contentType: 'graphql' | 'json',\n storefrontApiVersion: string,\n accessToken: string,\n): {\n 'content-type': string;\n 'X-SDK-Variant': string;\n 'X-SDK-Variant-Source': string;\n 'X-SDK-Version': string;\n 'X-Shopify-Storefront-Access-Token': string;\n} {\n return {\n // default to json\n 'content-type':\n contentType === 'graphql' ? 'application/graphql' : 'application/json',\n 'X-SDK-Variant': 'hydrogen-react',\n 'X-SDK-Variant-Source': 'react',\n 'X-SDK-Version': storefrontApiVersion,\n 'X-Shopify-Storefront-Access-Token': accessToken,\n };\n}\n\nconst warnings = new Set<string>();\nconst H2_PREFIX_ERROR = '[h2:error:createStorefrontClient] ';\nconst warnOnce = (string: string, type: 'warn' | 'info' = 'warn'): void => {\n if (!warnings.has(string)) {\n console[type](`[h2:${type}:createStorefrontClient] ` + string);\n warnings.add(string);\n }\n};\n\ntype OverrideTokenHeaderProps = Partial<\n Pick<StorefrontClientProps, 'contentType'>\n>;\n\ntype StorefrontClientReturn = {\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 `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:\n *\n * - `storeDomain`\n */\n getShopifyDomain: (\n props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,\n ) => string;\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 calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:\n *\n * - `storeDomain`\n * - `storefrontApiVersion`\n */\n getStorefrontApiUrl: (\n props?: Partial<\n Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>\n >,\n ) => string;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:\n *\n * - `contentType`\n * - `privateStorefrontToken`\n * - `buyerIp`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPrivateTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'privateStorefrontToken'> & {\n /**\n * The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.\n */\n buyerIp?: string;\n },\n ) => Record<string, string>;\n /**\n * Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.\n *\n * By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:\n *\n * - `contentType`\n * - `publicStorefrontToken`\n *\n * Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.\n */\n getPublicTokenHeaders: (\n props?: OverrideTokenHeaderProps &\n Pick<StorefrontClientProps, 'publicStorefrontToken'>,\n ) => Record<string, string>;\n};\n"],"names":[],"mappings":";AAmBA,MAAM,mBAAmB;AACzB,MAAM,aAAa,CAAC,WAClB,OAAO,SAAS,gBAAgB;AA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AAAA,QACjB,qCACE,+CAAe,2BAA0B,0BAA0B;AAAA,QACrE,IAAI,+CAAe,WACf,EAAC,+BAA+B,cAAc,QAAA,IAC9C,CAAA;AAAA,MAAC;AAAA,IAET;AAAA,IACA,sBAAsB,eAAuC;AAC3D,UACE,CAAC,yBACD,EAAC,+CAAe,0BAChB,CAAC,WAAW,WAAW,GACvB;AACA,cAAM,IAAI;AAAA,UACR,kBACE;AAAA,QAAA;AAAA,MAEN;AAEA,YAAM,oBACJ,+CAAe,gBAAe,eAAe;AAE/C,aAAO;AAAA,QACL;AAAA,QACA;AAAA,SACA,+CAAe,0BAAyB,yBAAyB;AAAA,MAAA;AAAA,IAErE;AAAA,EAAA;AAEJ;AAEO,SAAS,yBACd,aACA,sBACA,aAOA;AACA,SAAO;AAAA;AAAA,IAEL,gBACE,gBAAgB,YAAY,wBAAwB;AAAA,IACtD,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,IACxB,iBAAiB;AAAA,IACjB,qCAAqC;AAAA,EAAA;AAEzC;AAEA,MAAM,+BAAe,IAAA;AACrB,MAAM,kBAAkB;AACxB,MAAM,WAAW,CAAC,QAAgB,OAAwB,WAAiB;AACzE,MAAI,CAAC,SAAS,IAAI,MAAM,GAAG;AACzB,YAAQ,IAAI,EAAE,OAAO,IAAI,8BAA8B,MAAM;AAC7D,aAAS,IAAI,MAAM;AAAA,EACrB;AACF;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCartAPIStateMachine.mjs","sources":["../../src/useCartAPIStateMachine.tsx"],"sourcesContent":["import {useMachine} from '@xstate/react/fsm';\nimport {createMachine, assign, StateMachine} from '@xstate/fsm';\nimport {\n Cart,\n CartMachineActionEvent,\n CartMachineActions,\n CartMachineContext,\n CartMachineEvent,\n CartMachineFetchResultEvent,\n CartMachineTypeState,\n} from './cart-types.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {useCartActions} from './useCartActions.js';\nimport {useMemo} from 'react';\nimport {InitEvent} from '@xstate/fsm/lib/types.js';\nimport {\n CountryCode,\n Cart as CartType,\n LanguageCode,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nfunction invokeCart(\n action: keyof CartMachineActions,\n options?: {\n entryActions?: [keyof CartMachineActions];\n resolveTarget?: CartMachineTypeState['value'];\n errorTarget?: CartMachineTypeState['value'];\n exitActions?: [keyof CartMachineActions];\n },\n): StateMachine.Config<CartMachineContext, CartMachineEvent>['states']['on'] {\n return {\n entry: [\n ...(options?.entryActions || []),\n assign({\n lastValidCart: (context) => context?.cart,\n }),\n 'onCartActionEntry',\n 'onCartActionOptimisticUI',\n action,\n ],\n on: {\n RESOLVE: {\n target: options?.resolveTarget || 'idle',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (_, event) => event?.payload?.cart,\n rawCartResult: (_, event) => event?.payload?.rawCartResult,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n ],\n },\n ERROR: {\n target: options?.errorTarget || 'error',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (context) => context?.lastValidCart,\n errors: (_, event) => event?.payload?.errors,\n }),\n ],\n },\n CART_COMPLETED: {\n target: 'cartCompleted',\n actions: assign({\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prevCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n cart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n lastValidCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rawCartResult: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n },\n },\n exit: ['onCartActionComplete', ...(options?.exitActions || [])],\n };\n}\n\nconst INITIALIZING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['uninitialized']['on'] = {\n CART_FETCH: {\n target: 'cartFetching',\n },\n CART_CREATE: {\n target: 'cartCreating',\n },\n CART_SET: {\n target: 'idle',\n actions: [\n assign({\n rawCartResult: (_, event) => event.payload.cart,\n cart: (_, event) => cartFromGraphQL(event.payload.cart),\n }),\n ],\n },\n};\n\nconst UPDATING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['idle']['on'] = {\n CARTLINE_ADD: {\n target: 'cartLineAdding',\n },\n CARTLINE_UPDATE: {\n target: 'cartLineUpdating',\n },\n CARTLINE_REMOVE: {\n target: 'cartLineRemoving',\n },\n NOTE_UPDATE: {\n target: 'noteUpdating',\n },\n BUYER_IDENTITY_UPDATE: {\n target: 'buyerIdentityUpdating',\n },\n CART_ATTRIBUTES_UPDATE: {\n target: 'cartAttributesUpdating',\n },\n DISCOUNT_CODES_UPDATE: {\n target: 'discountCodesUpdating',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nfunction createCartMachine(\n initialCart?: PartialDeep<CartType, {recurseIntoArrays: true}>,\n) {\n return createMachine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n >({\n id: 'Cart',\n initial: initialCart ? 'idle' : 'uninitialized',\n context: {\n cart: initialCart && cartFromGraphQL(initialCart),\n },\n states: {\n uninitialized: {\n on: INITIALIZING_CART_EVENTS,\n },\n cartCompleted: {\n on: INITIALIZING_CART_EVENTS,\n },\n initializationError: {\n on: INITIALIZING_CART_EVENTS,\n },\n idle: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n error: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n cartFetching: invokeCart('cartFetchAction', {\n errorTarget: 'initializationError',\n }),\n cartCreating: invokeCart('cartCreateAction', {\n errorTarget: 'initializationError',\n }),\n cartLineRemoving: invokeCart('cartLineRemoveAction'),\n cartLineUpdating: invokeCart('cartLineUpdateAction'),\n cartLineAdding: invokeCart('cartLineAddAction'),\n noteUpdating: invokeCart('noteUpdateAction'),\n buyerIdentityUpdating: invokeCart('buyerIdentityUpdateAction'),\n cartAttributesUpdating: invokeCart('cartAttributesUpdateAction'),\n discountCodesUpdating: invokeCart('discountCodesUpdateAction'),\n },\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartAPIStateMachine({\n numCartLines,\n onCartActionEntry,\n onCartActionOptimisticUI,\n onCartActionComplete,\n data: cart,\n cartFragment,\n countryCode,\n languageCode,\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked just before a Cart API action executes. */\n onCartActionEntry?: (\n context: CartMachineContext,\n event: CartMachineActionEvent,\n ) => void;\n /** A callback that is invoked after executing the entry actions for optimistic UI changes. */\n onCartActionOptimisticUI?: (\n context: CartMachineContext,\n event: CartMachineEvent,\n ) => Partial<CartMachineContext>;\n /** A callback that is invoked after a Cart API completes. */\n onCartActionComplete?: (\n context: CartMachineContext,\n event: CartMachineFetchResultEvent,\n ) => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-10/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-10/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n /** The ISO language code for i18n. */\n languageCode?: LanguageCode;\n}) {\n const {\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n } = useCartActions({\n numCartLines,\n cartFragment,\n countryCode,\n languageCode,\n });\n\n const cartMachine = useMemo(() => createCartMachine(cart), [cart]);\n\n const [state, send, service] = useMachine(cartMachine, {\n actions: {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartFetchAction: async (_, event) => {\n if (event.type !== 'CART_FETCH') return;\n\n const {data, errors} = await cartFetch(event?.payload?.cartId);\n const resultEvent = eventFromFetchResult(event, data?.cart, errors);\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartCreateAction: async (_, event) => {\n if (event.type !== 'CART_CREATE') return;\n\n const {data, errors} = await cartCreate(event?.payload);\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartCreate?.cart,\n errors,\n );\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineAddAction: async (context, event) => {\n if (event.type !== 'CARTLINE_ADD' || !context?.cart?.id) return;\n\n const {data, errors} = await cartLineAdd(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesAdd?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineUpdateAction: async (context, event) => {\n if (event.type !== 'CARTLINE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineUpdate(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineRemoveAction: async (context, event) => {\n if (event.type !== 'CARTLINE_REMOVE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineRemove(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesRemove?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n noteUpdateAction: async (context, event) => {\n if (event.type !== 'NOTE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await noteUpdate(\n context.cart.id,\n event.payload.note,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartNoteUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n buyerIdentityUpdateAction: async (context, event) => {\n if (event.type !== 'BUYER_IDENTITY_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await buyerIdentityUpdate(\n context.cart.id,\n event.payload.buyerIdentity,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartBuyerIdentityUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartAttributesUpdateAction: async (context, event) => {\n if (event.type !== 'CART_ATTRIBUTES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await cartAttributesUpdate(\n context.cart.id,\n event.payload.attributes,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartAttributesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n discountCodesUpdateAction: async (context, event) => {\n if (event.type !== 'DISCOUNT_CODES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await discountCodesUpdate(\n context.cart.id,\n event.payload.discountCodes,\n );\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartDiscountCodesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n ...(onCartActionEntry && {\n onCartActionEntry: (context, event): void => {\n if (isCartActionEvent(event)) {\n onCartActionEntry(context, event);\n }\n },\n }),\n ...(onCartActionOptimisticUI && {\n onCartActionOptimisticUI: assign((context, event) => {\n return onCartActionOptimisticUI(context, event);\n }),\n }),\n ...(onCartActionComplete && {\n onCartActionComplete: (context, event): void => {\n if (isCartFetchResultEvent(event)) {\n onCartActionComplete(context, event);\n }\n },\n }),\n } as CartMachineActions,\n });\n\n return useMemo(() => [state, send, service] as const, [state, send, service]);\n}\n\nexport function cartFromGraphQL(\n cart: PartialDeep<CartType, {recurseIntoArrays: true}>,\n): Cart {\n return {\n ...cart,\n lines: flattenConnection(cart?.lines),\n note: cart.note ?? undefined,\n };\n}\n\nfunction eventFromFetchResult(\n cartActionEvent: CartMachineActionEvent,\n cart?: PartialDeep<CartType, {recurseIntoArrays: true}> | null,\n errors?: unknown,\n): CartMachineFetchResultEvent {\n if (errors) {\n return {type: 'ERROR', payload: {errors, cartActionEvent}};\n }\n\n if (!cart) {\n return {\n type: 'CART_COMPLETED',\n payload: {\n cartActionEvent,\n },\n };\n }\n\n return {\n type: 'RESOLVE',\n payload: {\n cart: cartFromGraphQL(cart),\n rawCartResult: cart,\n cartActionEvent,\n },\n };\n}\n\nfunction isCartActionEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineActionEvent {\n return (\n event.type === 'CART_CREATE' ||\n event.type === 'CARTLINE_ADD' ||\n event.type === 'CARTLINE_UPDATE' ||\n event.type === 'CARTLINE_REMOVE' ||\n event.type === 'NOTE_UPDATE' ||\n event.type === 'BUYER_IDENTITY_UPDATE' ||\n event.type === 'CART_ATTRIBUTES_UPDATE' ||\n event.type === 'DISCOUNT_CODES_UPDATE'\n );\n}\n\nfunction isCartFetchResultEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineFetchResultEvent {\n return (\n event.type === 'RESOLVE' ||\n event.type === 'ERROR' ||\n event.type === 'CART_COMPLETED'\n );\n}\n"],"names":["assign","createMachine"],"mappings":";;;;;AAsBA,SAAS,WACP,QACA,SAM2E;AAC3E,SAAO;AAAA,IACL,OAAO;AAAA,MACL,IAAI,mCAAS,iBAAgB,CAAA;AAAA,MAC7BA,EAAO;AAAA,QACL,eAAe,CAAC,YAAY,mCAAS;AAAA,MAAA,CACtC;AAAA,MACD;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,IAEF,IAAI;AAAA,MACF,SAAS;AAAA,QACP,SAAQ,mCAAS,kBAAiB;AAAA,QAClC,SAAS;AAAA,UACPA,EAAO;AAAA,YACL,UAAU,CAAC,YAAY,mCAAS;AAAA,YAChC,MAAM,CAAC,GAAG,UAAA;;AAAU,0DAAO,YAAP,mBAAgB;AAAA;AAAA,YACpC,eAAe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QACF;AAAA,MAAA;AAAA,IACF;AAAA,EACF,CACD;AAED,SAAO,QAAQ,MAAM,CAAC,OAAO,MAAM,OAAO,GAAY,CAAC,OAAO,MAAM,OAAO,CAAC;AAC9E;AAEO,SAAS,gBACd,MACM;AACN,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,kBAAkB,6BAAM,KAAK;AAAA,IACpC,MAAM,KAAK,QAAQ;AAAA,EAAA;AAEvB;AAEA,SAAS,qBACP,iBACA,MACA,QAC6B;AAC7B,MAAI,QAAQ;AACV,WAAO,EAAC,MAAM,SAAS,SAAS,EAAC,QAAQ,kBAAe;AAAA,EAC1D;AAEA,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,QACP;AAAA,MAAA;AAAA,IACF;AAAA,EAEJ;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,MACP,MAAM,gBAAgB,IAAI;AAAA,MAC1B,eAAe;AAAA,MACf;AAAA,IAAA;AAAA,EACF;AAEJ;AAEA,SAAS,kBACP,OACiC;AACjC,SACE,MAAM,SAAS,iBACf,MAAM,SAAS,kBACf,MAAM,SAAS,qBACf,MAAM,SAAS,qBACf,MAAM,SAAS,iBACf,MAAM,SAAS,2BACf,MAAM,SAAS,4BACf,MAAM,SAAS;AAEnB;AAEA,SAAS,uBACP,OACsC;AACtC,SACE,MAAM,SAAS,aACf,MAAM,SAAS,WACf,MAAM,SAAS;AAEnB;"}
|
|
1
|
+
{"version":3,"file":"useCartAPIStateMachine.mjs","sources":["../../src/useCartAPIStateMachine.tsx"],"sourcesContent":["import {useMachine} from '@xstate/react/fsm';\nimport {createMachine, assign, StateMachine} from '@xstate/fsm';\nimport {\n Cart,\n CartMachineActionEvent,\n CartMachineActions,\n CartMachineContext,\n CartMachineEvent,\n CartMachineFetchResultEvent,\n CartMachineTypeState,\n} from './cart-types.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {useCartActions} from './useCartActions.js';\nimport {useMemo} from 'react';\nimport {InitEvent} from '@xstate/fsm/lib/types.js';\nimport {\n CountryCode,\n Cart as CartType,\n LanguageCode,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nfunction invokeCart(\n action: keyof CartMachineActions,\n options?: {\n entryActions?: [keyof CartMachineActions];\n resolveTarget?: CartMachineTypeState['value'];\n errorTarget?: CartMachineTypeState['value'];\n exitActions?: [keyof CartMachineActions];\n },\n): StateMachine.Config<CartMachineContext, CartMachineEvent>['states']['on'] {\n return {\n entry: [\n ...(options?.entryActions || []),\n assign({\n lastValidCart: (context) => context?.cart,\n }),\n 'onCartActionEntry',\n 'onCartActionOptimisticUI',\n action,\n ],\n on: {\n RESOLVE: {\n target: options?.resolveTarget || 'idle',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (_, event) => event?.payload?.cart,\n rawCartResult: (_, event) => event?.payload?.rawCartResult,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n ],\n },\n ERROR: {\n target: options?.errorTarget || 'error',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (context) => context?.lastValidCart,\n errors: (_, event) => event?.payload?.errors,\n }),\n ],\n },\n CART_COMPLETED: {\n target: 'cartCompleted',\n actions: assign({\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prevCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n cart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n lastValidCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rawCartResult: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n },\n },\n exit: ['onCartActionComplete', ...(options?.exitActions || [])],\n };\n}\n\nconst INITIALIZING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['uninitialized']['on'] = {\n CART_FETCH: {\n target: 'cartFetching',\n },\n CART_CREATE: {\n target: 'cartCreating',\n },\n CART_SET: {\n target: 'idle',\n actions: [\n assign({\n rawCartResult: (_, event) => event.payload.cart,\n cart: (_, event) => cartFromGraphQL(event.payload.cart),\n }),\n ],\n },\n};\n\nconst UPDATING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['idle']['on'] = {\n CARTLINE_ADD: {\n target: 'cartLineAdding',\n },\n CARTLINE_UPDATE: {\n target: 'cartLineUpdating',\n },\n CARTLINE_REMOVE: {\n target: 'cartLineRemoving',\n },\n NOTE_UPDATE: {\n target: 'noteUpdating',\n },\n BUYER_IDENTITY_UPDATE: {\n target: 'buyerIdentityUpdating',\n },\n CART_ATTRIBUTES_UPDATE: {\n target: 'cartAttributesUpdating',\n },\n DISCOUNT_CODES_UPDATE: {\n target: 'discountCodesUpdating',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nfunction createCartMachine(\n initialCart?: PartialDeep<CartType, {recurseIntoArrays: true}>,\n) {\n return createMachine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n >({\n id: 'Cart',\n initial: initialCart ? 'idle' : 'uninitialized',\n context: {\n cart: initialCart && cartFromGraphQL(initialCart),\n },\n states: {\n uninitialized: {\n on: INITIALIZING_CART_EVENTS,\n },\n cartCompleted: {\n on: INITIALIZING_CART_EVENTS,\n },\n initializationError: {\n on: INITIALIZING_CART_EVENTS,\n },\n idle: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n error: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n cartFetching: invokeCart('cartFetchAction', {\n errorTarget: 'initializationError',\n }),\n cartCreating: invokeCart('cartCreateAction', {\n errorTarget: 'initializationError',\n }),\n cartLineRemoving: invokeCart('cartLineRemoveAction'),\n cartLineUpdating: invokeCart('cartLineUpdateAction'),\n cartLineAdding: invokeCart('cartLineAddAction'),\n noteUpdating: invokeCart('noteUpdateAction'),\n buyerIdentityUpdating: invokeCart('buyerIdentityUpdateAction'),\n cartAttributesUpdating: invokeCart('cartAttributesUpdateAction'),\n discountCodesUpdating: invokeCart('discountCodesUpdateAction'),\n },\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartAPIStateMachine({\n numCartLines,\n onCartActionEntry,\n onCartActionOptimisticUI,\n onCartActionComplete,\n data: cart,\n cartFragment,\n countryCode,\n languageCode,\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked just before a Cart API action executes. */\n onCartActionEntry?: (\n context: CartMachineContext,\n event: CartMachineActionEvent,\n ) => void;\n /** A callback that is invoked after executing the entry actions for optimistic UI changes. */\n onCartActionOptimisticUI?: (\n context: CartMachineContext,\n event: CartMachineEvent,\n ) => Partial<CartMachineContext>;\n /** A callback that is invoked after a Cart API completes. */\n onCartActionComplete?: (\n context: CartMachineContext,\n event: CartMachineFetchResultEvent,\n ) => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2026-01/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2026-01/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n /** The ISO language code for i18n. */\n languageCode?: LanguageCode;\n}) {\n const {\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n } = useCartActions({\n numCartLines,\n cartFragment,\n countryCode,\n languageCode,\n });\n\n const cartMachine = useMemo(() => createCartMachine(cart), [cart]);\n\n const [state, send, service] = useMachine(cartMachine, {\n actions: {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartFetchAction: async (_, event) => {\n if (event.type !== 'CART_FETCH') return;\n\n const {data, errors} = await cartFetch(event?.payload?.cartId);\n const resultEvent = eventFromFetchResult(event, data?.cart, errors);\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartCreateAction: async (_, event) => {\n if (event.type !== 'CART_CREATE') return;\n\n const {data, errors} = await cartCreate(event?.payload);\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartCreate?.cart,\n errors,\n );\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineAddAction: async (context, event) => {\n if (event.type !== 'CARTLINE_ADD' || !context?.cart?.id) return;\n\n const {data, errors} = await cartLineAdd(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesAdd?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineUpdateAction: async (context, event) => {\n if (event.type !== 'CARTLINE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineUpdate(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineRemoveAction: async (context, event) => {\n if (event.type !== 'CARTLINE_REMOVE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineRemove(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesRemove?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n noteUpdateAction: async (context, event) => {\n if (event.type !== 'NOTE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await noteUpdate(\n context.cart.id,\n event.payload.note,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartNoteUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n buyerIdentityUpdateAction: async (context, event) => {\n if (event.type !== 'BUYER_IDENTITY_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await buyerIdentityUpdate(\n context.cart.id,\n event.payload.buyerIdentity,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartBuyerIdentityUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartAttributesUpdateAction: async (context, event) => {\n if (event.type !== 'CART_ATTRIBUTES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await cartAttributesUpdate(\n context.cart.id,\n event.payload.attributes,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartAttributesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n discountCodesUpdateAction: async (context, event) => {\n if (event.type !== 'DISCOUNT_CODES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await discountCodesUpdate(\n context.cart.id,\n event.payload.discountCodes,\n );\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartDiscountCodesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n ...(onCartActionEntry && {\n onCartActionEntry: (context, event): void => {\n if (isCartActionEvent(event)) {\n onCartActionEntry(context, event);\n }\n },\n }),\n ...(onCartActionOptimisticUI && {\n onCartActionOptimisticUI: assign((context, event) => {\n return onCartActionOptimisticUI(context, event);\n }),\n }),\n ...(onCartActionComplete && {\n onCartActionComplete: (context, event): void => {\n if (isCartFetchResultEvent(event)) {\n onCartActionComplete(context, event);\n }\n },\n }),\n } as CartMachineActions,\n });\n\n return useMemo(() => [state, send, service] as const, [state, send, service]);\n}\n\nexport function cartFromGraphQL(\n cart: PartialDeep<CartType, {recurseIntoArrays: true}>,\n): Cart {\n return {\n ...cart,\n lines: flattenConnection(cart?.lines),\n note: cart.note ?? undefined,\n };\n}\n\nfunction eventFromFetchResult(\n cartActionEvent: CartMachineActionEvent,\n cart?: PartialDeep<CartType, {recurseIntoArrays: true}> | null,\n errors?: unknown,\n): CartMachineFetchResultEvent {\n if (errors) {\n return {type: 'ERROR', payload: {errors, cartActionEvent}};\n }\n\n if (!cart) {\n return {\n type: 'CART_COMPLETED',\n payload: {\n cartActionEvent,\n },\n };\n }\n\n return {\n type: 'RESOLVE',\n payload: {\n cart: cartFromGraphQL(cart),\n rawCartResult: cart,\n cartActionEvent,\n },\n };\n}\n\nfunction isCartActionEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineActionEvent {\n return (\n event.type === 'CART_CREATE' ||\n event.type === 'CARTLINE_ADD' ||\n event.type === 'CARTLINE_UPDATE' ||\n event.type === 'CARTLINE_REMOVE' ||\n event.type === 'NOTE_UPDATE' ||\n event.type === 'BUYER_IDENTITY_UPDATE' ||\n event.type === 'CART_ATTRIBUTES_UPDATE' ||\n event.type === 'DISCOUNT_CODES_UPDATE'\n );\n}\n\nfunction isCartFetchResultEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineFetchResultEvent {\n return (\n event.type === 'RESOLVE' ||\n event.type === 'ERROR' ||\n event.type === 'CART_COMPLETED'\n );\n}\n"],"names":["assign","createMachine"],"mappings":";;;;;AAsBA,SAAS,WACP,QACA,SAM2E;AAC3E,SAAO;AAAA,IACL,OAAO;AAAA,MACL,IAAI,mCAAS,iBAAgB,CAAA;AAAA,MAC7BA,EAAO;AAAA,QACL,eAAe,CAAC,YAAY,mCAAS;AAAA,MAAA,CACtC;AAAA,MACD;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,IAEF,IAAI;AAAA,MACF,SAAS;AAAA,QACP,SAAQ,mCAAS,kBAAiB;AAAA,QAClC,SAAS;AAAA,UACPA,EAAO;AAAA,YACL,UAAU,CAAC,YAAY,mCAAS;AAAA,YAChC,MAAM,CAAC,GAAG,UAAA;;AAAU,0DAAO,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CAAqB,SAAS,KAAK;AAAA,UACrC;AAAA,QACF;AAAA,MAAA;AAAA,IACF;AAAA,EACF,CACD;AAED,SAAO,QAAQ,MAAM,CAAC,OAAO,MAAM,OAAO,GAAY,CAAC,OAAO,MAAM,OAAO,CAAC;AAC9E;AAEO,SAAS,gBACd,MACM;AACN,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,kBAAkB,6BAAM,KAAK;AAAA,IACpC,MAAM,KAAK,QAAQ;AAAA,EAAA;AAEvB;AAEA,SAAS,qBACP,iBACA,MACA,QAC6B;AAC7B,MAAI,QAAQ;AACV,WAAO,EAAC,MAAM,SAAS,SAAS,EAAC,QAAQ,kBAAe;AAAA,EAC1D;AAEA,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,QACP;AAAA,MAAA;AAAA,IACF;AAAA,EAEJ;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,MACP,MAAM,gBAAgB,IAAI;AAAA,MAC1B,eAAe;AAAA,MACf;AAAA,IAAA;AAAA,EACF;AAEJ;AAEA,SAAS,kBACP,OACiC;AACjC,SACE,MAAM,SAAS,iBACf,MAAM,SAAS,kBACf,MAAM,SAAS,qBACf,MAAM,SAAS,qBACf,MAAM,SAAS,iBACf,MAAM,SAAS,2BACf,MAAM,SAAS,4BACf,MAAM,SAAS;AAEnB;AAEA,SAAS,uBACP,OACsC;AACtC,SACE,MAAM,SAAS,aACf,MAAM,SAAS,WACf,MAAM,SAAS;AAEnB;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCartActions.mjs","sources":["../../src/useCartActions.tsx"],"sourcesContent":["import {useCallback, useMemo} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n LanguageCode,\n Cart as CartType,\n MutationCartDiscountCodesUpdateArgs,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n CartAttributesUpdate,\n CartBuyerIdentityUpdate,\n CartCreate,\n CartDiscountCodesUpdate,\n CartLineAdd,\n CartLineRemove,\n CartLineUpdate,\n CartNoteUpdate,\n CartQuery,\n} from './cart-queries.js';\nimport {useCartFetch} from './cart-hooks.js';\nimport {PartialDeep} from 'type-fest';\n\ntype CartResponse = PartialDeep<CartType, {recurseIntoArrays: true}>;\n\n/**\n * The `useCartActions` hook returns helper graphql functions for Storefront Cart API\n *\n * See [cart API graphql mutations](https://shopify.dev/api/storefront/
|
|
1
|
+
{"version":3,"file":"useCartActions.mjs","sources":["../../src/useCartActions.tsx"],"sourcesContent":["import {useCallback, useMemo} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n LanguageCode,\n Cart as CartType,\n MutationCartDiscountCodesUpdateArgs,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n CartAttributesUpdate,\n CartBuyerIdentityUpdate,\n CartCreate,\n CartDiscountCodesUpdate,\n CartLineAdd,\n CartLineRemove,\n CartLineUpdate,\n CartNoteUpdate,\n CartQuery,\n} from './cart-queries.js';\nimport {useCartFetch} from './cart-hooks.js';\nimport {PartialDeep} from 'type-fest';\n\ntype CartResponse = PartialDeep<CartType, {recurseIntoArrays: true}>;\n\n/**\n * The `useCartActions` hook returns helper graphql functions for Storefront Cart API\n *\n * See [cart API graphql mutations](https://shopify.dev/api/storefront/2026-01/objects/Cart)\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartActions({\n numCartLines,\n cartFragment,\n countryCode = 'US',\n languageCode = 'EN',\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2026-01/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. Default to `US` */\n countryCode?: CountryCode;\n /** The ISO language code for i18n. Default to `EN` */\n languageCode?: LanguageCode;\n}) {\n const fetchCart = useCartFetch();\n\n const cartFetch = useCallback(\n (cartId: string) => {\n return fetchCart<{cart: CartResponse}>({\n query: CartQuery(cartFragment),\n variables: {\n id: cartId,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [fetchCart, cartFragment, numCartLines, countryCode, languageCode],\n );\n\n const cartCreate = useCallback(\n (cart: CartInput) => {\n return fetchCart<{cartCreate: {cart: CartResponse}}>({\n query: CartCreate(cartFragment),\n variables: {\n input: cart,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines, languageCode],\n );\n\n const cartLineAdd = useCallback(\n (cartId: string, lines: CartLineInput[]) => {\n return fetchCart<{cartLinesAdd: {cart: CartResponse}}>({\n query: CartLineAdd(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines, languageCode],\n );\n\n const cartLineUpdate = useCallback(\n (cartId: string, lines: CartLineUpdateInput[]) => {\n return fetchCart<{cartLinesUpdate: {cart: CartResponse}}>({\n query: CartLineUpdate(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines, languageCode],\n );\n\n const cartLineRemove = useCallback(\n (cartId: string, lines: string[]) => {\n return fetchCart<{cartLinesRemove: {cart: CartResponse}}>({\n query: CartLineRemove(cartFragment),\n variables: {\n cartId,\n lines,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines, languageCode],\n );\n\n const noteUpdate = useCallback(\n (cartId: string, note: MutationCartNoteUpdateArgs['note']) => {\n return fetchCart<{cartNoteUpdate: {cart: CartResponse}}>({\n query: CartNoteUpdate(cartFragment),\n variables: {\n cartId,\n note,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [fetchCart, cartFragment, numCartLines, countryCode, languageCode],\n );\n\n const buyerIdentityUpdate = useCallback(\n (cartId: string, buyerIdentity: CartBuyerIdentityInput) => {\n return fetchCart<{cartBuyerIdentityUpdate: {cart: CartResponse}}>({\n query: CartBuyerIdentityUpdate(cartFragment),\n variables: {\n cartId,\n buyerIdentity,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines, languageCode],\n );\n\n const cartAttributesUpdate = useCallback(\n (cartId: string, attributes: AttributeInput[]) => {\n return fetchCart<{cartAttributesUpdate: {cart: CartResponse}}>({\n query: CartAttributesUpdate(cartFragment),\n variables: {\n cartId,\n attributes,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines, languageCode],\n );\n\n const discountCodesUpdate = useCallback(\n (\n cartId: string,\n discountCodes: MutationCartDiscountCodesUpdateArgs['discountCodes'],\n ) => {\n return fetchCart<{cartDiscountCodesUpdate: {cart: CartResponse}}>({\n query: CartDiscountCodesUpdate(cartFragment),\n variables: {\n cartId,\n discountCodes,\n numCartLines,\n country: countryCode,\n language: languageCode,\n },\n });\n },\n [cartFragment, countryCode, fetchCart, numCartLines, languageCode],\n );\n\n return useMemo(\n () => ({\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n cartFragment,\n }),\n [\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n cartFragment,\n ],\n );\n}\n"],"names":[],"mappings":";;;AAmCO,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,eAAe;AACjB,GASG;AACD,QAAM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ACT,UAAU;AAAA,QAAA;AAAA,MACZ,CACD;AAAA,IACH;AAAA,IACA,CAAC,cAAc,aAAa,WAAW,cAAc,YAAY;AAAA,EAAA;AAGnE,SAAO;AAAA,IACL,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,IAEF;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAEJ;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useMoney.mjs","sources":["../../src/useMoney.tsx"],"sourcesContent":["import {useMemo} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {\n CurrencyCode as StorefrontApiCurrencyCode,\n MoneyV2 as StorefrontApiMoneyV2,\n} from './storefront-api-types.js';\nimport type {\n MoneyV2 as CustomerAccountApiMoneyV2,\n CurrencyCode as CustomerAccountApiCurrencyCode,\n} from './customer-account-api-types.js';\n\n// Support MoneyV2 from both Storefront API and Customer Account API\n// The APIs may have different CurrencyCode enums\n/**\n * Supports MoneyV2 from both Storefront API and Customer Account API.\n * The APIs may have different CurrencyCode enums (e.g., Customer Account API added USDC in 2025-10, but Storefront API doesn't support USDC in 2025-10).\n * This union type ensures useMoney works with data from either API.\n */\ntype MoneyV2 = StorefrontApiMoneyV2 | CustomerAccountApiMoneyV2;\n\n/**\n * Supports CurrencyCode from both Storefront API and Customer Account API. The APIs may have different CurrencyCode enums (e.g., Customer Account API added USDC in 2025-10, but Storefront API doesn't support USDC in 2025-10).\n * This union type ensures useMoney works with data from either API.\n */\ntype CurrencyCode = StorefrontApiCurrencyCode | CustomerAccountApiCurrencyCode;\n\nexport type UseMoneyValue = {\n /**\n * The currency code from the `MoneyV2` object.\n */\n currencyCode: CurrencyCode;\n /**\n * The name for the currency code, returned by `Intl.NumberFormat`.\n */\n currencyName?: string;\n /**\n * The currency symbol returned by `Intl.NumberFormat`.\n */\n currencySymbol?: string;\n /**\n * The currency narrow symbol returned by `Intl.NumberFormat`.\n */\n currencyNarrowSymbol?: string;\n /**\n * The localized amount, without any currency symbols or non-number types from the `Intl.NumberFormat.formatToParts` parts.\n */\n amount: string;\n /**\n * All parts returned by `Intl.NumberFormat.formatToParts`.\n */\n parts: Intl.NumberFormatPart[];\n /**\n * A string returned by `new Intl.NumberFormat` for the amount and currency code,\n * using the `locale` value in the [`LocalizationProvider` component](https://shopify.dev/api/hydrogen/components/localization/localizationprovider).\n */\n localizedString: string;\n /**\n * The `MoneyV2` object provided as an argument to the hook.\n */\n original: MoneyV2;\n /**\n * A string with trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `$640`.\n * `$640.42` remains `$640.42`.\n */\n withoutTrailingZeros: string;\n /**\n * A string without currency and without trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `640`.\n * `$640.42` turns into `640.42`.\n */\n withoutTrailingZerosAndCurrency: string;\n};\n\n/**\n * The `useMoney` hook takes a [MoneyV2 object from the Storefront API](https://shopify.dev/docs/api/storefront/2025-10/objects/MoneyV2)\n * or a [MoneyV2 object from the Customer Account API](https://shopify.dev/docs/api/customer/2025-10/objects/moneyv2) and returns a\n * default-formatted string of the amount with the correct currency indicator, along with some of the parts provided by\n * [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).\n * Uses `locale` from `ShopifyProvider`\n * \n * @see {@link https://shopify.dev/api/hydrogen/hooks/usemoney}\n * @example initialize the money object\n * ```ts\n * const money = useMoney({\n * amount: '100.00',\n * currencyCode: 'USD'\n * })\n * ```\n * \n *\n * @example basic usage, outputs: $100.00\n * ```ts\n * money.localizedString\n * ```\n * \n *\n * @example without currency, outputs: 100.00\n * ```ts\n * money.amount\n * ```\n * \n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * money.withoutTrailingZeros\n * ```\n * \n *\n * @example currency name, outputs: US dollars\n * ```ts\n * money.currencyCode\n * ```\n * \n *\n * @example currency symbol, outputs: $\n * ```ts\n * money.currencySymbol\n * ```\n * \n *\n * @example without currency and without trailing zeros, outputs: 100\n * ```ts\n * money.withoutTrailingZerosAndCurrency\n * ```\n */\nexport function useMoney(money: MoneyV2): UseMoneyValue {\n const {countryIsoCode, languageIsoCode} = useShop();\n const locale = languageIsoCode.includes('_')\n ? languageIsoCode.replace('_', '-')\n : `${languageIsoCode}-${countryIsoCode}`;\n\n if (!locale) {\n throw new Error(\n `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`,\n );\n }\n\n const amount = parseFloat(money.amount);\n\n // Check if the currency code is supported by Intl.NumberFormat\n let isCurrencySupported = true;\n try {\n new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: money.currencyCode,\n });\n } catch (e) {\n if (e instanceof RangeError && e.message.includes('currency')) {\n isCurrencySupported = false;\n }\n }\n\n const {\n defaultFormatter,\n nameFormatter,\n narrowSymbolFormatter,\n withoutTrailingZerosFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n } = useMemo(() => {\n // For unsupported currencies (like USDC cryptocurrency), use decimal formatting with 2 decimal places\n // We default to 2 decimal places based on research showing USDC displays like USD to reinforce its 1:1 peg\n const options = isCurrencySupported\n ? {\n style: 'currency' as const,\n currency: money.currencyCode,\n }\n : {\n style: 'decimal' as const,\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n };\n\n return {\n defaultFormatter: getLazyFormatter(locale, options),\n nameFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'name',\n }),\n narrowSymbolFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'narrowSymbol',\n }),\n withoutTrailingZerosFormatter: getLazyFormatter(locale, {\n ...options,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n withoutCurrencyFormatter: getLazyFormatter(locale, {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }),\n withoutTrailingZerosOrCurrencyFormatter: getLazyFormatter(locale, {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n };\n }, [money.currencyCode, locale, isCurrencySupported]);\n\n const isPartCurrency = (part: Intl.NumberFormatPart): boolean =>\n part.type === 'currency';\n\n // By wrapping these properties in functions, we only\n // create formatters if they are going to be used.\n const lazyFormatters = useMemo(\n () => ({\n original: (): MoneyV2 => money,\n currencyCode: (): CurrencyCode => money.currencyCode,\n\n localizedString: (): string => {\n const formatted = defaultFormatter().format(amount);\n // For unsupported currencies, append the currency code\n return isCurrencySupported\n ? formatted\n : `${formatted} ${money.currencyCode}`;\n },\n\n parts: (): Intl.NumberFormatPart[] => {\n const parts = defaultFormatter().formatToParts(amount);\n // For unsupported currencies, add currency code as a currency part\n if (!isCurrencySupported) {\n parts.push(\n {type: 'literal', value: ' '},\n {type: 'currency', value: money.currencyCode},\n );\n }\n return parts;\n },\n\n withoutTrailingZeros: (): string => {\n const formatted =\n amount % 1 === 0\n ? withoutTrailingZerosFormatter().format(amount)\n : defaultFormatter().format(amount);\n // For unsupported currencies, append the currency code\n return isCurrencySupported\n ? formatted\n : `${formatted} ${money.currencyCode}`;\n },\n\n withoutTrailingZerosAndCurrency: (): string =>\n amount % 1 === 0\n ? withoutTrailingZerosOrCurrencyFormatter().format(amount)\n : withoutCurrencyFormatter().format(amount),\n\n currencyName: (): string =>\n nameFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"US dollars\"\n\n currencySymbol: (): string =>\n defaultFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"USD\"\n\n currencyNarrowSymbol: (): string =>\n narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)\n ?.value ?? '', // e.g. \"$\"\n\n amount: (): string =>\n defaultFormatter()\n .formatToParts(amount)\n .filter((part) =>\n ['decimal', 'fraction', 'group', 'integer', 'literal'].includes(\n part.type,\n ),\n )\n .map((part) => part.value)\n .join(''),\n }),\n [\n money,\n amount,\n isCurrencySupported,\n nameFormatter,\n defaultFormatter,\n narrowSymbolFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n ],\n );\n\n // Call functions automatically when the properties are accessed\n // to keep these functions as an implementation detail.\n return useMemo(\n () =>\n new Proxy(lazyFormatters as unknown as UseMoneyValue, {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n get: (target, key) => Reflect.get(target, key)?.call(null),\n }),\n [lazyFormatters],\n );\n}\n\nconst formatterCache = new Map<string, Intl.NumberFormat>();\n\nfunction getLazyFormatter(\n locale: string,\n options?: Intl.NumberFormatOptions,\n): () => Intl.NumberFormat {\n const key = JSON.stringify([locale, options]);\n\n return function (): Intl.NumberFormat {\n let formatter = formatterCache.get(key);\n if (!formatter) {\n try {\n formatter = new Intl.NumberFormat(locale, options);\n } catch (error) {\n // Handle unsupported currency codes (e.g., USDC from Customer Account API)\n // Fall back to formatting without currency\n if (error instanceof RangeError && error.message.includes('currency')) {\n const fallbackOptions = {...options};\n delete fallbackOptions.currency;\n delete fallbackOptions.currencyDisplay;\n delete fallbackOptions.currencySign;\n formatter = new Intl.NumberFormat(locale, fallbackOptions);\n } else {\n throw error;\n }\n }\n formatterCache.set(key, formatter);\n }\n return formatter;\n };\n}\n"],"names":[],"mappings":";;AA8HO,SAAS,SAAS,OAA+B;AACtD,QAAM,EAAC,gBAAgB,gBAAA,IAAmB,QAAA;AAC1C,QAAM,SAAS,gBAAgB,SAAS,GAAG,IACvC,gBAAgB,QAAQ,KAAK,GAAG,IAChC,GAAG,eAAe,IAAI,cAAc;AAEx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ACrD,KAAK;AAAA,QAAA;AAAA,MACP,EAED,IAAI,CAAC,SAAS,KAAK,KAAK,EACxB,KAAK,EAAE;AAAA,IAAA;AAAA,IAEd;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAKF,SAAO;AAAA,IACL,MACE,IAAI,MAAM,gBAA4C;AAAA;AAAA,MAEpD,KAAK,CAAC,QAAQ;;AAAQ,6BAAQ,IAAI,QAAQ,GAAG,MAAvB,mBAA0B,KAAK;AAAA;AAAA,IAAI,CAC1D;AAAA,IACH,CAAC,cAAc;AAAA,EAAA;AAEnB;AAEA,MAAM,qCAAqB,IAAA;AAE3B,SAAS,iBACP,QACA,SACyB;AACzB,QAAM,MAAM,KAAK,UAAU,CAAC,QAAQ,OAAO,CAAC;AAE5C,SAAO,WAA+B;AACpC,QAAI,YAAY,eAAe,IAAI,GAAG;AACtC,QAAI,CAAC,WAAW;AACd,UAAI;AACF,oBAAY,IAAI,KAAK,aAAa,QAAQ,OAAO;AAAA,MACnD,SAAS,OAAO;AAGd,YAAI,iBAAiB,cAAc,MAAM,QAAQ,SAAS,UAAU,GAAG;AACrE,gBAAM,kBAAkB,EAAC,GAAG,QAAA;AAC5B,iBAAO,gBAAgB;AACvB,iBAAO,gBAAgB;AACvB,iBAAO,gBAAgB;AACvB,sBAAY,IAAI,KAAK,aAAa,QAAQ,eAAe;AAAA,QAC3D,OAAO;AACL,gBAAM;AAAA,QACR;AAAA,MACF;AACA,qBAAe,IAAI,KAAK,SAAS;AAAA,IACnC;AACA,WAAO;AAAA,EACT;AACF;"}
|
|
1
|
+
{"version":3,"file":"useMoney.mjs","sources":["../../src/useMoney.tsx"],"sourcesContent":["import {useMemo} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {\n CurrencyCode as StorefrontApiCurrencyCode,\n MoneyV2 as StorefrontApiMoneyV2,\n} from './storefront-api-types.js';\nimport type {\n MoneyV2 as CustomerAccountApiMoneyV2,\n CurrencyCode as CustomerAccountApiCurrencyCode,\n} from './customer-account-api-types.js';\n\n// Support MoneyV2 from both Storefront API and Customer Account API\n// The APIs may have different CurrencyCode enums\n/**\n * Supports MoneyV2 from both Storefront API and Customer Account API.\n * The APIs may have different CurrencyCode enums (e.g., Customer Account API added USDC in 2025-10, but Storefront API doesn't support USDC in 2025-10).\n * This union type ensures useMoney works with data from either API.\n */\ntype MoneyV2 = StorefrontApiMoneyV2 | CustomerAccountApiMoneyV2;\n\n/**\n * Supports CurrencyCode from both Storefront API and Customer Account API. The APIs may have different CurrencyCode enums (e.g., Customer Account API added USDC in 2025-10, but Storefront API doesn't support USDC in 2025-10).\n * This union type ensures useMoney works with data from either API.\n */\ntype CurrencyCode = StorefrontApiCurrencyCode | CustomerAccountApiCurrencyCode;\n\nexport type UseMoneyValue = {\n /**\n * The currency code from the `MoneyV2` object.\n */\n currencyCode: CurrencyCode;\n /**\n * The name for the currency code, returned by `Intl.NumberFormat`.\n */\n currencyName?: string;\n /**\n * The currency symbol returned by `Intl.NumberFormat`.\n */\n currencySymbol?: string;\n /**\n * The currency narrow symbol returned by `Intl.NumberFormat`.\n */\n currencyNarrowSymbol?: string;\n /**\n * The localized amount, without any currency symbols or non-number types from the `Intl.NumberFormat.formatToParts` parts.\n */\n amount: string;\n /**\n * All parts returned by `Intl.NumberFormat.formatToParts`.\n */\n parts: Intl.NumberFormatPart[];\n /**\n * A string returned by `new Intl.NumberFormat` for the amount and currency code,\n * using the `locale` value in the [`LocalizationProvider` component](https://shopify.dev/api/hydrogen/components/localization/localizationprovider).\n */\n localizedString: string;\n /**\n * The `MoneyV2` object provided as an argument to the hook.\n */\n original: MoneyV2;\n /**\n * A string with trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `$640`.\n * `$640.42` remains `$640.42`.\n */\n withoutTrailingZeros: string;\n /**\n * A string without currency and without trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `640`.\n * `$640.42` turns into `640.42`.\n */\n withoutTrailingZerosAndCurrency: string;\n};\n\n/**\n * The `useMoney` hook takes a [MoneyV2 object from the Storefront API](https://shopify.dev/docs/api/storefront/2026-01/objects/MoneyV2)\n * or a [MoneyV2 object from the Customer Account API](https://shopify.dev/docs/api/customer/2026-01/objects/moneyv2) and returns a\n * default-formatted string of the amount with the correct currency indicator, along with some of the parts provided by\n * [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).\n * Uses `locale` from `ShopifyProvider`\n * \n * @see {@link https://shopify.dev/api/hydrogen/hooks/usemoney}\n * @example initialize the money object\n * ```ts\n * const money = useMoney({\n * amount: '100.00',\n * currencyCode: 'USD'\n * })\n * ```\n * \n *\n * @example basic usage, outputs: $100.00\n * ```ts\n * money.localizedString\n * ```\n * \n *\n * @example without currency, outputs: 100.00\n * ```ts\n * money.amount\n * ```\n * \n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * money.withoutTrailingZeros\n * ```\n * \n *\n * @example currency name, outputs: US dollars\n * ```ts\n * money.currencyCode\n * ```\n * \n *\n * @example currency symbol, outputs: $\n * ```ts\n * money.currencySymbol\n * ```\n * \n *\n * @example without currency and without trailing zeros, outputs: 100\n * ```ts\n * money.withoutTrailingZerosAndCurrency\n * ```\n */\nexport function useMoney(money: MoneyV2): UseMoneyValue {\n const {countryIsoCode, languageIsoCode} = useShop();\n const locale = languageIsoCode.includes('_')\n ? languageIsoCode.replace('_', '-')\n : `${languageIsoCode}-${countryIsoCode}`;\n\n if (!locale) {\n throw new Error(\n `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`,\n );\n }\n\n const amount = parseFloat(money.amount);\n\n // Check if the currency code is supported by Intl.NumberFormat\n let isCurrencySupported = true;\n try {\n new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: money.currencyCode,\n });\n } catch (e) {\n if (e instanceof RangeError && e.message.includes('currency')) {\n isCurrencySupported = false;\n }\n }\n\n const {\n defaultFormatter,\n nameFormatter,\n narrowSymbolFormatter,\n withoutTrailingZerosFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n } = useMemo(() => {\n // For unsupported currencies (like USDC cryptocurrency), use decimal formatting with 2 decimal places\n // We default to 2 decimal places based on research showing USDC displays like USD to reinforce its 1:1 peg\n const options = isCurrencySupported\n ? {\n style: 'currency' as const,\n currency: money.currencyCode,\n }\n : {\n style: 'decimal' as const,\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n };\n\n return {\n defaultFormatter: getLazyFormatter(locale, options),\n nameFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'name',\n }),\n narrowSymbolFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'narrowSymbol',\n }),\n withoutTrailingZerosFormatter: getLazyFormatter(locale, {\n ...options,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n withoutCurrencyFormatter: getLazyFormatter(locale, {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }),\n withoutTrailingZerosOrCurrencyFormatter: getLazyFormatter(locale, {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n };\n }, [money.currencyCode, locale, isCurrencySupported]);\n\n const isPartCurrency = (part: Intl.NumberFormatPart): boolean =>\n part.type === 'currency';\n\n // By wrapping these properties in functions, we only\n // create formatters if they are going to be used.\n const lazyFormatters = useMemo(\n () => ({\n original: (): MoneyV2 => money,\n currencyCode: (): CurrencyCode => money.currencyCode,\n\n localizedString: (): string => {\n const formatted = defaultFormatter().format(amount);\n // For unsupported currencies, append the currency code\n return isCurrencySupported\n ? formatted\n : `${formatted} ${money.currencyCode}`;\n },\n\n parts: (): Intl.NumberFormatPart[] => {\n const parts = defaultFormatter().formatToParts(amount);\n // For unsupported currencies, add currency code as a currency part\n if (!isCurrencySupported) {\n parts.push(\n {type: 'literal', value: ' '},\n {type: 'currency', value: money.currencyCode},\n );\n }\n return parts;\n },\n\n withoutTrailingZeros: (): string => {\n const formatted =\n amount % 1 === 0\n ? withoutTrailingZerosFormatter().format(amount)\n : defaultFormatter().format(amount);\n // For unsupported currencies, append the currency code\n return isCurrencySupported\n ? formatted\n : `${formatted} ${money.currencyCode}`;\n },\n\n withoutTrailingZerosAndCurrency: (): string =>\n amount % 1 === 0\n ? withoutTrailingZerosOrCurrencyFormatter().format(amount)\n : withoutCurrencyFormatter().format(amount),\n\n currencyName: (): string =>\n nameFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"US dollars\"\n\n currencySymbol: (): string =>\n defaultFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"USD\"\n\n currencyNarrowSymbol: (): string =>\n narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)\n ?.value ?? '', // e.g. \"$\"\n\n amount: (): string =>\n defaultFormatter()\n .formatToParts(amount)\n .filter((part) =>\n ['decimal', 'fraction', 'group', 'integer', 'literal'].includes(\n part.type,\n ),\n )\n .map((part) => part.value)\n .join(''),\n }),\n [\n money,\n amount,\n isCurrencySupported,\n nameFormatter,\n defaultFormatter,\n narrowSymbolFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n ],\n );\n\n // Call functions automatically when the properties are accessed\n // to keep these functions as an implementation detail.\n return useMemo(\n () =>\n new Proxy(lazyFormatters as unknown as UseMoneyValue, {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n get: (target, key) => Reflect.get(target, key)?.call(null),\n }),\n [lazyFormatters],\n );\n}\n\nconst formatterCache = new Map<string, Intl.NumberFormat>();\n\nfunction getLazyFormatter(\n locale: string,\n options?: Intl.NumberFormatOptions,\n): () => Intl.NumberFormat {\n const key = JSON.stringify([locale, options]);\n\n return function (): Intl.NumberFormat {\n let formatter = formatterCache.get(key);\n if (!formatter) {\n try {\n formatter = new Intl.NumberFormat(locale, options);\n } catch (error) {\n // Handle unsupported currency codes (e.g., USDC from Customer Account API)\n // Fall back to formatting without currency\n if (error instanceof RangeError && error.message.includes('currency')) {\n const fallbackOptions = {...options};\n delete fallbackOptions.currency;\n delete fallbackOptions.currencyDisplay;\n delete fallbackOptions.currencySign;\n formatter = new Intl.NumberFormat(locale, fallbackOptions);\n } else {\n throw error;\n }\n }\n formatterCache.set(key, formatter);\n }\n return formatter;\n };\n}\n"],"names":[],"mappings":";;AA8HO,SAAS,SAAS,OAA+B;AACtD,QAAM,EAAC,gBAAgB,gBAAA,IAAmB,QAAA;AAC1C,QAAM,SAAS,gBAAgB,SAAS,GAAG,IACvC,gBAAgB,QAAQ,KAAK,GAAG,IAChC,GAAG,eAAe,IAAI,cAAc;AAExC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEA,QAAM,SAAS,WAAW,MAAM,MAAM;AAGtC,MAAI,sBAAsB;AAC1B,MAAI;AACF,QAAI,KAAK,aAAa,QAAQ;AAAA,MAC5B,OAAO;AAAA,MACP,UAAU,MAAM;AAAA,IAAA,CACjB;AAAA,EACH,SAAS,GAAG;AACV,QAAI,aAAa,cAAc,EAAE,QAAQ,SAAS,UAAU,GAAG;AAC7D,4BAAsB;AAAA,IACxB;AAAA,EACF;AAEA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE,QAAQ,MAAM;AAGhB,UAAM,UAAU,sBACZ;AAAA,MACE,OAAO;AAAA,MACP,UAAU,MAAM;AAAA,IAAA,IAElB;AAAA,MACE,OAAO;AAAA,MACP,uBAAuB;AAAA,MACvB,uBAAuB;AAAA,IAAA;AAG7B,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AI,CAAC,WAAW;AACd,UAAI;AACF,oBAAY,IAAI,KAAK,aAAa,QAAQ,OAAO;AAAA,MACnD,SAAS,OAAO;AAGd,YAAI,iBAAiB,cAAc,MAAM,QAAQ,SAAS,UAAU,GAAG;AACrE,gBAAM,kBAAkB,EAAC,GAAG,QAAA;AAC5B,iBAAO,gBAAgB;AACvB,iBAAO,gBAAgB;AACvB,iBAAO,gBAAgB;AACvB,sBAAY,IAAI,KAAK,aAAa,QAAQ,eAAe;AAAA,QAC3D,OAAO;AACL,gBAAM;AAAA,QACR;AAAA,MACF;AACA,qBAAe,IAAI,KAAK,SAAS;AAAA,IACnC;AACA,WAAO;AAAA,EACT;AACF;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CartLineProvider.mjs","sources":["../../src/CartLineProvider.tsx"],"sourcesContent":["import {useContext, createContext, type ReactNode} from 'react';\nimport {\n ComponentizableCartLine,\n type CartLine,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\ntype CartLinePartialDeep = PartialDeep<\n CartLine | ComponentizableCartLine,\n {recurseIntoArrays: true}\n>;\n\nexport const CartLineContext = createContext<CartLinePartialDeep | null>(null);\n\n/**\n * The `useCartLine` hook provides access to the [CartLine object](https://shopify.dev/api/storefront/
|
|
1
|
+
{"version":3,"file":"CartLineProvider.mjs","sources":["../../src/CartLineProvider.tsx"],"sourcesContent":["import {useContext, createContext, type ReactNode} from 'react';\nimport {\n ComponentizableCartLine,\n type CartLine,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\ntype CartLinePartialDeep = PartialDeep<\n CartLine | ComponentizableCartLine,\n {recurseIntoArrays: true}\n>;\n\nexport const CartLineContext = createContext<CartLinePartialDeep | null>(null);\n\n/**\n * The `useCartLine` hook provides access to the [CartLine object](https://shopify.dev/api/storefront/2026-01/objects/cartline) from the Storefront API. It must be a descendent of a `CartProvider` component.\n */\nexport function useCartLine(): CartLinePartialDeep {\n const context = useContext(CartLineContext);\n\n if (context == null) {\n throw new Error('Expected a cart line context but none was found');\n }\n\n return context;\n}\n\ntype CartLineProviderProps = {\n /** Any `ReactNode` elements. */\n children: ReactNode;\n /** A cart line object. */\n line: CartLinePartialDeep;\n};\n\n/**\n * The `CartLineProvider` component creates a context for using a cart line.\n */\nexport function CartLineProvider({\n children,\n line,\n}: CartLineProviderProps): JSX.Element {\n return (\n <CartLineContext.Provider value={line}>{children}</CartLineContext.Provider>\n );\n}\n"],"names":[],"mappings":";;AAYO,MAAM,kBAAkB,cAA0C,IAAI;AAKtE,SAAS,cAAmC;AACjD,QAAM,UAAU,WAAW,eAAe;AAE1C,MAAI,WAAW,MAAM;AACnB,UAAM,IAAI,MAAM,iDAAiD;AAAA,EACnE;AAEA,SAAO;AACT;AAYO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AACF,GAAuC;AACrC,6BACG,gBAAgB,UAAhB,EAAyB,OAAO,MAAO,UAAS;AAErD;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CartProvider.mjs","sources":["../../src/CartProvider.tsx"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n createContext,\n useContext,\n} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n LanguageCode,\n Cart as CartType,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n BuyerIdentityUpdateEvent,\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState,\n CartWithActions,\n CartWithActionsDocs,\n} from './cart-types.js';\nimport {useCartAPIStateMachine} from './useCartAPIStateMachine.js';\nimport {CART_ID_STORAGE_KEY} from './cart-constants.js';\nimport {PartialDeep} from 'type-fest';\nimport {defaultCartFragment} from './cart-queries.js';\nimport {useShop} from './ShopifyProvider.js';\n\nexport const CartContext = createContext<CartWithActions | null>(null);\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype UseCartDocs = () => CartWithActionsDocs;\n\n/**\n * The `useCart` hook provides access to the cart object. It must be a descendent of a `CartProvider` component.\n */\nexport function useCart(): CartWithActions {\n const context = useContext(CartContext);\n\n if (!context) {\n throw new Error('Expected a Cart Context, but no Cart Context was found');\n }\n\n return context;\n}\n\ntype CartProviderProps = {\n /** Any `ReactNode` elements. */\n children: React.ReactNode;\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked when the process to create a cart begins, but before the cart is created in the Storefront API. */\n onCreate?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart begins, but before the line item is added to the Storefront API. */\n onLineAdd?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart begins, but before the line item is removed from the Storefront API. */\n onLineRemove?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart begins, but before the line item is updated in the Storefront API. */\n onLineUpdate?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart begins, but before the note is added or updated in the Storefront API. */\n onNoteUpdate?: () => void;\n /** A callback that is invoked when the process to update the buyer identity begins, but before the buyer identity is updated in the Storefront API. */\n onBuyerIdentityUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart attributes begins, but before the attributes are updated in the Storefront API. */\n onAttributesUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes begins, but before the discount codes are updated in the Storefront API. */\n onDiscountCodesUpdate?: () => void;\n /** A callback that is invoked when the process to create a cart completes */\n onCreateComplete?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart completes */\n onLineAddComplete?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart completes */\n onLineRemoveComplete?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart completes */\n onLineUpdateComplete?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart completes */\n onNoteUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the buyer identity completes */\n onBuyerIdentityUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart attributes completes */\n onAttributesUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes completes */\n onDiscountCodesUpdateComplete?: () => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-10/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-10/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment?: string;\n /** A customer access token that's accessible on the server if there's a customer login. */\n customerAccessToken?: CartBuyerIdentityInput['customerAccessToken'];\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n /** The ISO language code for i18n. */\n languageCode?: LanguageCode;\n};\n\n/**\n * The `CartProvider` component synchronizes the state of the Storefront API Cart and a customer's cart,\n * and allows you to more easily manipulate the cart by adding, removing, and updating it.\n * It could be placed at the root of your app so that your whole app is able to use the `useCart()` hook anywhere.\n *\n * There are props that trigger when a call to the Storefront API is made, such as `onLineAdd={}` when a line is added to the cart.\n * There are also props that trigger when a call to the Storefront API is completed, such as `onLineAddComplete={}` when the fetch request for adding a line to the cart completes.\n *\n * The `CartProvider` component must be a descendant of the `ShopifyProvider` component.\n */\nexport function CartProvider({\n children,\n numCartLines,\n onCreate,\n onLineAdd,\n onLineRemove,\n onLineUpdate,\n onNoteUpdate,\n onBuyerIdentityUpdate,\n onAttributesUpdate,\n onDiscountCodesUpdate,\n onCreateComplete,\n onLineAddComplete,\n onLineRemoveComplete,\n onLineUpdateComplete,\n onNoteUpdateComplete,\n onBuyerIdentityUpdateComplete,\n onAttributesUpdateComplete,\n onDiscountCodesUpdateComplete,\n data: cart,\n cartFragment = defaultCartFragment,\n customerAccessToken,\n countryCode,\n languageCode,\n}: CartProviderProps): JSX.Element {\n const shop = useShop();\n\n if (!shop)\n throw new Error(\n '<CartProvider> needs to be a descendant of <ShopifyProvider>',\n );\n\n countryCode = (\n (countryCode as string) ??\n shop.countryIsoCode ??\n 'US'\n ).toUpperCase() as CountryCode;\n\n languageCode = (\n (languageCode as string) ??\n shop.languageIsoCode ??\n 'EN'\n ).toUpperCase() as LanguageCode;\n\n if (countryCode) countryCode = countryCode.toUpperCase() as CountryCode;\n\n const [prevCountryCode, setPrevCountryCode] = useState(countryCode);\n const [prevCustomerAccessToken, setPrevCustomerAccessToken] =\n useState(customerAccessToken);\n const customerOverridesCountryCode = useRef(false);\n\n if (\n prevCountryCode !== countryCode ||\n prevCustomerAccessToken !== customerAccessToken\n ) {\n setPrevCountryCode(countryCode);\n setPrevCustomerAccessToken(customerAccessToken);\n customerOverridesCountryCode.current = false;\n }\n\n const [cartState, cartSend] = useCartAPIStateMachine({\n numCartLines,\n data: cart,\n cartFragment,\n countryCode,\n languageCode,\n onCartActionEntry(_, event) {\n try {\n switch (event.type) {\n case 'CART_CREATE':\n return onCreate?.();\n case 'CARTLINE_ADD':\n return onLineAdd?.();\n case 'CARTLINE_REMOVE':\n return onLineRemove?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdate?.();\n case 'NOTE_UPDATE':\n return onNoteUpdate?.();\n case 'BUYER_IDENTITY_UPDATE':\n return onBuyerIdentityUpdate?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdate?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdate?.();\n }\n } catch (error) {\n console.error('Cart entry action failed', error);\n }\n },\n onCartActionOptimisticUI(context, event) {\n if (!context.cart) return {...context};\n switch (event.type) {\n case 'CARTLINE_REMOVE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.filter(\n (line) => line?.id && !event.payload.lines.includes(line?.id),\n ),\n },\n };\n case 'CARTLINE_UPDATE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.map((line) => {\n const updatedLine = event.payload.lines.find(\n ({id}) => id === line?.id,\n );\n\n if (updatedLine && updatedLine.quantity) {\n return {\n ...line,\n quantity: updatedLine.quantity,\n };\n }\n\n return line;\n }),\n },\n };\n }\n return {...context};\n },\n onCartActionComplete(context, event) {\n const cartActionEvent = event.payload.cartActionEvent;\n try {\n switch (event.type) {\n case 'RESOLVE':\n switch (cartActionEvent.type) {\n case 'CART_CREATE':\n return onCreateComplete?.();\n case 'CARTLINE_ADD':\n return onLineAddComplete?.();\n case 'CARTLINE_REMOVE':\n return onLineRemoveComplete?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdateComplete?.();\n case 'NOTE_UPDATE':\n return onNoteUpdateComplete?.();\n case 'BUYER_IDENTITY_UPDATE':\n if (countryCodeNotUpdated(context, cartActionEvent)) {\n customerOverridesCountryCode.current = true;\n }\n return onBuyerIdentityUpdateComplete?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdateComplete?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdateComplete?.();\n }\n }\n } catch (error) {\n console.error('onCartActionComplete failed', error);\n }\n },\n });\n\n const cartReady = useRef(false);\n const [isCartReady, setIsCartReady] = useState(false);\n const cartCompleted = cartState.matches('cartCompleted');\n\n const countryChanged =\n (cartState.value === 'idle' ||\n cartState.value === 'error' ||\n cartState.value === 'cartCompleted') &&\n countryCode !== cartState?.context?.cart?.buyerIdentity?.countryCode &&\n !cartState.context.errors;\n\n const fetchingFromStorage = useRef(false);\n\n /**\n * Initializes cart with priority in this order:\n * 1. cart props\n * 2. localStorage cartId\n */\n useEffect(() => {\n if (!cartReady.current && !fetchingFromStorage.current) {\n if (!cart && storageAvailable('localStorage')) {\n fetchingFromStorage.current = true;\n try {\n const cartId = window.localStorage.getItem(CART_ID_STORAGE_KEY);\n if (cartId) {\n cartSend({type: 'CART_FETCH', payload: {cartId}});\n }\n } catch (error) {\n console.warn('error fetching cartId');\n console.warn(error);\n }\n }\n cartReady.current = true;\n // Providing a separate cart ready state variable to avoid re-renders in this logic while still being able to pass the reactive status through context.\n setIsCartReady(true);\n }\n }, [cart, cartReady, cartSend]);\n\n // Update cart country code if cart and props countryCode's as different\n useEffect(() => {\n if (!countryChanged || customerOverridesCountryCode.current) return;\n cartSend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {buyerIdentity: {countryCode, customerAccessToken}},\n });\n }, [\n countryCode,\n customerAccessToken,\n countryChanged,\n customerOverridesCountryCode,\n cartSend,\n ]);\n\n // send cart events when ready\n const onCartReadySend = useCallback(\n (cartEvent: CartMachineEvent) => {\n if (!cartReady.current) {\n return console.warn(\"Cart isn't ready yet\");\n }\n cartSend(cartEvent);\n },\n [cartSend],\n );\n\n // save cart id to local storage\n useEffect(() => {\n if (cartState?.context?.cart?.id && storageAvailable('localStorage')) {\n try {\n window.localStorage.setItem(\n CART_ID_STORAGE_KEY,\n cartState.context.cart?.id,\n );\n } catch (error) {\n console.warn('Failed to save cartId to localStorage', error);\n }\n }\n }, [cartState?.context?.cart?.id]);\n\n // delete cart from local storage if cart fetched has been completed\n useEffect(() => {\n if (cartCompleted && storageAvailable('localStorage')) {\n try {\n window.localStorage.removeItem(CART_ID_STORAGE_KEY);\n } catch (error) {\n console.warn('Failed to delete cartId from localStorage', error);\n }\n }\n }, [cartCompleted]);\n\n const cartCreate = useCallback(\n (cartInput: CartInput) => {\n if (countryCode && !cartInput.buyerIdentity?.countryCode) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.countryCode = countryCode;\n }\n\n if (\n customerAccessToken &&\n !cartInput.buyerIdentity?.customerAccessToken\n ) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.customerAccessToken = customerAccessToken;\n }\n onCartReadySend({\n type: 'CART_CREATE',\n payload: cartInput,\n });\n },\n [countryCode, customerAccessToken, onCartReadySend],\n );\n\n // Delays the cart state in the context if the page is hydrating\n // preventing suspense boundary errors.\n const cartDisplayState = useDelayedStateUntilHydration(cartState);\n\n const cartContextValue = useMemo<CartWithActions>(() => {\n return {\n ...(cartDisplayState?.context?.cart ?? {lines: [], attributes: []}),\n status: transposeStatus(cartDisplayState.value),\n error: cartDisplayState?.context?.errors,\n totalQuantity: cartDisplayState?.context?.cart?.totalQuantity ?? 0,\n cartCreate,\n cartReady: isCartReady,\n linesAdd(lines: CartLineInput[]): void {\n if (cartDisplayState?.context?.cart?.id) {\n onCartReadySend({\n type: 'CARTLINE_ADD',\n payload: {lines},\n });\n } else {\n cartCreate({lines});\n }\n },\n linesRemove(lines: string[]): void {\n onCartReadySend({\n type: 'CARTLINE_REMOVE',\n payload: {\n lines,\n },\n });\n },\n linesUpdate(lines: CartLineUpdateInput[]): void {\n onCartReadySend({\n type: 'CARTLINE_UPDATE',\n payload: {\n lines,\n },\n });\n },\n noteUpdate(note: MutationCartNoteUpdateArgs['note']): void {\n onCartReadySend({\n type: 'NOTE_UPDATE',\n payload: {\n note,\n },\n });\n },\n buyerIdentityUpdate(buyerIdentity: CartBuyerIdentityInput): void {\n onCartReadySend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {\n buyerIdentity,\n },\n });\n },\n cartAttributesUpdate(attributes: AttributeInput[]): void {\n onCartReadySend({\n type: 'CART_ATTRIBUTES_UPDATE',\n payload: {\n attributes,\n },\n });\n },\n discountCodesUpdate(discountCodes: string[]): void {\n onCartReadySend({\n type: 'DISCOUNT_CODES_UPDATE',\n payload: {\n discountCodes,\n },\n });\n },\n cartFragment,\n };\n }, [\n cartCreate,\n isCartReady,\n cartDisplayState?.context?.cart,\n cartDisplayState?.context?.errors,\n cartDisplayState.value,\n cartFragment,\n onCartReadySend,\n ]);\n\n return (\n <CartContext.Provider value={cartContextValue}>\n {children}\n </CartContext.Provider>\n );\n}\n\nfunction transposeStatus(\n status: CartMachineTypeState['value'],\n): CartWithActions['status'] {\n switch (status) {\n case 'uninitialized':\n case 'initializationError':\n return 'uninitialized';\n case 'idle':\n case 'cartCompleted':\n case 'error':\n return 'idle';\n case 'cartFetching':\n return 'fetching';\n case 'cartCreating':\n return 'creating';\n case 'cartLineAdding':\n case 'cartLineRemoving':\n case 'cartLineUpdating':\n case 'noteUpdating':\n case 'buyerIdentityUpdating':\n case 'cartAttributesUpdating':\n case 'discountCodesUpdating':\n return 'updating';\n }\n}\n\n/**\n * Delays a state update until hydration finishes. Useful for preventing suspense boundaries errors when updating a context\n * @remarks this uses startTransition and waits for it to finish.\n */\nfunction useDelayedStateUntilHydration<T>(state: T): T {\n const [isPending, startTransition] = useTransition();\n const [delayedState, setDelayedState] = useState(state);\n\n const firstTimePending = useRef(false);\n if (isPending) {\n firstTimePending.current = true;\n }\n\n const firstTimePendingFinished = useRef(false);\n if (!isPending && firstTimePending.current) {\n firstTimePendingFinished.current = true;\n }\n\n useEffect(() => {\n startTransition(() => {\n if (!firstTimePendingFinished.current) {\n setDelayedState(state);\n }\n });\n }, [state]);\n\n const displayState = firstTimePendingFinished.current ? state : delayedState;\n\n return displayState;\n}\n\n/**\n * Check for storage availability function obtained from\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API\n */\nexport function storageAvailable(\n type: 'localStorage' | 'sessionStorage',\n): boolean {\n let storage;\n try {\n storage = window[type];\n const x = '__storage_test__';\n storage.setItem(x, x);\n storage.removeItem(x);\n return true;\n } catch (e) {\n return !!(\n e instanceof DOMException &&\n // everything except Firefox\n (e.code === 22 ||\n // Firefox\n e.code === 1014 ||\n // test name field too, because code might not be present\n // everything except Firefox\n e.name === 'QuotaExceededError' ||\n // Firefox\n e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&\n // acknowledge QuotaExceededError only if there's something already stored\n storage &&\n storage.length !== 0\n );\n }\n}\n\nfunction countryCodeNotUpdated(\n context: CartMachineContext,\n event: BuyerIdentityUpdateEvent,\n): boolean {\n return !!(\n event.payload.buyerIdentity.countryCode &&\n context.cart?.buyerIdentity?.countryCode !==\n event.payload.buyerIdentity.countryCode\n );\n}\n"],"names":["_b","_a","_d","_c"],"mappings":";;;;;;AAmCO,MAAM,cAAc,cAAsC,IAAI;AAQ9D,SAAS,UAA2B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b,qBAAiB,UAAU;AAAA,EAC7B;AAEA,QAAM,2BAA2B,OAAO,KAAK;AAC7C,MAAI,CAAC,aAAa,iBAAiB,SAAS;AAC1C,6BAAyB,UAAU;AAAA,EACrC;AAEA,YAAU,MAAM;AACd,oBAAgB,MAAM;AACpB,UAAI,CAAC,yBAAyB,SAAS;AACrC,wBAAgB,KAAK;AAAA,MACvB;AAAA,IACF,CAAC;AAAA,EACH,GAAG,CAAC,KAAK,CAAC;AAEV,QAAM,eAAe,yBAAyB,UAAU,QAAQ;AAEhE,SAAO;AACT;AAMO,SAAS,iBACd,MACS;AACT,MAAI;AACJ,MAAI;AACF,cAAU,OAAO,IAAI;AACrB,UAAM,IAAI;AACV,YAAQ,QAAQ,GAAG,CAAC;AACpB,YAAQ,WAAW,CAAC;AACpB,WAAO;AAAA,EACT,SAAS,GAAG;AACV,WAAO,CAAC,EACN,aAAa;AAAA,KAEZ,EAAE,SAAS;AAAA,IAEV,EAAE,SAAS;AAAA;AAAA,IAGX,EAAE,SAAS;AAAA,IAEX,EAAE,SAAS;AAAA,IAEb,WACA,QAAQ,WAAW;AAAA,EAEvB;AACF;AAEA,SAAS,sBACP,SACA,OACS;;AACT,SAAO,CAAC,EACN,MAAM,QAAQ,cAAc,iBAC5B,mBAAQ,SAAR,mBAAc,kBAAd,mBAA6B,iBAC3B,MAAM,QAAQ,cAAc;AAElC;"}
|
|
1
|
+
{"version":3,"file":"CartProvider.mjs","sources":["../../src/CartProvider.tsx"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n createContext,\n useContext,\n} from 'react';\nimport {\n AttributeInput,\n CartBuyerIdentityInput,\n CartInput,\n CartLineInput,\n CartLineUpdateInput,\n CountryCode,\n LanguageCode,\n Cart as CartType,\n MutationCartNoteUpdateArgs,\n} from './storefront-api-types.js';\nimport {\n BuyerIdentityUpdateEvent,\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState,\n CartWithActions,\n CartWithActionsDocs,\n} from './cart-types.js';\nimport {useCartAPIStateMachine} from './useCartAPIStateMachine.js';\nimport {CART_ID_STORAGE_KEY} from './cart-constants.js';\nimport {PartialDeep} from 'type-fest';\nimport {defaultCartFragment} from './cart-queries.js';\nimport {useShop} from './ShopifyProvider.js';\n\nexport const CartContext = createContext<CartWithActions | null>(null);\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype UseCartDocs = () => CartWithActionsDocs;\n\n/**\n * The `useCart` hook provides access to the cart object. It must be a descendent of a `CartProvider` component.\n */\nexport function useCart(): CartWithActions {\n const context = useContext(CartContext);\n\n if (!context) {\n throw new Error('Expected a Cart Context, but no Cart Context was found');\n }\n\n return context;\n}\n\ntype CartProviderProps = {\n /** Any `ReactNode` elements. */\n children: React.ReactNode;\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked when the process to create a cart begins, but before the cart is created in the Storefront API. */\n onCreate?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart begins, but before the line item is added to the Storefront API. */\n onLineAdd?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart begins, but before the line item is removed from the Storefront API. */\n onLineRemove?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart begins, but before the line item is updated in the Storefront API. */\n onLineUpdate?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart begins, but before the note is added or updated in the Storefront API. */\n onNoteUpdate?: () => void;\n /** A callback that is invoked when the process to update the buyer identity begins, but before the buyer identity is updated in the Storefront API. */\n onBuyerIdentityUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart attributes begins, but before the attributes are updated in the Storefront API. */\n onAttributesUpdate?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes begins, but before the discount codes are updated in the Storefront API. */\n onDiscountCodesUpdate?: () => void;\n /** A callback that is invoked when the process to create a cart completes */\n onCreateComplete?: () => void;\n /** A callback that is invoked when the process to add a line item to the cart completes */\n onLineAddComplete?: () => void;\n /** A callback that is invoked when the process to remove a line item to the cart completes */\n onLineRemoveComplete?: () => void;\n /** A callback that is invoked when the process to update a line item in the cart completes */\n onLineUpdateComplete?: () => void;\n /** A callback that is invoked when the process to add or update a note in the cart completes */\n onNoteUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the buyer identity completes */\n onBuyerIdentityUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart attributes completes */\n onAttributesUpdateComplete?: () => void;\n /** A callback that is invoked when the process to update the cart discount codes completes */\n onDiscountCodesUpdateComplete?: () => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2026-01/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2026-01/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment?: string;\n /** A customer access token that's accessible on the server if there's a customer login. */\n customerAccessToken?: CartBuyerIdentityInput['customerAccessToken'];\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n /** The ISO language code for i18n. */\n languageCode?: LanguageCode;\n};\n\n/**\n * The `CartProvider` component synchronizes the state of the Storefront API Cart and a customer's cart,\n * and allows you to more easily manipulate the cart by adding, removing, and updating it.\n * It could be placed at the root of your app so that your whole app is able to use the `useCart()` hook anywhere.\n *\n * There are props that trigger when a call to the Storefront API is made, such as `onLineAdd={}` when a line is added to the cart.\n * There are also props that trigger when a call to the Storefront API is completed, such as `onLineAddComplete={}` when the fetch request for adding a line to the cart completes.\n *\n * The `CartProvider` component must be a descendant of the `ShopifyProvider` component.\n */\nexport function CartProvider({\n children,\n numCartLines,\n onCreate,\n onLineAdd,\n onLineRemove,\n onLineUpdate,\n onNoteUpdate,\n onBuyerIdentityUpdate,\n onAttributesUpdate,\n onDiscountCodesUpdate,\n onCreateComplete,\n onLineAddComplete,\n onLineRemoveComplete,\n onLineUpdateComplete,\n onNoteUpdateComplete,\n onBuyerIdentityUpdateComplete,\n onAttributesUpdateComplete,\n onDiscountCodesUpdateComplete,\n data: cart,\n cartFragment = defaultCartFragment,\n customerAccessToken,\n countryCode,\n languageCode,\n}: CartProviderProps): JSX.Element {\n const shop = useShop();\n\n if (!shop)\n throw new Error(\n '<CartProvider> needs to be a descendant of <ShopifyProvider>',\n );\n\n countryCode = (\n (countryCode as string) ??\n shop.countryIsoCode ??\n 'US'\n ).toUpperCase() as CountryCode;\n\n languageCode = (\n (languageCode as string) ??\n shop.languageIsoCode ??\n 'EN'\n ).toUpperCase() as LanguageCode;\n\n if (countryCode) countryCode = countryCode.toUpperCase() as CountryCode;\n\n const [prevCountryCode, setPrevCountryCode] = useState(countryCode);\n const [prevCustomerAccessToken, setPrevCustomerAccessToken] =\n useState(customerAccessToken);\n const customerOverridesCountryCode = useRef(false);\n\n if (\n prevCountryCode !== countryCode ||\n prevCustomerAccessToken !== customerAccessToken\n ) {\n setPrevCountryCode(countryCode);\n setPrevCustomerAccessToken(customerAccessToken);\n customerOverridesCountryCode.current = false;\n }\n\n const [cartState, cartSend] = useCartAPIStateMachine({\n numCartLines,\n data: cart,\n cartFragment,\n countryCode,\n languageCode,\n onCartActionEntry(_, event) {\n try {\n switch (event.type) {\n case 'CART_CREATE':\n return onCreate?.();\n case 'CARTLINE_ADD':\n return onLineAdd?.();\n case 'CARTLINE_REMOVE':\n return onLineRemove?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdate?.();\n case 'NOTE_UPDATE':\n return onNoteUpdate?.();\n case 'BUYER_IDENTITY_UPDATE':\n return onBuyerIdentityUpdate?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdate?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdate?.();\n }\n } catch (error) {\n console.error('Cart entry action failed', error);\n }\n },\n onCartActionOptimisticUI(context, event) {\n if (!context.cart) return {...context};\n switch (event.type) {\n case 'CARTLINE_REMOVE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.filter(\n (line) => line?.id && !event.payload.lines.includes(line?.id),\n ),\n },\n };\n case 'CARTLINE_UPDATE':\n return {\n ...context,\n cart: {\n ...context.cart,\n lines: context?.cart?.lines?.map((line) => {\n const updatedLine = event.payload.lines.find(\n ({id}) => id === line?.id,\n );\n\n if (updatedLine && updatedLine.quantity) {\n return {\n ...line,\n quantity: updatedLine.quantity,\n };\n }\n\n return line;\n }),\n },\n };\n }\n return {...context};\n },\n onCartActionComplete(context, event) {\n const cartActionEvent = event.payload.cartActionEvent;\n try {\n switch (event.type) {\n case 'RESOLVE':\n switch (cartActionEvent.type) {\n case 'CART_CREATE':\n return onCreateComplete?.();\n case 'CARTLINE_ADD':\n return onLineAddComplete?.();\n case 'CARTLINE_REMOVE':\n return onLineRemoveComplete?.();\n case 'CARTLINE_UPDATE':\n return onLineUpdateComplete?.();\n case 'NOTE_UPDATE':\n return onNoteUpdateComplete?.();\n case 'BUYER_IDENTITY_UPDATE':\n if (countryCodeNotUpdated(context, cartActionEvent)) {\n customerOverridesCountryCode.current = true;\n }\n return onBuyerIdentityUpdateComplete?.();\n case 'CART_ATTRIBUTES_UPDATE':\n return onAttributesUpdateComplete?.();\n case 'DISCOUNT_CODES_UPDATE':\n return onDiscountCodesUpdateComplete?.();\n }\n }\n } catch (error) {\n console.error('onCartActionComplete failed', error);\n }\n },\n });\n\n const cartReady = useRef(false);\n const [isCartReady, setIsCartReady] = useState(false);\n const cartCompleted = cartState.matches('cartCompleted');\n\n const countryChanged =\n (cartState.value === 'idle' ||\n cartState.value === 'error' ||\n cartState.value === 'cartCompleted') &&\n countryCode !== cartState?.context?.cart?.buyerIdentity?.countryCode &&\n !cartState.context.errors;\n\n const fetchingFromStorage = useRef(false);\n\n /**\n * Initializes cart with priority in this order:\n * 1. cart props\n * 2. localStorage cartId\n */\n useEffect(() => {\n if (!cartReady.current && !fetchingFromStorage.current) {\n if (!cart && storageAvailable('localStorage')) {\n fetchingFromStorage.current = true;\n try {\n const cartId = window.localStorage.getItem(CART_ID_STORAGE_KEY);\n if (cartId) {\n cartSend({type: 'CART_FETCH', payload: {cartId}});\n }\n } catch (error) {\n console.warn('error fetching cartId');\n console.warn(error);\n }\n }\n cartReady.current = true;\n // Providing a separate cart ready state variable to avoid re-renders in this logic while still being able to pass the reactive status through context.\n setIsCartReady(true);\n }\n }, [cart, cartReady, cartSend]);\n\n // Update cart country code if cart and props countryCode's as different\n useEffect(() => {\n if (!countryChanged || customerOverridesCountryCode.current) return;\n cartSend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {buyerIdentity: {countryCode, customerAccessToken}},\n });\n }, [\n countryCode,\n customerAccessToken,\n countryChanged,\n customerOverridesCountryCode,\n cartSend,\n ]);\n\n // send cart events when ready\n const onCartReadySend = useCallback(\n (cartEvent: CartMachineEvent) => {\n if (!cartReady.current) {\n return console.warn(\"Cart isn't ready yet\");\n }\n cartSend(cartEvent);\n },\n [cartSend],\n );\n\n // save cart id to local storage\n useEffect(() => {\n if (cartState?.context?.cart?.id && storageAvailable('localStorage')) {\n try {\n window.localStorage.setItem(\n CART_ID_STORAGE_KEY,\n cartState.context.cart?.id,\n );\n } catch (error) {\n console.warn('Failed to save cartId to localStorage', error);\n }\n }\n }, [cartState?.context?.cart?.id]);\n\n // delete cart from local storage if cart fetched has been completed\n useEffect(() => {\n if (cartCompleted && storageAvailable('localStorage')) {\n try {\n window.localStorage.removeItem(CART_ID_STORAGE_KEY);\n } catch (error) {\n console.warn('Failed to delete cartId from localStorage', error);\n }\n }\n }, [cartCompleted]);\n\n const cartCreate = useCallback(\n (cartInput: CartInput) => {\n if (countryCode && !cartInput.buyerIdentity?.countryCode) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.countryCode = countryCode;\n }\n\n if (\n customerAccessToken &&\n !cartInput.buyerIdentity?.customerAccessToken\n ) {\n if (cartInput.buyerIdentity == null) {\n cartInput.buyerIdentity = {};\n }\n cartInput.buyerIdentity.customerAccessToken = customerAccessToken;\n }\n onCartReadySend({\n type: 'CART_CREATE',\n payload: cartInput,\n });\n },\n [countryCode, customerAccessToken, onCartReadySend],\n );\n\n // Delays the cart state in the context if the page is hydrating\n // preventing suspense boundary errors.\n const cartDisplayState = useDelayedStateUntilHydration(cartState);\n\n const cartContextValue = useMemo<CartWithActions>(() => {\n return {\n ...(cartDisplayState?.context?.cart ?? {lines: [], attributes: []}),\n status: transposeStatus(cartDisplayState.value),\n error: cartDisplayState?.context?.errors,\n totalQuantity: cartDisplayState?.context?.cart?.totalQuantity ?? 0,\n cartCreate,\n cartReady: isCartReady,\n linesAdd(lines: CartLineInput[]): void {\n if (cartDisplayState?.context?.cart?.id) {\n onCartReadySend({\n type: 'CARTLINE_ADD',\n payload: {lines},\n });\n } else {\n cartCreate({lines});\n }\n },\n linesRemove(lines: string[]): void {\n onCartReadySend({\n type: 'CARTLINE_REMOVE',\n payload: {\n lines,\n },\n });\n },\n linesUpdate(lines: CartLineUpdateInput[]): void {\n onCartReadySend({\n type: 'CARTLINE_UPDATE',\n payload: {\n lines,\n },\n });\n },\n noteUpdate(note: MutationCartNoteUpdateArgs['note']): void {\n onCartReadySend({\n type: 'NOTE_UPDATE',\n payload: {\n note,\n },\n });\n },\n buyerIdentityUpdate(buyerIdentity: CartBuyerIdentityInput): void {\n onCartReadySend({\n type: 'BUYER_IDENTITY_UPDATE',\n payload: {\n buyerIdentity,\n },\n });\n },\n cartAttributesUpdate(attributes: AttributeInput[]): void {\n onCartReadySend({\n type: 'CART_ATTRIBUTES_UPDATE',\n payload: {\n attributes,\n },\n });\n },\n discountCodesUpdate(discountCodes: string[]): void {\n onCartReadySend({\n type: 'DISCOUNT_CODES_UPDATE',\n payload: {\n discountCodes,\n },\n });\n },\n cartFragment,\n };\n }, [\n cartCreate,\n isCartReady,\n cartDisplayState?.context?.cart,\n cartDisplayState?.context?.errors,\n cartDisplayState.value,\n cartFragment,\n onCartReadySend,\n ]);\n\n return (\n <CartContext.Provider value={cartContextValue}>\n {children}\n </CartContext.Provider>\n );\n}\n\nfunction transposeStatus(\n status: CartMachineTypeState['value'],\n): CartWithActions['status'] {\n switch (status) {\n case 'uninitialized':\n case 'initializationError':\n return 'uninitialized';\n case 'idle':\n case 'cartCompleted':\n case 'error':\n return 'idle';\n case 'cartFetching':\n return 'fetching';\n case 'cartCreating':\n return 'creating';\n case 'cartLineAdding':\n case 'cartLineRemoving':\n case 'cartLineUpdating':\n case 'noteUpdating':\n case 'buyerIdentityUpdating':\n case 'cartAttributesUpdating':\n case 'discountCodesUpdating':\n return 'updating';\n }\n}\n\n/**\n * Delays a state update until hydration finishes. Useful for preventing suspense boundaries errors when updating a context\n * @remarks this uses startTransition and waits for it to finish.\n */\nfunction useDelayedStateUntilHydration<T>(state: T): T {\n const [isPending, startTransition] = useTransition();\n const [delayedState, setDelayedState] = useState(state);\n\n const firstTimePending = useRef(false);\n if (isPending) {\n firstTimePending.current = true;\n }\n\n const firstTimePendingFinished = useRef(false);\n if (!isPending && firstTimePending.current) {\n firstTimePendingFinished.current = true;\n }\n\n useEffect(() => {\n startTransition(() => {\n if (!firstTimePendingFinished.current) {\n setDelayedState(state);\n }\n });\n }, [state]);\n\n const displayState = firstTimePendingFinished.current ? state : delayedState;\n\n return displayState;\n}\n\n/**\n * Check for storage availability function obtained from\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API\n */\nexport function storageAvailable(\n type: 'localStorage' | 'sessionStorage',\n): boolean {\n let storage;\n try {\n storage = window[type];\n const x = '__storage_test__';\n storage.setItem(x, x);\n storage.removeItem(x);\n return true;\n } catch (e) {\n return !!(\n e instanceof DOMException &&\n // everything except Firefox\n (e.code === 22 ||\n // Firefox\n e.code === 1014 ||\n // test name field too, because code might not be present\n // everything except Firefox\n e.name === 'QuotaExceededError' ||\n // Firefox\n e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&\n // acknowledge QuotaExceededError only if there's something already stored\n storage &&\n storage.length !== 0\n );\n }\n}\n\nfunction countryCodeNotUpdated(\n context: CartMachineContext,\n event: BuyerIdentityUpdateEvent,\n): boolean {\n return !!(\n event.payload.buyerIdentity.countryCode &&\n context.cart?.buyerIdentity?.countryCode !==\n event.payload.buyerIdentity.countryCode\n );\n}\n"],"names":["_b","_a","_d","_c"],"mappings":";;;;;;AAmCO,MAAM,cAAc,cAAsC,IAAI;AAQ9D,SAAS,UAA2B;AACzC,QAAM,UAAU,WAAW,WAAW;AAEtC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,wDAAwD;AAAA,EAC1E;AAEA,SAAO;AACT;AA6DO,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAM;AAAA,EACN,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EACA;AACF,GAAmC;;AACjC,QAAM,OAAO,QAAA;AAEb,MAAI,CAAC;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGJ,iBACG,eACD,KAAK,kBACL,MACA,YAAA;AAEF,kBACG,gBACD,KAAK,mBACL,MACA,YAAA;AAEF,MAAI,YAAa,eAAc,YAAY,YAAA;AAE3C,QAAM,CAAC,iBAAiB,kBAAkB,IAAI,SAAS,WAAW;AAClE,QAAM,CAAC,yBAAyB,0BAA0B,IACxD,SAAS,mBAAmB;AAC9B,QAAM,+BAA+B,OAAO,KAAK;AAEjD,MACE,oBAAoB,eACpB,4BAA4B,qBAC5B;AACA,uBAAmB,WAAW;AAC9B,+BAA2B,mBAAmB;AAC9C,iCAA6B,UAAU;AAAA,EACzC;AAEA,QAAM,CAAC,WAAW,QAAQ,IAAI,uBAAuB;AAAA,IACnD;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA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AK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,EAAA;AAEb;AAMA,SAAS,8BAAiC,OAAa;AACrD,QAAM,CAAC,WAAW,eAAe,IAAI,cAAA;AACrC,QAAM,CAAC,cAAc,eAAe,IAAI,SAAS,KAAK;AAEtD,QAAM,mBAAmB,OAAO,KAAK;AACrC,MAAI,WAAW;AACb,qBAAiB,UAAU;AAAA,EAC7B;AAEA,QAAM,2BAA2B,OAAO,KAAK;AAC7C,MAAI,CAAC,aAAa,iBAAiB,SAAS;AAC1C,6BAAyB,UAAU;AAAA,EACrC;AAEA,YAAU,MAAM;AACd,oBAAgB,MAAM;AACpB,UAAI,CAAC,yBAAyB,SAAS;AACrC,wBAAgB,KAAK;AAAA,MACvB;AAAA,IACF,CAAC;AAAA,EACH,GAAG,CAAC,KAAK,CAAC;AAEV,QAAM,eAAe,yBAAyB,UAAU,QAAQ;AAEhE,SAAO;AACT;AAMO,SAAS,iBACd,MACS;AACT,MAAI;AACJ,MAAI;AACF,cAAU,OAAO,IAAI;AACrB,UAAM,IAAI;AACV,YAAQ,QAAQ,GAAG,CAAC;AACpB,YAAQ,WAAW,CAAC;AACpB,WAAO;AAAA,EACT,SAAS,GAAG;AACV,WAAO,CAAC,EACN,aAAa;AAAA,KAEZ,EAAE,SAAS;AAAA,IAEV,EAAE,SAAS;AAAA;AAAA,IAGX,EAAE,SAAS;AAAA,IAEX,EAAE,SAAS;AAAA,IAEb,WACA,QAAQ,WAAW;AAAA,EAEvB;AACF;AAEA,SAAS,sBACP,SACA,OACS;;AACT,SAAO,CAAC,EACN,MAAM,QAAQ,cAAc,iBAC5B,mBAAQ,SAAR,mBAAc,kBAAd,mBAA6B,iBAC3B,MAAM,QAAQ,cAAc;AAElC;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n /** The number of sizes to generate */\n intervals: number;\n /** The smallest image size */\n startingWidth: number;\n /** The increment by which to increase for each size, in pixels */\n incrementSize: number;\n /** The size used for placeholder fallback images */\n placeholderWidth: number;\n};\n\ntype NormalizedProps = {\n alt: string;\n aspectRatio: string | undefined;\n height: string;\n src: string | undefined;\n width: string;\n};\n\nexport type LoaderParams = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: number;\n /** The URL param that controls height */\n height?: number;\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\nexport type Loader = (params: LoaderParams) => string;\n\n/*\n * @TODO: Expand to include focal point support; and/or switch this to be an SF API type\n */\ntype Crop = 'center' | 'top' | 'bottom' | 'left' | 'right';\n\nexport type HydrogenImageProps = React.ComponentPropsWithRef<'img'> &\n HydrogenImageBaseProps;\n\ntype HydrogenImageBaseProps = {\n /** The aspect ratio of the image, in the format of `width/height`.\n *\n * @example\n * ```\n * <Image data={productImage} aspectRatio=\"4/5\" />\n * ```\n */\n aspectRatio?: string;\n /** The crop position of the image.\n *\n * @remarks\n * In the event that AspectRatio is set, without specifying a crop,\n * the Shopify CDN won't return the expected image.\n *\n * @defaultValue `center`\n */\n crop?: Crop;\n /** Data mapping to the [Storefront API `Image`](https://shopify.dev/docs/api/storefront/2025-10/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrogen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n data={data}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n data={data}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FixedWidthImage = React.forwardRef<\n HTMLImageElement,\n FixedWidthImageProps\n>(\n (\n {\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n width,\n data,\n },\n ref,\n ) => {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [\n aspectRatio,\n crop,\n data,\n height,\n imageWidths,\n loader,\n normalizedProps,\n width,\n ]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n },\n);\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FluidImage = React.forwardRef<HTMLImageElement, FluidImageProps>(\n (\n {\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n sizes,\n data,\n },\n ref,\n ) => {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, data, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n },\n);\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nconst PLACEHOLDER_DOMAIN = 'https://placeholder.shopify.com';\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src, PLACEHOLDER_DOMAIN);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href.replace(PLACEHOLDER_DOMAIN, '');\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return typeof width === 'number' || fixedEndings.test(width);\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n sourceDimensions?: {width?: number; height?: number},\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n return imageWidths\n .map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n })\n .filter(({width, height}) => {\n if (sourceDimensions?.width && width > sourceDimensions.width) {\n return false;\n }\n\n if (\n sourceDimensions?.height &&\n height &&\n height > sourceDimensions.height\n ) {\n return false;\n }\n\n return true;\n });\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA4GO,MAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CvB,MAAM,QAAQ,MAAM;AAAA,EACzB,CACE;AAAA,IACE;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA,WAAW;AAAA,IACX,SAAS;AAAA,IACT,SAAS;AAAA,IACT,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,MACd,WAAW;AAAA,MACX,eAAe;AAAA,MACf,eAAe;AAAA,MACf,kBAAkB;AAAA,IAAA;AAAA,IAEpB,QAAQ;AAAA,IACR,GAAG;AAAA,EAAA,GAEL,QACG;AAIH,UAAM,iBAAiB,MAAM,QAAQ,MAAM;AAEzC,YAAM,aACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,QAAQ;AAE9C,YAAM,cACJ,6BAAM,WAAS,6BAAM,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AAQ;AACvC;AASO,SAAS,iBAAiB,aAA0C;AACzE,MAAI,CAAC,YAAa;AAClB,QAAM,CAAC,OAAO,MAAM,IAAI,YAAY,MAAM,GAAG;AAC7C,SAAO,KAAK,OAAO,KAAK,IAAI,OAAO,MAAM;AAC3C;AAGO,SAAS,cACd,aACA,aACA,OAAa,UACb,kBAOY;AACZ,MAAI,CAAC,YAAa;AAClB,SAAO,YACJ,IAAI,CAAC,UAAkB;AACtB,WAAO;AAAA,MACL;AAAA,MACA,QAAQ,cACJ,SAAS,iBAAiB,WAAW,KAAK,KAC1C;AAAA,MACJ;AAAA,IAAA;AAAA,EAEJ,CAAC,EACA,OAAO,CAAC,EAAC,OAAO,aAAY;AAC3B,SAAI,qDAAkB,UAAS,QAAQ,iBAAiB,OAAO;AAC7D,aAAO;AAAA,IACT;AAEA,SACE,qDAAkB,WAClB,UACA,SAAS,iBAAiB,QAC1B;AACA,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,CAAC;AAQL;"}
|
|
1
|
+
{"version":3,"file":"Image.mjs","sources":["../../src/Image.tsx"],"sourcesContent":["/* eslint-disable eslint-comments/disable-enable-pair */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport * as React from 'react';\nimport type {PartialDeep} from 'type-fest';\nimport type {Image as ImageType} from './storefront-api-types.js';\n\n/*\n * An optional prop you can use to change the\n * default srcSet generation behaviour\n */\ntype SrcSetOptions = {\n /** The number of sizes to generate */\n intervals: number;\n /** The smallest image size */\n startingWidth: number;\n /** The increment by which to increase for each size, in pixels */\n incrementSize: number;\n /** The size used for placeholder fallback images */\n placeholderWidth: number;\n};\n\ntype NormalizedProps = {\n alt: string;\n aspectRatio: string | undefined;\n height: string;\n src: string | undefined;\n width: string;\n};\n\nexport type LoaderParams = {\n /** The base URL of the image */\n src?: ImageType['url'];\n /** The URL param that controls width */\n width?: number;\n /** The URL param that controls height */\n height?: number;\n /** The URL param that controls the cropping region */\n crop?: Crop;\n};\n\nexport type Loader = (params: LoaderParams) => string;\n\n/*\n * @TODO: Expand to include focal point support; and/or switch this to be an SF API type\n */\ntype Crop = 'center' | 'top' | 'bottom' | 'left' | 'right';\n\nexport type HydrogenImageProps = React.ComponentPropsWithRef<'img'> &\n HydrogenImageBaseProps;\n\ntype HydrogenImageBaseProps = {\n /** The aspect ratio of the image, in the format of `width/height`.\n *\n * @example\n * ```\n * <Image data={productImage} aspectRatio=\"4/5\" />\n * ```\n */\n aspectRatio?: string;\n /** The crop position of the image.\n *\n * @remarks\n * In the event that AspectRatio is set, without specifying a crop,\n * the Shopify CDN won't return the expected image.\n *\n * @defaultValue `center`\n */\n crop?: Crop;\n /** Data mapping to the [Storefront API `Image`](https://shopify.dev/docs/api/storefront/2026-01/objects/Image) object. Must be an Image object.\n *\n * @example\n * ```\n * import {IMAGE_FRAGMENT, Image} from '@shopify/hydrogen';\n *\n * export const IMAGE_QUERY = `#graphql\n * ${IMAGE_FRAGMENT}\n * query {\n * product {\n * featuredImage {\n * ...Image\n * }\n * }\n * }`\n *\n * <Image\n * data={productImage}\n * sizes=\"(min-width: 45em) 50vw, 100vw\"\n * aspectRatio=\"4/5\"\n * />\n * ```\n *\n * Image: {@link https://shopify.dev/api/storefront/reference/common-objects/image}\n */\n data?: PartialDeep<ImageType, {recurseIntoArrays: true}>;\n /** A function that returns a URL string for an image.\n *\n * @remarks\n * By default, this uses Shopify’s CDN {@link https://cdn.shopify.com/} but you can provide\n * your own function to use a another provider, as long as they support URL based image transformations.\n */\n loader?: Loader;\n /** An optional prop you can use to change the default srcSet generation behaviour */\n srcSetOptions?: SrcSetOptions;\n};\n\n/**\n * A Storefront API GraphQL fragment that can be used to query for an image.\n */\nexport const IMAGE_FRAGMENT = `#graphql\n fragment Image on Image {\n altText\n url\n width\n height\n }\n`;\n\n/**\n * Hydrogen’s Image component is a wrapper around the HTML image element.\n * It supports the same props as the HTML `img` element, but automatically\n * generates the srcSet and sizes attributes for you. For most use cases,\n * you’ll want to set the `aspectRatio` prop to ensure the image is sized\n * correctly.\n *\n * @remarks\n * - `decoding` is set to `async` by default.\n * - `loading` is set to `lazy` by default.\n * - `alt` will automatically be set to the `altText` from the Storefront API if passed in the `data` prop\n * - `src` will automatically be set to the `url` from the Storefront API if passed in the `data` prop\n *\n * @example\n * A responsive image with a 4:5 aspect ratio:\n * ```\n * <Image\n * data={product.featuredImage}\n * aspectRatio=\"4/5\"\n * sizes=\"(min-width: 45em) 40vw, 100vw\"\n * />\n * ```\n * @example\n * A fixed size image:\n * ```\n * <Image\n * data={product.featuredImage}\n * width={100}\n * height={100}\n * />\n * ```\n *\n * {@link https://shopify.dev/docs/api/hydrogen-react/components/image}\n */\nexport const Image = React.forwardRef<HTMLImageElement, HydrogenImageProps>(\n (\n {\n alt,\n aspectRatio,\n crop = 'center',\n data,\n decoding = 'async',\n height = 'auto',\n loader = shopifyLoader,\n loading = 'lazy',\n sizes,\n src,\n srcSetOptions = {\n intervals: 15,\n startingWidth: 200,\n incrementSize: 200,\n placeholderWidth: 100,\n },\n width = '100%',\n ...passthroughProps\n },\n ref,\n ) => {\n /*\n * Gets normalized values for width, height from data prop\n */\n const normalizedData = React.useMemo(() => {\n /* Only use data width if height is also set */\n const dataWidth: number | undefined =\n data?.width && data?.height ? data?.width : undefined;\n\n const dataHeight: number | undefined =\n data?.width && data?.height ? data?.height : undefined;\n\n return {\n width: dataWidth,\n height: dataHeight,\n unitsMatch: Boolean(unitsMatch(dataWidth, dataHeight)),\n };\n }, [data]);\n\n /*\n * Gets normalized values for width, height, src, alt, and aspectRatio props\n * supporting the presence of `data` in addition to flat props.\n */\n const normalizedProps = React.useMemo(() => {\n const nWidthProp: string | number = width || '100%';\n const widthParts = getUnitValueParts(nWidthProp.toString());\n const nWidth = `${widthParts.number}${widthParts.unit}`;\n\n const autoHeight = height === undefined || height === null;\n const heightParts = autoHeight\n ? null\n : getUnitValueParts(height.toString());\n\n const fixedHeight = heightParts\n ? `${heightParts.number}${heightParts.unit}`\n : '';\n\n const nHeight = autoHeight ? 'auto' : fixedHeight;\n\n const nSrc: string | undefined = src || data?.url;\n\n if (__HYDROGEN_DEV__ && !nSrc) {\n console.warn(\n `No src or data.url provided to Image component.`,\n passthroughProps?.key || '',\n );\n }\n\n const nAlt: string = data?.altText && !alt ? data?.altText : alt || '';\n\n const nAspectRatio: string | undefined = aspectRatio\n ? aspectRatio\n : normalizedData.unitsMatch\n ? [\n getNormalizedFixedUnit(normalizedData.width),\n getNormalizedFixedUnit(normalizedData.height),\n ].join('/')\n : undefined;\n\n return {\n width: nWidth,\n height: nHeight,\n src: nSrc,\n alt: nAlt,\n aspectRatio: nAspectRatio,\n };\n }, [\n width,\n height,\n src,\n data,\n alt,\n aspectRatio,\n normalizedData,\n passthroughProps?.key,\n ]);\n\n const {intervals, startingWidth, incrementSize, placeholderWidth} =\n srcSetOptions;\n\n /*\n * This function creates an array of widths to be used in srcSet\n */\n const imageWidths = React.useMemo(() => {\n return generateImageWidths(\n width,\n intervals,\n startingWidth,\n incrementSize,\n );\n }, [width, intervals, startingWidth, incrementSize]);\n\n const fixedWidth = isFixedWidth(normalizedProps.width);\n\n if (__HYDROGEN_DEV__ && !sizes && !fixedWidth) {\n console.warn(\n [\n 'No sizes prop provided to Image component,',\n 'you may be loading unnecessarily large images.',\n `Image used is ${\n src || data?.url || passthroughProps?.key || 'unknown'\n }`,\n ].join(' '),\n );\n }\n\n /*\n * We check to see whether the image is fixed width or not,\n * if fixed, we still provide a srcSet, but only to account for\n * different pixel densities.\n */\n if (fixedWidth) {\n return (\n <FixedWidthImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n height={height}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n ref={ref}\n width={width}\n data={data}\n />\n );\n } else {\n return (\n <FluidImage\n aspectRatio={aspectRatio}\n crop={crop}\n decoding={decoding}\n imageWidths={imageWidths}\n loader={loader}\n loading={loading}\n normalizedProps={normalizedProps}\n passthroughProps={passthroughProps}\n placeholderWidth={placeholderWidth}\n ref={ref}\n sizes={sizes}\n data={data}\n />\n );\n }\n },\n);\n\ntype FixedImageExludedProps =\n | 'data'\n | 'loader'\n | 'loaderOptions'\n | 'sizes'\n | 'srcSetOptions'\n | 'widths';\n\ntype FixedWidthImageProps = Omit<HydrogenImageProps, FixedImageExludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n loader: Loader;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n normalizedProps: NormalizedProps;\n imageWidths: number[];\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FixedWidthImage = React.forwardRef<\n HTMLImageElement,\n FixedWidthImageProps\n>(\n (\n {\n aspectRatio,\n crop,\n decoding,\n height,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n width,\n data,\n },\n ref,\n ) => {\n const fixed = React.useMemo(() => {\n const intWidth: number | undefined = getNormalizedFixedUnit(width);\n const intHeight: number | undefined = getNormalizedFixedUnit(height);\n\n /*\n * The aspect ratio for fixed width images is taken from the explicitly\n * set prop, but if that's not present, and both width and height are\n * set, we calculate the aspect ratio from the width and height—as\n * long as they share the same unit type (e.g. both are 'px').\n */\n const fixedAspectRatio = aspectRatio\n ? aspectRatio\n : unitsMatch(normalizedProps.width, normalizedProps.height)\n ? [intWidth, intHeight].join('/')\n : normalizedProps.aspectRatio\n ? normalizedProps.aspectRatio\n : undefined;\n\n /*\n * The Sizes Array generates an array of all the parts\n * that make up the srcSet, including the width, height, and crop\n */\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, fixedAspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const fixedHeight = intHeight\n ? intHeight\n : fixedAspectRatio && intWidth\n ? intWidth * (parseAspectRatio(fixedAspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n const src = loader({\n src: normalizedProps.src,\n width: intWidth,\n height: fixedHeight,\n crop: normalizedProps.height === 'auto' ? undefined : crop,\n });\n\n return {\n width: intWidth,\n aspectRatio: fixedAspectRatio,\n height: fixedHeight,\n srcSet,\n src,\n };\n }, [\n aspectRatio,\n crop,\n data,\n height,\n imageWidths,\n loader,\n normalizedProps,\n width,\n ]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fixed.height}\n loading={loading}\n src={fixed.src}\n srcSet={fixed.srcSet}\n width={fixed.width}\n style={{\n aspectRatio: fixed.aspectRatio,\n ...passthroughProps.style,\n }}\n {...passthroughProps}\n />\n );\n },\n);\n\ntype FluidImageExcludedProps =\n | 'data'\n | 'width'\n | 'height'\n | 'loader'\n | 'loaderOptions'\n | 'srcSetOptions';\n\ntype FluidImageProps = Omit<HydrogenImageProps, FluidImageExcludedProps> &\n Pick<HydrogenImageBaseProps, 'data'> & {\n imageWidths: number[];\n loader: Loader;\n normalizedProps: NormalizedProps;\n passthroughProps: React.ImgHTMLAttributes<HTMLImageElement>;\n placeholderWidth: number;\n ref: React.Ref<HTMLImageElement>;\n };\n\nconst FluidImage = React.forwardRef<HTMLImageElement, FluidImageProps>(\n (\n {\n crop,\n decoding,\n imageWidths,\n loader = shopifyLoader,\n loading,\n normalizedProps,\n passthroughProps,\n placeholderWidth,\n sizes,\n data,\n },\n ref,\n ) => {\n const fluid = React.useMemo(() => {\n const sizesArray =\n imageWidths === undefined\n ? undefined\n : generateSizes(imageWidths, normalizedProps.aspectRatio, crop, {\n width: data?.width ?? undefined,\n height: data?.height ?? undefined,\n });\n\n const placeholderHeight =\n normalizedProps.aspectRatio && placeholderWidth\n ? placeholderWidth *\n (parseAspectRatio(normalizedProps.aspectRatio) ?? 1)\n : undefined;\n\n const srcSet = generateSrcSet(normalizedProps.src, sizesArray, loader);\n\n const src = loader({\n src: normalizedProps.src,\n width: placeholderWidth,\n height: placeholderHeight,\n crop,\n });\n\n return {\n placeholderHeight,\n srcSet,\n src,\n };\n }, [crop, data, imageWidths, loader, normalizedProps, placeholderWidth]);\n\n return (\n <img\n ref={ref}\n alt={normalizedProps.alt}\n decoding={decoding}\n height={fluid.placeholderHeight}\n loading={loading}\n sizes={sizes}\n src={fluid.src}\n srcSet={fluid.srcSet}\n width={placeholderWidth}\n {...passthroughProps}\n style={{\n width: normalizedProps.width,\n aspectRatio: normalizedProps.aspectRatio,\n ...passthroughProps.style,\n }}\n />\n );\n },\n);\n\n/**\n * The shopifyLoader function is a simple utility function that takes a src, width,\n * height, and crop and returns a string that can be used as the src for an image.\n * It can be used with the Hydrogen Image component or with the next/image component.\n * (or any others that accept equivalent configuration)\n * @param src - The source URL of the image, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg`\n * @param width - The width of the image, e.g. `100`\n * @param height - The height of the image, e.g. `100`\n * @param crop - The crop of the image, e.g. `center`\n * @returns A Shopify image URL with the correct query parameters, e.g. `https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=100&height=100&crop=center`\n *\n * @example\n * ```\n * shopifyLoader({\n * src: 'https://cdn.shopify.com/static/sample-images/garnished.jpeg',\n * width: 100,\n * height: 100,\n * crop: 'center',\n * })\n * ```\n */\nconst PLACEHOLDER_DOMAIN = 'https://placeholder.shopify.com';\nexport function shopifyLoader({src, width, height, crop}: LoaderParams) {\n if (!src) {\n return '';\n }\n\n const url = new URL(src, PLACEHOLDER_DOMAIN);\n\n if (width) {\n url.searchParams.append('width', Math.round(width).toString());\n }\n\n if (height) {\n url.searchParams.append('height', Math.round(height).toString());\n }\n\n if (crop) {\n url.searchParams.append('crop', crop);\n }\n return url.href.replace(PLACEHOLDER_DOMAIN, '');\n}\n\n/**\n * Checks whether the width and height share the same unit type\n * @param width - The width of the image, e.g. 100% | 10px\n * @param height - The height of the image, e.g. auto | 100px\n * @returns Whether the width and height share the same unit type (boolean)\n */\nfunction unitsMatch(\n width: string | number = '100%',\n height: string | number = 'auto',\n): boolean {\n return (\n getUnitValueParts(width.toString()).unit ===\n getUnitValueParts(height.toString()).unit\n );\n}\n\n/**\n * Given a CSS size, returns the unit and number parts of the value\n * @param value - The CSS size, e.g. 100px\n * @returns The unit and number parts of the value, e.g. \\{unit: 'px', number: 100\\}\n */\nfunction getUnitValueParts(value: string): {unit: string; number: number} {\n const unit = value.replace(/[0-9.]/g, '');\n const number = parseFloat(value.replace(unit, ''));\n\n return {\n unit: unit === '' ? (number === undefined ? 'auto' : 'px') : unit,\n number,\n };\n}\n\n/**\n * Given a value, returns the width of the image as an integer in pixels\n * @param value - The width of the image, e.g. 16px | 1rem | 1em | 16\n * @returns The width of the image in pixels, e.g. 16, or undefined if the value is not a fixed unit\n */\nfunction getNormalizedFixedUnit(value?: string | number): number | undefined {\n if (value === undefined) {\n return;\n }\n\n const {unit, number} = getUnitValueParts(value.toString());\n\n switch (unit) {\n case 'em':\n return number * 16;\n case 'rem':\n return number * 16;\n case 'px':\n return number;\n case '':\n return number;\n default:\n return;\n }\n}\n\n/**\n * This function checks whether a width is fixed or not.\n * @param width - The width of the image, e.g. 100 | '100px' | '100em' | '100rem'\n * @returns Whether the width is fixed or not\n */\nfunction isFixedWidth(width: string | number): boolean {\n const fixedEndings = /\\d(px|em|rem)$/;\n return typeof width === 'number' || fixedEndings.test(width);\n}\n\n/**\n * This function generates a srcSet for Shopify images.\n * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg\n * @param sizesArray - An array of objects containing the `width`, `height`, and `crop` of the image, e.g. [\\{width: 200, height: 200, crop: 'center'\\}, \\{width: 400, height: 400, crop: 'center'\\}]\n * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters\n * @returns A srcSet for Shopify images, e.g. 'https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=200&height=200&crop=center 200w, https://cdn.shopify.com/static/sample-images/garnished.jpeg?width=400&height=400&crop=center 400w'\n */\nexport function generateSrcSet(\n src?: string,\n sizesArray?: Array<{width?: number; height?: number; crop?: Crop}>,\n loader: Loader = shopifyLoader,\n): string {\n if (!src) {\n return '';\n }\n\n if (sizesArray?.length === 0 || !sizesArray) {\n return src;\n }\n\n return sizesArray\n .map(\n (size, i) =>\n `${loader({\n src,\n width: size.width,\n height: size.height,\n crop: size.crop,\n })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`,\n )\n .join(`, `);\n}\n\n/**\n * This function generates an array of sizes for Shopify images, for both fixed and responsive images.\n * @param width - The CSS width of the image\n * @param intervals - The number of intervals to generate\n * @param startingWidth - The starting width of the image\n * @param incrementSize - The size of each interval\n * @returns An array of widths\n */\nexport function generateImageWidths(\n width: string | number = '100%',\n intervals: number,\n startingWidth: number,\n incrementSize: number,\n): number[] {\n const responsive = Array.from(\n {length: intervals},\n (_, i) => i * incrementSize + startingWidth,\n );\n\n const fixed = Array.from(\n {length: 3},\n (_, i) => (i + 1) * (getNormalizedFixedUnit(width) ?? 0),\n );\n\n return isFixedWidth(width) ? fixed : responsive;\n}\n\n/**\n * Simple utility function to convert an aspect ratio CSS string to a decimal, currently only supports values like `1/1`, not `0.5`, or `auto`\n * @param aspectRatio - The aspect ratio of the image, e.g. `1/1`\n * @returns The aspect ratio as a number, e.g. `0.5`\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio}\n */\nexport function parseAspectRatio(aspectRatio?: string): number | undefined {\n if (!aspectRatio) return;\n const [width, height] = aspectRatio.split('/');\n return 1 / (Number(width) / Number(height));\n}\n\n// Generate data needed for Imagery loader\nexport function generateSizes(\n imageWidths?: number[],\n aspectRatio?: string,\n crop: Crop = 'center',\n sourceDimensions?: {width?: number; height?: number},\n):\n | {\n width: number;\n height: number | undefined;\n crop: Crop;\n }[]\n | undefined {\n if (!imageWidths) return;\n return imageWidths\n .map((width: number) => {\n return {\n width,\n height: aspectRatio\n ? width * (parseAspectRatio(aspectRatio) ?? 1)\n : undefined,\n crop,\n };\n })\n .filter(({width, height}) => {\n if (sourceDimensions?.width && width > sourceDimensions.width) {\n return false;\n }\n\n if (\n sourceDimensions?.height &&\n height &&\n height > sourceDimensions.height\n ) {\n return false;\n }\n\n return true;\n });\n /*\n Given:\n ([100, 200], 1/1, 'center')\n Returns:\n [{width: 100, height: 100, crop: 'center'},\n {width: 200, height: 200, crop: 'center'}]\n */\n}\n"],"names":[],"mappings":";;AA4GO,MAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CvB,MAAM,QAAQ,MAAM;AAAA,EACzB,CACE;AAAA,IACE;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA,WAAW;AAAA,IACX,SAAS;AAAA,IACT,SAAS;AAAA,IACT,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,MACd,WAAW;AAAA,MACX,eAAe;AAAA,MACf,eAAe;AAAA,MACf,kBAAkB;AAAA,IAAA;AAAA,IAEpB,QAAQ;AAAA,IACR,GAAG;AAAA,EAAA,GAEL,QACG;AAIH,UAAM,iBAAiB,MAAM,QAAQ,MAAM;AAEzC,YAAM,aACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,QAAQ;AAE9C,YAAM,cACJ,6BAAM,WAAS,6BAAM,UAAS,6BAAM,SAAS;AAE/C,aAAO;AAAA,QACL,OAAO;AAAA,QACP,QAAQ;AAAA,QACR,YAAY,QAAQ,WAAW,WAAW,UAAU,CAAC;AAAA,MAAA;AAAA,IAEzD,GAAG,CAAC,IAAI,CAAC;AAMT,UAAM,kBAAkB,MAAM,QAAQ,MAAM;AAC1C,YAAM,aAA8B,SAAS;AAC7C,YAAM,aAAa,kBAAkB,WAAW,SAAA,CAAU;AAC1D,YAAM,SAAS,GAAG,WAAW,MAAM,GAAG,WAAW,IAAI;AAErD,YAAM,aAAa,WAAW,UAAa,WAAW;AACtD,YAAM,cAAc,aAChB,OACA,kBAAkB,OAAO,UAAU;AAEvC,YAAM,cAAc,cAChB,GAAG,YAAY,MAAM,GAAG,YAAY,IAAI,KACxC;AAEJ,Y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