@shopify/hydrogen-react 2026.4.2 → 2026.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/browser-dev/Image.mjs +4 -3
  2. package/dist/browser-dev/Image.mjs.map +1 -1
  3. package/dist/browser-dev/ShopifyProvider.mjs.map +1 -1
  4. package/dist/browser-dev/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
  5. package/dist/browser-dev/load-script.mjs +1 -1
  6. package/dist/browser-dev/packages/hydrogen-react/package.mjs +1 -1
  7. package/dist/browser-dev/packages/hydrogen-react/package.mjs.map +1 -1
  8. package/dist/browser-dev/tracking-utils.mjs +17 -58
  9. package/dist/browser-dev/tracking-utils.mjs.map +1 -1
  10. package/dist/browser-dev/useShopifyCookies.mjs +34 -97
  11. package/dist/browser-dev/useShopifyCookies.mjs.map +1 -1
  12. package/dist/browser-prod/Image.mjs +4 -3
  13. package/dist/browser-prod/Image.mjs.map +1 -1
  14. package/dist/browser-prod/ShopifyProvider.mjs.map +1 -1
  15. package/dist/browser-prod/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
  16. package/dist/browser-prod/load-script.mjs +1 -1
  17. package/dist/browser-prod/packages/hydrogen-react/package.mjs +1 -1
  18. package/dist/browser-prod/packages/hydrogen-react/package.mjs.map +1 -1
  19. package/dist/browser-prod/tracking-utils.mjs +17 -58
  20. package/dist/browser-prod/tracking-utils.mjs.map +1 -1
  21. package/dist/browser-prod/useShopifyCookies.mjs +34 -97
  22. package/dist/browser-prod/useShopifyCookies.mjs.map +1 -1
  23. package/dist/node-dev/Image.js +4 -3
  24. package/dist/node-dev/Image.js.map +1 -1
  25. package/dist/node-dev/Image.mjs +4 -3
  26. package/dist/node-dev/Image.mjs.map +1 -1
  27. package/dist/node-dev/ShopifyProvider.js.map +1 -1
  28. package/dist/node-dev/ShopifyProvider.mjs.map +1 -1
  29. package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.js +1 -1
  30. package/dist/node-dev/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
  31. package/dist/node-dev/load-script.js +2 -0
  32. package/dist/node-dev/load-script.js.map +1 -1
  33. package/dist/node-dev/load-script.mjs +1 -1
  34. package/dist/node-dev/packages/hydrogen-react/package.js +1 -1
  35. package/dist/node-dev/packages/hydrogen-react/package.js.map +1 -1
  36. package/dist/node-dev/packages/hydrogen-react/package.mjs +1 -1
  37. package/dist/node-dev/packages/hydrogen-react/package.mjs.map +1 -1
  38. package/dist/node-dev/tracking-utils.js +17 -58
  39. package/dist/node-dev/tracking-utils.js.map +1 -1
  40. package/dist/node-dev/tracking-utils.mjs +17 -58
  41. package/dist/node-dev/tracking-utils.mjs.map +1 -1
  42. package/dist/node-dev/useShopifyCookies.js +34 -97
  43. package/dist/node-dev/useShopifyCookies.js.map +1 -1
  44. package/dist/node-dev/useShopifyCookies.mjs +34 -97
  45. package/dist/node-dev/useShopifyCookies.mjs.map +1 -1
  46. package/dist/node-prod/Image.js +4 -3
  47. package/dist/node-prod/Image.js.map +1 -1
  48. package/dist/node-prod/Image.mjs +4 -3
  49. package/dist/node-prod/Image.mjs.map +1 -1
  50. package/dist/node-prod/ShopifyProvider.js.map +1 -1
  51. package/dist/node-prod/ShopifyProvider.mjs.map +1 -1
  52. package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.js +1 -1
  53. package/dist/node-prod/analytics-schema-custom-storefront-customer-tracking.mjs +1 -1
  54. package/dist/node-prod/load-script.js +2 -0
  55. package/dist/node-prod/load-script.js.map +1 -1
  56. package/dist/node-prod/load-script.mjs +1 -1
  57. package/dist/node-prod/packages/hydrogen-react/package.js +1 -1
  58. package/dist/node-prod/packages/hydrogen-react/package.js.map +1 -1
  59. package/dist/node-prod/packages/hydrogen-react/package.mjs +1 -1
  60. package/dist/node-prod/packages/hydrogen-react/package.mjs.map +1 -1
  61. package/dist/node-prod/tracking-utils.js +17 -58
  62. package/dist/node-prod/tracking-utils.js.map +1 -1
  63. package/dist/node-prod/tracking-utils.mjs +17 -58
  64. package/dist/node-prod/tracking-utils.mjs.map +1 -1
  65. package/dist/node-prod/useShopifyCookies.js +34 -97
  66. package/dist/node-prod/useShopifyCookies.js.map +1 -1
  67. package/dist/node-prod/useShopifyCookies.mjs +34 -97
  68. package/dist/node-prod/useShopifyCookies.mjs.map +1 -1
  69. package/dist/types/Image.d.ts +2 -1
  70. package/dist/types/ShopifyProvider.d.ts +3 -0
  71. package/dist/types/tracking-utils.d.ts +5 -4
  72. package/dist/types/useShopifyCookies.d.ts +14 -33
  73. package/dist/umd/hydrogen-react.dev.js +59 -165
  74. package/dist/umd/hydrogen-react.dev.js.map +1 -1
  75. package/dist/umd/hydrogen-react.prod.js +4 -4
  76. package/dist/umd/hydrogen-react.prod.js.map +1 -1
  77. package/package.json +2 -2
@@ -1,85 +1,50 @@
1
1
  require("./_virtual/_rolldown/runtime.js");
2
- const require_cart_constants = require("./cart-constants.js");
3
2
  const require_tracking_utils = require("./tracking-utils.js");
4
- const require_cookies_utils = require("./cookies-utils.js");
5
3
  let react = require("react");
6
- let worktop_cookie = require("worktop/cookie");
7
4
  //#region src/useShopifyCookies.tsx
8
- var longTermLength = 3600 * 24 * 360 * 1;
9
- var shortTermLength = 1800;
5
+ var CONSENT_MANAGEMENT_MARKER_HEADER = "Shopify-Storefront-Consent-Management";
10
6
  /**
11
- * Sets the `shopify_y` and `shopify_s` cookies in the browser based on user consent
12
- * for backward compatibility support.
7
+ * Optionally refreshes backend-managed cookies for standalone integrations.
8
+ * The Customer Privacy API owns tracking values and legacy cookie expiration.
13
9
  *
14
- * If `fetchTrackingValues` is true, it makes a request to Storefront API
15
- * to fetch or refresh Shopiy analytics and marketing cookies and tracking values.
16
- * Generally speaking, this should only be needed if you're not using Hydrogen's
17
- * built-in analytics components and hooks that already handle this automatically.
18
- * For example, set it to `true` if you are using `hydrogen-react` only with
19
- * a different framework and still need to make a same-domain request to
20
- * Storefront API to set cookies.
10
+ * If `fetchTrackingValues` is true, this sends a consent request through the
11
+ * Storefront API proxy, retrying against `checkoutDomain` if provided. Hydrogen's
12
+ * built-in analytics already delegates consent initialization to the Customer
13
+ * Privacy API and does not use this hook.
21
14
  *
22
- * If `ignoreDeprecatedCookies` is true, it skips setting the deprecated cookies entirely.
23
- * Useful when you only want to use the newer tracking values and not rely on the deprecated ones.
24
- *
25
- * @returns `true` when cookies are set and ready.
15
+ * @returns `true` when the consent request has settled and cookies are ready.
26
16
  * @publicDocs
27
17
  */
