@occluze/tether 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +9 -7
  2. package/dist/esm/astro.js +1 -1
  3. package/dist/esm/chunks/account-JBZJN7X7.js +1 -0
  4. package/dist/esm/chunks/analytics-22NMIVBV.js +1 -0
  5. package/dist/esm/chunks/chunk-4UR45XTC.js +1 -0
  6. package/dist/esm/chunks/chunk-6R752OYZ.js +1 -0
  7. package/dist/esm/chunks/chunk-BGIKQY6H.js +1 -0
  8. package/dist/esm/chunks/chunk-CISGFYOF.js +1 -0
  9. package/dist/esm/chunks/chunk-KARKXC6G.js +1 -0
  10. package/dist/esm/chunks/chunk-YXCXIPQV.js +4 -0
  11. package/dist/esm/chunks/{chunk-RBVRRQIU.js → chunk-YZMBXS6Y.js} +1 -1
  12. package/dist/esm/chunks/chunk-ZVUPVSLF.js +1 -0
  13. package/dist/esm/chunks/diagnose-6ZSK5DGE.js +1 -0
  14. package/dist/esm/chunks/extras-QDCSW6VU.js +1 -0
  15. package/dist/esm/chunks/markets-ui-HJCVLCKJ.js +1 -0
  16. package/dist/esm/chunks/search-LN2H6SXS.js +1 -0
  17. package/dist/esm/index.js +1 -1
  18. package/dist/esm/server.js +1 -1
  19. package/dist/tether.account.js +380 -0
  20. package/dist/tether.account.min.js +1 -0
  21. package/dist/tether.analytics.js +259 -0
  22. package/dist/tether.analytics.min.js +1 -0
  23. package/dist/tether.diagnose.js +11 -2
  24. package/dist/tether.diagnose.min.js +1 -1
  25. package/dist/tether.extras.js +87 -0
  26. package/dist/tether.extras.min.js +1 -0
  27. package/dist/tether.js +268 -75
  28. package/dist/tether.markets.js +3 -3
  29. package/dist/tether.markets.min.js +1 -1
  30. package/dist/tether.min.js +3 -3
  31. package/dist/tether.min.js.map +3 -3
  32. package/dist/tether.search.js +176 -0
  33. package/dist/tether.search.min.js +1 -0
  34. package/package.json +5 -2
  35. package/src/account.js +313 -0
  36. package/src/analytics.js +232 -0
  37. package/src/astro.js +4 -1
  38. package/src/cart.js +74 -11
  39. package/src/client.js +8 -3
  40. package/src/collection.js +15 -10
  41. package/src/config.js +3 -0
  42. package/src/diagnose.js +11 -2
  43. package/src/dom.js +7 -1
  44. package/src/extras.js +63 -0
  45. package/src/fragments.js +1 -1
  46. package/src/index.js +103 -41
  47. package/src/initial.js +13 -4
  48. package/src/lazy.js +9 -1
  49. package/src/loader.js +4 -1
  50. package/src/markets-ui.js +2 -1
  51. package/src/mounting.js +27 -2
  52. package/src/parts/account.js +3 -0
  53. package/src/parts/analytics.js +3 -0
  54. package/src/parts/extras.js +3 -0
  55. package/src/parts/search.js +3 -0
  56. package/src/product.js +19 -5
  57. package/src/search.js +153 -0
  58. package/src/server.js +78 -6
  59. package/src/status.js +2 -2
  60. package/types/index.d.ts +56 -3
  61. package/types/server.d.ts +10 -2
  62. package/dist/esm/chunks/chunk-HHMOPDZG.js +0 -1
  63. package/dist/esm/chunks/chunk-HXKV6QGB.js +0 -4
  64. package/dist/esm/chunks/chunk-RNZMTQTX.js +0 -1
  65. package/dist/esm/chunks/diagnose-J667GHGS.js +0 -1
  66. package/dist/esm/chunks/markets-ui-EGWIEUOZ.js +0 -1
package/README.md CHANGED
@@ -17,10 +17,11 @@ An open-source, free alternative to Smootify and Storesynk (formerly Shopyflow):
17
17
  - **With or without the CMS:** bind products to CMS items, or let one page show any product from the URL.
18
18
  - **Markets:** local prices and currency, a country selector, Webflow Localization.
