@shopify/hydrogen 2024.4.1 → 2024.4.2

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.
@@ -3,17 +3,18 @@ export { AnalyticsEventName, AnalyticsPageType, ExternalVideo, IMAGE_FRAGMENT, I
3
3
  import { lazy, createContext, forwardRef, useMemo, createElement, Suspense, Fragment, useRef, useEffect, useContext, useState } from 'react';
4
4
  import { useMatches, useLocation, useNavigation, Link, useNavigate, useFetcher, useFetchers } from '@remix-run/react';
5
5
  import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
6
- import na from 'content-security-policy-builder';
6
+ import da from 'content-security-policy-builder';
7
+ import br from 'tiny-invariant';
7
8
 
8
- function bt(e){let t=Array.isArray(e)?e:[e],r="";for(let o of t)o!=null&&(typeof o=="object"?r+=JSON.stringify(o):r+=o.toString());return encodeURIComponent(r)}var ve="public",Ur="private",$e="no-store",Et={maxAge:"max-age",staleWhileRevalidate:"stale-while-revalidate",sMaxAge:"s-maxage",staleIfError:"stale-if-error"};function ue(e){let t=[];return Object.keys(e).forEach(r=>{r==="mode"?t.push(e[r]):Et[r]&&t.push(`${Et[r]}=${e[r]}`);}),t.join(", ")}function qe(){return {mode:$e}}function He(e){if(e?.mode&&e?.mode!==ve&&e?.mode!==Ur)throw Error("'mode' must be either 'public' or 'private'")}function Z(e){return He(e),{mode:ve,maxAge:1,staleWhileRevalidate:9,...e}}function Qe(e){return He(e),{mode:ve,maxAge:3600,staleWhileRevalidate:82800,...e}}function ee(e){return He(e),{mode:ve,maxAge:1,staleWhileRevalidate:86399,...e}}function Ge(e){return e}function G(e){return String(e).includes("__proto__")?JSON.parse(e,_r):JSON.parse(e)}function _r(e,t){if(e!=="__proto__")return t}function Te(e,t){return e&&t?{...e,...t}:e||ee()}function Be(e){return ue(Te(e))}async function kr(e,t){if(!e)return;let r=await e.match(t);if(!r){return}return r}async function Lr(e,t,r,o){if(!e)return;let a=Te(o),i=Be(Te(a,{maxAge:(a.maxAge||0)+(a.staleWhileRevalidate||0)})),n=Be(Te(a));r.headers.set("cache-control",i),r.headers.set("real-cache-control",n),r.headers.set("cache-put-date",new Date().toUTCString()),await e.put(t,r);}async function Nr(e,t){e&&await e.delete(t);}function Mr(e,t){let r=e.headers.get("real-cache-control"),o=0;if(r){let i=r.match(/max-age=(\d*)/);i&&i.length>1&&(o=parseFloat(i[1]));}return [(new Date().valueOf()-new Date(t).valueOf())/1e3,o]}function Vr(e,t){let r=t.headers.get("cache-put-date");if(!r)return !1;let[o,a]=Mr(t,r),i=o>a;return i}var Re={get:kr,set:Lr,delete:Nr,generateDefaultCacheControlHeader:Be,isStale:Vr};function pe(e){return `https://shopify.dev/?${e}`}function Fr(e){return e||ee()}async function xt(e,t){if(!e)return;let r=pe(t),o=new Request(r),a=await Re.get(e,o);if(!a)return;let i=await a.text();try{return [G(i),a]}catch{return [i,a]}}async function Dt(e,t,r,o){if(!e)return;let a=pe(t),i=new Request(a),n=new Response(JSON.stringify(r));await Re.set(e,i,n,Fr(o));}function Ot(e,t){return Re.isStale(new Request(pe(e)),t)}function Ut(e,t){return [e,{status:t.status,statusText:t.statusText,headers:Array.from(t.headers.entries())}]}function _t([e,t]){return [e,new Response(e,t)]}var kt=(e,t)=>!e?.errors&&t.status<400,We=new Set;async function je(e,t,{strategy:r=Z(),cacheInstance:o,shouldCacheResult:a=()=>!0,waitUntil:i,debugInfo:n}){let u=bt([...typeof e=="string"?[e]:e]),d=f=>{({displayName:f.displayName,url:f.response?.url,responseInit:{status:f.response?.status||0,statusText:f.response?.statusText||"",headers:Array.from(f.response?.headers.entries()||[])}});},l=void 0;if(!o||!r||r.mode===$e){let f=await t({addDebugData:d});return f}let y=f=>Dt(o,u,{value:f,debugInfo:void 0},r),S=await xt(o,u);if(S&&typeof S[0]!="string"){let[{value:f,debugInfo:T},m]=S;let h=Ot(u,m)?"STALE":"HIT";if(!We.has(u)&&h==="STALE"){We.add(u);let A=Promise.resolve().then(async()=>{let v=Date.now();try{let R=await t({addDebugData:d});a(R)&&(await y(R),l?.({result:R,cacheStatus:"PUT",overrideStartTime:v}));}catch(R){R.message&&(R.message="SWR in sub-request failed: "+R.message),console.error(R);}finally{We.delete(u);}});i?.(A);}return f}let C=await t({addDebugData:d});if(a(C)){let f=Promise.resolve().then(async()=>{await y(C);});i?.(f);}return C}async function Lt(e,t,{cacheInstance:r,cache:o,cacheKey:a=[e,t],shouldCacheResponse:i=()=>!0,waitUntil:n,returnType:s="json",debugInfo:u}={}){return !o&&(!t.method||t.method==="GET")&&(o=Z()),je(a,async()=>{let c=await fetch(e,t),p;try{p=await c[s]();}catch{try{p=await c.text();}catch{return Ut("",c)}}return Ut(p,c)},{cacheInstance:r,waitUntil:n,strategy:o??null,debugInfo:u,shouldCacheResult:c=>i(..._t(c))}).then(_t)}var Ke="Custom-Storefront-Request-Group-ID",ze="X-Shopify-Storefront-Access-Token",Je="X-SDK-Variant",Ye="X-SDK-Variant-Source",Xe="X-SDK-Version";function Nt(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`weak-${Math.random().toString(16).substring(2)}`}var de="2024.4.1";function te(e){return e.replace(/\s*#.*$/gm,"").replace(/\s+/gm," ").trim()}var $r=/(^|}\s)query[\s({]/im,qr=/(^|}\s)mutation[\s({]/im;function Ie(e,t){if(!$r.test(e))throw new Error(`[h2:error:${t}] Can only execute queries`)}function we(e,t){if(!qr.test(e))throw new Error(`[h2:error:${t}] Can only execute mutations`)}var B=class extends Error{locations;path;extensions;constructor(t,r={}){let a=(r.clientOperation?`[h2:error:${r.clientOperation}] `:"")+t+(r.requestId?` - Request ID: ${r.requestId}`:"");super(a),this.name="GraphQLError",this.extensions=r.extensions,this.locations=r.locations,this.path=r.path,this.stack=r.stack||void 0;try{this.cause=JSON.stringify({...typeof r.cause=="object"?r.cause:{},requestId:r.requestId});}catch{r.cause&&(this.cause=r.cause);}}get[Symbol.toStringTag](){return this.name}toString(){let t=`${this.name}: ${this.message}`;if(this.path)try{t+=` | path: ${JSON.stringify(this.path)}`;}catch{}if(this.extensions)try{t+=` | extensions: ${JSON.stringify(this.extensions)}`;}catch{}return t+=`
9
+ function Dt(e){let t=Array.isArray(e)?e:[e],r="";for(let o of t)o!=null&&(typeof o=="object"?r+=JSON.stringify(o):r+=o.toString());return encodeURIComponent(r)}var be="public",Vr="private",Qe="no-store",Ot={maxAge:"max-age",staleWhileRevalidate:"stale-while-revalidate",sMaxAge:"s-maxage",staleIfError:"stale-if-error"};function ye(e){let t=[];return Object.keys(e).forEach(r=>{r==="mode"?t.push(e[r]):Ot[r]&&t.push(`${Ot[r]}=${e[r]}`);}),t.join(", ")}function Ge(){return {mode:Qe}}function Be(e){if(e?.mode&&e?.mode!==be&&e?.mode!==Vr)throw Error("'mode' must be either 'public' or 'private'")}function re(e){return Be(e),{mode:be,maxAge:1,staleWhileRevalidate:9,...e}}function We(e){return Be(e),{mode:be,maxAge:3600,staleWhileRevalidate:82800,...e}}function oe(e){return Be(e),{mode:be,maxAge:1,staleWhileRevalidate:86399,...e}}function je(e){return e}function j(e){return String(e).includes("__proto__")?JSON.parse(e,Fr):JSON.parse(e)}function Fr(e,t){if(e!=="__proto__")return t}function Ee(e,t){return e&&t?{...e,...t}:e||oe()}function Ke(e){return ye(Ee(e))}async function $r(e,t){if(!e)return;let r=await e.match(t);if(!r){return}return r}async function qr(e,t,r,o){if(!e)return;let a=Ee(o),s=Ke(Ee(a,{maxAge:(a.maxAge||0)+(a.staleWhileRevalidate||0)})),n=Ke(Ee(a));r.headers.set("cache-control",s),r.headers.set("real-cache-control",n),r.headers.set("cache-put-date",new Date().toUTCString()),await e.put(t,r);}async function Hr(e,t){e&&await e.delete(t);}function Qr(e,t){let r=e.headers.get("real-cache-control"),o=0;if(r){let s=r.match(/max-age=(\d*)/);s&&s.length>1&&(o=parseFloat(s[1]));}return [(new Date().valueOf()-new Date(t).valueOf())/1e3,o]}function Gr(e,t){let r=t.headers.get("cache-put-date");if(!r)return !1;let[o,a]=Qr(t,r),s=o>a;return s}var xe={get:$r,set:qr,delete:Hr,generateDefaultCacheControlHeader:Ke,isStale:Gr};function fe(e){return `https://shopify.dev/?${e}`}function Br(e){return e||oe()}async function Ut(e,t){if(!e)return;let r=fe(t),o=new Request(r),a=await xe.get(e,o);if(!a)return;let s=await a.text();try{return [j(s),a]}catch{return [s,a]}}async function _t(e,t,r,o){if(!e)return;let a=fe(t),s=new Request(a),n=new Response(JSON.stringify(r));await xe.set(e,s,n,Br(o));}function kt(e,t){return xe.isStale(new Request(fe(e)),t)}function Lt(e,t){return [e,{status:t.status,statusText:t.statusText,headers:Array.from(t.headers.entries())}]}function Nt([e,t]){return [e,new Response(e,t)]}var Mt=(e,t)=>!e?.errors&&t.status<400,ze=new Set;async function Je(e,t,{strategy:r=re(),cacheInstance:o,shouldCacheResult:a=()=>!0,waitUntil:s,debugInfo:n}){let u=Dt([...typeof e=="string"?[e]:e]),y=f=>{({displayName:f.displayName,url:f.response?.url,responseInit:{status:f.response?.status||0,statusText:f.response?.statusText||"",headers:Array.from(f.response?.headers.entries()||[])}});},p=void 0;if(!o||!r||r.mode===Qe){let f=await t({addDebugData:y});return f}let l=f=>_t(o,u,{value:f,debugInfo:void 0},r),g=await Ut(o,u);if(g&&typeof g[0]!="string"){let[{value:f,debugInfo:R},v]=g;let N=kt(u,v)?"STALE":"HIT";if(!ze.has(u)&&N==="STALE"){ze.add(u);let F=Promise.resolve().then(async()=>{let ee=Date.now();try{let _=await t({addDebugData:y});a(_)&&(await l(_),p?.({result:_,cacheStatus:"PUT",overrideStartTime:ee}));}catch(_){_.message&&(_.message="SWR in sub-request failed: "+_.message),console.error(_);}finally{ze.delete(u);}});s?.(F);}return f}let S=await t({addDebugData:y});if(a(S)){let f=Promise.resolve().then(async()=>{await l(S);});s?.(f);}return S}async function Vt(e,t,{cacheInstance:r,cache:o,cacheKey:a=[e,t],shouldCacheResponse:s=()=>!0,waitUntil:n,returnType:i="json",debugInfo:u}={}){return !o&&(!t.method||t.method==="GET")&&(o=re()),Je(a,async()=>{let c=await fetch(e,t),d;try{d=await c[i]();}catch{try{d=await c.text();}catch{return Lt("",c)}}return Lt(d,c)},{cacheInstance:r,waitUntil:n,strategy:o??null,debugInfo:u,shouldCacheResult:c=>s(...Nt(c))}).then(Nt)}var me="2024.4.2";var Ye="Custom-Storefront-Request-Group-ID",Xe="X-Shopify-Storefront-Access-Token",Ze="X-SDK-Variant",et="X-SDK-Variant-Source",tt="X-SDK-Version",De="2024-04",ae=`Shopify Hydrogen ${me}`,Ft="30243aa5-17c1-465a-8493-944bcc4e88aa",E="customerAccount",ne="buyer";function $t(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`weak-${Math.random().toString(16).substring(2)}`}function se(e){return e.replace(/\s*#.*$/gm,"").replace(/\s+/gm," ").trim()}var Wr=/(^|}\s)query[\s({]/im,jr=/(^|}\s)mutation[\s({]/im;function Oe(e,t){if(!Wr.test(e))throw new Error(`[h2:error:${t}] Can only execute queries`)}function Ue(e,t){if(!jr.test(e))throw new Error(`[h2:error:${t}] Can only execute mutations`)}var K=class extends Error{locations;path;extensions;constructor(t,r={}){let a=(r.clientOperation?`[h2:error:${r.clientOperation}] `:"")+t+(r.requestId?` - Request ID: ${r.requestId}`:"");super(a),this.name="GraphQLError",this.extensions=r.extensions,this.locations=r.locations,this.path=r.path,this.stack=r.stack||void 0;try{this.cause=JSON.stringify({...typeof r.cause=="object"?r.cause:{},requestId:r.requestId});}catch{r.cause&&(this.cause=r.cause);}}get[Symbol.toStringTag](){return this.name}toString(){let t=`${this.name}: ${this.message}`;if(this.path)try{t+=` | path: ${JSON.stringify(this.path)}`;}catch{}if(this.extensions)try{t+=` | extensions: ${JSON.stringify(this.extensions)}`;}catch{}return t+=`
9
10
  `,this.stack&&(t+=`${this.stack.slice(this.stack.indexOf(`
10
11
  `)+1)}
11
- `),t}toJSON(){return {name:"Error",message:""}}};function le({url:e,response:t,errors:r,type:o,query:a,queryVariables:i,ErrorConstructor:n=Error,client:s="storefront"}){let u=(typeof r=="string"?r:r?.map?.(p=>p.message).join(`
12
+ `),t}toJSON(){return {name:"Error",message:""}}};function ge({url:e,response:t,errors:r,type:o,query:a,queryVariables:s,ErrorConstructor:n=Error,client:i="storefront"}){let u=(typeof r=="string"?r:r?.map?.(d=>d.message).join(`
12
13
  `))||`URL: ${e}
13
- API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{errors:r},clientOperation:`${s}.${o}`,requestId:t.headers.get("x-request-id")});throw new n(c.message,{cause:c.cause})}function re(e,t={}){let r=new Error,o=(a,i="Error")=>{let n=(r.stack??"").split(`
14
+ API response error: ${t.status}`,c=new K(u,{query:a,queryVariables:s,cause:{errors:r},clientOperation:`${i}.${o}`,requestId:t.headers.get("x-request-id")});throw new n(c.message,{cause:c.cause})}function ie(e,t={}){let r=new Error,o=(a,s="Error")=>{let n=(r.stack??"").split(`
14
15
  `).slice(3+(t.stackOffset??0)).join(`
15
- `).replace(/ at loader(\d+) \(/,(s,u)=>s.replace(u,""));return `${i}: ${a}
16
- `+n};return e.then(a=>{if(a?.errors&&Array.isArray(a.errors)){let i=typeof t.logErrors=="function"?t.logErrors:()=>t.logErrors??!1;a.errors.forEach(n=>{n&&(n.stack=o(n.message,n.name),i(n)&&console.error(n));});}return a}).catch(a=>{throw a&&(a.stack=o(a.message,a.name)),a})}var L=void 0;var jr={language:"EN",country:"US"};function En(e){let {storefrontHeaders:t,cache:r,waitUntil:o,i18n:a,storefrontId:i,logErrors:n=!0,...s}=e,{getPublicTokenHeaders:c,getPrivateTokenHeaders:p,getStorefrontApiUrl:d,getShopifyDomain:g}=createStorefrontClient(s),y=(s.privateStorefrontToken?p:c)({contentType:"json",buyerIp:t?.buyerIp||""});if(y[Ke]=t?.requestGroupId||Nt(),i&&(y[SHOPIFY_STOREFRONT_ID_HEADER]=i),(y["user-agent"]=`Hydrogen ${de}`),t&&t.cookie){let f=getShopifyCookies(t.cookie??"");f[SHOPIFY_Y]&&(y[SHOPIFY_STOREFRONT_Y_HEADER]=f[SHOPIFY_Y]),f[SHOPIFY_S]&&(y[SHOPIFY_STOREFRONT_S_HEADER]=f[SHOPIFY_S]);}let S=JSON.stringify({"content-type":y["content-type"],"user-agent":y["user-agent"],[Je]:y[Je],[Ye]:y[Ye],[Xe]:y[Xe],[ze]:y[ze]});async function C({query:f,mutation:T,variables:m,cache:h,headers:A=[],storefrontApiVersion:v,displayName:R,stackInfo:H}){let U=A instanceof Headers?Object.fromEntries(A.entries()):Array.isArray(A)?Object.fromEntries(A):A,E=f??T,x={...m};a&&(!m?.country&&/\$country/.test(E)&&(x.country=a.country),!m?.language&&/\$language/.test(E)&&(x.language=a.language));let I=d({storefrontApiVersion:v}),_=JSON.stringify({query:E,variables:x}),V={method:"POST",headers:{...y,...U},body:_},Y=[I,V.method,S,V.body],[Q,X]=await Lt(I,V,{cacheInstance:T?void 0:r,cache:h||ee(),cacheKey:Y,shouldCacheResponse:kt,waitUntil:o,debugInfo:{requestId:V.headers[Ke],displayName:R,url:I,stackInfo:H,graphql:_,purpose:t?.purpose}}),se={url:I,response:X,type:T?"mutation":"query",query:E,queryVariables:x,errors:void 0};if(!X.ok){let ce;try{ce=G(Q);}catch{ce=[{message:Q}];}le({...se,errors:ce});}let{data:Ve,errors:Fe}=Q,Or=Fe?.map(({message:ce,...wt})=>new B(ce,{...wt,clientOperation:`storefront.${se.type}`,requestId:X.headers.get("x-request-id"),queryVariables:x,query:E}));return P(Ve,Or)}return {storefront:{query(f,T){f=te(f),Ie(f,"storefront.query");let m=Ft?.(f);return re(C({...T,query:f,stackInfo:L?.(m)}),{stackOffset:m,logErrors:n})},mutate(f,T){f=te(f),we(f,"storefront.mutate");let m=Ft?.(f);return re(C({...T,mutation:f,stackInfo:L?.(m)}),{stackOffset:m,logErrors:n})},cache:r,CacheNone:qe,CacheLong:Qe,CacheShort:Z,CacheCustom:Ge,generateCacheControlHeader:ue,getPublicTokenHeaders:c,getPrivateTokenHeaders:p,getShopifyDomain:g,getApiUrl:d,i18n:a??jr}}}var Ft=void 0;function P(e,t){return {...e,...t&&{errors:t}}}function be(e,t){let r=e.headers?.get?.(t)??e.headers?.[t];return typeof r=="string"?r:null}function W(e){return {requestId:e?be(e,"request-id"):void 0,purpose:e?be(e,"purpose"):void 0}}function kn({cache:e,waitUntil:t,request:r}){return function(a,i,n){return je(a,n,{strategy:i,cacheInstance:e,waitUntil:t,debugInfo:{...W(r),stackInfo:L?.()}})}}var Ze=class{#e;constructor(){this.#e=new Map;}add(t){throw new Error("Method not implemented. Use `put` instead.")}addAll(t){throw new Error("Method not implemented. Use `put` instead.")}matchAll(t,r){throw new Error("Method not implemented. Use `match` instead.")}async put(t,r){if(t.method!=="GET")throw new TypeError("Cannot cache response to non-GET request.");if(r.status===206)throw new TypeError("Cannot cache response to a range request (206 Partial Content).");if(r.headers.get("vary")?.includes("*"))throw new TypeError("Cannot cache response with 'Vary: *' header.");this.#e.set(t.url,{body:new Uint8Array(await r.arrayBuffer()),status:r.status,headers:[...r.headers],timestamp:Date.now()});}async match(t){if(t.method!=="GET")return;let r=this.#e.get(t.url);if(!r)return;let{body:o,timestamp:a,...i}=r,n=new Headers(i.headers),s=n.get("cache-control")||n.get("real-cache-control")||"",u=parseInt(s.match(/max-age=(\d+)/)?.[1]||"0",10),c=parseInt(s.match(/stale-while-revalidate=(\d+)/)?.[1]||"0",10),p=(Date.now()-a)/1e3;if(p>u+c){this.#e.delete(t.url);return}let g=p>u;return n.set("cache",g?"STALE":"HIT"),n.set("date",new Date(a).toUTCString()),new Response(o,{status:i.status??200,headers:n})}async delete(t){return this.#e.has(t.url)?(this.#e.delete(t.url),!0):!1}keys(t){let r=[];for(let o of this.#e.keys())(!t||t.url===o)&&r.push(new Request(o));return Promise.resolve(r)}};function Ee(e){if(!e)return;let{pathname:t,search:r}=new URL(e),o=t+r,a=new URLSearchParams(r),i=a.get("return_to")||a.get("redirect");if(i){if(qt(e,i))return i;console.warn(`Cross-domain redirects are not supported. Tried to redirect from ${o} to ${i}`);}}function qt(e,t){try{return new URL(e).origin===new URL(t,e).origin}catch{return !1}}function et({requestUrl:e,defaultUrl:t,redirectUrl:r}){let o=e,a=$t(e,t),i=r?$t(e,r):a;return qt(e,i.toString())?i.toString():(console.warn(`Cross-domain redirects are not supported. Tried to redirect from ${o} to ${i}. Default url ${a} is used instead.`),a.toString())}function $t(e,t){return Kr(t)?new URL(t):new URL(t,new URL(e).origin)}function Kr(e){try{return new URL(e),!0}catch{return !1}}async function zr(e){let{storefront:t,request:r,noAdminRedirect:o,matchQueryParams:a,response:i=new Response("Not Found",{status:404})}=e,n=new URL(r.url),{pathname:s,searchParams:u}=n,c=u.has("_data");u.delete("redirect"),u.delete("return_to"),u.delete("_data");let p=(a?n.toString().replace(n.origin,""):s).toLowerCase();if(n.pathname==="/admin"&&!o)return rt(`${t.getShopifyDomain()}/admin`,c,u,a);try{let{urlRedirects:d}=await t.query(Jr,{variables:{query:"path:"+p}}),g=d?.edges?.[0]?.node?.target;if(g)return rt(g,c,u,a);let l=Ee(r.url);if(l)return rt(l,c,u,a)}catch(d){console.error(`Failed to fetch redirects from Storefront API for route ${p}`,d);}return i}var tt="https://example.com";function rt(e,t,r,o){let a=new URL(e,tt);if(!o)for(let[i,n]of r)a.searchParams.append(i,n);return t?new Response(null,{status:200,headers:{"X-Remix-Redirect":a.toString().replace(tt,""),"X-Remix-Status":"301"}}):new Response(null,{status:301,headers:{location:a.toString().replace(tt,"")}})}var Jr=`#graphql
16
+ `).replace(/ at loader(\d+) \(/,(i,u)=>i.replace(u,""));return `${s}: ${a}
17
+ `+n};return e.then(a=>{if(a?.errors&&Array.isArray(a.errors)){let s=typeof t.logErrors=="function"?t.logErrors:()=>t.logErrors??!1;a.errors.forEach(n=>{n&&(n.stack=o(n.message,n.name),s(n)&&console.error(n));});}return a}).catch(a=>{throw a&&(a.stack=o(a.message,a.name)),a})}var q=void 0;var Zr={language:"EN",country:"US"};function Nn(e){let {storefrontHeaders:t,cache:r,waitUntil:o,i18n:a,storefrontId:s,logErrors:n=!0,...i}=e,{getPublicTokenHeaders:c,getPrivateTokenHeaders:d,getStorefrontApiUrl:y,getShopifyDomain:m}=createStorefrontClient(i),l=(i.privateStorefrontToken?d:c)({contentType:"json",buyerIp:t?.buyerIp||""});if(l[Ye]=t?.requestGroupId||$t(),s&&(l[SHOPIFY_STOREFRONT_ID_HEADER]=s),(l["user-agent"]=`Hydrogen ${me}`),t&&t.cookie){let f=getShopifyCookies(t.cookie??"");f[SHOPIFY_Y]&&(l[SHOPIFY_STOREFRONT_Y_HEADER]=f[SHOPIFY_Y]),f[SHOPIFY_S]&&(l[SHOPIFY_STOREFRONT_S_HEADER]=f[SHOPIFY_S]);}let g=JSON.stringify({"content-type":l["content-type"],"user-agent":l["user-agent"],[Ze]:l[Ze],[et]:l[et],[tt]:l[tt],[Xe]:l[Xe]});async function S({query:f,mutation:R,variables:v,cache:N,headers:F=[],storefrontApiVersion:ee,displayName:_,stackInfo:we}){let h=F instanceof Headers?Object.fromEntries(F.entries()):Array.isArray(F)?Object.fromEntries(F):F,C=f??R,A={...v};a&&(!v?.country&&/\$country/.test(C)&&(A.country=a.country),!v?.language&&/\$language/.test(C)&&(A.language=a.language));let T=y({storefrontApiVersion:ee}),M=JSON.stringify({query:C,variables:A}),V={method:"POST",headers:{...l,...h},body:M},D=[T,V.method,g,V.body],[O,U]=await Vt(T,V,{cacheInstance:R?void 0:r,cache:N||oe(),cacheKey:D,shouldCacheResponse:Mt,waitUntil:o,debugInfo:{requestId:V.headers[Ye],displayName:_,url:T,stackInfo:we,graphql:M,purpose:t?.purpose}}),b={url:T,response:U,type:R?"mutation":"query",query:C,queryVariables:A,errors:void 0};if(!U.ok){let $;try{$=j(O);}catch{$=[{message:O}];}ge({...b,errors:$});}let{data:L,errors:de}=O,te=de?.map(({message:$,...le})=>new K($,{...le,clientOperation:`storefront.${b.type}`,requestId:U.headers.get("x-request-id"),queryVariables:A,query:C}));return P(L,te)}return {storefront:{query(f,R){f=se(f),Oe(f,"storefront.query");let v=Qt?.(f);return ie(S({...R,query:f,stackInfo:q?.(v)}),{stackOffset:v,logErrors:n})},mutate(f,R){f=se(f),Ue(f,"storefront.mutate");let v=Qt?.(f);return ie(S({...R,mutation:f,stackInfo:q?.(v)}),{stackOffset:v,logErrors:n})},cache:r,CacheNone:Ge,CacheLong:We,CacheShort:re,CacheCustom:je,generateCacheControlHeader:ye,getPublicTokenHeaders:c,getPrivateTokenHeaders:d,getShopifyDomain:m,getApiUrl:y,i18n:a??Zr}}}var Qt=void 0;function P(e,t){return {...e,...t&&{errors:t}}}function _e(e,t){let r=e.headers?.get?.(t)??e.headers?.[t];return typeof r=="string"?r:null}function z(e){return {requestId:e?_e(e,"request-id"):void 0,purpose:e?_e(e,"purpose"):void 0}}function Hn({cache:e,waitUntil:t,request:r}){return function(a,s,n){return Je(a,n,{strategy:s,cacheInstance:e,waitUntil:t,debugInfo:{...z(r),stackInfo:q?.()}})}}var rt=class{#e;constructor(){this.#e=new Map;}add(t){throw new Error("Method not implemented. Use `put` instead.")}addAll(t){throw new Error("Method not implemented. Use `put` instead.")}matchAll(t,r){throw new Error("Method not implemented. Use `match` instead.")}async put(t,r){if(t.method!=="GET")throw new TypeError("Cannot cache response to non-GET request.");if(r.status===206)throw new TypeError("Cannot cache response to a range request (206 Partial Content).");if(r.headers.get("vary")?.includes("*"))throw new TypeError("Cannot cache response with 'Vary: *' header.");this.#e.set(t.url,{body:new Uint8Array(await r.arrayBuffer()),status:r.status,headers:[...r.headers],timestamp:Date.now()});}async match(t){if(t.method!=="GET")return;let r=this.#e.get(t.url);if(!r)return;let{body:o,timestamp:a,...s}=r,n=new Headers(s.headers),i=n.get("cache-control")||n.get("real-cache-control")||"",u=parseInt(i.match(/max-age=(\d+)/)?.[1]||"0",10),c=parseInt(i.match(/stale-while-revalidate=(\d+)/)?.[1]||"0",10),d=(Date.now()-a)/1e3;if(d>u+c){this.#e.delete(t.url);return}let m=d>u;return n.set("cache",m?"STALE":"HIT"),n.set("date",new Date(a).toUTCString()),new Response(o,{status:s.status??200,headers:n})}async delete(t){return this.#e.has(t.url)?(this.#e.delete(t.url),!0):!1}keys(t){let r=[];for(let o of this.#e.keys())(!t||t.url===o)&&r.push(new Request(o));return Promise.resolve(r)}};function ke(e){if(!e)return;let{pathname:t,search:r}=new URL(e),o=t+r,a=new URLSearchParams(r),s=a.get("return_to")||a.get("redirect");if(s){if(Bt(e,s))return s;console.warn(`Cross-domain redirects are not supported. Tried to redirect from ${o} to ${s}`);}}function Bt(e,t){try{return new URL(e).origin===new URL(t,e).origin}catch{return !1}}function ot({requestUrl:e,defaultUrl:t,redirectUrl:r}){let o=e,a=Gt(e,t),s=r?Gt(e,r):a;return Bt(e,s.toString())?s.toString():(console.warn(`Cross-domain redirects are not supported. Tried to redirect from ${o} to ${s}. Default url ${a} is used instead.`),a.toString())}function Gt(e,t){return eo(t)?new URL(t):new URL(t,new URL(e).origin)}function eo(e){try{return new URL(e),!0}catch{return !1}}async function to(e){let{storefront:t,request:r,noAdminRedirect:o,matchQueryParams:a,response:s=new Response("Not Found",{status:404})}=e,n=new URL(r.url),{pathname:i,searchParams:u}=n,c=u.has("_data");u.delete("redirect"),u.delete("return_to"),u.delete("_data");let d=(a?n.toString().replace(n.origin,""):i).toLowerCase();if(n.pathname==="/admin"&&!o)return nt(`${t.getShopifyDomain()}/admin`,c,u,a);try{let{urlRedirects:y}=await t.query(ro,{variables:{query:"path:"+d}}),m=y?.edges?.[0]?.node?.target;if(m)return nt(m,c,u,a);let p=ke(r.url);if(p)return nt(p,c,u,a)}catch(y){console.error(`Failed to fetch redirects from Storefront API for route ${d}`,y);}return s}var at="https://example.com";function nt(e,t,r,o){let a=new URL(e,at);if(!o)for(let[s,n]of r)a.searchParams.append(s,n);return t?new Response(null,{status:200,headers:{"X-Remix-Redirect":a.toString().replace(at,""),"X-Remix-Status":"301"}}):new Response(null,{status:301,headers:{location:a.toString().replace(at,"")}})}var ro=`#graphql
17
18
  query redirects($query: String) {
18
19
  urlRedirects(first: 1, query: $query) {
19
20
  edges {
@@ -23,12 +24,12 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
23
24
  }
24
25
  }
25
26
  }
26
- `;var Yr=async function({request:t,context:r}){let o=r.storefront,a=r.customerAccount,i=new URL(t.url);if(!o)throw new Error("GraphiQL: Hydrogen's storefront client must be injected in the loader context.");let n={};if(o){let c="X-Shopify-Storefront-Access-Token";n.storefront={name:"Storefront API",authHeader:c,accessToken:o.getPublicTokenHeaders()[c],apiUrl:o.getApiUrl(),icon:"SF"};}if(a){let c=await(await fetch(i.origin+"/graphiql/customer-account.schema.json")).json(),p=await a.getAccessToken();c&&(n["customer-account"]={name:"Customer Account API",value:c,authHeader:"Authorization",accessToken:p,apiUrl:a.getApiUrl(),icon:"CA"});}let s="https://avatars.githubusercontent.com/u/12972006?s=48&v=4",u=String.raw;return new Response(u`
27
+ `;var oo=async function({request:t,context:r}){let o=r.storefront,a=r.customerAccount,s=new URL(t.url);if(!o)throw new Error("GraphiQL: Hydrogen's storefront client must be injected in the loader context.");let n={};if(o){let c="X-Shopify-Storefront-Access-Token";n.storefront={name:"Storefront API",authHeader:c,accessToken:o.getPublicTokenHeaders()[c],apiUrl:o.getApiUrl(),icon:"SF"};}if(a){let c=await(await fetch(s.origin+"/graphiql/customer-account.schema.json")).json(),d=await a.getAccessToken();c&&(n["customer-account"]={name:"Customer Account API",value:c,authHeader:"Authorization",accessToken:d,apiUrl:a.getApiUrl(),icon:"CA"});}let i="https://avatars.githubusercontent.com/u/12972006?s=48&v=4",u=String.raw;return new Response(u`
27
28
  <!DOCTYPE html>
28
29
  <html lang="en">
29
30
  <head>
30
31
  <title>GraphiQL</title>
31
- <link rel="icon" type="image/x-icon" href="${s}" />
32
+ <link rel="icon" type="image/x-icon" href="${i}" />
32
33
  <style>
33
34
  body {
34
35
  height: 100%;
@@ -289,18 +290,24 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
289
290
  </script>
290
291
  </body>
291
292
  </html>
292
- `,{status:200,headers:{"content-type":"text/html"}})};var Xr={"&":"\\u0026",">":"\\u003e","<":"\\u003c","\u2028":"\\u2028","\u2029":"\\u2029"},Zr=/[&><\u2028\u2029]/g;function Ht(e){return e.replace(Zr,t=>Xr[t])}var F="Error in SEO input: ",N={title:{validate:e=>{if(typeof e!="string")throw new Error(F.concat("`title` should be a string"));if(typeof e=="string"&&e.length>120)throw new Error(F.concat("`title` should not be longer than 120 characters"));return e}},description:{validate:e=>{if(typeof e!="string")throw new Error(F.concat("`description` should be a string"));if(typeof e=="string"&&e.length>155)throw new Error(F.concat("`description` should not be longer than 155 characters"));return e}},url:{validate:e=>{if(typeof e!="string")throw new Error(F.concat("`url` should be a string"));if(typeof e=="string"&&!e.startsWith("http"))throw new Error(F.concat("`url` should be a valid URL"));return e}},handle:{validate:e=>{if(typeof e!="string")throw new Error(F.concat("`handle` should be a string"));if(typeof e=="string"&&!e.startsWith("@"))throw new Error(F.concat("`handle` should start with `@`"));return e}}};function Qt(e){let t=[];for(let r of Object.keys(e))switch(r){case"title":{let o=M(N.title,e.title),a=at(e?.titleTemplate,o);if(!a)break;t.push(D("title",{title:a}),D("meta",{property:"og:title",content:a}),D("meta",{name:"twitter:title",content:a}));break}case"description":{let o=M(N.description,e.description);if(!o)break;t.push(D("meta",{name:"description",content:o}),D("meta",{property:"og:description",content:o}),D("meta",{name:"twitter:description",content:o}));break}case"url":{let o=M(N.url,e.url);if(!o)break;let i=o.split("?")[0].replace(/\/$/,"");t.push(D("link",{rel:"canonical",href:i}),D("meta",{property:"og:url",content:i}));break}case"handle":{let o=M(N.handle,e.handle);if(!o)break;t.push(D("meta",{name:"twitter:site",content:o}),D("meta",{name:"twitter:creator",content:o}));break}case"media":{let o,a=$(e.media);for(let i of a)if(typeof i=="string"&&t.push(D("meta",{name:"og:image",content:i})),i&&typeof i=="object"){let n=i.type||"image",s=i?{url:i?.url,secure_url:i?.url,type:nt(i.url),width:i?.width,height:i?.height,alt:i?.altText}:{};for(let u of Object.keys(s))s[u]&&(o=s[u],t.push(D("meta",{property:`og:${n}:${u}`,content:o},s.url)));}break}case"jsonLd":{let o=$(e.jsonLd),a=0;for(let i of o){if(typeof i!="object")continue;let n=D("script",{type:"application/ld+json",children:JSON.stringify(i,(s,u)=>typeof u=="string"?Ht(u):u)},`json-ld-${i?.["@type"]||i?.name||a++}`);t.push(n);}break}case"alternates":{let o=$(e.alternates);for(let a of o){if(!a)continue;let{language:i,url:n,default:s}=a,u=i?`${i}${s?"-default":""}`:void 0;t.push(D("link",{rel:"alternate",hrefLang:u,href:n}));}break}case"robots":{if(!e.robots)break;let{maxImagePreview:o,maxSnippet:a,maxVideoPreview:i,noArchive:n,noFollow:s,noImageIndex:u,noIndex:c,noSnippet:p,noTranslate:d,unavailableAfter:g}=e.robots,l=[n&&"noarchive",u&&"noimageindex",p&&"nosnippet",d&&"notranslate",o&&`max-image-preview:${o}`,a&&`max-snippet:${a}`,i&&`max-video-preview:${i}`,g&&`unavailable_after:${g}`],y=(c?"noindex":"index")+","+(s?"nofollow":"follow");for(let S of l)S&&(y+=`,${S}`);t.push(D("meta",{name:"robots",content:y}));break}}return t.flat().sort((r,o)=>r.key.localeCompare(o.key))}function D(e,t,r){let o={tag:e,props:{},key:""};return e==="title"?(o.children=t.title,o.key=ot(o),o):e==="script"?(o.children=typeof t.children=="string"?t.children:"",o.key=ot(o,r),delete t.children,o.props=t,o):(o.props=t,Object.keys(o.props).forEach(a=>!o.props[a]&&delete o.props[a]),o.key=ot(o,r),o)}function ot(e,t){let{tag:r,props:o}=e;if(r==="title")return "0-title";if(r==="meta"){let a=o.content===t&&typeof o.property=="string"&&!o.property.endsWith("secure_url")&&"0";return [r,...[t,a],o.property||o.name].filter(n=>n).join("-")}return r==="link"?[r,o.rel,o.hrefLang||o.media].filter(i=>i).join("-").replace(/\s+/g,"-"):r==="script"?`${r}-${t}`:`${r}-${o.type}`}function at(e,t){if(t)return e?typeof e=="function"?e(t):e.replace("%s",t??""):t}function nt(e){switch(e&&e.split(".").pop()){case"svg":return "image/svg+xml";case"png":return "image/png";case"gif":return "image/gif";case"swf":return "application/x-shockwave-flash";case"mp3":return "audio/mpeg";case"jpg":case"jpeg":default:return "image/jpeg"}}function $(e){return Array.isArray(e)?e:[e]}function M(e,t){try{return e.validate(t)}catch(r){return console.warn(r.message),t}}var no=lazy(()=>import('./log-seo-tags-TY72EQWZ.js'));function io({debug:e}){let t=useMatches(),r=useLocation();console.warn("[h2:warn:Seo] The `<Seo/>` component is deprecated. Use `getSeoMeta` instead.\nSee: https://shopify.dev/docs/api/hydrogen/2024-01/utilities/getseometa");let o=useMemo(()=>t.flatMap(n=>{let{handle:s,...u}=n,c={...u,...r},p=s?.seo,d=u?.data?.seo;return !p&&!d?[]:p?xe(p,c):[d]}).reduce((n,s)=>{Object.keys(s).forEach(c=>!s[c]&&delete s[c]);let{jsonLd:u}=s;return u?n?.jsonLd?Array.isArray(u)?{...n,...s,jsonLd:[...n.jsonLd,...u]}:{...n,...s,jsonLd:[...n.jsonLd,u]}:{...n,...s,jsonLd:[u]}:{...n,...s}},{}),[t,r]),{html:a,loggerMarkup:i}=useMemo(()=>{let n=Qt(o),s=n.map(c=>c.tag==="script"?createElement(c.tag,{...c.props,key:c.key,dangerouslySetInnerHTML:{__html:c.children}}):createElement(c.tag,{...c.props,key:c.key},c.children)),u=createElement(Suspense,{fallback:null},createElement(no,{headTags:n}));return {html:s,loggerMarkup:u}},[o]);return createElement(Fragment,null,a,e&&i)}function xe(e,...t){if(e instanceof Function)return xe(e(...t),...t);let r={};return Array.isArray(e)?(r=e.reduce((o,a)=>[...o,xe(a)],[]),r):e instanceof Object?(Object.entries(e).forEach(([a,i])=>{r[a]=xe(i,...t);}),r):e}function so(...e){let t=[],r=e.reduce((o,a)=>{if(!a)return o;Object.keys(a).forEach(n=>!a[n]&&delete a[n]);let{jsonLd:i}=a;return i?o?.jsonLd?{...o,...a,jsonLd:$(o.jsonLd).concat(i)}:{...o,...a,jsonLd:[i]}:{...o,...a}},{})||{};for(let o of Object.keys(r))switch(o){case"title":{let a=M(N.title,r.title),i=at(r?.titleTemplate,a);if(!i)break;t.push({title:i},{property:"og:title",content:i},{property:"twitter:title",content:i});break}case"description":{let a=M(N.description,r.description);if(!a)break;t.push({name:"description",content:a},{property:"og:description",content:a},{property:"twitter:description",content:a});break}case"url":{let a=M(N.url,r.url);if(!a)break;let n=a.split("?")[0].replace(/\/$/,"");t.push({tagName:"link",rel:"canonical",href:n},{property:"og:url",content:n});break}case"handle":{let a=M(N.handle,r.handle);if(!a)break;t.push({property:"twitter:site",content:a},{property:"twitter:creator",content:a});break}case"media":{let a,i=$(r.media);for(let n of i)if(typeof n=="string"&&t.push({property:"og:image",content:n}),n&&typeof n=="object"){let s=n.type||"image",u=n?{url:n?.url,secure_url:n?.url,type:nt(n.url),width:n?.width,height:n?.height,alt:n?.altText}:{};for(let c of Object.keys(u))u[c]&&(a=u[c],t.push({property:`og:${s}:${c}`,content:a}));}break}case"jsonLd":{let a=$(r.jsonLd);for(let n of a)typeof n!="object"||Object.keys(n).length===0||t.push({"script:ld+json":n});break}case"alternates":{let a=$(r.alternates);for(let i of a){if(!i)continue;let{language:n,url:s,default:u}=i,c=n?`${n}${u?"-default":""}`:void 0;t.push({tagName:"link",rel:"alternate",hrefLang:c,href:s});}break}case"robots":{if(!r.robots)break;let{maxImagePreview:a,maxSnippet:i,maxVideoPreview:n,noArchive:s,noFollow:u,noImageIndex:c,noIndex:p,noSnippet:d,noTranslate:g,unavailableAfter:l}=r.robots,y=[s&&"noarchive",c&&"noimageindex",d&&"nosnippet",g&&"notranslate",a&&`max-image-preview:${a}`,i&&`max-snippet:${i}`,n&&`max-video-preview:${n}`,l&&`unavailable_after:${l}`],S=(p?"noindex":"index")+","+(u?"nofollow":"follow");for(let C of y)C&&(S+=`,${C}`);t.push({name:"robots",content:S});break}}return t}function yo({connection:e,children:t=()=>(console.warn("<Pagination> requires children to work properly"),null)}){let o=useNavigation().state==="loading",{endCursor:a,hasNextPage:i,hasPreviousPage:n,nextPageUrl:s,nodes:u,previousPageUrl:c,startCursor:p}=fo(e),d=useMemo(()=>({pageInfo:{endCursor:a,hasPreviousPage:n,hasNextPage:i,startCursor:p},nodes:u}),[a,i,n,p,u]),g=useMemo(()=>forwardRef(function(S,C){return i?createElement(Link,{preventScrollReset:!0,...S,to:s,state:d,replace:!0,ref:C}):null}),[i,s,d]),l=useMemo(()=>forwardRef(function(S,C){return n?createElement(Link,{preventScrollReset:!0,...S,to:c,state:d,replace:!0,ref:C}):null}),[n,c,d]);return t({state:d,hasNextPage:i,hasPreviousPage:n,isLoading:o,nextPageUrl:s,nodes:u,previousPageUrl:c,NextLink:g,PreviousLink:l})}function De(e){let t=new URLSearchParams(e);return t.delete("cursor"),t.delete("direction"),t.toString()}function fe(e){throw new Error(`The Pagination component requires ${"`"+e+"`"} to be a part of your query. See the guide on how to setup your query to include ${"`"+e+"`"}: https://shopify.dev/docs/custom-storefronts/hydrogen/data-fetching/pagination#setup-the-paginated-query`)}function fo(e){e.pageInfo||fe("pageInfo"),typeof e.pageInfo.startCursor>"u"&&fe("pageInfo.startCursor"),typeof e.pageInfo.endCursor>"u"&&fe("pageInfo.endCursor"),typeof e.pageInfo.hasNextPage>"u"&&fe("pageInfo.hasNextPage"),typeof e.pageInfo.hasPreviousPage>"u"&&fe("pageInfo.hasPreviousPage");let t=useNavigate(),{state:r,search:o,pathname:a}=useLocation(),s=new URLSearchParams(o).get("direction")==="previous",u=useMemo(()=>!globalThis?.window?.__hydrogenHydrated||!r||!r?.nodes?flattenConnection(e):s?[...flattenConnection(e),...r.nodes]:[...r.nodes,...flattenConnection(e)],[r,e]),c=useMemo(()=>{let l=globalThis?.window?.__hydrogenHydrated,y=!l||r?.pageInfo?.startCursor===void 0?e.pageInfo.startCursor:r.pageInfo.startCursor,S=!l||r?.pageInfo?.endCursor===void 0?e.pageInfo.endCursor:r.pageInfo.endCursor,C=!l||r?.pageInfo?.hasPreviousPage===void 0?e.pageInfo.hasPreviousPage:r.pageInfo.hasPreviousPage,f=!l||r?.pageInfo?.hasNextPage===void 0?e.pageInfo.hasNextPage:r.pageInfo.hasNextPage;return r?.nodes&&(s?(y=e.pageInfo.startCursor,C=e.pageInfo.hasPreviousPage):(S=e.pageInfo.endCursor,f=e.pageInfo.hasNextPage)),{startCursor:y,endCursor:S,hasPreviousPage:C,hasNextPage:f}},[s,r,e.pageInfo.hasNextPage,e.pageInfo.hasPreviousPage,e.pageInfo.startCursor,e.pageInfo.endCursor]),p=useRef({params:De(o),pathname:a});useEffect(()=>{window.__hydrogenHydrated=!0;},[]),useEffect(()=>{(De(o)!==p.current.params||a!==p.current.pathname)&&(p.current={pathname:a,params:De(o)},t(`${a}?${De(o)}`,{replace:!0,preventScrollReset:!0,state:{nodes:void 0,pageInfo:void 0}}));},[a,o]);let d=useMemo(()=>{let l=new URLSearchParams(o);return l.set("direction","previous"),c.startCursor&&l.set("cursor",c.startCursor),`?${l.toString()}`},[o,c.startCursor]),g=useMemo(()=>{let l=new URLSearchParams(o);return l.set("direction","next"),c.endCursor&&l.set("cursor",c.endCursor),`?${l.toString()}`},[o,c.endCursor]);return {...c,previousPageUrl:d,nextPageUrl:g,nodes:u}}function mo(e,t={pageBy:20}){if(typeof e?.url>"u")throw new Error("getPaginationVariables must be called with the Request object passed to your loader function");let{pageBy:r}=t,o=new URLSearchParams(new URL(e.url).search),a=o.get("cursor")??void 0;return (o.get("direction")==="previous"?"previous":"next")==="previous"?{last:r,startCursor:a??null}:{first:r,endCursor:a??null}}var Oe="2024-04",oe=`Shopify Hydrogen ${de}`,zt="30243aa5-17c1-465a-8493-944bcc4e88aa",O="customerAccount";var k=class extends Response{constructor(t,r,o){super(`Bad request: ${t}`,{status:400,headers:o});}};function ge(e,t={}){let r=t.headers?new Headers(t.headers):new Headers({});return r.set("location",e),new Response(null,{status:t.status||302,headers:r})}async function go({session:e,customerAccountId:t,customerAccountUrl:r,httpsOrigin:o,debugInfo:a}){let i=new URLSearchParams,s=e.get(O)?.refreshToken;if(!s)throw new k("Unauthorized","No refreshToken found in the session. Make sure your session is configured correctly and passed to `createCustomerAccountClient`.");i.append("grant_type","refresh_token"),i.append("refresh_token",s),i.append("client_id",t);let u={"content-type":"application/x-www-form-urlencoded","User-Agent":oe,Origin:o};new Date().getTime();let p=`${r}/auth/oauth/token`,d=await fetch(p,{method:"POST",headers:u,body:i});if(!d.ok){let f=await d.text();throw new Response(f,{status:d.status,headers:{"Content-Type":"text/html; charset=utf-8"}})}let{access_token:g,expires_in:l,id_token:y,refresh_token:S}=await d.json(),C=await st(g,t,r,o);e.set(O,{accessToken:C,expiresAt:new Date(new Date().getTime()+(l-120)*1e3).getTime()+"",refreshToken:S,idToken:y});}function ae(e){e.unset(O);}async function Jt({locks:e,expiresAt:t,session:r,customerAccountId:o,customerAccountUrl:a,httpsOrigin:i,debugInfo:n}){if(parseInt(t,10)-1e3<new Date().getTime())try{e.refresh||(e.refresh=go({session:r,customerAccountId:o,customerAccountUrl:a,httpsOrigin:i,debugInfo:n})),await e.refresh,delete e.refresh;}catch(s){throw ae(r),s&&s.status!==401?s:new k("Unauthorized","Login before querying the Customer Account API.",{"Set-Cookie":await r.commit()})}}function Yt(){let e=ho();return Zt(e)}async function Xt(e){let t=await crypto.subtle.digest({name:"SHA-256"},new TextEncoder().encode(e)),r=Co(t);return Zt(r)}function ho(){let e=new Uint8Array(32);return crypto.getRandomValues(e),String.fromCharCode.apply(null,Array.from(e))}function Zt(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Co(e){let t=new Uint8Array(e),r=Array.from(t);return String.fromCharCode(...r)}function er(){let e=Date.now().toString(),t=Math.random().toString(36).substring(2);return e+t}async function st(e,t,r,o,a){let i=t;if(!e)throw new k("Unauthorized","oAuth access token was not provided during token exchange.");let n=new URLSearchParams;n.append("grant_type","urn:ietf:params:oauth:grant-type:token-exchange"),n.append("client_id",i),n.append("audience",zt),n.append("subject_token",e),n.append("subject_token_type","urn:ietf:params:oauth:token-type:access_token"),n.append("scopes","https://api.customers.com/auth/customer.graphql");let s={"content-type":"application/x-www-form-urlencoded","User-Agent":oe,Origin:o};new Date().getTime();let c=`${r}/auth/oauth/token`,p=await fetch(c,{method:"POST",headers:s,body:n});let d=await p.json();if(d.error)throw new k(d.error_description);return d.access_token}function tr(e){return So(e).payload.nonce}function So(e){let[t,r,o]=e.split("."),a=JSON.parse(atob(t)),i=JSON.parse(atob(r));return {header:a,payload:i,signature:o}}function Ue(){return Ao(Po())}function Po(){try{return crypto.getRandomValues(new Uint8Array(16))}catch{return new Uint8Array(16).map(()=>Math.random()*255|0)}}function Ao(e){return Array.from(e,function(t){return ("0"+(t&255).toString(16)).slice(-2)}).join("")}var rr="/account/login",vo="/account/authorize",or="/account";function To(e){if(!e.url)return rr;let{pathname:t}=new URL(e.url),r=rr+`?${new URLSearchParams({return_to:t}).toString()}`;return ge(r)}function Ro({session:e,customerAccountId:t,customerAccountUrl:r,customerApiVersion:o=Oe,request:a,waitUntil:i,authUrl:n,customAuthStatusHandler:s,logErrors:u=!0}){if(o!==Oe&&console.warn(`[h2:warn:createCustomerAccountClient] You are using Customer Account API version ${o} when this version of Hydrogen was built for ${Oe}.`),!a?.url)throw new Error("[h2:error:createCustomerAccountClient] The request object does not contain a URL.");let c=s||(()=>To(a)),p=new URL(a.url),d=p.protocol==="http:"?p.origin.replace("http","https"):p.origin,g=et({requestUrl:d,defaultUrl:vo,redirectUrl:n}),l=`${r}/account/customer/api/${o}/graphql`,y={};async function S({query:m,type:h,variables:A={}}){let v=await T();if(!v)throw c();new Date().getTime();let U=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":oe,Origin:d,Authorization:v},body:JSON.stringify({query:m,variables:A})});let E=await U.text(),x={url:l,response:U,type:h,query:m,queryVariables:A,errors:void 0,client:"customer"};if(!U.ok){if(U.status===401){ae(e);let _=c();throw _ instanceof Response&&_.headers.set("Set-Cookie",await e.commit()),_}let I;try{I=G(E);}catch{I=[{message:E}];}le({...x,errors:I});}try{let I=G(E),{errors:_}=I,V=_?.map(({message:Y,...Q})=>new B(Y,{...Q,clientOperation:`customerAccount.${x.type}`,requestId:U.headers.get("x-request-id"),queryVariables:A,query:m}));return {...I,..._&&{errors:V}}}catch{le({...x,errors:[{message:E}]});}}async function C(){if(!r||!t)return !1;let m=e.get(O),h=m?.accessToken,A=m?.expiresAt;if(!h||!A)return !1;let v=L?.();try{await Jt({locks:y,expiresAt:A,session:e,customerAccountId:t,customerAccountUrl:r,httpsOrigin:d,debugInfo:{waitUntil:i,stackInfo:v,...W(a)}});}catch{return !1}return !0}async function f(){if(!await C())throw c()}async function T(){if(await C())return e.get(O)?.accessToken}return {login:async m=>{he(r,t);let h=new URL(`${r}/auth/oauth/authorize`),A=er(),v=Ue();if(h.searchParams.set("client_id",t),h.searchParams.set("scope","openid email"),h.searchParams.append("response_type","code"),h.searchParams.append("redirect_uri",g),h.searchParams.set("scope","openid email https://api.customers.com/auth/customer.graphql"),h.searchParams.append("state",A),h.searchParams.append("nonce",v),m?.uiLocales){let[U,E]=m.uiLocales.split("-"),x=U.toLowerCase();E&&(x+=`-${E.toUpperCase()}`),h.searchParams.append("ui_locales",x);}let R=Yt(),H=await Xt(R);return e.set(O,{...e.get(O),codeVerifier:R,state:A,nonce:v,redirectPath:Ee(a.url)||be(a,"Referer")||or}),h.searchParams.append("code_challenge",H),h.searchParams.append("code_challenge_method","S256"),ge(h.toString(),{headers:{"Set-Cookie":await e.commit()}})},logout:async m=>{he(r,t);let h=e.get(O)?.idToken,A=et({requestUrl:d,defaultUrl:d,redirectUrl:m?.postLogoutRedirectUri}),v=h?new URL(`${r}/auth/logout?${new URLSearchParams([["id_token_hint",h],["post_logout_redirect_uri",A]]).toString()}`).toString():A;return ae(e),ge(v,{status:302,headers:{"Set-Cookie":await e.commit()}})},isLoggedIn:C,handleAuthStatus:f,getAccessToken:T,getApiUrl:()=>l,mutate(m,h){return he(r,t),m=te(m),we(m,"customer.mutate"),re(S({query:m,type:"mutation",...h}),{logErrors:u})},query(m,h){return he(r,t),m=te(m),Ie(m,"customer.query"),re(S({query:m,type:"query",...h}),{logErrors:u})},authorize:async()=>{he(r,t);let m=p.searchParams.get("code"),h=p.searchParams.get("state");if(!m||!h)throw ae(e),new k("Unauthorized","No code or state parameter found in the redirect URL.",{"Set-Cookie":await e.commit()});if(e.get(O)?.state!==h)throw ae(e),new k("Unauthorized","The session state does not match the state parameter. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.",{"Set-Cookie":await e.commit()});let A=t,v=new URLSearchParams;v.append("grant_type","authorization_code"),v.append("client_id",A),v.append("redirect_uri",g),v.append("code",m);let R=e.get(O)?.codeVerifier;if(!R)throw new k("Unauthorized","No code verifier found in the session. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.");v.append("code_verifier",R);let H={"content-type":"application/x-www-form-urlencoded","User-Agent":oe,Origin:d},U=L?.();new Date().getTime();let x=`${r}/auth/oauth/token`,I=await fetch(x,{method:"POST",headers:H,body:v});if(!I.ok)throw new Response(await I.text(),{status:I.status,headers:{"Content-Type":"text/html; charset=utf-8"}});let{access_token:_,expires_in:V,id_token:Y,refresh_token:Q}=await I.json(),X=e.get(O)?.nonce,se=await tr(Y);if(X!==se)throw new k("Unauthorized",`Returned nonce does not match: ${X} !== ${se}`);let Ve=await st(_,t,r,d,{waitUntil:i,stackInfo:U,...W(a)}),Fe=e.get(O)?.redirectPath;return e.set(O,{accessToken:Ve,expiresAt:new Date(new Date().getTime()+(V-120)*1e3).getTime()+"",refreshToken:Q,idToken:Y,redirectPath:void 0}),ge(Fe||or,{headers:{"Set-Cookie":await e.commit()}})}}}function he(e,t){try{if(!e||!t)throw Error();new URL(e);}catch{console.error(new Error("[h2:error:customerAccount] You do not have the valid credential to use Customer Account API.\nRun `h2 env pull` to link your store credentials."));let r="Internal Server Error";throw new Response(r,{status:500})}}var Io="https://raw.githubusercontent.com/Shopify/hydrogen/main/docs/changelog.json";async function wo({request:e,changelogUrl:t}){new URL(e.url).searchParams;return fetch(t||Io)}var ar="cartFormInput";function _e({children:e,action:t,inputs:r,route:o,fetcherKey:a}){let i=useFetcher({key:a});return jsxs(i.Form,{action:o||"",method:"post",children:[(t||r)&&jsx("input",{type:"hidden",name:ar,value:JSON.stringify({action:t,inputs:r})}),typeof e=="function"?e(i):e]})}_e.INPUT_NAME=ar;_e.ACTIONS={AttributesUpdateInput:"AttributesUpdateInput",BuyerIdentityUpdate:"BuyerIdentityUpdate",Create:"Create",DiscountCodesUpdate:"DiscountCodesUpdate",LinesAdd:"LinesAdd",LinesRemove:"LinesRemove",LinesUpdate:"LinesUpdate",NoteUpdate:"NoteUpdate",SelectedDeliveryOptionsUpdate:"SelectedDeliveryOptionsUpdate",MetafieldsSet:"MetafieldsSet",MetafieldDelete:"MetafieldDelete"};function Eo(e){let t={};for(let n of e.entries()){let s=n[0],u=e.getAll(s);t[s]=u.length>1?u:n[1];}let{cartFormInput:r,...o}=t,{action:a,inputs:i}=r?JSON.parse(String(r)):{};return {action:a,inputs:{...i,...o}}}_e.getFormInput=Eo;var w=`#graphql
293
+ `,{status:200,headers:{"content-type":"text/html"}})};var ao={"&":"\\u0026",">":"\\u003e","<":"\\u003c","\u2028":"\\u2028","\u2029":"\\u2029"},no=/[&><\u2028\u2029]/g;function Wt(e){return e.replace(no,t=>ao[t])}var G="Error in SEO input: ",H={title:{validate:e=>{if(typeof e!="string")throw new Error(G.concat("`title` should be a string"));if(typeof e=="string"&&e.length>120)throw new Error(G.concat("`title` should not be longer than 120 characters"));return e}},description:{validate:e=>{if(typeof e!="string")throw new Error(G.concat("`description` should be a string"));if(typeof e=="string"&&e.length>155)throw new Error(G.concat("`description` should not be longer than 155 characters"));return e}},url:{validate:e=>{if(typeof e!="string")throw new Error(G.concat("`url` should be a string"));if(typeof e=="string"&&!e.startsWith("http"))throw new Error(G.concat("`url` should be a valid URL"));return e}},handle:{validate:e=>{if(typeof e!="string")throw new Error(G.concat("`handle` should be a string"));if(typeof e=="string"&&!e.startsWith("@"))throw new Error(G.concat("`handle` should start with `@`"));return e}}};function jt(e){let t=[];for(let r of Object.keys(e))switch(r){case"title":{let o=Q(H.title,e.title),a=it(e?.titleTemplate,o);if(!a)break;t.push(x("title",{title:a}),x("meta",{property:"og:title",content:a}),x("meta",{name:"twitter:title",content:a}));break}case"description":{let o=Q(H.description,e.description);if(!o)break;t.push(x("meta",{name:"description",content:o}),x("meta",{property:"og:description",content:o}),x("meta",{name:"twitter:description",content:o}));break}case"url":{let o=Q(H.url,e.url);if(!o)break;let s=o.split("?")[0].replace(/\/$/,"");t.push(x("link",{rel:"canonical",href:s}),x("meta",{property:"og:url",content:s}));break}case"handle":{let o=Q(H.handle,e.handle);if(!o)break;t.push(x("meta",{name:"twitter:site",content:o}),x("meta",{name:"twitter:creator",content:o}));break}case"media":{let o,a=B(e.media);for(let s of a)if(typeof s=="string"&&t.push(x("meta",{name:"og:image",content:s})),s&&typeof s=="object"){let n=s.type||"image",i=s?{url:s?.url,secure_url:s?.url,type:ct(s.url),width:s?.width,height:s?.height,alt:s?.altText}:{};for(let u of Object.keys(i))i[u]&&(o=i[u],t.push(x("meta",{property:`og:${n}:${u}`,content:o},i.url)));}break}case"jsonLd":{let o=B(e.jsonLd),a=0;for(let s of o){if(typeof s!="object")continue;let n=x("script",{type:"application/ld+json",children:JSON.stringify(s,(i,u)=>typeof u=="string"?Wt(u):u)},`json-ld-${s?.["@type"]||s?.name||a++}`);t.push(n);}break}case"alternates":{let o=B(e.alternates);for(let a of o){if(!a)continue;let{language:s,url:n,default:i}=a,u=s?`${s}${i?"-default":""}`:void 0;t.push(x("link",{rel:"alternate",hrefLang:u,href:n}));}break}case"robots":{if(!e.robots)break;let{maxImagePreview:o,maxSnippet:a,maxVideoPreview:s,noArchive:n,noFollow:i,noImageIndex:u,noIndex:c,noSnippet:d,noTranslate:y,unavailableAfter:m}=e.robots,p=[n&&"noarchive",u&&"noimageindex",d&&"nosnippet",y&&"notranslate",o&&`max-image-preview:${o}`,a&&`max-snippet:${a}`,s&&`max-video-preview:${s}`,m&&`unavailable_after:${m}`],l=(c?"noindex":"index")+","+(i?"nofollow":"follow");for(let g of p)g&&(l+=`,${g}`);t.push(x("meta",{name:"robots",content:l}));break}}return t.flat().sort((r,o)=>r.key.localeCompare(o.key))}function x(e,t,r){let o={tag:e,props:{},key:""};return e==="title"?(o.children=t.title,o.key=st(o),o):e==="script"?(o.children=typeof t.children=="string"?t.children:"",o.key=st(o,r),delete t.children,o.props=t,o):(o.props=t,Object.keys(o.props).forEach(a=>!o.props[a]&&delete o.props[a]),o.key=st(o,r),o)}function st(e,t){let{tag:r,props:o}=e;if(r==="title")return "0-title";if(r==="meta"){let a=o.content===t&&typeof o.property=="string"&&!o.property.endsWith("secure_url")&&"0";return [r,...[t,a],o.property||o.name].filter(n=>n).join("-")}return r==="link"?[r,o.rel,o.hrefLang||o.media].filter(s=>s).join("-").replace(/\s+/g,"-"):r==="script"?`${r}-${t}`:`${r}-${o.type}`}function it(e,t){if(t)return e?typeof e=="function"?e(t):e.replace("%s",t??""):t}function ct(e){switch(e&&e.split(".").pop()){case"svg":return "image/svg+xml";case"png":return "image/png";case"gif":return "image/gif";case"swf":return "application/x-shockwave-flash";case"mp3":return "audio/mpeg";case"jpg":case"jpeg":default:return "image/jpeg"}}function B(e){return Array.isArray(e)?e:[e]}function Q(e,t){try{return e.validate(t)}catch(r){return console.warn(r.message),t}}var lo=lazy(()=>import('./log-seo-tags-TY72EQWZ.js'));function yo({debug:e}){let t=useMatches(),r=useLocation();console.warn("[h2:warn:Seo] The `<Seo/>` component is deprecated. Use `getSeoMeta` instead.\nSee: https://shopify.dev/docs/api/hydrogen/2024-01/utilities/getseometa");let o=useMemo(()=>t.flatMap(n=>{let{handle:i,...u}=n,c={...u,...r},d=i?.seo,y=u?.data?.seo;return !d&&!y?[]:d?Le(d,c):[y]}).reduce((n,i)=>{Object.keys(i).forEach(c=>!i[c]&&delete i[c]);let{jsonLd:u}=i;return u?n?.jsonLd?Array.isArray(u)?{...n,...i,jsonLd:[...n.jsonLd,...u]}:{...n,...i,jsonLd:[...n.jsonLd,u]}:{...n,...i,jsonLd:[u]}:{...n,...i}},{}),[t,r]),{html:a,loggerMarkup:s}=useMemo(()=>{let n=jt(o),i=n.map(c=>c.tag==="script"?createElement(c.tag,{...c.props,key:c.key,dangerouslySetInnerHTML:{__html:c.children}}):createElement(c.tag,{...c.props,key:c.key},c.children)),u=createElement(Suspense,{fallback:null},createElement(lo,{headTags:n}));return {html:i,loggerMarkup:u}},[o]);return createElement(Fragment,null,a,e&&s)}function Le(e,...t){if(e instanceof Function)return Le(e(...t),...t);let r={};return Array.isArray(e)?(r=e.reduce((o,a)=>[...o,Le(a)],[]),r):e instanceof Object?(Object.entries(e).forEach(([a,s])=>{r[a]=Le(s,...t);}),r):e}function fo(...e){let t=[],r=e.reduce((o,a)=>{if(!a)return o;Object.keys(a).forEach(n=>!a[n]&&delete a[n]);let{jsonLd:s}=a;return s?o?.jsonLd?{...o,...a,jsonLd:B(o.jsonLd).concat(s)}:{...o,...a,jsonLd:[s]}:{...o,...a}},{})||{};for(let o of Object.keys(r))switch(o){case"title":{let a=Q(H.title,r.title),s=it(r?.titleTemplate,a);if(!s)break;t.push({title:s},{property:"og:title",content:s},{property:"twitter:title",content:s});break}case"description":{let a=Q(H.description,r.description);if(!a)break;t.push({name:"description",content:a},{property:"og:description",content:a},{property:"twitter:description",content:a});break}case"url":{let a=Q(H.url,r.url);if(!a)break;let n=a.split("?")[0].replace(/\/$/,"");t.push({tagName:"link",rel:"canonical",href:n},{property:"og:url",content:n});break}case"handle":{let a=Q(H.handle,r.handle);if(!a)break;t.push({property:"twitter:site",content:a},{property:"twitter:creator",content:a});break}case"media":{let a,s=B(r.media);for(let n of s)if(typeof n=="string"&&t.push({property:"og:image",content:n}),n&&typeof n=="object"){let i=n.type||"image",u=n?{url:n?.url,secure_url:n?.url,type:ct(n.url),width:n?.width,height:n?.height,alt:n?.altText}:{};for(let c of Object.keys(u))u[c]&&(a=u[c],t.push({property:`og:${i}:${c}`,content:a}));}break}case"jsonLd":{let a=B(r.jsonLd);for(let n of a)typeof n!="object"||Object.keys(n).length===0||t.push({"script:ld+json":n});break}case"alternates":{let a=B(r.alternates);for(let s of a){if(!s)continue;let{language:n,url:i,default:u}=s,c=n?`${n}${u?"-default":""}`:void 0;t.push({tagName:"link",rel:"alternate",hrefLang:c,href:i});}break}case"robots":{if(!r.robots)break;let{maxImagePreview:a,maxSnippet:s,maxVideoPreview:n,noArchive:i,noFollow:u,noImageIndex:c,noIndex:d,noSnippet:y,noTranslate:m,unavailableAfter:p}=r.robots,l=[i&&"noarchive",c&&"noimageindex",y&&"nosnippet",m&&"notranslate",a&&`max-image-preview:${a}`,s&&`max-snippet:${s}`,n&&`max-video-preview:${n}`,p&&`unavailable_after:${p}`],g=(d?"noindex":"index")+","+(u?"nofollow":"follow");for(let S of l)S&&(g+=`,${S}`);t.push({name:"robots",content:g});break}}return t}function So({connection:e,children:t=()=>(console.warn("<Pagination> requires children to work properly"),null)}){let o=useNavigation().state==="loading",{endCursor:a,hasNextPage:s,hasPreviousPage:n,nextPageUrl:i,nodes:u,previousPageUrl:c,startCursor:d}=Po(e),y=useMemo(()=>({pageInfo:{endCursor:a,hasPreviousPage:n,hasNextPage:s,startCursor:d},nodes:u}),[a,s,n,d,u]),m=useMemo(()=>forwardRef(function(g,S){return s?createElement(Link,{preventScrollReset:!0,...g,to:i,state:y,replace:!0,ref:S}):null}),[s,i,y]),p=useMemo(()=>forwardRef(function(g,S){return n?createElement(Link,{preventScrollReset:!0,...g,to:c,state:y,replace:!0,ref:S}):null}),[n,c,y]);return t({state:y,hasNextPage:s,hasPreviousPage:n,isLoading:o,nextPageUrl:i,nodes:u,previousPageUrl:c,NextLink:m,PreviousLink:p})}function Ne(e){let t=new URLSearchParams(e);return t.delete("cursor"),t.delete("direction"),t.toString()}function Ce(e){throw new Error(`The Pagination component requires ${"`"+e+"`"} to be a part of your query. See the guide on how to setup your query to include ${"`"+e+"`"}: https://shopify.dev/docs/custom-storefronts/hydrogen/data-fetching/pagination#setup-the-paginated-query`)}function Po(e){e.pageInfo||Ce("pageInfo"),typeof e.pageInfo.startCursor>"u"&&Ce("pageInfo.startCursor"),typeof e.pageInfo.endCursor>"u"&&Ce("pageInfo.endCursor"),typeof e.pageInfo.hasNextPage>"u"&&Ce("pageInfo.hasNextPage"),typeof e.pageInfo.hasPreviousPage>"u"&&Ce("pageInfo.hasPreviousPage");let t=useNavigate(),{state:r,search:o,pathname:a}=useLocation(),i=new URLSearchParams(o).get("direction")==="previous",u=useMemo(()=>!globalThis?.window?.__hydrogenHydrated||!r||!r?.nodes?flattenConnection(e):i?[...flattenConnection(e),...r.nodes]:[...r.nodes,...flattenConnection(e)],[r,e]),c=useMemo(()=>{let p=globalThis?.window?.__hydrogenHydrated,l=!p||r?.pageInfo?.startCursor===void 0?e.pageInfo.startCursor:r.pageInfo.startCursor,g=!p||r?.pageInfo?.endCursor===void 0?e.pageInfo.endCursor:r.pageInfo.endCursor,S=!p||r?.pageInfo?.hasPreviousPage===void 0?e.pageInfo.hasPreviousPage:r.pageInfo.hasPreviousPage,f=!p||r?.pageInfo?.hasNextPage===void 0?e.pageInfo.hasNextPage:r.pageInfo.hasNextPage;return r?.nodes&&(i?(l=e.pageInfo.startCursor,S=e.pageInfo.hasPreviousPage):(g=e.pageInfo.endCursor,f=e.pageInfo.hasNextPage)),{startCursor:l,endCursor:g,hasPreviousPage:S,hasNextPage:f}},[i,r,e.pageInfo.hasNextPage,e.pageInfo.hasPreviousPage,e.pageInfo.startCursor,e.pageInfo.endCursor]),d=useRef({params:Ne(o),pathname:a});useEffect(()=>{window.__hydrogenHydrated=!0;},[]),useEffect(()=>{(Ne(o)!==d.current.params||a!==d.current.pathname)&&(d.current={pathname:a,params:Ne(o)},t(`${a}?${Ne(o)}`,{replace:!0,preventScrollReset:!0,state:{nodes:void 0,pageInfo:void 0}}));},[a,o]);let y=useMemo(()=>{let p=new URLSearchParams(o);return p.set("direction","previous"),c.startCursor&&p.set("cursor",c.startCursor),`?${p.toString()}`},[o,c.startCursor]),m=useMemo(()=>{let p=new URLSearchParams(o);return p.set("direction","next"),c.endCursor&&p.set("cursor",c.endCursor),`?${p.toString()}`},[o,c.endCursor]);return {...c,previousPageUrl:y,nextPageUrl:m,nodes:u}}function Ao(e,t={pageBy:20}){if(typeof e?.url>"u")throw new Error("getPaginationVariables must be called with the Request object passed to your loader function");let{pageBy:r}=t,o=new URLSearchParams(new URL(e.url).search),a=o.get("cursor")??void 0;return (o.get("direction")==="previous"?"previous":"next")==="previous"?{last:r,startCursor:a??null}:{first:r,endCursor:a??null}}var k=class extends Response{constructor(t,r,o){super(`Bad request: ${t}`,{status:400,headers:o});}};function Pe(e,t={}){let r=t.headers?new Headers(t.headers):new Headers({});return r.set("location",e),new Response(null,{status:t.status||302,headers:r})}async function To({session:e,customerAccountId:t,customerAccountUrl:r,httpsOrigin:o,debugInfo:a,exchangeForStorefrontCustomerAccessToken:s}){let n=new URLSearchParams,u=e.get(E)?.refreshToken;if(!u)throw new k("Unauthorized","No refreshToken found in the session. Make sure your session is configured correctly and passed to `createCustomerAccountClient`.");n.append("grant_type","refresh_token"),n.append("refresh_token",u),n.append("client_id",t);let c={"content-type":"application/x-www-form-urlencoded","User-Agent":ae,Origin:o};new Date().getTime();let y=`${r}/auth/oauth/token`,m=await fetch(y,{method:"POST",headers:c,body:n});if(!m.ok){let R=await m.text();throw new Response(R,{status:m.status,headers:{"Content-Type":"text/html; charset=utf-8"}})}let{access_token:p,expires_in:l,id_token:g,refresh_token:S}=await m.json(),f=await pt(p,t,r,o);e.set(E,{accessToken:f,expiresAt:new Date(new Date().getTime()+(l-120)*1e3).getTime()+"",refreshToken:S,idToken:g}),await s();}function ce(e){e.unset(E),e.unset(ne);}async function Zt({locks:e,expiresAt:t,session:r,customerAccountId:o,customerAccountUrl:a,httpsOrigin:s,debugInfo:n,exchangeForStorefrontCustomerAccessToken:i}){if(parseInt(t,10)-1e3<new Date().getTime())try{e.refresh||(e.refresh=To({session:r,customerAccountId:o,customerAccountUrl:a,httpsOrigin:s,debugInfo:n,exchangeForStorefrontCustomerAccessToken:i})),await e.refresh,delete e.refresh;}catch(u){throw ce(r),u&&u.status!==401?u:new k("Unauthorized","Login before querying the Customer Account API.",{"Set-Cookie":await r.commit()})}}function er(){let e=vo();return rr(e)}async function tr(e){let t=await crypto.subtle.digest({name:"SHA-256"},new TextEncoder().encode(e)),r=Ro(t);return rr(r)}function vo(){let e=new Uint8Array(32);return crypto.getRandomValues(e),String.fromCharCode.apply(null,Array.from(e))}function rr(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ro(e){let t=new Uint8Array(e),r=Array.from(t);return String.fromCharCode(...r)}function or(){let e=Date.now().toString(),t=Math.random().toString(36).substring(2);return e+t}async function pt(e,t,r,o,a){let s=t;if(!e)throw new k("Unauthorized","oAuth access token was not provided during token exchange.");let n=new URLSearchParams;n.append("grant_type","urn:ietf:params:oauth:grant-type:token-exchange"),n.append("client_id",s),n.append("audience",Ft),n.append("subject_token",e),n.append("subject_token_type","urn:ietf:params:oauth:token-type:access_token"),n.append("scopes","https://api.customers.com/auth/customer.graphql");let i={"content-type":"application/x-www-form-urlencoded","User-Agent":ae,Origin:o};new Date().getTime();let c=`${r}/auth/oauth/token`,d=await fetch(c,{method:"POST",headers:i,body:n});let y=await d.json();if(y.error)throw new k(y.error_description);return y.access_token}function ar(e){return Io(e).payload.nonce}function Io(e){let[t,r,o]=e.split("."),a=JSON.parse(atob(t)),s=JSON.parse(atob(r));return {header:a,payload:s,signature:o}}function Me(){return bo(wo())}function wo(){try{return crypto.getRandomValues(new Uint8Array(16))}catch{return new Uint8Array(16).map(()=>Math.random()*255|0)}}function bo(e){return Array.from(e,function(t){return ("0"+(t&255).toString(16)).slice(-2)}).join("")}var nr="/account/login",Eo="/account/authorize",sr="/account";function xo(e){if(!e.url)return nr;let{pathname:t}=new URL(e.url),r=nr+`?${new URLSearchParams({return_to:t}).toString()}`;return Pe(r)}function Do({session:e,customerAccountId:t,customerAccountUrl:r,customerApiVersion:o=De,request:a,waitUntil:s,authUrl:n,customAuthStatusHandler:i,logErrors:u=!0,unstableB2b:c=!1}){if(o!==De&&console.warn(`[h2:warn:createCustomerAccountClient] You are using Customer Account API version ${o} when this version of Hydrogen was built for ${De}.`),!a?.url)throw new Error("[h2:error:createCustomerAccountClient] The request object does not contain a URL.");let d=i||(()=>xo(a)),y=new URL(a.url),m=y.protocol==="http:"?y.origin.replace("http","https"):y.origin,p=ot({requestUrl:m,defaultUrl:Eo,redirectUrl:n}),l=`${r}/account/customer/api/${o}/graphql`,g={};async function S({query:h,type:C,variables:A={}}){let T=await v();if(!T)throw d();new Date().getTime();let D=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ae,Origin:m,Authorization:T},body:JSON.stringify({query:h,variables:A})});let O=await D.text(),U={url:l,response:D,type:C,query:h,queryVariables:A,errors:void 0,client:"customer"};if(!D.ok){if(D.status===401){ce(e);let L=d();throw L instanceof Response&&L.headers.set("Set-Cookie",await e.commit()),L}let b;try{b=j(O);}catch{b=[{message:O}];}ge({...U,errors:b});}try{let b=j(O),{errors:L}=b,de=L?.map(({message:te,...$})=>new K(te,{...$,clientOperation:`customerAccount.${U.type}`,requestId:D.headers.get("x-request-id"),queryVariables:A,query:h}));return {...b,...L&&{errors:de}}}catch{ge({...U,errors:[{message:O}]});}}async function f(){if(!r||!t)return !1;let h=e.get(E),C=h?.accessToken,A=h?.expiresAt;if(!C||!A)return !1;let T=q?.();try{await Zt({locks:g,expiresAt:A,session:e,customerAccountId:t,customerAccountUrl:r,httpsOrigin:m,debugInfo:{waitUntil:s,stackInfo:T,...z(a)},exchangeForStorefrontCustomerAccessToken:we});}catch{return !1}return !0}async function R(){if(!await f())throw d()}async function v(){if(await f())return e.get(E)?.accessToken}async function N(h,C){return Ae(r,t),h=se(h),Ue(h,"customer.mutate"),ie(S({query:h,type:"mutation",...C}),{logErrors:u})}async function F(h,C){return Ae(r,t),h=se(h),Oe(h,"customer.query"),ie(S({query:h,type:"query",...C}),{logErrors:u})}function ee(h){e.set(ne,{...e.get(ne),...h});}async function _(){if(await f())return e.get(ne)}async function we(){if(!c)return;let h=`#graphql
294
+ mutation storefrontCustomerAccessTokenCreate {
295
+ storefrontCustomerAccessTokenCreate {
296
+ customerAccessToken
297
+ }
298
+ }
299
+ `,{data:C}=await N(h),A=C?.storefrontCustomerAccessTokenCreate?.customerAccessToken;A&&ee({customerAccessToken:A});}return {login:async h=>{Ae(r,t);let C=new URL(`${r}/auth/oauth/authorize`),A=or(),T=Me();if(C.searchParams.set("client_id",t),C.searchParams.set("scope","openid email"),C.searchParams.append("response_type","code"),C.searchParams.append("redirect_uri",p),C.searchParams.set("scope","openid email https://api.customers.com/auth/customer.graphql"),C.searchParams.append("state",A),C.searchParams.append("nonce",T),h?.uiLocales){let[D,O]=h.uiLocales.split("-"),U=D.toLowerCase();O&&(U+=`-${O.toUpperCase()}`),C.searchParams.append("ui_locales",U);}let M=er(),V=await tr(M);return e.set(E,{...e.get(E),codeVerifier:M,state:A,nonce:T,redirectPath:ke(a.url)||_e(a,"Referer")||sr}),C.searchParams.append("code_challenge",V),C.searchParams.append("code_challenge_method","S256"),Pe(C.toString(),{headers:{"Set-Cookie":await e.commit()}})},logout:async h=>{Ae(r,t);let C=e.get(E)?.idToken,A=ot({requestUrl:m,defaultUrl:m,redirectUrl:h?.postLogoutRedirectUri}),T=C?new URL(`${r}/auth/logout?${new URLSearchParams([["id_token_hint",C],["post_logout_redirect_uri",A]]).toString()}`).toString():A;return ce(e),Pe(T,{status:302,headers:{"Set-Cookie":await e.commit()}})},isLoggedIn:f,handleAuthStatus:R,getAccessToken:v,getApiUrl:()=>l,mutate:N,query:F,authorize:async()=>{Ae(r,t);let h=y.searchParams.get("code"),C=y.searchParams.get("state");if(!h||!C)throw ce(e),new k("Unauthorized","No code or state parameter found in the redirect URL.",{"Set-Cookie":await e.commit()});if(e.get(E)?.state!==C)throw ce(e),new k("Unauthorized","The session state does not match the state parameter. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.",{"Set-Cookie":await e.commit()});let A=t,T=new URLSearchParams;T.append("grant_type","authorization_code"),T.append("client_id",A),T.append("redirect_uri",p),T.append("code",h);let M=e.get(E)?.codeVerifier;if(!M)throw new k("Unauthorized","No code verifier found in the session. Make sure that the session is configured correctly and passed to `createCustomerAccountClient`.");T.append("code_verifier",M);let V={"content-type":"application/x-www-form-urlencoded","User-Agent":ae,Origin:m},D=q?.();new Date().getTime();let U=`${r}/auth/oauth/token`,b=await fetch(U,{method:"POST",headers:V,body:T});if(!b.ok)throw new Response(await b.text(),{status:b.status,headers:{"Content-Type":"text/html; charset=utf-8"}});let{access_token:L,expires_in:de,id_token:te,refresh_token:$}=await b.json(),le=e.get(E)?.nonce,xt=await ar(te);if(le!==xt)throw new k("Unauthorized",`Returned nonce does not match: ${le} !== ${xt}`);let Nr=await pt(L,t,r,m,{waitUntil:s,stackInfo:D,...z(a)}),Mr=e.get(E)?.redirectPath;return e.set(E,{accessToken:Nr,expiresAt:new Date(new Date().getTime()+(de-120)*1e3).getTime()+"",refreshToken:$,idToken:te}),await we(),Pe(Mr||sr,{headers:{"Set-Cookie":await e.commit()}})},UNSTABLE_setBuyer:ee,UNSTABLE_getBuyer:_}}function Ae(e,t){try{if(!e||!t)throw Error();new URL(e);}catch{console.error(new Error("[h2:error:customerAccount] You do not have the valid credential to use Customer Account API.\nRun `h2 env pull` to link your store credentials."));let r="Internal Server Error";throw new Response(r,{status:500})}}var Oo="https://raw.githubusercontent.com/Shopify/hydrogen/main/docs/changelog.json";async function Uo({request:e,changelogUrl:t}){new URL(e.url).searchParams;return fetch(t||Oo)}var ir="cartFormInput";function Ve({children:e,action:t,inputs:r,route:o,fetcherKey:a}){let s=useFetcher({key:a});return jsxs(s.Form,{action:o||"",method:"post",children:[(t||r)&&jsx("input",{type:"hidden",name:ir,value:JSON.stringify({action:t,inputs:r})}),typeof e=="function"?e(s):e]})}Ve.INPUT_NAME=ir;Ve.ACTIONS={AttributesUpdateInput:"AttributesUpdateInput",BuyerIdentityUpdate:"BuyerIdentityUpdate",Create:"Create",DiscountCodesUpdate:"DiscountCodesUpdate",LinesAdd:"LinesAdd",LinesRemove:"LinesRemove",LinesUpdate:"LinesUpdate",NoteUpdate:"NoteUpdate",SelectedDeliveryOptionsUpdate:"SelectedDeliveryOptionsUpdate",MetafieldsSet:"MetafieldsSet",MetafieldDelete:"MetafieldDelete"};function ko(e){let t={};for(let n of e.entries()){let i=n[0],u=e.getAll(i);t[i]=u.length>1?u:n[1];}let{cartFormInput:r,...o}=t,{action:a,inputs:s}=r?JSON.parse(String(r)):{};return {action:a,inputs:{...s,...o}}}Ve.getFormInput=ko;var I=`#graphql
293
300
  fragment CartApiError on CartUserError {
294
301
  message
295
302
  field
296
303
  code
297
304
  }
298
- `,b=`#graphql
305
+ `,w=`#graphql
299
306
  fragment CartApiMutation on Cart {
300
307
  id
301
308
  totalQuantity
302
309
  }
303
- `;function ct(e){return async(t,r)=>{let{cartId:o,...a}=r||{},{cartCreate:i,errors:n}=await e.storefront.mutate(Oo(e.cartFragment),{variables:{input:t,...a}});return P(i,n)}}var Oo=(e=b)=>`#graphql
310
+ `;function dt(e){return async(t,r)=>{let o=e.customerAccount?await e.customerAccount.UNSTABLE_getBuyer():void 0,{cartId:a,...s}=r||{},{buyerIdentity:n,...i}=t,{cartCreate:u,errors:c}=await e.storefront.mutate(Mo(e.cartFragment),{variables:{input:{...i,buyerIdentity:{...o,...n}},...s}});return P(u,c)}}var Mo=(e=w)=>`#graphql
304
311
  mutation cartCreate(
305
312
  $input: CartInput!
306
313
  $country: CountryCode = ZZ
@@ -317,8 +324,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
317
324
  }
318
325
  }
319
326
  ${e}
320
- ${w}
321
- `;function ut({storefront:e,customerAccount:t,getCartId:r,cartFragment:o}){return async a=>{let i=r();if(!i)return null;let[n,{cart:s,errors:u}]=await Promise.all([t?t.isLoggedIn():!1,e.query(_o(o),{variables:{cartId:i,...a},cache:e.CacheNone()})]);return P(Uo(n,s),u)}}function Uo(e,t){if(e&&t&&t.checkoutUrl){let r=new URL(t.checkoutUrl);r.searchParams.set("logged_in","true"),t.checkoutUrl=r.toString();}return t}var _o=(e=ko)=>`#graphql
327
+ ${I}
328
+ `;function lt({storefront:e,customerAccount:t,getCartId:r,cartFragment:o}){return async a=>{let s=r();if(!s)return null;let[n,{cart:i,errors:u}]=await Promise.all([t?t.isLoggedIn():!1,e.query(Fo(o),{variables:{cartId:s,...a},cache:e.CacheNone()})]);return P(Vo(n,i),u)}}function Vo(e,t){if(e&&t&&t.checkoutUrl){let r=new URL(t.checkoutUrl);r.searchParams.set("logged_in","true"),t.checkoutUrl=r.toString();}return t}var Fo=(e=$o)=>`#graphql
322
329
  query CartQuery(
323
330
  $cartId: ID!
324
331
  $numCartLines: Int = 100
@@ -331,7 +338,7 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
331
338
  }
332
339
 
333
340
  ${e}
334
- `,ko=`#graphql
341
+ `,$o=`#graphql
335
342
  fragment CartApiQuery on Cart {
336
343
  updatedAt
337
344
  id
@@ -439,7 +446,7 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
439
446
  width
440
447
  height
441
448
  }
442
- `;function pt(e){return async(t,r)=>{let{cartLinesAdd:o,errors:a}=await e.storefront.mutate(Lo(e.cartFragment),{variables:{cartId:e.getCartId(),lines:t,...r}});return P(o,a)}}var Lo=(e=b)=>`#graphql
449
+ `;function yt(e){return async(t,r)=>{let{cartLinesAdd:o,errors:a}=await e.storefront.mutate(qo(e.cartFragment),{variables:{cartId:e.getCartId(),lines:t,...r}});return P(o,a)}}var qo=(e=w)=>`#graphql
443
450
  mutation cartLinesAdd(
444
451
  $cartId: ID!
445
452
  $lines: [CartLineInput!]!
@@ -457,8 +464,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
457
464
  }
458
465
 
459
466
  ${e}
460
- ${w}
461
- `;function dt(e){return async(t,r)=>{let{cartLinesUpdate:o,errors:a}=await e.storefront.mutate(No(e.cartFragment),{variables:{cartId:e.getCartId(),lines:t,...r}});return P(o,a)}}var No=(e=b)=>`#graphql
467
+ ${I}
468
+ `;function ft(e){return async(t,r)=>{let{cartLinesUpdate:o,errors:a}=await e.storefront.mutate(Ho(e.cartFragment),{variables:{cartId:e.getCartId(),lines:t,...r}});return P(o,a)}}var Ho=(e=w)=>`#graphql
462
469
  mutation cartLinesUpdate(
463
470
  $cartId: ID!
464
471
  $lines: [CartLineUpdateInput!]!
@@ -476,8 +483,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
476
483
  }
477
484
 
478
485
  ${e}
479
- ${w}
480
- `;function lt(e){return async(t,r)=>{let{cartLinesRemove:o,errors:a}=await e.storefront.mutate(Mo(e.cartFragment),{variables:{cartId:e.getCartId(),lineIds:t,...r}});return P(o,a)}}var Mo=(e=b)=>`#graphql
486
+ ${I}
487
+ `;function mt(e){return async(t,r)=>{let{cartLinesRemove:o,errors:a}=await e.storefront.mutate(Qo(e.cartFragment),{variables:{cartId:e.getCartId(),lineIds:t,...r}});return P(o,a)}}var Qo=(e=w)=>`#graphql
481
488
  mutation cartLinesRemove(
482
489
  $cartId: ID!
483
490
  $lineIds: [ID!]!
@@ -495,8 +502,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
495
502
  }
496
503
 
497
504
  ${e}
498
- ${w}
499
- `;function yt(e){return async(t,r)=>{let o=t.filter((n,s,u)=>u.indexOf(n)===s),{cartDiscountCodesUpdate:a,errors:i}=await e.storefront.mutate(Vo(e.cartFragment),{variables:{cartId:e.getCartId(),discountCodes:o,...r}});return P(a,i)}}var Vo=(e=b)=>`#graphql
505
+ ${I}
506
+ `;function gt(e){return async(t,r)=>{let o=t.filter((n,i,u)=>u.indexOf(n)===i),{cartDiscountCodesUpdate:a,errors:s}=await e.storefront.mutate(Go(e.cartFragment),{variables:{cartId:e.getCartId(),discountCodes:o,...r}});return P(a,s)}}var Go=(e=w)=>`#graphql
500
507
  mutation cartDiscountCodesUpdate(
501
508
  $cartId: ID!
502
509
  $discountCodes: [String!]
@@ -513,8 +520,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
513
520
  }
514
521
  }
515
522
  ${e}
516
- ${w}
517
- `;function ft(e){return async(t,r)=>{let{cartBuyerIdentityUpdate:o,errors:a}=await e.storefront.mutate(Fo(e.cartFragment),{variables:{cartId:e.getCartId(),buyerIdentity:t,...r}});return P(o,a)}}var Fo=(e=b)=>`#graphql
523
+ ${I}
524
+ `;function ht(e){return async(t,r)=>{t.companyLocationId&&e.customerAccount&&e.customerAccount.UNSTABLE_setBuyer({companyLocationId:t.companyLocationId});let o=e.customerAccount?await e.customerAccount.UNSTABLE_getBuyer():void 0,{cartBuyerIdentityUpdate:a,errors:s}=await e.storefront.mutate(Bo(e.cartFragment),{variables:{cartId:e.getCartId(),buyerIdentity:{...o,...t},...r}});return P(a,s)}}var Bo=(e=w)=>`#graphql
518
525
  mutation cartBuyerIdentityUpdate(
519
526
  $cartId: ID!
520
527
  $buyerIdentity: CartBuyerIdentityInput!
@@ -531,8 +538,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
531
538
  }
532
539
  }
533
540
  ${e}
534
- ${w}
535
- `;function mt(e){return async(t,r)=>{let{cartNoteUpdate:o,errors:a}=await e.storefront.mutate($o(e.cartFragment),{variables:{cartId:e.getCartId(),note:t,...r}});return P(o,a)}}var $o=(e=b)=>`#graphql
541
+ ${I}
542
+ `;function Ct(e){return async(t,r)=>{let{cartNoteUpdate:o,errors:a}=await e.storefront.mutate(Wo(e.cartFragment),{variables:{cartId:e.getCartId(),note:t,...r}});return P(o,a)}}var Wo=(e=w)=>`#graphql
536
543
  mutation cartNoteUpdate(
537
544
  $cartId: ID!
538
545
  $note: String!
@@ -549,8 +556,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
549
556
  }
550
557
  }
551
558
  ${e}
552
- ${w}
553
- `;function gt(e){return async(t,r)=>{let{cartSelectedDeliveryOptionsUpdate:o,errors:a}=await e.storefront.mutate(qo(e.cartFragment),{variables:{cartId:e.getCartId(),selectedDeliveryOptions:t,...r}});return P(o,a)}}var qo=(e=b)=>`#graphql
559
+ ${I}
560
+ `;function St(e){return async(t,r)=>{let{cartSelectedDeliveryOptionsUpdate:o,errors:a}=await e.storefront.mutate(jo(e.cartFragment),{variables:{cartId:e.getCartId(),selectedDeliveryOptions:t,...r}});return P(o,a)}}var jo=(e=w)=>`#graphql
554
561
  mutation cartSelectedDeliveryOptionsUpdate(
555
562
  $cartId: ID!
556
563
  $selectedDeliveryOptions: [CartSelectedDeliveryOptionInput!]!
@@ -567,8 +574,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
567
574
  }
568
575
  }
569
576
  ${e}
570
- ${w}
571
- `;function ht(e){return async(t,r)=>{let{cartAttributesUpdate:o,errors:a}=await e.storefront.mutate(Ho(e.cartFragment),{variables:{cartId:r?.cartId||e.getCartId(),attributes:t}});return P(o,a)}}var Ho=(e=b)=>`#graphql
577
+ ${I}
578
+ `;function Pt(e){return async(t,r)=>{let{cartAttributesUpdate:o,errors:a}=await e.storefront.mutate(Ko(e.cartFragment),{variables:{cartId:r?.cartId||e.getCartId(),attributes:t}});return P(o,a)}}var Ko=(e=w)=>`#graphql
572
579
  mutation cartAttributesUpdate(
573
580
  $cartId: ID!
574
581
  $attributes: [AttributeInput!]!
@@ -583,8 +590,8 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
583
590
  }
584
591
  }
585
592
  ${e}
586
- ${w}
587
- `;function Ct(e){return async(t,r)=>{let o=r?.cartId||e.getCartId(),a=t.map(s=>({...s,ownerId:o})),{cartMetafieldsSet:i,errors:n}=await e.storefront.mutate(Qo(),{variables:{metafields:a}});return P({cart:{id:o},...i},n)}}var Qo=()=>`#graphql
593
+ ${I}
594
+ `;function At(e){return async(t,r)=>{let o=r?.cartId||e.getCartId(),a=t.map(i=>({...i,ownerId:o})),{cartMetafieldsSet:s,errors:n}=await e.storefront.mutate(zo(),{variables:{metafields:a}});return P({cart:{id:o},...s},n)}}var zo=()=>`#graphql
588
595
  mutation cartMetafieldsSet(
589
596
  $metafields: [CartMetafieldsSetInput!]!
590
597
  $language: LanguageCode
@@ -599,7 +606,7 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
599
606
  }
600
607
  }