28
18
  function useShopifyCookies(options) {
29
- const { hasUserConsent, domain = "", checkoutDomain = "", storefrontAccessToken, fetchTrackingValues, ignoreDeprecatedCookies = false } = options || {};
30
- const coreCookiesReady = useCoreShopifyCookies({
31
- storefrontAccessToken,
32
- fetchTrackingValues,
33
- checkoutDomain
34
- });
19
+ const { checkoutDomain, storefrontAccessToken, fetchTrackingValues = false } = options ?? {};
20
+ const [cookiesReady, setCookiesReady] = (0, react.useState)(!fetchTrackingValues);
21
+ const hasFetchedTrackingValues = (0, react.useRef)(false);
35
22
  (0, react.useEffect)(() => {
36
- if (ignoreDeprecatedCookies || !coreCookiesReady) return;
37
- /**
38
- * Setting cookie with domain
39
- *
40
- * If no domain is provided, the cookie will be set for the current host.
41
- * For Shopify, we need to ensure this domain is set with a leading dot.
42
- */
43
- let currentDomain = domain || window.location.host;
44
- if (checkoutDomain) {
45
- const checkoutDomainParts = checkoutDomain.split(".").reverse();
46
- const currentDomainParts = currentDomain.split(".").reverse();
47
- const sameDomainParts = [];
48
- checkoutDomainParts.forEach((part, index) => {
49
- if (part === currentDomainParts[index]) sameDomainParts.push(part);
50
- });
51
- currentDomain = sameDomainParts.reverse().join(".");
52
- }
53
- if (/^localhost/.test(currentDomain)) currentDomain = "";
54
- const domainWithLeadingDot = currentDomain ? /^\./.test(currentDomain) ? currentDomain : `.${currentDomain}` : "";
55
- /**
56
- * Set user and session cookies and refresh the expiry time
57
- */
58
- if (hasUserConsent) {
59
- const trackingValues = require_tracking_utils.getTrackingValues();
60
- if ((trackingValues.uniqueToken || trackingValues.visitToken || "").startsWith("00000000-")) return;
61
- setCookie(require_cart_constants.SHOPIFY_Y, trackingValues.uniqueToken || require_cookies_utils.buildUUID(), longTermLength, domainWithLeadingDot);
62
- setCookie(require_cart_constants.SHOPIFY_S, trackingValues.visitToken || require_cookies_utils.buildUUID(), shortTermLength, domainWithLeadingDot);
63
- } else {
64
- setCookie(require_cart_constants.SHOPIFY_Y, "", 0, domainWithLeadingDot);
65
- setCookie(require_cart_constants.SHOPIFY_S, "", 0, domainWithLeadingDot);
23
+ if (!fetchTrackingValues) {
24
+ setCookiesReady(true);
25
+ return;
66
26
  }
27
+ if (hasFetchedTrackingValues.current) return;
28
+ hasFetchedTrackingValues.current = true;
29
+ const fetchConsentValues = async () => {
30
+ try {
31
+ return await fetchTrackingValuesFromBrowser(storefrontAccessToken);
32
+ } catch (sameOriginError) {
33
+ if (!checkoutDomain) throw sameOriginError;
34
+ return fetchTrackingValuesFromBrowser(storefrontAccessToken, checkoutDomain);
35
+ }
36
+ };
37
+ fetchConsentValues().catch((error) => {
38
+ console.warn("[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: " + (error instanceof Error ? error.message : String(error)));
39
+ }).finally(() => {
40
+ setCookiesReady(true);
41
+ });
67
42
  }, [
68
- coreCookiesReady,
69
- hasUserConsent,
70
- domain,
71
43
  checkoutDomain,
72
- ignoreDeprecatedCookies
44
+ fetchTrackingValues,
45
+ storefrontAccessToken
73
46
  ]);
74
- return coreCookiesReady;
75
- }
76
- function setCookie(name, value, maxage, domain) {
77
- document.cookie = (0, worktop_cookie.stringify)(name, value, {
78
- maxage,
79
- domain,
80
- samesite: "Lax",
81
- path: "/"
82
- });
47
+ return cookiesReady;
83
48
  }
84
49
  async function fetchTrackingValuesFromBrowser(storefrontAccessToken, storefrontApiDomain = "") {
85
50
  const { uniqueToken, visitToken } = require_tracking_utils.getTrackingValues();
@@ -88,43 +53,15 @@ async function fetchTrackingValuesFromBrowser(storefrontAccessToken, storefrontA
88
53
  headers: {
89
54
  "Content-Type": "application/json",
90
55
  ...storefrontAccessToken && { "X-Shopify-Storefront-Access-Token": storefrontAccessToken },
56
+ ...storefrontApiDomain ? void 0 : { [CONSENT_MANAGEMENT_MARKER_HEADER]: "1" },
91
57
  ...visitToken || uniqueToken ? {
92
58
  [require_tracking_utils.SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,
93
59
  [require_tracking_utils.SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken
94
60
  } : void 0
95
61
  },
96
- body: JSON.stringify({ query: "query ensureCookies { consentManagement { cookies(visitorConsent:{}) { cookieDomain } } }" })
62
+ body: JSON.stringify({ query: "query ensureCookies { consentManagement { cookies(visitorConsent:{}) { trackingConsentCookie cookieDomain shopifyUnique shopifyVisit } } }" })
97
63
  });
98
64
  if (!response.ok) throw new Error(`Failed to fetch consent from browser: ${response.status} ${response.statusText}`);
99
- await response.json();
100
- require_tracking_utils.getTrackingValues();
101
- }
102
- /**
103
- * Gets http-only cookies from Storefront API via same-origin fetch request.
104
- * Falls back to checkout domain if provided to at least obtain the tracking
105
- * values via server-timing headers.
106
- */
107
- function useCoreShopifyCookies({ checkoutDomain, storefrontAccessToken, fetchTrackingValues = false }) {
108
- const [cookiesReady, setCookiesReady] = (0, react.useState)(!fetchTrackingValues);
109
- const hasFetchedTrackingValues = (0, react.useRef)(false);
110
- (0, react.useEffect)(() => {
111
- if (!fetchTrackingValues) {
112
- setCookiesReady(true);
113
- return;
114
- }
115
- if (hasFetchedTrackingValues.current) return;
116
- hasFetchedTrackingValues.current = true;
117
- fetchTrackingValuesFromBrowser(storefrontAccessToken).catch((error) => checkoutDomain ? fetchTrackingValuesFromBrowser(storefrontAccessToken, checkoutDomain) : Promise.reject(error)).catch((error) => {
118
- console.warn("[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: " + (error instanceof Error ? error.message : String(error)));
119
- }).finally(() => {
120
- setCookiesReady(true);
121
- });
122
- }, [
123
- checkoutDomain,
124
- fetchTrackingValues,
125
- storefrontAccessToken
126
- ]);
127
- return cookiesReady;
128
65
  }
129
66
  //#endregion
130
67
  exports.useShopifyCookies = useShopifyCookies;
@@ -1 +1 @@
1
- {"version":3,"file":"useShopifyCookies.js","names":[],"sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect, useRef, useState} from 'react';\n// @ts-ignore - worktop/cookie types not properly exported\nimport {stringify} from 'worktop/cookie';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\nimport {buildUUID} from './cookies-utils.js';\nimport {\n getTrackingValues,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from './tracking-utils.js';\n\nconst longTermLength = 60 * 60 * 24 * 360 * 1; // ~1 year expiry\nconst shortTermLength = 60 * 30; // 30 mins\n\ntype UseShopifyCookiesOptions = CoreShopifyCookiesOptions & {\n /**\n * If set to `false`, Shopify cookies will be removed.\n * If set to `true`, Shopify unique user token cookie will have cookie expiry of 1 year.\n * Defaults to false.\n **/\n hasUserConsent?: boolean;\n /**\n * The domain scope of the cookie. Defaults to empty string.\n **/\n domain?: string;\n /**\n * The checkout domain of the shop. Defaults to empty string. If set, the cookie domain will check if it can be set with the checkout domain.\n */\n checkoutDomain?: string;\n /**\n * If set to `true`, it skips modifying the deprecated shopify_y and shopify_s cookies.\n */\n ignoreDeprecatedCookies?: boolean;\n};\n\n/**\n * Sets the `shopify_y` and `shopify_s` cookies in the browser based on user consent\n * for backward compatibility support.\n *\n * If `fetchTrackingValues` is true, it makes a request to Storefront API\n * to fetch or refresh Shopiy analytics and marketing cookies and tracking values.\n * Generally speaking, this should only be needed if you're not using Hydrogen's\n * built-in analytics components and hooks that already handle this automatically.\n * For example, set it to `true` if you are using `hydrogen-react` only with\n * a different framework and still need to make a same-domain request to\n * Storefront API to set cookies.\n *\n * If `ignoreDeprecatedCookies` is true, it skips setting the deprecated cookies entirely.\n * Useful when you only want to use the newer tracking values and not rely on the deprecated ones.\n *\n * @returns `true` when cookies are set and ready.\n * @publicDocs\n */\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): boolean {\n const {\n hasUserConsent,\n domain = '',\n checkoutDomain = '',\n storefrontAccessToken,\n fetchTrackingValues,\n ignoreDeprecatedCookies = false,\n } = options || {};\n\n const coreCookiesReady = useCoreShopifyCookies({\n storefrontAccessToken,\n fetchTrackingValues,\n checkoutDomain,\n });\n\n useEffect(() => {\n // Skip setting JS cookies until http-only cookies and server-timing\n // are ready so that we have values synced in JS and http-only cookies.\n if (ignoreDeprecatedCookies || !coreCookiesReady) return;\n\n /**\n * Setting cookie with domain\n *\n * If no domain is provided, the cookie will be set for the current host.\n * For Shopify, we need to ensure this domain is set with a leading dot.\n */\n\n // Use override domain or current host\n let currentDomain = domain || window.location.host;\n\n if (checkoutDomain) {\n const checkoutDomainParts = checkoutDomain.split('.').reverse();\n const currentDomainParts = currentDomain.split('.').reverse();\n const sameDomainParts: Array<string> = [];\n checkoutDomainParts.forEach((part, index) => {\n if (part === currentDomainParts[index]) {\n sameDomainParts.push(part);\n }\n });\n\n currentDomain = sameDomainParts.reverse().join('.');\n }\n\n // Reset domain if localhost\n if (/^localhost/.test(currentDomain)) currentDomain = '';\n\n // Shopify checkout only consumes cookies set with leading dot domain\n const domainWithLeadingDot = currentDomain\n ? /^\\./.test(currentDomain)\n ? currentDomain\n : `.${currentDomain}`\n : '';\n\n /**\n * Set user and session cookies and refresh the expiry time\n */\n if (hasUserConsent) {\n const trackingValues = getTrackingValues();\n if (\n (\n trackingValues.uniqueToken ||\n trackingValues.visitToken ||\n ''\n ).startsWith('00000000-')\n ) {\n // Skip writing cookies when tracking values signal we don't have consent yet\n return;\n }\n\n setCookie(\n SHOPIFY_Y,\n trackingValues.uniqueToken || buildUUID(),\n longTermLength,\n domainWithLeadingDot,\n );\n setCookie(\n SHOPIFY_S,\n trackingValues.visitToken || buildUUID(),\n shortTermLength,\n domainWithLeadingDot,\n );\n } else {\n setCookie(SHOPIFY_Y, '', 0, domainWithLeadingDot);\n setCookie(SHOPIFY_S, '', 0, domainWithLeadingDot);\n }\n }, [\n coreCookiesReady,\n hasUserConsent,\n domain,\n checkoutDomain,\n ignoreDeprecatedCookies,\n ]);\n\n return coreCookiesReady;\n}\n\nfunction setCookie(\n name: string,\n value: string,\n maxage: number,\n domain: string,\n): void {\n document.cookie = stringify(name, value, {\n maxage,\n domain,\n samesite: 'Lax',\n path: '/',\n });\n}\n\nasync function fetchTrackingValuesFromBrowser(\n storefrontAccessToken?: string,\n storefrontApiDomain = '',\n): Promise<void> {\n // These values might come from server-timing or old cookies.\n // If consent cannot be initially assumed, these tokens\n // will be dropped in SFAPI and it will return a mock token\n // starting with '00000000-'.\n // However, if consent can be assumed initially, these tokens\n // will be used to create proper cookies and continue our flow.\n const {uniqueToken, visitToken} = getTrackingValues();\n\n const response = await fetch(\n // TODO: update this endpoint when it becomes stable\n `${storefrontApiDomain.replace(/\\/+$/, '')}/api/unstable/graphql.json`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(storefrontAccessToken && {\n 'X-Shopify-Storefront-Access-Token': storefrontAccessToken,\n }),\n ...(visitToken || uniqueToken\n ? {\n [SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,\n [SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken,\n }\n : undefined),\n },\n body: JSON.stringify({\n query:\n // This query ensures we get _cmp (consent) server-timing header, which is not available in other queries.\n // This value can be passed later to consent-tracking-api and privacy-banner scripts to avoid extra requests.\n 'query ensureCookies { consentManagement { cookies(visitorConsent:{}) { cookieDomain } } }',\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch consent from browser: ${response.status} ${response.statusText}`,\n );\n }\n\n // Consume the body to complete the request and\n // ensure server-timing is available in performance API\n await response.json();\n\n // Ensure we cache the latest tracking values from resources timing\n getTrackingValues();\n}\n\ntype CoreShopifyCookiesOptions = {\n storefrontAccessToken?: string;\n fetchTrackingValues?: boolean;\n checkoutDomain?: string;\n};\n\n/**\n * Gets http-only cookies from Storefront API via same-origin fetch request.\n * Falls back to checkout domain if provided to at least obtain the tracking\n * values via server-timing headers.\n */\nfunction useCoreShopifyCookies({\n checkoutDomain,\n storefrontAccessToken,\n fetchTrackingValues = false,\n}: CoreShopifyCookiesOptions) {\n const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);\n const hasFetchedTrackingValues = useRef(false);\n\n useEffect(() => {\n if (!fetchTrackingValues) {\n // Backend did the work, or proxy is disabled.\n setCookiesReady(true);\n return;\n }\n\n // React runs effects twice in dev mode, avoid double fetching\n if (hasFetchedTrackingValues.current) return;\n hasFetchedTrackingValues.current = true;\n\n // Fetch consent from browser via proxy\n fetchTrackingValuesFromBrowser(storefrontAccessToken)\n .catch((error) =>\n checkoutDomain\n ? // Retry with checkout domain if available to at least\n // get the server-timing values for tracking.\n fetchTrackingValuesFromBrowser(\n storefrontAccessToken,\n checkoutDomain,\n )\n : Promise.reject(error),\n )\n .catch((error) => {\n console.warn(\n '[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: ' +\n (error instanceof Error ? error.message : String(error)),\n );\n })\n .finally(() => {\n // Proceed even on errors, degraded tracking is better than no app\n setCookiesReady(true);\n });\n }, [checkoutDomain, fetchTrackingValues, storefrontAccessToken]);\n\n return cookiesReady;\n}\n"],"mappings":";;;;;;;AAWA,IAAM,iBAAiB,OAAU,KAAK,MAAM;AAC5C,IAAM,kBAAkB;;;;;;;;;;;;;;;;;;;AAyCxB,SAAgB,kBAAkB,SAA6C;CAC7E,MAAM,EACJ,gBACA,SAAS,IACT,iBAAiB,IACjB,uBACA,qBACA,0BAA0B,UACxB,WAAW,EAAE;CAEjB,MAAM,mBAAmB,sBAAsB;EAC7C;EACA;EACA;EACD,CAAC;AAEF,EAAA,GAAA,MAAA,iBAAgB;AAGd,MAAI,2BAA2B,CAAC,iBAAkB;;;;;;;EAUlD,IAAI,gBAAgB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BAAA,6BAA6B;KAC7B,uBAAA,8BAA8B;IAChC,GACD,KAAA;GACL;EACD,MAAM,KAAK,UAAU,EACnB,OAGE,6FACH,CAAC;EACH,CACF;AAED,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,yCAAyC,SAAS,OAAO,GAAG,SAAS,aACtE;AAKH,OAAM,SAAS,MAAM;AAGrB,wBAAA,mBAAmB;;;;;;;AAcrB,SAAS,sBAAsB,EAC7B,gBACA,uBACA,sBAAsB,SACM;CAC5B,MAAM,CAAC,cAAc,oBAAA,GAAA,MAAA,UAA4B,CAAC,oBAAoB;CACtE,MAAM,4BAAA,GAAA,MAAA,QAAkC,MAAM;AAE9C,EAAA,GAAA,MAAA,iBAAgB;AACd,MAAI,CAAC,qBAAqB;AAExB,mBAAgB,KAAK;AACrB;;AAIF,MAAI,yBAAyB,QAAS;AACtC,2BAAyB,UAAU;AAGnC,iCAA+B,sBAAsB,CAClD,OAAO,UACN,iBAGI,+BACE,uBACA,eACD,GACD,QAAQ,OAAO,MAAM,CAC1B,CACA,OAAO,UAAU;AAChB,WAAQ,KACN,gFACG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC1D;IACD,CACD,cAAc;AAEb,mBAAgB,KAAK;IACrB;IACH;EAAC;EAAgB;EAAqB;EAAsB,CAAC;AAEhE,QAAO"}
1
+ {"version":3,"file":"useShopifyCookies.js","names":[],"sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect, useRef, useState} from 'react';\nimport {\n getTrackingValues,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from './tracking-utils.js';\n\n// Marks the same-origin consent request so the backend can identify\n// headless consent-management traffic. A custom header on the cross-origin\n// checkout retry would fail its CORS preflight, so it is never sent there.\n// NOTE: packages/hydrogen/src/constants.ts defines the same header name\n// (STOREFRONT_CONSENT_MANAGEMENT_HEADER) for the server-side proxy\n// forwarding; keep the two in sync.\nconst CONSENT_MANAGEMENT_MARKER_HEADER =\n 'Shopify-Storefront-Consent-Management';\n\ntype UseShopifyCookiesOptions = {\n storefrontAccessToken?: string;\n fetchTrackingValues?: boolean;\n /** @deprecated No longer used. The Customer Privacy API manages Shopify cookies. */\n hasUserConsent?: boolean;\n /** @deprecated No longer used. The Customer Privacy API manages cookie domains. */\n domain?: string;\n /** The checkout domain used if the same-origin consent request fails. */\n checkoutDomain?: string;\n /** @deprecated No longer used. The Customer Privacy API expires deprecated cookies. */\n ignoreDeprecatedCookies?: boolean;\n};\n\n/**\n * Optionally refreshes backend-managed cookies for standalone integrations.\n * The Customer Privacy API owns tracking values and legacy cookie expiration.\n *\n * If `fetchTrackingValues` is true, this sends a consent request through the\n * Storefront API proxy, retrying against `checkoutDomain` if provided. Hydrogen's\n * built-in analytics already delegates consent initialization to the Customer\n * Privacy API and does not use this hook.\n *\n * @returns `true` when the consent request has settled and cookies are ready.\n * @publicDocs\n */\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): boolean {\n const {\n checkoutDomain,\n storefrontAccessToken,\n fetchTrackingValues = false,\n } = options ?? {};\n const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);\n const hasFetchedTrackingValues = useRef(false);\n\n useEffect(() => {\n if (!fetchTrackingValues) {\n // Backend did the work, or proxy is disabled.\n setCookiesReady(true);\n return;\n }\n\n // React runs effects twice in dev mode, avoid double fetching\n if (hasFetchedTrackingValues.current) return;\n hasFetchedTrackingValues.current = true;\n\n const fetchConsentValues = async () => {\n try {\n return await fetchTrackingValuesFromBrowser(storefrontAccessToken);\n } catch (sameOriginError) {\n if (!checkoutDomain) throw sameOriginError;\n // Retry with checkout domain if the same-origin proxy failed.\n return fetchTrackingValuesFromBrowser(\n storefrontAccessToken,\n checkoutDomain,\n );\n }\n };\n\n fetchConsentValues()\n .catch((error) => {\n console.warn(\n '[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: ' +\n (error instanceof Error ? error.message : String(error)),\n );\n })\n .finally(() => {\n // Proceed even on errors, degraded tracking is better than no app\n setCookiesReady(true);\n });\n }, [checkoutDomain, fetchTrackingValues, storefrontAccessToken]);\n\n return cookiesReady;\n}\n\nasync function fetchTrackingValuesFromBrowser(\n storefrontAccessToken?: string,\n storefrontApiDomain = '',\n): Promise<void> {\n // Forward the current CTA tokens or legacy cookies to preserve the session.\n // CTA suppresses token generation while its async consent is loading.\n const {uniqueToken, visitToken} = getTrackingValues();\n\n const response = await fetch(\n // TODO: update this endpoint when it becomes stable\n `${storefrontApiDomain.replace(/\\/+$/, '')}/api/unstable/graphql.json`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(storefrontAccessToken && {\n 'X-Shopify-Storefront-Access-Token': storefrontAccessToken,\n }),\n // The marker header goes on the same-origin request only, where the\n // Hydrogen server proxy can act on it.\n ...(storefrontApiDomain\n ? undefined\n : {[CONSENT_MANAGEMENT_MARKER_HEADER]: '1'}),\n ...(visitToken || uniqueToken\n ? {\n [SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,\n [SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken,\n }\n : undefined),\n },\n body: JSON.stringify({\n query:\n // The empty `visitorConsent` refreshes cookies without changing\n // the stored consent.\n 'query ensureCookies { consentManagement { cookies(visitorConsent:{}) { trackingConsentCookie cookieDomain shopifyUnique shopifyVisit } } }',\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch consent from browser: ${response.status} ${response.statusText}`,\n );\n }\n}\n"],"mappings":";;;;AAaA,IAAM,mCACJ;;;;;;;;;;;;;AA2BF,SAAgB,kBAAkB,SAA6C;CAC7E,MAAM,EACJ,gBACA,uBACA,sBAAsB,UACpB,WAAW,EAAE;CACjB,MAAM,CAAC,cAAc,oBAAA,GAAA,MAAA,UAA4B,CAAC,oBAAoB;CACtE,MAAM,4BAAA,GAAA,MAAA,QAAkC,MAAM;AAE9C,EAAA,GAAA,MAAA,iBAAgB;AACd,MAAI,CAAC,qBAAqB;AAExB,mBAAgB,KAAK;AACrB;;AAIF,MAAI,yBAAyB,QAAS;AACtC,2BAAyB,UAAU;EAEnC,MAAM,qBAAqB,YAAY;AACrC,OAAI;AACF,WAAO,MAAM,+BAA+B,sBAAsB;YAC3D,iBAAiB;AACxB,QAAI,CAAC,eAAgB,OAAM;AAE3B,WAAO,+BACL,uBACA,eACD;;;AAIL,sBAAoB,CACjB,OAAO,UAAU;AAChB,WAAQ,KACN,gFACG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC1D;IACD,CACD,cAAc;AAEb,mBAAgB,KAAK;IACrB;IACH;EAAC;EAAgB;EAAqB;EAAsB,CAAC;AAEhE,QAAO;;AAGT,eAAe,+BACb,uBACA,sBAAsB,IACP;CAGf,MAAM,EAAC,aAAa,eAAc,uBAAA,mBAAmB;CAErD,MAAM,WAAW,MAAM,MAErB,GAAG,oBAAoB,QAAQ,QAAQ,GAAG,CAAC,6BAC3C;EACE,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,GAAI,yBAAyB,EAC3B,qCAAqC,uBACtC;GAGD,GAAI,sBACA,KAAA,IACA,GAAE,mCAAmC,KAAI;GAC7C,GAAI,cAAc,cACd;KACG,uBAAA,6BAA6B;KAC7B,uBAAA,8BAA8B;IAChC,GACD,KAAA;GACL;EACD,MAAM,KAAK,UAAU,EACnB,OAGE,8IACH,CAAC;EACH,CACF;AAED,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,yCAAyC,SAAS,OAAO,GAAG,SAAS,aACtE"}
@@ -1,84 +1,49 @@
1
- import { SHOPIFY_S, SHOPIFY_Y } from "./cart-constants.mjs";
2
1
  import { SHOPIFY_UNIQUE_TOKEN_HEADER, SHOPIFY_VISIT_TOKEN_HEADER, getTrackingValues } from "./tracking-utils.mjs";
