@shopify/hydrogen 2026.10.1 → 2026.10.3

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 (265) hide show
  1. package/README.md +3 -5
  2. package/dist/cli/index.mjs +8 -5
  3. package/dist/client/client.mjs +45 -12
  4. package/dist/client/client.mjs.map +1 -1
  5. package/dist/client/i18n-variables.d.mts +13 -0
  6. package/dist/client/i18n-variables.mjs +92 -0
  7. package/dist/client/i18n-variables.mjs.map +1 -0
  8. package/dist/client/types.d.mts +21 -8
  9. package/dist/core/cache/fetch-with-cache.mjs +8 -1
  10. package/dist/core/cache/fetch-with-cache.mjs.map +1 -1
  11. package/dist/core/cart/cart.mjs +111 -24
  12. package/dist/core/cart/cart.mjs.map +1 -1
  13. package/dist/core/cart/cookie.mjs +6 -1
  14. package/dist/core/cart/cookie.mjs.map +1 -1
  15. package/dist/core/cart/form.d.mts +17 -5
  16. package/dist/core/cart/form.mjs +5 -0
  17. package/dist/core/cart/form.mjs.map +1 -1
  18. package/dist/core/cart/index.d.mts +1 -1
  19. package/dist/core/cart/queries.d.mts +57 -57
  20. package/dist/core/collection/url.mjs +8 -1
  21. package/dist/core/collection/url.mjs.map +1 -1
  22. package/dist/core/constants.mjs +2 -1
  23. package/dist/core/constants.mjs.map +1 -1
  24. package/dist/core/csp/index.d.mts +56 -0
  25. package/dist/core/csp/index.mjs +117 -0
  26. package/dist/core/csp/index.mjs.map +1 -0
  27. package/dist/core/csp/types.d.mts +52 -0
  28. package/dist/core/headers.mjs +2 -2
  29. package/dist/core/headers.mjs.map +1 -1
  30. package/dist/core/i18n/define.d.mts +54 -0
  31. package/dist/core/i18n/define.mjs +135 -0
  32. package/dist/core/i18n/define.mjs.map +1 -0
  33. package/dist/core/i18n/errors.d.mts +18 -0
  34. package/dist/core/i18n/errors.mjs +24 -0
  35. package/dist/core/i18n/errors.mjs.map +1 -0
  36. package/dist/core/i18n/href.d.mts +28 -0
  37. package/dist/core/i18n/href.mjs +45 -0
  38. package/dist/core/i18n/href.mjs.map +1 -0
  39. package/dist/core/i18n/locale.d.mts +21 -0
  40. package/dist/core/i18n/locale.mjs +36 -0
  41. package/dist/core/i18n/locale.mjs.map +1 -0
  42. package/dist/core/i18n/match.d.mts +37 -0
  43. package/dist/core/i18n/match.mjs +82 -0
  44. package/dist/core/i18n/match.mjs.map +1 -0
  45. package/dist/core/i18n/types.d.mts +80 -0
  46. package/dist/core/index.d.mts +14 -5
  47. package/dist/core/index.mjs +9 -2
  48. package/dist/core/predictive-search/index.d.mts +2 -2
  49. package/dist/core/predictive-search/queries.d.mts +2 -2
  50. package/dist/core/predictive-search/server-handlers.d.mts +27 -6
  51. package/dist/core/predictive-search/server-handlers.mjs +1 -4
  52. package/dist/core/predictive-search/server-handlers.mjs.map +1 -1
  53. package/dist/core/predictive-search/url.d.mts +2 -2
  54. package/dist/core/predictive-search/url.mjs.map +1 -1
  55. package/dist/core/product/accept-variant-id.mjs +1 -1
  56. package/dist/core/product/accept-variant-id.mjs.map +1 -1
  57. package/dist/core/request-context.d.mts +61 -35
  58. package/dist/core/request-context.mjs +11 -7
  59. package/dist/core/request-context.mjs.map +1 -1
  60. package/dist/core/request-routing/handle-shopify-routes.mjs.map +1 -1
  61. package/dist/core/request-routing/interceptors/api-proxy.mjs +9 -1
  62. package/dist/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
  63. package/dist/core/request-routing/interceptors/checkout.mjs +11 -5
  64. package/dist/core/request-routing/interceptors/checkout.mjs.map +1 -1
  65. package/dist/core/request-routing/interceptors/proxy.mjs.map +1 -1
  66. package/dist/core/request-routing/interceptors/standard-routes.mjs +1 -1
  67. package/dist/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
  68. package/dist/core/request-routing/interceptors/url-redirects.mjs +2 -1
  69. package/dist/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
  70. package/dist/core/request-routing/registered-routes.d.mts +13 -2
  71. package/dist/core/request-routing/registered-routes.mjs +33 -9
  72. package/dist/core/request-routing/registered-routes.mjs.map +1 -1
  73. package/dist/core/request-routing/route-types.d.mts +18 -8
  74. package/dist/core/shop-pay/shop-pay.mjs +5 -4
  75. package/dist/core/shop-pay/shop-pay.mjs.map +1 -1
  76. package/dist/core/shopify-scripts/analytics.mjs +3 -5
  77. package/dist/core/shopify-scripts/analytics.mjs.map +1 -1
  78. package/dist/core/shopify-scripts/constants.mjs +3 -1
  79. package/dist/core/shopify-scripts/constants.mjs.map +1 -1
  80. package/dist/core/shopify-scripts/global.mjs +13 -11
  81. package/dist/core/shopify-scripts/global.mjs.map +1 -1
  82. package/dist/core/shopify-scripts/hashes.d.mts +17 -0
  83. package/dist/core/shopify-scripts/hashes.mjs +12 -0
  84. package/dist/core/shopify-scripts/hashes.mjs.map +1 -0
  85. package/dist/core/shopify-scripts/index.d.mts +1 -0
  86. package/dist/core/shopify-scripts/index.mjs +12 -9
  87. package/dist/core/shopify-scripts/index.mjs.map +1 -1
  88. package/dist/core/shopify-scripts/page-view.mjs +4 -1
  89. package/dist/core/shopify-scripts/page-view.mjs.map +1 -1
  90. package/dist/core/shopify-scripts/perfkit.mjs +8 -2
  91. package/dist/core/shopify-scripts/perfkit.mjs.map +1 -1
  92. package/dist/core/shopify-scripts/types.d.mts +4 -2
  93. package/dist/core/shopify-scripts/utils/inline-script.mjs +4 -1
  94. package/dist/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
  95. package/dist/core/standard-routes/build.d.mts +7 -2
  96. package/dist/core/standard-routes/build.mjs +10 -3
  97. package/dist/core/standard-routes/build.mjs.map +1 -1
  98. package/dist/core/standard-routes/match.mjs +11 -1
  99. package/dist/core/standard-routes/match.mjs.map +1 -1
  100. package/dist/core/standard-routes/path.mjs +14 -3
  101. package/dist/core/standard-routes/path.mjs.map +1 -1
  102. package/dist/core/standard-routes/types.d.mts +6 -1
  103. package/dist/core/url.mjs +5 -3
  104. package/dist/core/url.mjs.map +1 -1
  105. package/dist/core/utils/load-script.mjs +6 -6
  106. package/dist/core/utils/load-script.mjs.map +1 -1
  107. package/dist/customer-account/client.d.mts +14 -10
  108. package/dist/customer-account/client.mjs +4 -5
  109. package/dist/customer-account/client.mjs.map +1 -1
  110. package/dist/customer-account/graphql.d.mts +7 -1
  111. package/dist/customer-account/graphql.mjs +6 -7
  112. package/dist/customer-account/graphql.mjs.map +1 -1
  113. package/dist/customer-account/session.mjs +3 -4
  114. package/dist/customer-account/session.mjs.map +1 -1
  115. package/dist/development/client/client.mjs +45 -12
  116. package/dist/development/client/client.mjs.map +1 -1
  117. package/dist/development/client/i18n-variables.d.mts +13 -0
  118. package/dist/development/client/i18n-variables.mjs +92 -0
  119. package/dist/development/client/i18n-variables.mjs.map +1 -0
  120. package/dist/development/client/types.d.mts +21 -8
  121. package/dist/development/core/cache/fetch-with-cache.mjs +8 -1
  122. package/dist/development/core/cache/fetch-with-cache.mjs.map +1 -1
  123. package/dist/development/core/cart/cart.mjs +111 -24
  124. package/dist/development/core/cart/cart.mjs.map +1 -1
  125. package/dist/development/core/cart/cookie.mjs +6 -1
  126. package/dist/development/core/cart/cookie.mjs.map +1 -1
  127. package/dist/development/core/cart/form.d.mts +17 -5
  128. package/dist/development/core/cart/form.mjs +5 -0
  129. package/dist/development/core/cart/form.mjs.map +1 -1
  130. package/dist/development/core/cart/index.d.mts +1 -1
  131. package/dist/development/core/cart/queries.d.mts +57 -57
  132. package/dist/development/core/collection/url.mjs +8 -1
  133. package/dist/development/core/collection/url.mjs.map +1 -1
  134. package/dist/development/core/constants.mjs +2 -1
  135. package/dist/development/core/constants.mjs.map +1 -1
  136. package/dist/development/core/csp/index.d.mts +56 -0
  137. package/dist/development/core/csp/index.mjs +128 -0
  138. package/dist/development/core/csp/index.mjs.map +1 -0
  139. package/dist/development/core/csp/types.d.mts +52 -0
  140. package/dist/development/core/development.d.mts +14 -5
  141. package/dist/development/core/development.mjs +9 -2
  142. package/dist/development/core/headers.mjs +2 -2
  143. package/dist/development/core/headers.mjs.map +1 -1
  144. package/dist/development/core/i18n/define.d.mts +54 -0
  145. package/dist/development/core/i18n/define.mjs +135 -0
  146. package/dist/development/core/i18n/define.mjs.map +1 -0
  147. package/dist/development/core/i18n/errors.d.mts +18 -0
  148. package/dist/development/core/i18n/errors.mjs +24 -0
  149. package/dist/development/core/i18n/errors.mjs.map +1 -0
  150. package/dist/development/core/i18n/href.d.mts +28 -0
  151. package/dist/development/core/i18n/href.mjs +45 -0
  152. package/dist/development/core/i18n/href.mjs.map +1 -0
  153. package/dist/development/core/i18n/locale.d.mts +21 -0
  154. package/dist/development/core/i18n/locale.mjs +36 -0
  155. package/dist/development/core/i18n/locale.mjs.map +1 -0
  156. package/dist/development/core/i18n/match.d.mts +37 -0
  157. package/dist/development/core/i18n/match.mjs +82 -0
  158. package/dist/development/core/i18n/match.mjs.map +1 -0
  159. package/dist/development/core/i18n/types.d.mts +80 -0
  160. package/dist/development/core/index.d.mts +13 -4
  161. package/dist/development/core/predictive-search/index.d.mts +2 -2
  162. package/dist/development/core/predictive-search/queries.d.mts +2 -2
  163. package/dist/development/core/predictive-search/server-handlers.d.mts +27 -6
  164. package/dist/development/core/predictive-search/server-handlers.mjs +1 -4
  165. package/dist/development/core/predictive-search/server-handlers.mjs.map +1 -1
  166. package/dist/development/core/predictive-search/url.d.mts +2 -2
  167. package/dist/development/core/predictive-search/url.mjs.map +1 -1
  168. package/dist/development/core/product/accept-variant-id.mjs +1 -1
  169. package/dist/development/core/product/accept-variant-id.mjs.map +1 -1
  170. package/dist/development/core/request-context.d.mts +61 -35
  171. package/dist/development/core/request-context.mjs +11 -7
  172. package/dist/development/core/request-context.mjs.map +1 -1
  173. package/dist/development/core/request-routing/handle-shopify-routes.mjs.map +1 -1
  174. package/dist/development/core/request-routing/interceptors/api-proxy.mjs +9 -1
  175. package/dist/development/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
  176. package/dist/development/core/request-routing/interceptors/checkout.mjs +11 -5
  177. package/dist/development/core/request-routing/interceptors/checkout.mjs.map +1 -1
  178. package/dist/development/core/request-routing/interceptors/proxy.mjs.map +1 -1
  179. package/dist/development/core/request-routing/interceptors/standard-routes.mjs +1 -1
  180. package/dist/development/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
  181. package/dist/development/core/request-routing/interceptors/url-redirects.mjs +2 -1
  182. package/dist/development/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
  183. package/dist/development/core/request-routing/registered-routes.d.mts +13 -2
  184. package/dist/development/core/request-routing/registered-routes.mjs +33 -9
  185. package/dist/development/core/request-routing/registered-routes.mjs.map +1 -1
  186. package/dist/development/core/request-routing/route-types.d.mts +18 -8
  187. package/dist/development/core/shop-pay/shop-pay.mjs +5 -4
  188. package/dist/development/core/shop-pay/shop-pay.mjs.map +1 -1
  189. package/dist/development/core/shopify-scripts/analytics.mjs +3 -5
  190. package/dist/development/core/shopify-scripts/analytics.mjs.map +1 -1
  191. package/dist/development/core/shopify-scripts/constants.mjs +3 -1
  192. package/dist/development/core/shopify-scripts/constants.mjs.map +1 -1
  193. package/dist/development/core/shopify-scripts/global.mjs +13 -11
  194. package/dist/development/core/shopify-scripts/global.mjs.map +1 -1
  195. package/dist/development/core/shopify-scripts/hashes.d.mts +17 -0
  196. package/dist/development/core/shopify-scripts/hashes.mjs +12 -0
  197. package/dist/development/core/shopify-scripts/hashes.mjs.map +1 -0
  198. package/dist/development/core/shopify-scripts/index.d.mts +1 -0
  199. package/dist/development/core/shopify-scripts/index.mjs +12 -9
  200. package/dist/development/core/shopify-scripts/index.mjs.map +1 -1
  201. package/dist/development/core/shopify-scripts/page-view.mjs +4 -1
  202. package/dist/development/core/shopify-scripts/page-view.mjs.map +1 -1
  203. package/dist/development/core/shopify-scripts/perfkit.mjs +8 -2
  204. package/dist/development/core/shopify-scripts/perfkit.mjs.map +1 -1
  205. package/dist/development/core/shopify-scripts/types.d.mts +4 -2
  206. package/dist/development/core/shopify-scripts/utils/inline-script.mjs +4 -1
  207. package/dist/development/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
  208. package/dist/development/core/standard-routes/build.d.mts +7 -2
  209. package/dist/development/core/standard-routes/build.mjs +10 -3
  210. package/dist/development/core/standard-routes/build.mjs.map +1 -1
  211. package/dist/development/core/standard-routes/match.mjs +11 -1
  212. package/dist/development/core/standard-routes/match.mjs.map +1 -1
  213. package/dist/development/core/standard-routes/path.mjs +14 -3
  214. package/dist/development/core/standard-routes/path.mjs.map +1 -1
  215. package/dist/development/core/standard-routes/types.d.mts +6 -1
  216. package/dist/development/core/url.mjs +5 -3
  217. package/dist/development/core/url.mjs.map +1 -1
  218. package/dist/development/core/utils/load-script.mjs +6 -6
  219. package/dist/development/core/utils/load-script.mjs.map +1 -1
  220. package/dist/development/customer-account/session.mjs.map +1 -1
  221. package/dist/development/globals.d.mts +8 -4
  222. package/dist/development/graphql/type-resolver.d.mts +39 -1
  223. package/dist/development/react/cart.mjs +79 -25
  224. package/dist/development/react/cart.mjs.map +1 -1
  225. package/dist/development/react/index.d.mts +2 -2
  226. package/dist/globals.d.mts +8 -4
  227. package/dist/graphql/type-resolver.d.mts +39 -1
  228. package/dist/react/cart.mjs +79 -25
  229. package/dist/react/cart.mjs.map +1 -1
  230. package/dist/react/index.d.mts +2 -2
  231. package/dist/vite/index.d.mts +11 -1
  232. package/dist/vite/index.mjs +21 -1
  233. package/dist/vite/index.mjs.map +1 -0
  234. package/package.json +13 -3
  235. package/skills/hydrogen-analytics/SKILL.md +2 -2
  236. package/skills/hydrogen-analytics/references/react.md +2 -2
  237. package/skills/hydrogen-cart-ui/SKILL.md +2 -2
  238. package/skills/hydrogen-markets/SKILL.md +127 -93
  239. package/skills/hydrogen-markets/references/nextjs.md +77 -87
  240. package/skills/hydrogen-oxygen/references/react-router.md +1 -2
  241. package/skills/hydrogen-predictive-search/SKILL.md +18 -1
  242. package/skills/hydrogen-request-handlers/SKILL.md +24 -6
  243. package/skills/hydrogen-request-handlers/references/content-security-policy.md +103 -0
  244. package/skills/hydrogen-request-handlers/references/frameworks.md +9 -12
  245. package/skills/hydrogen-request-handlers/references/nextjs.md +7 -3
  246. package/skills/hydrogen-request-handlers/references/nuxt.md +7 -7
  247. package/skills/hydrogen-robots-txt/SKILL.md +87 -0
  248. package/skills/hydrogen-routing/SKILL.md +36 -14
  249. package/skills/hydrogen-setup/SKILL.md +2 -2
  250. package/skills/hydrogen-setup/references/analytics.md +5 -5
  251. package/skills/hydrogen-setup/steps/2-scaffold.md +3 -0
  252. package/skills/hydrogen-setup/steps/7-shopify-runtime-scripts.md +4 -3
  253. package/skills/hydrogen-setup/steps/9-account-page.md +1 -1
  254. package/skills/hydrogen-smoke-test/SKILL.md +9 -2
  255. package/skills/hydrogen-storefront-client/SKILL.md +29 -9
  256. package/skills/hydrogen-storefront-client/references/astro.md +8 -3
  257. package/skills/hydrogen-storefront-client/references/caching.md +2 -0
  258. package/skills/hydrogen-storefront-client/references/nextjs.md +8 -3
  259. package/skills/hydrogen-storefront-client/references/nuxt.md +9 -5
  260. package/skills/hydrogen-storefront-client/references/react-router.md +6 -3
  261. package/skills/hydrogen-storefront-client/references/solidstart.md +6 -2
  262. package/skills/hydrogen-storefront-client/references/sveltekit.md +10 -4
  263. package/skills/migrate-to-hydrogen-2026-10/SKILL.md +20 -22
  264. package/skills/migrate-to-hydrogen-2026-10/references/sitemap-and-seo.md +1 -0
  265. package/skills/migrate-to-hydrogen-2026-10/references/typescript-and-gql-tada.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cart.mjs","names":[],"sources":["../../../src/react/cart.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n type FormHTMLAttributes,\n type ReactNode,\n type RefCallback,\n type SubmitEvent,\n} from \"react\";\n\nimport { trackCartAnalytics } from \"../core/analytics/cart-tracker\";\nimport { attachQuantityInput } from \"../core/cart/attach-quantity-input\";\nimport {\n configureCartEndpoint as configureCoreCartEndpoint,\n createCartStore,\n type CreateCartStoreOptions,\n type CartActions,\n type CartStore,\n} from \"../core/cart/cart\";\nimport { createCartFormRegister, type CartFormRegister } from \"../core/cart/form\";\nimport type { CartDataFromHandlers } from \"../core/cart/server-handlers\";\nimport { type CartData, type CartState } from \"../core/cart/state\";\n\nconst DEFAULT_CART_ENDPOINT = \"/api/cart\";\n\nlet cartEndpoint = DEFAULT_CART_ENDPOINT;\n\nconst CartContext = createContext<CartStore | null>(null);\n\nexport function configureCartEndpoint(endpoint: string): void {\n cartEndpoint = endpoint;\n configureCoreCartEndpoint(endpoint);\n}\n\nexport function getCartEndpoint(): string {\n return cartEndpoint;\n}\n\n/**\n * Props for the cart provider that `createCartComponents` returns.\n */\ntype TypedCartProviderProps<TData extends CartData> = {\n /**\n * The `data` property of the cart GET handler's result, or a promise of that data. Without initial data, the store loads the cart from `/api/cart` after the provider mounts, and the server-rendered page shows an empty cart. The provider creates its store from the first value and ignores later changes.\n */\n initialData?: CartInitialData<TData>;\n /** Content that can read the cart through the cart hooks. */\n children?: ReactNode;\n};\n\ntype CartInitialData<TData extends CartData = CartData> =\n CreateCartStoreOptions<TData>[\"initialData\"];\n\nexport type { CartActions };\n\n/** A hook that returns the slice of cart state that your selector picks. */\ntype CartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S;\n\n/** A hook that returns the slice of cart state that your selector picks, or `undefined` outside the cart provider. */\ntype OptionalCartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value, or `undefined` outside the cart provider.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S | undefined;\n\n/** Callbacks that run around a cart form submission. */\ninterface CartFormPropsOptions {\n /** Runs before the cart store handles the submission. Call `event.preventDefault()` to skip the cart submission. */\n beforeSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n /** Runs as soon as the cart change starts, before the server responds. */\n afterSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n}\n\n/** The form props function and the register function for a cart form. */\ninterface CartFormBindings {\n /** Returns the `method`, `action`, and `onSubmit` props to spread on the form. The form posts to the cart endpoint, and the cart store handles each submission. */\n formProps: (opts?: CartFormPropsOptions) => FormHTMLAttributes<HTMLFormElement>;\n /** Returns the attributes for a cart field or action button. Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled. */\n register: CartFormRegister;\n}\n\n/**\n * The cart provider and hooks that `createCartComponents` returns, typed with the custom cart fields from your cart server handlers.\n */\ntype TypedCartComponents<TData extends CartData> = {\n /** Creates the cart store and shares the store with the cart hooks inside the provider. The provider connects the store on mount and destroys the store on unmount. */\n CartProvider: (props: TypedCartProviderProps<TData>) => ReactNode;\n /**\n * Returns the slice of cart state that the selector picks. The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n */\n useCart: CartStateHook<TData>;\n /** Suspends while the full cart loads, then returns the slice of cart state that the selector picks. Wrap the component in a `Suspense` boundary. */\n useSuspenseCart: CartStateHook<TData>;\n /**\n * Returns the slice of cart state that the selector picks, or `undefined` outside the provider. Use the hook in a component that also renders above the provider, such as a cart badge on an error page.\n */\n useOptionalCart: OptionalCartStateHook<TData>;\n /** Returns the `refresh()` action. Call `refresh()` after a server-side cart change that skips cart forms. */\n useCartActions: typeof useCartActions;\n /** Returns form props and a register function for cart forms. */\n useCartForm: typeof useCartForm;\n};\n\n/**\n * Returns a cart provider and cart hooks typed to the cart fragment in your cart server handlers.\n * Pass `typeof cartServerHandlers` as the `THandlers` type argument. Every hook's cart state then includes your custom cart fields.\n *\n * On mount, the provider sends cart requests to `/api/cart` and connects the store. Every hook except `useOptionalCart` throws when you call it outside the provider.\n *\n * @returns The cart provider, the cart state hooks, and the cart actions and form hooks.\n *\n * @example\n * ```tsx\n * import type { cartServerHandlers } from \"./server/cart.server\";\n *\n * const {\n * CartProvider,\n * useCart,\n * useSuspenseCart,\n * useOptionalCart,\n * useCartActions,\n * useCartForm,\n * } = createCartComponents<typeof cartServerHandlers>();\n * ```\n * @publicDocs\n */\nexport function createCartComponents<THandlers>(): TypedCartComponents<\n CartDataFromHandlers<THandlers>\n> {\n type TData = CartDataFromHandlers<THandlers>;\n\n function TypedCartProvider({ initialData, children }: TypedCartProviderProps<TData>) {\n return (\n <CartProvider initialData={initialData as CartInitialData | undefined}>\n {children}\n </CartProvider>\n );\n }\n\n function useTypedCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n return useCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useTypedOptionalCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S | undefined {\n return useOptionalCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useSuspenseCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n const readyPromise = useCart((state) => state.readyPromise);\n if (readyPromise) throw readyPromise;\n return useCart(selector, isEqual);\n }\n\n return {\n CartProvider: TypedCartProvider,\n useCart: useTypedCart,\n useSuspenseCart,\n useOptionalCart: useTypedOptionalCart,\n useCartActions,\n useCartForm,\n } as const;\n}\n\nexport function useCartStore(hookName = \"useCart\"): CartStore {\n const store = useContext(CartContext);\n if (!store) throw new Error(`${hookName} must be used inside <CartProvider>.`);\n return store;\n}\n\nfunction useOptionalCartStore(): CartStore | null {\n return useContext(CartContext);\n}\n\n/**\n * Creates a cart store and shares the store with the cart hooks inside the provider.\n *\n * Render every cart hook inside the provider. On mount, the provider sends cart requests to `/api/cart` and connects the store. On unmount, the provider destroys the store. The provider creates its store from the first initial data and ignores later changes.\n *\n * @example\n * ```tsx\n * // In your root layout\n * <CartProvider initialData={{ cart: loaderData.cart }}>\n * <App />\n * </CartProvider>\n * ```\n * @param props - The initial cart data and the content that uses the cart hooks.\n * @returns A context provider that shares the cart store with its children.\n * @publicDocs\n */\nexport function CartProvider({\n initialData,\n children,\n}: {\n initialData?: CartInitialData;\n children?: ReactNode;\n}) {\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- store is created once with the initial server data\n const store = useMemo(() => createCartStore({ initialData }), []);\n\n useEffect(() => {\n configureCoreCartEndpoint(cartEndpoint);\n store.connect();\n return () => {\n store.destroy();\n };\n }, [store]);\n\n return <CartContext.Provider value={store}>{children}</CartContext.Provider>;\n}\n\n/**\n * Returns the slice of cart state that the selector picks.\n *\n * The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value.\n *\n * @example\n * ```tsx\n * // Select cart lines\n * const lines = useCart((state) => state.data.lines.nodes);\n *\n * // Select pending state for a specific line\n * const isPending = useCart((state) => state.pending.lines.has(lineId));\n *\n * // Custom equality to avoid re-renders on unchanged totals\n * const total = useCart(\n * (state) => state.data.cost.totalAmount,\n * (a, b) => a.amount === b.amount,\n * );\n * ```\n * @publicDocs\n */\nexport function useCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const store = useCartStore();\n return useCartSelector(store, selector, isEqual) as S;\n}\n\n/**\n * Returns the cart action that reloads the cart after a cart change outside cart forms.\n *\n * Call `refresh()` after a server-side cart change that skips cart forms, such as a server action that creates the cart.\n *\n * @returns The `refresh()` action.\n *\n * @example\n * ```tsx\n * const { refresh } = useCartActions();\n *\n * async function handleServerAction() {\n * await createCartOnServer();\n * refresh(); // re-fetch the cart\n * }\n * ```\n * @publicDocs\n */\nexport function useCartActions(): CartActions {\n const store = useCartStore(\"useCartActions\");\n\n return useMemo(() => ({ refresh: store.refresh }), [store]);\n}\n\n/**\n * Publishes cart analytics events when the customer's cart changes.\n *\n * Call the hook once near the root of your app, inside `CartProvider`. The hook starts tracking on mount and stops on unmount. The hook publishes `cart_updated`, `product_added_to_cart`, and `product_removed_from_cart` events.\n *\n * The hook throws outside `CartProvider`, and when the Shopify analytics bus isn't available. Render `ShopifyScripts` before the hook runs.\n *\n * @returns Nothing. The hook tracks cart analytics for the lifetime of the calling component.\n *\n * @example\n * ```tsx\n * function App() {\n * useCartAnalytics();\n * return <Layout />;\n * }\n * ```\n * @publicDocs\n */\nexport function useCartAnalytics(): void {\n const store = useCartStore(\"useCartAnalytics\");\n\n useEffect(() => trackCartAnalytics(store), [store]);\n}\n\n/**\n * Returns a selected slice of cart state, or `undefined` when the component renders outside the cart provider.\n *\n * Use the hook in a component that also renders above the provider, such as a header cart badge on an error page.\n * Wherever the provider always exists, use `useCart`, which throws when the provider is missing.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value, or `undefined` outside the provider.\n *\n * @example\n * ```tsx\n * function CartBadge() {\n * const count = useOptionalCart((state) => state.data.totalQuantity);\n * if (count === undefined) return null;\n * return <span>Cart ({count})</span>;\n * }\n * ```\n * @publicDocs\n */\nexport function useOptionalCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S | undefined {\n const store = useOptionalCartStore();\n if (!store) return undefined;\n return useCartSelector(store, selector, isEqual);\n}\n\nfunction useCartSelector<TData extends CartData = CartData, S = unknown>(\n store: CartStore,\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const cachedRef = useRef<{ state: unknown; selector: typeof selector; value: S } | null>(null);\n\n const getSnapshot = () => {\n const state = store.getState() as CartState<TData>;\n\n if (\n cachedRef.current &&\n cachedRef.current.state === state &&\n cachedRef.current.selector === selector\n ) {\n return cachedRef.current.value;\n }\n\n const next = selector(state);\n\n if (cachedRef.current && isEqual?.(cachedRef.current.value, next)) {\n cachedRef.current = { state, selector, value: cachedRef.current.value };\n return cachedRef.current.value;\n }\n\n cachedRef.current = { state, selector, value: next };\n return next;\n };\n\n return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * Returns form props and a field register function for building cart forms.\n *\n * Spread `formProps()` on the form. The form posts to the cart endpoint. On submit, the form props stop the browser's navigation and send the form through the cart store.\n * The submit handler ignores a failed cart change. Read failures from the cart state's `errors`.\n * To skip the cart submission, call `event.preventDefault()` in a `beforeSubmit` callback. The `afterSubmit` callback runs as soon as the cart change starts, before the server responds.\n * The register function returns the HTML attributes for each cart field and action.\n *\n * Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled.\n *\n * @returns The form props function and the register function.\n *\n * @example\n * ```tsx\n * function LineItem({ line }) {\n * const { formProps, register } = useCartForm();\n *\n * return (\n * <form {...formProps()}>\n * <input {...register(\"lineId\", { value: line.id })} />\n * <input {...register(\"quantity\", { value: line.quantity, interactive: true })} />\n * <button {...register(\"set\")} />\n * <button {...register(\"increase\")}>+</button>\n * <button {...register(\"decrease\")}>−</button>\n * <button {...register(\"remove\")}>Remove</button>\n * </form>\n * );\n * }\n * ```\n * @publicDocs\n */\nexport function useCartForm(): CartFormBindings {\n const store = useCartStore(\"useCartForm\");\n const coreRegister = useMemo(() => createCartFormRegister(), []);\n\n const register = useMemo(() => {\n type Register = typeof coreRegister;\n const wrapped = ((...args: Parameters<Register>) => {\n const result = (coreRegister as Function)(...args);\n const [field, opts] = args as [string, { interactive?: boolean }?];\n\n if (field === \"quantity\" && opts?.interactive) {\n let cleanup: (() => void) | null = null;\n const ref: RefCallback<HTMLInputElement> = (el) => {\n cleanup?.();\n cleanup = null;\n if (el) {\n const form = el.closest(\"form\");\n if (form) cleanup = attachQuantityInput(el, form);\n }\n };\n const { value: _, ...rest } = result;\n return { ...rest, defaultValue: result.value, ref };\n }\n\n return result;\n }) as Register;\n return wrapped;\n }, [coreRegister]);\n\n const formProps = (opts?: CartFormPropsOptions): FormHTMLAttributes<HTMLFormElement> => ({\n onSubmit: (e: SubmitEvent<HTMLFormElement>) => {\n opts?.beforeSubmit?.(e);\n if (e.defaultPrevented) return;\n e.preventDefault();\n store.handleFormSubmit(e.nativeEvent).catch(() => {});\n opts?.afterSubmit?.(e);\n },\n method: \"post\",\n action: cartEndpoint,\n });\n\n return { formProps, register };\n}\n"],"mappings":";;;;;;;;;;AA8BA,IAAI,eAAe;AAEnB,MAAM,cAAc,cAAgC,KAAK;AAOzD,SAAgB,kBAA0B;AACxC,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;AAmGT,SAAgB,uBAEd;CAGA,SAAS,kBAAkB,EAAE,aAAa,YAA2C;AACnF,SACE,oBAAC,cAAD;GAA2B;GACxB;GACY;;CAInB,SAAS,aACP,UACA,SACG;AACH,SAAO,SAAsB,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAGtF,SAAS,qBACP,UACA,SACe;AACf,SAAO,iBAA8B,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAG9F,SAAS,gBACP,UACA,SACG;EACH,MAAM,eAAe,SAAS,UAAU,MAAM,aAAa;AAC3D,MAAI,aAAc,OAAM;AACxB,SAAO,QAAQ,UAAU,QAAQ;;AAGnC,QAAO;EACL,cAAc;EACd,SAAS;EACT;EACA,iBAAiB;EACjB;EACA;EACD;;AAGH,SAAgB,aAAa,WAAW,WAAsB;CAC5D,MAAM,QAAQ,WAAW,YAAY;AACrC,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,GAAG,SAAS,sCAAsC;AAC9E,QAAO;;AAGT,SAAS,uBAAyC;AAChD,QAAO,WAAW,YAAY;;;;;;;;;;;;;;;;;;AAmBhC,SAAgB,aAAa,EAC3B,aACA,YAIC;CAED,MAAM,QAAQ,cAAc,gBAAgB,E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AAa,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCxE,SAAgB,cAAgC;CAC9C,MAAM,QAAQ,aAAa,cAAc;CACzC,MAAM,eAAe,cAAc,wBAAwB,EAAE,EAAE,CAAC;CAEhE,MAAM,WAAW,cAAc;EAE7B,MAAM,YAAY,GAAG,SAA+B;GAClD,MAAM,SAAU,aAA0B,GAAG,KAAK;GAClD,MAAM,CAAC,OAAO,QAAQ;AAEtB,OAAI,UAAU,cAAc,MAAM,aAAa;IAC7C,IAAI,UAA+B;IACnC,MAAM,OAAsC,OAAO;AACjD,gBAAW;AACX,eAAU;AACV,SAAI,IAAI;MACN,MAAM,OAAO,GAAG,QAAQ,OAAO;AAC/B,UAAI,KAAM,WAAU,oBAAoB,IAAI,KAAK;;;IAGrD,MAAM,EAAE,OAAO,GAAG,GAAG,SAAS;AAC9B,WAAO;KAAE,GAAG;KAAM,cAAc,OAAO;KAAO;KAAK;;AAGrD,UAAO;;AAET,SAAO;IACN,CAAC,aAAa,CAAC;CAElB,MAAM,aAAa,UAAsE;EACvF,WAAW,MAAoC;AAC7C,SAAM,eAAe,EAAE;AACvB,OAAI,EAAE,iBAAkB;AACxB,KAAE,gBAAgB;AAClB,SAAM,iBAAiB,EAAE,YAAY,CAAC,YAAY,GAAG;AACrD,SAAM,cAAc,EAAE;;EAExB,QAAQ;EACR,QAAQ;EACT;AAED,QAAO;EAAE;EAAW;EAAU"}