601
608
  }
602
- `;function St(e){return async(t,r)=>{let o=r?.cartId||e.getCartId(),{cartMetafieldDelete:a,errors:i}=await e.storefront.mutate(Go(),{variables:{input:{ownerId:o,key:t}}});return P({cart:{id:o},...a},i)}}var Go=()=>`#graphql
609
+ `;function Tt(e){return async(t,r)=>{let o=r?.cartId||e.getCartId(),{cartMetafieldDelete:a,errors:s}=await e.storefront.mutate(Jo(),{variables:{input:{ownerId:o,key:t}}});return P({cart:{id:o},...a},s)}}var Jo=()=>`#graphql
603
610
  mutation cartMetafieldDelete(
604
611
  $input: CartMetafieldDeleteInput!
605
612
  ) {
@@ -611,7 +618,7 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
611
618
  }
612
619
  }
613
620
  }
614
- `;var Bo=new Set(["domain","path","max-age","expires","samesite","secure","httponly"]);function nr(e){let t={},r,o,a=0,i=e.split(/;\s*/g),n,s;for(;a<i.length;a++)if(o=i[a],r=o.indexOf("="),~r){if(n=o.substring(0,r++).trim(),s=o.substring(r).trim(),s[0]==='"'&&(s=s.substring(1,s.length-1)),~s.indexOf("%"))try{s=decodeURIComponent(s);}catch{}Bo.has(o=n.toLowerCase())?o==="expires"?t.expires=new Date(s):o==="max-age"?t.maxage=+s:t[o]=s:t[n]=s;}else (n=o.trim().toLowerCase())&&(n==="httponly"||n==="secure")&&(t[n]=!0);return t}function ir(e,t,r={}){let o=e+"="+encodeURIComponent(t);return r.expires&&(o+="; Expires="+new Date(r.expires).toUTCString()),r.maxage!=null&&r.maxage>=0&&(o+="; Max-Age="+(r.maxage|0)),r.domain&&(o+="; Domain="+r.domain),r.path&&(o+="; Path="+r.path),r.samesite&&(o+="; SameSite="+r.samesite),(r.secure||r.samesite==="None")&&(o+="; Secure"),r.httponly&&(o+="; HttpOnly"),o}var Wo=e=>{let t=nr(e.get("Cookie")||"");return ()=>t.cart?`gid://shopify/Cart/${t.cart}`:void 0};var jo=e=>t=>{let r=new Headers;return r.append("Set-Cookie",ir("cart",t.split("/").pop()||"",{path:"/",...e})),r};function Ko(e){let{getCartId:t,setCartId:r,storefront:o,customerAccount:a,cartQueryFragment:i,cartMutateFragment:n}=e,s=t(),u=()=>s||t(),c={storefront:o,getCartId:u,cartFragment:n},p=ct(c),d=async function(...l){let y=await p(...l);return s=y?.cart?.id,y},g={get:ut({storefront:o,customerAccount:a,getCartId:u,cartFragment:i}),getCartId:u,setCartId:r,create:d,addLines:async(l,y)=>s||y?.cartId?await pt(c)(l,y):await d({lines:l},y),updateLines:dt(c),removeLines:lt(c),updateDiscountCodes:async(l,y)=>s||y?.cartId?await yt(c)(l,y):await d({discountCodes:l},y),updateBuyerIdentity:async(l,y)=>s||y?.cartId?await ft(c)(l,y):await d({buyerIdentity:l},y),updateNote:async(l,y)=>s||y?.cartId?await mt(c)(l,y):await d({note:l},y),updateSelectedDeliveryOption:gt(c),updateAttributes:async(l,y)=>s||y?.cartId?await ht(c)(l,y):await d({attributes:l},y),setMetafields:async(l,y)=>s||y?.cartId?await Ct(c)(l,y):await d({metafields:l},y),deleteMetafield:St(c)};return "customMethods"in e?{...g,...e.customMethods??{}}:g}function Zo({handle:e,options:t=[],variants:r=[],productPath:o="products",children:a}){let i=r instanceof Array?r:flattenConnection(r),{searchParams:n,path:s,alreadyOnProductPage:u}=ta(e,o),c=t.filter(p=>p?.values?.length===1);return createElement(Fragment,null,...useMemo(()=>t.filter(p=>p?.values?.length>1).map(p=>{let d,g=[];for(let l of p.values){let y=new URLSearchParams(u?n:void 0);y.set(p.name,l),c.forEach(m=>{y.set(m.name,m.values[0]);});let S=i.find(m=>m?.selectedOptions?.every(h=>y.get(h?.name)===h?.value)),C=n.get(p.name),f=C?C===l:!1;f&&(d=l);let T="?"+y.toString();g.push({value:l,isAvailable:S?S.availableForSale:!0,to:s+T,search:T,isActive:f});}return a({option:{name:p.name,value:d,values:g}})}),[t,i,a]))}var ea=e=>{if(typeof e?.url>"u")throw new TypeError(`Expected a Request instance, got ${typeof e}`);let t=new URL(e.url).searchParams,r=[];return t.forEach((o,a)=>{r.push({name:a,value:o});}),r};function ta(e,t){let{pathname:r,search:o}=useLocation();return useMemo(()=>{let a=/(\/[a-zA-Z]{2}-[a-zA-Z]{2}\/)/g.exec(r),i=a&&a.length>0;t=t.startsWith("/")?t.substring(1):t;let n=i?`${a[0]}${t}/${e}`:`/${t}/${e}`;return {searchParams:new URLSearchParams(o),alreadyOnProductPage:n===r,path:n}},[r,o,e,t])}var cr=createContext(void 0),ia=cr.Provider,Pt=()=>useContext(cr);function sa(e){let t=Ue(),r=ca(t,e);return {nonce:t,header:r,NonceProvider:({children:a})=>createElement(ia,{value:t},a)}}function ca(e,t){let{shop:r,...o}=t??{},a=`'nonce-${e}'`,i=["'self'","'unsafe-inline'","https://cdn.shopify.com"],n=["'self'","https://monorail-edge.shopifysvc.com"];r&&r.checkoutDomain&&n.push(`https://${r.checkoutDomain}`),r&&r.storeDomain&&n.push(`https://${r.storeDomain}`);let u={baseUri:["'self'"],defaultSrc:["'self'",a,"https://cdn.shopify.com","https://shopify.com"],frameAncestors:["'none'"],styleSrc:i,connectSrc:n},c=Object.assign({},u,o);for(let p in u){let d=o[p];p&&d&&(c[p]=ua(d,u[p]));}return c.scriptSrc instanceof Array&&!c.scriptSrc.includes(a)?c.scriptSrc.push(a):c.defaultSrc instanceof Array&&!c.defaultSrc.includes(a)&&c.defaultSrc.push(a),na({directives:c})}function ua(e,t){let r=typeof t=="string"?[t]:t,o=Array.isArray(e)?e:[String(e)];return Array.isArray(r)?[...o,...r]:r}var da=forwardRef((e,t)=>{let r=Pt();return jsx("script",{suppressHydrationWarning:!0,...e,nonce:r,ref:t})});function fa(e){let t=useFetchers(),r={};for(let{formData:o}of t)if(o?.get("optimistic-identifier")===e)try{if(o.has("optimistic-data")){let a=JSON.parse(String(o.get("optimistic-data")));Object.assign(r,a);}}catch{}return r}function ma({id:e,data:t}){return jsxs(Fragment$1,{children:[jsx("input",{type:"hidden",name:"optimistic-identifier",value:e}),jsx("input",{type:"hidden",name:"optimistic-data",value:JSON.stringify(t)})]})}function Sa(e){return jsx(ShopPayButton,{channel:"hydrogen",...e})}function ne(e){let{type:t,data:r={},customData:o}=e,a=useLocation(),{publish:i,cart:n,prevCart:s,shop:u}=K(),c=a.pathname+a.search;return useEffect(()=>{if(!u)return;let p={...r,customData:o,url:window.location.href,cart:n,prevCart:s,shop:u};i(t,p);},[i,c,n,s,u]),null}function pr(e){return jsx(ne,{...e,type:"page_viewed"})}function dr(e){return jsx(ne,{...e,type:"product_viewed"})}function lr(e){return jsx(ne,{...e,type:"collection_viewed"})}function yr(e){return jsx(ne,{...e,type:"cart_viewed"})}function fr(e){return jsx(ne,{...e,type:"search_viewed"})}function mr(e){return jsx(ne,{...e})}var z={PAGE_VIEWED:"page_viewed",PRODUCT_VIEWED:"product_viewed",COLLECTION_VIEWED:"collection_viewed",CART_VIEWED:"cart_viewed",SEARCH_VIEWED:"search_viewed",CART_UPDATED:"cart_updated",PRODUCT_ADD_TO_CART:"product_added_to_cart",PRODUCT_REMOVED_FROM_CART:"product_removed_from_cart",CUSTOM_EVENT:"custom_"};var Ia="https://cdn.shopify.com/shopifycloud/consent-tracking-api/v0.1/consent-tracking-api.js",wa="https://cdn.shopify.com/shopifycloud/privacy-banner/storefront-banner.js";function hr(e){console.error(`[h2:error:useCustomerPrivacy] Unable to setup Customer Privacy API: Missing consent.${e} consent configuration.`);}function At(e){let{withPrivacyBanner:t=!0,onVisitorConsentCollected:r,...o}=e,a=useRef(!1),i=useLoadScript(t?wa:Ia,{attributes:{id:"customer-privacy-api"}});o.checkoutDomain||hr("checkoutDomain"),o.storefrontAccessToken||hr("storefrontAccessToken"),useEffect(()=>{let n=s=>{r&&r(s.detail);};return document.addEventListener("visitorConsentCollected",n),()=>{document.removeEventListener("visitorConsentCollected",n);}},[r]),useEffect(()=>{if(!(i!=="done"||a.current)&&(a.current=!0,t&&window?.privacyBanner&&window?.privacyBanner?.loadBanner({checkoutRootDomain:o.checkoutDomain,storefrontAccessToken:o.storefrontAccessToken}),window.Shopify?.customerPrivacy)){let n=window.Shopify.customerPrivacy.setTrackingConsent;window.Shopify.customerPrivacy.setTrackingConsent=(s,u)=>{n({...s,headlessStorefront:!0,checkoutRootDomain:o.checkoutDomain,storefrontAccessToken:o.storefrontAccessToken},u);};}},[i,t,o]);}function vt(){try{return window.Shopify&&window.Shopify.customerPrivacy?window.Shopify?.customerPrivacy:null}catch{return null}}function Da(){let e=vt();if(!e)throw new Error("Shopify Customer Privacy API not available. Must be used within a useEffect. Make sure to load the Shopify Customer Privacy API with useCustomerPrivacy() or <AnalyticsProvider>.");return e}function Cr({consent:e}){let{subscribe:t,register:r,canTrack:o}=K(),{ready:a}=r("Internal_Shopify_Analytics"),{ready:i}=r("Internal_Shopify_CustomerPrivacy"),{checkoutDomain:n,storefrontAccessToken:s}=e;return n&&s&&At({...e,onVisitorConsentCollected:i}),useShopifyCookies({hasUserConsent:o()}),useEffect(()=>{t(z.PAGE_VIEWED,Ua),t(z.PRODUCT_VIEWED,_a),t(z.COLLECTION_VIEWED,ka),t(z.SEARCH_VIEWED,La),t(z.PRODUCT_ADD_TO_CART,Na),a();},[t,a]),null}function ke(e){console.error(`[h2:error:ShopifyAnalytics] Unable to send Shopify analytics: Missing shop.${e} configuration.`);}function Pe(e){let t=Da(),r=t.userCanBeTracked();if(!e?.shop?.shopId){ke("shopId");return}if(!e?.shop?.acceptedLanguage){ke("acceptedLanguage");return}if(!e?.shop?.currency){ke("currency");return}if(!e?.shop?.hydrogenSubchannelId){ke("hydrogenSubchannelId");return}return {shopifySalesChannel:"hydrogen",...e.shop,hasUserConsent:r,...getClientBrowserParameters(),ccpaEnforced:!t.saleOfDataAllowed(),gdprEnforced:!(t.marketingAllowed()&&t.analyticsProcessingAllowed())}}function Oa(e,t){if(t===null)return;let r=Pe(e);return r?{...r,cartId:t.id}:void 0}var q={};function Ua(e){let t=Pe(e);t&&(sendShopifyAnalytics({eventName:AnalyticsEventName.PAGE_VIEW_2,payload:{...t,...q}}),q={});}function _a(e){let t=Pe(e);if(t&&Sr({eventName:Va,productField:"products",variantField:"product.<displayed_variant>",fromSource:"product_viewed products array",products:e.products})){let r=Tt(e.products);q={pageType:AnalyticsPageType.product,resourceId:r[0].productGid},t={...t,...q,products:Tt(e.products)},sendShopifyAnalytics({eventName:AnalyticsEventName.PRODUCT_VIEW,payload:t});}}function ka(e){let t=Pe(e);t&&(q={pageType:AnalyticsPageType.collection,resourceId:e.collection.id},t={...t,...q,collectionHandle:e.collection.handle},sendShopifyAnalytics({eventName:AnalyticsEventName.COLLECTION_VIEW,payload:t}));}function La(e){let t=Pe(e);t&&(q={pageType:AnalyticsPageType.search},t={...t,...q,searchString:e.searchTerm},sendShopifyAnalytics({eventName:AnalyticsEventName.SEARCH_VIEW,payload:t}));}function Na(e){let{cart:t,currentLine:r}=e,o=Oa(e,t);!o||!r?.id||Ma({matchedLine:r,eventPayload:o});}function Ma({matchedLine:e,eventPayload:t}){let r={id:e.merchandise.product.id,variantId:e.id,title:e.merchandise.product.title,variantTitle:e.merchandise.title,vendor:e.merchandise.product.vendor,price:e.merchandise.price.amount,quantity:e.quantity,productType:e.merchandise.product.productType,sku:e.merchandise.sku};Sr({eventName:Fa,productField:"merchandise.product",variantField:"merchandise",fromSource:"cart query",products:[r]})&&sendShopifyAnalytics({eventName:AnalyticsEventName.ADD_TO_CART,payload:{...t,products:Tt([r])}});}var Va="Product viewed",Fa="Add to cart";function J(e,t,r){console.error(`[h2:error:ShopifyAnalytics] ${e}: ${t} is required from the ${r}.`);}function Sr({eventName:e,productField:t,variantField:r,products:o,fromSource:a}){return !o||o.length===0?(J(e,`${t}`,a),!1):(o.forEach(i=>{if(!i.id)return J(e,`${t}.id`,a),!1;if(!i.title)return J(e,`${t}.title`,a),!1;if(!i.price)return J(e,`${r}.price.amount`,a),!1;if(!i.vendor)return J(e,`${t}.vendor`,a),!1;if(!i.variantId)return J(e,`${r}.id`,a),!1;if(!i.variantTitle)return J(e,`${r}.title`,a),!1}),!0)}function Tt(e){return e.map(t=>{let r={productGid:t.id,variantGid:t.variantId,name:t.title,variantName:t.variantTitle,brand:t.vendor,price:t.price,quantity:t.quantity||1,category:t.productType};return t.sku&&(r.sku=t.sku),t.productType&&(r.category=t.productType),r})}function Ar(e){console.error(`[h2:error:CartAnalytics] Unable to set up cart analytics events: ${e} is missing.`);}function vr({cart:e,setCarts:t}){let{publish:r,shop:o,customData:a,canTrack:i,cart:n,prevCart:s}=K(),u=useRef(null);return useEffect(()=>{if(e)return Promise.resolve(e).then(c=>{if(c&&c.lines){if(!c.id){Ar("cart.id");return}if(!c.updatedAt){Ar("cart.updatedAt");return}}t(({cart:p,prevCart:d})=>c?.updatedAt!==p?.updatedAt?{cart:c,prevCart:p}:{cart:p,prevCart:d});}),()=>{}},[t,e]),useEffect(()=>{if(!n||!n?.updatedAt||n?.updatedAt===s?.updatedAt)return;let c;try{c=JSON.parse(localStorage.getItem("cartLastUpdatedAt")||"");}catch{c=null;}if(n.id===c?.id&&n.updatedAt===c?.updatedAt)return;let p={eventTimestamp:Date.now(),cart:n,prevCart:s,shop:o,customData:a};n.updatedAt!==u.current&&(u.current=n.updatedAt,r("cart_updated",p),localStorage.setItem("cartLastUpdatedAt",JSON.stringify({id:n.id,updatedAt:n.updatedAt})),s?.lines?.nodes?.forEach(d=>{let g=n?.lines.nodes.filter(l=>d.id===l.id);if(g?.length===1){let l=g[0];d.quantity<l.quantity?r("product_added_to_cart",{...p,prevLine:d,currentLine:l}):d.quantity>l.quantity&&r("product_removed_from_cart",{...p,prevLine:d,currentLine:l});}else r("product_removed_from_cart",{...p,prevLine:d});}),n?.lines?.nodes?.forEach(d=>{let g=s?.lines.nodes.filter(l=>d.id===l.id);(!g||g.length===0)&&r("product_added_to_cart",{...p,currentLine:d});}));},[n,s,r,o,a,i]),null}var Ba={canTrack:()=>!1,cart:null,customData:{},prevCart:null,publish:()=>{},shop:null,subscribe:()=>{},register:()=>({ready:()=>{}})},Er=createContext(Ba),Ne=new Map,Ae={};function xr(){return Object.values(Ae).every(Boolean)}function Tr(e,t){Ne.has(e)||Ne.set(e,new Map),Ne.get(e)?.set(t.toString(),t);}var Me=new Map;function Rr(e,t){if(!xr()){Me.set(e,t);return}Dr(e,t);}function Dr(e,t){(Ne.get(e)??new Map).forEach((r,o)=>{try{r(t);}catch(a){typeof a=="object"&&a instanceof Error?console.error("Analytics publish error",a.message,o,a.stack):console.error("Analytics publish error",a,o);}});}function Ir(e){return Ae.hasOwnProperty(e)||(Ae[e]=!1),{ready:()=>{Ae[e]=!0,xr()&&Me.size>0&&(Me.forEach((t,r)=>{Dr(r,t);}),Me.clear());}}}function wr(){return typeof window<"u"&&typeof window?.Shopify=="object"&&typeof window?.Shopify?.customerPrivacy=="object"&&typeof window?.Shopify?.customerPrivacy?.userCanBeTracked=="function"?window.Shopify.customerPrivacy.userCanBeTracked():!1}function Wa({canTrack:e,cart:t,children:r,consent:o,customData:a={},shop:i=null}){let n=useRef(!1),{shop:s}=ja(i),[u,c]=useState(!!e),[p,d]=useState({cart:null,prevCart:null}),[g,l]=useState(e?()=>e:()=>wr);useEffect(()=>{e||n.current||(n.current=!0,document.addEventListener("visitorConsentCollected",()=>{c(!0),l(()=>wr);}));},[c,l,e]);let y=useMemo(()=>({canTrack:g,...p,customData:a,publish:g()?Rr:()=>{},shop:s,subscribe:Tr,register:Ir}),[u,g(),g,JSON.stringify(g),p,p.cart?.updatedAt,p.prevCart,Rr,Tr,a,s,Ir,JSON.stringify(Ae)]);return jsxs(Er.Provider,{value:y,children:[r,s&&jsx(pr,{}),s&&t&&jsx(vr,{cart:t,setCarts:d}),s&&o&&jsx(Cr,{consent:o})]})}function K(){let e=useContext(Er);if(!e)throw new Error("[h2:error:useAnalytics] 'useAnalytics()' must be a descendent of <AnalyticsProvider/>");return e}function ja(e){let[t,r]=useState(null);return useEffect(()=>(Promise.resolve(e).then(r),()=>{}),[r,e]),{shop:t}}async function Ka({storefront:e,publicStorefrontId:t="0"}){return e.query(za,{cache:e.CacheLong()}).then(({shop:r,localization:o})=>({shopId:r.id,acceptedLanguage:o.language.isoCode,currency:o.country.currency.isoCode,hydrogenSubchannelId:t}))}var za=`#graphql
621
+ `;var Yo=new Set(["domain","path","max-age","expires","samesite","secure","httponly"]);function cr(e){let t={},r,o,a=0,s=e.split(/;\s*/g),n,i;for(;a<s.length;a++)if(o=s[a],r=o.indexOf("="),~r){if(n=o.substring(0,r++).trim(),i=o.substring(r).trim(),i[0]==='"'&&(i=i.substring(1,i.length-1)),~i.indexOf("%"))try{i=decodeURIComponent(i);}catch{}Yo.has(o=n.toLowerCase())?o==="expires"?t.expires=new Date(i):o==="max-age"?t.maxage=+i:t[o]=i:t[n]=i;}else (n=o.trim().toLowerCase())&&(n==="httponly"||n==="secure")&&(t[n]=!0);return t}function ur(e,t,r={}){let o=e+"="+encodeURIComponent(t);return r.expires&&(o+="; Expires="+new Date(r.expires).toUTCString()),r.maxage!=null&&r.maxage>=0&&(o+="; Max-Age="+(r.maxage|0)),r.domain&&(o+="; Domain="+r.domain),r.path&&(o+="; Path="+r.path),r.samesite&&(o+="; SameSite="+r.samesite),(r.secure||r.samesite==="None")&&(o+="; Secure"),r.httponly&&(o+="; HttpOnly"),o}var Xo=e=>{let t=cr(e.get("Cookie")||"");return ()=>t.cart?`gid://shopify/Cart/${t.cart}`:void 0};var Zo=e=>t=>{let r=new Headers;return r.append("Set-Cookie",ur("cart",t.split("/").pop()||"",{path:"/",...e})),r};function ea(e){let{getCartId:t,setCartId:r,storefront:o,customerAccount:a,cartQueryFragment:s,cartMutateFragment:n}=e,i=t(),u=()=>i||t(),c={storefront:o,getCartId:u,cartFragment:n,customerAccount:a},d=dt(c),y=async function(...p){let l=await d(...p);return i=l?.cart?.id,l},m={get:lt({storefront:o,customerAccount:a,getCartId:u,cartFragment:s}),getCartId:u,setCartId:r,create:y,addLines:async(p,l)=>i||l?.cartId?await yt(c)(p,l):await y({lines:p},l),updateLines:ft(c),removeLines:mt(c),updateDiscountCodes:async(p,l)=>i||l?.cartId?await gt(c)(p,l):await y({discountCodes:p},l),updateBuyerIdentity:async(p,l)=>i||l?.cartId?await ht(c)(p,l):await y({buyerIdentity:p},l),updateNote:async(p,l)=>i||l?.cartId?await Ct(c)(p,l):await y({note:p},l),updateSelectedDeliveryOption:St(c),updateAttributes:async(p,l)=>i||l?.cartId?await Pt(c)(p,l):await y({attributes:p},l),setMetafields:async(p,l)=>i||l?.cartId?await At(c)(p,l):await y({metafields:p},l),deleteMetafield:Tt(c)};return "customMethods"in e?{...m,...e.customMethods??{}}:m}function na({handle:e,options:t=[],variants:r=[],productPath:o="products",children:a}){let s=r instanceof Array?r:flattenConnection(r),{searchParams:n,path:i,alreadyOnProductPage:u}=ia(e,o),c=t.filter(d=>d?.values?.length===1);return createElement(Fragment,null,...useMemo(()=>t.filter(d=>d?.values?.length>1).map(d=>{let y,m=[];for(let p of d.values){let l=new URLSearchParams(u?n:void 0);l.set(d.name,p),c.forEach(v=>{l.set(v.name,v.values[0]);});let g=s.find(v=>v?.selectedOptions?.every(N=>l.get(N?.name)===N?.value)),S=n.get(d.name),f=S?S===p:!1;f&&(y=p);let R="?"+l.toString();m.push({value:p,isAvailable:g?g.availableForSale:!0,to:i+R,search:R,isActive:f});}return a({option:{name:d.name,value:y,values:m}})}),[t,s,a]))}var sa=e=>{if(typeof e?.url>"u")throw new TypeError(`Expected a Request instance, got ${typeof e}`);let t=new URL(e.url).searchParams,r=[];return t.forEach((o,a)=>{r.push({name:a,value:o});}),r};function ia(e,t){let{pathname:r,search:o}=useLocation();return useMemo(()=>{let a=/(\/[a-zA-Z]{2}-[a-zA-Z]{2}\/)/g.exec(r),s=a&&a.length>0;t=t.startsWith("/")?t.substring(1):t;let n=s?`${a[0]}${t}/${e}`:`/${t}/${e}`;return {searchParams:new URLSearchParams(o),alreadyOnProductPage:n===r,path:n}},[r,o,e,t])}var dr=createContext(void 0),la=dr.Provider,vt=()=>useContext(dr);function ya(e){let t=Me(),r=fa(t,e);return {nonce:t,header:r,NonceProvider:({children:a})=>createElement(la,{value:t},a)}}function fa(e,t){let{shop:r,...o}=t??{},a=`'nonce-${e}'`,s=["'self'","'unsafe-inline'","https://cdn.shopify.com"],n=["'self'","https://monorail-edge.shopifysvc.com"];r&&r.checkoutDomain&&n.push(`https://${r.checkoutDomain}`),r&&r.storeDomain&&n.push(`https://${r.storeDomain}`);let u={baseUri:["'self'"],defaultSrc:["'self'",a,"https://cdn.shopify.com","https://shopify.com"],frameAncestors:["'none'"],styleSrc:s,connectSrc:n},c=Object.assign({},u,o);for(let d in u){let y=o[d];d&&y&&(c[d]=ma(y,u[d]));}return c.scriptSrc instanceof Array&&!c.scriptSrc.includes(a)?c.scriptSrc.push(a):c.defaultSrc instanceof Array&&!c.defaultSrc.includes(a)&&c.defaultSrc.push(a),da({directives:c})}function ma(e,t){let r=typeof t=="string"?[t]:t,o=Array.isArray(e)?e:[String(e)];return Array.isArray(r)?r.every(s=>s==="'none'")?o:[...o,...r]:r}var ha=forwardRef((e,t)=>{let r=vt();return jsx("script",{suppressHydrationWarning:!0,...e,nonce:r,ref:t})});function Pa(e){let t=useFetchers(),r={};for(let{formData:o}of t)if(o?.get("optimistic-identifier")===e)try{if(o.has("optimistic-data")){let a=JSON.parse(String(o.get("optimistic-data")));Object.assign(r,a);}}catch{}return r}function Aa({id:e,data:t}){return jsxs(Fragment$1,{children:[jsx("input",{type:"hidden",name:"optimistic-identifier",value:e}),jsx("input",{type:"hidden",name:"optimistic-data",value:JSON.stringify(t)})]})}function Ia(e){return jsx(ShopPayButton,{channel:"hydrogen",...e})}function ue(e){let{type:t,data:r={},customData:o}=e,a=useLocation(),{publish:s,cart:n,prevCart:i,shop:u}=Y(),c=a.pathname+a.search;return useEffect(()=>{if(!u)return;let d={...r,customData:o,url:window.location.href,cart:n,prevCart:i,shop:u};s(t,d);},[s,c,n,i,u]),null}function yr(e){return jsx(ue,{...e,type:"page_viewed"})}function fr(e){return jsx(ue,{...e,type:"product_viewed"})}function mr(e){return jsx(ue,{...e,type:"collection_viewed"})}function gr(e){return jsx(ue,{...e,type:"cart_viewed"})}function hr(e){return jsx(ue,{...e,type:"search_viewed"})}function Cr(e){return jsx(ue,{...e})}var X={PAGE_VIEWED:"page_viewed",PRODUCT_VIEWED:"product_viewed",COLLECTION_VIEWED:"collection_viewed",CART_VIEWED:"cart_viewed",SEARCH_VIEWED:"search_viewed",CART_UPDATED:"cart_updated",PRODUCT_ADD_TO_CART:"product_added_to_cart",PRODUCT_REMOVED_FROM_CART:"product_removed_from_cart",CUSTOM_EVENT:"custom_"};var Oa="https://cdn.shopify.com/shopifycloud/consent-tracking-api/v0.1/consent-tracking-api.js",Ua="https://cdn.shopify.com/shopifycloud/privacy-banner/storefront-banner.js";function Pr(e){console.error(`[h2:error:useCustomerPrivacy] Unable to setup Customer Privacy API: Missing consent.${e} consent configuration.`);}function Rt(e){let{withPrivacyBanner:t=!0,onVisitorConsentCollected:r,onReady:o,...a}=e,s=useRef(!1),n=useLoadScript(t?Ua:Oa,{attributes:{id:"customer-privacy-api"}});a.checkoutDomain||Pr("checkoutDomain"),a.storefrontAccessToken||Pr("storefrontAccessToken"),useEffect(()=>{let i=u=>{r&&r(u.detail);};return document.addEventListener("visitorConsentCollected",i),()=>{document.removeEventListener("visitorConsentCollected",i);}},[r]),useEffect(()=>{if(!(n!=="done"||s.current)){if(s.current=!0,t&&window?.privacyBanner&&window?.privacyBanner?.loadBanner({checkoutRootDomain:a.checkoutDomain,storefrontAccessToken:a.storefrontAccessToken}),window.Shopify?.customerPrivacy){let i=window.Shopify.customerPrivacy.setTrackingConsent;window.Shopify.customerPrivacy.setTrackingConsent=(u,c)=>{i({...u,headlessStorefront:!0,checkoutRootDomain:a.checkoutDomain,storefrontAccessToken:a.storefrontAccessToken},c);};}o&&!t&&o();}},[n,t,a]);}function It(){try{return window.Shopify&&window.Shopify.customerPrivacy?window.Shopify?.customerPrivacy:null}catch{return null}}function Na(){let e=It();if(!e)throw new Error("Shopify Customer Privacy API not available. Must be used within a useEffect. Make sure to load the Shopify Customer Privacy API with useCustomerPrivacy() or <AnalyticsProvider>.");return e}function Ar({consent:e,onReady:t}){let{subscribe:r,register:o,canTrack:a}=Y(),{ready:s}=o("Internal_Shopify_Analytics"),{ready:n}=o("Internal_Shopify_CustomerPrivacy"),i=()=>{n(),t();};return Rt({...e,onVisitorConsentCollected:i,onReady:()=>{e.withPrivacyBanner||i();}}),useShopifyCookies({hasUserConsent:a()}),useEffect(()=>{r(X.PAGE_VIEWED,Va),r(X.PRODUCT_VIEWED,Fa),r(X.COLLECTION_VIEWED,$a),r(X.SEARCH_VIEWED,qa),r(X.PRODUCT_ADD_TO_CART,Ha),s();},[r,s]),null}function Fe(e){console.error(`[h2:error:ShopifyAnalytics] Unable to send Shopify analytics: Missing shop.${e} configuration.`);}function Re(e){let t=Na(),r=t.analyticsProcessingAllowed();if(!e?.shop?.shopId){Fe("shopId");return}if(!e?.shop?.acceptedLanguage){Fe("acceptedLanguage");return}if(!e?.shop?.currency){Fe("currency");return}if(!e?.shop?.hydrogenSubchannelId){Fe("hydrogenSubchannelId");return}return {shopifySalesChannel:"hydrogen",...e.shop,hasUserConsent:r,...getClientBrowserParameters(),ccpaEnforced:!t.saleOfDataAllowed(),gdprEnforced:!(t.marketingAllowed()&&t.analyticsProcessingAllowed())}}function Ma(e,t){if(t===null)return;let r=Re(e);return r?{...r,cartId:t.id}:void 0}var W={};function Va(e){let t=Re(e);t&&(sendShopifyAnalytics({eventName:AnalyticsEventName.PAGE_VIEW_2,payload:{...t,...W}}),W={});}function Fa(e){let t=Re(e);if(t&&Tr({eventName:Ga,productField:"products",variantField:"product.<displayed_variant>",fromSource:"product_viewed products array",products:e.products})){let r=wt(e.products);W={pageType:AnalyticsPageType.product,resourceId:r[0].productGid},t={...t,...W,products:wt(e.products)},sendShopifyAnalytics({eventName:AnalyticsEventName.PRODUCT_VIEW,payload:t});}}function $a(e){let t=Re(e);t&&(W={pageType:AnalyticsPageType.collection,resourceId:e.collection.id},t={...t,...W,collectionHandle:e.collection.handle},sendShopifyAnalytics({eventName:AnalyticsEventName.COLLECTION_VIEW,payload:t}));}function qa(e){let t=Re(e);t&&(W={pageType:AnalyticsPageType.search},t={...t,...W,searchString:e.searchTerm},sendShopifyAnalytics({eventName:AnalyticsEventName.SEARCH_VIEW,payload:t}));}function Ha(e){let{cart:t,currentLine:r}=e,o=Ma(e,t);!o||!r?.id||Qa({matchedLine:r,eventPayload:o});}function Qa({matchedLine:e,eventPayload:t}){let r={id:e.merchandise.product.id,variantId:e.id,title:e.merchandise.product.title,variantTitle:e.merchandise.title,vendor:e.merchandise.product.vendor,price:e.merchandise.price.amount,quantity:e.quantity,productType:e.merchandise.product.productType,sku:e.merchandise.sku};Tr({eventName:Ba,productField:"merchandise.product",variantField:"merchandise",fromSource:"cart query",products:[r]})&&sendShopifyAnalytics({eventName:AnalyticsEventName.ADD_TO_CART,payload:{...t,products:wt([r])}});}var Ga="Product viewed",Ba="Add to cart";function Z(e,t,r){console.error(`[h2:error:ShopifyAnalytics] ${e}: ${t} is required from the ${r}.`);}function Tr({eventName:e,productField:t,variantField:r,products:o,fromSource:a}){return !o||o.length===0?(Z(e,`${t}`,a),!1):(o.forEach(s=>{if(!s.id)return Z(e,`${t}.id`,a),!1;if(!s.title)return Z(e,`${t}.title`,a),!1;if(!s.price)return Z(e,`${r}.price.amount`,a),!1;if(!s.vendor)return Z(e,`${t}.vendor`,a),!1;if(!s.variantId)return Z(e,`${r}.id`,a),!1;if(!s.variantTitle)return Z(e,`${r}.title`,a),!1}),!0)}function wt(e){return e.map(t=>{let r={productGid:t.id,variantGid:t.variantId,name:t.title,variantName:t.variantTitle,brand:t.vendor,price:t.price,quantity:t.quantity||1,category:t.productType};return t.sku&&(r.sku=t.sku),t.productType&&(r.category=t.productType),r})}function Ir(e){console.error(`[h2:error:CartAnalytics] Unable to set up cart analytics events: ${e} is missing.`);}function wr({cart:e,setCarts:t}){let{publish:r,shop:o,customData:a,canTrack:s,cart:n,prevCart:i}=Y(),u=useRef(null);return useEffect(()=>{if(e)return Promise.resolve(e).then(c=>{if(c&&c.lines){if(!c.id){Ir("cart.id");return}if(!c.updatedAt){Ir("cart.updatedAt");return}}t(({cart:d,prevCart:y})=>c?.updatedAt!==d?.updatedAt?{cart:c,prevCart:d}:{cart:d,prevCart:y});}),()=>{}},[t,e]),useEffect(()=>{if(!n||!n?.updatedAt||n?.updatedAt===i?.updatedAt)return;let c;try{c=JSON.parse(localStorage.getItem("cartLastUpdatedAt")||"");}catch{c=null;}if(n.id===c?.id&&n.updatedAt===c?.updatedAt)return;let d={eventTimestamp:Date.now(),cart:n,prevCart:i,shop:o,customData:a};if(n.updatedAt===u.current)return;u.current=n.updatedAt,r("cart_updated",d),localStorage.setItem("cartLastUpdatedAt",JSON.stringify({id:n.id,updatedAt:n.updatedAt}));let y=i?.lines?flattenConnection(i?.lines):[],m=n.lines?flattenConnection(n.lines):[];y?.forEach(p=>{let l=m.filter(g=>p.id===g.id);if(l?.length===1){let g=l[0];p.quantity<g.quantity?r("product_added_to_cart",{...d,prevLine:p,currentLine:g}):p.quantity>g.quantity&&r("product_removed_from_cart",{...d,prevLine:p,currentLine:g});}else r("product_removed_from_cart",{...d,prevLine:p});}),m?.forEach(p=>{let l=y.filter(g=>p.id===g.id);(!l||l.length===0)&&r("product_added_to_cart",{...d,currentLine:p});});},[n,i,r,o,a,s]),null}var Xa={canTrack:()=>!1,cart:null,customData:{},prevCart:null,publish:()=>{},shop:null,subscribe:()=>{},register:()=>({ready:()=>{}})},_r=createContext(Xa),qe=new Map,Ie={};function kr(){return Object.values(Ie).every(Boolean)}function Er(e,t){qe.has(e)||qe.set(e,new Map),qe.get(e)?.set(t.toString(),t);}var He=new Map;function xr(e,t){if(!kr()){He.set(e,t);return}Lr(e,t);}function Lr(e,t){(qe.get(e)??new Map).forEach((r,o)=>{try{r(t);}catch(a){typeof a=="object"&&a instanceof Error?console.error("Analytics publish error",a.message,o,a.stack):console.error("Analytics publish error",a,o);}});}function Dr(e){return Ie.hasOwnProperty(e)||(Ie[e]=!1),{ready:()=>{Ie[e]=!0,kr()&&He.size>0&&(He.forEach((t,r)=>{Lr(r,t);}),He.clear());}}}function Or(){try{return window.Shopify.customerPrivacy.analyticsProcessingAllowed()}catch{}return !1}function Ur(e){return `[h2:error:Analytics.Provider] - ${e} is required`}function Za({canTrack:e,cart:t,children:r,consent:o,customData:a={},shop:s=null,disableThrowOnError:n=!1}){if(!o.checkoutDomain){let S=Ur("consent.checkoutDomain");n?console.error(S):br(!1,S);}if(!o.storefrontAccessToken){let S=Ur("consent.storefrontAccessToken");n?console.error(S):br(!1,S);}let i=useRef(!1),{shop:u}=en(s),[c,d]=useState(!!e),[y,m]=useState({cart:null,prevCart:null}),[p,l]=useState(e?()=>e:()=>Or),g=useMemo(()=>({canTrack:p,...y,customData:a,publish:p()?xr:()=>{},shop:u,subscribe:Er,register:Dr}),[c,p(),p,JSON.stringify(p),y,y.cart?.updatedAt,y.prevCart,xr,Er,a,u,Dr,JSON.stringify(Ie)]);return jsxs(_r.Provider,{value:g,children:[r,!!u&&jsx(yr,{}),!!u&&!!t&&jsx(wr,{cart:t,setCarts:m}),!!u&&jsx(Ar,{consent:o,onReady:()=>{i.current=!0,d(!0),l(()=>Or);}})]})}function Y(){let e=useContext(_r);if(!e)throw new Error("[h2:error:useAnalytics] 'useAnalytics()' must be a descendent of <AnalyticsProvider/>");return e}function en(e){let[t,r]=useState(null);return useEffect(()=>(Promise.resolve(e).then(r),()=>{}),[r,e]),{shop:t}}async function tn({storefront:e,publicStorefrontId:t="0"}){return e.query(rn,{cache:e.CacheLong()}).then(({shop:r,localization:o})=>({shopId:r.id,acceptedLanguage:o.language.isoCode,currency:o.country.currency.isoCode,hydrogenSubchannelId:t}))}var rn=`#graphql
615
622
  query ShopData(
616
623
  $country: CountryCode
617
624
  $language: LanguageCode
@@ -630,7 +637,7 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
630
637
  }