3
- import { buildUUID } from "./cookies-utils.mjs";
4
2
  import { useEffect, useRef, useState } from "react";
5
- import { stringify } from "worktop/cookie";
6
3
  //#region src/useShopifyCookies.tsx
7
- var longTermLength = 3600 * 24 * 360 * 1;
8
- var shortTermLength = 1800;
4
+ var CONSENT_MANAGEMENT_MARKER_HEADER = "Shopify-Storefront-Consent-Management";
9
5
  /**
10
- * Sets the `shopify_y` and `shopify_s` cookies in the browser based on user consent
11
- * for backward compatibility support.
6
+ * Optionally refreshes backend-managed cookies for standalone integrations.
7
+ * The Customer Privacy API owns tracking values and legacy cookie expiration.
12
8
  *
13
- * If `fetchTrackingValues` is true, it makes a request to Storefront API
14
- * to fetch or refresh Shopiy analytics and marketing cookies and tracking values.
15
- * Generally speaking, this should only be needed if you're not using Hydrogen's
16
- * built-in analytics components and hooks that already handle this automatically.
17
- * For example, set it to `true` if you are using `hydrogen-react` only with
18
- * a different framework and still need to make a same-domain request to
19
- * Storefront API to set cookies.
9
+ * If `fetchTrackingValues` is true, this sends a consent request through the
10
+ * Storefront API proxy, retrying against `checkoutDomain` if provided. Hydrogen's
11
+ * built-in analytics already delegates consent initialization to the Customer
12
+ * Privacy API and does not use this hook.
20
13
  *
21
- * If `ignoreDeprecatedCookies` is true, it skips setting the deprecated cookies entirely.
22
- * Useful when you only want to use the newer tracking values and not rely on the deprecated ones.
23
- *
24
- * @returns `true` when cookies are set and ready.
14
+ * @returns `true` when the consent request has settled and cookies are ready.
25
15
  * @publicDocs
26
16
  */