1
+ {"version":3,"file":"cart.mjs","names":[],"sources":["../../../src/react/cart.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n type FormHTMLAttributes,\n type ReactNode,\n type RefCallback,\n type SubmitEvent,\n} from \"react\";\n\nimport { trackCartAnalytics } from \"../core/analytics/cart-tracker\";\nimport { attachQuantityInput } from \"../core/cart/attach-quantity-input\";\nimport {\n configureCartEndpoint as configureCoreCartEndpoint,\n createCartStore,\n type CreateCartStoreOptions,\n type CartActions,\n type CartStore,\n} from \"../core/cart/cart\";\nimport { createCartFormRegister, type CartFormRegister } from \"../core/cart/form\";\nimport type { CartDataFromHandlers } from \"../core/cart/server-handlers\";\nimport { type CartData, type CartState } from \"../core/cart/state\";\n\nconst DEFAULT_CART_ENDPOINT = \"/api/cart\";\n\nlet cartEndpoint = DEFAULT_CART_ENDPOINT;\n\ninterface CartContextValue {\n store: CartStore;\n hydrationSnapshot: CartState;\n}\n\nconst CartContext = createContext<CartContextValue | null>(null);\n\nexport function configureCartEndpoint(endpoint: string): void {\n cartEndpoint = endpoint;\n configureCoreCartEndpoint(endpoint);\n}\n\nexport function getCartEndpoint(): string {\n return cartEndpoint;\n}\n\n/**\n * Props for the cart provider that `createCartComponents` returns.\n */\ntype TypedCartProviderProps<TData extends CartData> = {\n /**\n * The `data` property of the cart GET handler's result, or a promise of that data. Without initial data, the store loads the cart from `/api/cart` after the provider mounts, and the server-rendered page shows an empty cart. The provider creates its store from the first value and ignores later changes.\n */\n initialData?: CartInitialData<TData>;\n /** Content that can read the cart through the cart hooks. */\n children?: ReactNode;\n};\n\ntype CartInitialData<TData extends CartData = CartData> =\n CreateCartStoreOptions<TData>[\"initialData\"];\n\nexport type { CartActions };\n\n/** A hook that returns the slice of cart state that your selector picks. */\ntype CartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S;\n\n/** A hook that returns the slice of cart state that your selector picks, or `undefined` outside the cart provider. */\ntype OptionalCartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value, or `undefined` outside the cart provider.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S | undefined;\n\n/** Callbacks that run around a cart form submission. */\ninterface CartFormPropsOptions {\n /** Runs before the cart store handles the submission. Call `event.preventDefault()` to skip the cart submission. */\n beforeSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n /** Runs as soon as the cart change starts, before the server responds. */\n afterSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n}\n\n/** The form props function and the register function for a cart form. */\ninterface CartFormBindings {\n /** Returns the `method`, `action`, and `onSubmit` props to spread on the form. The form posts to the cart endpoint, and the cart store handles each submission. */\n formProps: (opts?: CartFormPropsOptions) => FormHTMLAttributes<HTMLFormElement>;\n /** Returns the attributes for a cart field or action button. Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled. */\n register: CartFormRegister;\n}\n\n/**\n * The cart provider and hooks that `createCartComponents` returns, typed with the custom cart fields from your cart server handlers.\n */\ntype TypedCartComponents<TData extends CartData> = {\n /** Creates the cart store and shares the store with the cart hooks inside the provider. The provider connects the store on mount and destroys the store on unmount. */\n CartProvider: (props: TypedCartProviderProps<TData>) => ReactNode;\n /**\n * Returns the slice of cart state that the selector picks. The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n */\n useCart: CartStateHook<TData>;\n /** Suspends while the full cart loads, then returns the slice of cart state that the selector picks. Wrap the component in a `Suspense` boundary. */\n useSuspenseCart: CartStateHook<TData>;\n /**\n * Returns the slice of cart state that the selector picks, or `undefined` outside the provider. Use the hook in a component that also renders above the provider, such as a cart badge on an error page.\n */\n useOptionalCart: OptionalCartStateHook<TData>;\n /** Returns the `refresh()` action. Call `refresh()` after a server-side cart change that skips cart forms. */\n useCartActions: typeof useCartActions;\n /** Returns form props and a register function for cart forms. */\n useCartForm: typeof useCartForm;\n};\n\n/**\n * Returns a cart provider and cart hooks typed to the cart fragment in your cart server handlers.\n * Pass `typeof cartServerHandlers` as the `THandlers` type argument. Every hook's cart state then includes your custom cart fields.\n *\n * On mount, the provider sends cart requests to `/api/cart` and connects the store. Every hook except `useOptionalCart` throws when you call it outside the provider.\n *\n * @returns The cart provider, the cart state hooks, and the cart actions and form hooks.\n *\n * @example\n * ```tsx\n * import type { cartServerHandlers } from \"./server/cart.server\";\n *\n * const {\n * CartProvider,\n * useCart,\n * useSuspenseCart,\n * useOptionalCart,\n * useCartActions,\n * useCartForm,\n * } = createCartComponents<typeof cartServerHandlers>();\n * ```\n * @publicDocs\n */\nexport function createCartComponents<THandlers>(): TypedCartComponents<\n CartDataFromHandlers<THandlers>\n> {\n type TData = CartDataFromHandlers<THandlers>;\n\n function TypedCartProvider({ initialData, children }: TypedCartProviderProps<TData>) {\n return (\n <CartProvider initialData={initialData as CartInitialData | undefined}>\n {children}\n </CartProvider>\n );\n }\n\n function useTypedCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n return useCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useTypedOptionalCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S | undefined {\n return useOptionalCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useSuspenseCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n return useSuspenseCartSelector(selector, isEqual);\n }\n\n return {\n CartProvider: TypedCartProvider,\n useCart: useTypedCart,\n useSuspenseCart,\n useOptionalCart: useTypedOptionalCart,\n useCartActions,\n useCartForm,\n } as const;\n}\n\nexport function useCartStore(hookName = \"useCart\"): CartStore {\n return useCartContext(hookName).store;\n}\n\nfunction useCartContext(hookName = \"useCart\"): CartContextValue {\n const context = useContext(CartContext);\n if (!context) throw new Error(`${hookName} must be used inside <CartProvider>.`);\n return context;\n}\n\nfunction useOptionalCartContext(): CartContextValue | null {\n return useContext(CartContext);\n}\n\n/**\n * Creates a cart store and shares the store with the cart hooks inside the provider.\n *\n * Render every cart hook inside the provider. On mount, the provider sends cart requests to `/api/cart` and connects the store. On unmount, the provider destroys the store. The provider creates its store from the first initial data and ignores later changes.\n *\n * @example\n * ```tsx\n * // In your root layout\n * <CartProvider initialData={{ cart: loaderData.cart }}>\n * <App />\n * </CartProvider>\n * ```\n * @param props - The initial cart data and the content that uses the cart hooks.\n * @returns A context provider that shares the cart store with its children.\n * @publicDocs\n */\nexport function CartProvider({\n initialData,\n children,\n}: {\n initialData?: CartInitialData;\n children?: ReactNode;\n}) {\n const context = useMemo(() => {\n const store = createCartStore({ initialData });\n // Plain consumers must hydrate from the state used for SSR, even if the live store settles first.\n return { store, hydrationSnapshot: store.getState() };\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- provider initialData seeds one store for its lifetime\n }, []);\n const { store } = context;\n\n useEffect(() => {\n configureCoreCartEndpoint(cartEndpoint);\n store.connect();\n return () => {\n store.destroy();\n };\n }, [store]);\n\n return <CartContext.Provider value={context}>{children}</CartContext.Provider>;\n}\n\n/**\n * Returns the slice of cart state that the selector picks.\n *\n * The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value.\n *\n * @example\n * ```tsx\n * // Select cart lines\n * const lines = useCart((state) => state.data.lines.nodes);\n *\n * // Select pending state for a specific line\n * const isPending = useCart((state) => state.pending.lines.has(lineId));\n *\n * // Custom equality to avoid re-renders on unchanged totals\n * const total = useCart(\n * (state) => state.data.cost.totalAmount,\n * (a, b) => a.amount === b.amount,\n * );\n * ```\n * @publicDocs\n */\nexport function useCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const { store, hydrationSnapshot } = useCartContext();\n return useCartSelector(store, hydrationSnapshot, selector, isEqual) as S;\n}\n\n/**\n * Returns the cart action that reloads the cart after a cart change outside cart forms.\n *\n * Call `refresh()` after a server-side cart change that skips cart forms, such as a server action that creates the cart.\n *\n * @returns The `refresh()` action.\n *\n * @example\n * ```tsx\n * const { refresh } = useCartActions();\n *\n * async function handleServerAction() {\n * await createCartOnServer();\n * refresh(); // re-fetch the cart\n * }\n * ```\n * @publicDocs\n */\nexport function useCartActions(): CartActions {\n const store = useCartStore(\"useCartActions\");\n\n return useMemo(() => ({ refresh: store.refresh }), [store]);\n}\n\n/**\n * Publishes cart analytics events when the customer's cart changes.\n *\n * Call the hook once near the root of your app, inside `CartProvider`. The hook starts tracking on mount and stops on unmount. The hook publishes `cart_updated`, `product_added_to_cart`, and `product_removed_from_cart` events.\n *\n * The hook throws outside `CartProvider`, and when the Shopify analytics bus isn't available. Render `ShopifyScripts` before the hook runs.\n *\n * @returns Nothing. The hook tracks cart analytics for the lifetime of the calling component.\n *\n * @example\n * ```tsx\n * function App() {\n * useCartAnalytics();\n * return <Layout />;\n * }\n * ```\n * @publicDocs\n */\nexport function useCartAnalytics(): void {\n const store = useCartStore(\"useCartAnalytics\");\n\n useEffect(() => trackCartAnalytics(store), [store]);\n}\n\n/**\n * Returns a selected slice of cart state, or `undefined` when the component renders outside the cart provider.\n *\n * Use the hook in a component that also renders above the provider, such as a header cart badge on an error page.\n * Wherever the provider always exists, use `useCart`, which throws when the provider is missing.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value, or `undefined` outside the provider.\n *\n * @example\n * ```tsx\n * function CartBadge() {\n * const count = useOptionalCart((state) => state.data.totalQuantity);\n * if (count === undefined) return null;\n * return <span>Cart ({count})</span>;\n * }\n * ```\n * @publicDocs\n */\nexport function useOptionalCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S | undefined {\n const context = useOptionalCartContext();\n if (!context) return undefined;\n return useCartSelector(context.store, context.hydrationSnapshot, selector, isEqual);\n}\n\nfunction useCartSelector<TData extends CartData = CartData, S = unknown>(\n store: CartStore,\n hydrationSnapshot: CartState,\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const liveCacheRef = useRef<SelectorCache<S> | null>(null);\n const hydrationCacheRef = useRef<SelectorCache<S> | null>(null);\n\n const getSnapshot = () =>\n selectCartSnapshot(store.getState() as CartState<TData>, selector, isEqual, liveCacheRef);\n const getServerSnapshot = () =>\n selectCartSnapshot(hydrationSnapshot as CartState<TData>, selector, isEqual, hydrationCacheRef);\n\n return useSyncExternalStore(store.subscribe, getSnapshot, getServerSnapshot);\n}\n\ninterface SelectorCache<S> {\n state: unknown;\n selector: unknown;\n value: S;\n}\n\nfunction selectCartSnapshot<TData extends CartData, S>(\n state: CartState<TData>,\n selector: (state: CartState<TData>) => S,\n isEqual: ((a: S, b: S) => boolean) | undefined,\n cacheRef: { current: SelectorCache<S> | null },\n): S {\n if (cacheRef.current?.state === state && cacheRef.current.selector === selector) {\n return cacheRef.current.value;\n }\n\n const next = selector(state);\n\n if (cacheRef.current && isEqual?.(cacheRef.current.value, next)) {\n cacheRef.current = { state, selector, value: cacheRef.current.value };\n return cacheRef.current.value;\n }\n\n cacheRef.current = { state, selector, value: next };\n return next;\n}\n\ntype SuspenseSnapshot<S> =\n | { status: \"pending\"; promise: PromiseLike<void> }\n | { status: \"ready\"; value: S };\n\ninterface SuspenseSelectorCache<S> {\n state: unknown;\n selector: unknown;\n snapshot: SuspenseSnapshot<S>;\n}\n\nfunction useSuspenseCartSelector<TData extends CartData, S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const { store } = useCartContext();\n const cacheRef = useRef<SuspenseSelectorCache<S> | null>(null);\n\n // Suspense retries must read live readiness and data; the hydration snapshot would freeze the fallback.\n const getSnapshot = () => {\n const state = store.getState() as CartState<TData>;\n\n if (cacheRef.current?.state === state && cacheRef.current.selector === selector) {\n return cacheRef.current.snapshot;\n }\n\n if (state.readyPromise) {\n const snapshot: SuspenseSnapshot<S> = { status: \"pending\", promise: state.readyPromise };\n cacheRef.current = { state, selector, snapshot };\n return snapshot;\n }\n\n const value = selector(state);\n const previous = cacheRef.current?.snapshot;\n\n if (previous?.status === \"ready\" && isEqual?.(previous.value, value)) {\n cacheRef.current = { state, selector, snapshot: previous };\n return previous;\n }\n\n const snapshot: SuspenseSnapshot<S> = { status: \"ready\", value };\n cacheRef.current = { state, selector, snapshot };\n return snapshot;\n };\n\n const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n if (snapshot.status === \"pending\") throw snapshot.promise;\n return snapshot.value;\n}\n\n/**\n * Returns form props and a field register function for building cart forms.\n *\n * Spread `formProps()` on the form. The form posts to the cart endpoint. On submit, the form props stop the browser's navigation and send the form through the cart store.\n * The submit handler ignores a failed cart change. Read failures from the cart state's `errors`.\n * To skip the cart submission, call `event.preventDefault()` in a `beforeSubmit` callback. The `afterSubmit` callback runs as soon as the cart change starts, before the server responds.\n * The register function returns the HTML attributes for each cart field and action.\n *\n * Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled.\n *\n * @returns The form props function and the register function.\n *\n * @example\n * ```tsx\n * function LineItem({ line }) {\n * const { formProps, register } = useCartForm();\n *\n * return (\n * <form {...formProps()}>\n * <input {...register(\"lineId\", { value: line.id })} />\n * <input {...register(\"quantity\", { value: line.quantity, interactive: true })} />\n * <button {...register(\"set\")} />\n * <button {...register(\"increase\")}>+</button>\n * <button {...register(\"decrease\")}>−</button>\n * <button {...register(\"remove\")}>Remove</button>\n * </form>\n * );\n * }\n * ```\n * @publicDocs\n */\nexport function useCartForm(): CartFormBindings {\n const store = useCartStore(\"useCartForm\");\n const coreRegister = useMemo(() => createCartFormRegister(), []);\n\n const register = useMemo(() => {\n type Register = typeof coreRegister;\n const wrapped = ((...args: Parameters<Register>) => {\n const result = (coreRegister as Function)(...args);\n const [field, opts] = args as [string, { interactive?: boolean }?];\n\n if (field === \"quantity\" && opts?.interactive) {\n let cleanup: (() => void) | null = null;\n const ref: RefCallback<HTMLInputElement> = (el) => {\n cleanup?.();\n cleanup = null;\n if (el) {\n const form = el.closest(\"form\");\n if (form) cleanup = attachQuantityInput(el, form);\n }\n };\n const { value: _, ...rest } = result;\n return { ...rest, defaultValue: result.value, ref };\n }\n\n return result;\n }) as Register;\n return wrapped;\n }, [coreRegister]);\n\n const formProps = (opts?: CartFormPropsOptions): FormHTMLAttributes<HTMLFormElement> => ({\n onSubmit: (e: SubmitEvent<HTMLFormElement>) => {\n opts?.beforeSubmit?.(e);\n if (e.defaultPrevented) return;\n e.preventDefault();\n store.handleFormSubmit(e.nativeEvent).catch(() => {});\n opts?.afterSubmit?.(e);\n },\n method: \"post\",\n action: cartEndpoint,\n });\n\n return { formProps, register };\n}\n"],"mappings":";;;;;;;;;;AA8BA,IAAI,eAAe;AAOnB,MAAM,cAAc,cAAuC,KAAK;AAOhE,SAAgB,kBAA0B;AACxC,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;AAmGT,SAAgB,uBAEd;CAGA,SAAS,kBAAkB,EAAE,aAAa,YAA2C;AACnF,SACE,oBAAC,cAAD;GAA2B;GACxB;GACY;;CAInB,SAAS,aACP,UACA,SACG;AACH,SAAO,SAAsB,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAGtF,SAAS,qBACP,UACA,SACe;AACf,SAAO,iBAA8B,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAG9F,SAAS,gBACP,UACA,SACG;AACH,SAAO,wBAAwB,UAAU,QAAQ;;AAGnD,QAAO;EACL,cAAc;EACd,SAAS;EACT;EACA,iBAAiB;EACjB;EACA;EACD;;AAGH,SAAgB,aAAa,WAAW,WAAsB;AAC5D,QAAO,eAAe,SAAS,CAAC;;AAGlC,SAAS,eAAe,WAAW,WAA6B;CAC9D,MAAM,UAAU,WAAW,YAAY;AACvC,KAAI,CAAC,QAAS,OAAM,IAAI,MAAM,GAAG,SAAS,sCAAsC;A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;;;;;;;;;;;;;;;;;;;;;;;AAkClB,SAAgB,cAAgC;CAC9C,MAAM,QAAQ,aAAa,cAAc;CACzC,MAAM,eAAe,cAAc,wBAAwB,EAAE,EAAE,CAAC;CAEhE,MAAM,WAAW,cAAc;EAE7B,MAAM,YAAY,GAAG,SAA+B;GAClD,MAAM,SAAU,aAA0B,GAAG,KAAK;GAClD,MAAM,CAAC,OAAO,QAAQ;AAEtB,OAAI,UAAU,cAAc,MAAM,aAAa;IAC7C,IAAI,UAA+B;IACnC,MAAM,OAAsC,OAAO;AACjD,gBAAW;AACX,eAAU;AACV,SAAI,IAAI;MACN,MAAM,OAAO,GAAG,QAAQ,OAAO;AAC/B,UAAI,KAAM,WAAU,oBAAoB,IAAI,KAAK;;;IAGrD,MAAM,EAAE,OAAO,GAAG,GAAG,SAAS;AAC9B,WAAO;KAAE,GAAG;KAAM,cAAc,OAAO;KAAO;KAAK;;AAGrD,UAAO;;AAET,SAAO;IACN,CAAC,aAAa,CAAC;CAElB,MAAM,aAAa,UAAsE;EACvF,WAAW,MAAoC;AAC7C,SAAM,eAAe,EAAE;AACvB,OAAI,EAAE,iBAAkB;AACxB,KAAE,gBAAgB;AAClB,SAAM,iBAAiB,EAAE,YAAY,CAAC,YAAY,GAAG;AACrD,SAAM,cAAc,EAAE;;EAExB,QAAQ;EACR,QAAQ;EACT;AAED,QAAO;EAAE;EAAW;EAAU"}
@@ -1,7 +1,7 @@
1
1
  import { ShopifyStandardActions } from "../vendor/standard-actions.mjs";