19
19
  - **Optional CMS sync:** a Webflow CMS item per Shopify product, kept up to date automatically ([one-click deploy](#sync-shopify-products-to-the-webflow-cms-optional)).
20
+ - **Search as you type, customer accounts, analytics:** optional parts that load only where you use them ([accounts](docs/accounts.md), [analytics](docs/analytics.md): GA4/Tag Manager and Shopify's own).
20
21
  - **Astro too:** build-time product pages with live prices and cart, View Transitions included ([Astro guide](docs/astro.md)).
21
22
  - **Hand-over ready:** loading, error and not-found states, `Tether.diagnose()`, error reporting.
22
23
 
23
- MIT licensed · 18 KB gzipped · no dependencies · TypeScript types · [full reference](docs/reference.md) · [comparison](docs/comparison.md) · [changelog](CHANGELOG.md)
24
+ MIT licensed · 20 KB gzipped · no dependencies · TypeScript types · [full reference](docs/reference.md) · [comparison](docs/comparison.md) · [changelog](CHANGELOG.md)
24
25
 
25
26
  ---
26
27
 
@@ -46,13 +47,13 @@ Site settings → Custom code → **Head**:
46
47
  productPath: '/product', // your Webflow product template
47
48
  };
48
49
  </script>
49
- <script src="https://cdn.jsdelivr.net/gh/ravi-klaassens/tether@0.5/dist/tether.min.js" defer></script>
50
+ <script src="https://cdn.jsdelivr.net/gh/ravi-klaassens/tether@0.6/dist/tether.min.js" defer></script>
50
51
  ```
51
52
 
52
- **Versions:** `@0.5` gets every 0.5.x fix automatically (recommended), `@v0.5.0` pins one release,
53
- `@latest` always takes the newest. Hosting the file yourself? Put `tether.markets.min.js` and
54
- `tether.diagnose.min.js` next to it: those optional parts load only when a page uses markets or
55
- `Tether.diagnose()`.
53
+ **Versions:** `@0.6` gets every 0.6.x fix automatically (recommended), `@v0.6.1` pins one release,
54
+ `@latest` always takes the newest. Hosting the file yourself? Put the optional parts next to it (`tether.markets.min.js`,
55
+ `tether.search.min.js`, `tether.account.min.js`, `tether.analytics.min.js`, `tether.extras.min.js`,
56
+ `tether.diagnose.min.js`): each loads only when a page uses it.
56
57
 
57
58
  ## 3. Add attributes in the Designer
58
59
 
@@ -122,7 +123,8 @@ npm run build
122
123
 
123
124
  Bundlers: `npm install @occluze/tether`, then `import Tether from "@occluze/tether"` (TypeScript
124
125
  types included; markets and diagnose are split into their own chunks). Server-side data:
125
- `@occluze/tether/server`. Astro: `@occluze/tether/astro` ([guide](docs/astro.md), [starter](examples/astro)).
126
+ `@occluze/tether/server`. Astro: `@occluze/tether/astro` ([guide](docs/astro.md), [starter](examples/astro)). Next.js,
127
+ SvelteKit, Vite, Eleventy: [other frameworks](docs/frameworks.md).
126
128
  JavaScript API, config, releases and the Shopify API version policy are in the [reference](docs/reference.md).
127
129
 
128
130
  ## License
package/dist/esm/astro.js CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunks/chunk-VC46IEJQ.js";var T={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};async function _(O,f){let e=O==="dev"?"development":"production",o={};try{let{readFile:u}=await import("node:fs/promises"),{join:c}=await import("node:path");for(let i of[".env",".env.local",`.env.${e}`,`.env.${e}.local`]){let r;try{r=await u(c(f,i),"utf8")}catch{continue}for(let a of r.split(/\r?\n/)){let n=/^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*?)\s*$/.exec(a);if(!n||a.trim().startsWith("#"))continue;let t=n[2],s=/^(["'])(.*?)\1/.exec(t);t=s?s[2]:t.replace(/\s+#.*$/,""),o[n[1]]=t}}}catch{}return{...o,...process.env}}function d(O={}){let{inject:f=!0,...e}=O;return{name:"@occluze/tether",hooks:{"astro:config:setup":async({injectScript:o,command:u,config:c,logger:i})=>{let r=c?.root?decodeURIComponent(new URL(c.root).pathname):process.cwd(),a=await _(u,r);for(let[t,s]of Object.entries(T))e[t]||(e[t]=s.map(I=>a[I]).find(Boolean));let n=Object.entries(e).filter(([,t])=>typeof t=="function").map(([t])=>t);n.forEach(t=>delete e[t]),n.length&&i.warn(`${n.join(", ")}: functions can't be passed here. Set them in window.TETHER_CONFIG in your layout.`),(!e.domain||!e.token)&&i.warn("No Shopify store configured: set PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN in .env (the public Storefront API token)."),f&&(o("head-inline",'window.TETHER_INTEGRATION="astro";'),o("page",["import Tether from '@occluze/tether';",`Tether.init({ ...${JSON.stringify({autoMount:!1,...e})}, ...(window.TETHER_CONFIG || {}) }).then(() => Tether.mount(document));`].join(`
1
+ import"./chunks/chunk-VC46IEJQ.js";var I={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};async function _(O,f){let e=O==="dev"?"development":"production",o={};try{let{readFile:T}=await import("node:fs/promises"),{join:i}=await import("node:path");for(let c of[".env",".env.local",`.env.${e}`,`.env.${e}.local`]){let r;try{r=await T(i(f,c),"utf8")}catch{continue}for(let a of r.split(/\r?\n/)){let n=/^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*?)\s*$/.exec(a);if(!n||a.trim().startsWith("#"))continue;let t=n[2],s=/^(["'])(.*?)\1/.exec(t);t=s?s[2]:t.replace(/\s+#.*$/,""),o[n[1]]=t}}}catch{}return{...o,...process.env}}function d(O={}){let{inject:f=!0,...e}=O;return{name:"@occluze/tether",hooks:{"astro:config:setup":async({injectScript:o,command:T,config:i,logger:c})=>{let r=i?.root?decodeURIComponent(new URL(i.root).pathname):process.cwd(),a=await _(T,r);for(let[t,s]of Object.entries(I))e[t]||(e[t]=s.map(u=>a[u]).find(Boolean));let n=Object.entries(e).filter(([,t])=>typeof t=="function").map(([t])=>t);n.forEach(t=>delete e[t]),n.length&&c.warn(`${n.join(", ")}: functions can't be passed here. Set them in window.TETHER_CONFIG in your layout.`),(!e.domain||!e.token)&&c.warn("No Shopify store configured: set PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN in .env (the public Storefront API token)."),f&&(o("head-inline",'window.TETHER_INTEGRATION="astro";'),o("page",["import Tether from '@occluze/tether';",`window.TETHER_CONFIG = { ...${JSON.stringify({autoMount:!1,...e})}, ...(window.TETHER_CONFIG || {}) };`,"Tether.init().then(() => Tether.mount(document));"].join(`
2
2
  `)))}}}}export{d as default};
@@ -0,0 +1 @@
1
+ import{b as u}from"./chunk-BGIKQY6H.js";import"./chunk-ZVUPVSLF.js";import"./chunk-YXCXIPQV.js";import{B as x,D as O,G as F,b as a,e as G,g,h as f,o as p,p as y,s as _,u as S,w as z}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";var N=()=>`${a.prefix}:account:${a.domain}`,L=()=>`${a.prefix}:account-login:${a.domain}`,P=()=>a.account?.remember?window.localStorage:window.sessionStorage,H=t=>btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),v=()=>H(crypto.getRandomValues(new Uint8Array(32))),Z=async t=>H(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),A=t=>(a.account?.navigate||(e=>window.location.assign(e)))(t),B=(t,e)=>{try{return JSON.parse(t.getItem(e)||"null")}catch{return null}},b=(t,e,n)=>{try{n?t.setItem(e,JSON.stringify(n)):t.removeItem(e)}catch{}},U=null,s=null,D=null,I=null,d=()=>a.account?.server?String(a.account.server).replace(/\/$/,""):"",R=()=>`${a.prefix}:account-hint:${a.domain}`,T=null;async function C(t,{method:e="GET",body:n}={}){let r=await fetch(`${d()}${t}`,{method:e,credentials:"include",headers:e==="POST"?{"Content-Type":"application/json","X-Tether-Account":"1"}:{},body:n?JSON.stringify(n):void 0}),c=await r.json().catch(()=>({}));if(!r.ok&&r.status!==401)throw new f(`Customer accounts: ${c.error||r.status}`,{status:r.status});return c}async function J(){T||(T=await C("/me"));try{T.loggedIn?window.localStorage.setItem(R(),"1"):window.localStorage.removeItem(R())}catch{}return T}async function $(){if(U)return U;let t=a.account?.shopDomain||a.domain,e=c=>fetch(`https://${t}/.well-known/${c}`).then(o=>{if(!o.ok)throw new f(`Customer accounts: ${c} answered ${o.status}`,{status:o.status});return o.json()}),[n,r]=await Promise.all([e("openid-configuration"),e("customer-account-api")]);return U={...n,graphql:r.graphql_api},U}var tt=()=>a.account?.callbackUrl||`${window.location.origin}${window.location.pathname}`;function V(){return d()?!!T?.loggedIn:!!(s?.refresh||s?.access&&s.expiresAt>Date.now())}async function et({returnTo:t=window.location.href,locale:e}={}){if(d()){let h=new URL(`${d()}/login`);h.searchParams.set("returnTo",t);let m=e||a.account.locale||(a.locale||"").split("-")[0];m&&h.searchParams.set("locale",m),a.country&&h.searchParams.set("country",String(a.country).toUpperCase()),A(h.toString());return}if(!a.account?.clientId)throw new f("Customer accounts: set account.clientId",{code:"NOT_CONFIGURED"});let n=await $(),r=v(),c=v(),o=v(),l=tt();b(window.sessionStorage,L(),{state:r,nonce:c,verifier:o,redirect:l,returnTo:t,at:Date.now()});let i=new URL(n.authorization_endpoint),w={client_id:a.account.clientId,scope:"openid email customer-account-api:full",response_type:"code",redirect_uri:l,state:r,nonce:c,code_challenge:await Z(o),code_challenge_method:"S256"},k=e||a.account.locale||(a.locale||"").split("-")[0];k&&(w.locale=k),a.country&&(w.region_country=String(a.country).toUpperCase()),Object.entries(w).forEach(([h,m])=>i.searchParams.set(h,m)),A(i.toString())}async function W(t){let e=await $(),n=await fetch(a.account.tokenUrl||e.token_endpoint,{method:"POST",body:new URLSearchParams(t)}),r=await n.json().catch(()=>({}));if(!n.ok||!r.access_token)throw new f(`Customer accounts: token ${n.status} ${r.error||""}`.trim(),{status:n.status,code:n.status===400||n.status===401?"SESSION_ENDED":"TOKEN_FAILED"});return r}function nt(t){try{return JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function X(t,e=s){s={access:t.access_token,expiresAt:Date.now()+Math.max(0,(Number(t.expires_in)||3600)-120)*1e3,refresh:t.refresh_token||e?.refresh,idToken:t.id_token||e?.idToken},b(P(),N(),s)}async function ot(){let t=new URLSearchParams(window.location.search),e=B(window.sessionStorage,L());if(!e||!t.has("code")&&!t.has("error")||t.get("state")!==e.state)return!1;b(window.sessionStorage,L(),null);let n=new URL(window.location.href);if(["code","state","iss","error","error_description"].forEach(w=>n.searchParams.delete(w)),window.history.replaceState(window.history.state,"",n),t.has("error"))return S("account-error",{error:t.get("error")}),!1;if(Date.now()-e.at>10*6e4)throw new f("Customer accounts: the login took too long, please try again");let r=await W({grant_type:"authorization_code",client_id:a.account.clientId,redirect_uri:e.redirect,code:t.get("code"),code_verifier:e.verifier}),c=await $(),o=nt(r.id_token||""),l=[].concat(o?.aud||[]);if(!o||o.nonce!==e.nonce||o.iss!==c.issuer||!l.includes(a.account.clientId)||o.exp*1e3<Date.now())throw new f("Customer accounts: the login answer did not check out (nonce/issuer/audience)");X(r,null),await Y(),S("account-login",{});let i=e.returnTo&&new URL(e.returnTo,window.location.href);return i&&i.origin===window.location.origin&&i.href!==n.href&&A(i.href),!0}async function E(){return d()||(s||(s=B(P(),N())),!s)?null:s.access&&s.expiresAt>Date.now()?s.access:s.refresh?(D||(D=(async()=>{try{X(await W({grant_type:"refresh_token",client_id:a.account.clientId,refresh_token:s.refresh})),await Y()}catch(t){if(t.code==="SESSION_ENDED")q();else throw t}finally{D=null}})()),await D,s?.access||null):(q(),null)}function q(){s=null,I=null,b(P(),N(),null),u.customerAccessToken=null}async function Y(){u.customerAccessToken=s?.access||null,u.id()&&s?.access&&await u.setBuyerIdentity({customerAccessToken:s.access},{create:!1}).catch(t=>g(t,"account cart"))}async function Q(t,e={}){if(d())throw new f("Customer accounts in server mode only answer customer() and orders()",{code:"NOT_ALLOWED"});let n=await E();if(!n)throw new f("Not logged in",{code:"NOT_LOGGED_IN"});let r=await $(),c=i=>fetch(r.graphql,{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:JSON.stringify({query:t,variables:e})}),o=await c(n);o.status===401&&s?.refresh&&(s.expiresAt=0,o=await c(await E()));let l=await o.json().catch(()=>({}));if(!o.ok||l.errors?.length)throw new f(l.errors?.map(i=>i.message).join(" | ")||`Customer accounts: ${o.status}`,{status:o.status});return l.data}async function rt(){if(d()){let e=await J();return e.loggedIn?{...e.customer,emailAddress:{emailAddress:e.customer.email},defaultAddress:{formatted:e.customer.address}}:null}return I||(I=(await Q("query TetherCustomer{customer{id firstName lastName displayName emailAddress{emailAddress}defaultAddress{formatted}}}")).customer,I)}async function at({first:t=10}={}){return d()?(await C(`/orders?first=${t}`)).orders||[]:(await Q("query TetherOrders($first:Int!){customer{orders(first:$first,sortKey:PROCESSED_AT,reverse:true){nodes{id name processedAt financialStatus fulfillmentStatus statusPageUrl totalPrice{amount currencyCode}lineItems(first:20){nodes{title variantTitle quantity image{url altText}}}}}}}",{first:t})).customer?.orders?.nodes||[]}async function ct({returnTo:t=a.account?.logoutUrl||`${window.location.origin}/`}={}){if(d()){let c=await C("/logout",{method:"POST",body:{returnTo:t,cartId:u.id()}});T={loggedIn:!1};try{window.localStorage.removeItem(R())}catch{}S("account-logout",{}),c.logoutUrl?A(c.logoutUrl):j(document);return}let e=s?.idToken||B(P(),N())?.idToken;if(u.id()&&await u.setBuyerIdentity({customerAccessToken:null},{create:!1}).catch(()=>{}),q(),S("account-logout",{}),!e){j(document);return}let n=await $(),r=new URL(n.end_session_endpoint);r.searchParams.set("id_token_hint",e),r.searchParams.set("post_logout_redirect_uri",t),A(r.toString())}var K=t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},st=t=>{try{return new Date(t).toLocaleDateString(a.locale||void 0)}catch{return t}};async function j(t=document){let e=d()?!!(await J().catch(()=>({loggedIn:!1}))).loggedIn:V()||!!await E().catch(()=>null);if(_(t,p("show")).forEach(c=>{let o=y(c,"show");o==="logged-in"&&O(c,e),o==="logged-out"&&O(c,!e)}),!e)return;let n=_(t,p("account-bind"));if(n.length){let c=await rt().catch(o=>(g(o,"account"),null));n.forEach(o=>{let l={"first-name":c?.firstName,"last-name":c?.lastName,name:c?.displayName,email:c?.emailAddress?.emailAddress,address:c?.defaultAddress?.formatted?.join(", ")}[y(o,"account-bind")];l!=null&&x(o,l)})}let r=_(t,p("orders"));if(r.length){let c=await at({first:parseInt(y(r[0],"limit")||"10",10)}).catch(o=>(g(o,"orders"),[]));r.forEach(o=>F(o,c,(l,i)=>{_(l,p("order-bind")).forEach(w=>{let k=y(w,"order-bind");if(k==="url"){K(i.statusPageUrl)&&w.setAttribute("href",i.statusPageUrl);return}let h={name:i.name,date:st(i.processedAt),total:z(i.totalPrice),status:i.financialStatus?.toLowerCase(),fulfillment:i.fulfillmentStatus?.toLowerCase(),items:i.lineItems.nodes.map(m=>`${m.quantity}\xD7 ${m.title}`).join(", ")}[k];h!=null&&x(w,h)}),y(l,"order-bind")==="url"&&K(i.statusPageUrl)&&l.setAttribute("href",i.statusPageUrl)}))}}var M=!1;async function ft(t=document){if(!M){if(M=!0,document.addEventListener("click",e=>{let n=e.target;n.closest?.(p("account-login"))?(e.preventDefault(),et().catch(r=>g(r,"login"))):n.closest?.(p("account-logout"))&&(e.preventDefault(),ct().catch(r=>g(r,"logout")))}),d()){let e=new URL(window.location.href);e.searchParams.get("account")&&(e.searchParams.delete("account"),window.history.replaceState(window.history.state,"",e),S("account-login",{})),u.beforeCheckout=async()=>{if(!(await J()).loggedIn||!u.id())return null;let n=await C("/cart",{method:"POST",body:{cartId:u.id()}}).catch(()=>null);return n?.checkoutUrl?`${n.checkoutUrl}${n.checkoutUrl.includes("?")?"&":"?"}logged_in=true`:null}}else{try{await ot()}catch(e){g(e,"login")}!u.customerAccessToken&&await E().catch(()=>null)&&(u.customerAccessToken=s.access)}G("account",V()?"logged in":"logged out")}await j(t)}export{rt as customer,E as getToken,ot as handleCallback,V as isLoggedIn,et as login,ct as logout,ft as mountAccount,at as orders,Q as query,j as render};
@@ -0,0 +1 @@
1
+ import{b}from"./chunk-BGIKQY6H.js";import"./chunk-ZVUPVSLF.js";import"./chunk-YXCXIPQV.js";import{b as s,e as T,g as m,l as x,o as g}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";var j=n=>n?parseFloat(n.amount):0,L=n=>String(n||"").split("/").pop();function S(n,t,e=1,o){return{item_id:t?.sku||L(t?.id)||L(n.id),item_name:n.title,item_variant:t?.title==="Default Title"?void 0:t?.title,item_brand:n.vendor||void 0,item_category:n.productType||void 0,price:j(t?.price||n.priceRange?.minVariantPrice),quantity:e,...o!=null?{index:o}:{}}}function v(n,t=n.quantity){let e=n.merchandise||{};return S({...e.product||{},title:e.product?.title},e,t)}var w=n=>Math.round(n.reduce((t,e)=>t+(e.price||0)*(e.quantity||1),0)*100)/100;function F(n,t){let e=typeof s.analytics.dataLayer=="string"?s.analytics.dataLayer:"dataLayer",o=window[e]=window[e]||[];t&&o.push({ecommerce:null}),o.push(t?{event:n,ecommerce:t}:{event:n})}var p=null;function V(n){let t=[],e=[],o=()=>window.Shopify?.customerPrivacy,a=()=>{try{let i=o();return i?.consentStatus==="loaded"&&i.currentVisitorConsent?.()?.analytics!=="no"&&!!i.analyticsProcessingAllowed?.()}catch{return!1}},c={shop:{shopId:n,channel:"headless"},consent:{mode:s.analytics.shopify?.consent||"no-banner"}},d=()=>{a()&&t.forEach(i=>{for(;i.next<e.length;){let{event:l,payload:u}=e[i.next++];(i.subs.get(l)||[]).forEach(_=>{try{_(u,i.context)}catch(r){m(r,`analytics ${i.name}`)}})}})},f={getConfig:()=>c,publish(i,l={}){e.push({event:i,payload:{shop:c.shop,url:window.location.href,...l}}),e.length>500&&(e.shift(),t.forEach(u=>{u.next=Math.max(0,u.next-1)})),d()},addDestination(i){let l=`hydrogen:${i.name}`,u={name:i.name,next:0,subs:new Map,context:{getTrackingValues:()=>{let r=a()?o()?.__internal:null;return{uniqueToken:r?.uniqueToken?.({generateFallback:!0,tag:l})??"",visitToken:r?.visitToken?.({generateFallback:!0,tag:l})??""}}}},_=(r,C)=>(u.subs.has(r)||u.subs.set(r,new Set),u.subs.get(r).add(C),()=>u.subs.get(r)?.delete(C));return Promise.resolve(i.setup?.({subscribe:_,getConfig:f.getConfig})).then(()=>{t.push(u),d()}).catch(r=>m(r,`analytics ${i.name}`)),()=>{let r=t.indexOf(u);r>=0&&t.splice(r,1)}}};return document.addEventListener("consentTrackingApiLoaded",d),document.addEventListener("visitorConsentCollected",d),f}function q(n){let t=document.createElement("script");t.src=n,t.async=!0,document.head.appendChild(t)}async function D(){if(window.Shopify?.analytics){p=window.Shopify.analytics;return}let n=await x("query TetherShopId { shop { id } }",{},{context:!1}),t=String(s.country||"US").toUpperCase(),e=window.Shopify=window.Shopify||{};Object.assign(e,{country:t,locale:(s.locale||"en").split("-")[0].toLowerCase(),shop:s.domain,routes:{root:"/",match:()=>({pageTemplateName:$()?"product":"page"}),...e.routes||{}}});let o=s.analytics.shopify?.proxy;e.customerPrivacy={...e.customerPrivacy||{},config:o?{isHeadless:!0,asyncConsent:!0,asyncVisitorState:!0,consentDomain:window.location.host}:{isHeadless:!0,storefrontAccessToken:s.token,checkoutRootDomain:s.domain}},p=V(n.shop.id),e.analytics=p,q(s.analytics.shopify?.consent==="default-banner"?"https://cdn.shopify.com/shopifycloud/privacy-banner/storefront-banner.js":"https://cdn.shopify.com/shopifycloud/consent-tracking-api/v0.2/consent-tracking-api.js"),q("https://cdn.shopify.com/storefront/analytics/shopify.js"),T("shopify analytics ready",n.shop.id)}var M=(n,t,e=1)=>({id:n.id,title:n.title,price:t.price,vendor:n.vendor||"",variantId:t.id,variantTitle:t.title,quantity:e,sku:t.sku||void 0,productType:n.productType||void 0});function E(n){let t=n.merchandise||{};return{id:n.id,quantity:n.quantity,merchandise:{id:t.id,title:t.title,price:t.price,sku:t.sku,product:{id:t.product?.id,title:t.product?.title,vendor:t.product?.vendor||"",handle:t.product?.handle}}}}function $(){let n=document.querySelector(g("product"));return n&&!n.closest(`${g("collection")},${g("products")},${g("recommendations")}`)?window.Tether?.getScope(n):null}var y=(n,t,e,o)=>{s.analytics.dataLayer&&F(n,t),p&&e&&p.publish(e,o);try{s.analytics.onEvent?.(n,t)}catch(a){m(a,"analytics onEvent")}},h=null,k=new WeakSet;function P(n){let t=n.type.slice(s.prefix.length+1),e=n.detail||{};if(t==="product-ready"){let o=e.scope;if(!o||k.has(o.root)||$()!==o)return;k.add(o.root);let a=o.variant||e.product.variants.nodes[0],c=[S(e.product,a)];y("view_item",{currency:a?.price?.currencyCode,value:w(c),items:c},"product_viewed",{products:[M(e.product,a)]})}else if(t==="list-ready"){let o=(e.products||[]).slice(0,200).map((c,d)=>S(c,c.variants?.nodes?.[0],1,d)),a={item_list_id:e.collection?.handle||"products",item_list_name:e.collection?.title||"Products"};y("view_item_list",{...a,items:o},e.collection?"collection_viewed":null,e.collection?{collection:{id:e.collection.id,handle:e.collection.handle}}:null)}else if(t==="cart-updated"){let o=e.cart,a=new Map((o?.lines?.nodes||[]).map(c=>[c.merchandise?.id,c]));if(h&&e.reason!=="load"&&e.reason!=="pending"){let c=o?.cost?.totalAmount?.currencyCode;a.forEach((d,f)=>{let i=d.quantity-(h.get(f)?.quantity||0);if(i>0){let l=[v(d,i)];y("add_to_cart",{currency:c,value:w(l),items:l},"product_added_to_cart",{cart:o,prevCart:A,currentLine:E(d),prevLine:h.get(f)?E(h.get(f)):void 0})}}),h.forEach((d,f)=>{let i=d.quantity-(a.get(f)?.quantity||0);if(i>0){let l=[v(d,i)];y("remove_from_cart",{currency:c,value:w(l),items:l})}})}h=a,A=o}else if(t==="cart-toggled"&&e.open){let o=b.lines.map(a=>v(a));y("view_cart",{currency:b.state?.cost?.totalAmount?.currencyCode,value:w(o),items:o})}else if(t==="checkout"){let o=(e.cart?.lines?.nodes||[]).map(c=>v(c)),a=(e.cart?.discountCodes||[]).filter(c=>c.applicable).map(c=>c.code).join(",")||void 0;y("begin_checkout",{currency:e.cart?.cost?.totalAmount?.currencyCode,value:w(o),coupon:a,items:o})}else t==="search"&&e.term?y("search",{search_term:e.term},"search_viewed",{searchTerm:e.term}):t==="page"&&(k=new WeakSet,p&&p.publish("page_viewed",{}))}var A=null;async function R(n){s.analytics.shopify&&await D().catch(t=>m(t,"shopify analytics")),p&&p.publish("page_viewed",{}),n.splice(0).forEach(P),n.push=t=>(P(t),0)}export{R as startAnalytics};
@@ -0,0 +1 @@
1
+ import{D as f,n as s,o as i,p as d,t as l}from"./chunk-KARKXC6G.js";function w(e,r=window.location,c="product"){let t=(d(e,c)||"").trim();if(!t.toLowerCase().startsWith("url:"))return{key:t||null,fromUrl:!1,raw:t};let o=t.slice(4).trim(),n=null;if(o.toLowerCase()==="path"){let a=r.pathname.split("/").filter(Boolean);n=a.length?p(a[a.length-1]):null}else n=new URLSearchParams(r.search).get(o||"handle");return n=n&&n.trim()?n.trim():null,{key:n,fromUrl:!0,raw:t}}function p(e){try{return decodeURIComponent(e)}catch{return e}}var m=["loading","ready","error","not-found"],y=e=>e?.code==="NOT_FOUND",u=()=>["product","collection","products","recommendations"].map(e=>i(e)).join(","),b=(e,r)=>e===r||e.parentElement?.closest(u())===r;function x(e,r,c){let t=r==="not-found";e.setAttribute(s("state"),t?"error":r),r==="error"||t?e.setAttribute(s("error"),t?"not-found":c?.code||"error"):e.removeAttribute(s("error")),l(e,i("show"),u()).forEach(o=>{let n=d(o,"show");m.includes(n)&&f(o,n===r)}),(r==="error"||t)&&l(e,i("add-to-cart"),u()).forEach(o=>{o.classList.add("is-disabled"),o.setAttribute("aria-disabled","true"),"disabled"in o&&(o.disabled=!0)})}export{w as a,m as b,y as c,u as d,b as e,x as f};
@@ -0,0 +1 @@
1
+ import{b as rt,e as ot}from"./chunk-4UR45XTC.js";import{b as nt}from"./chunk-BGIKQY6H.js";import{d as V,e as F,f as S,g as N,h as W,i as M,j as Y,k as E}from"./chunk-YXCXIPQV.js";import{A as I,B as d,D as q,E as k,F as tt,G as A,I as D,J as et,K as it,L as st,M as at,b as T,g as G,n as g,o as l,p as c,q as P,r as J,s as B,t as K,u as x,v as z,w as $,x as X,z as Z}from"./chunk-KARKXC6G.js";var pt=new WeakMap,lt=()=>l("product");function mt(w,i){let t=i.indexOf("."),e=i.slice(0,t),s=i.slice(t+1);return(w.metafields||[]).find(a=>a&&a.namespace===e&&a.key===s)||null}var C=new Map;function ft(w){(w||[]).forEach(i=>{i?.handle&&!C.has(i.handle)&&C.set(i.handle,(i.options||[]).map(t=>t.name))})}var ct=class{constructor(i,t){this.root=i,this.product=t,this.selected={},this.variant=null,this.quantity=Math.max(0,parseInt(c(i,"quantity")??"1",10)||(P(i,"quantity")?0:1)),this.plans=F(t),this.purchase="one-time",this.planId=null,pt.set(i,this),i.setAttribute(g("state"),"ready"),i.removeAttribute(g("error")),this.initSelection(),this.initPurchase(),this.renderProduct(),this.bind(),this.renderVariant(),et(i,"product"),D("product"),x("product-ready",{product:t,scope:this},i)}update(i){let t=this.variant?.id;this.product=i,this.plans=F(i),this.planId&&!this.plans.some(s=>s.id===this.planId)&&(this.planId=this.plans[0]?.id||null),!this.plans.length&&this.purchase==="subscription"&&(this.purchase="one-time");let e=i.variants.nodes.find(s=>s.id===t);e&&(this.selected={},e.selectedOptions.forEach(s=>{this.selected[s.name]=s.value})),this.root.setAttribute(g("state"),"ready"),this.root.removeAttribute(g("error")),this.renderProduct(),this.renderVariant(),D("product"),x("product-updated",{product:i,scope:this},this.root)}$(i){let t=K(this.root,i,lt());return this.root.matches(i)?[this.root,...t]:t}optName(i){let t=this.product?.options||[];if(!i||t.some(s=>s.name===i))return i;let e=(C.get(this.product.handle)||[]).indexOf(i);return e>=0&&t[e]?t[e].name:i}initSelection(){let i=this.product.variants.nodes,t=i.find(s=>s.availableForSale)||i[0];t&&t.selectedOptions.forEach(s=>{this.selected[s.name]=s.value});let e=new URLSearchParams(window.location.search).get("variant")||c(this.root,"variant");if(e){let s=V.variant(e),o=i.find(a=>a.id===s);o&&(this.selected={},o.selectedOptions.forEach(a=>{this.selected[a.name]=a.value}))}}initPurchase(){if(!this.plans.length)return;let i=new URLSearchParams(window.location.search),t=E(this.product,i.get("selling_plan")),e=E(this.product,c(this.root,"default-plan"));this.planId=(t||e||this.plans[0]).id;let s=t?"subscription":c(this.root,"default-purchase")||T.defaultPurchase;this.purchase=this.product.requiresSellingPlan||s==="subscription"?"subscription":"one-time"}findVariant(){return this.product.variants.nodes.find(i=>i.selectedOptions.every(t=>this.selected[t.name]===t.value))||null}isValueAvailable(i,t){return this.product.variants.nodes.some(e=>e.availableForSale&&e.selectedOptions.every(s=>s.name===i?s.value===t:this.selected[s.name]===s.value))}get plan(){return this.plans.find(i=>i.id===this.planId)||null}get subscriptionAvailable(){return!!(this.variant&&this.plans.some(i=>S(this.variant,i.id)))}get isSubscription(){return this.purchase==="subscription"&&!!S(this.variant,this.planId)}getLine(){if(!this.variant)return null;let i={merchandiseId:this.variant.id,quantity:this.quantity};this.isSubscription&&(i.sellingPlanId=this.planId);let t=this.collectAttributes();return t.length&&(i.attributes=t),i}collectAttributes(){let i=at(st(this.root,"line-attributes")),t=this.$(l("line-attribute")).map(e=>{let s=c(e,"line-attribute"),o;return e.type==="checkbox"?o=e.checked?e.value&&e.value!=="on"?e.value:"Yes":"":e.type==="radio"?o=e.checked?e.value:null:o=e.value,o==null||o===""?null:{key:s,value:String(o)}}).filter(Boolean);return[...i,...t]}select(i,t){if(this.selected[i]===t)return;let e=this.product.variants.nodes.filter(o=>o.selectedOptions.some(a=>a.name===i&&a.value===t));if(!e.length)return;let s={...this.selected,[i]:t};if(!e.some(o=>o.selectedOptions.every(a=>s[a.name]===a.value))){let o=r=>r.selectedOptions.filter(u=>u.name!==i&&this.selected[u.name]===u.value).length*2+(r.availableForSale?1:0);e.reduce((r,u)=>o(u)>o(r)?u:r).selectedOptions.forEach(r=>{s[r.name]=r.value})}this.selected=s,this.renderVariant()}selectVariant(i){let t=this.product.variants.nodes.find(e=>e.id===V.variant(i));t&&(this.selected={},t.selectedOptions.forEach(e=>{this.selected[e.name]=e.value}),this.renderVariant())}setPurchase(i){let t=i==="subscription"?"subscription":"one-time";t==="one-time"&&this.product.requiresSellingPlan||this.purchase!==t&&(this.purchase=t,this.renderVariant())}selectPlan(i){let t=E(this.product,i);t&&(this.planId=t.id,this.purchase="subscription",this.renderVariant())}setQuantity(i){let t=P(this.root,"quantity")?0:1;this.quantity=Math.max(t,parseInt(i,10)||0),this.$(l("qty")).forEach(e=>d(e,this.quantity)),this.renderVariant()}async addToCart(){if(!this.variant?.availableForSale)return null;let i=this.getLine();if(!i||i.quantity<1)return null;let t=await nt.add(i);return x("product-added",{product:this.product,variant:this.variant,line:i},this.root),t}bind(){let i=t=>t&&t.closest(lt())===this.root;this.root.addEventListener("click",t=>{let e=t.target;if(!e?.closest)return;let s=e.closest(l("option-value"));if(i(s)&&s.closest(l("option-list"))){t.preventDefault(),this.select(this.optName(c(s.closest(l("option-list")),"option-list")),c(s,"option-value"));return}let o=e.closest(l("plan-value"));if(i(o)){t.preventDefault(),this.selectPlan(c(o,"plan-value"));return}let a=e.closest(`${l("purchase")}:not(select)`);if(i(a)){a.tagName!=="INPUT"&&t.preventDefault(),this.setPurchase(c(a,"purchase"));return}let r=e.closest(l("qty-plus"));if(i(r)){t.preventDefault(),this.setQuantity(this.quantity+1);return}let u=e.closest(l("qty-minus"));if(i(u)){t.preventDefault(),this.setQuantity(this.quantity-1);return}let v=e.closest(l("add-to-cart"));i(v)&&(t.preventDefault(),this.onAddClick(v))}),this.root.addEventListener("change",t=>{let e=t.target;i(e)&&(e.matches(`select${l("option")}`)?this.select(this.optName(c(e,"option")),e.value):e.matches(`select${l("variant-select")}`)?this.selectVariant(e.value):e.matches(`select${l("plan")}`)?e.value?this.selectPlan(e.value):this.setPurchase("one-time"):e.matches(`select${l("purchase")}`)?this.setPurchase(e.value):e.matches(l("qty"))&&this.setQuantity(e.value))})}onAddClick(i){let t=i.querySelector(l("add-label"))||i,e=c(i,"adding-text"),s=o=>d(t,o);t.dataset.tetherLabel===void 0&&(t.dataset.tetherLabel=t.tagName==="INPUT"?t.value:t.textContent),it(i,async()=>{e&&s(e);try{await this.addToCart()}catch(o){G(o,"add to cart failed"),x("error",{error:o,context:"add-to-cart"},this.root)}finally{e&&s(t.dataset.tetherLabel)}}).then(()=>{this.renderVariant()})}renderProduct(){let i=this.product;C.has(i.handle)||this.$(`${l("option-list")},select${l("option")}`).map(s=>c(s,"option-list")||c(s,"option")).some(s=>i.options.some(o=>o.name===s))&&ft([i]);let t=this.product;this.$(l("bind")).forEach(e=>{let s=c(e,"bind")||"",o={title:t.title,"description-text":t.description,vendor:t.vendor,type:t.productType,handle:t.handle}[s];if(o!==void 0)return d(e,o);switch(s){case"description":e.innerHTML=t.descriptionHtml||"";return;case"published-at":return d(e,X(t.publishedAt));case"min-price":return d(e,$(t.priceRange.minVariantPrice));case"max-price":return d(e,$(t.priceRange.maxVariantPrice));case"featured-image":return I(e,t.featuredImage?.url,t.featuredImage?.altText||t.title);case"url":case"link":e.setAttribute("href",J(t.handle,t.id)),s==="url"&&!e.firstElementChild&&!e.textContent.trim()&&d(e,t.title);return;case"images":{let a=[...e.children].map(r=>r.tagName==="IMG"?r:r.querySelector("img"));if(!tt(e)&&a.length===t.images.nodes.length&&a.every((r,u)=>Z(r?.getAttribute("src"),t.images.nodes[u].url)))return}return A(e,t.images.nodes,(a,r)=>{let u=a.matches(`img,${l("bind","image")}`)?a:a.querySelector("img")||a;I(u,r.url,r.altText||t.title)});case"tags":{let a=(e.getAttribute("exclude")||"").split(",").map(r=>r.trim()).filter(Boolean);return A(e,t.tags.filter(r=>!a.includes(r)),(r,u)=>d(r,u))}default:if(/^image:\d+$/.test(s)){let a=t.images.nodes[s.slice(6)-1]||t.featuredImage;return I(e,a?.url,a?.altText||t.title)}if(s.startsWith("metafield:")){let a=mt(t,s.slice(10));return a?a.reference?.image?I(e,a.reference.image.url,a.reference.image.altText):(/^(rich_text|multi_line_text)_field$/.test(a.type)&&(e.style.whiteSpace="pre-line"),d(e,a.value)):d(e,"")}return}}),this.$(l("option-list")).forEach(e=>{let s=this.optName(c(e,"option-list")),o=t.options.find(a=>a.name===s);return!o||o.optionValues.length<=1&&P(e,"hide-single")?q(e,!1):A(e,o.optionValues,(a,r)=>{a.setAttribute(g("option-value"),r.name);let u=a.querySelector(l("bind","option-value"));u?d(u,r.name):a.firstElementChild||d(a,r.name);let v=a.querySelector(l("bind","swatch"));v&&r.swatch?.color&&(v.style.backgroundColor=r.swatch.color),v&&r.swatch?.image?.previewImage&&I(v,r.swatch.image.previewImage.url,r.name)})}),this.$(`select${l("option")}`).forEach(e=>{let s=t.options.find(o=>o.name===this.optName(c(e,"option")));if(!s)return q(e,!1);e.innerHTML="",s.optionValues.forEach(o=>e.appendChild(new Option(o.name,o.name)))}),this.$(`select${l("variant-select")}`).forEach(e=>{e.innerHTML="",t.variants.nodes.forEach(s=>e.appendChild(new Option(s.title,s.id)))}),this.$(l("plan-list")).forEach(e=>{let s=(c(e,"plan-list")||"").trim(),o=["","true","all","*"].includes(s.toLowerCase())?null:s,a=this.plans.filter(r=>!o||r.group.name===o);A(e,a,(r,u)=>{r.setAttribute(g("plan-value"),u.id),!r.firstElementChild&&!r.querySelector(l("plan-bind"))&&d(r,u.name)})}),this.$(`select${l("plan")}`).forEach(e=>{e.innerHTML="",!t.requiresSellingPlan&&c(e,"plan")!=="subscription-only"&&e.appendChild(new Option(e.getAttribute(g("one-time-label"))||"One-time purchase","")),this.plans.forEach(s=>e.appendChild(new Option(s.name,s.id)))})}renderVariant(){let i=this.product,t=this.findVariant();if(t||([t]=i.variants.nodes,t&&(this.selected={},t.selectedOptions.forEach(n=>{this.selected[n.name]=n.value}))),this.variant=t,!t)return;if(this.plans.length&&!S(t,this.planId)){let n=this.plans.find(h=>S(t,h.id));n&&(this.planId=n.id)}let e=this.isSubscription,s=t.price,o=this.planId?N(t,this.planId):null,a=e?o:s,r=e&&S(t,this.planId)?.priceAdjustments?.[0]?.compareAtPrice||t.compareAtPrice,u=r&&parseFloat(r.amount)>parseFloat(a.amount),v=u?Math.round((1-parseFloat(a.amount)/parseFloat(r.amount))*100):0,L=this.planId?M(t,this.planId):{amount:null,percentage:0},O=this.plan,ut={amount:(parseFloat(a.amount)*Math.max(1,this.quantity)).toFixed(2),currencyCode:a.currencyCode},f=$,U=n=>z(n),j={price:()=>f(a),"total-price":()=>f(ut),"one-time-price":()=>f(s),"subscription-price":()=>f(o),"subscription-savings":()=>U(L.percentage),"subscription-savings-amount":()=>f(L.amount),"checkout-charge":()=>{let n=e?W(t,this.planId):a;return n&&f({amount:(parseFloat(n.amount)*Math.max(1,this.quantity)).toFixed(2),currencyCode:n.currencyCode})},"plan-name":()=>O?.name,"plan-description":()=>O?.description,"plan-group":()=>O?.group?.name,"compare-at-price":()=>u?f(r):"","unit-price":()=>f(t.unitPrice),"discount-percentage":()=>`${v}%`,"discount-amount":()=>u?f({amount:String(parseFloat(r.amount)-parseFloat(a.amount)),currencyCode:a.currencyCode}):"","variant-title":()=>t.title,"variant-id":()=>t.id,sku:()=>t.sku,barcode:()=>t.barcode,stock:()=>t.quantityAvailable,quantity:()=>this.quantity};this.$(l("bind")).forEach(n=>{let h=c(n,"bind");h==="variant-image"?I(n,t.image?.url||i.featuredImage?.url,t.image?.altText||i.title):j[h]&&d(n,j[h]())}),this.$(l("option-selected")).forEach(n=>d(n,this.selected[this.optName(c(n,"option-selected"))]||"")),this.$(l("option-list")).forEach(n=>{let h=this.optName(c(n,"option-list"));B(n,l("option-value")).forEach(p=>{let b=c(p,"option-value");k(p,this.selected[h]===b);let m=!this.isValueAvailable(h,b);p.classList.toggle("is-unavailable",m),p.setAttribute("data-unavailable",m?"true":"false")})}),this.$(`select${l("option")}`).forEach(n=>{n.value=this.selected[this.optName(c(n,"option"))]||""}),this.$(`select${l("variant-select")}`).forEach(n=>{n.value=t.id}),this.$(l("purchase")).forEach(n=>{if(n.tagName==="SELECT"){n.value=this.purchase;return}let h=c(n,"purchase");k(n,h===this.purchase);let p=h==="subscription"?!this.subscriptionAvailable:i.requiresSellingPlan;n.classList.toggle("is-unavailable",p)}),this.$(l("plan-value")).forEach(n=>{let h=c(n,"plan-value"),p=this.plans.find(m=>m.id===h),b=!!S(t,h);k(n,e&&h===this.planId),n.classList.toggle("is-unavailable",!b),B(n,l("plan-bind")).forEach(m=>{let y=Y(p),Q=M(t,h),ht=c(m,"plan-bind"),R={name:()=>p?.name,option:()=>(p?.options||[]).map(dt=>dt.value).join(", "),description:()=>p?.description,price:()=>f(N(t,h)),savings:()=>U(Q.percentage),"savings-amount":()=>f(Q.amount),adjustment:()=>y?y.type==="percentage"?`${y.value}%`:f(y.value):""}[ht];R&&d(m,R())})}),this.$(`select${l("plan")}`).forEach(n=>{n.value=e?this.planId:""});let _=t.quantityAvailable!=null&&t.quantityAvailable>0&&t.quantityAvailable<=(T.lowStock??5),H={"in-stock":t.availableForSale,"out-of-stock":!t.availableForSale,backorder:t.availableForSale&&t.currentlyNotInStock,"on-sale":!!u,"not-on-sale":!u,"has-variants":i.variants.nodes.length>1,"single-variant":i.variants.nodes.length===1,"low-stock":_,"plenty-in-stock":t.availableForSale&&!_,"subscription-available":this.subscriptionAvailable,"subscription-unavailable":!this.subscriptionAvailable,"subscription-only":!!i.requiresSellingPlan,"one-time-available":!i.requiresSellingPlan,"subscription-selected":e,"one-time-selected":!e,"has-savings":e?L.percentage>0:!!u,loading:!1,ready:!0,error:!1,"not-found":!1};this.$(l("show")).forEach(n=>{let h=c(n,"show");h in H&&(rt.includes(h)&&!ot(n,this.root)||q(n,H[h]))}),this.root.classList.toggle("is-subscription",e),this.root.setAttribute(g("purchase-mode"),e?"subscription":"one-time"),this.$(l("add-to-cart")).forEach(n=>{let h=!t.availableForSale;n.classList.toggle("is-disabled",h),n.setAttribute("aria-disabled",String(h)),"disabled"in n&&(n.disabled=h);let p=c(n,"soldout-text"),b=c(n,"subscribe-text");if(p||b){let m=n.querySelector(l("add-label"))||n;m.dataset.tetherLabel===void 0&&(m.dataset.tetherLabel=m.tagName==="INPUT"?m.value:m.textContent);let y=m.dataset.tetherLabel;e&&b&&(y=b),h&&p&&(y=p),n.getAttribute("aria-busy")!=="true"&&d(m,y)}}),x("variant-changed",{product:i,variant:t,selected:{...this.selected},purchase:this.purchase,sellingPlanId:e?this.planId:null},this.root)}};export{pt as a,ft as b,ct as c};
@@ -0,0 +1 @@
1
+ import{c as U}from"./chunk-ZVUPVSLF.js";import{b as S,d as $,e as B}from"./chunk-YXCXIPQV.js";import{A as M,B as j,C as m,D as L,G as K,H as N,I as R,M as q,b as o,e as O,g as I,h as _,l as A,m as Q,n as E,o as u,p as g,r as F,s as l,u as h,w as b}from"./chunk-KARKXC6G.js";function G(t,e=1,n={}){let a=typeof t=="object"&&t!==null?t:{variantId:t,quantity:e,...n},r=$.variant(a.merchandiseId||a.variantId||a.id);if(!r)throw new _("add(): variantId is required");let s={merchandiseId:r,quantity:Math.max(1,parseInt(a.quantity??1,10)||1)},c=a.sellingPlanId||a.sellingPlan;c&&(s.sellingPlanId=$.sellingPlan(c));let i=q(a.attributes);return i.length&&(s.attributes=i),s}function V(t,e,n){return`mutation Tether_${t}(${e}){${t}(${n}){cart{...TetherCart}userErrors{field message}warnings{code message target}}}${S()}`}var H='a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])',k=null,W=t=>l(t,H).filter(e=>e.offsetParent!==null||e===document.activeElement);function x(t){l(document,u("cart-open")).forEach(e=>e.setAttribute("aria-expanded",String(t))),l(document,u("cart-drawer")).forEach(e=>{e.hasAttribute("role")||e.setAttribute("role","dialog"),!e.hasAttribute("aria-label")&&!e.hasAttribute("aria-labelledby")&&e.setAttribute("aria-label",g(e,"cart-label")||"Cart"),e.setAttribute("aria-modal",String(t)),e.classList.contains(o.cartDrawerOpenClass)||(e.setAttribute("aria-hidden","true"),o.cartFocus!==!1&&(e.inert=!0))})}var T=t=>/does not exist|not found|invalid id/i.test(t?.message||""),D={state:null,_chain:Promise.resolve(),id(){try{return localStorage.getItem(o.storageKey)}catch{return null}},_setId(t){try{t?localStorage.setItem(o.storageKey,t):localStorage.removeItem(o.storageKey)}catch{}},get lines(){return this.state?.lines?.nodes||[]},get count(){return this.state?.totalQuantity||0},lastError:null,customerAccessToken:null,pendingQty:new Map,warnings:[],loaded:!1,_take(t,e){let n=Q(t,e);return this.warnings=(n.warnings||[]).filter((a,r,s)=>s.findIndex(c=>c.message===a.message)===r).map(a=>({...a,message:typeof o.warningText=="function"&&o.warningText(a)||a.message})),this.warnings.length&&h("cart-warning",{warnings:this.warnings}),n.cart},_queue(t){let e=this._chain.then(t,t).then(n=>(this.lastError&&(this.lastError=null,this.render()),n),n=>{throw this.lastError=n,this.render(),h("cart-error",{error:n}),n});return this._chain=e.catch(()=>{}),e},_commit(t,e){this.state=t,t?.id&&this._setId(t.id);try{localStorage.setItem(`${o.storageKey}:seen`,`${Date.now()}|${t?.totalQuantity||0}`)}catch{}return this.render(),h("cart-updated",{cart:t,reason:e}),t},async init(){let t=this.id();if(!t)return this.state=null,this.loaded=!0,this.render(),h("cart-updated",{cart:null,reason:"load"}),null;if(!this.loaded)try{let e=(localStorage.getItem(`${o.storageKey}:seen`)||"").split("|")[1];e&&l(document,u("cart-count")).forEach(n=>{/^\s*0?\s*$/.test(n.textContent)&&(n.textContent=e)})}catch{}try{let e=await A(`query TetherCart($id:ID!){cart(id:$id){...TetherCart}}${S()}`,{id:t});e.cart?this.state=e.cart:(this._setId(null),this.state=null)}catch(e){I(e,"cart load failed"),this.lastError=e,T(e)&&this._setId(null),this.state=null}return this.loaded=!0,this.render(),h("cart-updated",{cart:this.state,reason:"load"}),this.state},async _create(t={}){let e=o.country||this.customerAccessToken?{...o.country?{countryCode:String(o.country).toUpperCase()}:{},...this.customerAccessToken?{customerAccessToken:this.customerAccessToken}:{}}:void 0,n=await A(V("cartCreate","$input: CartInput!","input: $input"),{input:{buyerIdentity:e,...t}});return this._take(n.cartCreate,"cartCreate")},async _mutate(t,e,n,a,r){let s=this.id();if(!s)return r?this._create(r):null;try{let c=await A(V(t,`$cartId: ID!, ${e}`,`cartId: $cartId, ${n}`),{...a,cartId:s});return this._take(c[t],t)}catch(c){if(r&&T(c))return O("cart expired, creating a new one"),this._setId(null),this._create(r);throw c}},add(t,e=1,n={}){let a=(Array.isArray(t)?t:[t]).map(r=>G(r,e,n));return this._queue(async()=>{let r=await this._mutate("cartLinesAdd","$lines: [CartLineInput!]!","lines: $lines",{lines:a},{lines:a});return this._commit(r,"add"),h("added",{cart:r,lines:a}),o.openCartOnAdd&&this.open(),r})},updateLine(t,e){let n=typeof e=="number"?{quantity:e}:{...e};if(n.quantity!==void 0&&n.quantity<=0)return this.removeLine(t);let a={id:t};return n.quantity!==void 0&&(a.quantity=n.quantity),"sellingPlanId"in n&&(a.sellingPlanId=n.sellingPlanId?$.sellingPlan(n.sellingPlanId):null),n.attributes&&(a.attributes=q(n.attributes)),(n.merchandiseId||n.variantId)&&(a.merchandiseId=$.variant(n.merchandiseId||n.variantId)),this._queue(async()=>this._commit(await this._mutate("cartLinesUpdate","$lines: [CartLineUpdateInput!]!","lines: $lines",{lines:[a]}),"update"))},changeQuantity(t,e){let n=this.lines.find(s=>s.id===t);if(!n)return Promise.resolve(this.state);let a=Math.max(0,(this.pendingQty.get(t)?.qty??n.quantity)+e),r={qty:a,done:!1};return this.pendingQty.set(t,r),this.render(),h("cart-updated",{cart:this.state,reason:"pending"}),this.updateLine(t,a).finally(()=>{this.pendingQty.get(t)===r&&(this.pendingQty.delete(t),this.render(),h("cart-updated",{cart:this.state,reason:"settled"}))})},quantityOf(t){return this.pendingQty.get(t.id)?.qty??t.quantity},removeLine(t){let e=Array.isArray(t)?t:[t];return this._queue(async()=>this._commit(await this._mutate("cartLinesRemove","$lineIds: [ID!]!","lineIds: $lineIds",{lineIds:e}),"remove"))},clear(){let t=this.lines.map(e=>e.id);return t.length?this.removeLine(t):Promise.resolve(this.state)},setNote(t){return this._queue(async()=>this._commit(await this._mutate("cartNoteUpdate","$note: String!","note: $note",{note:t??""},{note:t??""}),"note"))},setAttributes(t){let e=new Map((this.state?.attributes||[]).map(a=>[a.key,a.value]));q(t).forEach(a=>e.set(a.key,a.value));let n=[...e].filter(([,a])=>a!=="").map(([a,r])=>({key:a,value:r}));return this._queue(async()=>this._commit(await this._mutate("cartAttributesUpdate","$attributes: [AttributeInput!]!","attributes: $attributes",{attributes:n},{attributes:n}),"attributes"))},setDiscountCodes(t){let e=(Array.isArray(t)?t:[t]).map(n=>String(n).trim()).filter(Boolean);return this._queue(async()=>this._commit(await this._mutate("cartDiscountCodesUpdate","$discountCodes: [String!]!","discountCodes: $discountCodes",{discountCodes:e},{discountCodes:e}),"discount"))},async applyDiscount(t){let e=(this.state?.discountCodes||[]).map(r=>r.code),n=await this.setDiscountCodes([...new Set([...e,t])]);if((n?.discountCodes||[]).find(r=>r.code.toLowerCase()===String(t).toLowerCase())?.applicable)return n;throw await this.removeDiscount(t).catch(()=>{}),new _(`Discount code not valid: ${t}`,{code:"INVALID_DISCOUNT"})},removeDiscount(t){let e=String(t).toLowerCase();return this.setDiscountCodes((this.state?.discountCodes||[]).map(n=>n.code).filter(n=>n.toLowerCase()!==e))},setBuyerIdentity(t,{create:e=!0}={}){return this._queue(async()=>{let n=await this._mutate("cartBuyerIdentityUpdate","$buyerIdentity: CartBuyerIdentityInput!","buyerIdentity: $buyerIdentity",{buyerIdentity:t},e?{buyerIdentity:t}:null).catch(a=>{if(e||!T(a))throw a;return this._setId(null),null});return this._commit(n,"buyer-identity")})},async checkout(t=o.checkoutTarget){let e=this.id();if(!e||this.state&&!this.count)return null;let n=t==="_blank"?window.open("","_blank"):null;if(n)try{n.opener=null}catch{}try{let a=await A("query TetherCheckout($id: ID!) { cart(id: $id) { checkoutUrl } }",{id:e}),r=this.beforeCheckout&&await this.beforeCheckout().catch(()=>null)||a.cart?.checkoutUrl;if(r&&this.customerAccessToken&&(r+=`${r.includes("?")?"&":"?"}logged_in=true`),!r)throw new _("No checkoutUrl (cart empty or expired)");return h("checkout",{url:r,cart:this.state}),n&&!n.closed?n.location.href=r:window.location.href=r,r}catch(a){return n&&n.close(),I(a,"checkout failed"),null}},drawers(){return l(document,u("cart-drawer"))},_open:!1,isOpen(){let t=this.drawers();return t.length?t.some(e=>e.classList.contains(o.cartDrawerOpenClass)):this._open},open(){if(this.isOpen())return;this._open=!0;let t=this.drawers().filter(e=>g(e,"cart-drawer")!=="manual");t.forEach(e=>{e.inert=!1,e.classList.add(o.cartDrawerOpenClass),e.setAttribute("aria-hidden","false")}),x(!0),o.cartFocus!==!1&&t[0]&&(k=document.activeElement,setTimeout(()=>{let e=W(t[0])[0]||t[0];e===t[0]&&!t[0].hasAttribute("tabindex")&&(t[0].tabIndex=-1),e.focus?.({preventScroll:!0})},60)),typeof o.onCartOpen=="function"&&o.onCartOpen(t),h("cart-toggled",{open:!0})},close(){if(!this.isOpen())return;this._open=!1;let t=this.drawers(),e=t.some(n=>n.contains(document.activeElement));t.forEach(n=>{n.classList.remove(o.cartDrawerOpenClass),n.setAttribute("aria-hidden","true"),o.cartFocus!==!1&&(n.inert=!0)}),x(!1),e&&k?.isConnected&&k.focus({preventScroll:!0}),k=null,typeof o.onCartClose=="function"&&o.onCartClose(t),h("cart-toggled",{open:!1})},toggle(){this.isOpen()?this.close():this.open()},subscribe(t){let e=()=>t(this.state,{open:this.isOpen(),count:this.count,loaded:this.loaded,warnings:this.warnings}),n=()=>e();return["cart-updated","cart-toggled"].forEach(a=>document.addEventListener(`${o.prefix}:${a}`,n)),e(),()=>["cart-updated","cart-toggled"].forEach(a=>document.removeEventListener(`${o.prefix}:${a}`,n))},render(){let t=this.state,e=t?t.totalQuantity:0,n=s=>t?b(t.cost?.[s]):"";x(this.isOpen()),l(document,u("cart-count")).forEach(s=>m(s,e)),l(document,u("cart-subtotal")).forEach(s=>m(s,n("subtotalAmount"))),l(document,u("cart-total")).forEach(s=>m(s,n("totalAmount"))),l(document,u("cart-checkout-charge")).forEach(s=>m(s,n("checkoutChargeAmount")));let a=this.lines.some(s=>s.sellingPlanAllocation),r={"cart-empty":e===0,"cart-filled":e>0,"cart-has-subscription":a,"cart-no-subscription":!a,"cart-has-discount":(t?.discountCodes||[]).some(s=>s.applicable),"cart-error":!!this.lastError,"cart-warning":this.warnings.length>0};l(document,u("cart-warning")).forEach(s=>m(s,[...new Set(this.warnings.map(c=>c.message))].join(" "))),l(document,u("show")).forEach(s=>{let c=g(s,"show");c in r&&!s.closest(u("product"))&&L(s,r[c])}),l(document,u("checkout")).forEach(s=>{s.classList.toggle("is-disabled",!e),s.setAttribute("aria-disabled",String(!e))}),l(document,`textarea${u("cart-note")},input${u("cart-note")}`).forEach(s=>{document.activeElement!==s&&(s.value=t?.note||"")}),l(document,u("cart-discounts")).forEach(s=>{K(s,t?.discountCodes||[],(c,i)=>{c.setAttribute(E("discount-code"),i.code);let d=c.querySelector(u("discount","code"))||(c.firstElementChild?null:c);d&&j(d,i.code),c.classList.toggle("is-inapplicable",!i.applicable)})}),l(document,u("cart-lines")).forEach(s=>{N(s,this.lines,c=>c.id,(c,i)=>J(c,i),{onEnter:o.onLineEnter,onLeave:o.onLineLeave})}),t&&R("cart")}};function z(t,e){let n=t.merchandise||{},a=t.sellingPlanAllocation?.sellingPlan;switch(e){case"title":return n.product?.title;case"product-title":return n.product?.title;case"variant-title":return n.title==="Default Title"?"":n.title;case"options":return(n.selectedOptions||[]).filter(r=>r.value!=="Default Title").map(r=>`${r.name}: ${r.value}`).join(", ");case"vendor":return n.product?.vendor;case"sku":return n.sku;case"price":return b(t.cost?.amountPerQuantity||n.price);case"compare-at-price":return b(t.cost?.compareAtAmountPerQuantity||n.compareAtPrice);case"line-total":return b(t.cost?.totalAmount);case"line-subtotal":return b(t.cost?.subtotalAmount);case"quantity":return D.quantityOf(t);case"plan":return a?.name||"";case"plan-description":return a?.description||"";case"components":return(t.lineComponents||[]).map(r=>`${r.quantity} \xD7 ${r.merchandise?.product?.title||""}`).join(", ");default:if(e.startsWith("attribute:")){let r=e.slice(10);return(t.attributes||[]).find(s=>s.key===r)?.value||""}return}}function J(t,e){let n=e.merchandise||{},a=!!e.sellingPlanAllocation;t.setAttribute(E("line-id"),e.id),t.classList.toggle("is-subscription",a),l(t,u("line")).forEach(i=>{let d=g(i,"line");if(d==="image")return M(i,n.image?.url||n.product?.featuredImage?.url,n.product?.title);if(d==="url"){let y=F(n.product?.handle,n.product?.id),v=new URLSearchParams;n.id&&v.set("variant",String(n.id).split("/").pop());let w=e.sellingPlanAllocation?.sellingPlan?.id;w&&v.set("selling_plan",w.split("/").pop());let C=v.toString();return i.setAttribute("href",C?`${y}${y.includes("?")?"&":"?"}${C}`:y)}let p=z(e,d);p!==void 0&&m(i,p)});let r=D.warnings.find(i=>i.target===e.id);t.classList.toggle("is-warning",!!r);let s=D.pendingQty.has(e.id);t.classList.toggle("is-busy",s),s?t.setAttribute("aria-busy","true"):t.removeAttribute("aria-busy"),l(t,u("line","warning")).forEach(i=>m(i,r?.message||""));let c={subscription:a,"one-time":!a,"on-sale":parseFloat(e.cost?.compareAtAmountPerQuantity?.amount)>parseFloat(e.cost?.amountPerQuantity?.amount),"has-components":(e.lineComponents||[]).length>0,warning:!!r};l(t,u("line-show")).forEach(i=>{let d=g(i,"line-show");d in c&&L(i,c[d])}),l(t,`select${u("line-plan")}`).forEach(i=>{let d=n.product?.handle;d&&U(d).then(p=>{let y=B(p),w=[...!p.requiresSellingPlan&&g(i,"line-plan")!=="subscription-only"?[{value:"",label:i.getAttribute(E("one-time-label"))||"One-time purchase"}]:[],...y.map(f=>({value:f.id,label:f.name}))],C=w.map(f=>f.value).join("|");i.dataset.tetherSig!==C&&(i.innerHTML="",w.forEach(f=>{let P=document.createElement("option");P.value=f.value,P.textContent=f.label,i.appendChild(P)}),i.dataset.tetherSig=C),i.value=e.sellingPlanAllocation?.sellingPlan?.id||"",L(i,y.length>0)}).catch(p=>I(p,"line plan options"))})}export{W as a,D as b};
@@ -0,0 +1 @@
1
+ import{a as E,b as K,c as z}from"./chunk-6R752OYZ.js";import{a as g,c as k,f as p}from"./chunk-4UR45XTC.js";import{c as L,e as A,f as F,g as O,h as q,i as D}from"./chunk-ZVUPVSLF.js";import{A as R,B as C,D as x,G as U,I as W,K as J,b as h,e as T,f as b,g as m,h as I,n as l,o as a,p as c,q as S,s as N,t as M,u as f}from"./chunk-KARKXC6G.js";var v=()=>`${a("collection")},${a("products")},${a("recommendations")}`,B=class{constructor(e){this.root=e,this.products=[],this.pageInfo=null,this.collection=null,p(e,"loading"),e.addEventListener("click",n=>{let o=n.target.closest?.(a("load-more"));o&&o.closest(v())===e&&(n.preventDefault(),J(o,()=>this.load(!0)))})}$(e){return M(this.root,e,v())}options(){let e=this.root,n={first:parseInt(c(e,"limit")||"",10)||void 0,sortKey:c(e,"sort")||void 0,reverse:c(e,"reverse")==="true"};return S(e,"collection")?n.collection=c(e,"collection"):n.query=c(e,"products")||"",n}async load(e=!1){let n=this.loadToken=(this.loadToken||0)+1,o=()=>n!==this.loadToken;try{if(S(this.root,"recommendations")){let{key:r}=g(this.root,window.location,"recommendations"),s=this.root.closest(a("product"));if(!r&&s&&({key:r}=g(s)),!r)throw new I("No product for recommendations",{code:"NOT_FOUND"});let u=await D(r,c(this.root,"intent")||"RELATED");if(o())return;let i=parseInt(c(this.root,"limit")||"",10);this.products=i?u.slice(0,i):u}else{let r=await q({...this.options(),after:e?this.pageInfo?.endCursor:null});if(o())return;this.collection=r.collection,this.pageInfo=r.pageInfo,this.products=e?[...this.products,...r.products]:r.products}this.render(),p(this.root,"ready"),f("list-ready",{products:this.products,collection:this.collection},this.root)}catch(r){if(o())return;e||p(this.root,k(r)?"not-found":"error",r),k(r)&&S(this.root,"recommendations")||m(r,"list load failed"),f("error",{error:r,context:"list"},this.root)}}render(){let e=this.collection;this.$(a("collection-bind")).forEach(o=>{switch(c(o,"collection-bind")){case"title":return C(o,e?.title||"");case"description":o.innerHTML=e?.descriptionHtml||"";return;case"image":return R(o,e?.image?.url,e?.image?.altText||e?.title);case"count":return C(o,this.products.length);default:return}}),this.$(a("list")).forEach(o=>{U(o,this.products,(r,s)=>{r.setAttribute(l("product"),s.handle),r.removeAttribute(l("state"))}),f("list-rendered",{container:o},this.root)});let n=this.products.length===0;this.$(a("show")).forEach(o=>{let r=c(o,"show");r==="list-empty"&&x(o,n),r==="list-filled"&&x(o,!n)}),this.$(a("load-more")).forEach(o=>x(o,!!this.pageInfo?.hasNextPage)),W("list")}};var P=new WeakSet,ft=new WeakSet,w=new Set,H=new Set,j=new WeakMap;function _(){w.forEach(t=>{t.isConnected||w.delete(t)}),H.forEach(t=>{t.root.isConnected||H.delete(t)})}function pt(t,e){return[...t.matches?.(e)?[t]:[],...N(t,e)]}function G(t){if(P.has(t))return!1;let{key:e,fromUrl:n,raw:o}=g(t);if(!e)return n?(P.add(t),p(t,"not-found"),f("product-not-found",{key:null,source:o},t)):t.closest(v())||b(`[${l("product")}] without a value. Bind it to the Shopify handle field, or use "url:handle".`,t),!1;P.add(t),w.add(t);let r={};j.set(t,r);let s=()=>j.get(t)===r;E.get(t)?t.setAttribute(l("state"),"updating"):p(t,"loading");let u=L(e);return d?.add(u),u.then(i=>{if(!s())return;let y=E.get(t);y?y.update(i):new z(t,i),V(t,i),h.revalidate!==!1&&F(e)&&X(e)}).catch(i=>{if(!s())return;let y=k(i);p(t,y?"not-found":"error",i),y?(f("product-not-found",{key:e,source:o},t),n?T(`product not found: ${e}`):m(i,`product ${e}`)):(m(i,`product ${e}`),f("error",{error:i,context:"product",key:e},t))}),!0}function V(t,e){let n=c(t,"page-title");!n||typeof document>"u"||(document.title=n.replace(/\{title\}/g,e.title).replace(/\{vendor\}/g,e.vendor||"").replace(/\{type\}/g,e.productType||""))}function ht(){_(),w.forEach(t=>{t.getAttribute(l("state"))!=="error"||t.getAttribute(l("error"))==="not-found"||(P.delete(t),G(t))})}var $=new Set;function X(t){$.size||setTimeout(Y,0),$.add(t)}function Y(){let t=[...$];$=new Set,O(t).forEach((e,n)=>e.then(o=>{w.forEach(r=>{let s=E.get(r);if(!s||!r.isConnected)return;let u=g(r).key;u!==t[n]&&u!==o.handle&&u!==o.id||JSON.stringify(s.product)!==JSON.stringify(o)&&s.update(o)})}).catch(o=>m(o,`refresh ${t[n]}`)))}var Q=new WeakSet,d=null,mt=t=>(d?.add(t),t);function Z(){if(!d)return;let t=[...d];Promise.allSettled(t).then(()=>{!d||t.some(e=>!d.has(e))||(t.length===d.size?(d=null,document.documentElement.classList.remove(`${h.prefix}-market-pending`)):Z())})}function gt(t=document){N(t.ownerDocument||t,'script[type="application/json"][data-tether-hydrate]').forEach(e=>{if(!Q.has(e)){Q.add(e);try{let n=JSON.parse(e.textContent);K(n.products);let o=(r,s)=>String(r||"").toUpperCase()===String(s||"").toUpperCase();o(n.country,h.country)&&o(n.language,h.language)?A(n.products):(T("hydration skipped: other market"),d||(d=new Set,document.documentElement.classList.add(`${h.prefix}-market-pending`)))}catch(n){b("bad data-tether-hydrate",n)}}})}export{v as a,B as b,P as c,ft as d,w as e,H as f,_ as g,pt as h,G as i,ht as j,mt as k,Z as l,gt as m};
@@ -0,0 +1 @@
1
+ var C={domain:"",token:"",apiVersion:"2026-07",country:void 0,language:void 0,locale:void 0,markets:null,prefix:"tether",productPath:"/product",collectionPath:"/collection",metafields:[],imagesFirst:25,variantsFirst:100,sellingPlanGroupsFirst:10,sellingPlansFirst:25,collectionFirst:24,retries:2,revalidate:!0,storageKey:null,cartDrawerOpenClass:"is-open",openCartOnAdd:!0,cartFocus:!0,checkoutTarget:"_self",defaultPurchase:"one-time",variantUrl:!1,maxAge:60,lowStock:5,autoMount:!0,observe:!1,astro:!0,partsUrl:null,formatMoney:null,onLayoutChange:null,onCartOpen:null,onCartClose:null,onLineEnter:null,onLineLeave:null,onValueChange:null,onError:null,debug:!1},n={...C};function G(t={}){return Object.keys(n).forEach(e=>delete n[e]),Object.assign(n,C,t),n.domain&&(n.domain=String(n.domain).replace(/^https?:\/\//,"").replace(/\/.*$/,"")),n.storageKey||(n.storageKey=`${n.prefix}:cart:${n.domain}`),n.apiVersion==="unstable"&&x('apiVersion "unstable" changes without notice. Pin a dated version (e.g. 2026-07).'),n}var H=()=>!!(n.domain&&n.token);function S(...t){n.debug&&console.log(`[${n.prefix}]`,...t)}function x(...t){console.warn(`[${n.prefix}]`,...t)}function J(t,e){if(x(e,t&&t.message?t.message:t),typeof n.onError=="function")try{n.onError(t,e)}catch{}}var d=class extends Error{constructor(e,{status:r,errors:o,userErrors:a,code:u}={}){super(e),this.name="TetherError",this.code=u||(r?`HTTP_${r}`:"ERROR"),this.status=r,this.errors=o,this.userErrors=a}};function I(t=n){return`https://${t.domain}/api/${t.apiVersion}/graphql.json`}function L(t,e=n){let r=[];if(e.country&&r.push(`country: ${String(e.country).toUpperCase()}`),e.language&&r.push(`language: ${String(e.language).toUpperCase().replace("-","_")}`),!r.length||/@inContext/.test(t))return t;let o=`@inContext(${r.join(", ")})`;return/^\s*\{/.test(t)?`query ${o} ${t.trimStart()}`:t.replace(/^(\s*(?:query|mutation)(?:\s+\w+)?\s*(?:\([^)]*\))?)/,`$1 ${o}`)}var T=t=>new Promise(e=>setTimeout(e,t));async function v(t,e,r={},{context:o=!0}={}){if(!t.domain||!t.token)throw new d("Tether is not configured: domain and token are required",{code:"NOT_CONFIGURED"});let a=o?L(e,t):e,u=t.maxAge??60;u>0&&!/^\s*mutation\b/.test(a)&&(a+=` #${Math.floor(Date.now()/(u*1e3))}`);let g=JSON.stringify({query:a,variables:r}),l=0;for(;;){let i;try{i=await(t.fetch||fetch)(I(t),{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t.token},body:g})}catch(h){if(l++<t.retries){await T(300*2**l);continue}throw new d(`Network error: ${h.message}`,{code:"NETWORK"})}if(i.status===430)throw new d("Shopify security rejection (430)",{status:430});if((i.status===429||i.status>=500)&&l++<t.retries){S("retry",i.status,l),await T(300*2**l);continue}let c;try{c=await i.json()}catch{throw new d(`Invalid response (${i.status})`,{status:i.status})}if(c.errors?.length){if(c.errors.some(p=>/quantityAvailable/.test(p.message||""))&&/\bquantityAvailable\b/.test(g))return S("no inventory permission, retrying without quantityAvailable"),v(t,e.replace(/\bquantityAvailable\b/g,""),r,{context:o});if(c.errors.some(p=>/'warnings'/.test(p.message||""))&&/warnings \{ code message target \}/.test(e))return v(t,e.replace(/ warnings \{ code message target \}/g,""),r,{context:o});if(c.errors.some(p=>p.extensions?.code==="THROTTLED")&&l++<t.retries){await T(500*2**l);continue}throw new d(c.errors.map(p=>p.message).join(" | "),{status:i.status,errors:c.errors})}if(!i.ok)throw new d(`HTTP ${i.status}`,{status:i.status});return c.data}}var X=(t,e,r)=>v(n,t,e,r);function z(t,e){if(!t)throw new d(`${e}: empty response`);let r=t.userErrors||[];if(r.length)throw new d(r.map(o=>o.message).join(" | "),{userErrors:r});return t}var b=t=>`${n.prefix}-${t}`,Q=(t,e)=>e===void 0?`[${b(t)}]`:`[${b(t)}="${e}"]`,U=(t,e)=>t.getAttribute(b(e)),Z=(t,e)=>t.hasAttribute(b(e)),F=()=>`data-${n.prefix}-key`;function tt(t,e){let r=n.productPath||"/product";if(!/\{(handle|id)\}/.test(r))return`${r.replace(/\/$/,"")}/${t}`;let o=e?String(e).split("/").pop():"";return r.replace(/\{handle\}/g,encodeURIComponent(t||"")).replace(/\{id\}/g,encodeURIComponent(o))}var P=(t,e)=>t?[...t.querySelectorAll(e)]:[],et=(t,e,r)=>P(t,e).filter(o=>o.closest(r)===t);function D(t,e,r=document){r.dispatchEvent(new CustomEvent(`${n.prefix}:${t}`,{detail:e,bubbles:!0}))}function rt(t,e=n.locale){if(!t)return"";try{return new Intl.NumberFormat(e||void 0,{style:"percent",maximumFractionDigits:0}).format(t/100)}catch{return`${t}%`}}function nt(t){if(!t)return"";if(typeof n.formatMoney=="function")return n.formatMoney(t,n.locale);let e=parseFloat(t.amount);if(Number.isNaN(e))return"";try{return new Intl.NumberFormat(n.locale||void 0,{style:"currency",currency:t.currencyCode}).format(e)}catch{return`${t.currencyCode} ${e.toFixed(2)}`}}function ot(t){if(!t)return"";try{return new Date(t).toLocaleDateString(n.locale||void 0)}catch{return""}}function M(t,{width:e,height:r,crop:o}={}){if(!t)return t;try{let a=new URL(t);return e&&a.searchParams.set("width",String(e)),r&&a.searchParams.set("height",String(r)),o&&a.searchParams.set("crop",o),a.toString()}catch{return t}}function R(t,e){if(!t||!e)return t;let r=o=>e.getAttribute(o);return M(t,{width:r("max-width"),height:r("max-height"),crop:r("max-width")||r("max-height")?r("crop"):null})}var j=(t,e)=>!!(t&&e)&&t.split("?")[0]===e.split("?")[0];function st(t,e,r){if(!e)return;let o=R(e,t);if(t.tagName==="IMG"&&j(t.getAttribute("src"),o)){r!=null&&!t.getAttribute("alt")&&t.setAttribute("alt",r);return}t.tagName==="IMG"?(t.removeAttribute("srcset"),t.removeAttribute("sizes"),t.setAttribute("src",o),r!=null&&t.setAttribute("alt",r),t.getAttribute("loading")||t.setAttribute("loading","lazy")):t.style.backgroundImage=`url("${o}")`}function V(t,e){let r=e==null?"":String(e);t.tagName==="INPUT"||t.tagName==="TEXTAREA"?t.value=r:t.textContent=r}var N=t=>t.tagName==="INPUT"||t.tagName==="TEXTAREA"?t.value:t.textContent;function at(t,e){let r=N(t);V(t,e);let o=N(t);if(r!==o&&t.dataset.tetherSeen&&typeof n.onValueChange=="function")try{n.onValueChange(t,r)}catch{}t.dataset.tetherSeen="1"}function it(t,e){let r="tetherPrevDisplay";if(e){if(t.dataset.tetherShown!==void 0)return;t.dataset.tetherShown="",t.removeAttribute("hidden"),t.dataset[r]!==void 0?(t.style.display=t.dataset[r],delete t.dataset[r]):t.style.display==="none"&&(t.style.display=""),typeof getComputedStyle=="function"&&getComputedStyle(t).display==="none"&&(t.style.display=t.getAttribute(`${n.prefix}-display`)||"block")}else delete t.dataset.tetherShown,t.dataset[r]===void 0&&t.style.display!=="none"&&(t.dataset[r]=t.style.display||""),t.style.display="none"}function ut(t,e){t.classList.toggle("is-selected",e),t.setAttribute("aria-pressed",e?"true":"false"),t.tagName==="INPUT"&&(t.type==="radio"||t.type==="checkbox")&&(t.checked=e);let r=t.querySelector?.('input[type="radio"],input[type="checkbox"]');r&&(r.checked=e)}var A=new WeakMap,ct=t=>!!A.get(t);function O(t){if(!A.has(t)){let e=t.firstElementChild?.cloneNode(!0)??null;A.set(t,e),t.innerHTML=""}return A.get(t)}function lt(t,e,r){let o=O(t);if(!o){e.length&&x("repeater without a template child",t);return}t.innerHTML="",e.forEach((a,u)=>{let g=o.cloneNode(!0);r(g,a,u),t.appendChild(g)})}function pt(t,e,r,o,{onEnter:a,onLeave:u}={}){let g=O(t);if(!g){x("repeater without a template child",t);return}let l=F(),i=`data-${n.prefix}-leaving`,$=()=>[...t.children].filter(s=>s.hasAttribute(l)&&!s.hasAttribute(i)),c=new Map($().map(s=>[s.getAttribute(l),s])),h=[],w=new Set;e.forEach((s,f)=>{let m=String(r(s,f)),y=c.get(m);y?c.delete(m):(y=g.cloneNode(!0),y.setAttribute(l,m),w.add(y)),o(y,s,f,w.has(y)),h.push(y)});let p=h.filter(s=>!w.has(s)),E=$().filter(s=>p.includes(s));if(!(E.length===p.length&&E.every((s,f)=>s===p[f]))){c.forEach(s=>s.remove()),h.forEach(s=>t.appendChild(s));return}h.forEach((s,f)=>{if(!w.has(s))return;let m=h[f-1];if(m&&m.parentNode===t?m.after(s):t.prepend(s),a)try{a(s)}catch{}}),c.forEach(s=>{s.setAttribute(i,""),s.removeAttribute(l),s.style.pointerEvents="none",s.inert=!0;let f=()=>s.remove();if(u)try{u(s,f)}catch{f()}else f()})}var k=null;function K(t){clearTimeout(k),k=setTimeout(()=>{typeof n.onLayoutChange=="function"?n.onLayoutChange(t):window.ScrollTrigger?.refresh&&window.ScrollTrigger.refresh(),D("layout-changed",{reason:t})},120)}function ft(t,e){let r=P(t,"img").filter(u=>!u.complete);if(!r.length)return;let o=r.length,a=()=>{--o===0&&K(`${e}:images`)};r.forEach(u=>{u.addEventListener("load",a,{once:!0}),u.addEventListener("error",a,{once:!0})})}function dt(t,e){return t.getAttribute("aria-busy")==="true"?Promise.resolve():(t.setAttribute("aria-busy","true"),Promise.resolve().then(e).finally(()=>t.removeAttribute("aria-busy")))}function gt(t,e){let r=t&&U(t,e);if(!r)return null;try{return JSON.parse(r)}catch{return x(`invalid JSON in ${b(e)}`,t),null}}function ht(t){return t?Array.isArray(t)?t.map(e=>({key:String(e.key),value:String(e.value??"")})):Object.entries(t).map(([e,r])=>({key:e,value:String(r??"")})):[]}export{C as a,n as b,G as c,H as d,S as e,x as f,J as g,d as h,I as i,L as j,v as k,X as l,z as m,b as n,Q as o,U as p,Z as q,tt as r,P as s,et as t,D as u,rt as v,nt as w,ot as x,M as y,j as z,st as A,V as B,at as C,it as D,ut as E,ct as F,lt as G,pt as H,K as I,ft as J,dt as K,gt as L,ht as M};
@@ -0,0 +1,4 @@
1
+ import{b as l}from"./chunk-KARKXC6G.js";import{a as P}from"./chunk-VC46IEJQ.js";var i="amount currencyCode",a="url altText width height";function f(e=l){return(e.metafields||[]).map(t=>{if(typeof t=="string"){let n=t.indexOf(".");return{namespace:t.slice(0,n),key:t.slice(n+1)}}return t}).filter(t=>t.namespace&&t.key)}function $(e=l){let t=f(e);return t.length?`metafields(identifiers:[${t.map(r=>`{namespace: ${JSON.stringify(r.namespace)}, key: ${JSON.stringify(r.key)}}`).join(", ")}]){namespace key type value reference{... on MediaImage{image{${a}}}}}`:""}var A=` id name description recurringDeliveries options{name value}priceAdjustments{orderCount adjustmentValue{__typename ... on SellingPlanPercentagePriceAdjustment{adjustmentPercentage}... on SellingPlanFixedAmountPriceAdjustment{adjustmentAmount{${i}}}... on SellingPlanFixedPriceAdjustment{price{${i}}}}}`,y=` sellingPlan{id}checkoutChargeAmount{${i}}remainingBalanceChargeAmount{${i}}priceAdjustments{price{${i}}compareAtPrice{${i}}perDeliveryPrice{${i}}unitPrice{${i}}}`;function k(e=l){return` fragment TetherProduct on Product{id handle title description descriptionHtml productType vendor tags availableForSale publishedAt onlineStoreUrl requiresSellingPlan seo{title description}featuredImage{${a}}images(first:${e.imagesFirst}){nodes{${a}}}options{name optionValues{name swatch{color image{previewImage{${a}}}}}}priceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}compareAtPriceRange{minVariantPrice{${i}}maxVariantPrice{${i}}}${$(e)} sellingPlanGroups(first:${e.sellingPlanGroupsFirst}){nodes{name appName options{name values}sellingPlans(first:${e.sellingPlansFirst}){nodes{${A}}}}}variants(first:${e.variantsFirst}){nodes{id title availableForSale currentlyNotInStock quantityAvailable sku barcode selectedOptions{name value}image{${a}}price{${i}}compareAtPrice{${i}}unitPrice{${i}}sellingPlanAllocations(first:${e.sellingPlansFirst}){nodes{${y}}}}}}`}function I(){return` fragment TetherCart on Cart{id checkoutUrl totalQuantity note createdAt updatedAt attributes{key value}buyerIdentity{countryCode email}discountCodes{code applicable}cost{subtotalAmount{${i}}totalAmount{${i}}checkoutChargeAmount{${i}}}lines(first:100){nodes{id quantity attributes{key value}cost{totalAmount{${i}}subtotalAmount{${i}}amountPerQuantity{${i}}compareAtAmountPerQuantity{${i}}}discountAllocations{discountedAmount{${i}}}sellingPlanAllocation{sellingPlan{id name description recurringDeliveries options{name value}}checkoutChargeAmount{${i}}priceAdjustments{price{${i}}compareAtPrice{${i}}perDeliveryPrice{${i}}}}merchandise{... on ProductVariant{id title sku availableForSale requiresShipping quantityAvailable image{${a}}price{${i}}compareAtPrice{${i}}selectedOptions{name value}product{id title handle vendor featuredImage{${a}}}}}... on ComponentizableCartLine{lineComponents{id quantity merchandise{... on ProductVariant{id title product{title handle}}}}}}}}`}function L(){return`
2
+ id handle title description descriptionHtml
3
+ image { ${a} }
4
+ seo { title description }`}var j={};P(j,{GID:()=>p,allPlans:()=>u,allocationFor:()=>c,findPlan:()=>C,hasPlans:()=>h,planAdjustment:()=>S,planCheckoutCharge:()=>x,planPrice:()=>m,planSavings:()=>F,plansForVariant:()=>v,toGid:()=>s});var p={product:e=>s(e,"Product"),variant:e=>s(e,"ProductVariant"),sellingPlan:e=>s(e,"SellingPlan")};function s(e,t){let n=String(e??"").trim();return n?n.startsWith("gid://")?n:/^\d+$/.test(n)?`gid://shopify/${t}/${n}`:n:null}function u(e){return(e?.sellingPlanGroups?.nodes||[]).flatMap(n=>(n.sellingPlans?.nodes||[]).map(r=>({...r,group:n})))}function h(e){return u(e).length>0}function c(e,t){return!e||!t?null:(e.sellingPlanAllocations?.nodes||[]).find(n=>n.sellingPlan?.id===t)||null}function v(e,t){return u(e).filter(n=>c(t,n.id))}function m(e,t){let r=c(e,t)?.priceAdjustments?.[0];return r?.perDeliveryPrice||r?.price||e?.price||null}function x(e,t){let n=c(e,t);return n?.checkoutChargeAmount||n?.priceAdjustments?.[0]?.price||e?.price||null}function F(e,t){let n=parseFloat(e?.price?.amount),r=parseFloat(m(e,t)?.amount);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r>=n?{amount:null,percentage:0}:{amount:{amount:(n-r).toFixed(2),currencyCode:e.price.currencyCode},percentage:Math.round((1-r/n)*100)}}function S(e){let t=e?.priceAdjustments?.[0]?.adjustmentValue;if(!t)return null;switch(t.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:t.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"amount",value:t.adjustmentAmount};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:t.price};default:return null}}function C(e,t){if(!t)return null;let n=u(e),r=p.sellingPlan(t),d=String(t).trim().toLowerCase();return n.find(o=>o.id===r)||n.find(o=>o.name.toLowerCase()===d)||n.find(o=>(o.options||[]).some(g=>String(g.value).toLowerCase()===d))||null}export{k as a,I as b,L as c,p as d,u as e,c as f,m as g,x as h,F as i,S as j,C as k,j as l};
@@ -1 +1 @@
1
- import{b as c,l as g}from"./chunk-HXKV6QGB.js";var p=/^[A-Z]{2}$/,y=new Set(["PT_BR","PT_PT","ZH_CN","ZH_TW"]),d=()=>`${c.prefix}:market:${c.domain}`,h=()=>({document:typeof document<"u"?document:null,location:typeof window<"u"?window.location:null,storage:(()=>{try{return window.localStorage}catch{return null}})(),global:typeof window<"u"?window:{}});function w(t){let e=String(t||"").trim().toUpperCase();return p.test(e)&&e!=="XX"&&e!=="T1"?e:null}function C(t){let e=String(t||"").trim().replace("-","_").toUpperCase();if(!e)return null;if(y.has(e))return e;let n=e.split("_")[0];return/^[A-Z]{2,3}$/.test(n)?n:null}function b(t,e){if(!t||!e)return null;let n=String(t.cookie||"").split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?decodeURIComponent(n.slice(e.length+1)):null}var s=(t,e)=>{if(!t||!e)return null;let n=String(e).toLowerCase(),r=Object.keys(t).find(o=>o.toLowerCase()===n);return r?t[r]:null},T={saved(t,e){if(t.remember===!1||!e.storage)return null;try{return JSON.parse(e.storage.getItem(d())||"null")}catch{return null}},server(t,e){let n=a=>e.document?.querySelector?.(`meta[name="${a}"]`)?.getAttribute("content"),r=e.global.TETHER_COUNTRY||n("tether-country")||b(e.document,t.cookie||"tether_country"),o=e.global.TETHER_LANGUAGE||n("tether-language");return{country:r,language:o}},webflow(t,e){let n=(e.location?.pathname||"/").split("/").filter(Boolean)[0],r=s(t.locales,n);if(r)return r;let o=e.document?.documentElement?.getAttribute("lang");if(!o)return null;let a=s(t.locales,o)||s(t.locales,o.split("-")[0]);if(a)return{locale:o,...a};if(t.locales&&t.strict)return null;let l=o.split("-")[1];return{language:o,country:l&&l.length===2?l:null,locale:o}}};function L(t=c.markets,e=h()){let n=t||{};if(n.detect===!1)return{};let r=n.detect?n.detect===!0?["saved","server","webflow"]:[].concat(n.detect):["saved"];t=n;let o={sources:{}};return r.forEach(a=>{let l=T[a]?.(t,e);if(!l)return;let m={country:w(l.country),language:C(l.language),locale:l.locale||null};Object.entries(m).forEach(([i,f])=>{f&&!o[i]&&(o[i]=f,o.sources[i]=a)})}),o}function _(t){if(c.markets?.remember!==!1)try{localStorage.setItem(d(),JSON.stringify({country:t.country,language:t.language||void 0,locale:t.locale||void 0}))}catch{}}var u=null;function A(){u=null}function x(){return u||(u=g("query TetherLocalization{localization{country{isoCode name currency{isoCode symbol}}language{isoCode name}availableCountries{isoCode name currency{isoCode symbol}availableLanguages{isoCode name}}}}").then(t=>t.localization).catch(t=>{throw u=null,t})),u}export{w as a,C as b,L as c,_ as d,A as e,x as f};
1
+ import{b as c,l as g}from"./chunk-KARKXC6G.js";var p=/^[A-Z]{2}$/,y=new Set(["PT_BR","PT_PT","ZH_CN","ZH_TW"]),d=()=>`${c.prefix}:market:${c.domain}`,h=()=>({document:typeof document<"u"?document:null,location:typeof window<"u"?window.location:null,storage:(()=>{try{return window.localStorage}catch{return null}})(),global:typeof window<"u"?window:{}});function w(t){let e=String(t||"").trim().toUpperCase();return p.test(e)&&e!=="XX"&&e!=="T1"?e:null}function C(t){let e=String(t||"").trim().replace("-","_").toUpperCase();if(!e)return null;if(y.has(e))return e;let n=e.split("_")[0];return/^[A-Z]{2,3}$/.test(n)?n:null}function b(t,e){if(!t||!e)return null;let n=String(t.cookie||"").split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?decodeURIComponent(n.slice(e.length+1)):null}var s=(t,e)=>{if(!t||!e)return null;let n=String(e).toLowerCase(),r=Object.keys(t).find(o=>o.toLowerCase()===n);return r?t[r]:null},T={saved(t,e){if(t.remember===!1||!e.storage)return null;try{return JSON.parse(e.storage.getItem(d())||"null")}catch{return null}},server(t,e){let n=a=>e.document?.querySelector?.(`meta[name="${a}"]`)?.getAttribute("content"),r=e.global.TETHER_COUNTRY||n("tether-country")||b(e.document,t.cookie||"tether_country"),o=e.global.TETHER_LANGUAGE||n("tether-language");return{country:r,language:o}},webflow(t,e){let n=(e.location?.pathname||"/").split("/").filter(Boolean)[0],r=s(t.locales,n);if(r)return r;let o=e.document?.documentElement?.getAttribute("lang");if(!o)return null;let a=s(t.locales,o)||s(t.locales,o.split("-")[0]);if(a)return{locale:o,...a};if(t.locales&&t.strict)return null;let l=o.split("-")[1];return{language:o,country:l&&l.length===2?l:null,locale:o}}};function L(t=c.markets,e=h()){let n=t||{};if(n.detect===!1)return{};let r=n.detect?n.detect===!0?["saved","server","webflow"]:[].concat(n.detect):["saved"];t=n;let o={sources:{}};return r.forEach(a=>{let l=T[a]?.(t,e);if(!l)return;let m={country:w(l.country),language:C(l.language),locale:l.locale||null};Object.entries(m).forEach(([i,f])=>{f&&!o[i]&&(o[i]=f,o.sources[i]=a)})}),o}function _(t){if(c.markets?.remember!==!1)try{localStorage.setItem(d(),JSON.stringify({country:t.country,language:t.language||void 0,locale:t.locale||void 0}))}catch{}}var u=null;function A(){u=null}function x(){return u||(u=g("query TetherLocalization{localization{country{isoCode name currency{isoCode symbol}}language{isoCode name}availableCountries{isoCode name currency{isoCode symbol}availableLanguages{isoCode name}}}}").then(t=>t.localization).catch(t=>{throw u=null,t})),u}export{w as a,C as b,L as c,_ as d,A as e,x as f};
@@ -0,0 +1 @@
1
+ import{a as w,c as v}from"./chunk-YXCXIPQV.js";import{b as x,e as K,h as P,l as p}from"./chunk-KARKXC6G.js";var d=new Map,D=[],E=new Map,S=!1,g=0,q=t=>typeof t=="string"&&t.startsWith("gid://");function I(t){let e=String(t??"").trim();if(!e)return null;if(q(e))return e;if(/^\d+$/.test(e))return`gid://shopify/Product/${e}`;let n=e.match(/\/products\/([^/?#]+)/);return n?n[1]:e}function y(t){if(!t)return;let e=Promise.resolve(t);d.set(t.handle,e),d.set(t.id,e)}function F(t){let e=I(t);if(!e)return Promise.reject(new P("empty product key",{code:"NOT_FOUND"}));if(d.has(e))return d.get(e);let n=new Promise((c,i)=>{E.set(e,{resolve:c,reject:i}),D.push(e),S||(S=!0,setTimeout(N,0))});return d.set(e,n),n}async function N(){S=!1;let t=g,e=D.splice(0);if(!e.length)return;let n=e.filter(q),c=e.filter(s=>!q(s)),i=[],a=[],h={};n.length&&(i.push("$ids: [ID!]!"),h.ids=n,a.push("byId: nodes(ids: $ids) { ... on Product { ...TetherProduct } }")),c.forEach((s,o)=>{i.push(`$h${o}: String!`),h[`h${o}`]=s,a.push(`h${o}: product(handle: $h${o}) { ...TetherProduct }`)});let m=`query TetherProducts(${i.join(",")}){${a.join(" ")}}${w()}`;K("fetch products",e);let f=(s,o)=>{let r=E.get(s);E.delete(s),r&&o(r)};try{let s=await p(m,h),o=new Map;(s.byId||[]).forEach(r=>{r&&o.set(r.id,r)}),c.forEach((r,$)=>{s[`h${$}`]&&o.set(r,s[`h${$}`])}),e.forEach(r=>f(r,$=>{if(o.has(r)){let l=o.get(r);t===g&&(y(l),T.set(l.handle,Date.now()),T.set(l.id,Date.now())),$.resolve(l)}else{let l=d.get(r);t===g&&setTimeout(()=>{d.get(r)===l&&d.delete(r)},1e4),$.reject(new P(`Product not found: ${r}`,{code:"NOT_FOUND"}))}}))}catch(s){e.forEach(o=>f(o,r=>{t===g&&d.delete(o),r.reject(s)}))}}function M(){d.clear(),g++,u.clear(),T.clear()}var u=new Set,T=new Map,C=6e4;function b(t){(t||[]).forEach(e=>{!e?.id||!e.handle||Date.now()-(T.get(e.handle)||0)<C&&d.has(e.handle)||(y(e),u.add(e.handle),u.add(e.id))})}function _(t){let e=I(t);if(!u.has(e))return!1;let n=d.get(e);return u.delete(e),n?.then?.(c=>{u.delete(c.handle),u.delete(c.id)}),!0}function U(t){return t.forEach(e=>d.delete(I(e))),t.map(e=>F(e))}async function A({collection:t,query:e,first:n=x.collectionFirst,after:c=null,sortKey:i,reverse:a=!1,filters:h}={}){let m=w();if(t){let s=await p(`query TetherCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${v()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}${m}`,{handle:t,first:n,after:c,sortKey:i||void 0,reverse:a,filters:h||void 0});if(!s.collection)throw new P(`Collection not found: ${t}`,{code:"NOT_FOUND"});let{products:o,...r}=s.collection;return o.nodes.forEach(y),{collection:r,products:o.nodes,pageInfo:o.pageInfo}}let f=await p(`query TetherSearch($first:Int!,$after:String,$query:String,$sortKey:ProductSortKeys,$reverse:Boolean){products(first:$first,after:$after,query:$query,sortKey:$sortKey,reverse:$reverse){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}${m}`,{first:n,after:c,query:e||void 0,sortKey:i||void 0,reverse:a});return f.products.nodes.forEach(y),{collection:null,products:f.products.nodes,pageInfo:f.products.pageInfo}}async function B(t,e="RELATED"){let n=I(typeof t=="object"?t?.id:t),c=n?.startsWith("gid://"),a=(await p(`query TetherRecs(${c?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${c?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}${w()}`,c?{id:n,intent:e}:{handle:n,intent:e})).productRecommendations||[];return a.forEach(y),a}export{I as a,y as b,F as c,M as d,b as e,_ as f,U as g,A as h,B as i};
@@ -0,0 +1 @@
1
+ import{c as D}from"./chunk-YZMBXS6Y.js";import{a as b,d as x}from"./chunk-4UR45XTC.js";import{c as E}from"./chunk-ZVUPVSLF.js";import{e as P}from"./chunk-YXCXIPQV.js";import{F as V,b as a,d as w,i as S,l as v,n as u,o as r,p as y,s as c}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";var q=e=>{let o=/^(\d{4})-(01|04|07|10)$/.exec(String(e||""));return o?{y:+o[1],m:+o[2]}:null},C=(e,o)=>`${e}-${String(o).padStart(2,"0")}`;function M(e,o=1){let n=q(e);if(!n)throw new Error(`not a quarterly Shopify API version: ${e}`);let p=n.y*4+(n.m-1)/3+o;return C(Math.floor(p/4),p%4*3+1)}function A(e,o=new Date){if(e==="unstable")return{version:e,ok:!1,note:'"unstable" changes without notice: pin a dated version such as 2026-07'};let n=q(e);if(!n)return{version:e,ok:!1,note:"not a quarterly version (YYYY-01, -04, -07 or -10)"};let p=new Date(Date.UTC(n.y,n.m-1,1)),s=new Date(Date.UTC(n.y+1,n.m-1,1)),g=(s-o)/(30.44*24*3600*1e3),l=`supported until about ${s.toISOString().slice(0,7)}`;return p>o?l="not released yet (release candidate at best)":g<=0?l="no longer supported: Shopify falls back to the oldest supported version. Upgrade (see README)":g<3&&(l=`${l}: plan the upgrade to ${M(e)} or later (see README)`),{version:e,ok:p<=o&&g>0,monthsLeft:Math.round(g),next:M(e),note:l}}var I=e=>e?`${String(e).slice(0,4)}\u2026${String(e).slice(-4)} (${String(e).length} chars)`:"(missing)";function T(e){let o=e.id?`#${e.id}`:"",n=e.className&&typeof e.className=="string"?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";return`<${e.tagName.toLowerCase()}${o}${n}>`}function N(e=document){let o=[],n=(t,i,d)=>o.push({level:t,message:i,element:d?T(d):void 0,el:d}),p=t=>!!t.closest(r("product")),s=`${r("collection")},${r("products")},${r("recommendations")}`;c(e,r("product")).forEach(t=>{if(t.closest(s)&&t.closest(r("list")))return;let{key:i,fromUrl:d,raw:h}=b(t);h?d&&!i&&n("warn",`${u("product")}="${h}" but this URL has no value for it (e.g. ?handle=my-product).`,t):n("error",`${u("product")} has no value. Bind it to the Shopify handle (CMS field), or use "url:handle".`,t)}),["bind","option-list","option","variant-select","add-to-cart","purchase","plan-list","plan","qty","line-attribute"].forEach(t=>{c(e,r(t)).forEach(i=>{p(i)||t==="line-attribute"&&i.closest(r("group"))||n("warn",`${u(t)} outside any ${u("product")}: it does nothing here.`,i)})}),c(e,r("group-add")).forEach(t=>{t.closest(r("group"))||n("warn",`${u("group-add")} outside a ${u("group")}.`,t)}),[...c(e,r("option-list")),...c(e,r("plan-list")),...c(e,r("cart-lines")),...c(e,r("list"))].forEach(t=>{!t.firstElementChild&&!V(t)&&n("warn","Repeater without a template child: put one example element inside it.",t)}),c(e,s).forEach(t=>{c(t,r("list")).length||n("error",`List without a ${u("list")} child: products have nowhere to render.`,t)});let l=new Set(["in-stock","out-of-stock","backorder","low-stock","plenty-in-stock","on-sale","not-on-sale","has-variants","single-variant","subscription-available","subscription-unavailable","subscription-only","one-time-available","subscription-selected","one-time-selected","has-savings","loading","ready","error","not-found","cart-empty","cart-filled","cart-has-subscription","cart-no-subscription","cart-has-discount","cart-error","cart-warning","list-empty","list-filled"]);return c(e,r("show")).forEach(t=>{let i=y(t,"show");l.has(i)||n("warn",`Unknown ${u("show")}="${i}".`,t)}),c(e,r("bind")).forEach(t=>{let i=y(t,"bind")||"";if(!i.startsWith("metafield:"))return;let d=i.slice(10);(a.metafields||[]).some($=>(typeof $=="string"?$:`${$.namespace}.${$.key}`)===d)||n("error",`${u("bind")}="${i}" but "${d}" is not in config.metafields, so it stays empty.`,t)}),c(e,r("cart-open")).length&&!c(e,r("cart-drawer")).length&&n("warn",`${u("cart-open")} exists but there is no ${u("cart-drawer")} on this page.`),c(e,r("cart-drawer")).length>1&&n("warn",`More than one ${u("cart-drawer")}.`),c(e,`[${u("state")}="error"]`).forEach(t=>{t.matches(x())&&n("error",`Scope failed to load (${y(t,"error")||"error"}).`,t)}),o}async function G({root:e=document,silent:o=!1,version:n,now:p=new Date}={}){let s={version:n,config:{domain:a.domain||"(missing)",token:I(a.token),apiVersion:a.apiVersion,endpoint:a.domain?S():null,country:a.country,language:a.language,locale:a.locale,markets:a.markets||null,prefix:a.prefix,productPath:a.productPath,metafields:a.metafields,autoMount:a.autoMount,observe:a.observe,onError:typeof a.onError=="function"},apiVersion:A(a.apiVersion,p),market:{country:a.country||null,language:a.language||null,locale:a.locale||null,detected:a.markets?.detect?D(a.markets):null},reachable:!1,shop:null,latencyMs:null,products:[],sellingPlans:[],problems:[]};if(!w())s.problems.push({level:"error",message:"TETHER_CONFIG needs domain and token."});else{let g=Date.now();try{let l=await v("query TetherDiagnose { shop { name primaryDomain { url } paymentSettings { currencyCode } } }",{},{context:!1});s.reachable=!0,s.shop={name:l.shop?.name,url:l.shop?.primaryDomain?.url,currency:l.shop?.paymentSettings?.currencyCode}}catch(l){let t=l.status===401||l.status===403?"Token rejected: use the public Storefront token from the Headless channel, not an Admin token.":l.status===404?"Store or API version not found: check domain (x.myshopify.com) and apiVersion.":"";s.problems.push({level:"error",message:`Storefront API not reachable: ${l.message}${t?`. ${t}`:""}`})}if(s.latencyMs=Date.now()-g,s.reachable){let l=[...new Set(c(e,r("product")).map(i=>b(i).key).filter(Boolean))].slice(0,20);(await Promise.allSettled(l.map(i=>E(i)))).forEach((i,d)=>{if(i.status==="fulfilled"){let h=i.value,$=P(h);s.products.push({key:l[d],handle:h.handle,title:h.title,plans:$.length,requiresSellingPlan:h.requiresSellingPlan}),$.forEach(f=>s.sellingPlans.push({product:h.handle,group:f.group?.name,plan:f.name,id:f.id})),c(e,r("product")).filter(f=>b(f).key===l[d]&&f.querySelector(r("add-to-cart"))).forEach(f=>{let k=new Set(c(f,`${r("option-list")},select${r("option")}`).map(m=>y(m,"option-list")||y(m,"option")));!k.size&&c(f,`select${r("variant-select")}`).length||(h.options||[]).filter(m=>m.optionValues.length>1&&!k.has(m.name)).forEach(m=>{s.problems.push({level:"warn",message:`Product "${h.handle}": option "${m.name}" (${m.optionValues.length} values) has no tether-option-list, so visitors can't choose it.`})})})}else s.products.push({key:l[d],error:i.reason?.message}),s.problems.push({level:"error",message:`Product "${l[d]}": ${i.reason?.message}. Is it published to the Headless channel?`})})}}return(!s.apiVersion.ok||(s.apiVersion.monthsLeft??99)<3)&&s.problems.push({level:s.apiVersion.ok?"warn":"error",message:`apiVersion ${a.apiVersion}: ${s.apiVersion.note}`}),typeof document<"u"&&s.problems.push(...N(e)),o||U(s),s}function U(e){let o=console,n=e.problems.filter(p=>p.level==="error").length;o.group?.(`[${a.prefix}] diagnose: ${n?`${n} error(s)`:"no errors"}, ${e.problems.length-n} warning(s)`),o.log("version",e.version,"| API",e.apiVersion.version,`(${e.apiVersion.note})`),o.log("config",e.config),e.market&&o.log("market detected",e.market,"(in use:",e.config.country,e.config.language,")"),o.log(e.reachable?`Storefront API reachable: ${e.shop?.name} (${e.latencyMs} ms)`:"Storefront API NOT reachable"),e.products.length&&(o.table||o.log)(e.products),e.sellingPlans.length?(o.table||o.log)(e.sellingPlans):e.reachable&&o.log("No selling plans on the products of this page."),e.problems.forEach(p=>(p.level==="error"?o.error:o.warn)(p.message,p.el||"")),o.groupEnd?.()}export{A as apiVersionStatus,N as checkMarkup,G as diagnose};
@@ -0,0 +1 @@
1
+ import{a as b}from"./chunk-6R752OYZ.js";import"./chunk-4UR45XTC.js";import{b as l}from"./chunk-BGIKQY6H.js";import"./chunk-ZVUPVSLF.js";import"./chunk-YXCXIPQV.js";import{L as w,M as h,b as o,f as p,g,o as u,p as d,q as f,s as m,u as y}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";async function q(e){let t=e.closest(u("group"));if(!t)return null;let n=d(t,"group"),s=h(w(t,"line-attributes")),i=n?[{key:"_group",value:n},...s]:s,a=m(t,u("product")).map(r=>b.get(r)).filter(r=>r&&r.variant?.availableForSale&&r.quantity>0).map(r=>{let c=r.getLine();return c.attributes=[...c.attributes||[],...i],c});if(!a.length)return p("group-add: nothing selected"),null;try{let r=await l.add(a);return y("group-added",{group:n,lines:a},t),r}catch(r){return g(r,"group add"),null}}function A(e){if(e.key===o.storageKey||e.key===`${o.storageKey}:seen`)l.init();else if(e.key===`${o.prefix}:market:${o.domain}`&&e.newValue)try{let t=JSON.parse(e.newValue);t?.country&&window.Tether?.setCountry(t.country,{language:t.language??null,locale:t.locale,remember:!1}).catch(()=>{})}catch{}}var k=new WeakMap;function K(e,{variant:t,sellingPlanId:n}){let s=`${t.id}|${n||""}`,i=k.get(e);if(k.set(e,s),!(!i||i===s)&&!(!f(e,"variant-url")&&!(o.variantUrl&&document.querySelector(u("product"))===e)))try{let a=new URL(window.location.href);a.searchParams.set("variant",t.id.split("/").pop()),n?a.searchParams.set("selling_plan",n.split("/").pop()):a.searchParams.delete("selling_plan"),window.history.replaceState(window.history.state,"",a)}catch{}}export{q as addGroup,A as onStorage,K as writeVariantUrl};
@@ -0,0 +1 @@
1
+ import{a as k,c as U,e as z,f as B,g as M,h as L,i as N}from"./chunk-CISGFYOF.js";import{a as C,b,c as T,d as A,e as I,f as v}from"./chunk-YZMBXS6Y.js";import"./chunk-6R752OYZ.js";import"./chunk-4UR45XTC.js";import{b as d}from"./chunk-BGIKQY6H.js";import{d as E}from"./chunk-ZVUPVSLF.js";import"./chunk-YXCXIPQV.js";import{b as t,g as p,h as w,n as g,o as h,p as P,u as x}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";function O(s=document){let u=L(s,`select${h("country-select")}`),m=L(s,h("country-bind"));return!u.length&&!m.length?Promise.resolve():v().then(l=>{let r=(t.country||l.country?.isoCode||"").toUpperCase(),c=[...l.availableCountries||[]].sort((e,o)=>e.name.localeCompare(o.name,t.locale||void 0)),i=c.find(e=>e.isoCode===r)||l.country,f=(e,o)=>e.replace(/\{name\}/g,o.name).replace(/\{code\}/g,o.isoCode).replace(/\{currency\}/g,o.currency?.isoCode||"").replace(/\{symbol\}/g,o.currency?.symbol||"");u.forEach(e=>{let o=e.getAttribute(g("country-label"))||"{name} ({currency})",a=(e.getAttribute(g("countries"))||"").toUpperCase().split(/[\s,]+/).filter(Boolean),n=a.length?a.map(y=>c.find(S=>S.isoCode===y)).filter(Boolean):c;e.innerHTML="",n.forEach(y=>e.appendChild(new Option(f(o,y),y.isoCode))),e.value=r,e.value!==r&&(e.selectedIndex=-1),e.disabled=n.length<2&&!e.hasAttribute(g("always-enabled"))}),m.forEach(e=>{let o=P(e,"country-bind")||"name",a={name:i?.name,code:i?.isoCode,currency:i?.currency?.isoCode,symbol:i?.currency?.symbol}[o];e.textContent=a||""})}).catch(l=>p(l,"country select"))}async function q(s,{language:u,locale:m,remember:l=!0}={}){let r=C(s);if(!r)throw new w(`Not a country code: ${s}`,{code:"INVALID_COUNTRY"});let c=Object.values(t.markets?.locales||{}).find(n=>C(n?.country)===r),i=m||c?.locale,f=i||t.locale,e=u!==void 0?b(u):c?c.language?b(c.language):void 0:t.language,o=r!==String(t.country||"").toUpperCase()||e!==t.language||f!==t.locale;if(t.country=r,t.language=e||void 0,t.locale=f,l&&A({country:r,language:e,locale:i}),!o)return O(),d.state;E();let a=[];return u!==void 0&&I(),d.id()&&a.push(d.setBuyerIdentity({countryCode:r},{create:!1}).catch(n=>p(n,"cart country"))),M(),B.forEach(n=>a.push(n.load())),z.forEach(n=>{n.closest(k())||(U.delete(n),N(n))}),O(),x("country-changed",{country:r,language:t.language}),await Promise.all(a),d.state}export{T as detectMarket,v as getLocalization,O as renderCountrySelects,q as setCountry};
@@ -0,0 +1 @@
1
+ import{A as N,B as O,D as q,G as V,b as y,g as C,l as E,n as D,o as u,p,r as R,s as h,u as U,w as P}from"./chunk-KARKXC6G.js";import"./chunk-VC46IEJQ.js";var H="query TetherPredictive($q:String!,$limit:Int!){predictiveSearch(query:$q,limit:$limit,limitScope:EACH,types:[PRODUCT,COLLECTION,QUERY]){products{id handle title availableForSale featuredImage{url altText}priceRange{minVariantPrice{amount currencyCode}}}collections{handle title image{url altText}}queries{text}}}",F=new WeakSet,W=0;function J(s=document){[...s.matches?.(u("search"))?[s]:[],...h(s,u("search"))].forEach(c=>{F.has(c)||(F.add(c),j(c))})}function j(s){let n=s.querySelector(u("search-input"))||s.querySelector("input"),c=s.querySelector(u("search-results"));if(!n||!c)return;let M=parseInt(p(s,"search-limit")||"6",10)||6,v=parseInt(p(s,"search-min")||"2",10)||2,k=c.id||(c.id=`${y.prefix}-search-${++W}`);n.setAttribute("role","combobox"),n.setAttribute("aria-autocomplete","list"),n.setAttribute("aria-controls",k),n.setAttribute("aria-expanded","false"),n.setAttribute("autocomplete","off"),c.hasAttribute("role")||c.setAttribute("role","listbox"),c.hidden=!0;let x=0,w=null,I="",L=new Map,b=t=>s.setAttribute(D("search-state"),t),f=t=>{s.classList.toggle("is-open",t),c.hidden=!t,n.setAttribute("aria-expanded",String(t)),t||n.removeAttribute("aria-activedescendant")},S=()=>h(c,'[role="option"]');async function Q(t){let e=++x;if(t.length<v){f(!1),b("idle");return}b("loading");try{let r=L.get(t)||(await E(H,{q:t,limit:M})).predictiveSearch;if(L.set(t,r),e!==x)return;Y(r,t)}catch(r){if(e!==x)return;b("error"),C(r,"search")}}function Y(t,e){let r=t?.products||[],o=t?.collections||[],l=(t?.queries||[]).filter(i=>i.text.toLowerCase()!==e.toLowerCase()),d=(i,a,A)=>h(c,u(i)).forEach(g=>{V(g,a,A),q(g,a.length>0)});d("search-products",r,(i,a)=>{$(i,{title:a.title,price:P(a.priceRange?.minVariantPrice),image:a.featuredImage}),T(i,R(a.handle,a.id)),i.classList.toggle("is-sold-out",!a.availableForSale)}),d("search-collections",o,(i,a)=>{$(i,{title:a.title,image:a.image}),T(i,`${(y.collectionPath||"/collection").replace(/\/$/,"")}/${a.handle}`)}),d("search-queries",l,(i,a)=>{$(i,{text:a.text});let A=i.tagName==="A"?i:i.querySelector("a"),g=s.getAttribute("action")||"/search";A&&A.setAttribute("href",`${g}${g.includes("?")?"&":"?"}${n.name||"q"}=${encodeURIComponent(a.text)}`)});let m=r.length+o.length+l.length;h(s,u("show")).forEach(i=>{let a=p(i,"show");a==="search-empty"&&q(i,m===0),a==="search-results"&&q(i,m>0)}),S().forEach((i,a)=>{i.id||(i.id=`${k}-${a}`),i.setAttribute("aria-selected","false")}),b(m?"ready":"empty"),f(!0),U("search",{term:e,products:r,collections:o,queries:l},s)}function $(t,e){h(t,u("search-bind")).forEach(r=>{let o=p(r,"search-bind");o==="image"?N(r,e.image?.url,e.image?.altText||e.title):e[o]!=null&&O(r,e[o])})}function T(t,e){let r=t.tagName==="A"?t:t.querySelector("a");r&&(r.setAttribute("href",e),r.setAttribute("role","option"))}n.addEventListener("input",()=>{let t=n.value.trim();t!==I&&(I=t,clearTimeout(w),w=setTimeout(()=>Q(t),y.searchDelay??150))}),n.addEventListener("focus",()=>{n.value.trim().length>=v&&S().length&&f(!0)}),n.addEventListener("keydown",t=>{let e=S(),r=e.findIndex(l=>l.getAttribute("aria-selected")==="true"),o=l=>{e.forEach((d,m)=>d.setAttribute("aria-selected",String(m===l))),e[l]&&(n.setAttribute("aria-activedescendant",e[l].id),e[l].scrollIntoView?.({block:"nearest"}))};t.key==="ArrowDown"&&e.length?(t.preventDefault(),f(!0),o((r+1)%e.length)):t.key==="ArrowUp"&&e.length?(t.preventDefault(),o(r<=0?e.length-1:r-1)):t.key==="Enter"&&r>=0?(t.preventDefault(),e[r].click()):t.key==="Escape"&&f(!1)}),document.addEventListener("click",t=>{s.contains(t.target)||f(!1)})}export{J as mountSearch};
package/dist/esm/index.js CHANGED
@@ -1 +1 @@
1
- import{a as j,b as c,c as T,d as Z,e as Q,g as $,i as O,j as W,k as v,l as X,m as Y,n as tt}from"./chunks/chunk-HHMOPDZG.js";import{a as q,b as A,c as _,d as F,h as R,i as G,j as V}from"./chunks/chunk-RNZMTQTX.js";import{A as o,B as H,E as x,G as h,H as z,J as B,V as g,W as J,X as U,b as a,c as P,d as L,e as k,f as b,g as d,h as I,j as M,l as N,y as K,z as C}from"./chunks/chunk-HXKV6QGB.js";import"./chunks/chunk-VC46IEJQ.js";var f=e=>e==="diagnose"?import("./chunks/diagnose-J667GHGS.js"):import("./chunks/markets-ui-EGWIEUOZ.js");var et="0.5.0",m=null,S=null;function y(e=document){if(!L())return 0;let t=0;return W(),tt(e),v(e,Z()).forEach(r=>{if($.has(r))return;$.add(r),t++;let n=new Q(r);O.add(n),r.addEventListener(`${a.prefix}:list-rendered`,i=>y(i.detail.container)),n.load()}),v(e,o("product")).forEach(r=>{X(r)&&t++}),v(e,`${o("country-select")},${o("country-bind")}`).length&&f("markets").then(r=>r.renderCountrySelects(e)).catch(r=>d(r,"markets")),x(e,o("account-link")).forEach(r=>{r.setAttribute("href",`https://${a.domain}/account`)}),c.render(),k(`mounted ${t} scope(s)`,e),t}function ot(){c.close()}function lt(e){let t=e?.closest?.(o("product"));return t&&T.get(t)||null}var rt=!1;function dt(){rt||(rt=!0,document.addEventListener("click",e=>{let t=e.target;if(!t?.closest)return;if(t.closest(o("cart-open"))){e.preventDefault(),c.toggle();return}if(t.closest(o("cart-close"))){e.preventDefault(),c.close();return}let r=t.closest(o("cart-clear"));if(r){e.preventDefault(),g(r,()=>c.clear().catch(l=>d(l,"cart clear")));return}let n=t.closest(o("checkout"));if(n){e.preventDefault(),g(n,()=>c.checkout());return}let i=t.closest(nt());if(i&&i.closest(o("cart-lines"))){let l=i.getAttribute(`data-${a.prefix}-key`),p=c.lines.find(w=>w.id===l),E=w=>{e.preventDefault(),w().catch(st=>d(st,"cart line"))};if(t.closest(o("line-remove")))return E(()=>c.removeLine(l));if(p&&t.closest(o("line-plus")))return E(()=>c.updateLine(l,p.quantity+1));if(p&&t.closest(o("line-minus")))return E(()=>c.updateLine(l,p.quantity-1))}let u=t.closest(o("discount-remove"));if(u){e.preventDefault();let l=u.closest(o("discount-code"))?.getAttribute(C("discount-code"));l&&c.removeDiscount(l).catch(p=>d(p,"discount"));return}let s=t.closest(o("group-add"));s&&(e.preventDefault(),g(s,()=>it(s)))}),document.addEventListener("change",e=>{let t=e.target;if(!t?.closest)return;let n=t.closest(nt())?.getAttribute(`data-${a.prefix}-key`);n&&t.matches(`input${o("line","quantity")}`)?c.updateLine(n,parseInt(t.value,10)||0).catch(i=>d(i,"cart line")):n&&t.matches(`select${o("line-plan")}`)?c.updateLine(n,{sellingPlanId:t.value||null}).catch(i=>d(i,"cart line plan")):t.matches(`select${o("country-select")}`)?t.value&&at(t.value).catch(i=>d(i,"country")):t.matches(o("cart-note"))&&c.setNote(t.value).catch(i=>d(i,"cart note"))}),document.addEventListener("submit",e=>{let t=e.target.closest?.(o("discount-form"));if(!t)return;e.preventDefault();let r=t.querySelector(o("discount-input"))||t.querySelector("input"),n=r?.value.trim();n&&g(t,async()=>{try{let u=((await c.applyDiscount(n))?.discountCodes||[]).find(s=>s.code.toLowerCase()===n.toLowerCase())?.applicable;u||await c.removeDiscount(n).catch(()=>{}),t.classList.toggle("is-invalid",!u),h(u?"discount-applied":"discount-invalid",{code:n},t),u&&r&&(r.value="")}catch(i){t.classList.add("is-invalid"),d(i,"discount")}})},!0),document.addEventListener("input",e=>{e.target.closest?.(o("discount-form"))?.classList.remove("is-invalid")}),a.astro!==!1&&(document.addEventListener("astro:page-load",()=>y(document)),document.addEventListener("astro:before-swap",()=>ot())),window.addEventListener("online",()=>{Y(),O.forEach(e=>{e.root.getAttribute(C("state"))==="error"&&e.load()})}),document.addEventListener("keydown",e=>{if(!c.isOpen())return;if(e.key==="Escape"){c.close();return}if(e.key!=="Tab"||a.cartFocus===!1)return;let t=c.drawers().find(u=>u.classList.contains(a.cartDrawerOpenClass)),r=t?j(t):[];if(!r.length)return;let n=r[0],i=r[r.length-1];(!t.contains(document.activeElement)||e.shiftKey&&document.activeElement===n||!e.shiftKey&&document.activeElement===i)&&(e.preventDefault(),(e.shiftKey?i:n).focus())}))}function nt(){return`[data-${a.prefix}-key]`}async function it(e){let t=e.closest(o("group"));if(!t)return null;let r=H(t,"group"),n=U(J(t,"line-attributes")),i=r?[{key:"_group",value:r},...n]:n,u=x(t,o("product")).map(s=>T.get(s)).filter(s=>s&&s.variant?.availableForSale&&s.quantity>0).map(s=>{let l=s.getLine();return l.attributes=[...l.attributes||[],...i],l});if(!u.length)return b("group-add: nothing selected"),null;try{let s=await c.add(u);return h("group-added",{group:r,lines:u},t),s}catch(s){return d(s,"group add"),null}}function ct(e={}){return m&&!Object.keys(e).length?m:(P({...window.TETHER_CONFIG||{},...e}),L()?(dt(),a.observe&&mt(),m=ft(e).then(()=>c.init()).then(async t=>{let r=a.country?String(a.country).toUpperCase():null;if(t&&r&&t.buyerIdentity?.countryCode&&t.buyerIdentity.countryCode!==r)try{t=await c.setBuyerIdentity({countryCode:r},{create:!1})}catch(n){d(n,"cart country")}return h("ready",{cart:t}),D}),m):(b("TETHER_CONFIG is missing domain or token. Tether is idle."),m=Promise.resolve(null),m))}async function ft(e){let t=a.markets||{};if(t.detect===!1)return;let r=null;if(t.detect)try{r=(await f("markets")).detectMarket(t)}catch(n){d(n,"markets");return}else if(t.remember!==!1){try{r=JSON.parse(localStorage.getItem(`${a.prefix}:market:${a.domain}`)||"null")}catch{}r&&!/^[A-Z]{2}$/.test(r.country||"")&&(r=null)}r&&(r.country&&(a.country=r.country),r.language&&(a.language=r.language),r.locale&&!e.locale&&(a.locale=r.locale),k("market",r))}function at(e,t){return f("markets").then(r=>r.setCountry(e,t))}function mt(){if(S||typeof MutationObserver>"u")return;let e=null,t=new Set;S=new MutationObserver(r=>{r.forEach(n=>n.addedNodes.forEach(i=>{i.nodeType===1&&t.add(i)})),clearTimeout(e),e=setTimeout(()=>{t.forEach(n=>{n.isConnected&&y(n)}),t.clear()},50)}),S.observe(document.body,{childList:!0,subtree:!0})}var D={VERSION:et,init:ct,mount:y,unmount:ot,get config(){return a},get ready(){return m||Promise.resolve(null)},query:N,withContext:M,cart:c,getProduct:_,getProducts:R,getRecommendations:G,getScope:lt,addGroup:it,primeProduct:A,normalizeProductKey:q,clearProductCache:F,formatMoney:z,imageUrl:B,plans:K,TetherError:I,resolveProductKey:V,setCountry:at,detectMarket:e=>f("markets").then(t=>t.detectMarket(e||a.markets)),getLocalization:()=>f("markets").then(e=>e.getLocalization()),diagnose:e=>f("diagnose").then(t=>t.diagnose({...e,version:et})),__core:void 0,__parts:{},on(e,t){let r=n=>t(n.detail,n);return document.addEventListener(`${a.prefix}:${e}`,r),()=>document.removeEventListener(`${a.prefix}:${e}`,r)}},xt=D;if(typeof window<"u"&&typeof document<"u"&&(window.Tether=D,window.TETHER_CONFIG&&window.TETHER_CONFIG.autoMount!==!1&&!window.TETHER_INTEGRATION)){let t=()=>ct().then(()=>y(document));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}export{et as VERSION,it as addGroup,D as api,xt as default,lt as getScope,ct as init,y as mount,at as setCountry,ot as unmount};
1
+ import{a as W,b as Z,d as x,f as S,g as X,h as g,i as Y,j as ee,k as te,l as ne,m as re}from"./chunks/chunk-CISGFYOF.js";import{a as j}from"./chunks/chunk-6R752OYZ.js";import{a as V}from"./chunks/chunk-4UR45XTC.js";import{a as Q,b as c}from"./chunks/chunk-BGIKQY6H.js";import{a as _,b as R,c as q,d as F,h as G,i as B}from"./chunks/chunk-ZVUPVSLF.js";import{l as K}from"./chunks/chunk-YXCXIPQV.js";import{K as h,b as r,c as O,d as w,e as L,f as M,g as u,h as D,j as N,l as U,n as f,o as a,s as H,u as k,w as z,y as J}from"./chunks/chunk-KARKXC6G.js";import"./chunks/chunk-VC46IEJQ.js";var me={diagnose:()=>import("./chunks/diagnose-6ZSK5DGE.js"),markets:()=>import("./chunks/markets-ui-HJCVLCKJ.js"),search:()=>import("./chunks/search-LN2H6SXS.js"),extras:()=>import("./chunks/extras-QDCSW6VU.js"),account:()=>import("./chunks/account-JBZJN7X7.js"),analytics:()=>import("./chunks/analytics-22NMIVBV.js")},l=t=>me[t](),oe=void 0;var ae="0.6.1",m=null,C=null;function p(t=document){if(!w())return 0;let e=0;return X(),re(t),g(t,W()).forEach(n=>{if(x.has(n))return;x.add(n),e++;let o=new Z(n);S.add(o),n.addEventListener(`${r.prefix}:list-rendered`,i=>p(i.detail.container)),te(o.load())}),g(t,a("product")).forEach(n=>{Y(n)&&e++}),g(t,`${a("country-select")},${a("country-bind")}`).length&&l("markets").then(n=>n.renderCountrySelects(t)).catch(n=>u(n,"markets")),(r.account?.clientId||r.account?.server)&&(g(t,`[${f("account-login")}],[${f("account-bind")}],[${f("orders")}],[${f("show")}^="logged-"]`).length||/[?&]code=/.test(window.location.search)||he())&&l("account").then(n=>n.mountAccount(t)).catch(n=>u(n,"account")),g(t,a("search")).length&&l("search").then(n=>n.mountSearch(t)).catch(n=>u(n,"search")),H(t,a("account-link")).forEach(n=>{n.setAttribute("href",`https://${r.domain}/account`)}),ne(),c.render(),L(`mounted ${e} scope(s)`,t),e}function se(){c.close()}function pe(t){let e=t?.closest?.(a("product"));return e&&j.get(e)||null}var ce=!1;function ge(){ce||(ce=!0,document.addEventListener("click",t=>{let e=t.target;if(!e?.closest)return;if(e.closest(a("cart-open"))){t.preventDefault(),c.toggle();return}if(e.closest(a("cart-close"))){t.preventDefault(),c.close();return}let n=e.closest(a("cart-clear"));if(n){t.preventDefault(),h(n,()=>c.clear().catch(d=>u(d,"cart clear")));return}let o=e.closest(a("checkout"));if(o){t.preventDefault(),h(o,()=>c.checkout());return}let i=e.closest(ie());if(i&&i.closest(a("cart-lines"))){let d=i.getAttribute(`data-${r.prefix}-key`),E=c.lines.find($=>$.id===d),b=$=>{t.preventDefault(),$().catch(fe=>u(fe,"cart line"))};if(e.closest(a("line-remove")))return i.classList.add("is-busy"),b(()=>c.removeLine(d));if(E&&e.closest(a("line-plus")))return b(()=>c.changeQuantity(d,1));if(E&&e.closest(a("line-minus")))return b(()=>c.changeQuantity(d,-1))}let s=e.closest(a("discount-remove"));if(s){t.preventDefault();let d=s.closest(a("discount-code"))?.getAttribute(f("discount-code"));d&&c.removeDiscount(d).catch(E=>u(E,"discount"));return}let y=e.closest(a("group-add"));y&&(t.preventDefault(),h(y,()=>ue(y)))}),document.addEventListener("change",t=>{let e=t.target;if(!e?.closest)return;let n=e.closest(ie()),o=n?.getAttribute(`data-${r.prefix}-key`),i=(s,y)=>{n.classList.add("is-busy"),n.setAttribute("aria-busy","true"),s.catch(d=>u(d,y))};o&&e.matches(`input${a("line","quantity")}`)?i(c.updateLine(o,parseInt(e.value,10)||0),"cart line"):o&&e.matches(`select${a("line-plan")}`)?i(c.updateLine(o,{sellingPlanId:e.value||null}),"cart line plan"):e.matches(`select${a("country-select")}`)?e.value&&I(e.value).catch(s=>u(s,"country")):e.matches(a("cart-note"))&&c.setNote(e.value).catch(s=>u(s,"cart note"))}),document.addEventListener("submit",t=>{let e=t.target.closest?.(a("discount-form"));if(!e)return;t.preventDefault();let n=e.querySelector(a("discount-input"))||e.querySelector("input"),o=n?.value.trim();o&&h(e,async()=>{let i=s=>{e.classList.toggle("is-invalid",s),n&&(s?n.setAttribute("aria-invalid","true"):n.removeAttribute("aria-invalid"))};try{await c.applyDiscount(o),i(!1),k("discount-applied",{code:o},e),n&&(n.value="")}catch(s){i(!0),s?.code==="INVALID_DISCOUNT"?k("discount-invalid",{code:o},e):u(s,"discount")}})},!0),document.addEventListener("input",t=>{let e=t.target.closest?.(a("discount-form"));e&&(e.classList.remove("is-invalid"),t.target.removeAttribute?.("aria-invalid"))}),window.addEventListener("storage",t=>{r.domain&&t.key?.startsWith(`${r.prefix}:`)&&l("extras").then(e=>e.onStorage(t)).catch(()=>{})}),document.addEventListener(`${r.prefix}:variant-changed`,t=>{let e=t.target;(r.variantUrl||e.hasAttribute?.(f("variant-url")))&&l("extras").then(n=>n.writeVariantUrl(e,t.detail)).catch(()=>{})}),r.astro!==!1&&(document.addEventListener("astro:page-load",()=>(m||Promise.resolve()).then(()=>{let t=A();if(!t&&T){try{t=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{t=null}t=t?.country?t:de}T=!!A(),t?.country&&(String(t.country).toUpperCase()!==String(r.country||"").toUpperCase()||String(t.language||"").toUpperCase()!==String(r.language||"").toUpperCase())?I(t.country,{language:t.language??null,locale:t.locale,remember:!1}).then(()=>p(document),()=>p(document)):p(document)})),document.addEventListener("astro:before-swap",()=>se())),window.addEventListener("online",()=>{ee(),S.forEach(t=>{t.root.getAttribute(f("state"))==="error"&&t.load()})}),document.addEventListener("keydown",t=>{if(!c.isOpen())return;if(t.key==="Escape"){c.close();return}if(t.key!=="Tab"||r.cartFocus===!1)return;let e=c.drawers().find(s=>s.classList.contains(r.cartDrawerOpenClass)),n=e?Q(e):[];if(!n.length)return;let o=n[0],i=n[n.length-1];(!e.contains(document.activeElement)||t.shiftKey&&document.activeElement===o||!t.shiftKey&&document.activeElement===i)&&(t.preventDefault(),(t.shiftKey?i:o).focus())}))}function ie(){return`[data-${r.prefix}-key]`}var ue=t=>l("extras").then(e=>e.addGroup(t)),v=null;function le(t={}){return m&&!Object.keys(t).length?m:(O({...window.TETHER_CONFIG||{},...t}),w()?(ge(),r.observe&&Ee(),r.analytics&&!v&&(v=[],["product-ready","list-ready","cart-updated","cart-toggled","checkout","search"].forEach(e=>document.addEventListener(`${r.prefix}:${e}`,n=>v.push(n))),document.addEventListener("astro:page-load",()=>v.push(new CustomEvent(`${r.prefix}:page`))),l("analytics").then(e=>e.startAnalytics(v)).catch(e=>u(e,"analytics"))),m=ye(t).then(()=>c.init()).then(async e=>{let n=r.country?String(r.country).toUpperCase():null;if(e&&n&&e.buyerIdentity?.countryCode&&e.buyerIdentity.countryCode!==n)try{e=await c.setBuyerIdentity({countryCode:n},{create:!1})}catch(o){u(o,"cart country")}return k("ready",{cart:e}),P}),m):(M("TETHER_CONFIG is missing domain or token. Tether is idle."),m=Promise.resolve(null),m))}function A(t=document){let e=o=>t.querySelector(`meta[name="${r.prefix}-page-${o}"]`)?.getAttribute("content")||void 0,n=e("country");return n?{country:n.toUpperCase(),language:e("language"),locale:e("locale")}:null}var de=null,T=!1;async function ye(t){let e=r.markets||{};de={country:r.country,language:r.language,locale:r.locale};let n=A();if(T=!!n,n){r.country=n.country,r.language=n.language?n.language.toUpperCase():void 0,n.locale&&(r.locale=n.locale);return}if(e.detect===!1)return;let o=null;if(e.detect)try{o=(await l("markets")).detectMarket(e)}catch(i){u(i,"markets");return}else if(e.remember!==!1){try{o=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{}o&&!/^[A-Z]{2}$/.test(o.country||"")&&(o=null)}o&&(o.country&&(r.country=o.country),o.language&&(r.language=o.language),o.locale&&!t.locale&&(r.locale=o.locale),L("market",o))}function he(){try{return!!(sessionStorage[`${r.prefix}:account:${r.domain}`]||localStorage[`${r.prefix}:account:${r.domain}`]||localStorage[`${r.prefix}:account-hint:${r.domain}`])}catch{return!1}}var ve=new Proxy({},{get:(t,e)=>(...n)=>l("account").then(o=>o[e](...n))});function I(t,e){return l("markets").then(n=>n.setCountry(t,e))}function Ee(){if(C||typeof MutationObserver>"u")return;let t=null,e=new Set;C=new MutationObserver(n=>{n.forEach(o=>o.addedNodes.forEach(i=>{i.nodeType===1&&e.add(i)})),clearTimeout(t),t=setTimeout(()=>{e.forEach(o=>{o.isConnected&&p(o)}),e.clear()},50)}),C.observe(document.body,{childList:!0,subtree:!0})}var P={VERSION:ae,init:le,mount:p,unmount:se,get config(){return r},get ready(){return m||Promise.resolve(null)},query:U,withContext:N,cart:c,getProduct:q,getProducts:G,getRecommendations:B,getScope:pe,addGroup:ue,account:ve,primeProduct:R,normalizeProductKey:_,clearProductCache:F,formatMoney:z,imageUrl:J,plans:K,TetherError:D,resolveProductKey:V,setCountry:I,detectMarket:t=>l("markets").then(e=>e.detectMarket(t||r.markets)),getLocalization:()=>l("markets").then(t=>t.getLocalization()),diagnose:t=>l("diagnose").then(e=>e.diagnose({...t,version:ae})),__core:oe,__parts:{},on(t,e){let n=o=>e(o.detail,o);return document.addEventListener(`${r.prefix}:${t}`,n),()=>document.removeEventListener(`${r.prefix}:${t}`,n)}},De=P;if(typeof window<"u"&&typeof document<"u"&&(window.Tether=P,window.TETHER_CONFIG&&window.TETHER_CONFIG.autoMount!==!1&&!window.TETHER_INTEGRATION)){let e=()=>le().then(()=>p(document));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{ae as VERSION,ue as addGroup,P as api,De as default,pe as getScope,le as init,p as mount,I as setCountry,se as unmount};
@@ -1 +1 @@
1
- import{J as U,a as O,h as _,j as D,k as q,n as w,p as F,q as E,r as R,s as h,t as T,v as N,x as A,y as B}from"./chunks/chunk-HXKV6QGB.js";import"./chunks/chunk-VC46IEJQ.js";function x(o,{variant:s,sellingPlan:r,defaultPurchase:P="one-time"}={}){let c=o?.variants?.nodes||[],f=s?E.variant(s):null,a=f&&c.find(l=>l.id===f)||c.find(l=>l.availableForSale)||c[0]||null;if(!a)return null;let m=Object.fromEntries((a.selectedOptions||[]).map(l=>[l.name,l.value])),p=R(o),I=A(o,r),u=p.length?I||p[0]:null;u&&!h(a,u.id)&&(u=p.find(l=>h(a,l.id))||u);let b=o.requiresSellingPlan||I||P==="subscription",$=p.some(l=>h(a,l.id)),e=p.length&&b?"subscription":"one-time",t=e==="subscription"&&$,n=t?T(a,u.id):a.price,i=t&&h(a,u.id)?.priceAdjustments?.[0]?.compareAtPrice||a.compareAtPrice,d=!!(i&&parseFloat(i.amount)>parseFloat(n.amount)),S=a.quantityAvailable;return{variant:a,selected:m,purchase:e,plan:t?u:null,plans:p.map(l=>({id:l.id,name:l.name,price:T(a,l.id),savings:N(a,l.id).percentage,selected:t&&l.id===u.id,available:!!h(a,l.id)})),savings:u?N(a,u.id).percentage:0,price:n,compareAtPrice:d?i:null,available:a.availableForSale,show:{"in-stock":a.availableForSale,"out-of-stock":!a.availableForSale,backorder:!!(a.availableForSale&&a.currentlyNotInStock),"on-sale":d,"not-on-sale":!d,"has-variants":c.length>1,"single-variant":c.length===1,"low-stock":S!=null&&S>0&&S<=5,"subscription-available":$,"subscription-unavailable":!$,"subscription-only":!!o.requiresSellingPlan,"one-time-available":!o.requiresSellingPlan,"subscription-selected":t,"one-time-selected":!t},isUnavailable:(l,v)=>!c.some(y=>y.availableForSale&&y.selectedOptions.every(g=>g.name===l?g.value===v:m[g.name]===g.value))}}var C=o=>typeof o=="string"&&o.startsWith("gid://");function K(o){let s=String(o??"").trim();if(!s)return null;if(C(s))return s;if(/^\d+$/.test(s))return`gid://shopify/Product/${s}`;let r=s.match(/\/products\/([^/?#]+)/);return r?r[1]:s}function H(o,s){if(!o)return"";let r=parseFloat(o.amount);if(Number.isNaN(r))return"";try{return new Intl.NumberFormat(s||void 0,{style:"currency",currency:o.currencyCode}).format(r)}catch{return`${o.currencyCode} ${r.toFixed(2)}`}}function L(o,{productPath:s="/product",id:r}={}){return/\{(handle|id)\}/.test(s)?s.replace(/\{handle\}/g,encodeURIComponent(o||"")).replace(/\{id\}/g,encodeURIComponent(r?String(r).split("/").pop():"")):`${s.replace(/\/$/,"")}/${o}`}var Y=o=>JSON.stringify(o).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),j={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};function X(o={}){let s=Object.fromEntries(Object.entries(o).filter(([e])=>e in O||e==="fetch"||e==="pageSize")),r={...O,...s};for(let[e,t]of Object.entries(j))r[e]||(r[e]=t.map(n=>o[n]).find(Boolean)||"");if(r.domain=String(r.domain||"").replace(/^https?:\/\//,"").replace(/\/.*$/,""),!r.domain||!r.token)throw new _("createStorefront needs domain and token: pass them, or import.meta.env with PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN",{code:"NOT_CONFIGURED"});let P=o.pageSize||25,c=(e,t,n)=>q(r,e,t,n),f=()=>w(r);async function a(e){let t=K(e);if(!t)return null;let n=C(t)?await c(`query TetherServerProductById($id:ID!){node(id:$id){... on Product{...TetherProduct}}}${f()}`,{id:t}):await c(`query TetherServerProduct($handle:String!){product(handle:$handle){...TetherProduct}}${f()}`,{handle:t}),i=C(t)?n.node:n.product;return i&&i.id?i:null}async function m({collection:e,query:t,first:n=P,after:i=null,sortKey:d,reverse:S=!1,filters:l}={}){if(e){let y=await c(`query TetherServerCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${F()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}${f()}`,{handle:e,first:n,after:i,sortKey:d||void 0,reverse:S,filters:l||void 0});if(!y.collection)return{collection:null,products:[],pageInfo:{hasNextPage:!1,endCursor:null}};let{products:g,...k}=y.collection;return{collection:k,products:g.nodes,pageInfo:g.pageInfo}}let v=await c(`query TetherServerProducts($first:Int!,$after:String,$query:String,$sortKey:ProductSortKeys,$reverse:Boolean){products(first:$first,after:$after,query:$query,sortKey:$sortKey,reverse:$reverse){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}${f()}`,{first:n,after:i,query:t||void 0,sortKey:d||void 0,reverse:S});return{collection:null,products:v.products.nodes,pageInfo:v.products.pageInfo}}async function p(e={}){let t=[],n=null;for(let i=0;i<500;i++){let d=await m({...e,first:P,after:n});if(t.push(...d.products),!d.pageInfo.hasNextPage)break;n=d.pageInfo.endCursor}return t}async function I(e,t={}){let n=await m({...t,collection:e});return n.collection?{...n.collection,products:n.products,pageInfo:n.pageInfo}:null}async function u(){let e=[],t=null;for(let n=0;n<100;n++){let i=await c(`query TetherServerCollections($first:Int!,$after:String){collections(first:$first,after:$after){nodes{${F()}}pageInfo{hasNextPage endCursor}}}`,{first:100,after:t});if(e.push(...i.collections.nodes),!i.collections.pageInfo.hasNextPage)break;t=i.collections.pageInfo.endCursor}return e}async function b(e,t="RELATED"){let n=K(typeof e=="object"?e?.id:e),i=n?.startsWith("gid://");return(await c(`query TetherServerRecs(${i?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${i?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}${f()}`,i?{id:n,intent:t}:{handle:n,intent:t})).productRecommendations||[]}function $(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean),n={v:1,at:new Date().toISOString(),country:r.country||null,language:r.language||null,products:t};return`<script type="application/json" data-tether-hydrate>${Y(n)}<\/script>`}return{config:r,query:c,getProduct:a,getProducts:m,allProducts:p,getCollection:I,allCollections:u,getRecommendations:b,hydrate:$,formatMoney:(e,t=r.locale)=>H(e,t),imageUrl:U,initialState:(e,t={})=>x(e,{defaultPurchase:r.defaultPurchase,...t}),productUrl:(e,t={})=>L(e,{productPath:r.productPath,...t}),plans:B}}export{_ as TetherError,X as createStorefront,H as formatMoney,U as imageUrl,x as initialState,B as plans,K as productKey,L as productUrl,D as withContext};
1
+ import{a as D,c as R,d as j,e as k,f as $,g as b,i as B,k as H,l as Y}from"./chunks/chunk-YXCXIPQV.js";import{a as q,h as K,j as X,k as L,v as M,y as z}from"./chunks/chunk-KARKXC6G.js";import"./chunks/chunk-VC46IEJQ.js";function G(l,{variant:c,sellingPlan:o,defaultPurchase:F="one-time",lowStock:g=5}={}){let p=l?.variants?.nodes||[],N=c?j.variant(c):null,s=N&&p.find(r=>r.id===N)||p.find(r=>r.availableForSale)||p[0]||null;if(!s)return null;let C=Object.fromEntries((s.selectedOptions||[]).map(r=>[r.name,r.value])),S=k(l),w=H(l,o),d=S.length?w||S[0]:null;d&&!$(s,d.id)&&(d=S.find(r=>$(s,r.id))||d);let U=l.requiresSellingPlan||w||F==="subscription",v=S.some(r=>$(s,r.id)),T=S.length&&U?"subscription":"one-time",m=T==="subscription"&&v,e=m?b(s,d.id):s.price,t=m&&$(s,d.id)?.priceAdjustments?.[0]?.compareAtPrice||s.compareAtPrice,n=!!(t&&parseFloat(t.amount)>parseFloat(e.amount)),i=s.quantityAvailable,f=i!=null&&i>0&&i<=g,O=m?B(s,d.id).percentage:0;return{variant:s,selected:C,purchase:T,plan:m?d:null,plans:S.map(r=>({id:r.id,name:r.name,price:b(s,r.id),savings:B(s,r.id).percentage,selected:m&&r.id===d.id,available:!!$(s,r.id)})),savings:d?B(s,d.id).percentage:0,price:e,compareAtPrice:n?t:null,available:s.availableForSale,show:{"in-stock":s.availableForSale,"out-of-stock":!s.availableForSale,backorder:!!(s.availableForSale&&s.currentlyNotInStock),"on-sale":n,"not-on-sale":!n,"has-variants":p.length>1,"single-variant":p.length===1,"low-stock":f,"plenty-in-stock":s.availableForSale&&!f,"subscription-available":v,"subscription-unavailable":!v,"subscription-only":!!l.requiresSellingPlan,"one-time-available":!l.requiresSellingPlan,"subscription-selected":m,"one-time-selected":!m,"has-savings":m?O>0:n},unavailable:Object.fromEntries((l.options||[]).map(r=>[r.name,r.optionValues.map(u=>u.name).filter(u=>P(r.name,u))])),isUnavailable:(r,u)=>P(r,u)};function P(r,u){return!p.some(y=>y.availableForSale&&y.selectedOptions.every(h=>h.name===r?h.value===u:C[h.name]===h.value))}}var x=l=>typeof l=="string"&&l.startsWith("gid://");function J(l){let c=String(l??"").trim();if(!c)return null;if(x(c))return c;if(/^\d+$/.test(c))return`gid://shopify/Product/${c}`;let o=c.match(/\/products\/([^/?#]+)/);return o?o[1]:c}function Z(l,c){if(!l)return"";let o=parseFloat(l.amount);if(Number.isNaN(o))return"";try{return new Intl.NumberFormat(c||void 0,{style:"currency",currency:l.currencyCode}).format(o)}catch{return`${l.currencyCode} ${o.toFixed(2)}`}}function V(l,{productPath:c="/product",id:o}={}){return/\{(handle|id)\}/.test(c)?c.replace(/\{handle\}/g,encodeURIComponent(l||"")).replace(/\{id\}/g,encodeURIComponent(o?String(o).split("/").pop():"")):`${c.replace(/\/$/,"")}/${l}`}var W=l=>JSON.stringify(l).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),ee={domain:["PUBLIC_SHOPIFY_DOMAIN","PUBLIC_SHOPIFY_STORE_DOMAIN","SHOPIFY_DOMAIN"],token:["PUBLIC_SHOPIFY_STOREFRONT_TOKEN","PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN","SHOPIFY_STOREFRONT_TOKEN"]};function le(l={}){let c=Object.fromEntries(Object.entries(l).filter(([e])=>e in q||e==="fetch"||e==="pageSize"||e==="siteUrl")),o={...q,...c};for(let[e,t]of Object.entries(ee))o[e]||(o[e]=t.map(n=>l[n]).find(Boolean)||"");if(o.domain=String(o.domain||"").replace(/^https?:\/\//,"").replace(/\/.*$/,""),!o.domain||!o.token)throw new K("createStorefront needs domain and token: pass them, or import.meta.env with PUBLIC_SHOPIFY_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN",{code:"NOT_CONFIGURED"});let F=l.pageSize||25,g=(e,t,n)=>L(o,e,t,n),p=()=>D(o);async function N(e){let t=J(e);if(!t)return null;let n=x(t)?await g(`query TetherServerProductById($id:ID!){node(id:$id){... on Product{...TetherProduct}}}${p()}`,{id:t}):await g(`query TetherServerProduct($handle:String!){product(handle:$handle){...TetherProduct}}${p()}`,{handle:t}),i=x(t)?n.node:n.product;return i&&i.id?i:null}async function s({collection:e,query:t,first:n=F,after:i=null,sortKey:f,reverse:O=!1,filters:P}={}){if(e){let u=await g(`query TetherServerCollection($handle:String!,$first:Int!,$after:String,$sortKey:ProductCollectionSortKeys,$reverse:Boolean,$filters:[ProductFilter!]){collection(handle:$handle){${R()} products(first:$first,after:$after,sortKey:$sortKey,reverse:$reverse,filters:$filters){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}}${p()}`,{handle:e,first:n,after:i,sortKey:f||void 0,reverse:O,filters:P||void 0});if(!u.collection)return{collection:null,products:[],pageInfo:{hasNextPage:!1,endCursor:null}};let{products:y,...h}=u.collection;return{collection:h,products:y.nodes,pageInfo:y.pageInfo}}let r=await g(`query TetherServerProducts($first:Int!,$after:String,$query:String,$sortKey:ProductSortKeys,$reverse:Boolean){products(first:$first,after:$after,query:$query,sortKey:$sortKey,reverse:$reverse){nodes{...TetherProduct}pageInfo{hasNextPage endCursor}}}${p()}`,{first:n,after:i,query:t||void 0,sortKey:f||void 0,reverse:O});return{collection:null,products:r.products.nodes,pageInfo:r.products.pageInfo}}async function C(e={}){let t=[],n=null;for(let i=0;i<500;i++){let f=await s({...e,first:F,after:n});if(t.push(...f.products),!f.pageInfo.hasNextPage)break;n=f.pageInfo.endCursor}return t}async function S(e,t={}){let n=await s({...t,collection:e});return n.collection?{...n.collection,products:n.products,pageInfo:n.pageInfo}:null}async function w(){let e=[],t=null;for(let n=0;n<100;n++){let i=await g(`query TetherServerCollections($first:Int!,$after:String){collections(first:$first,after:$after){nodes{${R()}}pageInfo{hasNextPage endCursor}}}`,{first:100,after:t});if(e.push(...i.collections.nodes),!i.collections.pageInfo.hasNextPage)break;t=i.collections.pageInfo.endCursor}return e}async function d(e,t="RELATED"){let n=J(typeof e=="object"?e?.id:e),i=n?.startsWith("gid://");return(await g(`query TetherServerRecs(${i?"$id: ID!":"$handle: String!"},$intent:ProductRecommendationIntent){productRecommendations(${i?"productId: $id":"productHandle: $handle"},intent:$intent){...TetherProduct}}${p()}`,i?{id:n,intent:t}:{handle:n,intent:t})).productRecommendations||[]}function U(e,{card:t=!1}={}){let n=(Array.isArray(e)?e:[e]).filter(Boolean);t&&(n=n.map(m));let i={v:1,at:new Date().toISOString(),country:o.country||null,language:o.language||null,products:n};return`<script type="application/json" data-tether-hydrate>${W(i)}<\/script>`}function v(e,{url:t,brand:n}={}){if(!e)return null;let i=t||(o.siteUrl?new URL(V(e.handle,{productPath:o.productPath,id:e.id}),o.siteUrl).toString():void 0),f=a=>String(a.id).split("/").pop(),O=a=>i?`${i}${i.includes("?")?"&":"?"}variant=${f(a)}`:void 0,P=(e.description||"").trim()||void 0,r=(e.images?.nodes||[]).map(a=>a.url).filter(Boolean),u=n||e.vendor,y=a=>{if(!e.requiresSellingPlan)return a.price;let I=k(e).find(Q=>$(a,Q.id));return I?b(a,I.id):a.price},h=a=>({"@type":"Offer",price:y(a)?.amount,priceCurrency:y(a)?.currencyCode,availability:`https://schema.org/${a.availableForSale?a.currentlyNotInStock?"BackOrder":"InStock":"OutOfStock"}`,url:O(a)}),_=e.variants?.nodes||[],A=a=>JSON.parse(JSON.stringify(a));if(_.length<=1){let a=_[0];return A({"@context":"https://schema.org","@type":"Product",name:e.title,description:P,url:i,image:r,sku:a?.sku||void 0,brand:u?{"@type":"Brand",name:u}:void 0,offers:a?h(a):void 0})}let E={size:"https://schema.org/size",color:"https://schema.org/color",colour:"https://schema.org/color",material:"https://schema.org/material"};return A({"@context":"https://schema.org","@type":"ProductGroup",name:e.title,description:P,url:i,productGroupID:String(e.id).split("/").pop(),image:r,brand:u?{"@type":"Brand",name:u}:void 0,variesBy:[...new Set((e.options||[]).map(a=>E[a.name.toLowerCase()]).filter(Boolean))],hasVariant:_.map(a=>({"@type":"Product",name:`${e.title} - ${a.title}`,sku:a.sku||void 0,image:a.image?.url||r[0],...Object.fromEntries((a.selectedOptions||[]).filter(I=>E[I.name.toLowerCase()]).map(I=>[E[I.name.toLowerCase()].split("/").pop(),I.value])),offers:h(a)}))})}let T=(e,t)=>e?`<script type="application/ld+json">${W(v(e,t))}<\/script>`:"";function m(e){return{...e,description:"",descriptionHtml:"",images:{nodes:(e.images?.nodes||[]).slice(0,1)},variants:{nodes:(e.variants?.nodes||[]).map(t=>({...t,image:null}))}}}return{config:o,query:g,getProduct:N,getProducts:s,allProducts:C,getCollection:S,allCollections:w,getRecommendations:d,hydrate:U,formatMoney:(e,t=o.locale)=>Z(e,t),formatPercent:(e,t=o.locale)=>M(e,t),imageUrl:z,jsonLd:T,jsonLdData:v,initialState:(e,t={})=>G(e,{defaultPurchase:o.defaultPurchase,lowStock:o.lowStock,...t}),productUrl:(e,t={})=>V(e,{productPath:o.productPath,...t}),plans:Y}}export{K as TetherError,le as createStorefront,Z as formatMoney,M as formatPercent,z as imageUrl,G as initialState,Y as plans,J as productKey,V as productUrl,X as withContext};