27
17
  function useShopifyCookies(options) {
28
- const { hasUserConsent, domain = "", checkoutDomain = "", storefrontAccessToken, fetchTrackingValues, ignoreDeprecatedCookies = false } = options || {};
29
- const coreCookiesReady = useCoreShopifyCookies({
30
- storefrontAccessToken,
31
- fetchTrackingValues,
32
- checkoutDomain
33
- });
18
+ const { checkoutDomain, storefrontAccessToken, fetchTrackingValues = false } = options ?? {};
19
+ const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);
20
+ const hasFetchedTrackingValues = useRef(false);
34
21
  useEffect(() => {
35
- if (ignoreDeprecatedCookies || !coreCookiesReady) return;
36
- /**
37
- * Setting cookie with domain
38
- *
39
- * If no domain is provided, the cookie will be set for the current host.
40
- * For Shopify, we need to ensure this domain is set with a leading dot.
41
- */
42
- let currentDomain = domain || window.location.host;
43
- if (checkoutDomain) {
44
- const checkoutDomainParts = checkoutDomain.split(".").reverse();
45
- const currentDomainParts = currentDomain.split(".").reverse();
46
- const sameDomainParts = [];
47
- checkoutDomainParts.forEach((part, index) => {
48
- if (part === currentDomainParts[index]) sameDomainParts.push(part);
49
- });
50
- currentDomain = sameDomainParts.reverse().join(".");
51
- }
52
- if (/^localhost/.test(currentDomain)) currentDomain = "";
53
- const domainWithLeadingDot = currentDomain ? /^\./.test(currentDomain) ? currentDomain : `.${currentDomain}` : "";
54
- /**
55
- * Set user and session cookies and refresh the expiry time
56
- */
57
- if (hasUserConsent) {
58
- const trackingValues = getTrackingValues();
59
- if ((trackingValues.uniqueToken || trackingValues.visitToken || "").startsWith("00000000-")) return;
60
- setCookie(SHOPIFY_Y, trackingValues.uniqueToken || buildUUID(), longTermLength, domainWithLeadingDot);
61
- setCookie(SHOPIFY_S, trackingValues.visitToken || buildUUID(), shortTermLength, domainWithLeadingDot);
62
- } else {
63
- setCookie(SHOPIFY_Y, "", 0, domainWithLeadingDot);
64
- setCookie(SHOPIFY_S, "", 0, domainWithLeadingDot);
22
+ if (!fetchTrackingValues) {
23
+ setCookiesReady(true);
24
+ return;
65
25
  }
26
+ if (hasFetchedTrackingValues.current) return;
27
+ hasFetchedTrackingValues.current = true;
28
+ const fetchConsentValues = async () => {
29
+ try {
30
+ return await fetchTrackingValuesFromBrowser(storefrontAccessToken);
31
+ } catch (sameOriginError) {
32
+ if (!checkoutDomain) throw sameOriginError;
33
+ return fetchTrackingValuesFromBrowser(storefrontAccessToken, checkoutDomain);
34
+ }
35
+ };
36
+ fetchConsentValues().catch((error) => {
37
+ console.warn("[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: " + (error instanceof Error ? error.message : String(error)));
38
+ }).finally(() => {
39
+ setCookiesReady(true);
40
+ });
66
41
  }, [
67
- coreCookiesReady,
68
- hasUserConsent,
69
- domain,
70
42
  checkoutDomain,
71
- ignoreDeprecatedCookies
43
+ fetchTrackingValues,
44
+ storefrontAccessToken
72
45
  ]);
73
- return coreCookiesReady;
74
- }
75
- function setCookie(name, value, maxage, domain) {
76
- document.cookie = stringify(name, value, {
77
- maxage,
78
- domain,
79
- samesite: "Lax",
80
- path: "/"
81
- });
46
+ return cookiesReady;
82
47
  }
