@shopify/hydrogen-react 2025.1.4 → 2025.4.1

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 (95) hide show
  1. package/dist/browser-dev/CartLineProvider.mjs.map +1 -1
  2. package/dist/browser-dev/CartProvider.mjs.map +1 -1
  3. package/dist/browser-dev/Image.mjs.map +1 -1
  4. package/dist/browser-dev/ModelViewer.mjs.map +1 -1
  5. package/dist/browser-dev/Money.mjs.map +1 -1
  6. package/dist/browser-dev/Video.mjs.map +1 -1
  7. package/dist/browser-dev/codegen.helpers.mjs.map +1 -1
  8. package/dist/browser-dev/optionValueDecoder.mjs.map +1 -1
  9. package/dist/browser-dev/packages/hydrogen-react/package.json.mjs +1 -1
  10. package/dist/browser-dev/storefront-api-constants.mjs +1 -1
  11. package/dist/browser-dev/storefront-api-constants.mjs.map +1 -1
  12. package/dist/browser-dev/useCartAPIStateMachine.mjs.map +1 -1
  13. package/dist/browser-dev/useCartActions.mjs.map +1 -1
  14. package/dist/browser-prod/CartLineProvider.mjs.map +1 -1
  15. package/dist/browser-prod/CartProvider.mjs.map +1 -1
  16. package/dist/browser-prod/Image.mjs.map +1 -1
  17. package/dist/browser-prod/ModelViewer.mjs.map +1 -1
  18. package/dist/browser-prod/Money.mjs.map +1 -1
  19. package/dist/browser-prod/Video.mjs.map +1 -1
  20. package/dist/browser-prod/codegen.helpers.mjs.map +1 -1
  21. package/dist/browser-prod/optionValueDecoder.mjs.map +1 -1
  22. package/dist/browser-prod/packages/hydrogen-react/package.json.mjs +1 -1
  23. package/dist/browser-prod/storefront-api-constants.mjs +1 -1
  24. package/dist/browser-prod/storefront-api-constants.mjs.map +1 -1
  25. package/dist/browser-prod/useCartAPIStateMachine.mjs.map +1 -1
  26. package/dist/browser-prod/useCartActions.mjs.map +1 -1
  27. package/dist/node-dev/CartLineProvider.js.map +1 -1
  28. package/dist/node-dev/CartLineProvider.mjs.map +1 -1
  29. package/dist/node-dev/CartProvider.js.map +1 -1
  30. package/dist/node-dev/CartProvider.mjs.map +1 -1
  31. package/dist/node-dev/Image.js.map +1 -1
  32. package/dist/node-dev/Image.mjs.map +1 -1
  33. package/dist/node-dev/ModelViewer.js.map +1 -1
  34. package/dist/node-dev/ModelViewer.mjs.map +1 -1
  35. package/dist/node-dev/Money.js.map +1 -1
  36. package/dist/node-dev/Money.mjs.map +1 -1
  37. package/dist/node-dev/Video.js.map +1 -1
  38. package/dist/node-dev/Video.mjs.map +1 -1
  39. package/dist/node-dev/codegen.helpers.js.map +1 -1
  40. package/dist/node-dev/codegen.helpers.mjs.map +1 -1
  41. package/dist/node-dev/optionValueDecoder.js.map +1 -1
  42. package/dist/node-dev/optionValueDecoder.mjs.map +1 -1
  43. package/dist/node-dev/packages/hydrogen-react/package.json.js +1 -1
  44. package/dist/node-dev/packages/hydrogen-react/package.json.mjs +1 -1
  45. package/dist/node-dev/storefront-api-constants.js +1 -1
  46. package/dist/node-dev/storefront-api-constants.js.map +1 -1
  47. package/dist/node-dev/storefront-api-constants.mjs +1 -1
  48. package/dist/node-dev/storefront-api-constants.mjs.map +1 -1
  49. package/dist/node-dev/useCartAPIStateMachine.js.map +1 -1
  50. package/dist/node-dev/useCartAPIStateMachine.mjs.map +1 -1
  51. package/dist/node-dev/useCartActions.js.map +1 -1
  52. package/dist/node-dev/useCartActions.mjs.map +1 -1
  53. package/dist/node-prod/CartLineProvider.js.map +1 -1
  54. package/dist/node-prod/CartLineProvider.mjs.map +1 -1
  55. package/dist/node-prod/CartProvider.js.map +1 -1
  56. package/dist/node-prod/CartProvider.mjs.map +1 -1
  57. package/dist/node-prod/Image.js.map +1 -1
  58. package/dist/node-prod/Image.mjs.map +1 -1
  59. package/dist/node-prod/ModelViewer.js.map +1 -1
  60. package/dist/node-prod/ModelViewer.mjs.map +1 -1
  61. package/dist/node-prod/Money.js.map +1 -1
  62. package/dist/node-prod/Money.mjs.map +1 -1
  63. package/dist/node-prod/Video.js.map +1 -1
  64. package/dist/node-prod/Video.mjs.map +1 -1
  65. package/dist/node-prod/codegen.helpers.js.map +1 -1
  66. package/dist/node-prod/codegen.helpers.mjs.map +1 -1
  67. package/dist/node-prod/optionValueDecoder.js.map +1 -1
  68. package/dist/node-prod/optionValueDecoder.mjs.map +1 -1
  69. package/dist/node-prod/packages/hydrogen-react/package.json.js +1 -1
  70. package/dist/node-prod/packages/hydrogen-react/package.json.mjs +1 -1
  71. package/dist/node-prod/storefront-api-constants.js +1 -1
  72. package/dist/node-prod/storefront-api-constants.js.map +1 -1
  73. package/dist/node-prod/storefront-api-constants.mjs +1 -1
  74. package/dist/node-prod/storefront-api-constants.mjs.map +1 -1
  75. package/dist/node-prod/useCartAPIStateMachine.js.map +1 -1
  76. package/dist/node-prod/useCartAPIStateMachine.mjs.map +1 -1
  77. package/dist/node-prod/useCartActions.js.map +1 -1
  78. package/dist/node-prod/useCartActions.mjs.map +1 -1
  79. package/dist/types/CartLineProvider.d.ts +1 -1
  80. package/dist/types/CartProvider.d.ts +2 -2
  81. package/dist/types/Image.d.ts +1 -1
  82. package/dist/types/ModelViewer.d.ts +1 -1
  83. package/dist/types/Money.d.ts +1 -1
  84. package/dist/types/Video.d.ts +1 -1
  85. package/dist/types/codegen.helpers.d.ts +2 -2
  86. package/dist/types/optionValueDecoder.d.ts +2 -2
  87. package/dist/types/storefront-api-constants.d.ts +1 -1
  88. package/dist/types/storefront-api-types.d.ts +2 -2
  89. package/dist/types/useCartAPIStateMachine.d.ts +2 -2
  90. package/dist/types/useCartActions.d.ts +2 -2
  91. package/dist/umd/hydrogen-react.dev.js +2 -2
  92. package/dist/umd/hydrogen-react.dev.js.map +1 -1
  93. package/dist/umd/hydrogen-react.prod.js +2 -2
  94. package/dist/umd/hydrogen-react.prod.js.map +1 -1
  95. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ModelViewer.js","sources":["../../src/ModelViewer.tsx"],"sourcesContent":["import {useState, useEffect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2025-01/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n const hydrogenEventListener = {\n error: passthroughProps.onError,\n load: passthroughProps.onLoad,\n preload: passthroughProps.onPreload,\n 'model-visibility': passthroughProps.onModelVisibility,\n progress: passthroughProps.onProgress,\n 'ar-status': passthroughProps.onArStatus,\n 'ar-tracking': passthroughProps.onArTracking,\n 'quick-look-button-tapped': passthroughProps.onQuickLookButtonTapped,\n 'camera-change': passthroughProps.onCameraChange,\n 'environment-change': passthroughProps.onEnvironmentChange,\n play: passthroughProps.onPlay,\n pause: passthroughProps.onPause,\n 'scene-graph-ready': passthroughProps.onSceneGraphReady,\n };\n\n if (!modelViewer) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.addEventListener(eventName, callbackFunc);\n }\n },\n );\n\n return (): void => {\n if (modelViewer == null) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.removeEventListener(eventName, callbackFunc);\n }\n },\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n ref={callbackRef}\n {...passthroughProps}\n // @ts-expect-error src should exist\n // @eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n class={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n interaction-policy={(passthroughProps as any).interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bounds={(passthroughProps as any).bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n"],"names":["useState","useCallback","useLoadScript","useEffect","jsx"],"mappings":";;;;;AA+DO,SAAS,YAAY,OAA6C;;AACjE,QAAA,CAAC,aAAa,cAAc,IAAIA,MAAA;AAAA,IACpC;AAAA,EACF;AACM,QAAA,cAAcC,kBAAY,CAAC,SAAsB;AACrD,mBAAe,IAAI;AAAA,EACrB,GAAG,EAAE;AACL,QAAM,EAAC,MAAM,UAAU,WAAW,GAAG,iBAAoB,IAAA;AAEzD,QAAM,0BAA0BC,WAAA;AAAA,IAC9B;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,IAAA;AAAA,EAEZ;AAEAC,QAAAA,UAAU,MAAM;AACd,UAAM,wBAAwB;AAAA,MAC5B,OAAO,iBAAiB;AAAA,MACxB,MAAM,iBAAiB;AAAA,MACvB,SAAS,iBAAiB;AAAA,MAC1B,oBAAoB,iBAAiB;AAAA,MACrC,UAAU,iBAAiB;AAAA,MAC3B,aAAa,iBAAiB;AAAA,MAC9B,eAAe,iBAAiB;AAAA,MAChC,4BAA4B,iBAAiB;AAAA,MAC7C,iBAAiB,iBAAiB;AAAA,MAClC,sBAAsB,iBAAiB;AAAA,MACvC,MAAM,iBAAiB;AAAA,MACvB,OAAO,iBAAiB;AAAA,MACxB,qBAAqB,iBAAiB;AAAA,IACxC;AAEA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Effect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2025-04/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n const hydrogenEventListener = {\n error: passthroughProps.onError,\n load: passthroughProps.onLoad,\n preload: passthroughProps.onPreload,\n 'model-visibility': passthroughProps.onModelVisibility,\n progress: passthroughProps.onProgress,\n 'ar-status': passthroughProps.onArStatus,\n 'ar-tracking': passthroughProps.onArTracking,\n 'quick-look-button-tapped': passthroughProps.onQuickLookButtonTapped,\n 'camera-change': passthroughProps.onCameraChange,\n 'environment-change': passthroughProps.onEnvironmentChange,\n play: passthroughProps.onPlay,\n pause: passthroughProps.onPause,\n 'scene-graph-ready': passthroughProps.onSceneGraphReady,\n };\n\n if (!modelViewer) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.addEventListener(eventName, callbackFunc);\n }\n },\n );\n\n return (): void => {\n if (modelViewer == null) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.removeEventListener(eventName, callbackFunc);\n }\n },\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n ref={callbackRef}\n {...passthroughProps}\n // @ts-expect-error src should exist\n // @eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n class={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n interaction-policy={(passthroughProps as any).interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bounds={(passthroughProps as any).bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n"],"names":["useState","useCallback","useLoadScript","useEffect","jsx"],"mappings":";;;;;AA+DO,SAAS,YAAY,OAA6C;;AACjE,QAAA,CAAC,aAAa,cAAc,IAAIA,MAAA;AAAA,IACpC;AAAA,EACF;AACM,QAAA,cAAcC,kBAAY,CAAC,SAAsB;AACrD,mBAAe,IAAI;AAAA,EACrB,GAAG,EAAE;AACL,QAAM,EAAC,MAAM,UAAU,WAAW,GAAG,iBAAoB,IAAA;AAEzD,QAAM,0BAA0BC,WAAA;AAAA,IAC9B;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,IAAA;AAAA,EAEZ;AAEAC,QAAAA,UAAU,MAAM;AACd,UAAM,wBAAwB;AAAA,MAC5B,OAAO,iBAAiB;AAAA,MACxB,MAAM,iBAAiB;AAAA,MACvB,SAAS,iBAAiB;AAAA,MAC1B,oBAAoB,iBAAiB;AAAA,MACrC,UAAU,iBAAiB;AAAA,MAC3B,aAAa,iBAAiB;AAAA,MAC9B,eAAe,iBAAiB;AAAA,MAChC,4BAA4B,iBAAiB;AAAA,MAC7C,iBAAiB,iBAAiB;AAAA,MAClC,sBAAsB,iBAAiB;AAAA,MACvC,MAAM,iBAAiB;AAAA,MACvB,OAAO,iBAAiB;AAAA,MACxB,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er.mjs","sources":["../../src/ModelViewer.tsx"],"sourcesContent":["import {useState, useEffect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2025-01/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n const hydrogenEventListener = {\n error: passthroughProps.onError,\n load: passthroughProps.onLoad,\n preload: passthroughProps.onPreload,\n 'model-visibility': passthroughProps.onModelVisibility,\n progress: passthroughProps.onProgress,\n 'ar-status': passthroughProps.onArStatus,\n 'ar-tracking': passthroughProps.onArTracking,\n 'quick-look-button-tapped': passthroughProps.onQuickLookButtonTapped,\n 'camera-change': passthroughProps.onCameraChange,\n 'environment-change': passthroughProps.onEnvironmentChange,\n play: passthroughProps.onPlay,\n pause: passthroughProps.onPause,\n 'scene-graph-ready': passthroughProps.onSceneGraphReady,\n };\n\n if (!modelViewer) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.addEventListener(eventName, callbackFunc);\n }\n },\n );\n\n return (): void => {\n if (modelViewer == null) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.removeEventListener(eventName, callbackFunc);\n }\n },\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n ref={callbackRef}\n {...passthroughProps}\n // @ts-expect-error src should exist\n // @eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n class={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n interaction-policy={(passthroughProps as any).interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bounds={(passthroughProps as any).bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n"],"names":[],"mappings":";;;AA+DO,SAAS,YAAY,OAA6C;;AACjE,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC;AAAA,EACF;AACM,QAAA,cAAc,YAAY,CAAC,SAAsB;AACrD,mBAAe,IAAI;AAAA,EACrB,GAAG,EAAE;AACL,QAAM,EAAC,MAAM,UAAU,WAAW,GAAG,iBAAoB,IAAA;AAEzD,QAAM,0BAA0B;AAAA,IAC9B;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,IAAA;AAAA,EAEZ;AAEA,YAAU,MAAM;AACd,UAAM,wBAAwB;AAAA,MAC5B,OAAO,iBAAiB;AAAA,MACxB,MAAM,iBAAiB;AAAA,MACvB,SAAS,iBAAiB;AAAA,MAC1B,oBAAoB,iBAAiB;AAAA,MACrC,UAAU,iBAAiB;AAAA,MAC3B,aAAa,iBAAiB;AAAA,MAC9B,eAAe,iBAAiB;AAAA,MAChC,4BAA4B,iBAAiB;AAAA,MAC7C,iBAAiB,iBAAiB;AAAA,MAClC,sBAAsB,iBAAiB;AAAA,MACvC,MAAM,iBAAiB;AAAA,MACvB,OAAO,iBAAiB;AAAA,MACxB,qBAAqB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],"sourcesContent":["import {useState, useEffect, useCallback} from 'react';\nimport {useLoadScript} from './load-script.js';\nimport type {Model3d} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\nimport type {ModelViewerElement} from '@google/model-viewer/lib/model-viewer.js';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n interface IntrinsicElements {\n 'model-viewer': PartialDeep<\n ModelViewerElement,\n {recurseIntoArrays: true}\n >;\n }\n }\n}\n\ntype ModelViewerProps = Omit<\n PartialDeep<JSX.IntrinsicElements['model-viewer'], {recurseIntoArrays: true}>,\n 'src'\n> &\n ModelViewerBaseProps;\n\ntype ModelViewerBaseProps = {\n /** An object with fields that correspond to the Storefront API's [Model3D object](https://shopify.dev/api/storefront/2025-04/objects/model3d). */\n data: PartialDeep<Model3d, {recurseIntoArrays: true}>;\n /** The callback to invoke when the 'error' event is triggered. Refer to [error in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-error). */\n onError?: (event: Event) => void;\n /** The callback to invoke when the `load` event is triggered. Refer to [load in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-load). */\n onLoad?: (event: Event) => void;\n /** The callback to invoke when the 'preload' event is triggered. Refer to [preload in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-preload). */\n onPreload?: (event: Event) => void;\n /** The callback to invoke when the 'model-visibility' event is triggered. Refer to [model-visibility in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-modelVisibility). */\n onModelVisibility?: (event: Event) => void;\n /** The callback to invoke when the 'progress' event is triggered. Refer to [progress in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-loading-events-progress). */\n onProgress?: (event: Event) => void;\n /** The callback to invoke when the 'ar-status' event is triggered. Refer to [ar-status in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arStatus). */\n onArStatus?: (event: Event) => void;\n /** The callback to invoke when the 'ar-tracking' event is triggered. Refer to [ar-tracking in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-arTracking). */\n onArTracking?: (event: Event) => void;\n /** The callback to invoke when the 'quick-look-button-tapped' event is triggered. Refer to [quick-look-button-tapped in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-augmentedreality-events-quickLookButtonTapped). */\n onQuickLookButtonTapped?: (event: Event) => void;\n /** The callback to invoke when the 'camera-change' event is triggered. Refer to [camera-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-events-cameraChange). */\n onCameraChange?: (event: Event) => void;\n /** The callback to invoke when the 'environment-change' event is triggered. Refer to [environment-change in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-lightingandenv-events-environmentChange). */\n onEnvironmentChange?: (event: Event) => void;\n /** The callback to invoke when the 'play' event is triggered. Refer to [play in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-play). */\n onPlay?: (event: Event) => void;\n /** The callback to invoke when the 'pause' event is triggered. Refer to [pause in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-animation-events-pause). */\n onPause?: (event: Event) => void;\n /** The callback to invoke when the 'scene-graph-ready' event is triggered. Refer to [scene-graph-ready in the <model-viewer> documentation](https://modelviewer.dev/docs/index.html#entrydocs-scenegraph-events-sceneGraphReady). */\n onSceneGraphReady?: (event: Event) => void;\n};\n\n/**\n * The `ModelViewer` component renders a 3D model (with the `model-viewer` custom element) for\n * the Storefront API's [Model3d object](https://shopify.dev/api/storefront/reference/products/model3d).\n *\n * The `model-viewer` custom element is lazily downloaded through a dynamically-injected `<script type=\"module\">` tag when the `<ModelViewer />` component is rendered\n *\n * ModelViewer is using version `1.21.1` of the `@google/model-viewer` library.\n */\nexport function ModelViewer(props: ModelViewerProps): JSX.Element | null {\n const [modelViewer, setModelViewer] = useState<undefined | HTMLElement>(\n undefined,\n );\n const callbackRef = useCallback((node: HTMLElement) => {\n setModelViewer(node);\n }, []);\n const {data, children, className, ...passthroughProps} = props;\n\n const modelViewerLoadedStatus = useLoadScript(\n 'https://unpkg.com/@google/model-viewer@v1.12.1/dist/model-viewer.min.js',\n {\n module: true,\n },\n );\n\n useEffect(() => {\n const hydrogenEventListener = {\n error: passthroughProps.onError,\n load: passthroughProps.onLoad,\n preload: passthroughProps.onPreload,\n 'model-visibility': passthroughProps.onModelVisibility,\n progress: passthroughProps.onProgress,\n 'ar-status': passthroughProps.onArStatus,\n 'ar-tracking': passthroughProps.onArTracking,\n 'quick-look-button-tapped': passthroughProps.onQuickLookButtonTapped,\n 'camera-change': passthroughProps.onCameraChange,\n 'environment-change': passthroughProps.onEnvironmentChange,\n play: passthroughProps.onPlay,\n pause: passthroughProps.onPause,\n 'scene-graph-ready': passthroughProps.onSceneGraphReady,\n };\n\n if (!modelViewer) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.addEventListener(eventName, callbackFunc);\n }\n },\n );\n\n return (): void => {\n if (modelViewer == null) {\n return;\n }\n Object.entries(hydrogenEventListener).forEach(\n ([eventName, callbackFunc]) => {\n if (callbackFunc) {\n modelViewer.removeEventListener(eventName, callbackFunc);\n }\n },\n );\n };\n }, [\n modelViewer,\n passthroughProps.onArStatus,\n passthroughProps.onArTracking,\n passthroughProps.onCameraChange,\n passthroughProps.onEnvironmentChange,\n passthroughProps.onError,\n passthroughProps.onLoad,\n passthroughProps.onModelVisibility,\n passthroughProps.onPause,\n passthroughProps.onPlay,\n passthroughProps.onPreload,\n passthroughProps.onProgress,\n passthroughProps.onQuickLookButtonTapped,\n passthroughProps.onSceneGraphReady,\n ]);\n\n if (modelViewerLoadedStatus !== 'done') {\n // TODO: What do we want to display while the model-viewer library loads?\n return null;\n }\n\n if (!data.sources?.[0]?.url) {\n const sourcesUrlError = `<ModelViewer/> requires 'data.sources' prop to be an array, with an object that has a property 'url' on it. Rendering 'null'`;\n if (__HYDROGEN_DEV__) {\n throw new Error(sourcesUrlError);\n } else {\n console.error(sourcesUrlError);\n return null;\n }\n }\n\n if (__HYDROGEN_DEV__ && !data.alt) {\n console.warn(\n `<ModelViewer/> requires the 'data.alt' prop for accessibility`,\n );\n }\n\n return (\n <model-viewer\n ref={callbackRef}\n {...passthroughProps}\n // @ts-expect-error src should exist\n // @eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n class={className}\n id={passthroughProps.id ?? data.id}\n src={data.sources[0].url}\n alt={data.alt ?? null}\n camera-controls={passthroughProps.cameraControls ?? true}\n poster={(passthroughProps.poster || data.previewImage?.url) ?? null}\n autoplay={passthroughProps.autoplay ?? true}\n loading={passthroughProps.loading}\n reveal={passthroughProps.reveal}\n ar={passthroughProps.ar}\n ar-modes={passthroughProps.arModes}\n ar-scale={passthroughProps.arScale}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n ar-placement={passthroughProps.arPlacement}\n ios-src={passthroughProps.iosSrc}\n touch-action={passthroughProps.touchAction}\n disable-zoom={passthroughProps.disableZoom}\n orbit-sensitivity={passthroughProps.orbitSensitivity}\n auto-rotate={passthroughProps.autoRotate}\n auto-rotate-delay={passthroughProps.autoRotateDelay}\n // @ts-expect-error rotationPerSecond should exist as a type, not sure why it doesn't. https://modelviewer.dev/docs/index.html#entrydocs-stagingandcameras-attributes-rotationPerSecond\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n rotation-per-second={passthroughProps.rotationPerSecond}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n interaction-policy={(passthroughProps as any).interactionPolicy}\n interaction-prompt={passthroughProps.interactionPrompt}\n interaction-prompt-style={passthroughProps.interactionPromptStyle}\n interaction-prompt-threshold={passthroughProps.interactionPromptThreshold}\n camera-orbit={passthroughProps.cameraOrbit}\n camera-target={passthroughProps.cameraTarget}\n field-of-view={passthroughProps.fieldOfView}\n max-camera-orbit={passthroughProps.maxCameraOrbit}\n min-camera-orbit={passthroughProps.minCameraOrbit}\n max-field-of-view={passthroughProps.maxFieldOfView}\n min-field-of-view={passthroughProps.minFieldOfView}\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bounds={(passthroughProps as any).bounds}\n interpolation-decay={passthroughProps.interpolationDecay ?? 100}\n skybox-image={passthroughProps.skyboxImage}\n environment-image={passthroughProps.environmentImage}\n exposure={passthroughProps.exposure}\n shadow-intensity={passthroughProps.shadowIntensity ?? 0}\n shadow-softness={passthroughProps.shadowSoftness ?? 0}\n animation-name={passthroughProps.animationName}\n animation-crossfade-duration={passthroughProps.animationCrossfadeDuration}\n variant-name={passthroughProps.variantName}\n orientation={passthroughProps.orientation}\n scale={passthroughProps.scale}\n >\n {children}\n </model-viewer>\n );\n}\n"],"names":[],"mappings":";;;AA+DO,SAAS,YAAY,OAA6C;;AACjE,QAAA,CAAC,aAAa,cAAc,IAAI;AAAA,IACpC;AAAA,EACF;AACM,QAAA,cAAc,YAAY,CAAC,SAAsB;AACrD,mBAAe,IAAI;AAAA,EACrB,GAAG,EAAE;AACL,QAAM,EAAC,MAAM,UAAU,WAAW,GAAG,iBAAoB,IAAA;AAEzD,QAAM,0BAA0B;AAAA,IAC9B;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,IAAA;AAAA,EAEZ;AAEA,YAAU,MAAM;AACd,UAAM,wBAAwB;AAAA,MAC5B,OAAO,iBAAiB;AAAA,MACxB,MAAM,iBAAiB;AAAA,MACvB,SAAS,iBAAiB;AAAA,MAC1B,oBAAoB,iBAAiB;AAAA,MACrC,UAAU,iBAAiB;AAAA,MAC3B,aAAa,iBAAiB;AAAA,MAC9B,eAAe,iBAAiB;AAAA,MAChC,4BAA4B,iBAAiB;AAAA,MAC7C,iBAAiB,iBAAiB;AAAA,MAClC,sBAAsB,iBAAiB;AAAA,MACvC,MAAM,iBAAiB;AAAA,MACvB,OAAO,iBAAiB;AAAA,MACxB,qBAAqB,iBAAiB;AAAA,IACxC;AAEA,QA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\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2025-01/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n (ComponentGeneric extends keyof React.JSX.IntrinsicElements\n ? Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof MoneyPropsBase<ComponentGeneric>\n >\n : React.ComponentPropsWithoutRef<ComponentGeneric>);\n\n/**\n * The `Money` component renders a string of the Storefront API's\n * [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2)\n * according to the `locale` in the `ShopifyProvider` component.\n * &nbsp;\n * @see {@link https://shopify.dev/api/hydrogen/components/money}\n * @example basic usage, outputs: $100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} />\n * ```\n * &nbsp;\n *\n * @example without currency, outputs: 100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutCurrency />\n * ```\n * &nbsp;\n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutTrailingZeros />\n * ```\n * &nbsp;\n *\n * @example with per-unit measurement, outputs: $100.00 per G\n * ```ts\n * <Money\n * data={{amount: '100.00', currencyCode: 'USD'}}\n * measurement={{referenceUnit: 'G'}}\n * measurementSeparator=\" per \"\n * />\n * ```\n */\nexport function Money<ComponentGeneric extends React.ElementType = 'div'>({\n data,\n as,\n withoutCurrency,\n withoutTrailingZeros,\n measurement,\n measurementSeparator = '/',\n ...passthroughProps\n}: MoneyProps<ComponentGeneric>): JSX.Element {\n if (!isMoney(data)) {\n throw new Error(\n `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`,\n );\n }\n const moneyObject = useMoney(data);\n const Wrapper = as ?? 'div';\n\n let output = moneyObject.localizedString;\n\n if (withoutCurrency || withoutTrailingZeros) {\n if (withoutCurrency && !withoutTrailingZeros) {\n output = moneyObject.amount;\n } else if (!withoutCurrency && withoutTrailingZeros) {\n output = moneyObject.withoutTrailingZeros;\n } else {\n // both\n output = moneyObject.withoutTrailingZerosAndCurrency;\n }\n }\n\n return (\n <Wrapper {...passthroughProps}>\n {output}\n {measurement && measurement.referenceUnit && (\n <>\n {measurementSeparator}\n {measurement.referenceUnit}\n </>\n )}\n </Wrapper>\n );\n}\n\n// required in order to narrow the money object down and make TS happy\nfunction isMoney(\n maybeMoney: PartialDeep<MoneyV2, {recurseIntoArrays: true}>,\n): maybeMoney is MoneyV2 {\n return (\n typeof maybeMoney.amount === 'string' &&\n !!maybeMoney.amount &&\n typeof maybeMoney.currencyCode === 'string' &&\n !!maybeMoney.currencyCode\n );\n}\n"],"names":["useMoney","jsxs","Fragment"],"mappings":";;;;AA+DO,SAAS,MAA0D;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB,GAAG;AACL,GAA8C;AACxC,MAAA,CAAC,QAAQ,IAAI,GAAG;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAEI,QAAA,cAAcA,kBAAS,IAAI;AACjC,QAAM,UAAU,MAAM;AAEtB,MAAI,SAAS,YAAY;AAEzB,MAAI,mBAAmB,sBAAsB;AACvC,QAAA,mBAAmB,CAAC,sBAAsB;AAC5C,eAAS,YAAY;AAAA,IAAA,WACZ,CAAC,mBAAmB,sBAAsB;AACnD,eAAS,YAAY;AAAA,IAAA,OAChB;AAEL,eAAS,YAAY;AAAA,IAAA;AAAA,EACvB;AAIA,SAAAC,2BAAA,KAAC,SAAS,EAAA,GAAG,kBACV,UAAA;AAAA,IAAA;AAAA,IACA,eAAe,YAAY,iBAEvBA,2BAAA,KAAAC,WAAA,UAAA,EAAA,UAAA;AAAA,MAAA;AAAA,MACA,YAAY;AAAA,IAAA,EACf,CAAA;AAAA,EAAA,GAEJ;AAEJ;AAGA,SAAS,QACP,YACuB;AACvB,SACE,OAAO,WAAW,WAAW,YAC7B,CAAC,CAAC,WAAW,UACb,OAAO,WAAW,iBAAiB,YACnC,CAAC,CAAC,WAAW;AAEjB;;"}