2
2
  import { CartActions } from "../core/cart/cart.mjs";
3
3
  import { ShopifyGlobal } from "../globals.mjs";
4
- import { QuantityInputAttributes, SetButtonAttributes } from "../core/cart/form.mjs";
4
+ import { QuantityInputAttributes, RemoveButtonAttributes, SetButtonAttributes } from "../core/cart/form.mjs";
5
5
  import { CollectionActions, CollectionData } from "../core/collection/collection.mjs";
6
6
  import { ValidProductSelectionResult } from "../core/product/product-form.mjs";
7
7
  import { ProductAddToCartProps, ProductAttributeDefaultValueProps, ProductAttributeValueProps, ProductFormRegister, ProductMerchandiseIdProps, ProductOptionValueProps, ProductQuantityDefaultProps, ProductQuantityProps } from "../core/product/form.mjs";
@@ -12,4 +12,4 @@ import { PredictiveSearchFormPropsOptions, PredictiveSearchFormRegister, Predict
12
12
  import { ProductProviderProps, UseProductFormOptions, UseProductFormResult, UseProductResult, createProductComponents, useProductForm } from "./product.mjs";
13
13
  import { ShopPayButton, ShopPayButtonProps } from "./shop-pay.mjs";
14
14
  import { ShopifyScripts, ShopifyScriptsProps } from "./shopify-scripts.mjs";
15
- export { type CartActions, type CollectionActions, type CollectionData, CollectionProvider, type CollectionProviderProps, type PredictiveSearchActions, type PredictiveSearchFormPropsOptions, type PredictiveSearchFormRegister, type PredictiveSearchFormResult, PredictiveSearchProvider, type PredictiveSearchProviderProps, type PredictiveSearchQueryInputPropsOptions, type ProductAddToCartProps, type ProductAttributeDefaultValueProps, type ProductAttributeValueProps, type ProductFormRegister, type ProductMerchandiseIdProps, type ProductOptionValueProps, type ProductProviderProps, type ProductQuantityDefaultProps, type ProductQuantityProps, type QuantityInputAttributes, type SetButtonAttributes, ShopPayButton, type ShopPayButtonProps, type ShopifyGlobal, ShopifyScripts, type ShopifyScriptsProps, type ShopifyStandardActions, type UseProductFormOptions, type UseProductFormResult, type UseProductResult, type ValidProductSelectionResult, createCartComponents, createProductComponents, useCartAnalytics, useCollection, useCollectionActions, useCollectionForm, usePredictiveSearch, usePredictiveSearchActions, usePredictiveSearchForm, useProductForm };
15
+ export { type CartActions, type CollectionActions, type CollectionData, CollectionProvider, type CollectionProviderProps, type PredictiveSearchActions, type PredictiveSearchFormPropsOptions, type PredictiveSearchFormRegister, type PredictiveSearchFormResult, PredictiveSearchProvider, type PredictiveSearchProviderProps, type PredictiveSearchQueryInputPropsOptions, type ProductAddToCartProps, type ProductAttributeDefaultValueProps, type ProductAttributeValueProps, type ProductFormRegister, type ProductMerchandiseIdProps, type ProductOptionValueProps, type ProductProviderProps, type ProductQuantityDefaultProps, type ProductQuantityProps, type QuantityInputAttributes, type RemoveButtonAttributes, type SetButtonAttributes, ShopPayButton, type ShopPayButtonProps, type ShopifyGlobal, ShopifyScripts, type ShopifyScriptsProps, type ShopifyStandardActions, type UseProductFormOptions, type UseProductFormResult, type UseProductResult, type ValidProductSelectionResult, createCartComponents, createProductComponents, useCartAnalytics, useCollection, useCollectionActions, useCollectionForm, usePredictiveSearch, usePredictiveSearchActions, usePredictiveSearchForm, useProductForm };
@@ -1,4 +1,4 @@
1
- import { I18nConfig } from "./core/request-context.mjs";
1
+ import { ShopifyCountryCode, ShopifyLanguageCode } from "./core/i18n/types.mjs";
2
2
  import { ShopifyStandardRouteMatch } from "./core/standard-routes/types.mjs";
3
3
  import { ShopifyStandardActions } from "./vendor/standard-actions.mjs";
4
4
  import { StorefrontAnalytics } from "./core/analytics/types.mjs";
@@ -11,7 +11,11 @@ import { StorefrontAnalytics } from "./core/analytics/types.mjs";
11
11
  */
12
12
  type ShopifyGlobal = {
13
13
  actions: ShopifyStandardActions;
14
- analytics?: StorefrontAnalytics; /** The store settings that Shopify's storefront web components read. */
14
+ analytics?: StorefrontAnalytics; /** The application that rendered the page. */
15
+ application: {
16
+ name: "hydrogen"; /** The `@shopify/hydrogen` release in use. */
17
+ version: string;
18
+ }; /** The store settings that Shopify's storefront web components read. */
15
19
  components: {
16
20
  config: {
17
21
  storeDomain: string;
@@ -21,7 +25,7 @@ type ShopifyGlobal = {
21
25
  language?: string;
22
26
  };
23
27
  }; /** The customer's country code. Defaults to `US`. */
24
- country: I18nConfig["country"] | string; /** The active currency code, in uppercase. */
28
+ country: ShopifyCountryCode | string; /** The active currency code, in uppercase. */
25
29
  currency?: {
26
30
  active: string;
27
31
  }; /** Shopify's Customer Privacy API, which reads and updates the customer's consent. */
@@ -42,7 +46,7 @@ type ShopifyGlobal = {
42
46
  shouldShowBanner: () => boolean;
43
47
  shouldShowGDPRBanner: () => boolean;
44
48
  }; /** The customer's language code, in lowercase. Defaults to `en`. */
45
- locale: Lowercase<I18nConfig["language"]> | string;
49
+ locale: Lowercase<ShopifyLanguageCode> | string;
46
50
  /**
47
51
  * Navigates to a storefront URL.
48
52
  * @deprecated Use `Shopify.routes.navigate` instead.
@@ -245,6 +245,44 @@ type InferResult<T extends string> = InferResultForSchema<T, StorefrontSchema>;
245
245
  type InferVariables<T extends string> = InferVariablesForSchema<T, StorefrontSchema>;
246
246
  /** The operation kind of a query string, such as `query`. Resolves to `unknown` unless the query text has exactly one operation. */
247
247
  type InferOperationKind<T extends string> = parseDocument<T> extends infer Doc ? [Doc] extends [never] ? "unknown" : OperationKindType<Doc> : "unknown";
248
+ type DeclaredNameOfType<Definition, Types> = Definition extends {
249
+ variable: {
250
+ name: {
251
+ value: infer Name extends keyof Types;
252
+ };
253
+ };
254
+ type: infer Type;
255
+ } ? (Type extends {
256
+ kind: "NonNullType";
257
+ type: infer Inner;
258
+ } ? Inner : Type) extends {
259
+ kind: "NamedType";
260
+ name: {
261
+ value: Types[Name];
262
+ };
263
+ } ? Name : never : never;
264
+ /**
265
+ * Names of the first operation's variables that are declared with the named
266
+ * type `Types` maps them to, nullable or non-null. List types never match.
267
+ */
268
+ type InferVariableNamesDeclaredAs<T extends string, Types extends Record<string, string>> = parseDocument<T> extends infer Doc ? Doc extends {
269
+ kind: "Document";
270
+ definitions: infer Defs extends readonly unknown[];
271
+ } ? FirstOperation<Defs> extends {
272
+ variableDefinitions: infer Vars extends readonly unknown[];
273
+ } ? DeclaredNameOfType<Vars[number], Types> : never : never : never;
274
+ type IsExactly<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
275
+ /**
276
+ * Names of the variables whose resolved type is exactly the enum `Types` maps
277
+ * them to in `Introspection`. Documents without source text only expose
278
+ * resolved variable types, so an exact enum match stands in for the declared
279
+ * type that `InferVariableNamesDeclaredAs` reads from the source.
280
+ */
281
+ type InferVariableNamesByEnumValue<Variables, Types extends Record<string, string>, Introspection extends {
282
+ types: Record<Types[keyof Types], {
283
+ enumValues: unknown;
284
+ }>;
285
+ }> = { [K in keyof Variables & keyof Types]-?: IsExactly<NonNullable<Variables[K]>, Introspection["types"][Types[K]]["enumValues"]> extends true ? K : never }[keyof Variables & keyof Types];
248
286
  //#endregion
249
- export { GraphQLSchemaFor, InferOperationKind, InferResult, InferResultForSchema, InferVariables, InferVariablesForSchema };
287
+ export { GraphQLSchemaFor, InferOperationKind, InferResult, InferResultForSchema, InferVariableNamesByEnumValue, InferVariableNamesDeclaredAs, InferVariables, InferVariablesForSchema };
250
288
  //# sourceMappingURL=type-resolver.d.mts.map
@@ -50,9 +50,7 @@ function createCartComponents() {
50
50
  return useOptionalCart((state) => selector(state), isEqual);
51
51
  }
52
52
  function useSuspenseCart(selector, isEqual) {
53
- const readyPromise = useCart((state) => state.readyPromise);
54
- if (readyPromise) throw readyPromise;
55
- return useCart(selector, isEqual);
53
+ return useSuspenseCartSelector(selector, isEqual);
56
54
  }
57
55
  return {
58
56
  CartProvider: TypedCartProvider,
@@ -64,11 +62,14 @@ function createCartComponents() {
64
62
  };
65
63
  }
66
64
  function useCartStore(hookName = "useCart") {
67
- const store = useContext(CartContext);
68
- if (!store) throw new Error(`${hookName} must be used inside <CartProvider>.`);
69
- return store;
65
+ return useCartContext(hookName).store;
70
66
  }
71
- function useOptionalCartStore() {
67
+ function useCartContext(hookName = "useCart") {
68
+ const context = useContext(CartContext);
69
+ if (!context) throw new Error(`${hookName} must be used inside <CartProvider>.`);
70
+ return context;
71
+ }
72
+ function useOptionalCartContext() {
72
73
  return useContext(CartContext);
73
74
  }
74
75
  /**
@@ -88,7 +89,14 @@ function useOptionalCartStore() {
88
89
  * @publicDocs
89
90
  */
90
91
  function CartProvider({ initialData, children }) {
91
- const store = useMemo(() => createCartStore({ initialData }), []);
92
+ const context = useMemo(() => {
93
+ const store = createCartStore({ initialData });
94
+ return {
95
+ store,
96
+ hydrationSnapshot: store.getState()
97
+ };
98
+ }, []);
99
+ const { store } = context;
92
100
  useEffect(() => {
93
101
  configureCartEndpoint(cartEndpoint);
94
102
  store.connect();
@@ -97,7 +105,7 @@ function CartProvider({ initialData, children }) {
97
105
  };
98
106
  }, [store]);
99
107
  return /* @__PURE__ */ jsx(CartContext.Provider, {
100
- value: store,
108
+ value: context,
101
109
  children
102
110
  });
103
111
  }
@@ -127,7 +135,8 @@ function CartProvider({ initialData, children }) {
127
135
  * @publicDocs
128
136
  */
129
137
  function useCart(selector, isEqual) {
130
- return useCartSelector(useCartStore(), selector, isEqual);
138
+ const { store, hydrationSnapshot } = useCartContext();
139
+ return useCartSelector(store, hydrationSnapshot, selector, isEqual);
131
140
  }
132
141
  /**
133
142
  * Returns the cart action that reloads the cart after a cart change outside cart forms.
@@ -194,32 +203,77 @@ function useCartAnalytics() {
194
203
  * @publicDocs
195
204
  */
196
205
  function useOptionalCart(selector, isEqual) {
197
- const store = useOptionalCartStore();
198
- if (!store) return void 0;
199
- return useCartSelector(store, selector, isEqual);
206
+ const context = useOptionalCartContext();
207
+ if (!context) return void 0;
208
+ return useCartSelector(context.store, context.hydrationSnapshot, selector, isEqual);
200
209
  }
201
- function useCartSelector(store, selector, isEqual) {
202
- const cachedRef = useRef(null);
210
+ function useCartSelector(store, hydrationSnapshot, selector, isEqual) {
211
+ const liveCacheRef = useRef(null);
212
+ const hydrationCacheRef = useRef(null);
213
+ const getSnapshot = () => selectCartSnapshot(store.getState(), selector, isEqual, liveCacheRef);
214
+ const getServerSnapshot = () => selectCartSnapshot(hydrationSnapshot, selector, isEqual, hydrationCacheRef);
215
+ return useSyncExternalStore(store.subscribe, getSnapshot, getServerSnapshot);
216
+ }
217
+ function selectCartSnapshot(state, selector, isEqual, cacheRef) {
218
+ if (cacheRef.current?.state === state && cacheRef.current.selector === selector) return cacheRef.current.value;
219
+ const next = selector(state);
220
+ if (cacheRef.current && isEqual?.(cacheRef.current.value, next)) {
221
+ cacheRef.current = {
222
+ state,
223
+ selector,
224
+ value: cacheRef.current.value
225
+ };
226
+ return cacheRef.current.value;
227
+ }
228
+ cacheRef.current = {
229
+ state,
230
+ selector,
231
+ value: next
232
+ };
233
+ return next;
234
+ }
235
+ function useSuspenseCartSelector(selector, isEqual) {
236
+ const { store } = useCartContext();
237
+ const cacheRef = useRef(null);
203
238
  const getSnapshot = () => {
204
239
  const state = store.getState();
205
- if (cachedRef.current && cachedRef.current.state === state && cachedRef.current.selector === selector) return cachedRef.current.value;
206
- const next = selector(state);
207
- if (cachedRef.current && isEqual?.(cachedRef.current.value, next)) {
208
- cachedRef.current = {
240
+ if (cacheRef.current?.state === state && cacheRef.current.selector === selector) return cacheRef.current.snapshot;
241
+ if (state.readyPromise) {
242
+ const snapshot = {
243
+ status: "pending",
244
+ promise: state.readyPromise
245
+ };
246
+ cacheRef.current = {
209
247
  state,
210
248
  selector,
211
- value: cachedRef.current.value
249
+ snapshot
212
250
  };
213
- return cachedRef.current.value;
251
+ return snapshot;
214
252
  }
215
- cachedRef.current = {
253
+ const value = selector(state);
254
+ const previous = cacheRef.current?.snapshot;
255
+ if (previous?.status === "ready" && isEqual?.(previous.value, value)) {
256
+ cacheRef.current = {
257
+ state,
258
+ selector,
259
+ snapshot: previous
260
+ };
261
+ return previous;
262
+ }
263
+ const snapshot = {
264
+ status: "ready",
265
+ value
266
+ };
267
+ cacheRef.current = {
216
268
  state,
217
269
  selector,
218
- value: next
270
+ snapshot
219
271
  };
220
- return next;
272
+ return snapshot;
221
273
  };
222
- return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
274
+ const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
275
+ if (snapshot.status === "pending") throw snapshot.promise;
276
+ return snapshot.value;
223
277
  }
224
278
  /**
225
279
  * Returns form props and a field register function for building cart forms.
@@ -1 +1 @@
1
- {"version":3,"file":"cart.mjs","names":[],"sources":["../../src/react/cart.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n type FormHTMLAttributes,\n type ReactNode,\n type RefCallback,\n type SubmitEvent,\n} from \"react\";\n\nimport { trackCartAnalytics } from \"../core/analytics/cart-tracker\";\nimport { attachQuantityInput } from \"../core/cart/attach-quantity-input\";\nimport {\n configureCartEndpoint as configureCoreCartEndpoint,\n createCartStore,\n type CreateCartStoreOptions,\n type CartActions,\n type CartStore,\n} from \"../core/cart/cart\";\nimport { createCartFormRegister, type CartFormRegister } from \"../core/cart/form\";\nimport type { CartDataFromHandlers } from \"../core/cart/server-handlers\";\nimport { type CartData, type CartState } from \"../core/cart/state\";\n\nconst DEFAULT_CART_ENDPOINT = \"/api/cart\";\n\nlet cartEndpoint = DEFAULT_CART_ENDPOINT;\n\nconst CartContext = createContext<CartStore | null>(null);\n\nexport function configureCartEndpoint(endpoint: string): void {\n cartEndpoint = endpoint;\n configureCoreCartEndpoint(endpoint);\n}\n\nexport function getCartEndpoint(): string {\n return cartEndpoint;\n}\n\n/**\n * Props for the cart provider that `createCartComponents` returns.\n */\ntype TypedCartProviderProps<TData extends CartData> = {\n /**\n * The `data` property of the cart GET handler's result, or a promise of that data. Without initial data, the store loads the cart from `/api/cart` after the provider mounts, and the server-rendered page shows an empty cart. The provider creates its store from the first value and ignores later changes.\n */\n initialData?: CartInitialData<TData>;\n /** Content that can read the cart through the cart hooks. */\n children?: ReactNode;\n};\n\ntype CartInitialData<TData extends CartData = CartData> =\n CreateCartStoreOptions<TData>[\"initialData\"];\n\nexport type { CartActions };\n\n/** A hook that returns the slice of cart state that your selector picks. */\ntype CartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S;\n\n/** A hook that returns the slice of cart state that your selector picks, or `undefined` outside the cart provider. */\ntype OptionalCartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value, or `undefined` outside the cart provider.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S | undefined;\n\n/** Callbacks that run around a cart form submission. */\ninterface CartFormPropsOptions {\n /** Runs before the cart store handles the submission. Call `event.preventDefault()` to skip the cart submission. */\n beforeSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n /** Runs as soon as the cart change starts, before the server responds. */\n afterSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n}\n\n/** The form props function and the register function for a cart form. */\ninterface CartFormBindings {\n /** Returns the `method`, `action`, and `onSubmit` props to spread on the form. The form posts to the cart endpoint, and the cart store handles each submission. */\n formProps: (opts?: CartFormPropsOptions) => FormHTMLAttributes<HTMLFormElement>;\n /** Returns the attributes for a cart field or action button. Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled. */\n register: CartFormRegister;\n}\n\n/**\n * The cart provider and hooks that `createCartComponents` returns, typed with the custom cart fields from your cart server handlers.\n */\ntype TypedCartComponents<TData extends CartData> = {\n /** Creates the cart store and shares the store with the cart hooks inside the provider. The provider connects the store on mount and destroys the store on unmount. */\n CartProvider: (props: TypedCartProviderProps<TData>) => ReactNode;\n /**\n * Returns the slice of cart state that the selector picks. The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n */\n useCart: CartStateHook<TData>;\n /** Suspends while the full cart loads, then returns the slice of cart state that the selector picks. Wrap the component in a `Suspense` boundary. */\n useSuspenseCart: CartStateHook<TData>;\n /**\n * Returns the slice of cart state that the selector picks, or `undefined` outside the provider. Use the hook in a component that also renders above the provider, such as a cart badge on an error page.\n */\n useOptionalCart: OptionalCartStateHook<TData>;\n /** Returns the `refresh()` action. Call `refresh()` after a server-side cart change that skips cart forms. */\n useCartActions: typeof useCartActions;\n /** Returns form props and a register function for cart forms. */\n useCartForm: typeof useCartForm;\n};\n\n/**\n * Returns a cart provider and cart hooks typed to the cart fragment in your cart server handlers.\n * Pass `typeof cartServerHandlers` as the `THandlers` type argument. Every hook's cart state then includes your custom cart fields.\n *\n * On mount, the provider sends cart requests to `/api/cart` and connects the store. Every hook except `useOptionalCart` throws when you call it outside the provider.\n *\n * @returns The cart provider, the cart state hooks, and the cart actions and form hooks.\n *\n * @example\n * ```tsx\n * import type { cartServerHandlers } from \"./server/cart.server\";\n *\n * const {\n * CartProvider,\n * useCart,\n * useSuspenseCart,\n * useOptionalCart,\n * useCartActions,\n * useCartForm,\n * } = createCartComponents<typeof cartServerHandlers>();\n * ```\n * @publicDocs\n */\nexport function createCartComponents<THandlers>(): TypedCartComponents<\n CartDataFromHandlers<THandlers>\n> {\n type TData = CartDataFromHandlers<THandlers>;\n\n function TypedCartProvider({ initialData, children }: TypedCartProviderProps<TData>) {\n return (\n <CartProvider initialData={initialData as CartInitialData | undefined}>\n {children}\n </CartProvider>\n );\n }\n\n function useTypedCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n return useCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useTypedOptionalCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S | undefined {\n return useOptionalCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useSuspenseCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n const readyPromise = useCart((state) => state.readyPromise);\n if (readyPromise) throw readyPromise;\n return useCart(selector, isEqual);\n }\n\n return {\n CartProvider: TypedCartProvider,\n useCart: useTypedCart,\n useSuspenseCart,\n useOptionalCart: useTypedOptionalCart,\n useCartActions,\n useCartForm,\n } as const;\n}\n\nexport function useCartStore(hookName = \"useCart\"): CartStore {\n const store = useContext(CartContext);\n if (!store) throw new Error(`${hookName} must be used inside <CartProvider>.`);\n return store;\n}\n\nfunction useOptionalCartStore(): CartStore | null {\n return useContext(CartContext);\n}\n\n/**\n * Creates a cart store and shares the store with the cart hooks inside the provider.\n *\n * Render every cart hook inside the provider. On mount, the provider sends cart requests to `/api/cart` and connects the store. On unmount, the provider destroys the store. The provider creates its store from the first initial data and ignores later changes.\n *\n * @example\n * ```tsx\n * // In your root layout\n * <CartProvider initialData={{ cart: loaderData.cart }}>\n * <App />\n * </CartProvider>\n * ```\n * @param props - The initial cart data and the content that uses the cart hooks.\n * @returns A context provider that shares the cart store with its children.\n * @publicDocs\n */\nexport function CartProvider({\n initialData,\n children,\n}: {\n initialData?: CartInitialData;\n children?: ReactNode;\n}) {\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- store is created once with the initial server data\n const store = useMemo(() => createCartStore({ initialData }), []);\n\n useEffect(() => {\n configureCoreCartEndpoint(cartEndpoint);\n store.connect();\n return () => {\n store.destroy();\n };\n }, [store]);\n\n return <CartContext.Provider value={store}>{children}</CartContext.Provider>;\n}\n\n/**\n * Returns the slice of cart state that the selector picks.\n *\n * The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value.\n *\n * @example\n * ```tsx\n * // Select cart lines\n * const lines = useCart((state) => state.data.lines.nodes);\n *\n * // Select pending state for a specific line\n * const isPending = useCart((state) => state.pending.lines.has(lineId));\n *\n * // Custom equality to avoid re-renders on unchanged totals\n * const total = useCart(\n * (state) => state.data.cost.totalAmount,\n * (a, b) => a.amount === b.amount,\n * );\n * ```\n * @publicDocs\n */\nexport function useCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const store = useCartStore();\n return useCartSelector(store, selector, isEqual) as S;\n}\n\n/**\n * Returns the cart action that reloads the cart after a cart change outside cart forms.\n *\n * Call `refresh()` after a server-side cart change that skips cart forms, such as a server action that creates the cart.\n *\n * @returns The `refresh()` action.\n *\n * @example\n * ```tsx\n * const { refresh } = useCartActions();\n *\n * async function handleServerAction() {\n * await createCartOnServer();\n * refresh(); // re-fetch the cart\n * }\n * ```\n * @publicDocs\n */\nexport function useCartActions(): CartActions {\n const store = useCartStore(\"useCartActions\");\n\n return useMemo(() => ({ refresh: store.refresh }), [store]);\n}\n\n/**\n * Publishes cart analytics events when the customer's cart changes.\n *\n * Call the hook once near the root of your app, inside `CartProvider`. The hook starts tracking on mount and stops on unmount. The hook publishes `cart_updated`, `product_added_to_cart`, and `product_removed_from_cart` events.\n *\n * The hook throws outside `CartProvider`, and when the Shopify analytics bus isn't available. Render `ShopifyScripts` before the hook runs.\n *\n * @returns Nothing. The hook tracks cart analytics for the lifetime of the calling component.\n *\n * @example\n * ```tsx\n * function App() {\n * useCartAnalytics();\n * return <Layout />;\n * }\n * ```\n * @publicDocs\n */\nexport function useCartAnalytics(): void {\n const store = useCartStore(\"useCartAnalytics\");\n\n useEffect(() => trackCartAnalytics(store), [store]);\n}\n\n/**\n * Returns a selected slice of cart state, or `undefined` when the component renders outside the cart provider.\n *\n * Use the hook in a component that also renders above the provider, such as a header cart badge on an error page.\n * Wherever the provider always exists, use `useCart`, which throws when the provider is missing.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value, or `undefined` outside the provider.\n *\n * @example\n * ```tsx\n * function CartBadge() {\n * const count = useOptionalCart((state) => state.data.totalQuantity);\n * if (count === undefined) return null;\n * return <span>Cart ({count})</span>;\n * }\n * ```\n * @publicDocs\n */\nexport function useOptionalCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S | undefined {\n const store = useOptionalCartStore();\n if (!store) return undefined;\n return useCartSelector(store, selector, isEqual);\n}\n\nfunction useCartSelector<TData extends CartData = CartData, S = unknown>(\n store: CartStore,\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const cachedRef = useRef<{ state: unknown; selector: typeof selector; value: S } | null>(null);\n\n const getSnapshot = () => {\n const state = store.getState() as CartState<TData>;\n\n if (\n cachedRef.current &&\n cachedRef.current.state === state &&\n cachedRef.current.selector === selector\n ) {\n return cachedRef.current.value;\n }\n\n const next = selector(state);\n\n if (cachedRef.current && isEqual?.(cachedRef.current.value, next)) {\n cachedRef.current = { state, selector, value: cachedRef.current.value };\n return cachedRef.current.value;\n }\n\n cachedRef.current = { state, selector, value: next };\n return next;\n };\n\n return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * Returns form props and a field register function for building cart forms.\n *\n * Spread `formProps()` on the form. The form posts to the cart endpoint. On submit, the form props stop the browser's navigation and send the form through the cart store.\n * The submit handler ignores a failed cart change. Read failures from the cart state's `errors`.\n * To skip the cart submission, call `event.preventDefault()` in a `beforeSubmit` callback. The `afterSubmit` callback runs as soon as the cart change starts, before the server responds.\n * The register function returns the HTML attributes for each cart field and action.\n *\n * Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled.\n *\n * @returns The form props function and the register function.\n *\n * @example\n * ```tsx\n * function LineItem({ line }) {\n * const { formProps, register } = useCartForm();\n *\n * return (\n * <form {...formProps()}>\n * <input {...register(\"lineId\", { value: line.id })} />\n * <input {...register(\"quantity\", { value: line.quantity, interactive: true })} />\n * <button {...register(\"set\")} />\n * <button {...register(\"increase\")}>+</button>\n * <button {...register(\"decrease\")}>−</button>\n * <button {...register(\"remove\")}>Remove</button>\n * </form>\n * );\n * }\n * ```\n * @publicDocs\n */\nexport function useCartForm(): CartFormBindings {\n const store = useCartStore(\"useCartForm\");\n const coreRegister = useMemo(() => createCartFormRegister(), []);\n\n const register = useMemo(() => {\n type Register = typeof coreRegister;\n const wrapped = ((...args: Parameters<Register>) => {\n const result = (coreRegister as Function)(...args);\n const [field, opts] = args as [string, { interactive?: boolean }?];\n\n if (field === \"quantity\" && opts?.interactive) {\n let cleanup: (() => void) | null = null;\n const ref: RefCallback<HTMLInputElement> = (el) => {\n cleanup?.();\n cleanup = null;\n if (el) {\n const form = el.closest(\"form\");\n if (form) cleanup = attachQuantityInput(el, form);\n }\n };\n const { value: _, ...rest } = result;\n return { ...rest, defaultValue: result.value, ref };\n }\n\n return result;\n }) as Register;\n return wrapped;\n }, [coreRegister]);\n\n const formProps = (opts?: CartFormPropsOptions): FormHTMLAttributes<HTMLFormElement> => ({\n onSubmit: (e: SubmitEvent<HTMLFormElement>) => {\n opts?.beforeSubmit?.(e);\n if (e.defaultPrevented) return;\n e.preventDefault();\n store.handleFormSubmit(e.nativeEvent).catch(() => {});\n opts?.afterSubmit?.(e);\n },\n method: \"post\",\n action: cartEndpoint,\n });\n\n return { formProps, register };\n}\n"],"mappings":";;;;;;;;;;AA8BA,IAAI,eAAe;AAEnB,MAAM,cAAc,cAAgC,KAAK;AAOzD,SAAgB,kBAA0B;AACxC,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;AAmGT,SAAgB,uBAEd;CAGA,SAAS,kBAAkB,EAAE,aAAa,YAA2C;AACnF,SACE,oBAAC,cAAD;GAA2B;GACxB;GACY;;CAInB,SAAS,aACP,UACA,SACG;AACH,SAAO,SAAsB,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAGtF,SAAS,qBACP,UACA,SACe;AACf,SAAO,iBAA8B,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAG9F,SAAS,gBACP,UACA,SACG;EACH,MAAM,eAAe,SAAS,UAAU,MAAM,aAAa;AAC3D,MAAI,aAAc,OAAM;AACxB,SAAO,QAAQ,UAAU,QAAQ;;AAGnC,QAAO;EACL,cAAc;EACd,SAAS;EACT;EACA,iBAAiB;EACjB;EACA;EACD;;AAGH,SAAgB,aAAa,WAAW,WAAsB;CAC5D,MAAM,QAAQ,WAAW,YAAY;AACrC,KAAI,CAAC,MAAO,OAAM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E;AACjE,aAAU,UAAU;IAAE;IAAO;IAAU,OAAO,UAAU,QAAQ;IAAO;AACvE,UAAO,UAAU,QAAQ;;AAG3B,YAAU,UAAU;GAAE;GAAO;GAAU,OAAO;GAAM;AACpD,SAAO;;AAGT,QAAO,qBAAqB,MAAM,WAAW,aAAa,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCxE,SAAgB,cAAgC;CAC9C,MAAM,QAAQ,aAAa,cAAc;CACzC,MAAM,eAAe,cAAc,wBAAwB,EAAE,EAAE,CAAC;CAEhE,MAAM,WAAW,cAAc;EAE7B,MAAM,YAAY,GAAG,SAA+B;GAClD,MAAM,SAAU,aAA0B,GAAG,KAAK;GAClD,MAAM,CAAC,OAAO,QAAQ;AAEtB,OAAI,UAAU,cAAc,MAAM,aAAa;IAC7C,IAAI,UAA+B;IACnC,MAAM,OAAsC,OAAO;AACjD,gBAAW;AACX,eAAU;AACV,SAAI,IAAI;MACN,MAAM,OAAO,GAAG,QAAQ,OAAO;AAC/B,UAAI,KAAM,WAAU,oBAAoB,IAAI,KAAK;;;IAGrD,MAAM,EAAE,OAAO,GAAG,GAAG,SAAS;AAC9B,WAAO;KAAE,GAAG;KAAM,cAAc,OAAO;KAAO;KAAK;;AAGrD,UAAO;;AAET,SAAO;IACN,CAAC,aAAa,CAAC;CAElB,MAAM,aAAa,UAAsE;EACvF,WAAW,MAAoC;AAC7C,SAAM,eAAe,EAAE;AACvB,OAAI,EAAE,iBAAkB;AACxB,KAAE,gBAAgB;AAClB,SAAM,iBAAiB,EAAE,YAAY,CAAC,YAAY,GAAG;AACrD,SAAM,cAAc,EAAE;;EAExB,QAAQ;EACR,QAAQ;EACT;AAED,QAAO;EAAE;EAAW;EAAU"}
1
+ {"version":3,"file":"cart.mjs","names":[],"sources":["../../src/react/cart.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n type FormHTMLAttributes,\n type ReactNode,\n type RefCallback,\n type SubmitEvent,\n} from \"react\";\n\nimport { trackCartAnalytics } from \"../core/analytics/cart-tracker\";\nimport { attachQuantityInput } from \"../core/cart/attach-quantity-input\";\nimport {\n configureCartEndpoint as configureCoreCartEndpoint,\n createCartStore,\n type CreateCartStoreOptions,\n type CartActions,\n type CartStore,\n} from \"../core/cart/cart\";\nimport { createCartFormRegister, type CartFormRegister } from \"../core/cart/form\";\nimport type { CartDataFromHandlers } from \"../core/cart/server-handlers\";\nimport { type CartData, type CartState } from \"../core/cart/state\";\n\nconst DEFAULT_CART_ENDPOINT = \"/api/cart\";\n\nlet cartEndpoint = DEFAULT_CART_ENDPOINT;\n\ninterface CartContextValue {\n store: CartStore;\n hydrationSnapshot: CartState;\n}\n\nconst CartContext = createContext<CartContextValue | null>(null);\n\nexport function configureCartEndpoint(endpoint: string): void {\n cartEndpoint = endpoint;\n configureCoreCartEndpoint(endpoint);\n}\n\nexport function getCartEndpoint(): string {\n return cartEndpoint;\n}\n\n/**\n * Props for the cart provider that `createCartComponents` returns.\n */\ntype TypedCartProviderProps<TData extends CartData> = {\n /**\n * The `data` property of the cart GET handler's result, or a promise of that data. Without initial data, the store loads the cart from `/api/cart` after the provider mounts, and the server-rendered page shows an empty cart. The provider creates its store from the first value and ignores later changes.\n */\n initialData?: CartInitialData<TData>;\n /** Content that can read the cart through the cart hooks. */\n children?: ReactNode;\n};\n\ntype CartInitialData<TData extends CartData = CartData> =\n CreateCartStoreOptions<TData>[\"initialData\"];\n\nexport type { CartActions };\n\n/** A hook that returns the slice of cart state that your selector picks. */\ntype CartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S;\n\n/** A hook that returns the slice of cart state that your selector picks, or `undefined` outside the cart provider. */\ntype OptionalCartStateHook<TData extends CartData> =\n /**\n * @param selector - Picks the value to return from the cart state.\n * @param isEqual - Compares the previous and next selected values. Return `true` to skip the re-render. Without the function, the hook compares the values by reference.\n * @returns The selected value, or `undefined` outside the cart provider.\n */\n <S>(selector: (state: CartState<TData>) => S, isEqual?: (a: S, b: S) => boolean) => S | undefined;\n\n/** Callbacks that run around a cart form submission. */\ninterface CartFormPropsOptions {\n /** Runs before the cart store handles the submission. Call `event.preventDefault()` to skip the cart submission. */\n beforeSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n /** Runs as soon as the cart change starts, before the server responds. */\n afterSubmit?: (e: SubmitEvent<HTMLFormElement>) => void;\n}\n\n/** The form props function and the register function for a cart form. */\ninterface CartFormBindings {\n /** Returns the `method`, `action`, and `onSubmit` props to spread on the form. The form posts to the cart endpoint, and the cart store handles each submission. */\n formProps: (opts?: CartFormPropsOptions) => FormHTMLAttributes<HTMLFormElement>;\n /** Returns the attributes for a cart field or action button. Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled. */\n register: CartFormRegister;\n}\n\n/**\n * The cart provider and hooks that `createCartComponents` returns, typed with the custom cart fields from your cart server handlers.\n */\ntype TypedCartComponents<TData extends CartData> = {\n /** Creates the cart store and shares the store with the cart hooks inside the provider. The provider connects the store on mount and destroys the store on unmount. */\n CartProvider: (props: TypedCartProviderProps<TData>) => ReactNode;\n /**\n * Returns the slice of cart state that the selector picks. The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n */\n useCart: CartStateHook<TData>;\n /** Suspends while the full cart loads, then returns the slice of cart state that the selector picks. Wrap the component in a `Suspense` boundary. */\n useSuspenseCart: CartStateHook<TData>;\n /**\n * Returns the slice of cart state that the selector picks, or `undefined` outside the provider. Use the hook in a component that also renders above the provider, such as a cart badge on an error page.\n */\n useOptionalCart: OptionalCartStateHook<TData>;\n /** Returns the `refresh()` action. Call `refresh()` after a server-side cart change that skips cart forms. */\n useCartActions: typeof useCartActions;\n /** Returns form props and a register function for cart forms. */\n useCartForm: typeof useCartForm;\n};\n\n/**\n * Returns a cart provider and cart hooks typed to the cart fragment in your cart server handlers.\n * Pass `typeof cartServerHandlers` as the `THandlers` type argument. Every hook's cart state then includes your custom cart fields.\n *\n * On mount, the provider sends cart requests to `/api/cart` and connects the store. Every hook except `useOptionalCart` throws when you call it outside the provider.\n *\n * @returns The cart provider, the cart state hooks, and the cart actions and form hooks.\n *\n * @example\n * ```tsx\n * import type { cartServerHandlers } from \"./server/cart.server\";\n *\n * const {\n * CartProvider,\n * useCart,\n * useSuspenseCart,\n * useOptionalCart,\n * useCartActions,\n * useCartForm,\n * } = createCartComponents<typeof cartServerHandlers>();\n * ```\n * @publicDocs\n */\nexport function createCartComponents<THandlers>(): TypedCartComponents<\n CartDataFromHandlers<THandlers>\n> {\n type TData = CartDataFromHandlers<THandlers>;\n\n function TypedCartProvider({ initialData, children }: TypedCartProviderProps<TData>) {\n return (\n <CartProvider initialData={initialData as CartInitialData | undefined}>\n {children}\n </CartProvider>\n );\n }\n\n function useTypedCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n return useCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useTypedOptionalCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S | undefined {\n return useOptionalCart<CartData, S>((state) => selector(state as CartState<TData>), isEqual);\n }\n\n function useSuspenseCart<S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n ): S {\n return useSuspenseCartSelector(selector, isEqual);\n }\n\n return {\n CartProvider: TypedCartProvider,\n useCart: useTypedCart,\n useSuspenseCart,\n useOptionalCart: useTypedOptionalCart,\n useCartActions,\n useCartForm,\n } as const;\n}\n\nexport function useCartStore(hookName = \"useCart\"): CartStore {\n return useCartContext(hookName).store;\n}\n\nfunction useCartContext(hookName = \"useCart\"): CartContextValue {\n const context = useContext(CartContext);\n if (!context) throw new Error(`${hookName} must be used inside <CartProvider>.`);\n return context;\n}\n\nfunction useOptionalCartContext(): CartContextValue | null {\n return useContext(CartContext);\n}\n\n/**\n * Creates a cart store and shares the store with the cart hooks inside the provider.\n *\n * Render every cart hook inside the provider. On mount, the provider sends cart requests to `/api/cart` and connects the store. On unmount, the provider destroys the store. The provider creates its store from the first initial data and ignores later changes.\n *\n * @example\n * ```tsx\n * // In your root layout\n * <CartProvider initialData={{ cart: loaderData.cart }}>\n * <App />\n * </CartProvider>\n * ```\n * @param props - The initial cart data and the content that uses the cart hooks.\n * @returns A context provider that shares the cart store with its children.\n * @publicDocs\n */\nexport function CartProvider({\n initialData,\n children,\n}: {\n initialData?: CartInitialData;\n children?: ReactNode;\n}) {\n const context = useMemo(() => {\n const store = createCartStore({ initialData });\n // Plain consumers must hydrate from the state used for SSR, even if the live store settles first.\n return { store, hydrationSnapshot: store.getState() };\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- provider initialData seeds one store for its lifetime\n }, []);\n const { store } = context;\n\n useEffect(() => {\n configureCoreCartEndpoint(cartEndpoint);\n store.connect();\n return () => {\n store.destroy();\n };\n }, [store]);\n\n return <CartContext.Provider value={context}>{children}</CartContext.Provider>;\n}\n\n/**\n * Returns the slice of cart state that the selector picks.\n *\n * The component re-renders when the selected value changes by reference, or when your `isEqual` function reports a change. A selector that returns the full state re-renders on every cart update.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value.\n *\n * @example\n * ```tsx\n * // Select cart lines\n * const lines = useCart((state) => state.data.lines.nodes);\n *\n * // Select pending state for a specific line\n * const isPending = useCart((state) => state.pending.lines.has(lineId));\n *\n * // Custom equality to avoid re-renders on unchanged totals\n * const total = useCart(\n * (state) => state.data.cost.totalAmount,\n * (a, b) => a.amount === b.amount,\n * );\n * ```\n * @publicDocs\n */\nexport function useCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const { store, hydrationSnapshot } = useCartContext();\n return useCartSelector(store, hydrationSnapshot, selector, isEqual) as S;\n}\n\n/**\n * Returns the cart action that reloads the cart after a cart change outside cart forms.\n *\n * Call `refresh()` after a server-side cart change that skips cart forms, such as a server action that creates the cart.\n *\n * @returns The `refresh()` action.\n *\n * @example\n * ```tsx\n * const { refresh } = useCartActions();\n *\n * async function handleServerAction() {\n * await createCartOnServer();\n * refresh(); // re-fetch the cart\n * }\n * ```\n * @publicDocs\n */\nexport function useCartActions(): CartActions {\n const store = useCartStore(\"useCartActions\");\n\n return useMemo(() => ({ refresh: store.refresh }), [store]);\n}\n\n/**\n * Publishes cart analytics events when the customer's cart changes.\n *\n * Call the hook once near the root of your app, inside `CartProvider`. The hook starts tracking on mount and stops on unmount. The hook publishes `cart_updated`, `product_added_to_cart`, and `product_removed_from_cart` events.\n *\n * The hook throws outside `CartProvider`, and when the Shopify analytics bus isn't available. Render `ShopifyScripts` before the hook runs.\n *\n * @returns Nothing. The hook tracks cart analytics for the lifetime of the calling component.\n *\n * @example\n * ```tsx\n * function App() {\n * useCartAnalytics();\n * return <Layout />;\n * }\n * ```\n * @publicDocs\n */\nexport function useCartAnalytics(): void {\n const store = useCartStore(\"useCartAnalytics\");\n\n useEffect(() => trackCartAnalytics(store), [store]);\n}\n\n/**\n * Returns a selected slice of cart state, or `undefined` when the component renders outside the cart provider.\n *\n * Use the hook in a component that also renders above the provider, such as a header cart badge on an error page.\n * Wherever the provider always exists, use `useCart`, which throws when the provider is missing.\n *\n * @param selector The function that picks a value from the cart state.\n * @param isEqual The function that compares the previous and next selected values. Return `true` to skip the re-render.\n * @returns The selected value, or `undefined` outside the provider.\n *\n * @example\n * ```tsx\n * function CartBadge() {\n * const count = useOptionalCart((state) => state.data.totalQuantity);\n * if (count === undefined) return null;\n * return <span>Cart ({count})</span>;\n * }\n * ```\n * @publicDocs\n */\nexport function useOptionalCart<TData extends CartData = CartData, S = unknown>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S | undefined {\n const context = useOptionalCartContext();\n if (!context) return undefined;\n return useCartSelector(context.store, context.hydrationSnapshot, selector, isEqual);\n}\n\nfunction useCartSelector<TData extends CartData = CartData, S = unknown>(\n store: CartStore,\n hydrationSnapshot: CartState,\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const liveCacheRef = useRef<SelectorCache<S> | null>(null);\n const hydrationCacheRef = useRef<SelectorCache<S> | null>(null);\n\n const getSnapshot = () =>\n selectCartSnapshot(store.getState() as CartState<TData>, selector, isEqual, liveCacheRef);\n const getServerSnapshot = () =>\n selectCartSnapshot(hydrationSnapshot as CartState<TData>, selector, isEqual, hydrationCacheRef);\n\n return useSyncExternalStore(store.subscribe, getSnapshot, getServerSnapshot);\n}\n\ninterface SelectorCache<S> {\n state: unknown;\n selector: unknown;\n value: S;\n}\n\nfunction selectCartSnapshot<TData extends CartData, S>(\n state: CartState<TData>,\n selector: (state: CartState<TData>) => S,\n isEqual: ((a: S, b: S) => boolean) | undefined,\n cacheRef: { current: SelectorCache<S> | null },\n): S {\n if (cacheRef.current?.state === state && cacheRef.current.selector === selector) {\n return cacheRef.current.value;\n }\n\n const next = selector(state);\n\n if (cacheRef.current && isEqual?.(cacheRef.current.value, next)) {\n cacheRef.current = { state, selector, value: cacheRef.current.value };\n return cacheRef.current.value;\n }\n\n cacheRef.current = { state, selector, value: next };\n return next;\n}\n\ntype SuspenseSnapshot<S> =\n | { status: \"pending\"; promise: PromiseLike<void> }\n | { status: \"ready\"; value: S };\n\ninterface SuspenseSelectorCache<S> {\n state: unknown;\n selector: unknown;\n snapshot: SuspenseSnapshot<S>;\n}\n\nfunction useSuspenseCartSelector<TData extends CartData, S>(\n selector: (state: CartState<TData>) => S,\n isEqual?: (a: S, b: S) => boolean,\n): S {\n const { store } = useCartContext();\n const cacheRef = useRef<SuspenseSelectorCache<S> | null>(null);\n\n // Suspense retries must read live readiness and data; the hydration snapshot would freeze the fallback.\n const getSnapshot = () => {\n const state = store.getState() as CartState<TData>;\n\n if (cacheRef.current?.state === state && cacheRef.current.selector === selector) {\n return cacheRef.current.snapshot;\n }\n\n if (state.readyPromise) {\n const snapshot: SuspenseSnapshot<S> = { status: \"pending\", promise: state.readyPromise };\n cacheRef.current = { state, selector, snapshot };\n return snapshot;\n }\n\n const value = selector(state);\n const previous = cacheRef.current?.snapshot;\n\n if (previous?.status === \"ready\" && isEqual?.(previous.value, value)) {\n cacheRef.current = { state, selector, snapshot: previous };\n return previous;\n }\n\n const snapshot: SuspenseSnapshot<S> = { status: \"ready\", value };\n cacheRef.current = { state, selector, snapshot };\n return snapshot;\n };\n\n const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n if (snapshot.status === \"pending\") throw snapshot.promise;\n return snapshot.value;\n}\n\n/**\n * Returns form props and a field register function for building cart forms.\n *\n * Spread `formProps()` on the form. The form posts to the cart endpoint. On submit, the form props stop the browser's navigation and send the form through the cart store.\n * The submit handler ignores a failed cart change. Read failures from the cart state's `errors`.\n * To skip the cart submission, call `event.preventDefault()` in a `beforeSubmit` callback. The `afterSubmit` callback runs as soon as the cart change starts, before the server responds.\n * The register function returns the HTML attributes for each cart field and action.\n *\n * Register the quantity field with `interactive: true` to submit the form when the quantity changes. The interactive input takes the quantity as a default value and stays uncontrolled.\n *\n * @returns The form props function and the register function.\n *\n * @example\n * ```tsx\n * function LineItem({ line }) {\n * const { formProps, register } = useCartForm();\n *\n * return (\n * <form {...formProps()}>\n * <input {...register(\"lineId\", { value: line.id })} />\n * <input {...register(\"quantity\", { value: line.quantity, interactive: true })} />\n * <button {...register(\"set\")} />\n * <button {...register(\"increase\")}>+</button>\n * <button {...register(\"decrease\")}>−</button>\n * <button {...register(\"remove\")}>Remove</button>\n * </form>\n * );\n * }\n * ```\n * @publicDocs\n */\nexport function useCartForm(): CartFormBindings {\n const store = useCartStore(\"useCartForm\");\n const coreRegister = useMemo(() => createCartFormRegister(), []);\n\n const register = useMemo(() => {\n type Register = typeof coreRegister;\n const wrapped = ((...args: Parameters<Register>) => {\n const result = (coreRegister as Function)(...args);\n const [field, opts] = args as [string, { interactive?: boolean }?];\n\n if (field === \"quantity\" && opts?.interactive) {\n let cleanup: (() => void) | null = null;\n const ref: RefCallback<HTMLInputElement> = (el) => {\n cleanup?.();\n cleanup = null;\n if (el) {\n const form = el.closest(\"form\");\n if (form) cleanup = attachQuantityInput(el, form);\n }\n };\n const { value: _, ...rest } = result;\n return { ...rest, defaultValue: result.value, ref };\n }\n\n return result;\n }) as Register;\n return wrapped;\n }, [coreRegister]);\n\n const formProps = (opts?: CartFormPropsOptions): FormHTMLAttributes<HTMLFormElement> => ({\n onSubmit: (e: SubmitEvent<HTMLFormElement>) => {\n opts?.beforeSubmit?.(e);\n if (e.defaultPrevented) return;\n e.preventDefault();\n store.handleFormSubmit(e.nativeEvent).catch(() => {});\n opts?.afterSubmit?.(e);\n },\n method: \"post\",\n action: cartEndpoint,\n });\n\n return { formProps, register };\n}\n"],"mappings":";;;;;;;;;;AA8BA,IAAI,eAAe;AAOnB,MAAM,cAAc,cAAuC,KAAK;AAOhE,SAAgB,kBAA0B;AACxC,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;AAmGT,SAAgB,uBAEd;CAGA,SAAS,kBAAkB,EAAE,aAAa,YAA2C;AACnF,SACE,oBAAC,cAAD;GAA2B;GACxB;GACY;;CAInB,SAAS,aACP,UACA,SACG;AACH,SAAO,SAAsB,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAGtF,SAAS,qBACP,UACA,SACe;AACf,SAAO,iBAA8B,UAAU,SAAS,MAA0B,EAAE,QAAQ;;CAG9F,SAAS,gBACP,UACA,SACG;AACH,SAAO,wBAAwB,UAAU,QAAQ;;AAGnD,QAAO;EACL,cAAc;EACd,SAAS;EACT;EACA,iBAAiB;EACjB;EACA;EACD;;AAGH,S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S;GAAO;AAChE,WAAS,UAAU;GAAE;GAAO;GAAU;GAAU;AAChD,SAAO;;CAGT,MAAM,WAAW,qBAAqB,MAAM,WAAW,aAAa,YAAY;AAChF,KAAI,SAAS,WAAW,UAAW,OAAM,SAAS;AAClD,QAAO,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkClB,SAAgB,cAAgC;CAC9C,MAAM,QAAQ,aAAa,cAAc;CACzC,MAAM,eAAe,cAAc,wBAAwB,EAAE,EAAE,CAAC;CAEhE,MAAM,WAAW,cAAc;EAE7B,MAAM,YAAY,GAAG,SAA+B;GAClD,MAAM,SAAU,aAA0B,GAAG,KAAK;GAClD,MAAM,CAAC,OAAO,QAAQ;AAEtB,OAAI,UAAU,cAAc,MAAM,aAAa;IAC7C,IAAI,UAA+B;IACnC,MAAM,OAAsC,OAAO;AACjD,gBAAW;AACX,eAAU;AACV,SAAI,IAAI;MACN,MAAM,OAAO,GAAG,QAAQ,OAAO;AAC/B,UAAI,KAAM,WAAU,oBAAoB,IAAI,KAAK;;;IAGrD,MAAM,EAAE,OAAO,GAAG,GAAG,SAAS;AAC9B,WAAO;KAAE,GAAG;KAAM,cAAc,OAAO;KAAO;KAAK;;AAGrD,UAAO;;AAET,SAAO;IACN,CAAC,aAAa,CAAC;CAElB,MAAM,aAAa,UAAsE;EACvF,WAAW,MAAoC;AAC7C,SAAM,eAAe,EAAE;AACvB,OAAI,EAAE,iBAAkB;AACxB,KAAE,gBAAgB;AAClB,SAAM,iBAAiB,EAAE,YAAY,CAAC,YAAY,GAAG;AACrD,SAAM,cAAc,EAAE;;EAExB,QAAQ;EACR,QAAQ;EACT;AAED,QAAO;EAAE;EAAW;EAAU"}
@@ -1,7 +1,7 @@
1
1
  import { ShopifyStandardActions } from "../vendor/standard-actions.mjs";
2
2
  import { CartActions } from "../core/cart/cart.mjs";
3
3
  import { ShopifyGlobal } from "../globals.mjs";
4
- import { QuantityInputAttributes, SetButtonAttributes } from "../core/cart/form.mjs";
4
+ import { QuantityInputAttributes, RemoveButtonAttributes, SetButtonAttributes } from "../core/cart/form.mjs";
5
5
  import { CollectionActions, CollectionData } from "../core/collection/collection.mjs";
6
6
  import { ValidProductSelectionResult } from "../core/product/product-form.mjs";
7
7
  import { ProductAddToCartProps, ProductAttributeDefaultValueProps, ProductAttributeValueProps, ProductFormRegister, ProductMerchandiseIdProps, ProductOptionValueProps, ProductQuantityDefaultProps, ProductQuantityProps } from "../core/product/form.mjs";
@@ -12,4 +12,4 @@ import { PredictiveSearchFormPropsOptions, PredictiveSearchFormRegister, Predict
12
12
  import { ProductProviderProps, UseProductFormOptions, UseProductFormResult, UseProductResult, createProductComponents, useProductForm } from "./product.mjs";
13
13
  import { ShopPayButton, ShopPayButtonProps } from "./shop-pay.mjs";
14
14
  import { ShopifyScripts, ShopifyScriptsProps } from "./shopify-scripts.mjs";
15
- export { type CartActions, type CollectionActions, type CollectionData, CollectionProvider, type CollectionProviderProps, type PredictiveSearchActions, type PredictiveSearchFormPropsOptions, type PredictiveSearchFormRegister, type PredictiveSearchFormResult, PredictiveSearchProvider, type PredictiveSearchProviderProps, type PredictiveSearchQueryInputPropsOptions, type ProductAddToCartProps, type ProductAttributeDefaultValueProps, type ProductAttributeValueProps, type ProductFormRegister, type ProductMerchandiseIdProps, type ProductOptionValueProps, type ProductProviderProps, type ProductQuantityDefaultProps, type ProductQuantityProps, type QuantityInputAttributes, type SetButtonAttributes, ShopPayButton, type ShopPayButtonProps, type ShopifyGlobal, ShopifyScripts, type ShopifyScriptsProps, type ShopifyStandardActions, type UseProductFormOptions, type UseProductFormResult, type UseProductResult, type ValidProductSelectionResult, createCartComponents, createProductComponents, useCartAnalytics, useCollection, useCollectionActions, useCollectionForm, usePredictiveSearch, usePredictiveSearchActions, usePredictiveSearchForm, useProductForm };
15
+ export { type CartActions, type CollectionActions, type CollectionData, CollectionProvider, type CollectionProviderProps, type PredictiveSearchActions, type PredictiveSearchFormPropsOptions, type PredictiveSearchFormRegister, type PredictiveSearchFormResult, PredictiveSearchProvider, type PredictiveSearchProviderProps, type PredictiveSearchQueryInputPropsOptions, type ProductAddToCartProps, type ProductAttributeDefaultValueProps, type ProductAttributeValueProps, type ProductFormRegister, type ProductMerchandiseIdProps, type ProductOptionValueProps, type ProductProviderProps, type ProductQuantityDefaultProps, type ProductQuantityProps, type QuantityInputAttributes, type RemoveButtonAttributes, type SetButtonAttributes, ShopPayButton, type ShopPayButtonProps, type ShopifyGlobal, ShopifyScripts, type ShopifyScriptsProps, type ShopifyStandardActions, type UseProductFormOptions, type UseProductFormResult, type UseProductResult, type ValidProductSelectionResult, createCartComponents, createProductComponents, useCartAnalytics, useCollection, useCollectionActions, useCollectionForm, usePredictiveSearch, usePredictiveSearchActions, usePredictiveSearchForm, useProductForm };
@@ -1,2 +1,12 @@
1
1
  import { LOCAL_HTTPS_DEFAULTS, LocalHttpsDevServerConfig, LocalHttpsOptions, LocalHttpsPlugin, ProvisionLocalHttpsOptions, localHttps, provisionLocalHttps } from "./local-https.mjs";
2
- export { LOCAL_HTTPS_DEFAULTS, LocalHttpsDevServerConfig, LocalHttpsOptions, LocalHttpsPlugin, ProvisionLocalHttpsOptions, localHttps, provisionLocalHttps };
2
+
3
+ //#region src/vite/index.d.ts
4
+ /**
5
+ * Projects built on 2026.4 import this name from their `vite.config`. Without it, a project whose `^2026.4.0` range resolved to 2026.10 fails at ESM link time with "does not provide an export named 'hydrogen'" before any Hydrogen code can explain the collision. This export turns that failure into a message with the fix.
6
+ *
7
+ * @deprecated Removed in `@shopify/hydrogen` 2026.10. Pin `@shopify/hydrogen` to `~2026.4.0` to keep using the `hydrogen()` Vite plugin.
8
+ */
9
+ declare function hydrogen(): never;
10
+ //#endregion
11
+ export { LOCAL_HTTPS_DEFAULTS, LocalHttpsDevServerConfig, LocalHttpsOptions, LocalHttpsPlugin, ProvisionLocalHttpsOptions, hydrogen, localHttps, provisionLocalHttps };
12
+ //# sourceMappingURL=index.d.mts.map
@@ -1,3 +1,23 @@
1
1
  import { LOCAL_HTTPS_DEFAULTS, localHttps, provisionLocalHttps } from "./local-https.mjs";
2
2
 
3
- export { LOCAL_HTTPS_DEFAULTS, localHttps, provisionLocalHttps };
3
+ //#region src/vite/index.ts
4
+ const HYDROGEN_MIGRATION_GUIDE_URL = "https://shopify.dev/docs/storefronts/hydrogen/migrate";
5
+ /**
6
+ * Projects built on 2026.4 import this name from their `vite.config`. Without it, a project whose `^2026.4.0` range resolved to 2026.10 fails at ESM link time with "does not provide an export named 'hydrogen'" before any Hydrogen code can explain the collision. This export turns that failure into a message with the fix.
7
+ *
8
+ * @deprecated Removed in `@shopify/hydrogen` 2026.10. Pin `@shopify/hydrogen` to `~2026.4.0` to keep using the `hydrogen()` Vite plugin.
9
+ */
10
+ function hydrogen() {
11
+ throw new Error([
12
+ `This project is not compatible with @shopify/hydrogen 2026.10.3.`,
13
+ "Its vite.config imports `hydrogen()` from `@shopify/hydrogen/vite`, which 2026.10 and later no longer provide. A caret range such as `^2026.4.0` resolves to 2026.10.",
14
+ "",
15
+ "To stay on 2026.4, pin \"@shopify/hydrogen\" to \"~2026.4.0\" in package.json and reinstall.",
16
+ "",
17
+ `To move to 2026.10, follow the migration guide: ${HYDROGEN_MIGRATION_GUIDE_URL}`
18
+ ].join("\n"));
19
+ }
20
+
21
+ //#endregion
22
+ export { LOCAL_HTTPS_DEFAULTS, hydrogen, localHttps, provisionLocalHttps };
23
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/vite/index.ts"],"sourcesContent":["export * from \"./local-https\";\n\nconst HYDROGEN_MIGRATION_GUIDE_URL = \"https://shopify.dev/docs/storefronts/hydrogen/migrate\";\n\n/**\n * Projects built on 2026.4 import this name from their `vite.config`. Without it, a project whose `^2026.4.0` range resolved to 2026.10 fails at ESM link time with \"does not provide an export named 'hydrogen'\" before any Hydrogen code can explain the collision. This export turns that failure into a message with the fix.\n *\n * @deprecated Removed in `@shopify/hydrogen` 2026.10. Pin `@shopify/hydrogen` to `~2026.4.0` to keep using the `hydrogen()` Vite plugin.\n */\nexport function hydrogen(): never {\n throw new Error(\n [\n `This project is not compatible with @shopify/hydrogen ${__HYDROGEN_VERSION__}.`,\n \"Its vite.config imports `hydrogen()` from `@shopify/hydrogen/vite`, which 2026.10 and later no longer provide. A caret range such as `^2026.4.0` resolves to 2026.10.\",\n \"\",\n 'To stay on 2026.4, pin \"@shopify/hydrogen\" to \"~2026.4.0\" in package.json and reinstall.',\n \"\",\n `To move to 2026.10, follow the migration guide: ${HYDROGEN_MIGRATION_GUIDE_URL}`,\n ].join(\"\\n\"),\n );\n}\n"],"mappings":";;;AAEA,MAAM,+BAA+B;;;;;;AAOrC,SAAgB,WAAkB;AAChC,OAAM,IAAI,MACR;EACE;EACA;EACA;EACA;EACA;EACA,mDAAmD;EACpD,CAAC,KAAK,KAAK,CACb"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopify/hydrogen",
3
- "version": "2026.10.1",
3
+ "version": "2026.10.3",
4
4
  "description": "Framework-agnostic Shopify storefront SDK and agent skills.",
5
5
  "license": "MIT",
6
6
  "author": "Shopify",
@@ -40,7 +40,8 @@
40
40
  },
41
41
  "./customer-account": {
42
42
  "types": "./dist/customer-account/index.d.mts",
43
- "import": "./dist/customer-account/index.mjs"
43
+ "import": "./dist/customer-account/index.mjs",
44
+ "default": "./dist/customer-account/index.mjs"
44
45
  },
45
46
  "./customer-account-api-types": "./dist/customer-account-api-types.d.ts",
46
47
  "./customer-account.schema.json": "./dist/customer-account.schema.json",
@@ -55,7 +56,8 @@
55
56
  },
56
57
  "./vite": {
57
58
  "types": "./dist/vite/index.d.mts",
58
- "import": "./dist/vite/index.mjs"
59
+ "import": "./dist/vite/index.mjs",
60
+ "default": "./dist/vite/index.mjs"
59
61
  },
60
62
  "./react": {
61
63
  "types": {
@@ -65,6 +67,10 @@
65
67
  "import": {
66
68
  "development": "./dist/development/react/index.mjs",
67
69
  "default": "./dist/react/index.mjs"
70
+ },
71
+ "default": {
72
+ "development": "./dist/development/react/index.mjs",
73
+ "default": "./dist/react/index.mjs"
68
74
  }
69
75
  },
70
76
  "./vue": {
@@ -75,6 +81,10 @@
75
81
  "import": {
76
82
  "development": "./dist/development/vue/index.mjs",
77
83
  "default": "./dist/vue/index.mjs"
84
+ },
85
+ "default": {
86
+ "development": "./dist/development/vue/index.mjs",
87
+ "default": "./dist/vue/index.mjs"
78
88
  }
79
89
  }
80
90
  },
@@ -19,7 +19,7 @@ Prerequisite: analytics depends on the same-origin SFAPI proxy (see `hydrogen-re
19
19
 
20
20
  ## Core Pattern
21
21
 
22
- Render Shopify runtime scripts once from the app root/document head with the same resolved market used by Storefront API requests. Use `ShopifyScripts` from your framework binding if it exports one, or `getShopifyScriptTags()` / `renderShopifyScriptTags()` from core in other framework heads. Pass the `shop` object matching the `ShopifyScriptsShop` type, and `i18n` matching the `ShopifyScriptsI18n` type and serialize them into ShopifyScripts. — declare them as constants with type annotations to keep errors located close to the source of writing. The analytics bus is created by default; pass `analytics` only for optional bus configuration such as `customData`. `customData` isn't added to events you publish; destinations read it via `getConfig().customData`. Do not pass market `country` or `language` through analytics consent config.
22
+ Render Shopify runtime scripts once from the app root/document head with the same resolved locale used by Storefront API requests (`requestContext.locale`, also `storefrontClient.locale`). Use `ShopifyScripts` from your framework binding if it exports one, or `getShopifyScriptTags()` / `renderShopifyScriptTags()` from core in other framework heads. Pass the `shop` object matching the `ShopifyScriptsShop` type, and `i18n` matching the `ShopifyScriptsI18n` type and serialize them into ShopifyScripts. — declare them as constants with type annotations to keep errors located close to the source of writing. The analytics bus is created by default; pass `analytics` only for optional bus configuration such as `customData`. `customData` isn't added to events you publish; destinations read it via `getConfig().customData`. Do not pass market `country` or `language` through analytics consent config.
23
23
 
24
24
  Read one browser-lazy singleton from the Shopify global created by `ShopifyScripts`:
25
25
 
@@ -70,7 +70,7 @@ Required product analytics fields include Shopify Product GID, ProductVariant GI
70
70
  - For third-party banners, use `consent: {mode: "custom-banner", setup}` and read [Custom consent providers](references/custom-consent.md) for readiness, synchronization, and framework integration.
71
71
  - Render ShopifyScripts before route components publish events.
72
72
  - Do not dispatch server-side analytics through this browser bus.
73
- - Keep ShopifyScripts i18n aligned with the resolved market when the storefront uses markets.
73
+ - Keep ShopifyScripts `i18n` aligned with `requestContext.locale` when the storefront serves several locales; pass the resolved locale, not the `defineShopifyI18n` definition.
74
74
 
75
75
  ## Verify
76
76