83
48
  async function fetchTrackingValuesFromBrowser(storefrontAccessToken, storefrontApiDomain = "") {
84
49
  const { uniqueToken, visitToken } = getTrackingValues();
@@ -87,43 +52,15 @@ async function fetchTrackingValuesFromBrowser(storefrontAccessToken, storefrontA
87
52
  headers: {
88
53
  "Content-Type": "application/json",
89
54
  ...storefrontAccessToken && { "X-Shopify-Storefront-Access-Token": storefrontAccessToken },
55
+ ...storefrontApiDomain ? void 0 : { [CONSENT_MANAGEMENT_MARKER_HEADER]: "1" },
90
56
  ...visitToken || uniqueToken ? {
91
57
  [SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,
92
58
  [SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken
93
59
  } : void 0
94
60
  },
95
- body: JSON.stringify({ query: "query ensureCookies { consentManagement { cookies(visitorConsent:{}) { cookieDomain } } }" })
61
+ body: JSON.stringify({ query: "query ensureCookies { consentManagement { cookies(visitorConsent:{}) { trackingConsentCookie cookieDomain shopifyUnique shopifyVisit } } }" })
96
62
  });
97
63
  if (!response.ok) throw new Error(`Failed to fetch consent from browser: ${response.status} ${response.statusText}`);
98
- await response.json();
99
- getTrackingValues();
100
- }
101
- /**
102
- * Gets http-only cookies from Storefront API via same-origin fetch request.
103
- * Falls back to checkout domain if provided to at least obtain the tracking
104
- * values via server-timing headers.
105
- */
106
- function useCoreShopifyCookies({ checkoutDomain, storefrontAccessToken, fetchTrackingValues = false }) {
107
- const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);
108
- const hasFetchedTrackingValues = useRef(false);
109
- useEffect(() => {
110
- if (!fetchTrackingValues) {
111
- setCookiesReady(true);
112
- return;
113
- }
114
- if (hasFetchedTrackingValues.current) return;
115
- hasFetchedTrackingValues.current = true;
116
- fetchTrackingValuesFromBrowser(storefrontAccessToken).catch((error) => checkoutDomain ? fetchTrackingValuesFromBrowser(storefrontAccessToken, checkoutDomain) : Promise.reject(error)).catch((error) => {
117
- console.warn("[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: " + (error instanceof Error ? error.message : String(error)));
118
- }).finally(() => {
119
- setCookiesReady(true);
120
- });
121
- }, [
122
- checkoutDomain,
123
- fetchTrackingValues,
124
- storefrontAccessToken
125
- ]);
126
- return cookiesReady;
127
64
  }
128
65
  //#endregion
129
66
  export { useShopifyCookies };