631
638
  }
632
639
  }
633
- `,Ja={CartView:yr,CollectionView:lr,CustomView:mr,ProductView:dr,Provider:Wa,SearchView:fr};//! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartCreate
640
+ `,on={CartView:gr,CollectionView:mr,CustomView:Cr,ProductView:fr,Provider:Za,SearchView:hr};//! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartCreate
634
641
  //! @see https://shopify.dev/docs/api/storefront/latest/queries/cart
635
642
  //! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartLinesAdd
636
643
  //! @see: https://shopify.dev/docs/api/storefront/latest/mutations/cartLinesUpdate
@@ -642,6 +649,6 @@ API response error: ${t.status}`,c=new B(u,{query:a,queryVariables:i,cause:{erro
642
649
  //! @see https://shopify.dev/docs/api/storefront/latest/mutations/cartMetafieldsSet
643
650
  //! @see https://shopify.dev/docs/api/storefront/2024-04/mutations/cartMetafieldDelete
644
651
 
645
- export { z as AnalyticsEvent, Ge as CacheCustom, Qe as CacheLong, qe as CacheNone, Z as CacheShort, _e as CartForm, Ze as InMemoryCache, ma as OptimisticInput, yo as Pagination, da as Script, io as Seo, Sa as ShopPayButton, Ja as UNSTABLE_Analytics, Zo as VariantSelector, ht as cartAttributesUpdateDefault, ft as cartBuyerIdentityUpdateDefault, ct as cartCreateDefault, yt as cartDiscountCodesUpdateDefault, ut as cartGetDefault, Wo as cartGetIdDefault, pt as cartLinesAddDefault, lt as cartLinesRemoveDefault, dt as cartLinesUpdateDefault, St as cartMetafieldDeleteDefault, Ct as cartMetafieldsSetDefault, mt as cartNoteUpdateDefault, gt as cartSelectedDeliveryOptionsUpdateDefault, jo as cartSetIdDefault, wo as changelogHandler, Ko as createCartHandler, sa as createContentSecurityPolicy, Ro as createCustomerAccountClient, En as createStorefrontClient, kn as createWithCache, P as formatAPIResult, ue as generateCacheControlHeader, vt as getCustomerPrivacy, mo as getPaginationVariables, ea as getSelectedProductOptions, so as getSeoMeta, Ka as getShopAnalytics, Yr as graphiqlLoader, zr as storefrontRedirect, K as unstable_useAnalytics, At as useCustomerPrivacy, Pt as useNonce, fa as useOptimisticData };
652
+ export { X as AnalyticsEvent, je as CacheCustom, We as CacheLong, Ge as CacheNone, re as CacheShort, Ve as CartForm, rt as InMemoryCache, Aa as OptimisticInput, So as Pagination, ha as Script, yo as Seo, Ia as ShopPayButton, on as UNSTABLE_Analytics, na as VariantSelector, Pt as cartAttributesUpdateDefault, ht as cartBuyerIdentityUpdateDefault, dt as cartCreateDefault, gt as cartDiscountCodesUpdateDefault, lt as cartGetDefault, Xo as cartGetIdDefault, yt as cartLinesAddDefault, mt as cartLinesRemoveDefault, ft as cartLinesUpdateDefault, Tt as cartMetafieldDeleteDefault, At as cartMetafieldsSetDefault, Ct as cartNoteUpdateDefault, St as cartSelectedDeliveryOptionsUpdateDefault, Zo as cartSetIdDefault, Uo as changelogHandler, ea as createCartHandler, ya as createContentSecurityPolicy, Do as createCustomerAccountClient, Nn as createStorefrontClient, Hn as createWithCache, P as formatAPIResult, ye as generateCacheControlHeader, It as getCustomerPrivacy, Ao as getPaginationVariables, sa as getSelectedProductOptions, fo as getSeoMeta, tn as getShopAnalytics, oo as graphiqlLoader, to as storefrontRedirect, Y as unstable_useAnalytics, Rt as useCustomerPrivacy, vt as useNonce, Pa as useOptimisticData };
646
653
  //# sourceMappingURL=out.js.map
647
654
  //# sourceMappingURL=index.js.map