1
+ {"version":3,"file":"Money.js","sources":["../../src/Money.tsx"],"sourcesContent":["import {type ReactNode} from 'react';\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2025-04/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n (ComponentGeneric extends keyof React.JSX.IntrinsicElements\n ? Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof MoneyPropsBase<ComponentGeneric>\n >\n : React.ComponentPropsWithoutRef<ComponentGeneric>);\n\n/**\n * The `Money` component renders a string of the Storefront API's\n * [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2)\n * according to the `locale` in the `ShopifyProvider` component.\n * &nbsp;\n * @see {@link https://shopify.dev/api/hydrogen/components/money}\n * @example basic usage, outputs: $100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} />\n * ```\n * &nbsp;\n *\n * @example without currency, outputs: 100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutCurrency />\n * ```\n * &nbsp;\n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutTrailingZeros />\n * ```\n * &nbsp;\n *\n * @example with per-unit measurement, outputs: $100.00 per G\n * ```ts\n * <Money\n * data={{amount: '100.00', currencyCode: 'USD'}}\n * measurement={{referenceUnit: 'G'}}\n * measurementSeparator=\" per \"\n * />\n * ```\n */\nexport function Money<ComponentGeneric extends React.ElementType = 'div'>({\n data,\n as,\n withoutCurrency,\n withoutTrailingZeros,\n measurement,\n measurementSeparator = '/',\n ...passthroughProps\n}: MoneyProps<ComponentGeneric>): JSX.Element {\n if (!isMoney(data)) {\n throw new Error(\n `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`,\n );\n }\n const moneyObject = useMoney(data);\n const Wrapper = as ?? 'div';\n\n let output = moneyObject.localizedString;\n\n if (withoutCurrency || withoutTrailingZeros) {\n if (withoutCurrency && !withoutTrailingZeros) {\n output = moneyObject.amount;\n } else if (!withoutCurrency && withoutTrailingZeros) {\n output = moneyObject.withoutTrailingZeros;\n } else {\n // both\n output = moneyObject.withoutTrailingZerosAndCurrency;\n }\n }\n\n return (\n <Wrapper {...passthroughProps}>\n {output}\n {measurement && measurement.referenceUnit && (\n <>\n {measurementSeparator}\n {measurement.referenceUnit}\n </>\n )}\n </Wrapper>\n );\n}\n\n// required in order to narrow the money object down and make TS happy\nfunction isMoney(\n maybeMoney: PartialDeep<MoneyV2, {recurseIntoArrays: true}>,\n): maybeMoney is MoneyV2 {\n return (\n typeof maybeMoney.amount === 'string' &&\n !!maybeMoney.amount &&\n typeof maybeMoney.currencyCode === 'string' &&\n !!maybeMoney.currencyCode\n );\n}\n"],"names":["useMoney","jsxs","Fragment"],"mappings":";;;;AA+DO,SAAS,MAA0D;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB,GAAG;AACL,GAA8C;AACxC,MAAA,CAAC,QAAQ,IAAI,GAAG;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAEI,QAAA,cAAcA,kBAAS,IAAI;AACjC,QAAM,UAAU,MAAM;AAEtB,MAAI,SAAS,YAAY;AAEzB,MAAI,mBAAmB,sBAAsB;AACvC,QAAA,mBAAmB,CAAC,sBAAsB;AAC5C,eAAS,YAAY;AAAA,IAAA,WACZ,CAAC,mBAAmB,sBAAsB;AACnD,eAAS,YAAY;AAAA,IAAA,OAChB;AAEL,eAAS,YAAY;AAAA,IAAA;AAAA,EACvB;AAIA,SAAAC,2BAAA,KAAC,SAAS,EAAA,GAAG,kBACV,UAAA;AAAA,IAAA;AAAA,IACA,eAAe,YAAY,iBAEvBA,2BAAA,KAAAC,WAAA,UAAA,EAAA,UAAA;AAAA,MAAA;AAAA,MACA,YAAY;AAAA,IAAA,EACf,CAAA;AAAA,EAAA,GAEJ;AAEJ;AAGA,SAAS,QACP,YACuB;AACvB,SACE,OAAO,WAAW,WAAW,YAC7B,CAAC,CAAC,WAAW,UACb,OAAO,WAAW,iBAAiB,YACnC,CAAC,CAAC,WAAW;AAEjB;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Money.mjs","sources":["../../src/Money.tsx"],"sourcesContent":["import {type ReactNode} from 'react';\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2025-01/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n (ComponentGeneric extends keyof React.JSX.IntrinsicElements\n ? Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof MoneyPropsBase<ComponentGeneric>\n >\n : React.ComponentPropsWithoutRef<ComponentGeneric>);\n\n/**\n * The `Money` component renders a string of the Storefront API's\n * [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2)\n * according to the `locale` in the `ShopifyProvider` component.\n * &nbsp;\n * @see {@link https://shopify.dev/api/hydrogen/components/money}\n * @example basic usage, outputs: $100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} />\n * ```\n * &nbsp;\n *\n * @example without currency, outputs: 100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutCurrency />\n * ```\n * &nbsp;\n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutTrailingZeros />\n * ```\n * &nbsp;\n *\n * @example with per-unit measurement, outputs: $100.00 per G\n * ```ts\n * <Money\n * data={{amount: '100.00', currencyCode: 'USD'}}\n * measurement={{referenceUnit: 'G'}}\n * measurementSeparator=\" per \"\n * />\n * ```\n */\nexport function Money<ComponentGeneric extends React.ElementType = 'div'>({\n data,\n as,\n withoutCurrency,\n withoutTrailingZeros,\n measurement,\n measurementSeparator = '/',\n ...passthroughProps\n}: MoneyProps<ComponentGeneric>): JSX.Element {\n if (!isMoney(data)) {\n throw new Error(\n `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`,\n );\n }\n const moneyObject = useMoney(data);\n const Wrapper = as ?? 'div';\n\n let output = moneyObject.localizedString;\n\n if (withoutCurrency || withoutTrailingZeros) {\n if (withoutCurrency && !withoutTrailingZeros) {\n output = moneyObject.amount;\n } else if (!withoutCurrency && withoutTrailingZeros) {\n output = moneyObject.withoutTrailingZeros;\n } else {\n // both\n output = moneyObject.withoutTrailingZerosAndCurrency;\n }\n }\n\n return (\n <Wrapper {...passthroughProps}>\n {output}\n {measurement && measurement.referenceUnit && (\n <>\n {measurementSeparator}\n {measurement.referenceUnit}\n </>\n )}\n </Wrapper>\n );\n}\n\n// required in order to narrow the money object down and make TS happy\nfunction isMoney(\n maybeMoney: PartialDeep<MoneyV2, {recurseIntoArrays: true}>,\n): maybeMoney is MoneyV2 {\n return (\n typeof maybeMoney.amount === 'string' &&\n !!maybeMoney.amount &&\n typeof maybeMoney.currencyCode === 'string' &&\n !!maybeMoney.currencyCode\n );\n}\n"],"names":[],"mappings":";;AA+DO,SAAS,MAA0D;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB,GAAG;AACL,GAA8C;AACxC,MAAA,CAAC,QAAQ,IAAI,GAAG;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAEI,QAAA,cAAc,SAAS,IAAI;AACjC,QAAM,UAAU,MAAM;AAEtB,MAAI,SAAS,YAAY;AAEzB,MAAI,mBAAmB,sBAAsB;AACvC,QAAA,mBAAmB,CAAC,sBAAsB;AAC5C,eAAS,YAAY;AAAA,IAAA,WACZ,CAAC,mBAAmB,sBAAsB;AACnD,eAAS,YAAY;AAAA,IAAA,OAChB;AAEL,eAAS,YAAY;AAAA,IAAA;AAAA,EACvB;AAIA,SAAA,qBAAC,SAAS,EAAA,GAAG,kBACV,UAAA;AAAA,IAAA;AAAA,IACA,eAAe,YAAY,iBAEvB,qBAAA,UAAA,EAAA,UAAA;AAAA,MAAA;AAAA,MACA,YAAY;AAAA,IAAA,EACf,CAAA;AAAA,EAAA,GAEJ;AAEJ;AAGA,SAAS,QACP,YACuB;AACvB,SACE,OAAO,WAAW,WAAW,YAC7B,CAAC,CAAC,WAAW,UACb,OAAO,WAAW,iBAAiB,YACnC,CAAC,CAAC,WAAW;AAEjB;"}
1
+ {"version":3,"file":"Money.mjs","sources":["../../src/Money.tsx"],"sourcesContent":["import {type ReactNode} from 'react';\nimport {useMoney} from './useMoney.js';\nimport type {MoneyV2, UnitPriceMeasurement} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface MoneyPropsBase<ComponentGeneric extends React.ElementType> {\n /** An HTML tag or React Component to be rendered as the base element wrapper. The default is `div`. */\n as?: ComponentGeneric;\n /** An object with fields that correspond to the Storefront API's [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2). */\n data: PartialDeep<MoneyV2, {recurseIntoArrays: true}>;\n /** Whether to remove the currency symbol from the output. */\n withoutCurrency?: boolean;\n /** Whether to remove trailing zeros (fractional money) from the output. */\n withoutTrailingZeros?: boolean;\n /** A [UnitPriceMeasurement object](https://shopify.dev/api/storefront/2025-04/objects/unitpricemeasurement). */\n measurement?: PartialDeep<UnitPriceMeasurement, {recurseIntoArrays: true}>;\n /** Customizes the separator between the money output and the measurement output. Used with the `measurement` prop. Defaults to `'/'`. */\n measurementSeparator?: ReactNode;\n}\n\n// This article helps understand the typing here https://www.benmvp.com/blog/polymorphic-react-components-typescript/ Ben is the best :)\nexport type MoneyProps<ComponentGeneric extends React.ElementType> =\n MoneyPropsBase<ComponentGeneric> &\n (ComponentGeneric extends keyof React.JSX.IntrinsicElements\n ? Omit<\n React.ComponentPropsWithoutRef<ComponentGeneric>,\n keyof MoneyPropsBase<ComponentGeneric>\n >\n : React.ComponentPropsWithoutRef<ComponentGeneric>);\n\n/**\n * The `Money` component renders a string of the Storefront API's\n * [MoneyV2 object](https://shopify.dev/api/storefront/reference/common-objects/moneyv2)\n * according to the `locale` in the `ShopifyProvider` component.\n * &nbsp;\n * @see {@link https://shopify.dev/api/hydrogen/components/money}\n * @example basic usage, outputs: $100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} />\n * ```\n * &nbsp;\n *\n * @example without currency, outputs: 100.00\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutCurrency />\n * ```\n * &nbsp;\n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * <Money data={{amount: '100.00', currencyCode: 'USD'}} withoutTrailingZeros />\n * ```\n * &nbsp;\n *\n * @example with per-unit measurement, outputs: $100.00 per G\n * ```ts\n * <Money\n * data={{amount: '100.00', currencyCode: 'USD'}}\n * measurement={{referenceUnit: 'G'}}\n * measurementSeparator=\" per \"\n * />\n * ```\n */\nexport function Money<ComponentGeneric extends React.ElementType = 'div'>({\n data,\n as,\n withoutCurrency,\n withoutTrailingZeros,\n measurement,\n measurementSeparator = '/',\n ...passthroughProps\n}: MoneyProps<ComponentGeneric>): JSX.Element {\n if (!isMoney(data)) {\n throw new Error(\n `<Money/> needs a valid 'data' prop that has 'amount' and 'currencyCode'`,\n );\n }\n const moneyObject = useMoney(data);\n const Wrapper = as ?? 'div';\n\n let output = moneyObject.localizedString;\n\n if (withoutCurrency || withoutTrailingZeros) {\n if (withoutCurrency && !withoutTrailingZeros) {\n output = moneyObject.amount;\n } else if (!withoutCurrency && withoutTrailingZeros) {\n output = moneyObject.withoutTrailingZeros;\n } else {\n // both\n output = moneyObject.withoutTrailingZerosAndCurrency;\n }\n }\n\n return (\n <Wrapper {...passthroughProps}>\n {output}\n {measurement && measurement.referenceUnit && (\n <>\n {measurementSeparator}\n {measurement.referenceUnit}\n </>\n )}\n </Wrapper>\n );\n}\n\n// required in order to narrow the money object down and make TS happy\nfunction isMoney(\n maybeMoney: PartialDeep<MoneyV2, {recurseIntoArrays: true}>,\n): maybeMoney is MoneyV2 {\n return (\n typeof maybeMoney.amount === 'string' &&\n !!maybeMoney.amount &&\n typeof maybeMoney.currencyCode === 'string' &&\n !!maybeMoney.currencyCode\n );\n}\n"],"names":[],"mappings":";;AA+DO,SAAS,MAA0D;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB,GAAG;AACL,GAA8C;AACxC,MAAA,CAAC,QAAQ,IAAI,GAAG;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAEI,QAAA,cAAc,SAAS,IAAI;AACjC,QAAM,UAAU,MAAM;AAEtB,MAAI,SAAS,YAAY;AAEzB,MAAI,mBAAmB,sBAAsB;AACvC,QAAA,mBAAmB,CAAC,sBAAsB;AAC5C,eAAS,YAAY;AAAA,IAAA,WACZ,CAAC,mBAAmB,sBAAsB;AACnD,eAAS,YAAY;AAAA,IAAA,OAChB;AAEL,eAAS,YAAY;AAAA,IAAA;AAAA,EACvB;AAIA,SAAA,qBAAC,SAAS,EAAA,GAAG,kBACV,UAAA;AAAA,IAAA;AAAA,IACA,eAAe,YAAY,iBAEvB,qBAAA,UAAA,EAAA,UAAA;AAAA,MAAA;AAAA,MACA,YAAY;AAAA,IAAA,EACf,CAAA;AAAA,EAAA,GAEJ;AAEJ;AAGA,SAAS,QACP,YACuB;AACvB,SACE,OAAO,WAAW,WAAW,YAC7B,CAAC,CAAC,WAAW,UACb,OAAO,WAAW,iBAAiB,YACnC,CAAC,CAAC,WAAW;AAEjB;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Video.js","sources":["../../src/Video.tsx"],"sourcesContent":["import {forwardRef, type HTMLAttributes} from 'react';\nimport {shopifyLoader} from './Image.js';\nimport type {Video as VideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface VideoProps {\n /** An object with fields that correspond to the Storefront API's [Video object](https://shopify.dev/api/storefront/2025-01/objects/video). */\n data: PartialDeep<VideoType, {recurseIntoArrays: true}>;\n /** An object of image size options for the video's `previewImage`. Uses `shopifyImageLoader` to generate the `poster` URL. */\n previewImageOptions?: Parameters<typeof shopifyLoader>[0];\n /** Props that will be passed to the `video` element's `source` children elements. */\n sourceProps?: HTMLAttributes<HTMLSourceElement> & {\n 'data-testid'?: string;\n };\n}\n\n/**\n * The `Video` component renders a `video` for the Storefront API's [Video object](https://shopify.dev/api/storefront/reference/products/video).\n */\nexport const Video = forwardRef<\n HTMLVideoElement,\n JSX.IntrinsicElements['video'] & VideoProps\n>((props, ref): JSX.Element => {\n const {\n data,\n previewImageOptions,\n id = data.id,\n playsInline = true,\n controls = true,\n sourceProps = {},\n ...passthroughProps\n } = props;\n\n const posterUrl = shopifyLoader({\n src: data.previewImage?.url ?? '',\n ...previewImageOptions,\n });\n\n if (!data.sources) {\n throw new Error(`<Video/> requires a 'data.sources' array`);\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/media-has-caption\n <video\n {...passthroughProps}\n id={id}\n playsInline={playsInline}\n controls={controls}\n poster={posterUrl}\n ref={ref}\n >\n {data.sources.map((source) => {\n if (!(source?.url && source?.mimeType)) {\n throw new Error(`<Video/> needs 'source.url' and 'source.mimeType'`);\n }\n return (\n <source\n {...sourceProps}\n key={source.url}\n src={source.url}\n type={source.mimeType}\n />\n );\n })}\n </video>\n );\n});\n"],"names":["forwardRef","shopifyLoader","jsx","createElement"],"mappings":";;;;;AAmBO,MAAM,QAAQA,MAAA,WAGnB,CAAC,OAAO,QAAqB;;AACvB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA,KAAK,KAAK;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,cAAc,CAAC;AAAA,IACf,GAAG;AAAA,EAAA,IACD;AAEJ,QAAM,YAAYC,MAAAA,cAAc;AAAA,IAC9B,OAAK,UAAK,iBAAL,mBAAmB,QAAO;AAAA,IAC/B,GAAG;AAAA,EAAA,CACJ;AAEG,MAAA,CAAC,KAAK,SAAS;AACX,UAAA,IAAI,MAAM,0CAA0C;AAAA,EAAA;AAG5D;AAAA;AAAA,IAEEC,2BAAA;AAAA,MAAC;AAAA,MAAA;AAAA,QACE,GAAG;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QAEC,UAAK,KAAA,QAAQ,IAAI,CAAC,WAAW;AAC5B,cAAI,GAAE,iCAAQ,SAAO,iCAAQ,YAAW;AAChC,kBAAA,IAAI,MAAM,mDAAmD;AAAA,UAAA;AAGnE,iBAAAC,sBAAA;AAAA,YAAC;AAAA,YAAA;AAAA,cACE,GAAG;AAAA,cACJ,KAAK,OAAO;AAAA,cACZ,KAAK,OAAO;AAAA,cACZ,MAAM,OAAO;AAAA,YAAA;AAAA,UACf;AAAA,QAEH,CAAA;AAAA,MAAA;AAAA,IAAA;AAAA;AAGP,CAAC;;"}
1
+ {"version":3,"file":"Video.js","sources":["../../src/Video.tsx"],"sourcesContent":["import {forwardRef, type HTMLAttributes} from 'react';\nimport {shopifyLoader} from './Image.js';\nimport type {Video as VideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface VideoProps {\n /** An object with fields that correspond to the Storefront API's [Video object](https://shopify.dev/api/storefront/2025-04/objects/video). */\n data: PartialDeep<VideoType, {recurseIntoArrays: true}>;\n /** An object of image size options for the video's `previewImage`. Uses `shopifyImageLoader` to generate the `poster` URL. */\n previewImageOptions?: Parameters<typeof shopifyLoader>[0];\n /** Props that will be passed to the `video` element's `source` children elements. */\n sourceProps?: HTMLAttributes<HTMLSourceElement> & {\n 'data-testid'?: string;\n };\n}\n\n/**\n * The `Video` component renders a `video` for the Storefront API's [Video object](https://shopify.dev/api/storefront/reference/products/video).\n */\nexport const Video = forwardRef<\n HTMLVideoElement,\n JSX.IntrinsicElements['video'] & VideoProps\n>((props, ref): JSX.Element => {\n const {\n data,\n previewImageOptions,\n id = data.id,\n playsInline = true,\n controls = true,\n sourceProps = {},\n ...passthroughProps\n } = props;\n\n const posterUrl = shopifyLoader({\n src: data.previewImage?.url ?? '',\n ...previewImageOptions,\n });\n\n if (!data.sources) {\n throw new Error(`<Video/> requires a 'data.sources' array`);\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/media-has-caption\n <video\n {...passthroughProps}\n id={id}\n playsInline={playsInline}\n controls={controls}\n poster={posterUrl}\n ref={ref}\n >\n {data.sources.map((source) => {\n if (!(source?.url && source?.mimeType)) {\n throw new Error(`<Video/> needs 'source.url' and 'source.mimeType'`);\n }\n return (\n <source\n {...sourceProps}\n key={source.url}\n src={source.url}\n type={source.mimeType}\n />\n );\n })}\n </video>\n );\n});\n"],"names":["forwardRef","shopifyLoader","jsx","createElement"],"mappings":";;;;;AAmBO,MAAM,QAAQA,MAAA,WAGnB,CAAC,OAAO,QAAqB;;AACvB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA,KAAK,KAAK;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,cAAc,CAAC;AAAA,IACf,GAAG;AAAA,EAAA,IACD;AAEJ,QAAM,YAAYC,MAAAA,cAAc;AAAA,IAC9B,OAAK,UAAK,iBAAL,mBAAmB,QAAO;AAAA,IAC/B,GAAG;AAAA,EAAA,CACJ;AAEG,MAAA,CAAC,KAAK,SAAS;AACX,UAAA,IAAI,MAAM,0CAA0C;AAAA,EAAA;AAG5D;AAAA;AAAA,IAEEC,2BAAA;AAAA,MAAC;AAAA,MAAA;AAAA,QACE,GAAG;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QAEC,UAAK,KAAA,QAAQ,IAAI,CAAC,WAAW;AAC5B,cAAI,GAAE,iCAAQ,SAAO,iCAAQ,YAAW;AAChC,kBAAA,IAAI,MAAM,mDAAmD;AAAA,UAAA;AAGnE,iBAAAC,sBAAA;AAAA,YAAC;AAAA,YAAA;AAAA,cACE,GAAG;AAAA,cACJ,KAAK,OAAO;AAAA,cACZ,KAAK,OAAO;AAAA,cACZ,MAAM,OAAO;AAAA,YAAA;AAAA,UACf;AAAA,QAEH,CAAA;AAAA,MAAA;AAAA,IAAA;AAAA;AAGP,CAAC;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Video.mjs","sources":["../../src/Video.tsx"],"sourcesContent":["import {forwardRef, type HTMLAttributes} from 'react';\nimport {shopifyLoader} from './Image.js';\nimport type {Video as VideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface VideoProps {\n /** An object with fields that correspond to the Storefront API's [Video object](https://shopify.dev/api/storefront/2025-01/objects/video). */\n data: PartialDeep<VideoType, {recurseIntoArrays: true}>;\n /** An object of image size options for the video's `previewImage`. Uses `shopifyImageLoader` to generate the `poster` URL. */\n previewImageOptions?: Parameters<typeof shopifyLoader>[0];\n /** Props that will be passed to the `video` element's `source` children elements. */\n sourceProps?: HTMLAttributes<HTMLSourceElement> & {\n 'data-testid'?: string;\n };\n}\n\n/**\n * The `Video` component renders a `video` for the Storefront API's [Video object](https://shopify.dev/api/storefront/reference/products/video).\n */\nexport const Video = forwardRef<\n HTMLVideoElement,\n JSX.IntrinsicElements['video'] & VideoProps\n>((props, ref): JSX.Element => {\n const {\n data,\n previewImageOptions,\n id = data.id,\n playsInline = true,\n controls = true,\n sourceProps = {},\n ...passthroughProps\n } = props;\n\n const posterUrl = shopifyLoader({\n src: data.previewImage?.url ?? '',\n ...previewImageOptions,\n });\n\n if (!data.sources) {\n throw new Error(`<Video/> requires a 'data.sources' array`);\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/media-has-caption\n <video\n {...passthroughProps}\n id={id}\n playsInline={playsInline}\n controls={controls}\n poster={posterUrl}\n ref={ref}\n >\n {data.sources.map((source) => {\n if (!(source?.url && source?.mimeType)) {\n throw new Error(`<Video/> needs 'source.url' and 'source.mimeType'`);\n }\n return (\n <source\n {...sourceProps}\n key={source.url}\n src={source.url}\n type={source.mimeType}\n />\n );\n })}\n </video>\n );\n});\n"],"names":[],"mappings":";;;AAmBO,MAAM,QAAQ,WAGnB,CAAC,OAAO,QAAqB;;AACvB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA,KAAK,KAAK;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,cAAc,CAAC;AAAA,IACf,GAAG;AAAA,EAAA,IACD;AAEJ,QAAM,YAAY,cAAc;AAAA,IAC9B,OAAK,UAAK,iBAAL,mBAAmB,QAAO;AAAA,IAC/B,GAAG;AAAA,EAAA,CACJ;AAEG,MAAA,CAAC,KAAK,SAAS;AACX,UAAA,IAAI,MAAM,0CAA0C;AAAA,EAAA;AAG5D;AAAA;AAAA,IAEE;AAAA,MAAC;AAAA,MAAA;AAAA,QACE,GAAG;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QAEC,UAAK,KAAA,QAAQ,IAAI,CAAC,WAAW;AAC5B,cAAI,GAAE,iCAAQ,SAAO,iCAAQ,YAAW;AAChC,kBAAA,IAAI,MAAM,mDAAmD;AAAA,UAAA;AAGnE,iBAAA;AAAA,YAAC;AAAA,YAAA;AAAA,cACE,GAAG;AAAA,cACJ,KAAK,OAAO;AAAA,cACZ,KAAK,OAAO;AAAA,cACZ,MAAM,OAAO;AAAA,YAAA;AAAA,UACf;AAAA,QAEH,CAAA;AAAA,MAAA;AAAA,IAAA;AAAA;AAGP,CAAC;"}
1
+ {"version":3,"file":"Video.mjs","sources":["../../src/Video.tsx"],"sourcesContent":["import {forwardRef, type HTMLAttributes} from 'react';\nimport {shopifyLoader} from './Image.js';\nimport type {Video as VideoType} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nexport interface VideoProps {\n /** An object with fields that correspond to the Storefront API's [Video object](https://shopify.dev/api/storefront/2025-04/objects/video). */\n data: PartialDeep<VideoType, {recurseIntoArrays: true}>;\n /** An object of image size options for the video's `previewImage`. Uses `shopifyImageLoader` to generate the `poster` URL. */\n previewImageOptions?: Parameters<typeof shopifyLoader>[0];\n /** Props that will be passed to the `video` element's `source` children elements. */\n sourceProps?: HTMLAttributes<HTMLSourceElement> & {\n 'data-testid'?: string;\n };\n}\n\n/**\n * The `Video` component renders a `video` for the Storefront API's [Video object](https://shopify.dev/api/storefront/reference/products/video).\n */\nexport const Video = forwardRef<\n HTMLVideoElement,\n JSX.IntrinsicElements['video'] & VideoProps\n>((props, ref): JSX.Element => {\n const {\n data,\n previewImageOptions,\n id = data.id,\n playsInline = true,\n controls = true,\n sourceProps = {},\n ...passthroughProps\n } = props;\n\n const posterUrl = shopifyLoader({\n src: data.previewImage?.url ?? '',\n ...previewImageOptions,\n });\n\n if (!data.sources) {\n throw new Error(`<Video/> requires a 'data.sources' array`);\n }\n\n return (\n // eslint-disable-next-line jsx-a11y/media-has-caption\n <video\n {...passthroughProps}\n id={id}\n playsInline={playsInline}\n controls={controls}\n poster={posterUrl}\n ref={ref}\n >\n {data.sources.map((source) => {\n if (!(source?.url && source?.mimeType)) {\n throw new Error(`<Video/> needs 'source.url' and 'source.mimeType'`);\n }\n return (\n <source\n {...sourceProps}\n key={source.url}\n src={source.url}\n type={source.mimeType}\n />\n );\n })}\n </video>\n );\n});\n"],"names":[],"mappings":";;;AAmBO,MAAM,QAAQ,WAGnB,CAAC,OAAO,QAAqB;;AACvB,QAAA;AAAA,IACJ;AAAA,IACA;AAAA,IACA,KAAK,KAAK;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,cAAc,CAAC;AAAA,IACf,GAAG;AAAA,EAAA,IACD;AAEJ,QAAM,YAAY,cAAc;AAAA,IAC9B,OAAK,UAAK,iBAAL,mBAAmB,QAAO;AAAA,IAC/B,GAAG;AAAA,EAAA,CACJ;AAEG,MAAA,CAAC,KAAK,SAAS;AACX,UAAA,IAAI,MAAM,0CAA0C;AAAA,EAAA;AAG5D;AAAA;AAAA,IAEE;AAAA,MAAC;AAAA,MAAA;AAAA,QACE,GAAG;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QAEC,UAAK,KAAA,QAAQ,IAAI,CAAC,WAAW;AAC5B,cAAI,GAAE,iCAAQ,SAAO,iCAAQ,YAAW;AAChC,kBAAA,IAAI,MAAM,mDAAmD;AAAA,UAAA;AAGnE,iBAAA;AAAA,YAAC;AAAA,YAAA;AAAA,cACE,GAAG;AAAA,cACJ,KAAK,OAAO;AAAA,cACZ,KAAK,OAAO;AAAA,cACZ,MAAM,OAAO;AAAA,YAAA;AAAA,UACf;AAAA,QAEH,CAAA;AAAA,MAAA;AAAA,IAAA;AAAA;AAGP,CAAC;"}
@@ -1 +1 @@
1
- {"version":3,"file":"codegen.helpers.js","sources":["../../src/codegen.helpers.ts"],"sourcesContent":["/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/storefront/2025-01/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const storefrontApiCustomScalars = {\n // Keep in sync with the definitions in the app/nextjs/codegen.ts!\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n URL: 'string',\n Color: 'string',\n UnsignedInt64: 'string',\n};\n\n/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/customer/2025-01/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const customerAccountApiCustomScalars = {\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n ISO8601DateTime: 'string',\n URL: 'string',\n UnsignedInt64: 'string',\n};\n"],"names":[],"mappings":";;AAKO,MAAM,6BAA6B;AAAA;AAAA,EAExC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AAAA,EACP,eAAe;AACjB;AAOO,MAAM,kCAAkC;AAAA,EAC7C,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,iBAAiB;AAAA,EACjB,KAAK;AAAA,EACL,eAAe;AACjB;;;"}
1
+ {"version":3,"file":"codegen.helpers.js","sources":["../../src/codegen.helpers.ts"],"sourcesContent":["/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/storefront/2025-04/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const storefrontApiCustomScalars = {\n // Keep in sync with the definitions in the app/nextjs/codegen.ts!\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n URL: 'string',\n Color: 'string',\n UnsignedInt64: 'string',\n};\n\n/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/customer/2025-04/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const customerAccountApiCustomScalars = {\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n ISO8601DateTime: 'string',\n URL: 'string',\n UnsignedInt64: 'string',\n};\n"],"names":[],"mappings":";;AAKO,MAAM,6BAA6B;AAAA;AAAA,EAExC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AAAA,EACP,eAAe;AACjB;AAOO,MAAM,kCAAkC;AAAA,EAC7C,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,iBAAiB;AAAA,EACjB,KAAK;AAAA,EACL,eAAe;AACjB;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"codegen.helpers.mjs","sources":["../../src/codegen.helpers.ts"],"sourcesContent":["/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/storefront/2025-01/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const storefrontApiCustomScalars = {\n // Keep in sync with the definitions in the app/nextjs/codegen.ts!\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n URL: 'string',\n Color: 'string',\n UnsignedInt64: 'string',\n};\n\n/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/customer/2025-01/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const customerAccountApiCustomScalars = {\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n ISO8601DateTime: 'string',\n URL: 'string',\n UnsignedInt64: 'string',\n};\n"],"names":[],"mappings":"AAKO,MAAM,6BAA6B;AAAA;AAAA,EAExC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AAAA,EACP,eAAe;AACjB;AAOO,MAAM,kCAAkC;AAAA,EAC7C,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,iBAAiB;AAAA,EACjB,KAAK;AAAA,EACL,eAAe;AACjB;"}
1
+ {"version":3,"file":"codegen.helpers.mjs","sources":["../../src/codegen.helpers.ts"],"sourcesContent":["/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/storefront/2025-04/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const storefrontApiCustomScalars = {\n // Keep in sync with the definitions in the app/nextjs/codegen.ts!\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n URL: 'string',\n Color: 'string',\n UnsignedInt64: 'string',\n};\n\n/**\n * Meant to be used with GraphQL CodeGen to type the Storefront API's custom scalars correctly.\n * Reference for the GraphQL types: https://shopify.dev/docs/api/customer/2025-04/scalars/HTML\n * Note: JSON is generated as 'unknown' by default.\n */\nexport const customerAccountApiCustomScalars = {\n DateTime: 'string',\n Decimal: 'string',\n HTML: 'string',\n ISO8601DateTime: 'string',\n URL: 'string',\n UnsignedInt64: 'string',\n};\n"],"names":[],"mappings":"AAKO,MAAM,6BAA6B;AAAA;AAAA,EAExC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AAAA,EACP,eAAe;AACjB;AAOO,MAAM,kCAAkC;AAAA,EAC7C,UAAU;AAAA,EACV,SAAS;AAAA,EACT,MAAM;AAAA,EACN,iBAAiB;AAAA,EACjB,KAAK;AAAA,EACL,eAAe;AACjB;"}
@@ -1 +1 @@
1
- {"version":3,"file":"optionValueDecoder.js","sources":["../../src/optionValueDecoder.ts"],"sourcesContent":["/**\n * This file provides utility functions for determining whether or not an option value combination is present in an encoded option value string.\n *\n * In V1 of the encoding strategy, option value arrays are encoded as a trie with the following rules:\n * - `:` `,` ` ` and `-` are control characters.\n * - `:` indicates a new option. ex: 0:1 indicates value 0 for the option in position 1, value 1 for the option in position 2.\n * - `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * - ` ` indicates a gap in the sequence of option values. ex: `0 4` indicates option values in position 0 and 4 are present.\n * - `-` indicates a continuous range of option values. ex: `0 1-3 4`. Ranges are only present encoded in the final option value position, so for example the trie for the set [[0,0,0],[0,0,1], ..., [0,2,2]] will be structured as `0:0:0-2,1:0-2,2:0-2`, not `0:0-2:0-2`.\n */\n\nimport {Product} from './storefront-api-types.js';\n\nconst OPTION_VALUE_SEPARATOR = ',';\n\nconst V1_CONTROL_CHARS = {\n OPTION: ':',\n END_OF_PREFIX: ',',\n SEQUENCE_GAP: ' ',\n RANGE: '-',\n};\n\nexport type IsOptionValueCombinationInEncodedVariant = (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n) => boolean;\n\n/**\n * Determine whether an option value combination is present in an encoded option value string. Function is memoized by encodedVariantField.\n *\n * @param targetOptionValueCombination - Indices of option values to look up in the encoded option value string. A partial set of indices may be passed to determine whether a node or any children is present. For example, if a product has 3 options, passing [0] will return true if any option value combination for the first option's option value is present in the encoded string.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantavailability)\n * @returns - True if a full or partial targetOptionValueIndices is present in the encoded option value string, false otherwise.\n */\nexport const isOptionValueCombinationInEncodedVariant: IsOptionValueCombinationInEncodedVariant =\n ((): IsOptionValueCombinationInEncodedVariant => {\n const decodedOptionValues = new Map<string, Set<string>>();\n\n return function (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n ): boolean {\n if (targetOptionValueCombination.length === 0) {\n return false;\n }\n\n if (!decodedOptionValues.has(encodedVariantField)) {\n const decodedOptionValuesSet = new Set<string>();\n\n for (const optionValue of decodeEncodedVariant(encodedVariantField)) {\n // add the complete option value to the decoded option values set\n decodedOptionValuesSet.add(optionValue.join(OPTION_VALUE_SEPARATOR));\n\n // add all composite parts of the option value to the decoded option values set. e.g. if the option value is [0,1,2], add \"0\", \"0,1\", \"0,1,2\"\n for (let i = 0; i < optionValue.length; i++) {\n decodedOptionValuesSet.add(\n optionValue.slice(0, i + 1).join(OPTION_VALUE_SEPARATOR),\n );\n }\n }\n\n decodedOptionValues.set(encodedVariantField, decodedOptionValuesSet);\n }\n\n return Boolean(\n decodedOptionValues\n .get(encodedVariantField)\n ?.has(targetOptionValueCombination.join(OPTION_VALUE_SEPARATOR)),\n );\n };\n })();\n\ntype EncodedVariantField =\n | Product['encodedVariantAvailability']\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n | Product['encodedVariantExistence'];\ntype DecodedOptionValues = number[][];\n\n/**\n * For an encoded option value string, decode into option value combinations. Entries represent a valid combination formatted as an array of option value positions.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantavailability)\n * @returns Decoded option value combinations\n */\nexport function decodeEncodedVariant(\n encodedVariantField: EncodedVariantField,\n): DecodedOptionValues {\n if (!encodedVariantField) return [];\n\n if (encodedVariantField.startsWith('v1_')) {\n return v1Decoder(stripVersion(encodedVariantField));\n }\n\n throw new Error('Unsupported option value encoding');\n}\n\nconst stripVersion: (encodedVariantField: string) => string = (\n encodedVariantField: string,\n) => encodedVariantField.replace(/^v1_/, '');\n\n/**\n * We encode an array of arrays representing variants, expressed in terms of options and option values, as a trie.\n *\n * This encoding strategy allows extremely large numbers of variants to be expressed in an extremely compact data structure.\n *\n * Integers represent option and values, so [0,0,0] represents option_value at array index 0 for the options at array indexes 0, 1 and 2\n *\n * `:`, `,`, ` ` and `-` are control characters.\n * `:` indicates a new option\n * `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * ` ` indicates a gap in the sequence of option values\n * `-` indicates a continuous range of option values\n *\n * Encoding process:\n *\n * example input array: [[0,0,0], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,1], [2,0,1], [2,1,0]]\n *\n * step 1: encode as string: \"0:0:0,0:1:0,0:1:1,1:0:0,1:0:1,1:1:1,2:0:1,2:1:0,\"\n * step 2: combine nodes that share a prefix: \"0:0:0,0:1:0 1,1:0:0 1,1:1:1,2:0:1,2:1:0,\"\n * step 3: encode data as a trie so no prefixes need to be repeated: \"0:0:0,1:0 1,,1:0:0 1,1:1,,2:0:1,1:0,,\"\n * step 4: since the options are sorted, use a dash to express ranges: \"0:0:0,1:0-1,,1:0:0-1,1:1,,2:0:1,1:0,,\"\n */\nfunction v1Decoder(encodedVariantField: string): number[][] {\n const tokenizer = /[ :,-]/g;\n let index = 0;\n let token: RegExpExecArray | null;\n const options: number[][] = [];\n const currentOptionValue: number[] = [];\n let depth = 0;\n let rangeStart: number | null = null;\n\n // iterate over control characters\n while ((token = tokenizer.exec(encodedVariantField))) {\n const operation = token[0];\n const optionValueIndex =\n Number.parseInt(encodedVariantField.slice(index, token.index)) || 0;\n\n if (rangeStart !== null) {\n // If a range has been started, iterate over the range and add each option value to the list of options\n // - `rangeStart` is set if the last control char was a dash, e.g. `0` for 0-2. It represents the numeric option value position for the start of the range.\n // - `optionValueIndex` is the numeric option value position for the end of the range\n for (; rangeStart < optionValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n // indicates the range has been processed\n rangeStart = null;\n }\n\n currentOptionValue[depth] = optionValueIndex;\n\n if (operation === V1_CONTROL_CHARS.RANGE) {\n // dash operation indicates we are in a range. e.g. 0-2 means option values 0, 1, 2\n rangeStart = optionValueIndex;\n } else if (operation === V1_CONTROL_CHARS.OPTION) {\n // colon operation indicates that we are moving down to the next layer of option values. e.g. 0:0:0-2 means we traverse down from option1 to option3 and represents [[0,0,0], [0,0,1], [0,0,2]]\n depth++;\n } else {\n if (\n operation === V1_CONTROL_CHARS.SEQUENCE_GAP ||\n (operation === V1_CONTROL_CHARS.END_OF_PREFIX &&\n encodedVariantField[token.index - 1] !==\n V1_CONTROL_CHARS.END_OF_PREFIX)\n ) {\n // add the current option value to the list of options if we hit a gap in our sequence or we are at the end of our depth and need to move back up\n options.push([...currentOptionValue]);\n }\n if (operation === V1_CONTROL_CHARS.END_OF_PREFIX) {\n // go up an option level, trash the last item in currentOptionValue\n currentOptionValue.pop();\n depth--;\n }\n }\n index = tokenizer.lastIndex;\n }\n\n // The while loop only iterates control characters, meaning if an encoded string ends with an index it will not be processed.\n const encodingEndsWithIndex = encodedVariantField.match(/\\d+$/g);\n if (encodingEndsWithIndex) {\n const finalValueIndex = parseInt(encodingEndsWithIndex[0]);\n if (rangeStart != null) {\n // process final range\n for (; rangeStart <= finalValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n } else {\n // process final index\n options.push([finalValueIndex]);\n }\n }\n\n return options;\n}\n"],"names":[],"mappings":";;AAaA,MAAM,yBAAyB;AAE/B,MAAM,mBAAmB;AAAA,EACvB,QAAQ;AAAA,EACR,eAAe;AAAA,EACf,cAAc;AAAA,EACd,OAAO;AACT;AAcO,MAAM,2CACsC,uBAAA;AACzC,QAAA,0CAA0B,IAAyB;AAElD,SAAA,SACL,8BACA,qBACS;;AACL,QAAA,6BAA6B,WAAW,GAAG;AACtC,aAAA;AAAA,IAAA;AAGT,QAAI,CAAC,oBAAoB,IAAI,mBAAmB,GAAG;AAC3C,YAAA,6CAA6B,IAAY;AAEpC,iBAAA,eAAe,qBAAqB,mBAAmB,GAAG;AAEnE,+BAAuB,IAAI,YAAY,KAAK,sBAAsB,CAAC;AAGnE,iBAAS,IAAI,GAAG,IAAI,YAAY,QAAQ,KAAK;AACpB,iCAAA;AAAA,YACrB,YAAY,MAAM,GAAG,IAAI,CAAC,EAAE,KAAK,sBAAsB;AAAA,UACzD;AAAA,QAAA;AAAA,MACF;AAGkB,0BAAA,IAAI,qBAAqB,sBAAsB;AAAA,IAAA;AAG9D,WAAA;AAAA,OACL,yBACG,IAAI,mBA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AU;AAAA,EAAA;AAId,QAAA,wBAAwB,oBAAoB,MAAM,OAAO;AAC/D,MAAI,uBAAuB;AACzB,UAAM,kBAAkB,SAAS,sBAAsB,CAAC,CAAC;AACzD,QAAI,cAAc,MAAM;AAEf,aAAA,cAAc,iBAAiB,cAAc;AAClD,2BAAmB,KAAK,IAAI;AAC5B,gBAAQ,KAAK,CAAC,GAAG,kBAAkB,CAAC;AAAA,MAAA;AAAA,IACtC,OACK;AAEG,cAAA,KAAK,CAAC,eAAe,CAAC;AAAA,IAAA;AAAA,EAChC;AAGK,SAAA;AACT;;;"}
1
+ {"version":3,"file":"optionValueDecoder.js","sources":["../../src/optionValueDecoder.ts"],"sourcesContent":["/**\n * This file provides utility functions for determining whether or not an option value combination is present in an encoded option value string.\n *\n * In V1 of the encoding strategy, option value arrays are encoded as a trie with the following rules:\n * - `:` `,` ` ` and `-` are control characters.\n * - `:` indicates a new option. ex: 0:1 indicates value 0 for the option in position 1, value 1 for the option in position 2.\n * - `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * - ` ` indicates a gap in the sequence of option values. ex: `0 4` indicates option values in position 0 and 4 are present.\n * - `-` indicates a continuous range of option values. ex: `0 1-3 4`. Ranges are only present encoded in the final option value position, so for example the trie for the set [[0,0,0],[0,0,1], ..., [0,2,2]] will be structured as `0:0:0-2,1:0-2,2:0-2`, not `0:0-2:0-2`.\n */\n\nimport {Product} from './storefront-api-types.js';\n\nconst OPTION_VALUE_SEPARATOR = ',';\n\nconst V1_CONTROL_CHARS = {\n OPTION: ':',\n END_OF_PREFIX: ',',\n SEQUENCE_GAP: ' ',\n RANGE: '-',\n};\n\nexport type IsOptionValueCombinationInEncodedVariant = (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n) => boolean;\n\n/**\n * Determine whether an option value combination is present in an encoded option value string. Function is memoized by encodedVariantField.\n *\n * @param targetOptionValueCombination - Indices of option values to look up in the encoded option value string. A partial set of indices may be passed to determine whether a node or any children is present. For example, if a product has 3 options, passing [0] will return true if any option value combination for the first option's option value is present in the encoded string.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantavailability)\n * @returns - True if a full or partial targetOptionValueIndices is present in the encoded option value string, false otherwise.\n */\nexport const isOptionValueCombinationInEncodedVariant: IsOptionValueCombinationInEncodedVariant =\n ((): IsOptionValueCombinationInEncodedVariant => {\n const decodedOptionValues = new Map<string, Set<string>>();\n\n return function (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n ): boolean {\n if (targetOptionValueCombination.length === 0) {\n return false;\n }\n\n if (!decodedOptionValues.has(encodedVariantField)) {\n const decodedOptionValuesSet = new Set<string>();\n\n for (const optionValue of decodeEncodedVariant(encodedVariantField)) {\n // add the complete option value to the decoded option values set\n decodedOptionValuesSet.add(optionValue.join(OPTION_VALUE_SEPARATOR));\n\n // add all composite parts of the option value to the decoded option values set. e.g. if the option value is [0,1,2], add \"0\", \"0,1\", \"0,1,2\"\n for (let i = 0; i < optionValue.length; i++) {\n decodedOptionValuesSet.add(\n optionValue.slice(0, i + 1).join(OPTION_VALUE_SEPARATOR),\n );\n }\n }\n\n decodedOptionValues.set(encodedVariantField, decodedOptionValuesSet);\n }\n\n return Boolean(\n decodedOptionValues\n .get(encodedVariantField)\n ?.has(targetOptionValueCombination.join(OPTION_VALUE_SEPARATOR)),\n );\n };\n })();\n\ntype EncodedVariantField =\n | Product['encodedVariantAvailability']\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n | Product['encodedVariantExistence'];\ntype DecodedOptionValues = number[][];\n\n/**\n * For an encoded option value string, decode into option value combinations. Entries represent a valid combination formatted as an array of option value positions.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantavailability)\n * @returns Decoded option value combinations\n */\nexport function decodeEncodedVariant(\n encodedVariantField: EncodedVariantField,\n): DecodedOptionValues {\n if (!encodedVariantField) return [];\n\n if (encodedVariantField.startsWith('v1_')) {\n return v1Decoder(stripVersion(encodedVariantField));\n }\n\n throw new Error('Unsupported option value encoding');\n}\n\nconst stripVersion: (encodedVariantField: string) => string = (\n encodedVariantField: string,\n) => encodedVariantField.replace(/^v1_/, '');\n\n/**\n * We encode an array of arrays representing variants, expressed in terms of options and option values, as a trie.\n *\n * This encoding strategy allows extremely large numbers of variants to be expressed in an extremely compact data structure.\n *\n * Integers represent option and values, so [0,0,0] represents option_value at array index 0 for the options at array indexes 0, 1 and 2\n *\n * `:`, `,`, ` ` and `-` are control characters.\n * `:` indicates a new option\n * `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * ` ` indicates a gap in the sequence of option values\n * `-` indicates a continuous range of option values\n *\n * Encoding process:\n *\n * example input array: [[0,0,0], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,1], [2,0,1], [2,1,0]]\n *\n * step 1: encode as string: \"0:0:0,0:1:0,0:1:1,1:0:0,1:0:1,1:1:1,2:0:1,2:1:0,\"\n * step 2: combine nodes that share a prefix: \"0:0:0,0:1:0 1,1:0:0 1,1:1:1,2:0:1,2:1:0,\"\n * step 3: encode data as a trie so no prefixes need to be repeated: \"0:0:0,1:0 1,,1:0:0 1,1:1,,2:0:1,1:0,,\"\n * step 4: since the options are sorted, use a dash to express ranges: \"0:0:0,1:0-1,,1:0:0-1,1:1,,2:0:1,1:0,,\"\n */\nfunction v1Decoder(encodedVariantField: string): number[][] {\n const tokenizer = /[ :,-]/g;\n let index = 0;\n let token: RegExpExecArray | null;\n const options: number[][] = [];\n const currentOptionValue: number[] = [];\n let depth = 0;\n let rangeStart: number | null = null;\n\n // iterate over control characters\n while ((token = tokenizer.exec(encodedVariantField))) {\n const operation = token[0];\n const optionValueIndex =\n Number.parseInt(encodedVariantField.slice(index, token.index)) || 0;\n\n if (rangeStart !== null) {\n // If a range has been started, iterate over the range and add each option value to the list of options\n // - `rangeStart` is set if the last control char was a dash, e.g. `0` for 0-2. It represents the numeric option value position for the start of the range.\n // - `optionValueIndex` is the numeric option value position for the end of the range\n for (; rangeStart < optionValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n // indicates the range has been processed\n rangeStart = null;\n }\n\n currentOptionValue[depth] = optionValueIndex;\n\n if (operation === V1_CONTROL_CHARS.RANGE) {\n // dash operation indicates we are in a range. e.g. 0-2 means option values 0, 1, 2\n rangeStart = optionValueIndex;\n } else if (operation === V1_CONTROL_CHARS.OPTION) {\n // colon operation indicates that we are moving down to the next layer of option values. e.g. 0:0:0-2 means we traverse down from option1 to option3 and represents [[0,0,0], [0,0,1], [0,0,2]]\n depth++;\n } else {\n if (\n operation === V1_CONTROL_CHARS.SEQUENCE_GAP ||\n (operation === V1_CONTROL_CHARS.END_OF_PREFIX &&\n encodedVariantField[token.index - 1] !==\n V1_CONTROL_CHARS.END_OF_PREFIX)\n ) {\n // add the current option value to the list of options if we hit a gap in our sequence or we are at the end of our depth and need to move back up\n options.push([...currentOptionValue]);\n }\n if (operation === V1_CONTROL_CHARS.END_OF_PREFIX) {\n // go up an option level, trash the last item in currentOptionValue\n currentOptionValue.pop();\n depth--;\n }\n }\n index = tokenizer.lastIndex;\n }\n\n // The while loop only iterates control characters, meaning if an encoded string ends with an index it will not be processed.\n const encodingEndsWithIndex = encodedVariantField.match(/\\d+$/g);\n if (encodingEndsWithIndex) {\n const finalValueIndex = parseInt(encodingEndsWithIndex[0]);\n if (rangeStart != null) {\n // process final range\n for (; rangeStart <= finalValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n } else {\n // process final index\n options.push([finalValueIndex]);\n }\n }\n\n return options;\n}\n"],"names":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,GAAI;AAC9C,UAAA,YAAY,MAAM,CAAC;AACnB,UAAA,mBACJ,OAAO,SAAS,oBAAoB,MAAM,OAAO,MAAM,KAAK,CAAC,KAAK;AAEpE,QAAI,eAAe,MAAM;AAIhB,aAAA,aAAa,kBAAkB,cAAc;AAClD,2BAAmB,KAAK,IAAI;AAC5B,gBAAQ,KAAK,CAAC,GAAG,kBAAkB,CAAC;AAAA,MAAA;AAGzB,mBAAA;AAAA,IAAA;AAGf,uBAAmB,KAAK,IAAI;AAExB,QAAA,cAAc,iBAAiB,OAAO;AAE3B,mBAAA;AAAA,IAAA,WACJ,cAAc,iBAAiB,QAAQ;AAEhD;AAAA,IAAA,OACK;AACL,UACE,cAAc,iBAAiB,gBAC9B,cAAc,iBAAiB,iBAC9B,oBAAoB,MAAM,QAAQ,CAAC,MACjC,iBAAiB,eACrB;AAEA,gBAAQ,KAAK,CAAC,GAAG,kBAAkB,CAAC;AAAA,MAAA;AAElC,UAAA,cAAc,iBAAiB,eAAe;AAEhD,2BAAmB,IAAI;AACvB;AAAA,MAAA;AAAA,IACF;AAEF,YAAQ,UAAU;AAAA,EAAA;AAId,QAAA,wBAAwB,oBAAoB,MAAM,OAAO;AAC/D,MAAI,uBAAuB;AACzB,UAAM,kBAAkB,SAAS,sBAAsB,CAAC,CAAC;AACzD,QAAI,cAAc,MAAM;AAEf,aAAA,cAAc,iBAAiB,cAAc;AAClD,2BAAmB,KAAK,IAAI;AAC5B,gBAAQ,KAAK,CAAC,GAAG,kBAAkB,CAAC;AAAA,MAAA;AAAA,IACtC,OACK;AAEG,cAAA,KAAK,CAAC,eAAe,CAAC;AAAA,IAAA;AAAA,EAChC;AAGK,SAAA;AACT;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"optionValueDecoder.mjs","sources":["../../src/optionValueDecoder.ts"],"sourcesContent":["/**\n * This file provides utility functions for determining whether or not an option value combination is present in an encoded option value string.\n *\n * In V1 of the encoding strategy, option value arrays are encoded as a trie with the following rules:\n * - `:` `,` ` ` and `-` are control characters.\n * - `:` indicates a new option. ex: 0:1 indicates value 0 for the option in position 1, value 1 for the option in position 2.\n * - `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * - ` ` indicates a gap in the sequence of option values. ex: `0 4` indicates option values in position 0 and 4 are present.\n * - `-` indicates a continuous range of option values. ex: `0 1-3 4`. Ranges are only present encoded in the final option value position, so for example the trie for the set [[0,0,0],[0,0,1], ..., [0,2,2]] will be structured as `0:0:0-2,1:0-2,2:0-2`, not `0:0-2:0-2`.\n */\n\nimport {Product} from './storefront-api-types.js';\n\nconst OPTION_VALUE_SEPARATOR = ',';\n\nconst V1_CONTROL_CHARS = {\n OPTION: ':',\n END_OF_PREFIX: ',',\n SEQUENCE_GAP: ' ',\n RANGE: '-',\n};\n\nexport type IsOptionValueCombinationInEncodedVariant = (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n) => boolean;\n\n/**\n * Determine whether an option value combination is present in an encoded option value string. Function is memoized by encodedVariantField.\n *\n * @param targetOptionValueCombination - Indices of option values to look up in the encoded option value string. A partial set of indices may be passed to determine whether a node or any children is present. For example, if a product has 3 options, passing [0] will return true if any option value combination for the first option's option value is present in the encoded string.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantavailability)\n * @returns - True if a full or partial targetOptionValueIndices is present in the encoded option value string, false otherwise.\n */\nexport const isOptionValueCombinationInEncodedVariant: IsOptionValueCombinationInEncodedVariant =\n ((): IsOptionValueCombinationInEncodedVariant => {\n const decodedOptionValues = new Map<string, Set<string>>();\n\n return function (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n ): boolean {\n if (targetOptionValueCombination.length === 0) {\n return false;\n }\n\n if (!decodedOptionValues.has(encodedVariantField)) {\n const decodedOptionValuesSet = new Set<string>();\n\n for (const optionValue of decodeEncodedVariant(encodedVariantField)) {\n // add the complete option value to the decoded option values set\n decodedOptionValuesSet.add(optionValue.join(OPTION_VALUE_SEPARATOR));\n\n // add all composite parts of the option value to the decoded option values set. e.g. if the option value is [0,1,2], add \"0\", \"0,1\", \"0,1,2\"\n for (let i = 0; i < optionValue.length; i++) {\n decodedOptionValuesSet.add(\n optionValue.slice(0, i + 1).join(OPTION_VALUE_SEPARATOR),\n );\n }\n }\n\n decodedOptionValues.set(encodedVariantField, decodedOptionValuesSet);\n }\n\n return Boolean(\n decodedOptionValues\n .get(encodedVariantField)\n ?.has(targetOptionValueCombination.join(OPTION_VALUE_SEPARATOR)),\n );\n };\n })();\n\ntype EncodedVariantField =\n | Product['encodedVariantAvailability']\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n | Product['encodedVariantExistence'];\ntype DecodedOptionValues = number[][];\n\n/**\n * For an encoded option value string, decode into option value combinations. Entries represent a valid combination formatted as an array of option value positions.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-01/objects/Product#field-encodedvariantavailability)\n * @returns Decoded option value combinations\n */\nexport function decodeEncodedVariant(\n encodedVariantField: EncodedVariantField,\n): DecodedOptionValues {\n if (!encodedVariantField) return [];\n\n if (encodedVariantField.startsWith('v1_')) {\n return v1Decoder(stripVersion(encodedVariantField));\n }\n\n throw new Error('Unsupported option value encoding');\n}\n\nconst stripVersion: (encodedVariantField: string) => string = (\n encodedVariantField: string,\n) => encodedVariantField.replace(/^v1_/, '');\n\n/**\n * We encode an array of arrays representing variants, expressed in terms of options and option values, as a trie.\n *\n * This encoding strategy allows extremely large numbers of variants to be expressed in an extremely compact data structure.\n *\n * Integers represent option and values, so [0,0,0] represents option_value at array index 0 for the options at array indexes 0, 1 and 2\n *\n * `:`, `,`, ` ` and `-` are control characters.\n * `:` indicates a new option\n * `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * ` ` indicates a gap in the sequence of option values\n * `-` indicates a continuous range of option values\n *\n * Encoding process:\n *\n * example input array: [[0,0,0], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,1], [2,0,1], [2,1,0]]\n *\n * step 1: encode as string: \"0:0:0,0:1:0,0:1:1,1:0:0,1:0:1,1:1:1,2:0:1,2:1:0,\"\n * step 2: combine nodes that share a prefix: \"0:0:0,0:1:0 1,1:0:0 1,1:1:1,2:0:1,2:1:0,\"\n * step 3: encode data as a trie so no prefixes need to be repeated: \"0:0:0,1:0 1,,1:0:0 1,1:1,,2:0:1,1:0,,\"\n * step 4: since the options are sorted, use a dash to express ranges: \"0:0:0,1:0-1,,1:0:0-1,1:1,,2:0:1,1:0,,\"\n */\nfunction v1Decoder(encodedVariantField: string): number[][] {\n const tokenizer = /[ :,-]/g;\n let index = 0;\n let token: RegExpExecArray | null;\n const options: number[][] = [];\n const currentOptionValue: number[] = [];\n let depth = 0;\n let rangeStart: number | null = null;\n\n // iterate over control characters\n while ((token = tokenizer.exec(encodedVariantField))) {\n const operation = token[0];\n const optionValueIndex =\n Number.parseInt(encodedVariantField.slice(index, token.index)) || 0;\n\n if (rangeStart !== null) {\n // If a range has been started, iterate over the range and add each option value to the list of options\n // - `rangeStart` is set if the last control char was a dash, e.g. `0` for 0-2. It represents the numeric option value position for the start of the range.\n // - `optionValueIndex` is the numeric option value position for the end of the range\n for (; rangeStart < optionValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n // indicates the range has been processed\n rangeStart = null;\n }\n\n currentOptionValue[depth] = optionValueIndex;\n\n if (operation === V1_CONTROL_CHARS.RANGE) {\n // dash operation indicates we are in a range. e.g. 0-2 means option values 0, 1, 2\n rangeStart = optionValueIndex;\n } else if (operation === V1_CONTROL_CHARS.OPTION) {\n // colon operation indicates that we are moving down to the next layer of option values. e.g. 0:0:0-2 means we traverse down from option1 to option3 and represents [[0,0,0], [0,0,1], [0,0,2]]\n depth++;\n } else {\n if (\n operation === V1_CONTROL_CHARS.SEQUENCE_GAP ||\n (operation === V1_CONTROL_CHARS.END_OF_PREFIX &&\n encodedVariantField[token.index - 1] !==\n V1_CONTROL_CHARS.END_OF_PREFIX)\n ) {\n // add the current option value to the list of options if we hit a gap in our sequence or we are at the end of our depth and need to move back up\n options.push([...currentOptionValue]);\n }\n if (operation === V1_CONTROL_CHARS.END_OF_PREFIX) {\n // go up an option level, trash the last item in currentOptionValue\n currentOptionValue.pop();\n depth--;\n }\n }\n index = tokenizer.lastIndex;\n }\n\n // The while loop only iterates control characters, meaning if an encoded string ends with an index it will not be processed.\n const encodingEndsWithIndex = encodedVariantField.match(/\\d+$/g);\n if (encodingEndsWithIndex) {\n const finalValueIndex = parseInt(encodingEndsWithIndex[0]);\n if (rangeStart != null) {\n // process final range\n for (; rangeStart <= finalValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n } else {\n // process final index\n options.push([finalValueIndex]);\n }\n }\n\n return options;\n}\n"],"names":[],"mappings":"AAaA,MAAM,yBAAyB;AAE/B,MAAM,mBAAmB;AAAA,EACvB,QAAQ;AAAA,EACR,eAAe;AAAA,EACf,cAAc;AAAA,EACd,OAAO;AACT;AAcO,MAAM,2CACsC,uBAAA;AACzC,QAAA,0CAA0B,IAAyB;AAElD,SAAA,SACL,8BACA,qBACS;AA5Bf;AA6BU,QAAA,6BAA6B,WAAW,GAAG;AACtC,aAAA;AAAA,IAAA;AAGT,QAAI,CAAC,oBAAoB,IAAI,mBAAmB,GAAG;AAC3C,YAAA,6CAA6B,IAAY;AAEpC,iBAAA,eAAe,qBAAqB,mBAAmB,GAAG;AAEnE,+BAAuB,IAAI,YAAY,KAAK,sBAAsB,CAAC;AAGnE,iBAAS,IAAI,GAAG,IAAI,YAAY,QAAQ,KAAK;AACpB,iCAAA;AAAA,YACrB,YAAY,MAAM,G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rB;AAEA,gBAAQ,KAAK,CAAC,GAAG,kBAAkB,CAAC;AAAA,MAAA;AAElC,UAAA,cAAc,iBAAiB,eAAe;AAEhD,2BAAmB,IAAI;AACvB;AAAA,MAAA;AAAA,IACF;AAEF,YAAQ,UAAU;AAAA,EAAA;AAId,QAAA,wBAAwB,oBAAoB,MAAM,OAAO;AAC/D,MAAI,uBAAuB;AACzB,UAAM,kBAAkB,SAAS,sBAAsB,CAAC,CAAC;AACzD,QAAI,cAAc,MAAM;AAEf,aAAA,cAAc,iBAAiB,cAAc;AAClD,2BAAmB,KAAK,IAAI;AAC5B,gBAAQ,KAAK,CAAC,GAAG,kBAAkB,CAAC;AAAA,MAAA;AAAA,IACtC,OACK;AAEG,cAAA,KAAK,CAAC,eAAe,CAAC;AAAA,IAAA;AAAA,EAChC;AAGK,SAAA;AACT;"}
1
+ {"version":3,"file":"optionValueDecoder.mjs","sources":["../../src/optionValueDecoder.ts"],"sourcesContent":["/**\n * This file provides utility functions for determining whether or not an option value combination is present in an encoded option value string.\n *\n * In V1 of the encoding strategy, option value arrays are encoded as a trie with the following rules:\n * - `:` `,` ` ` and `-` are control characters.\n * - `:` indicates a new option. ex: 0:1 indicates value 0 for the option in position 1, value 1 for the option in position 2.\n * - `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * - ` ` indicates a gap in the sequence of option values. ex: `0 4` indicates option values in position 0 and 4 are present.\n * - `-` indicates a continuous range of option values. ex: `0 1-3 4`. Ranges are only present encoded in the final option value position, so for example the trie for the set [[0,0,0],[0,0,1], ..., [0,2,2]] will be structured as `0:0:0-2,1:0-2,2:0-2`, not `0:0-2:0-2`.\n */\n\nimport {Product} from './storefront-api-types.js';\n\nconst OPTION_VALUE_SEPARATOR = ',';\n\nconst V1_CONTROL_CHARS = {\n OPTION: ':',\n END_OF_PREFIX: ',',\n SEQUENCE_GAP: ' ',\n RANGE: '-',\n};\n\nexport type IsOptionValueCombinationInEncodedVariant = (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n) => boolean;\n\n/**\n * Determine whether an option value combination is present in an encoded option value string. Function is memoized by encodedVariantField.\n *\n * @param targetOptionValueCombination - Indices of option values to look up in the encoded option value string. A partial set of indices may be passed to determine whether a node or any children is present. For example, if a product has 3 options, passing [0] will return true if any option value combination for the first option's option value is present in the encoded string.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantavailability)\n * @returns - True if a full or partial targetOptionValueIndices is present in the encoded option value string, false otherwise.\n */\nexport const isOptionValueCombinationInEncodedVariant: IsOptionValueCombinationInEncodedVariant =\n ((): IsOptionValueCombinationInEncodedVariant => {\n const decodedOptionValues = new Map<string, Set<string>>();\n\n return function (\n targetOptionValueCombination: number[],\n encodedVariantField: string,\n ): boolean {\n if (targetOptionValueCombination.length === 0) {\n return false;\n }\n\n if (!decodedOptionValues.has(encodedVariantField)) {\n const decodedOptionValuesSet = new Set<string>();\n\n for (const optionValue of decodeEncodedVariant(encodedVariantField)) {\n // add the complete option value to the decoded option values set\n decodedOptionValuesSet.add(optionValue.join(OPTION_VALUE_SEPARATOR));\n\n // add all composite parts of the option value to the decoded option values set. e.g. if the option value is [0,1,2], add \"0\", \"0,1\", \"0,1,2\"\n for (let i = 0; i < optionValue.length; i++) {\n decodedOptionValuesSet.add(\n optionValue.slice(0, i + 1).join(OPTION_VALUE_SEPARATOR),\n );\n }\n }\n\n decodedOptionValues.set(encodedVariantField, decodedOptionValuesSet);\n }\n\n return Boolean(\n decodedOptionValues\n .get(encodedVariantField)\n ?.has(targetOptionValueCombination.join(OPTION_VALUE_SEPARATOR)),\n );\n };\n })();\n\ntype EncodedVariantField =\n | Product['encodedVariantAvailability']\n // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents\n | Product['encodedVariantExistence'];\ntype DecodedOptionValues = number[][];\n\n/**\n * For an encoded option value string, decode into option value combinations. Entries represent a valid combination formatted as an array of option value positions.\n * @param encodedVariantField - Encoded option value string from the Storefront API, e.g. [product.encodedVariantExistence](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantexistence) or [product.encodedVariantAvailability](/docs/api/storefront/2025-04/objects/Product#field-encodedvariantavailability)\n * @returns Decoded option value combinations\n */\nexport function decodeEncodedVariant(\n encodedVariantField: EncodedVariantField,\n): DecodedOptionValues {\n if (!encodedVariantField) return [];\n\n if (encodedVariantField.startsWith('v1_')) {\n return v1Decoder(stripVersion(encodedVariantField));\n }\n\n throw new Error('Unsupported option value encoding');\n}\n\nconst stripVersion: (encodedVariantField: string) => string = (\n encodedVariantField: string,\n) => encodedVariantField.replace(/^v1_/, '');\n\n/**\n * We encode an array of arrays representing variants, expressed in terms of options and option values, as a trie.\n *\n * This encoding strategy allows extremely large numbers of variants to be expressed in an extremely compact data structure.\n *\n * Integers represent option and values, so [0,0,0] represents option_value at array index 0 for the options at array indexes 0, 1 and 2\n *\n * `:`, `,`, ` ` and `-` are control characters.\n * `:` indicates a new option\n * `,` indicates the end of a repeated prefix, mulitple consecutive commas indicate the end of multiple repeated prefixes.\n * ` ` indicates a gap in the sequence of option values\n * `-` indicates a continuous range of option values\n *\n * Encoding process:\n *\n * example input array: [[0,0,0], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,1], [2,0,1], [2,1,0]]\n *\n * step 1: encode as string: \"0:0:0,0:1:0,0:1:1,1:0:0,1:0:1,1:1:1,2:0:1,2:1:0,\"\n * step 2: combine nodes that share a prefix: \"0:0:0,0:1:0 1,1:0:0 1,1:1:1,2:0:1,2:1:0,\"\n * step 3: encode data as a trie so no prefixes need to be repeated: \"0:0:0,1:0 1,,1:0:0 1,1:1,,2:0:1,1:0,,\"\n * step 4: since the options are sorted, use a dash to express ranges: \"0:0:0,1:0-1,,1:0:0-1,1:1,,2:0:1,1:0,,\"\n */\nfunction v1Decoder(encodedVariantField: string): number[][] {\n const tokenizer = /[ :,-]/g;\n let index = 0;\n let token: RegExpExecArray | null;\n const options: number[][] = [];\n const currentOptionValue: number[] = [];\n let depth = 0;\n let rangeStart: number | null = null;\n\n // iterate over control characters\n while ((token = tokenizer.exec(encodedVariantField))) {\n const operation = token[0];\n const optionValueIndex =\n Number.parseInt(encodedVariantField.slice(index, token.index)) || 0;\n\n if (rangeStart !== null) {\n // If a range has been started, iterate over the range and add each option value to the list of options\n // - `rangeStart` is set if the last control char was a dash, e.g. `0` for 0-2. It represents the numeric option value position for the start of the range.\n // - `optionValueIndex` is the numeric option value position for the end of the range\n for (; rangeStart < optionValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n // indicates the range has been processed\n rangeStart = null;\n }\n\n currentOptionValue[depth] = optionValueIndex;\n\n if (operation === V1_CONTROL_CHARS.RANGE) {\n // dash operation indicates we are in a range. e.g. 0-2 means option values 0, 1, 2\n rangeStart = optionValueIndex;\n } else if (operation === V1_CONTROL_CHARS.OPTION) {\n // colon operation indicates that we are moving down to the next layer of option values. e.g. 0:0:0-2 means we traverse down from option1 to option3 and represents [[0,0,0], [0,0,1], [0,0,2]]\n depth++;\n } else {\n if (\n operation === V1_CONTROL_CHARS.SEQUENCE_GAP ||\n (operation === V1_CONTROL_CHARS.END_OF_PREFIX &&\n encodedVariantField[token.index - 1] !==\n V1_CONTROL_CHARS.END_OF_PREFIX)\n ) {\n // add the current option value to the list of options if we hit a gap in our sequence or we are at the end of our depth and need to move back up\n options.push([...currentOptionValue]);\n }\n if (operation === V1_CONTROL_CHARS.END_OF_PREFIX) {\n // go up an option level, trash the last item in currentOptionValue\n currentOptionValue.pop();\n depth--;\n }\n }\n index = tokenizer.lastIndex;\n }\n\n // The while loop only iterates control characters, meaning if an encoded string ends with an index it will not be processed.\n const encodingEndsWithIndex = encodedVariantField.match(/\\d+$/g);\n if (encodingEndsWithIndex) {\n const finalValueIndex = parseInt(encodingEndsWithIndex[0]);\n if (rangeStart != null) {\n // process final range\n for (; rangeStart <= finalValueIndex; rangeStart++) {\n currentOptionValue[depth] = rangeStart;\n options.push([...currentOptionValue]);\n }\n } else {\n // process final index\n options.push([finalValueIndex]);\n }\n }\n\n return options;\n}\n"],"names":[],"mappings":"AAaA,MAAM,yBAAyB;AAE/B,MAAM,mBAAmB;AAAA,EACvB,QAAQ;AAAA,EACR,eAAe;AAAA,EACf,cAAc;AAAA,EACd,OAAO;AACT;AAcO,MAAM,2CACsC,uBAAA;AACzC,QAAA,0CAA0B,IAAyB;AAElD,SAAA,SACL,8BACA,qBACS;AA5Bf;AA6BU,QAAA,6BAA6B,WAAW,GAAG;AACtC,aAAA;AAAA,IAAA;AAGT,QAAI,CAAC,oBAAoB,IAAI,mBAAmB,GAAG;AAC3C,YAAA,6CAA6B,IAAY;AAEpC,iBAAA,eAAe,qBAAqB,mBAAmB,GAAG;AAEnE,+BAAuB,IAAI,YAAY,KAAK,sBAAsB,CAAC;AAGnE,iBAAS,IAAI,GAAG,IAAI,YAAY,QAAQ,KAAK;AACpB,iCAAA;AAAA,YACrB,YAAY,MAAM,GAAG,IAAI,CAAC,EAAE,KAAK,sBAAsB;AAAA,UACzD;AAAA,QAAA;AAAA,MACF;AAGkB,0BAAA,IAAI,qBAAqB,sBAAsB;AAAA,IAAA;AAG9D,WAAA;AAAA,OACL,yBACG,IAAI,mBAAmB,MAD1B,mBAEI,IAAI,6BAA6B,KAAK,sBAAsB;AAAA,IAClE;AAAA,EACF;AACF,GAAG;AAaE,SAAS,qBACd,qBACqB;AACjB,MAAA,CAAC,oBAAqB,QAAO,CAAC;AAE9B,MAAA,oBAAoB,WAAW,KAAK,GAAG;AAClC,WAAA,UAAU,aAAa,mBAAmB,CAAC;AAAA,EAAA;AAG9C,QAAA,IAAI,MAAM,mCAAmC;AACrD;AAEA,MAAM,eAAwD,CAC5D,wBACG,oBAAoB,QAAQ,QAAQ,EAAE;AAwB3C,SAAS,UAAU,qBAAyC;AAC1D,QAAM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5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const version = "2025.1.4";
3
+ const version = "2025.4.1";
4
4
  exports.version = version;
5
5
  //# sourceMappingURL=package.json.js.map
@@ -1,4 +1,4 @@
1
- const version = "2025.1.4";
1
+ const version = "2025.4.1";
2
2
  export {
3
3
  version
4
4
  };
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const SFAPI_VERSION = "2025-01";
3
+ const SFAPI_VERSION = "2025-04";
4
4
  exports.SFAPI_VERSION = SFAPI_VERSION;
5
5
  //# sourceMappingURL=storefront-api-constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storefront-api-constants.js","sources":["../../src/storefront-api-constants.ts"],"sourcesContent":["export const SFAPI_VERSION = '2025-01';\n"],"names":[],"mappings":";;AAAO,MAAM,gBAAgB;;"}
1
+ {"version":3,"file":"storefront-api-constants.js","sources":["../../src/storefront-api-constants.ts"],"sourcesContent":["export const SFAPI_VERSION = '2025-04';\n"],"names":[],"mappings":";;AAAO,MAAM,gBAAgB;;"}
@@ -1,4 +1,4 @@
1
- const SFAPI_VERSION = "2025-01";
1
+ const SFAPI_VERSION = "2025-04";
2
2
  export {
3
3
  SFAPI_VERSION
4
4
  };
@@ -1 +1 @@
1
- {"version":3,"file":"storefront-api-constants.mjs","sources":["../../src/storefront-api-constants.ts"],"sourcesContent":["export const SFAPI_VERSION = '2025-01';\n"],"names":[],"mappings":"AAAO,MAAM,gBAAgB;"}
1
+ {"version":3,"file":"storefront-api-constants.mjs","sources":["../../src/storefront-api-constants.ts"],"sourcesContent":["export const SFAPI_VERSION = '2025-04';\n"],"names":[],"mappings":"AAAO,MAAM,gBAAgB;"}
@@ -1 +1 @@
1
- {"version":3,"file":"useCartAPIStateMachine.js","sources":["../../src/useCartAPIStateMachine.tsx"],"sourcesContent":["import {useMachine} from '@xstate/react/fsm';\nimport {createMachine, assign, StateMachine} from '@xstate/fsm';\nimport {\n Cart,\n CartMachineActionEvent,\n CartMachineActions,\n CartMachineContext,\n CartMachineEvent,\n CartMachineFetchResultEvent,\n CartMachineTypeState,\n} from './cart-types.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {useCartActions} from './useCartActions.js';\nimport {useMemo} from 'react';\nimport {InitEvent} from '@xstate/fsm/lib/types.js';\nimport {\n CountryCode,\n Cart as CartType,\n LanguageCode,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nfunction invokeCart(\n action: keyof CartMachineActions,\n options?: {\n entryActions?: [keyof CartMachineActions];\n resolveTarget?: CartMachineTypeState['value'];\n errorTarget?: CartMachineTypeState['value'];\n exitActions?: [keyof CartMachineActions];\n },\n): StateMachine.Config<CartMachineContext, CartMachineEvent>['states']['on'] {\n return {\n entry: [\n ...(options?.entryActions || []),\n assign({\n lastValidCart: (context) => context?.cart,\n }),\n 'onCartActionEntry',\n 'onCartActionOptimisticUI',\n action,\n ],\n on: {\n RESOLVE: {\n target: options?.resolveTarget || 'idle',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (_, event) => event?.payload?.cart,\n rawCartResult: (_, event) => event?.payload?.rawCartResult,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n ],\n },\n ERROR: {\n target: options?.errorTarget || 'error',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (context) => context?.lastValidCart,\n errors: (_, event) => event?.payload?.errors,\n }),\n ],\n },\n CART_COMPLETED: {\n target: 'cartCompleted',\n actions: assign({\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prevCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n cart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n lastValidCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rawCartResult: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n },\n },\n exit: ['onCartActionComplete', ...(options?.exitActions || [])],\n };\n}\n\nconst INITIALIZING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['uninitialized']['on'] = {\n CART_FETCH: {\n target: 'cartFetching',\n },\n CART_CREATE: {\n target: 'cartCreating',\n },\n CART_SET: {\n target: 'idle',\n actions: [\n assign({\n rawCartResult: (_, event) => event.payload.cart,\n cart: (_, event) => cartFromGraphQL(event.payload.cart),\n }),\n ],\n },\n};\n\nconst UPDATING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['idle']['on'] = {\n CARTLINE_ADD: {\n target: 'cartLineAdding',\n },\n CARTLINE_UPDATE: {\n target: 'cartLineUpdating',\n },\n CARTLINE_REMOVE: {\n target: 'cartLineRemoving',\n },\n NOTE_UPDATE: {\n target: 'noteUpdating',\n },\n BUYER_IDENTITY_UPDATE: {\n target: 'buyerIdentityUpdating',\n },\n CART_ATTRIBUTES_UPDATE: {\n target: 'cartAttributesUpdating',\n },\n DISCOUNT_CODES_UPDATE: {\n target: 'discountCodesUpdating',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nfunction createCartMachine(\n initialCart?: PartialDeep<CartType, {recurseIntoArrays: true}>,\n) {\n return createMachine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n >({\n id: 'Cart',\n initial: initialCart ? 'idle' : 'uninitialized',\n context: {\n cart: initialCart && cartFromGraphQL(initialCart),\n },\n states: {\n uninitialized: {\n on: INITIALIZING_CART_EVENTS,\n },\n cartCompleted: {\n on: INITIALIZING_CART_EVENTS,\n },\n initializationError: {\n on: INITIALIZING_CART_EVENTS,\n },\n idle: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n error: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n cartFetching: invokeCart('cartFetchAction', {\n errorTarget: 'initializationError',\n }),\n cartCreating: invokeCart('cartCreateAction', {\n errorTarget: 'initializationError',\n }),\n cartLineRemoving: invokeCart('cartLineRemoveAction'),\n cartLineUpdating: invokeCart('cartLineUpdateAction'),\n cartLineAdding: invokeCart('cartLineAddAction'),\n noteUpdating: invokeCart('noteUpdateAction'),\n buyerIdentityUpdating: invokeCart('buyerIdentityUpdateAction'),\n cartAttributesUpdating: invokeCart('cartAttributesUpdateAction'),\n discountCodesUpdating: invokeCart('discountCodesUpdateAction'),\n },\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartAPIStateMachine({\n numCartLines,\n onCartActionEntry,\n onCartActionOptimisticUI,\n onCartActionComplete,\n data: cart,\n cartFragment,\n countryCode,\n languageCode,\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked just before a Cart API action executes. */\n onCartActionEntry?: (\n context: CartMachineContext,\n event: CartMachineActionEvent,\n ) => void;\n /** A callback that is invoked after executing the entry actions for optimistic UI changes. */\n onCartActionOptimisticUI?: (\n context: CartMachineContext,\n event: CartMachineEvent,\n ) => Partial<CartMachineContext>;\n /** A callback that is invoked after a Cart API completes. */\n onCartActionComplete?: (\n context: CartMachineContext,\n event: CartMachineFetchResultEvent,\n ) => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-01/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-01/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n /** The ISO language code for i18n. */\n languageCode?: LanguageCode;\n}) {\n const {\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n } = useCartActions({\n numCartLines,\n cartFragment,\n countryCode,\n languageCode,\n });\n\n const cartMachine = useMemo(() => createCartMachine(cart), [cart]);\n\n const [state, send, service] = useMachine(cartMachine, {\n actions: {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartFetchAction: async (_, event) => {\n if (event.type !== 'CART_FETCH') return;\n\n const {data, errors} = await cartFetch(event?.payload?.cartId);\n const resultEvent = eventFromFetchResult(event, data?.cart, errors);\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartCreateAction: async (_, event) => {\n if (event.type !== 'CART_CREATE') return;\n\n const {data, errors} = await cartCreate(event?.payload);\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartCreate?.cart,\n errors,\n );\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineAddAction: async (context, event) => {\n if (event.type !== 'CARTLINE_ADD' || !context?.cart?.id) return;\n\n const {data, errors} = await cartLineAdd(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesAdd?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineUpdateAction: async (context, event) => {\n if (event.type !== 'CARTLINE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineUpdate(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineRemoveAction: async (context, event) => {\n if (event.type !== 'CARTLINE_REMOVE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineRemove(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesRemove?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n noteUpdateAction: async (context, event) => {\n if (event.type !== 'NOTE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await noteUpdate(\n context.cart.id,\n event.payload.note,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartNoteUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n buyerIdentityUpdateAction: async (context, event) => {\n if (event.type !== 'BUYER_IDENTITY_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await buyerIdentityUpdate(\n context.cart.id,\n event.payload.buyerIdentity,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartBuyerIdentityUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartAttributesUpdateAction: async (context, event) => {\n if (event.type !== 'CART_ATTRIBUTES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await cartAttributesUpdate(\n context.cart.id,\n event.payload.attributes,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartAttributesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n discountCodesUpdateAction: async (context, event) => {\n if (event.type !== 'DISCOUNT_CODES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await discountCodesUpdate(\n context.cart.id,\n event.payload.discountCodes,\n );\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartDiscountCodesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n ...(onCartActionEntry && {\n onCartActionEntry: (context, event): void => {\n if (isCartActionEvent(event)) {\n onCartActionEntry(context, event);\n }\n },\n }),\n ...(onCartActionOptimisticUI && {\n onCartActionOptimisticUI: assign((context, event) => {\n return onCartActionOptimisticUI(context, event);\n }),\n }),\n ...(onCartActionComplete && {\n onCartActionComplete: (context, event): void => {\n if (isCartFetchResultEvent(event)) {\n onCartActionComplete(context, event);\n }\n },\n }),\n } as CartMachineActions,\n });\n\n return useMemo(() => [state, send, service] as const, [state, send, service]);\n}\n\nexport function cartFromGraphQL(\n cart: PartialDeep<CartType, {recurseIntoArrays: true}>,\n): Cart {\n return {\n ...cart,\n lines: flattenConnection(cart?.lines),\n note: cart.note ?? undefined,\n };\n}\n\nfunction eventFromFetchResult(\n cartActionEvent: CartMachineActionEvent,\n cart?: PartialDeep<CartType, {recurseIntoArrays: true}> | null,\n errors?: unknown,\n): CartMachineFetchResultEvent {\n if (errors) {\n return {type: 'ERROR', payload: {errors, cartActionEvent}};\n }\n\n if (!cart) {\n return {\n type: 'CART_COMPLETED',\n payload: {\n cartActionEvent,\n },\n };\n }\n\n return {\n type: 'RESOLVE',\n payload: {\n cart: cartFromGraphQL(cart),\n rawCartResult: cart,\n cartActionEvent,\n },\n };\n}\n\nfunction isCartActionEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineActionEvent {\n return (\n event.type === 'CART_CREATE' ||\n event.type === 'CARTLINE_ADD' ||\n event.type === 'CARTLINE_UPDATE' ||\n event.type === 'CARTLINE_REMOVE' ||\n event.type === 'NOTE_UPDATE' ||\n event.type === 'BUYER_IDENTITY_UPDATE' ||\n event.type === 'CART_ATTRIBUTES_UPDATE' ||\n event.type === 'DISCOUNT_CODES_UPDATE'\n );\n}\n\nfunction isCartFetchResultEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineFetchResultEvent {\n return (\n event.type === 'RESOLVE' ||\n event.type === 'ERROR' ||\n event.type === 'CART_COMPLETED'\n );\n}\n"],"names":["assign","createMachine","useCartActions","useMemo","useMachine","flattenConnection"],"mappings":";;;;;;;AAsBA,SAAS,WACP,QACA,SAM2E;AACpE,SAAA;AAAA,IACL,OAAO;AAAA,MACL,IAAI,mCAAS,iBAAgB,CAAC;AAAA,MAC9BA,aAAO;AAAA,QACL,eAAe,CAAC,YAAY,mCAAS;AAAA,MAAA,CACtC;AAAA,MACD;AAAA,MACA;AA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sx"],"sourcesContent":["import {useMachine} from '@xstate/react/fsm';\nimport {createMachine, assign, StateMachine} from '@xstate/fsm';\nimport {\n Cart,\n CartMachineActionEvent,\n CartMachineActions,\n CartMachineContext,\n CartMachineEvent,\n CartMachineFetchResultEvent,\n CartMachineTypeState,\n} from './cart-types.js';\nimport {flattenConnection} from './flatten-connection.js';\nimport {useCartActions} from './useCartActions.js';\nimport {useMemo} from 'react';\nimport {InitEvent} from '@xstate/fsm/lib/types.js';\nimport {\n CountryCode,\n Cart as CartType,\n LanguageCode,\n} from './storefront-api-types.js';\nimport type {PartialDeep} from 'type-fest';\n\nfunction invokeCart(\n action: keyof CartMachineActions,\n options?: {\n entryActions?: [keyof CartMachineActions];\n resolveTarget?: CartMachineTypeState['value'];\n errorTarget?: CartMachineTypeState['value'];\n exitActions?: [keyof CartMachineActions];\n },\n): StateMachine.Config<CartMachineContext, CartMachineEvent>['states']['on'] {\n return {\n entry: [\n ...(options?.entryActions || []),\n assign({\n lastValidCart: (context) => context?.cart,\n }),\n 'onCartActionEntry',\n 'onCartActionOptimisticUI',\n action,\n ],\n on: {\n RESOLVE: {\n target: options?.resolveTarget || 'idle',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (_, event) => event?.payload?.cart,\n rawCartResult: (_, event) => event?.payload?.rawCartResult,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n ],\n },\n ERROR: {\n target: options?.errorTarget || 'error',\n actions: [\n assign({\n prevCart: (context) => context?.lastValidCart,\n cart: (context) => context?.lastValidCart,\n errors: (_, event) => event?.payload?.errors,\n }),\n ],\n },\n CART_COMPLETED: {\n target: 'cartCompleted',\n actions: assign({\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prevCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n cart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n lastValidCart: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rawCartResult: (_) => undefined,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n errors: (_) => undefined,\n }),\n },\n },\n exit: ['onCartActionComplete', ...(options?.exitActions || [])],\n };\n}\n\nconst INITIALIZING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['uninitialized']['on'] = {\n CART_FETCH: {\n target: 'cartFetching',\n },\n CART_CREATE: {\n target: 'cartCreating',\n },\n CART_SET: {\n target: 'idle',\n actions: [\n assign({\n rawCartResult: (_, event) => event.payload.cart,\n cart: (_, event) => cartFromGraphQL(event.payload.cart),\n }),\n ],\n },\n};\n\nconst UPDATING_CART_EVENTS: StateMachine.Machine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n>['config']['states']['idle']['on'] = {\n CARTLINE_ADD: {\n target: 'cartLineAdding',\n },\n CARTLINE_UPDATE: {\n target: 'cartLineUpdating',\n },\n CARTLINE_REMOVE: {\n target: 'cartLineRemoving',\n },\n NOTE_UPDATE: {\n target: 'noteUpdating',\n },\n BUYER_IDENTITY_UPDATE: {\n target: 'buyerIdentityUpdating',\n },\n CART_ATTRIBUTES_UPDATE: {\n target: 'cartAttributesUpdating',\n },\n DISCOUNT_CODES_UPDATE: {\n target: 'discountCodesUpdating',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nfunction createCartMachine(\n initialCart?: PartialDeep<CartType, {recurseIntoArrays: true}>,\n) {\n return createMachine<\n CartMachineContext,\n CartMachineEvent,\n CartMachineTypeState\n >({\n id: 'Cart',\n initial: initialCart ? 'idle' : 'uninitialized',\n context: {\n cart: initialCart && cartFromGraphQL(initialCart),\n },\n states: {\n uninitialized: {\n on: INITIALIZING_CART_EVENTS,\n },\n cartCompleted: {\n on: INITIALIZING_CART_EVENTS,\n },\n initializationError: {\n on: INITIALIZING_CART_EVENTS,\n },\n idle: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n error: {\n on: {...INITIALIZING_CART_EVENTS, ...UPDATING_CART_EVENTS},\n },\n cartFetching: invokeCart('cartFetchAction', {\n errorTarget: 'initializationError',\n }),\n cartCreating: invokeCart('cartCreateAction', {\n errorTarget: 'initializationError',\n }),\n cartLineRemoving: invokeCart('cartLineRemoveAction'),\n cartLineUpdating: invokeCart('cartLineUpdateAction'),\n cartLineAdding: invokeCart('cartLineAddAction'),\n noteUpdating: invokeCart('noteUpdateAction'),\n buyerIdentityUpdating: invokeCart('buyerIdentityUpdateAction'),\n cartAttributesUpdating: invokeCart('cartAttributesUpdateAction'),\n discountCodesUpdating: invokeCart('discountCodesUpdateAction'),\n },\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function useCartAPIStateMachine({\n numCartLines,\n onCartActionEntry,\n onCartActionOptimisticUI,\n onCartActionComplete,\n data: cart,\n cartFragment,\n countryCode,\n languageCode,\n}: {\n /** Maximum number of cart lines to fetch. Defaults to 250 cart lines. */\n numCartLines?: number;\n /** A callback that is invoked just before a Cart API action executes. */\n onCartActionEntry?: (\n context: CartMachineContext,\n event: CartMachineActionEvent,\n ) => void;\n /** A callback that is invoked after executing the entry actions for optimistic UI changes. */\n onCartActionOptimisticUI?: (\n context: CartMachineContext,\n event: CartMachineEvent,\n ) => Partial<CartMachineContext>;\n /** A callback that is invoked after a Cart API completes. */\n onCartActionComplete?: (\n context: CartMachineContext,\n event: CartMachineFetchResultEvent,\n ) => void;\n /** An object with fields that correspond to the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-04/objects/cart). */\n data?: PartialDeep<CartType, {recurseIntoArrays: true}>;\n /** A fragment used to query the Storefront API's [Cart object](https://shopify.dev/api/storefront/2025-04/objects/cart) for all queries and mutations. A default value is used if no argument is provided. */\n cartFragment: string;\n /** The ISO country code for i18n. */\n countryCode?: CountryCode;\n /** The ISO language code for i18n. */\n languageCode?: LanguageCode;\n}) {\n const {\n cartFetch,\n cartCreate,\n cartLineAdd,\n cartLineUpdate,\n cartLineRemove,\n noteUpdate,\n buyerIdentityUpdate,\n cartAttributesUpdate,\n discountCodesUpdate,\n } = useCartActions({\n numCartLines,\n cartFragment,\n countryCode,\n languageCode,\n });\n\n const cartMachine = useMemo(() => createCartMachine(cart), [cart]);\n\n const [state, send, service] = useMachine(cartMachine, {\n actions: {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartFetchAction: async (_, event) => {\n if (event.type !== 'CART_FETCH') return;\n\n const {data, errors} = await cartFetch(event?.payload?.cartId);\n const resultEvent = eventFromFetchResult(event, data?.cart, errors);\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartCreateAction: async (_, event) => {\n if (event.type !== 'CART_CREATE') return;\n\n const {data, errors} = await cartCreate(event?.payload);\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartCreate?.cart,\n errors,\n );\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineAddAction: async (context, event) => {\n if (event.type !== 'CARTLINE_ADD' || !context?.cart?.id) return;\n\n const {data, errors} = await cartLineAdd(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesAdd?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineUpdateAction: async (context, event) => {\n if (event.type !== 'CARTLINE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineUpdate(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartLineRemoveAction: async (context, event) => {\n if (event.type !== 'CARTLINE_REMOVE' || !context?.cart?.id) return;\n const {data, errors} = await cartLineRemove(\n context.cart.id,\n event.payload.lines,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartLinesRemove?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n noteUpdateAction: async (context, event) => {\n if (event.type !== 'NOTE_UPDATE' || !context?.cart?.id) return;\n const {data, errors} = await noteUpdate(\n context.cart.id,\n event.payload.note,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartNoteUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n buyerIdentityUpdateAction: async (context, event) => {\n if (event.type !== 'BUYER_IDENTITY_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await buyerIdentityUpdate(\n context.cart.id,\n event.payload.buyerIdentity,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartBuyerIdentityUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n cartAttributesUpdateAction: async (context, event) => {\n if (event.type !== 'CART_ATTRIBUTES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await cartAttributesUpdate(\n context.cart.id,\n event.payload.attributes,\n );\n\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartAttributesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n discountCodesUpdateAction: async (context, event) => {\n if (event.type !== 'DISCOUNT_CODES_UPDATE' || !context?.cart?.id)\n return;\n const {data, errors} = await discountCodesUpdate(\n context.cart.id,\n event.payload.discountCodes,\n );\n const resultEvent = eventFromFetchResult(\n event,\n data?.cartDiscountCodesUpdate?.cart,\n errors,\n );\n\n send(resultEvent);\n },\n ...(onCartActionEntry && {\n onCartActionEntry: (context, event): void => {\n if (isCartActionEvent(event)) {\n onCartActionEntry(context, event);\n }\n },\n }),\n ...(onCartActionOptimisticUI && {\n onCartActionOptimisticUI: assign((context, event) => {\n return onCartActionOptimisticUI(context, event);\n }),\n }),\n ...(onCartActionComplete && {\n onCartActionComplete: (context, event): void => {\n if (isCartFetchResultEvent(event)) {\n onCartActionComplete(context, event);\n }\n },\n }),\n } as CartMachineActions,\n });\n\n return useMemo(() => [state, send, service] as const, [state, send, service]);\n}\n\nexport function cartFromGraphQL(\n cart: PartialDeep<CartType, {recurseIntoArrays: true}>,\n): Cart {\n return {\n ...cart,\n lines: flattenConnection(cart?.lines),\n note: cart.note ?? undefined,\n };\n}\n\nfunction eventFromFetchResult(\n cartActionEvent: CartMachineActionEvent,\n cart?: PartialDeep<CartType, {recurseIntoArrays: true}> | null,\n errors?: unknown,\n): CartMachineFetchResultEvent {\n if (errors) {\n return {type: 'ERROR', payload: {errors, cartActionEvent}};\n }\n\n if (!cart) {\n return {\n type: 'CART_COMPLETED',\n payload: {\n cartActionEvent,\n },\n };\n }\n\n return {\n type: 'RESOLVE',\n payload: {\n cart: cartFromGraphQL(cart),\n rawCartResult: cart,\n cartActionEvent,\n },\n };\n}\n\nfunction isCartActionEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineActionEvent {\n return (\n event.type === 'CART_CREATE' ||\n event.type === 'CARTLINE_ADD' ||\n event.type === 'CARTLINE_UPDATE' ||\n event.type === 'CARTLINE_REMOVE' ||\n event.type === 'NOTE_UPDATE' ||\n event.type === 'BUYER_IDENTITY_UPDATE' ||\n event.type === 'CART_ATTRIBUTES_UPDATE' ||\n event.type === 'DISCOUNT_CODES_UPDATE'\n );\n}\n\nfunction isCartFetchResultEvent(\n event: CartMachineEvent | InitEvent,\n): event is CartMachineFetchResultEvent {\n return (\n event.type === 'RESOLVE' ||\n event.type === 'ERROR' ||\n event.type === 'CART_COMPLETED'\n );\n}\n"],"names":["assign","createMachine","useCartActions","useMemo","useMachine","flattenConnection"],"mappings":";;;;;;;AAsBA,SAAS,WACP,QACA,SAM2E;AACpE,SAAA;AAAA,IACL,OAAO;AAAA,MACL,IAAI,mCAAS,iBAAgB,CAAC;AAAA,MAC9BA,aAAO;AAAA,QACL,eAAe,CAAC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