@@ -1 +1 @@
1
- {"version":3,"file":"useShopifyCookies.mjs","names":[],"sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect, useRef, useState} from 'react';\n// @ts-ignore - worktop/cookie types not properly exported\nimport {stringify} from 'worktop/cookie';\nimport {SHOPIFY_Y, SHOPIFY_S} from './cart-constants.js';\nimport {buildUUID} from './cookies-utils.js';\nimport {\n getTrackingValues,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from './tracking-utils.js';\n\nconst longTermLength = 60 * 60 * 24 * 360 * 1; // ~1 year expiry\nconst shortTermLength = 60 * 30; // 30 mins\n\ntype UseShopifyCookiesOptions = CoreShopifyCookiesOptions & {\n /**\n * If set to `false`, Shopify cookies will be removed.\n * If set to `true`, Shopify unique user token cookie will have cookie expiry of 1 year.\n * Defaults to false.\n **/\n hasUserConsent?: boolean;\n /**\n * The domain scope of the cookie. Defaults to empty string.\n **/\n domain?: string;\n /**\n * The checkout domain of the shop. Defaults to empty string. If set, the cookie domain will check if it can be set with the checkout domain.\n */\n checkoutDomain?: string;\n /**\n * If set to `true`, it skips modifying the deprecated shopify_y and shopify_s cookies.\n */\n ignoreDeprecatedCookies?: boolean;\n};\n\n/**\n * Sets the `shopify_y` and `shopify_s` cookies in the browser based on user consent\n * for backward compatibility support.\n *\n * If `fetchTrackingValues` is true, it makes a request to Storefront API\n * to fetch or refresh Shopiy analytics and marketing cookies and tracking values.\n * Generally speaking, this should only be needed if you're not using Hydrogen's\n * built-in analytics components and hooks that already handle this automatically.\n * For example, set it to `true` if you are using `hydrogen-react` only with\n * a different framework and still need to make a same-domain request to\n * Storefront API to set cookies.\n *\n * If `ignoreDeprecatedCookies` is true, it skips setting the deprecated cookies entirely.\n * Useful when you only want to use the newer tracking values and not rely on the deprecated ones.\n *\n * @returns `true` when cookies are set and ready.\n * @publicDocs\n */\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): boolean {\n const {\n hasUserConsent,\n domain = '',\n checkoutDomain = '',\n storefrontAccessToken,\n fetchTrackingValues,\n ignoreDeprecatedCookies = false,\n } = options || {};\n\n const coreCookiesReady = useCoreShopifyCookies({\n storefrontAccessToken,\n fetchTrackingValues,\n checkoutDomain,\n });\n\n useEffect(() => {\n // Skip setting JS cookies until http-only cookies and server-timing\n // are ready so that we have values synced in JS and http-only cookies.\n if (ignoreDeprecatedCookies || !coreCookiesReady) return;\n\n /**\n * Setting cookie with domain\n *\n * If no domain is provided, the cookie will be set for the current host.\n * For Shopify, we need to ensure this domain is set with a leading dot.\n */\n\n // Use override domain or current host\n let currentDomain = domain || window.location.host;\n\n if (checkoutDomain) {\n const checkoutDomainParts = checkoutDomain.split('.').reverse();\n const currentDomainParts = currentDomain.split('.').reverse();\n const sameDomainParts: Array<string> = [];\n checkoutDomainParts.forEach((part, index) => {\n if (part === currentDomainParts[index]) {\n sameDomainParts.push(part);\n }\n });\n\n currentDomain = sameDomainParts.reverse().join('.');\n }\n\n // Reset domain if localhost\n if (/^localhost/.test(currentDomain)) currentDomain = '';\n\n // Shopify checkout only consumes cookies set with leading dot domain\n const domainWithLeadingDot = currentDomain\n ? /^\\./.test(currentDomain)\n ? currentDomain\n : `.${currentDomain}`\n : '';\n\n /**\n * Set user and session cookies and refresh the expiry time\n */\n if (hasUserConsent) {\n const trackingValues = getTrackingValues();\n if (\n (\n trackingValues.uniqueToken ||\n trackingValues.visitToken ||\n ''\n ).startsWith('00000000-')\n ) {\n // Skip writing cookies when tracking values signal we don't have consent yet\n return;\n }\n\n setCookie(\n SHOPIFY_Y,\n trackingValues.uniqueToken || buildUUID(),\n longTermLength,\n domainWithLeadingDot,\n );\n setCookie(\n SHOPIFY_S,\n trackingValues.visitToken || buildUUID(),\n shortTermLength,\n domainWithLeadingDot,\n );\n } else {\n setCookie(SHOPIFY_Y, '', 0, domainWithLeadingDot);\n setCookie(SHOPIFY_S, '', 0, domainWithLeadingDot);\n }\n }, [\n coreCookiesReady,\n hasUserConsent,\n domain,\n checkoutDomain,\n ignoreDeprecatedCookies,\n ]);\n\n return coreCookiesReady;\n}\n\nfunction setCookie(\n name: string,\n value: string,\n maxage: number,\n domain: string,\n): void {\n document.cookie = stringify(name, value, {\n maxage,\n domain,\n samesite: 'Lax',\n path: '/',\n });\n}\n\nasync function fetchTrackingValuesFromBrowser(\n storefrontAccessToken?: string,\n storefrontApiDomain = '',\n): Promise<void> {\n // These values might come from server-timing or old cookies.\n // If consent cannot be initially assumed, these tokens\n // will be dropped in SFAPI and it will return a mock token\n // starting with '00000000-'.\n // However, if consent can be assumed initially, these tokens\n // will be used to create proper cookies and continue our flow.\n const {uniqueToken, visitToken} = getTrackingValues();\n\n const response = await fetch(\n // TODO: update this endpoint when it becomes stable\n `${storefrontApiDomain.replace(/\\/+$/, '')}/api/unstable/graphql.json`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(storefrontAccessToken && {\n 'X-Shopify-Storefront-Access-Token': storefrontAccessToken,\n }),\n ...(visitToken || uniqueToken\n ? {\n [SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,\n [SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken,\n }\n : undefined),\n },\n body: JSON.stringify({\n query:\n // This query ensures we get _cmp (consent) server-timing header, which is not available in other queries.\n // This value can be passed later to consent-tracking-api and privacy-banner scripts to avoid extra requests.\n 'query ensureCookies { consentManagement { cookies(visitorConsent:{}) { cookieDomain } } }',\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch consent from browser: ${response.status} ${response.statusText}`,\n );\n }\n\n // Consume the body to complete the request and\n // ensure server-timing is available in performance API\n await response.json();\n\n // Ensure we cache the latest tracking values from resources timing\n getTrackingValues();\n}\n\ntype CoreShopifyCookiesOptions = {\n storefrontAccessToken?: string;\n fetchTrackingValues?: boolean;\n checkoutDomain?: string;\n};\n\n/**\n * Gets http-only cookies from Storefront API via same-origin fetch request.\n * Falls back to checkout domain if provided to at least obtain the tracking\n * values via server-timing headers.\n */\nfunction useCoreShopifyCookies({\n checkoutDomain,\n storefrontAccessToken,\n fetchTrackingValues = false,\n}: CoreShopifyCookiesOptions) {\n const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);\n const hasFetchedTrackingValues = useRef(false);\n\n useEffect(() => {\n if (!fetchTrackingValues) {\n // Backend did the work, or proxy is disabled.\n setCookiesReady(true);\n return;\n }\n\n // React runs effects twice in dev mode, avoid double fetching\n if (hasFetchedTrackingValues.current) return;\n hasFetchedTrackingValues.current = true;\n\n // Fetch consent from browser via proxy\n fetchTrackingValuesFromBrowser(storefrontAccessToken)\n .catch((error) =>\n checkoutDomain\n ? // Retry with checkout domain if available to at least\n // get the server-timing values for tracking.\n fetchTrackingValuesFromBrowser(\n storefrontAccessToken,\n checkoutDomain,\n )\n : Promise.reject(error),\n )\n .catch((error) => {\n console.warn(\n '[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: ' +\n (error instanceof Error ? error.message : String(error)),\n );\n })\n .finally(() => {\n // Proceed even on errors, degraded tracking is better than no app\n setCookiesReady(true);\n });\n }, [checkoutDomain, fetchTrackingValues, storefrontAccessToken]);\n\n return cookiesReady;\n}\n"],"mappings":";;;;;;AAWA,IAAM,iBAAiB,OAAU,KAAK,MAAM;AAC5C,IA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AAM,EAAC,aAAa,eAAc,mBAAmB;CAErD,MAAM,WAAW,MAAM,MAErB,GAAG,oBAAoB,QAAQ,QAAQ,GAAG,CAAC,6BAC3C;EACE,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,GAAI,yBAAyB,EAC3B,qCAAqC,uBACtC;GACD,GAAI,cAAc,cACd;KACG,6BAA6B;KAC7B,8BAA8B;IAChC,GACD,KAAA;GACL;EACD,MAAM,KAAK,UAAU,EACnB,OAGE,6FACH,CAAC;EACH,CACF;AAED,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,yCAAyC,SAAS,OAAO,GAAG,SAAS,aACtE;AAKH,OAAM,SAAS,MAAM;AAGrB,oBAAmB;;;;;;;AAcrB,SAAS,sBAAsB,EAC7B,gBACA,uBACA,sBAAsB,SACM;CAC5B,MAAM,CAAC,cAAc,mBAAmB,SAAS,CAAC,oBAAoB;CACtE,MAAM,2BAA2B,OAAO,MAAM;AAE9C,iBAAgB;AACd,MAAI,CAAC,qBAAqB;AAExB,mBAAgB,KAAK;AACrB;;AAIF,MAAI,yBAAyB,QAAS;AACtC,2BAAyB,UAAU;AAGnC,iCAA+B,sBAAsB,CAClD,OAAO,UACN,iBAGI,+BACE,uBACA,eACD,GACD,QAAQ,OAAO,MAAM,CAC1B,CACA,OAAO,UAAU;AAChB,WAAQ,KACN,gFACG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC1D;IACD,CACD,cAAc;AAEb,mBAAgB,KAAK;IACrB;IACH;EAAC;EAAgB;EAAqB;EAAsB,CAAC;AAEhE,QAAO"}
1
+ {"version":3,"file":"useShopifyCookies.mjs","names":[],"sources":["../../src/useShopifyCookies.tsx"],"sourcesContent":["import {useEffect, useRef, useState} from 'react';\nimport {\n getTrackingValues,\n SHOPIFY_UNIQUE_TOKEN_HEADER,\n SHOPIFY_VISIT_TOKEN_HEADER,\n} from './tracking-utils.js';\n\n// Marks the same-origin consent request so the backend can identify\n// headless consent-management traffic. A custom header on the cross-origin\n// checkout retry would fail its CORS preflight, so it is never sent there.\n// NOTE: packages/hydrogen/src/constants.ts defines the same header name\n// (STOREFRONT_CONSENT_MANAGEMENT_HEADER) for the server-side proxy\n// forwarding; keep the two in sync.\nconst CONSENT_MANAGEMENT_MARKER_HEADER =\n 'Shopify-Storefront-Consent-Management';\n\ntype UseShopifyCookiesOptions = {\n storefrontAccessToken?: string;\n fetchTrackingValues?: boolean;\n /** @deprecated No longer used. The Customer Privacy API manages Shopify cookies. */\n hasUserConsent?: boolean;\n /** @deprecated No longer used. The Customer Privacy API manages cookie domains. */\n domain?: string;\n /** The checkout domain used if the same-origin consent request fails. */\n checkoutDomain?: string;\n /** @deprecated No longer used. The Customer Privacy API expires deprecated cookies. */\n ignoreDeprecatedCookies?: boolean;\n};\n\n/**\n * Optionally refreshes backend-managed cookies for standalone integrations.\n * The Customer Privacy API owns tracking values and legacy cookie expiration.\n *\n * If `fetchTrackingValues` is true, this sends a consent request through the\n * Storefront API proxy, retrying against `checkoutDomain` if provided. Hydrogen's\n * built-in analytics already delegates consent initialization to the Customer\n * Privacy API and does not use this hook.\n *\n * @returns `true` when the consent request has settled and cookies are ready.\n * @publicDocs\n */\nexport function useShopifyCookies(options?: UseShopifyCookiesOptions): boolean {\n const {\n checkoutDomain,\n storefrontAccessToken,\n fetchTrackingValues = false,\n } = options ?? {};\n const [cookiesReady, setCookiesReady] = useState(!fetchTrackingValues);\n const hasFetchedTrackingValues = useRef(false);\n\n useEffect(() => {\n if (!fetchTrackingValues) {\n // Backend did the work, or proxy is disabled.\n setCookiesReady(true);\n return;\n }\n\n // React runs effects twice in dev mode, avoid double fetching\n if (hasFetchedTrackingValues.current) return;\n hasFetchedTrackingValues.current = true;\n\n const fetchConsentValues = async () => {\n try {\n return await fetchTrackingValuesFromBrowser(storefrontAccessToken);\n } catch (sameOriginError) {\n if (!checkoutDomain) throw sameOriginError;\n // Retry with checkout domain if the same-origin proxy failed.\n return fetchTrackingValuesFromBrowser(\n storefrontAccessToken,\n checkoutDomain,\n );\n }\n };\n\n fetchConsentValues()\n .catch((error) => {\n console.warn(\n '[h2:warn:useShopifyCookies] Failed to fetch tracking values from browser: ' +\n (error instanceof Error ? error.message : String(error)),\n );\n })\n .finally(() => {\n // Proceed even on errors, degraded tracking is better than no app\n setCookiesReady(true);\n });\n }, [checkoutDomain, fetchTrackingValues, storefrontAccessToken]);\n\n return cookiesReady;\n}\n\nasync function fetchTrackingValuesFromBrowser(\n storefrontAccessToken?: string,\n storefrontApiDomain = '',\n): Promise<void> {\n // Forward the current CTA tokens or legacy cookies to preserve the session.\n // CTA suppresses token generation while its async consent is loading.\n const {uniqueToken, visitToken} = getTrackingValues();\n\n const response = await fetch(\n // TODO: update this endpoint when it becomes stable\n `${storefrontApiDomain.replace(/\\/+$/, '')}/api/unstable/graphql.json`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(storefrontAccessToken && {\n 'X-Shopify-Storefront-Access-Token': storefrontAccessToken,\n }),\n // The marker header goes on the same-origin request only, where the\n // Hydrogen server proxy can act on it.\n ...(storefrontApiDomain\n ? undefined\n : {[CONSENT_MANAGEMENT_MARKER_HEADER]: '1'}),\n ...(visitToken || uniqueToken\n ? {\n [SHOPIFY_VISIT_TOKEN_HEADER]: visitToken,\n [SHOPIFY_UNIQUE_TOKEN_HEADER]: uniqueToken,\n }\n : undefined),\n },\n body: JSON.stringify({\n query:\n // The empty `visitorConsent` refreshes cookies without changing\n // the stored consent.\n 'query ensureCookies { consentManagement { cookies(visitorConsent:{}) { trackingConsentCookie cookieDomain shopifyUnique shopifyVisit } } }',\n }),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch consent from browser: ${response.status} ${response.statusText}`,\n );\n }\n}\n"],"mappings":";;;AAaA,IAAM,mCACJ;;;;;;;;;;;;;AA2BF,SAAgB,kBAAkB,SAA6C;CAC7E,MAAM,EACJ,gBACA,uBACA,sBAAsB,UACpB,WAAW,EAAE;CACjB,MAAM,CAAC,cAAc,mBAAmB,SAAS,CAAC,oBAAoB;CACtE,MAAM,2BAA2B,OAAO,MAAM;AAE9C,iBAAgB;AACd,MAAI,CAAC,qBAAqB;AAExB,mBAAgB,KAAK;AACrB;;AAIF,MAAI,yBAAyB,QAAS;AACtC,2BAAyB,UAAU;EAEnC,MAAM,qBAAqB,YAAY;AACrC,OAAI;AACF,WAAO,MAAM,+BAA+B,sBAAsB;YAC3D,iBAAiB;AACxB,QAAI,CAAC,eAAgB,OAAM;AAE3B,WAAO,+BACL,uBACA,eACD;;;AAIL,sBAAoB,CACjB,OAAO,UAAU;AAChB,WAAQ,KACN,gFACG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC1D;IACD,CACD,cAAc;AAEb,mBAAgB,KAAK;IACrB;IACH;EAAC;EAAgB;EAAqB;EAAsB,CAAC;AAEhE,QAAO;;AAGT,eAAe,+BACb,uBACA,sBAAsB,IACP;CAGf,MAAM,EAAC,aAAa,eAAc,mBAAmB;CAErD,MAAM,WAAW,MAAM,MAErB,GAAG,oBAAoB,QAAQ,QAAQ,GAAG,CAAC,6BAC3C;EACE,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,GAAI,yBAAyB,EAC3B,qCAAqC,uBACtC;GAGD,GAAI,sBACA,KAAA,IACA,GAAE,mCAAmC,KAAI;GAC7C,GAAI,cAAc,cACd;KACG,6BAA6B;KAC7B,8BAA8B;IAChC,GACD,KAAA;GACL;EACD,MAAM,KAAK,UAAU,EACnB,OAGE,8IACH,CAAC;EACH,CACF;AAED,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,yCAAyC,SAAS,OAAO,GAAG,SAAS,aACtE"}
@@ -139,7 +139,7 @@ var FixedWidthImage = react.forwardRef(({ aspectRatio, crop, decoding, height, i
139
139
  width: intWidth,
140
140
  aspectRatio: fixedAspectRatio,
141
141
  height: fixedHeight,
142
- srcSet: generateSrcSet(normalizedProps.src, sizesArray, loader),
142
+ srcSet: generateSrcSet(normalizedProps.src, sizesArray, loader, "density"),
143
143
  src: loader({
144
144
  src: normalizedProps.src,
145
145
  width: intWidth,
@@ -297,9 +297,10 @@ function isFixedWidth(width) {
297
297
  * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg
298
298
  * @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'\}]
299
299
  * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters
300
+ * @param descriptorType - Whether to use `w` (width) or `x` (density) descriptors in the srcset. Use `'density'` for fixed-width images and `'width'` (default) for fluid images.
300
301
  * @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'
301
302
  */
302
- function generateSrcSet(src, sizesArray, loader = shopifyLoader) {
303
+ function generateSrcSet(src, sizesArray, loader = shopifyLoader, descriptorType = "width") {
303
304
  if (!src) return "";
304
305
  if (sizesArray?.length === 0 || !sizesArray) return src;
305
306
  return sizesArray.map((size, i) => `${loader({
@@ -307,7 +308,7 @@ function generateSrcSet(src, sizesArray, loader = shopifyLoader) {
307
308
  width: size.width,
308
309
  height: size.height,
309
310
  crop: size.crop
310
- })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`).join(`, `);
311
+ })} ${descriptorType === "density" ? `${i + 1}x` : `${size.width ?? 0}w`}`).join(`, `);
311
312
  }
312
313
  /**
313
314
  * This function generates an array of sizes for Shopify images, for both fixed and responsive images.
@@ -1 +1 @@
1
- {"version":3,"file":"Image.js","names":[],"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\n/** @publicDocs */\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-04/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 * @publicDocs\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"],"mappings":";;;;;;;;AA6GA,IAAa,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4C9B,IAAa,QAAQ,MAAM,YAEvB,EACE,KACA,aACA,OAAO,UACP,MACA,WAAW,SACX,SAAS,QACT,SAAS,eACT,UAAU,QACV,OACA,KACA,gBAAgB;CACd,WAAW;CACX,eAAe;CACf,eAAe;CACf,kBAAkB;CACnB,EACD,QAAQ,QACR,GAAG,oBAEL,QACG;CAIH,MAAM,iBAAiB,MAAM,cAAc;EAEzC,MAAM,YACJ,MAAM,SAAS,MAAM,SAAS,MAAM,QAAQ,KAAA;EAE9C,MAAM,aACJ,MAAM,SAAS,MAAM,SAAS,MAAM,SAAS,KAAA;AAE/C,SAAO;GACL,OAAO;GACP,QAAQ;GACR,YAAY,QAAQ,WAAW,WAAW,WAAW,CAAC;GACvD;IACA,CAAC,KAAK,CAAC;CAMV,MAAM,kBAAkB,MAAM,cAAc;EAE1C,MAAM,aAAa,mB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,SAAS,iBAAiB,YAAY,IAAI,KAC1C,KAAA;GACJ;GACD;GACD,CACD,QAAQ,EAAC,OAAO,aAAY;AAC3B,MAAI,kBAAkB,SAAS,QAAQ,iBAAiB,MACtD,QAAO;AAGT,MACE,kBAAkB,UAClB,UACA,SAAS,iBAAiB,OAE1B,QAAO;AAGT,SAAO;GACP"}
1
+ {"version":3,"file":"Image.js","names":[],"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\n/** @publicDocs */\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-04/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 * @publicDocs\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(\n normalizedProps.src,\n sizesArray,\n loader,\n 'density',\n );\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 * @param descriptorType - Whether to use `w` (width) or `x` (density) descriptors in the srcset. Use `'density'` for fixed-width images and `'width'` (default) for fluid images.\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 descriptorType: 'width' | 'density' = 'width',\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 })} ${descriptorType === 'density' ? `${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"],"mappings":";;;;;;;;AA6GA,IAAa,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,QAAyB,QACzB,WACA,eACA,eACU;CACV,MAAM,aAAa,MAAM,KACvB,EAAC,QAAQ,WAAU,GAClB,GAAG,MAAM,IAAI,gBAAgB,cAC/B;CAED,MAAM,QAAQ,MAAM,KAClB,EAAC,QAAQ,GAAE,GACV,GAAG,OAAO,IAAI,MAAM,uBAAuB,MAAM,IAAI,GACvD;AAED,QAAO,aAAa,MAAM,GAAG,QAAQ;;;;;;;;;AAUvC,SAAgB,iBAAiB,aAA0C;AACzE,KAAI,CAAC,YAAa;CAClB,MAAM,CAAC,OAAO,UAAU,YAAY,MAAM,IAAI;AAC9C,QAAO,KAAK,OAAO,MAAM,GAAG,OAAO,OAAO;;AAI5C,SAAgB,cACd,aACA,aACA,OAAa,UACb,kBAOY;AACZ,KAAI,CAAC,YAAa;AAClB,QAAO,YACJ,KAAK,UAAkB;AACtB,SAAO;GACL;GACA,QAAQ,cACJ,SAAS,iBAAiB,YAAY,IAAI,KAC1C,KAAA;GACJ;GACD;GACD,CACD,QAAQ,EAAC,OAAO,aAAY;AAC3B,MAAI,kBAAkB,SAAS,QAAQ,iBAAiB,MACtD,QAAO;AAGT,MACE,kBAAkB,UAClB,UACA,SAAS,iBAAiB,OAE1B,QAAO;AAGT,SAAO;GACP"}
@@ -137,7 +137,7 @@ var FixedWidthImage = React.forwardRef(({ aspectRatio, crop, decoding, height, i
137
137
  width: intWidth,
138
138
  aspectRatio: fixedAspectRatio,
139
139
  height: fixedHeight,
140
- srcSet: generateSrcSet(normalizedProps.src, sizesArray, loader),
140
+ srcSet: generateSrcSet(normalizedProps.src, sizesArray, loader, "density"),
141
141
  src: loader({
142
142
  src: normalizedProps.src,
143
143
  width: intWidth,
@@ -295,9 +295,10 @@ function isFixedWidth(width) {
295
295
  * @param src - The source URL of the image, e.g. https://cdn.shopify.com/static/sample-images/garnished.jpeg
296
296
  * @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'\}]
297
297
  * @param loader - A function that takes a Shopify image URL and returns a Shopify image URL with the correct query parameters
298
+ * @param descriptorType - Whether to use `w` (width) or `x` (density) descriptors in the srcset. Use `'density'` for fixed-width images and `'width'` (default) for fluid images.
298
299
  * @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'
299
300
  */
300
- function generateSrcSet(src, sizesArray, loader = shopifyLoader) {
301
+ function generateSrcSet(src, sizesArray, loader = shopifyLoader, descriptorType = "width") {
301
302
  if (!src) return "";
302
303
  if (sizesArray?.length === 0 || !sizesArray) return src;
303
304
  return sizesArray.map((size, i) => `${loader({
@@ -305,7 +306,7 @@ function generateSrcSet(src, sizesArray, loader = shopifyLoader) {
305
306
  width: size.width,
306
307
  height: size.height,
307
308
  crop: size.crop
308
- })} ${sizesArray.length === 3 ? `${i + 1}x` : `${size.width ?? 0}w`}`).join(`, `);
309
+ })} ${descriptorType === "density" ? `${i + 1}x` : `${size.width ?? 0}w`}`).join(`, `);
309
310
  }
310
311
  /**
311
312
  * This function generates an array of sizes for Shopify images, for both fixed and responsive images.