@occluze/tether 0.6.6 → 0.6.7

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.
package/README.md CHANGED
@@ -33,7 +33,7 @@ MIT licensed · 20 KB gzipped · no dependencies · TypeScript types · [full re
33
33
  | **npm** | Astro, Vite or another bundler or framework | `npm install @occluze/tether` ([Astro guide](docs/astro.md), [other frameworks](docs/frameworks.md)) |
34
34
  | **With the Worker** | you also want the CMS sync, rebuilds when products change, or secure customer accounts | either of the above, plus your own free Cloudflare Worker ([Worker](server/README.md), [accounts](docs/accounts.md)) |
35
35
 
36
- The script tag pinned to one release: `…/tether@v0.6.6/dist/tether.min.js`. Its optional parts
36
+ The script tag pinned to one release: `…/tether@v0.6.7/dist/tether.min.js`. Its optional parts
37
37
  (search, accounts, markets, analytics) load from the same folder when a page uses them; host the
38
38
  files yourself and set `partsUrl` if they live somewhere else. Customer accounts without the Worker
39
39
  run in browser mode; [server mode](docs/accounts.md#server-mode) (recommended for live shops)
@@ -64,7 +64,7 @@ Site settings → Custom code → **Head**:
64
64
  <script src="https://cdn.jsdelivr.net/gh/ravi-klaassens/tether@0.6/dist/tether.min.js" defer></script>
65
65
  ```
66
66
 
67
- **Versions:** `@0.6` gets every 0.6.x fix automatically (recommended), `@v0.6.6` pins one release,
67
+ **Versions:** `@0.6` gets every 0.6.x fix automatically (recommended), `@v0.6.7` pins one release,
68
68
  `@latest` always takes the newest. Hosting the file yourself? Put the optional parts next to it (`tether.markets.min.js`,
69
69
  `tether.search.min.js`, `tether.account.min.js`, `tether.account-pages.min.js`, `tether.analytics.min.js`, `tether.extras.min.js`,
70
70
  `tether.diagnose.min.js`): each loads only when a page uses it.
@@ -0,0 +1 @@
1
+ import{a as X}from"./chunk-PAYT5ZD7.js";import{b as f}from"./chunk-4QJKLPYR.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{A as L,B as $,D as x,G as R,b as r,e as V,g as A,h as w,o as d,p as S,s as g,u as T,w as W}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var N=()=>`${r.prefix}:account:${r.domain}`,G=()=>`${r.prefix}:account-login:${r.domain}`,O=()=>r.account?.remember?window.localStorage:window.sessionStorage,Z=t=>btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),q=()=>Z(crypto.getRandomValues(new Uint8Array(32))),it=async t=>Z(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),E=t=>(r.account?.navigate||(e=>window.location.assign(e)))(t),K=(t,e)=>{try{return JSON.parse(t.getItem(e)||"null")}catch{return null}},D=(t,e,n)=>{try{n?t.setItem(e,JSON.stringify(n)):t.removeItem(e)}catch{}},v=null,i=null,j=null,I=null,m=()=>r.account?.server?new URL(String(r.account.server),window.location.href).href.replace(/\/$/,""):"",J=()=>`${r.prefix}:account-hint:${r.domain}`,b=null;async function U(t,{method:e="GET",body:n}={}){let o=await fetch(`${m()}${t}`,{method:e,credentials:"include",headers:e==="POST"?{"Content-Type":"application/json","X-Tether-Account":"1"}:{},body:n?JSON.stringify(n):void 0}),s=await o.json().catch(()=>({}));if(!o.ok&&o.status!==401)throw new w(`Customer accounts: ${s.error||o.status}`,{status:o.status,userErrors:s.userErrors});return s}async function M(){b||(b=await U("/me"));try{b.loggedIn?window.localStorage.setItem(J(),"1"):window.localStorage.removeItem(J())}catch{}return b}async function P(){if(v)return v;let t=r.account?.shopDomain||r.domain,e=s=>fetch(`https://${t}/.well-known/${s}`).then(a=>{if(!a.ok)throw new w(`Customer accounts: ${s} answered ${a.status}`,{status:a.status});return a.json()}),[n,o]=await Promise.all([e("openid-configuration"),e("customer-account-api")]);return v={...n,graphql:o.graphql_api},v}var ut=()=>r.account?.callbackUrl||`${window.location.origin}${window.location.pathname}`;function tt(){return m()?!!b?.loggedIn:!!(i?.refresh||i?.access&&i.expiresAt>Date.now())}async function lt({returnTo:t=window.location.href,locale:e}={}){if(m()){let h=new URL(`${m()}/login`);h.searchParams.set("returnTo",t);let _=e||r.account.locale||(r.locale||"").split("-")[0];_&&h.searchParams.set("locale",_),r.country&&h.searchParams.set("country",String(r.country).toUpperCase()),E(h.toString());return}if(!r.account?.clientId)throw new w("Customer accounts: set account.clientId",{code:"NOT_CONFIGURED"});let n=await P(),o=q(),s=q(),a=q(),u=ut();D(window.sessionStorage,G(),{state:o,nonce:s,verifier:a,redirect:u,returnTo:t,at:Date.now()});let c=new URL(n.authorization_endpoint),l={client_id:r.account.clientId,scope:"openid email customer-account-api:full",response_type:"code",redirect_uri:u,state:o,nonce:s,code_challenge:await it(a),code_challenge_method:"S256"},p=e||r.account.locale||(r.locale||"").split("-")[0];p&&(l.locale=p),r.country&&(l.region_country=String(r.country).toUpperCase()),Object.entries(l).forEach(([h,_])=>c.searchParams.set(h,_)),E(c.toString())}async function et(t){let e=await P(),n=await fetch(r.account.tokenUrl||e.token_endpoint,{method:"POST",body:new URLSearchParams(t)}),o=await n.json().catch(()=>({}));if(!n.ok||!o.access_token)throw new w(`Customer accounts: token ${n.status} ${o.error||""}`.trim(),{status:n.status,code:n.status===400||n.status===401?"SESSION_ENDED":"TOKEN_FAILED"});return o}function dt(t){try{return JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function nt(t,e=i){i={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},D(O(),N(),i)}async function ft(){let t=new URLSearchParams(window.location.search),e=K(window.sessionStorage,G());if(!e||!t.has("code")&&!t.has("error")||t.get("state")!==e.state)return!1;D(window.sessionStorage,G(),null);let n=new URL(window.location.href);if(["code","state","iss","error","error_description"].forEach(l=>n.searchParams.delete(l)),window.history.replaceState(window.history.state,"",n),t.has("error"))return T("account-error",{error:t.get("error")}),!1;if(Date.now()-e.at>10*6e4)throw new w("Customer accounts: the login took too long, please try again");let o=await et({grant_type:"authorization_code",client_id:r.account.clientId,redirect_uri:e.redirect,code:t.get("code"),code_verifier:e.verifier}),s=await P(),a=dt(o.id_token||""),u=[].concat(a?.aud||[]);if(!a||a.nonce!==e.nonce||a.iss!==s.issuer||!u.includes(r.account.clientId)||a.exp*1e3<Date.now())throw new w("Customer accounts: the login answer did not check out (nonce/issuer/audience)");nt(o,null),await ot(),T("account-login",{});let c=e.returnTo&&new URL(e.returnTo,window.location.href);return c&&c.origin===window.location.origin&&c.href!==n.href&&E(c.href),!0}async function C(){return m()||(i||(i=K(O(),N())),!i)?null:i.access&&i.expiresAt>Date.now()?i.access:i.refresh?(j||(j=(async()=>{try{nt(await et({grant_type:"refresh_token",client_id:r.account.clientId,refresh_token:i.refresh})),await ot()}catch(t){if(t.code==="SESSION_ENDED")z();else throw t}finally{j=null}})()),await j,i?.access||null):(z(),null)}function z(){i=null,I=null,D(O(),N(),null),f.customerAccessToken=null}async function ot(){f.customerAccessToken=i?.access||null,f.id()&&i?.access&&await f.setBuyerIdentity({customerAccessToken:i.access},{create:!1}).catch(t=>A(t,"account cart"))}async function H(t,e={}){if(m())throw new w("Customer accounts in server mode only answer customer() and orders()",{code:"NOT_ALLOWED"});let n=await C();if(!n)throw new w("Not logged in",{code:"NOT_LOGGED_IN"});let o=await P(),s=c=>fetch(o.graphql,{method:"POST",headers:{"Content-Type":"application/json",Authorization:c},body:JSON.stringify({query:t,variables:e})}),a=await s(n);a.status===401&&i?.refresh&&(i.expiresAt=0,a=await s(await C()));let u=await a.json().catch(()=>({}));if(!a.ok||u.errors?.length)throw new w(u.errors?.map(c=>c.message).join(" | ")||`Customer accounts: ${a.status}`,{status:a.status});return u.data}async function rt(){if(m()){let e=await M();return e.loggedIn?{...e.customer,emailAddress:{emailAddress:e.customer.email},defaultAddress:{formatted:e.customer.address}}:null}return I||(I=(await H("query TetherCustomer{customer{id firstName lastName displayName emailAddress{emailAddress}defaultAddress{formatted}}}")).customer,I)}async function mt({first:t=10}={}){return m()?(await U(`/orders?first=${t}`)).orders||[]:(await H("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 ht({returnTo:t=r.account?.logoutUrl||`${window.location.origin}/`}={}){if(m()){let s=await U("/logout",{method:"POST",body:{returnTo:t,cartId:f.id()}});b={loggedIn:!1};try{window.localStorage.removeItem(J())}catch{}T("account-logout",{}),s.logoutUrl?E(s.logoutUrl):F(document);return}let e=i?.idToken||K(O(),N())?.idToken;if(f.id()&&await f.setBuyerIdentity({customerAccessToken:null},{create:!1}).catch(()=>{}),z(),T("account-logout",{}),!e){F(document);return}let n=await P(),o=new URL(n.end_session_endpoint);o.searchParams.set("id_token_hint",e),o.searchParams.set("post_logout_redirect_uri",t),E(o.toString())}var wt=t=>{try{return new URL(t).protocol==="https:"}catch{return!1}},gt=t=>{try{return new Date(t).toLocaleDateString(r.locale||void 0)}catch{return t}};async function F(t=document){let e=m()?!!(await M().catch(()=>({loggedIn:!1}))).loggedIn:tt()||!!await C().catch(()=>null);g(t,d("show")).forEach(n=>{let o=S(n,"show");o==="logged-in"&&x(n,e),o==="logged-out"&&x(n,!e)}),g(t,d("account-link")).forEach(n=>{let o=S(n,"account-link"),s=o==="payment"&&(r.account?.paymentUrl||r.account?.subscriptionsUrl)||o==="subscriptions"&&r.account?.subscriptionsUrl;n.setAttribute("href",s||`https://${r.domain}/account`)}),e&&(await st(t),await Promise.all([pt(t),kt.some(n=>g(t,d(n)).length)?at().then(n=>n.renderPages(t)):null]))}async function pt(t){let e=g(t,d("orders"));if(e.length){let n=(a,u)=>g(t,d("show")).forEach(c=>{let l=S(c,"show");l==="orders-loading"&&x(c,a),l==="orders-empty"&&x(c,u)});n(!0,!1);let o=!1,s=await mt({first:parseInt(S(e[0],"limit")||"10",10)}).catch(a=>(A(a,"orders"),o=!0,[]));n(!1,!o&&s.length===0),e.forEach(a=>R(a,s,(u,c)=>{let l=c.lineItems?.nodes||[];g(u,d("order-bind")).forEach(p=>{let h=S(p,"order-bind");if(h==="url"){let y=B(c);y&&p.setAttribute("href",y);return}if(h==="image"){let y=l.find(ct=>ct.image)?.image;y&&L(p,y.url,y.altText||l[0]?.title||"");return}let _={name:c.name,date:gt(c.processedAt),total:W(c.totalPrice),status:c.financialStatus?.toLowerCase(),fulfillment:c.fulfillmentStatus?.toLowerCase(),items:l.map(y=>`${y.quantity}\xD7 ${y.title}`).join(", ")}[h];_!=null&&$(p,_)}),g(u,d("order-lines")).forEach(p=>St(p,l)),S(u,"order-bind")==="url"&&B(c)&&u.setAttribute("href",B(c))}))}}var yt=t=>String(t||"").split("/").pop().split("?")[0];function B(t){let e=r.account?.orderUrl;return e?String(e).replace("{id}",encodeURIComponent(yt(t.id))):wt(t.statusPageUrl)?t.statusPageUrl:null}function St(t,e){R(t,e,(n,o)=>{g(n,d("order-line")).concat(n.matches(d("order-line"))?[n]:[]).forEach(s=>{let a=S(s,"order-line");if(a==="image"){o.image&&L(s,o.image.url,o.image.altText||o.title);return}let u={title:o.title,"variant-title":o.variantTitle||"",quantity:String(o.quantity)}[a];u!=null&&$(s,u)})})}var kt=["order","addresses","subscriptions","profile-form","address-form"],Y=null;async function st(t){let e=g(t,d("account-bind"));if(!e.length)return;let n=await rt().catch(o=>(A(o,"account"),null));e.forEach(o=>{let s={"first-name":n?.firstName,"last-name":n?.lastName,name:n?.displayName,email:n?.emailAddress?.emailAddress,address:n?.defaultAddress?.formatted?.join(", ")}[S(o,"account-bind")];s!=null&&$(o,s)})}function at(){return Y||(Y=X("account-pages").then(t=>(t.setup({server:m,serverFetch:U,query:H,customer:rt,bindCustomer:st,reset:()=>{I=null,b=null}}),t))),Y}var k=t=>(...e)=>at().then(n=>n[t](...e)),Et=k("order"),Ut=k("updateProfile"),Pt=k("addresses"),$t=k("saveAddress"),vt=k("deleteAddress"),Ct=k("subscriptions"),Nt=k("subscriptionAction"),Ot=k("requestReturn"),Q=!1;async function Dt(t=document){if(!Q){if(Q=!0,document.addEventListener("click",e=>{let n=e.target;n.closest?.(d("account-login"))?(e.preventDefault(),lt().catch(o=>A(o,"login"))):n.closest?.(d("account-logout"))&&(e.preventDefault(),ht().catch(o=>A(o,"logout")))}),m()){let e=new URL(window.location.href);e.searchParams.get("account")&&(e.searchParams.delete("account"),window.history.replaceState(window.history.state,"",e),T("account-login",{})),f.beforeCheckout=async()=>{if(!(await M()).loggedIn||!f.id())return null;let n=await U("/cart",{method:"POST",body:{cartId:f.id()}}).catch(()=>null);return n?.checkoutUrl?`${n.checkoutUrl}${n.checkoutUrl.includes("?")?"&":"?"}logged_in=true`:null}}else{try{await ft()}catch(e){A(e,"login")}!f.customerAccessToken&&await C().catch(()=>null)&&(f.customerAccessToken=i.access)}V("account",tt()?"logged in":"logged out")}await F(t)}export{Pt as addresses,rt as customer,vt as deleteAddress,C as getToken,ft as handleCallback,tt as isLoggedIn,lt as login,ht as logout,Dt as mountAccount,Et as order,mt as orders,H as query,F as render,Ot as requestReturn,$t as saveAddress,Nt as subscriptionAction,Ct as subscriptions,Ut as updateProfile};
@@ -0,0 +1 @@
1
+ import{A as V,B as C,D as z,G as T,b as W,g as q,h as F,n as I,o as d,p as y,s as c,u as X,w as b}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var E="amount currencyCode",O="id firstName lastName company address1 address2 city province zoneCode zip country countryCode phoneNumber formatted",B={order:`query TetherOrder($id:ID!){order(id:$id){id name number processedAt cancelledAt financialStatus fulfillmentStatus statusPageUrl requiresShipping totalPrice{${E}}subtotal{${E}}totalShipping{${E}}totalTax{${E}}shippingAddress{${O}}billingAddress{${O}}lineItems(first:50){nodes{id name title variantTitle quantity sku image{url altText}price{${E}}totalPrice{${E}}suggestedReturnReasonDefinitions(first:10){nodes{id name handle}}}}fulfillments(first:10){nodes{id status createdAt estimatedDeliveryAt latestShipmentStatus trackingInformation{company number url}}}returnInformation{returnableLineItems(first:50){nodes{quantity lineItem{id}}}}returns(first:10){nodes{id status}}}}`,addresses:`query TetherAddresses{customer{defaultAddress{id}addresses(first:20){nodes{${O}}}}}`,subscriptions:`query TetherSubscriptions{customer{subscriptionContracts(first:20,reverse:true){nodes{id status nextBillingDate currencyCode deliveryPrice{${E}}deliveryPolicy{interval intervalCount{count}}lines(first:20){nodes{id name title variantTitle quantity sku currentPrice{${E}}lineDiscountedPrice{${E}}image{url altText}}}upcomingBillingCycles(first:3){nodes{cycleIndex skipped billingAttemptExpectedDate}}}}}}`,contract:"query TetherContract($id:ID!){customer{subscriptionContract(id:$id){id status upcomingBillingCycles(first:3){nodes{cycleIndex skipped}}}}}"},D={profile:"mutation TetherProfile($input: CustomerUpdateInput!) { customerUpdate(input: $input) { customer { firstName lastName } userErrors { field message } } }",addressCreate:`mutation TetherAddressCreate($address:CustomerAddressInput!,$default:Boolean){customerAddressCreate(address:$address,defaultAddress:$default){customerAddress{${O}}userErrors{field message}}}`,addressUpdate:`mutation TetherAddressUpdate($id:ID!,$address:CustomerAddressInput,$default:Boolean){customerAddressUpdate(addressId:$id,address:$address,defaultAddress:$default){customerAddress{${O}}userErrors{field message}}}`,addressDelete:"mutation TetherAddressDelete($id: ID!) { customerAddressDelete(addressId: $id) { deletedAddressId userErrors { field message } } }",pause:"mutation TetherPause($id: ID!) { subscriptionContractPause(subscriptionContractId: $id) { contract { id status } userErrors { field message } } }",resume:"mutation TetherResume($id: ID!) { subscriptionContractActivate(subscriptionContractId: $id) { contract { id status } userErrors { field message } } }",cancel:"mutation TetherCancel($id: ID!) { subscriptionContractCancel(subscriptionContractId: $id) { contract { id status } userErrors { field message } } }",skip:"mutation TetherSkip($input: SubscriptionBillingCycleInput!) { subscriptionBillingCycleSkip(billingCycleInput: $input) { billingCycle { cycleIndex skipped } userErrors { field message } } }",unskip:"mutation TetherUnskip($input: SubscriptionBillingCycleInput!) { subscriptionBillingCycleUnskip(billingCycleInput: $input) { billingCycle { cycleIndex skipped } userErrors { field message } } }",returnRequest:"mutation TetherReturn($orderId: ID!, $lines: [RequestedLineItemInput!]!) { orderRequestReturn(orderId: $orderId, requestedLineItems: $lines) { return { id status } userErrors { field message } } }"},f=class extends Error{},R=e=>new RegExp(`^gid://shopify/${e}/\\d+(\\?[\\w=&.-]{1,80})?$`),re={Order:R("Order"),CustomerAddress:R("CustomerAddress"),SubscriptionContract:R("SubscriptionContract"),LineItem:R("LineItem"),ReturnReasonDefinition:R("ReturnReasonDefinition")};function $(e,t){let s=/^\d{1,20}$/.test(String(t??""))?`gid://shopify/${e}/${t}`:String(t??"");if(!re[e].test(s))throw new f(`${e} id`);return s}var j=(e,t=255)=>{if(e==null||e==="")return;if(typeof e!="string"&&typeof e!="number")throw new f("text");let s=String(e).replace(/[\u0000-\u001f\u007f]/g,"").trim();if(s.length>t)throw new f("too long");return s},ne=["firstName","lastName","company","address1","address2","city","zip","zoneCode","phoneNumber"];function ie(e={},{clear:t=!1}={}){if(!e||typeof e!="object"||Array.isArray(e))throw new f("address");let s={};if(ne.forEach(i=>{let r=j(e[i]);r!==void 0?s[i]=r:t&&i in e&&(e[i]===""||e[i]===null)&&(s[i]="")}),e.countryCode!=null&&e.countryCode!==""){let i=String(e.countryCode).toUpperCase();if(!/^[A-Z]{2}$/.test(i))throw new f("countryCode");s.countryCode=i}return s}var v=e=>{let t=e?.userErrors||[];if(t.length){let s=new f(t.map(i=>i.message).join(" | "));throw s.userErrors=t,s}return e},Y={async order(e,{id:t}){return{order:(await e(B.order,{id:$("Order",t)}))?.order||null}},async profile(e,{firstName:t,lastName:s}){let i={};if(t!==void 0&&(i.firstName=j(t,100)??""),s!==void 0&&(i.lastName=j(s,100)??""),!Object.keys(i).length)throw new f("nothing to change");return{customer:v((await e(D.profile,{input:i}))?.customerUpdate).customer}},async addresses(e){let t=(await e(B.addresses,{}))?.customer,s=t?.defaultAddress?.id||null;return{addresses:(t?.addresses?.nodes||[]).map(i=>({...i,isDefault:i.id===s}))}},async saveAddress(e,{id:t,address:s,isDefault:i}){let r=ie(s||{},{clear:!!t}),n=i===!0?!0:void 0;return{address:v(t?(await e(D.addressUpdate,{id:$("CustomerAddress",t),address:Object.keys(r).length?r:null,default:n??null}))?.customerAddressUpdate:(await e(D.addressCreate,{address:r,default:n??!1}))?.customerAddressCreate).customerAddress}},async deleteAddress(e,{id:t}){return{deleted:v((await e(D.addressDelete,{id:$("CustomerAddress",t)}))?.customerAddressDelete).deletedAddressId}},async subscriptions(e){return{subscriptions:(await e(B.subscriptions,{}))?.customer?.subscriptionContracts?.nodes||[]}},async subscription(e,{id:t,action:s}){if(!["pause","resume","skip","unskip","cancel"].includes(s))throw new f("action");let i=$("SubscriptionContract",t),r=(await e(B.contract,{id:i}))?.customer?.subscriptionContract;if(!r){let a=new f("not found");throw a.status=404,a}if(s==="skip"||s==="unskip"){let a=r.upcomingBillingCycles?.nodes||[],u=s==="skip"?a.find(m=>!m.skipped):a.find(m=>m.skipped);if(!u)throw new f(s==="skip"?"no upcoming delivery to skip":"nothing skipped");return{billingCycle:v((await e(D[s],{input:{contractId:i,selector:{index:u.cycleIndex}}}))?.[s==="skip"?"subscriptionBillingCycleSkip":"subscriptionBillingCycleUnskip"]).billingCycle}}let n={pause:"subscriptionContractPause",resume:"subscriptionContractActivate",cancel:"subscriptionContractCancel"}[s];return{contract:v((await e(D[s],{id:i}))?.[n]).contract}},async requestReturn(e,{orderId:t,lines:s}){let i=$("Order",t);if(!Array.isArray(s)||!s.length||s.length>50)throw new f("lines");let r=s.map(o=>{let a=Number(o?.quantity);if(!Number.isInteger(a)||a<1||a>1e3)throw new f("quantity");let u={lineItemId:$("LineItem",o.lineItemId),quantity:a};o.reasonId&&(u.returnReasonDefinitionId=$("ReturnReasonDefinition",o.reasonId));let l=j(o.note,300);return l&&(u.customerNote=l),u});return{return:v((await e(D.returnRequest,{orderId:i,lines:r}))?.orderRequestReturn).return}}};var L=null,Z=!1;function De(e){L=e}var H=e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},U=e=>{try{return new Date(e).toLocaleDateString(W.locale||void 0)}catch{return e}},ae={order:e=>["GET",`/order?id=${encodeURIComponent(e.id)}`],addresses:()=>["GET","/addresses"],subscriptions:()=>["GET","/subscriptions"],profile:()=>["POST","/profile"],saveAddress:()=>["POST","/address"],deleteAddress:()=>["POST","/address/delete"],subscription:()=>["POST","/subscription"],requestReturn:()=>["POST","/return"]};async function S(e,t={}){let{server:s,serverFetch:i,query:r}=L;if(s()){let[n,o]=ae[e](t),a=await i(o,n==="POST"?{method:n,body:t}:{});if(a.loggedIn===!1)throw new F("Not logged in",{code:"NOT_LOGGED_IN",status:401});return a}try{return await Y[e]((n,o)=>r(n,o),t)}catch(n){throw n instanceof f?new F(n.message,{code:"INVALID",userErrors:n.userErrors}):n}}var N=e=>{L.reset(),X("account-updated",{what:e})},oe=e=>S("order",{id:e}).then(t=>t.order),de=({firstName:e,lastName:t}={})=>S("profile",{firstName:e,lastName:t}).then(s=>(N("profile"),s.customer)),ue=()=>S("addresses").then(e=>e.addresses),J=(e,{id:t,isDefault:s}={})=>S("saveAddress",{id:t,address:e,isDefault:s}).then(i=>(N("addresses"),i.address)),ce=e=>S("deleteAddress",{id:e}).then(t=>(N("addresses"),t.deleted)),le=()=>S("subscriptions").then(e=>e.subscriptions),pe=(e,t)=>S("subscription",{id:e,action:t}).then(s=>(N("subscriptions"),s)),fe=(e,t)=>S("requestReturn",{orderId:e,lines:t}).then(s=>(N("orders"),s.return));var P=e=>e?String(e).toLowerCase().replace(/_/g," "):"",_=e=>(e?.formatted||[]).join(", "),w=(e,t,s)=>c(e,d(t)).forEach(i=>{let r=y(i,t);r in s&&z(i,!!s[r])}),k=(e,t)=>w(e,"show",t);function me(e,t,s=null){T(e,t,(i,r)=>{let n=s&&s.get(r.id)||0;i.dataset.tetherLine=r.id,c(i,d("order-line")).concat(i.matches(d("order-line"))?[i]:[]).forEach(o=>{let a=y(o,"order-line");if(a==="image"){r.image&&V(o,r.image.url,r.image.altText||r.title);return}let u={title:r.title||r.name,"variant-title":r.variantTitle||"",quantity:String(r.quantity),price:r.price?b(r.price):"",total:r.totalPrice?b(r.totalPrice):"",sku:r.sku||"",returnable:String(n)}[a];u!=null&&C(o,u)}),w(i,"order-line-show",{returnable:n>0}),c(i,d("return-quantity")).forEach(o=>{o.max=String(n),o.min="0",o.value||(o.value="0"),o.disabled=n<1}),c(i,`select${d("return-reason")}`).forEach(o=>{let a=r.suggestedReturnReasonDefinitions?.nodes||[];o.dataset.tetherFilled!==r.id&&(o.dataset.tetherFilled=r.id,a.forEach(u=>o.appendChild(new Option(u.name,u.id))))})})}var he={order:d("order")};async function ee(e){let t=y(e,"order")||"",s=t.startsWith("url:")?new URL(window.location.href).searchParams.get(t.slice(4)||"id"):t,i=a=>e.setAttribute(I("order-state"),a);if(!s){i("not-found"),w(e,"order-show",{"not-found":!0});return}i("loading"),w(e,"order-show",{loading:!0,ready:!1,"not-found":!1,error:!1});let r;try{r=await oe(s)}catch(a){q(a,"order"),i("error"),w(e,"order-show",{loading:!1,error:!0});return}if(!r){i("not-found"),w(e,"order-show",{loading:!1,"not-found":!0});return}e.dataset.tetherOrderId=r.id;let n=new Map((r.returnInformation?.returnableLineItems?.nodes||[]).map(a=>[a.lineItem?.id,a.quantity])),o=r.fulfillments?.nodes||[];c(e,d("order-bind")).forEach(a=>{let u=y(a,"order-bind");if(u==="url"){H(r.statusPageUrl)&&a.setAttribute("href",r.statusPageUrl);return}let l={name:r.name,date:U(r.processedAt),total:b(r.totalPrice),subtotal:r.subtotal?b(r.subtotal):"",shipping:r.totalShipping?b(r.totalShipping):"",tax:r.totalTax?b(r.totalTax):"",status:P(r.financialStatus),fulfillment:P(r.fulfillmentStatus),"shipping-address":_(r.shippingAddress),"billing-address":_(r.billingAddress),items:(r.lineItems?.nodes||[]).map(m=>`${m.quantity}\xD7 ${m.title||m.name}`).join(", "),cancelled:r.cancelledAt?U(r.cancelledAt):""}[u];l!=null&&C(a,l)}),c(e,d("order-lines")).forEach(a=>me(a,r.lineItems?.nodes||[],n)),c(e,d("order-fulfillments")).forEach(a=>T(a,o,(u,l)=>{let m=l.trackingInformation?.[0]||{};c(u,d("fulfillment-bind")).concat(u.matches(d("fulfillment-bind"))?[u]:[]).forEach(h=>{let g=y(h,"fulfillment-bind");if(g==="url"){let A=H(m.url);A&&h.setAttribute("href",m.url),z(h,A);return}let p={status:P(l.latestShipmentStatus||l.status),date:U(l.createdAt),eta:l.estimatedDeliveryAt?U(l.estimatedDeliveryAt):"",company:m.company||"",number:m.number||""}[g];p!=null&&C(h,p)})})),w(e,"order-show",{loading:!1,ready:!0,error:!1,"not-found":!1,cancelled:!!r.cancelledAt,shipped:o.length>0,returnable:[...n.values()].some(a=>a>0),"has-returns":e.dataset.tetherReturned!=="1"&&(r.returns?.nodes||[]).length>0,"return-requested":e.dataset.tetherReturned==="1"}),i("ready")}async function ge(e){let t=await L.customer().catch(()=>null);t&&["firstName","lastName"].forEach(s=>{let i=e.elements?.[s];i&&!i.dataset.tetherTouched&&(i.value=t[s]||"")})}var te=null;async function G(e){let t=c(e,d("addresses"));if(!t.length)return;k(e,{"addresses-loading":!0,"addresses-empty":!1});let s;try{s=te=await ue()}catch(i){q(i,"addresses"),k(e,{"addresses-loading":!1,"addresses-error":!0});return}k(e,{"addresses-loading":!1,"addresses-empty":s.length===0,"addresses-error":!1}),t.forEach(i=>T(i,s,(r,n)=>{r.dataset.tetherAddress=n.id,c(r,d("address-bind")).concat(r.matches(d("address-bind"))?[r]:[]).forEach(o=>{let a={formatted:_(n),name:[n.firstName,n.lastName].filter(Boolean).join(" "),company:n.company||"",address1:n.address1||"",address2:n.address2||"",city:n.city||"",zip:n.zip||"",province:n.province||"",country:n.country||"",phone:n.phoneNumber||""}[y(o,"address-bind")];a!=null&&C(o,a)}),w(r,"address-show",{default:n.isDefault,"not-default":!n.isDefault})}))}var ye=["pause","resume","skip","unskip","cancel"];function be(e){let t=e.upcomingBillingCycles?.nodes?.[0],s=e.status;return{active:s==="ACTIVE",paused:s==="PAUSED",cancelled:s==="CANCELLED",expired:s==="EXPIRED",failed:s==="FAILED",skipped:!!t?.skipped,"can-pause":s==="ACTIVE","can-resume":s==="PAUSED"||s==="FAILED","can-skip":s==="ACTIVE"&&!!t&&!t.skipped,"can-unskip":s==="ACTIVE"&&!!t?.skipped,"can-cancel":s==="ACTIVE"||s==="PAUSED"||s==="FAILED"}}async function se(e){let t=c(e,d("subscriptions"));if(!t.length)return;k(e,{"subscriptions-loading":!0,"subscriptions-empty":!1});let s;try{s=await le()}catch(i){q(i,"subscriptions"),k(e,{"subscriptions-loading":!1,"subscriptions-error":!0});return}k(e,{"subscriptions-loading":!1,"subscriptions-empty":s.length===0,"subscriptions-error":!1}),t.forEach(i=>T(i,s,(r,n)=>{r.dataset.tetherSubscription=n.id,r.setAttribute(I("subscription-status"),P(n.status));let o=n.lines?.nodes||[],a=n.deliveryPolicy?.intervalCount?.count||1,u=P(n.deliveryPolicy?.interval),l=o.reduce((h,g)=>h+parseFloat(g.lineDiscountedPrice?.amount||0),0);c(r,d("subscription-bind")).forEach(h=>{let g=y(h,"subscription-bind"),p={status:P(n.status),next:n.nextBillingDate?U(n.nextBillingDate):"",interval:u?a===1?u:`${a} ${u}s`:"",products:o.map(A=>`${A.quantity}\xD7 ${A.title}`).join(", "),total:o.length?b({amount:String(l),currencyCode:n.currencyCode}):"",delivery:n.deliveryPrice?b(n.deliveryPrice):""}[g];p!=null&&C(h,p)}),c(r,d("subscription-lines")).forEach(h=>T(h,o,(g,p)=>{c(g,d("subscription-line")).concat(g.matches(d("subscription-line"))?[g]:[]).forEach(A=>{let M=y(A,"subscription-line");if(M==="image"){p.image&&V(A,p.image.url,p.image.altText||p.title);return}let Q={title:p.title,"variant-title":p.variantTitle||"",quantity:String(p.quantity),price:b(p.currentPrice)}[M];Q!=null&&C(A,Q)})}));let m=be(n);w(r,"subscription-show",m),c(r,d("subscription-action")).forEach(h=>{let g=y(h,"subscription-action"),p=m[`can-${g}`];h.disabled=!p,h.classList.toggle("is-disabled",!p)})}))}async function $e(e=document){Z||(Z=!0,Ae()),await Promise.all([...c(e,d("order")).map(t=>ee(t)),...c(e,d("profile-form")).map(t=>ge(t)),G(e),se(e)])}var K=e=>Object.fromEntries([...e.elements].filter(t=>t.name&&t.type!=="submit"&&t.type!=="button"&&t.type!=="checkbox").map(t=>[t.name,t.value]));async function x(e,t,{error:s}={}){if(e.getAttribute("aria-busy")!=="true"){e.classList.add("is-busy"),e.setAttribute("aria-busy","true"),e.setAttribute(I("form-state"),"pending"),c(e,d("form-error")).forEach(i=>C(i,""));try{let i=await t();return e.setAttribute(I("form-state"),"saved"),i}catch(i){e.setAttribute(I("form-state"),"error");let r=i?.userErrors?.map(n=>n.message).join(" ")||i?.message||"Something went wrong";c(e,d("form-error")).forEach(n=>C(n,r.replace(/^Customer accounts: /,""))),s&&q(i,s);return}finally{e.classList.remove("is-busy"),e.removeAttribute("aria-busy")}}}function Ae(){document.addEventListener("submit",e=>{let t=e.target;if(t.matches?.(d("profile-form")))e.preventDefault(),x(t,async()=>{await de(K(t)),await L.bindCustomer?.(document)});else if(t.matches?.(d("address-form"))){e.preventDefault();let s=t.dataset.tetherAddressId||void 0,i=!!t.elements?.isDefault?.checked;x(t,async()=>{await J(K(t),{id:s,isDefault:i}),t.reset(),delete t.dataset.tetherAddressId,await G(document)})}},!0),document.addEventListener("input",e=>{e.target.closest?.(d("profile-form"))&&(e.target.dataset.tetherTouched="1")}),document.addEventListener("click",e=>{let t=e.target,s=t.closest?.("[data-tether-address]"),i=n=>{let o=y(n,"confirm");return!o||window.confirm(o)},r;if((r=t.closest?.(d("address-delete")))&&s)e.preventDefault(),i(r)&&x(s,async()=>{await ce(s.dataset.tetherAddress),await G(document)});else if((r=t.closest?.(d("address-default")))&&s)e.preventDefault(),x(s,async()=>{await J(null,{id:s.dataset.tetherAddress,isDefault:!0}),await G(document)});else if((r=t.closest?.(d("address-edit")))&&s){e.preventDefault();let n=(te||[]).find(a=>a.id===s.dataset.tetherAddress),o=document.querySelector(d("address-form"));n&&o&&(o.dataset.tetherAddressId=n.id,[...o.elements].forEach(a=>{a.name&&a.name in n&&(a.value=n[a.name]??""),a.name==="isDefault"&&(a.checked=n.isDefault)}),o.scrollIntoView?.({block:"nearest"}))}else if(r=t.closest?.(d("address-new"))){let n=document.querySelector(d("address-form"));n&&(n.reset(),delete n.dataset.tetherAddressId)}else if(r=t.closest?.(d("subscription-action"))){e.preventDefault();let n=r.closest("[data-tether-subscription]"),o=y(r,"subscription-action");if(!n||!ye.includes(o)||r.disabled||!i(r))return;let a=n.dataset.tetherSubscription;n.setAttribute(I("subscription-state"),"pending"),x(n,async()=>{await pe(a,o),await se(document)}).then(()=>{let u=n.getAttribute(I("form-state"))==="error"?"error":"done";c(document,"[data-tether-subscription]").filter(l=>l===n||l.dataset.tetherSubscription===a).forEach(l=>l.setAttribute(I("subscription-state"),u))})}else if(r=t.closest?.(d("order-return"))){e.preventDefault();let n=r.closest(he.order);if(!n?.dataset.tetherOrderId)return;let o=c(n,"[data-tether-line]").map(a=>({lineItemId:a.dataset.tetherLine,quantity:parseInt(a.querySelector(d("return-quantity"))?.value||"0",10),reasonId:a.querySelector(d("return-reason"))?.value||void 0,note:a.querySelector(d("return-note"))?.value||void 0})).filter(a=>a.quantity>0);if(!o.length||!i(r))return;x(n,async()=>{await fe(n.dataset.tetherOrderId,o),n.dataset.tetherReturned="1",await ee(n)})}})}export{ue as addresses,ce as deleteAddress,oe as order,$e as renderPages,fe as requestReturn,J as saveAddress,De as setup,pe as subscriptionAction,le as subscriptions,de as updateProfile};
@@ -1 +1 @@
1
- import{b}from"./chunk-L2TRRKYV.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{b as s,e as T,g as m,l as x,o as g}from"./chunk-K2YEQAIH.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};
1
+ import{b}from"./chunk-4QJKLPYR.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.js";import{b as s,e as T,g as m,l as x,o as g}from"./chunk-K2YEQAIH.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{c as Q}from"./chunk-FIOZPPC5.js";import{b as S,d as I,e as B}from"./chunk-AJLPU2JC.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 c,e as O,g as A,h as v,l as $,m as U,n as E,o as u,p as g,r as F,s as l,u as h,w as b}from"./chunk-K2YEQAIH.js";function G(t,e=1,n={}){let a=typeof t=="object"&&t!==null?t:{variantId:t,quantity:e,...n},r=I.variant(a.merchandiseId||a.variantId||a.id);if(!r)throw new v("add(): variantId is required");let s={merchandiseId:r,quantity:Math.max(1,parseInt(a.quantity??1,10)||1)},o=a.sellingPlanId||a.sellingPlan;o&&(s.sellingPlanId=I.sellingPlan(o));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(c.cartDrawerOpenClass)||(e.setAttribute("aria-hidden","true"),c.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(c.storageKey)}catch{return null}},_setId(t){try{t?localStorage.setItem(c.storageKey,t):localStorage.removeItem(c.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=U(t,e);return this.warnings=(n.warnings||[]).filter((a,r,s)=>s.findIndex(o=>o.message===a.message)===r).map(a=>({...a,message:typeof c.warningText=="function"&&c.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(`${c.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(`${c.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 $(`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){A(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=c.country||this.customerAccessToken?{...c.country?{countryCode:String(c.country).toUpperCase()}:{},...this.customerAccessToken?{customerAccessToken:this.customerAccessToken}:{}}:void 0,n=await $(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 o=await $(V(t,`$cartId: ID!, ${e}`,`cartId: $cartId, ${n}`),{...a,cartId:s});return this._take(o[t],t)}catch(o){if(r&&T(o))return O("cart expired, creating a new one"),this._setId(null),this._create(r);throw o}},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}),c.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?I.sellingPlan(n.sellingPlanId):null),n.attributes&&(a.attributes=q(n.attributes)),(n.merchandiseId||n.variantId)&&(a.merchandiseId=I.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(o=>o.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};this.pendingQty.set(t,r),this.render(),h("cart-updated",{cart:this.state,reason:"pending"});let s=()=>this.pendingQty.get(t)===r;return this._queue(async()=>{if(!s())return this.state;let o=this.lines.find(d=>d.id===t);if(o&&o.quantity===a)return this.state;let i=a>0?await this._mutate("cartLinesUpdate","$lines: [CartLineUpdateInput!]!","lines: $lines",{lines:[{id:t,quantity:a}]}):await this._mutate("cartLinesRemove","$lineIds: [ID!]!","lineIds: $lineIds",{lineIds:[t]});return s()?this._commit(i,a>0?"update":"remove"):(this.state=i,i?.id&&this._setId(i.id),i)}).finally(()=>{s()&&(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=q(t);return this._queue(async()=>{let n=new Map((this.state?.attributes||[]).map(r=>[r.key,r.value]));e.forEach(r=>n.set(r.key,r.value));let a=[...n].filter(([,r])=>r!=="").map(([r,s])=>({key:r,value:s}));return this._commit(await this._mutate("cartAttributesUpdate","$attributes: [AttributeInput!]!","attributes: $attributes",{attributes:a},{attributes:a}),"attributes")})},setDiscountCodes(t){return this._queue(async()=>{let e=typeof t=="function"?t((this.state?.discountCodes||[]).map(a=>a.code)):t,n=(Array.isArray(e)?e:[e]).map(a=>String(a).trim()).filter(Boolean);return this._commit(await this._mutate("cartDiscountCodesUpdate","$discountCodes: [String!]!","discountCodes: $discountCodes",{discountCodes:n},{discountCodes:n}),"discount")})},async applyDiscount(t){let e=await this.setDiscountCodes(a=>[...new Set([...a,t])]);if((e?.discountCodes||[]).find(a=>a.code.toLowerCase()===String(t).toLowerCase())?.applicable)return e;throw await this.removeDiscount(t).catch(()=>{}),new v(`Discount code not valid: ${t}`,{code:"INVALID_DISCOUNT"})},removeDiscount(t){let e=String(t).toLowerCase();return this.setDiscountCodes(n=>n.filter(a=>a.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=c.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=$("query TetherCheckout($id: ID!) { cart(id: $id) { checkoutUrl } }",{id:e}).then(s=>s.cart?.checkoutUrl);a.catch(()=>{});let r=this.beforeCheckout&&await this.beforeCheckout().catch(()=>null)||await a;if(r&&this.customerAccessToken&&(r+=`${r.includes("?")?"&":"?"}logged_in=true`),!r)throw new v("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(),A(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(c.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(c.cartDrawerOpenClass),e.setAttribute("aria-hidden","false")}),x(!0),c.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 c.onCartOpen=="function"&&c.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(c.cartDrawerOpenClass),n.setAttribute("aria-hidden","true"),c.cartFocus!==!1&&(n.inert=!0)}),x(!1),e&&k?.isConnected&&k.focus({preventScroll:!0}),k=null,typeof c.onCartClose=="function"&&c.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(`${c.prefix}:${a}`,n)),e(),()=>["cart-updated","cart-toggled"].forEach(a=>document.removeEventListener(`${c.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(o=>o.message))].join(" "))),l(document,u("show")).forEach(s=>{let o=g(s,"show");o in r&&!s.closest(u("product"))&&L(s,r[o])}),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||[],(o,i)=>{o.setAttribute(E("discount-code"),i.code);let d=o.querySelector(u("discount","code"))||(o.firstElementChild?null:o);d&&j(d,i.code),o.classList.toggle("is-inapplicable",!i.applicable)})}),l(document,u("cart-lines")).forEach(s=>{N(s,this.lines,o=>o.id,(o,i)=>J(o,i),{onEnter:c.onLineEnter,onLeave:c.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),_=new URLSearchParams;n.id&&_.set("variant",String(n.id).split("/").pop());let w=e.sellingPlanAllocation?.sellingPlan?.id;w&&_.set("selling_plan",w.split("/").pop());let C=_.toString();return i.setAttribute("href",C?`${y}${y.includes("?")?"&":"?"}${C}`:y)}let f=z(e,d);f!==void 0&&m(i,f)});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 o={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 o&&L(i,o[d])}),l(t,`select${u("line-plan")}`).forEach(i=>{let d=n.product?.handle;d&&Q(d).then(f=>{let y=B(f),w=[...!f.requiresSellingPlan&&g(i,"line-plan")!=="subscription-only"?[{value:"",label:i.getAttribute(E("one-time-label"))||"One-time purchase"}]:[],...y.map(p=>({value:p.id,label:p.name}))],C=w.map(p=>p.value).join("|");i.dataset.tetherSig!==C&&(i.innerHTML="",w.forEach(p=>{let P=document.createElement("option");P.value=p.value,P.textContent=p.label,i.appendChild(P)}),i.dataset.tetherSig=C),i.value=e.sellingPlanAllocation?.sellingPlan?.id||"",L(i,y.length>0)}).catch(f=>A(f,"line plan options"))})}export{W as a,D as b};
@@ -1 +1 @@
1
- import{b as rt,e as ot}from"./chunk-RREHGH4A.js";import{b as nt}from"./chunk-L2TRRKYV.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-AJLPU2JC.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-K2YEQAIH.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};
1
+ import{b as rt,e as ot}from"./chunk-RREHGH4A.js";import{b as nt}from"./chunk-4QJKLPYR.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-AJLPU2JC.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-K2YEQAIH.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
+ var t={diagnose:()=>import("./diagnose-3WVAWNTX.js"),markets:()=>import("./markets-ui-545XLFTE.js"),search:()=>import("./search-NILMGYXG.js"),extras:()=>import("./extras-7I7WJX35.js"),account:()=>import("./account-Q6E2TFEV.js"),"account-pages":()=>import("./account-pages-UZXR4R5F.js"),analytics:()=>import("./analytics-IJBKATUP.js")},r=o=>t[o](),a=void 0;export{r as a,a as b};
@@ -1 +1 @@
1
- import{a as E,b as K,c as z}from"./chunk-ZIUIWEON.js";import{a as g,c as w,f as p}from"./chunk-RREHGH4A.js";import{c as I,e as A,f as F,g as O,h as R,i as U}from"./chunk-FIOZPPC5.js";import{A as q,B as L,D as x,G as D,I as M,K as J,b as h,e as T,f as b,g as m,h as C,n as l,o as a,p as c,q as S,s as N,t as W,u as f}from"./chunk-K2YEQAIH.js";var P=()=>`${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(P())===e&&(n.preventDefault(),J(o,()=>this.load(!0)))})}$(e){return W(this.root,e,P())}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"};if(S(e,"collection"))n.collection=c(e,"collection");else{let o=c(e,"products")||"";n.query=o.startsWith("url:")?new URL(window.location.href).searchParams.get(o.slice(4))||"":o}return 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 C("No product for recommendations",{code:"NOT_FOUND"});let u=await U(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 R({...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,w(r)?"not-found":"error",r),w(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 L(o,e?.title||"");case"description":o.innerHTML=e?.descriptionHtml||"";return;case"image":return q(o,e?.image?.url,e?.image?.altText||e?.title);case"count":return L(o,this.products.length);default:return}}),this.$(a("list")).forEach(o=>{D(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)),M("list")}};var v=new WeakSet,ft=new WeakSet,k=new Set,H=new Set,j=new WeakMap;function _(){k.forEach(t=>{t.isConnected||k.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(v.has(t))return!1;let{key:e,fromUrl:n,raw:o}=g(t);if(!e)return n?(v.add(t),p(t,"not-found"),f("product-not-found",{key:null,source:o},t)):t.closest(P())||b(`[${l("product")}] without a value. Bind it to the Shopify handle field, or use "url:handle".`,t),!1;v.add(t),k.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=I(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=w(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(){_(),k.forEach(t=>{t.getAttribute(l("state"))!=="error"||t.getAttribute(l("error"))==="not-found"||(v.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=>{k.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{P as a,B as b,v as c,ft as d,k 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};
1
+ import{a as E,b as K,c as z}from"./chunk-KIDH76B7.js";import{a as g,c as w,f as p}from"./chunk-RREHGH4A.js";import{c as I,e as A,f as F,g as O,h as R,i as U}from"./chunk-FIOZPPC5.js";import{A as q,B as L,D as x,G as D,I as M,K as J,b as h,e as T,f as b,g as m,h as C,n as l,o as a,p as c,q as S,s as N,t as W,u as f}from"./chunk-K2YEQAIH.js";var P=()=>`${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(P())===e&&(n.preventDefault(),J(o,()=>this.load(!0)))})}$(e){return W(this.root,e,P())}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"};if(S(e,"collection"))n.collection=c(e,"collection");else{let o=c(e,"products")||"";n.query=o.startsWith("url:")?new URL(window.location.href).searchParams.get(o.slice(4))||"":o}return 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 C("No product for recommendations",{code:"NOT_FOUND"});let u=await U(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 R({...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,w(r)?"not-found":"error",r),w(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 L(o,e?.title||"");case"description":o.innerHTML=e?.descriptionHtml||"";return;case"image":return q(o,e?.image?.url,e?.image?.altText||e?.title);case"count":return L(o,this.products.length);default:return}}),this.$(a("list")).forEach(o=>{D(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)),M("list")}};var v=new WeakSet,ft=new WeakSet,k=new Set,H=new Set,j=new WeakMap;function _(){k.forEach(t=>{t.isConnected||k.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(v.has(t))return!1;let{key:e,fromUrl:n,raw:o}=g(t);if(!e)return n?(v.add(t),p(t,"not-found"),f("product-not-found",{key:null,source:o},t)):t.closest(P())||b(`[${l("product")}] without a value. Bind it to the Shopify handle field, or use "url:handle".`,t),!1;v.add(t),k.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=I(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=w(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(){_(),k.forEach(t=>{t.getAttribute(l("state"))!=="error"||t.getAttribute(l("error"))==="not-found"||(v.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=>{k.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{P as a,B as b,v as c,ft as d,k 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};
@@ -1,4 +1,4 @@
1
- import{c as D}from"./chunk-64TUD3QR.js";import{a as y,d as M}from"./chunk-RREHGH4A.js";import{c as P}from"./chunk-FIOZPPC5.js";import{e as V}from"./chunk-AJLPU2JC.js";import{F as q,b as i,d as S,i as E,l as x,n as h,o as c,p as g,s as d}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var I=e=>{let n=/^(\d{4})-(01|04|07|10)$/.exec(String(e||""));return n?{y:+n[1],m:+n[2]}:null},B=(e,n)=>`${e}-${String(n).padStart(2,"0")}`;function A(e,n=1){let o=I(e);if(!o)throw new Error(`not a quarterly Shopify API version: ${e}`);let a=o.y*4+(o.m-1)/3+n;return B(Math.floor(a/4),a%4*3+1)}function T(e,n=new Date){if(e==="unstable")return{version:e,ok:!1,note:'"unstable" changes without notice: pin a dated version such as 2026-07'};let o=I(e);if(!o)return{version:e,ok:!1,note:"not a quarterly version (YYYY-01, -04, -07 or -10)"};let a=new Date(Date.UTC(o.y,o.m-1,1)),r=new Date(Date.UTC(o.y+1,o.m-1,1)),f=(r-n)/(30.44*24*3600*1e3),l=`supported until about ${r.toISOString().slice(0,7)}`;return a>n?l="not released yet (release candidate at best)":f<=0?l="no longer supported: Shopify falls back to the oldest supported version. Upgrade (see README)":f<3&&(l=`${l}: plan the upgrade to ${A(e)} or later (see README)`),{version:e,ok:a<=n&&f>0,monthsLeft:Math.round(f),next:A(e),note:l}}var C=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","search-empty","search-results","logged-in","logged-out","orders-empty","orders-loading","addresses-loading","addresses-empty","subscriptions-loading","subscriptions-empty"]),N=new Set(["title","description","description-text","vendor","type","handle","published-at","price","total-price","compare-at-price","unit-price","min-price","max-price","discount-percentage","discount-amount","variant-title","variant-id","sku","barcode","stock","quantity","featured-image","variant-image","images","tags","link","url","one-time-price","subscription-price","subscription-savings","subscription-savings-amount","checkout-charge","plan-name","plan-description","plan-group","option-value","swatch","image"]),U=new Set(`account account-bind account-link account-login account-logout add-label add-to-cart adding-text
1
+ import{c as D}from"./chunk-64TUD3QR.js";import{a as y,d as M}from"./chunk-RREHGH4A.js";import{c as P}from"./chunk-FIOZPPC5.js";import{e as V}from"./chunk-AJLPU2JC.js";import{F as q,b as i,d as S,i as E,l as x,n as h,o as c,p as g,s as d}from"./chunk-K2YEQAIH.js";import"./chunk-VC46IEJQ.js";var I=e=>{let n=/^(\d{4})-(01|04|07|10)$/.exec(String(e||""));return n?{y:+n[1],m:+n[2]}:null},B=(e,n)=>`${e}-${String(n).padStart(2,"0")}`;function A(e,n=1){let o=I(e);if(!o)throw new Error(`not a quarterly Shopify API version: ${e}`);let a=o.y*4+(o.m-1)/3+n;return B(Math.floor(a/4),a%4*3+1)}function T(e,n=new Date){if(e==="unstable")return{version:e,ok:!1,note:'"unstable" changes without notice: pin a dated version such as 2026-07'};let o=I(e);if(!o)return{version:e,ok:!1,note:"not a quarterly version (YYYY-01, -04, -07 or -10)"};let a=new Date(Date.UTC(o.y,o.m-1,1)),r=new Date(Date.UTC(o.y+1,o.m-1,1)),f=(r-n)/(30.44*24*3600*1e3),l=`supported until about ${r.toISOString().slice(0,7)}`;return a>n?l="not released yet (release candidate at best)":f<=0?l="no longer supported: Shopify falls back to the oldest supported version. Upgrade (see README)":f<3&&(l=`${l}: plan the upgrade to ${A(e)} or later (see README)`),{version:e,ok:a<=n&&f>0,monthsLeft:Math.round(f),next:A(e),note:l}}var C=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","search-empty","search-results","logged-in","logged-out","orders-empty","orders-loading","addresses-loading","addresses-empty","addresses-error","subscriptions-loading","subscriptions-empty","subscriptions-error"]),N=new Set(["title","description","description-text","vendor","type","handle","published-at","price","total-price","compare-at-price","unit-price","min-price","max-price","discount-percentage","discount-amount","variant-title","variant-id","sku","barcode","stock","quantity","featured-image","variant-image","images","tags","link","url","one-time-price","subscription-price","subscription-savings","subscription-savings-amount","checkout-charge","plan-name","plan-description","plan-group","option-value","swatch","image"]),U=new Set(`account account-bind account-link account-login account-logout add-label add-to-cart adding-text
2
2
  always-enabled bind cart-checkout-charge cart-clear cart-close cart-count cart-discounts cart-drawer cart-label cart-lines
3
3
  cart-note cart-open cart-subtotal cart-total cart-warning checkout code collection collection-bind countries country
4
4
  country-bind country-label country-select default-plan default-purchase discount discount-code discount-form discount-input
@@ -1 +1 @@
1
- import{a as b}from"./chunk-ZIUIWEON.js";import"./chunk-RREHGH4A.js";import{b as l}from"./chunk-L2TRRKYV.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.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-K2YEQAIH.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};
1
+ import{a as b}from"./chunk-KIDH76B7.js";import"./chunk-RREHGH4A.js";import{b as l}from"./chunk-4QJKLPYR.js";import"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.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-K2YEQAIH.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};
@@ -1 +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-VCPI7MJ2.js";import{a as C,b,c as T,d as A,e as I,f as v}from"./chunk-64TUD3QR.js";import"./chunk-ZIUIWEON.js";import"./chunk-RREHGH4A.js";import{b as d}from"./chunk-L2TRRKYV.js";import{d as E}from"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.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-K2YEQAIH.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};
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-SSJT43CJ.js";import{a as C,b,c as T,d as A,e as I,f as v}from"./chunk-64TUD3QR.js";import"./chunk-KIDH76B7.js";import"./chunk-RREHGH4A.js";import{b as d}from"./chunk-4QJKLPYR.js";import{d as E}from"./chunk-FIOZPPC5.js";import"./chunk-AJLPU2JC.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-K2YEQAIH.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};
package/dist/esm/index.js CHANGED
@@ -1 +1 @@
1
- import{a as j,b as W,d as x,f as C,g as Z,h as g,i as X,j as Y,k as ee,l as te,m as ne}from"./chunks/chunk-VCPI7MJ2.js";import{a as V}from"./chunks/chunk-ZIUIWEON.js";import{a as Q}from"./chunks/chunk-RREHGH4A.js";import{a as l,b as re}from"./chunks/chunk-VPVJPNB4.js";import{a as J,b as c}from"./chunks/chunk-L2TRRKYV.js";import{a as _,b as q,c as R,d as F,h as G,i as B}from"./chunks/chunk-FIOZPPC5.js";import{l as K}from"./chunks/chunk-AJLPU2JC.js";import{K as h,b as r,c as P,d as L,e as $,f as D,g as u,h as M,j as N,l as U,n as p,o as a,u as k,w as H,y as z}from"./chunks/chunk-K2YEQAIH.js";import"./chunks/chunk-VC46IEJQ.js";var oe="0.6.6",f=null,S=null;function m(t=document){if(!L())return 0;let e=0;return Z(),ne(t),g(t,j()).forEach(n=>{if(x.has(n))return;x.add(n),e++;let o=new W(n);C.add(o),n.addEventListener(`${r.prefix}:list-rendered`,i=>m(i.detail.container)),ee(o.load())}),g(t,a("product")).forEach(n=>{X(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,["account-login","account-bind","account-link","orders","order","addresses","subscriptions","profile-form","address-form"].map(n=>`[${p(n)}]`).join(",")+`,[${p("show")}^="logged-"]`).length||/[?&]code=/.test(window.location.search)||ge())&&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")),te(),c.render(),$(`mounted ${e} scope(s)`,t),e}function ie(){c.close()}function fe(t){let e=t?.closest?.(a("product"));return e&&V.get(e)||null}var ae=!1;function me(){ae||(ae=!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(ce());if(i&&i.closest(a("cart-lines"))){let d=i.getAttribute(`data-${r.prefix}-key`),E=c.lines.find(w=>w.id===d),b=w=>{t.preventDefault(),w().catch(de=>u(de,"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(p("discount-code"));d&&c.removeDiscount(d).catch(E=>u(E,"discount"));return}let y=e.closest(a("group-add"));y&&(t.preventDefault(),h(y,()=>se(y)))}),document.addEventListener("change",t=>{let e=t.target;if(!e?.closest)return;let n=e.closest(ce()),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?.(p("variant-url")))&&l("extras").then(n=>n.writeVariantUrl(e,t.detail)).catch(()=>{})}),r.astro!==!1&&(document.addEventListener("astro:page-load",()=>(f||Promise.resolve()).then(()=>{let t=T();if(!t&&A){try{t=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{t=null}t=t?.country?t:le}A=!!T(),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(()=>m(document),()=>m(document)):m(document)})),document.addEventListener("astro:before-swap",()=>ie())),window.addEventListener("online",()=>{Y(),C.forEach(t=>{t.root.getAttribute(p("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?J(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 ce(){return`[data-${r.prefix}-key]`}var se=t=>l("extras").then(e=>e.addGroup(t)),v=null;function ue(t={}){return f&&!Object.keys(t).length?f:(P({...window.TETHER_CONFIG||{},...t}),L()?(me(),r.observe&&he(),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"))),f=pe(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}),O}),f):(D("TETHER_CONFIG is missing domain or token. Tether is idle."),f=Promise.resolve(null),f))}function T(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 le=null,A=!1;async function pe(t){let e=r.markets||{};le={country:r.country,language:r.language,locale:r.locale};let n=T();if(A=!!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),$("market",o))}function ge(){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 ye=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 he(){if(S||typeof MutationObserver>"u")return;let t=null,e=new Set;S=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&&m(o)}),e.clear()},50)}),S.observe(document.body,{childList:!0,subtree:!0})}var O={VERSION:oe,init:ue,mount:m,unmount:ie,get config(){return r},get ready(){return f||Promise.resolve(null)},query:U,withContext:N,cart:c,getProduct:R,getProducts:G,getRecommendations:B,getScope:fe,addGroup:se,account:ye,primeProduct:q,normalizeProductKey:_,clearProductCache:F,formatMoney:H,imageUrl:z,plans:K,TetherError:M,resolveProductKey:Q,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:oe})),__core:re,__parts:{},on(t,e){let n=o=>e(o.detail,o);return document.addEventListener(`${r.prefix}:${t}`,n),()=>document.removeEventListener(`${r.prefix}:${t}`,n)}},Pe=O;if(typeof window<"u"&&typeof document<"u"&&(window.Tether=O,window.TETHER_CONFIG&&window.TETHER_CONFIG.autoMount!==!1&&!window.TETHER_INTEGRATION)){let e=()=>ue().then(()=>m(document));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{oe as VERSION,se as addGroup,O as api,Pe as default,fe as getScope,ue as init,m as mount,I as setCountry,ie as unmount};
1
+ import{a as W,b as Z,d as x,f as C,g as X,h as g,i as Y,j as ee,k as te,l as ne,m as re}from"./chunks/chunk-SSJT43CJ.js";import{a as j}from"./chunks/chunk-KIDH76B7.js";import{a as V}from"./chunks/chunk-RREHGH4A.js";import{a as l,b as oe}from"./chunks/chunk-PAYT5ZD7.js";import{a as Q,b as c}from"./chunks/chunk-4QJKLPYR.js";import{a as q,b as R,c as B,d as F,h as G,i as K}from"./chunks/chunk-FIOZPPC5.js";import{l as H}from"./chunks/chunk-AJLPU2JC.js";import{K as h,b as r,c as D,d as L,e as $,f as M,g as u,h as N,j as U,l as _,n as p,o as a,u as b,w as z,y as J}from"./chunks/chunk-K2YEQAIH.js";import"./chunks/chunk-VC46IEJQ.js";var ae="0.6.7",f=null,S=null,T=null;function m(t=document){if(!L())return 0;t===document&&(T=document.body);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);C.add(o),n.addEventListener(`${r.prefix}:list-rendered`,i=>m(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,["account-login","account-bind","account-link","orders","order","addresses","subscriptions","profile-form","address-form"].map(n=>`[${p(n)}]`).join(",")+`,[${p("show")}^="logged-"]`).length||/[?&]code=/.test(window.location.search)||ye())&&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")),ne(),c.render(),$(`mounted ${e} scope(s)`,t),e}function se(){c.close()}function me(t){let e=t?.closest?.(a("product"));return e&&j.get(e)||null}var ce=!1;function pe(){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(w=>w.id===d),k=w=>{t.preventDefault(),w().catch(fe=>u(fe,"cart line"))};if(e.closest(a("line-remove")))return i.classList.add("is-busy"),k(()=>c.removeLine(d));if(E&&e.closest(a("line-plus")))return k(()=>c.changeQuantity(d,1));if(E&&e.closest(a("line-minus")))return k(()=>c.changeQuantity(d,-1))}let s=e.closest(a("discount-remove"));if(s){t.preventDefault();let d=s.closest(a("discount-code"))?.getAttribute(p("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&&O(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),b("discount-applied",{code:o},e),n&&(n.value="")}catch(s){i(!0),s?.code==="INVALID_DISCOUNT"?b("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?.(p("variant-url")))&&l("extras").then(n=>n.writeVariantUrl(e,t.detail)).catch(()=>{})}),r.astro!==!1&&(document.addEventListener("astro:page-load",()=>(f||Promise.resolve()).then(()=>{let t=A();if(!t&&I){try{t=JSON.parse(localStorage.getItem(`${r.prefix}:market:${r.domain}`)||"null")}catch{t=null}t=t?.country?t:de}I=!!A(),t?.country&&(String(t.country).toUpperCase()!==String(r.country||"").toUpperCase()||String(t.language||"").toUpperCase()!==String(r.language||"").toUpperCase())?O(t.country,{language:t.language??null,locale:t.locale,remember:!1}).then(()=>m(document),()=>m(document)):T!==document.body&&m(document)})),document.addEventListener("astro:before-swap",()=>{T=null,se()})),window.addEventListener("online",()=>{ee(),C.forEach(t=>{t.root.getAttribute(p("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 f&&!Object.keys(t).length?f:(D({...window.TETHER_CONFIG||{},...t}),L()?(pe(),r.observe&&ve(),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"))),f=ge(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 b("ready",{cart:e}),P}),f):(M("TETHER_CONFIG is missing domain or token. Tether is idle."),f=Promise.resolve(null),f))}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,I=!1;async function ge(t){let e=r.markets||{};de={country:r.country,language:r.language,locale:r.locale};let n=A();if(I=!!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),$("market",o))}function ye(){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 he=new Proxy({},{get:(t,e)=>(...n)=>l("account").then(o=>o[e](...n))});function O(t,e){return l("markets").then(n=>n.setCountry(t,e))}function ve(){if(S||typeof MutationObserver>"u")return;let t=null,e=new Set;S=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&&m(o)}),e.clear()},50)}),S.observe(document.body,{childList:!0,subtree:!0})}var P={VERSION:ae,init:le,mount:m,unmount:se,get config(){return r},get ready(){return f||Promise.resolve(null)},query:_,withContext:U,cart:c,getProduct:B,getProducts:G,getRecommendations:K,getScope:me,addGroup:ue,account:he,primeProduct:R,normalizeProductKey:q,clearProductCache:F,formatMoney:z,imageUrl:J,plans:H,TetherError:N,resolveProductKey:V,setCountry:O,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(()=>m(document));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}export{ae as VERSION,ue as addGroup,P as api,De as default,me as getScope,le as init,m as mount,O as setCountry,se as unmount};
@@ -76,12 +76,13 @@
76
76
  return s;
77
77
  };
78
78
  var ADDRESS_FIELDS = ["firstName", "lastName", "company", "address1", "address2", "city", "zip", "zoneCode", "phoneNumber"];
79
- function addressInput(a = {}) {
79
+ function addressInput(a = {}, { clear = false } = {}) {
80
80
  if (!a || typeof a !== "object" || Array.isArray(a)) throw new InputError("address");
81
81
  const out = {};
82
82
  ADDRESS_FIELDS.forEach((k) => {
83
83
  const v = text(a[k]);
84
84
  if (v !== void 0) out[k] = v;
85
+ else if (clear && k in a && (a[k] === "" || a[k] === null)) out[k] = "";
85
86
  });
86
87
  if (a.countryCode != null && a.countryCode !== "") {
87
88
  const c = String(a.countryCode).toUpperCase();
@@ -118,7 +119,7 @@
118
119
  return { addresses: (c?.addresses?.nodes || []).map((a) => ({ ...a, isDefault: a.id === def })) };
119
120
  },
120
121
  async saveAddress(ask, { id, address, isDefault }) {
121
- const a = addressInput(address || {});
122
+ const a = addressInput(address || {}, { clear: Boolean(id) });
122
123
  const def = isDefault === true ? true : void 0;
123
124
  const p = id ? userErrors((await ask(M.addressUpdate, { id: idOf("CustomerAddress", id), address: Object.keys(a).length ? a : null, default: def ?? null }))?.customerAddressUpdate) : userErrors((await ask(M.addressCreate, { address: a, default: def ?? false }))?.customerAddressCreate);
124
125
  return { address: p.customerAddress };
@@ -332,7 +333,9 @@
332
333
  qsa(row, sel("fulfillment-bind")).concat(row.matches(sel("fulfillment-bind")) ? [row] : []).forEach((b) => {
333
334
  const k = get(b, "fulfillment-bind");
334
335
  if (k === "url") {
335
- if (https(t.url)) b.setAttribute("href", t.url);
336
+ const ok = https(t.url);
337
+ if (ok) b.setAttribute("href", t.url);
338
+ show(b, ok);
336
339
  return;
337
340
  }
338
341
  const v = { status: lower(f.latestShipmentStatus || f.status), date: date(f.createdAt), eta: f.estimatedDeliveryAt ? date(f.estimatedDeliveryAt) : "", company: t.company || "", number: t.number || "" }[k];
@@ -347,7 +350,7 @@
347
350
  cancelled: Boolean(o.cancelledAt),
348
351
  shipped: ships.length > 0,
349
352
  returnable: [...returnable.values()].some((q) => q > 0),
350
- "has-returns": (o.returns?.nodes || []).length > 0,
353
+ "has-returns": el.dataset.tetherReturned !== "1" && (o.returns?.nodes || []).length > 0,
351
354
  "return-requested": el.dataset.tetherReturned === "1"
352
355
  });
353
356
  state("ready");
@@ -365,13 +368,15 @@
365
368
  const boxes = qsa(root, sel("addresses"));
366
369
  if (!boxes.length) return;
367
370
  showGlobal(root, { "addresses-loading": true, "addresses-empty": false });
368
- let list = [];
371
+ let list;
369
372
  try {
370
373
  list = addressCache = await addresses();
371
374
  } catch (err) {
372
375
  reportError(err, "addresses");
376
+ showGlobal(root, { "addresses-loading": false, "addresses-error": true });
377
+ return;
373
378
  }
374
- showGlobal(root, { "addresses-loading": false, "addresses-empty": list.length === 0 });
379
+ showGlobal(root, { "addresses-loading": false, "addresses-empty": list.length === 0, "addresses-error": false });
375
380
  boxes.forEach((box) => repeat(box, list, (row, a) => {
376
381
  row.dataset.tetherAddress = a.id;
377
382
  qsa(row, sel("address-bind")).concat(row.matches(sel("address-bind")) ? [row] : []).forEach((b) => {
@@ -403,13 +408,15 @@
403
408
  const boxes = qsa(root, sel("subscriptions"));
404
409
  if (!boxes.length) return;
405
410
  showGlobal(root, { "subscriptions-loading": true, "subscriptions-empty": false });
406
- let list = [];
411
+ let list;
407
412
  try {
408
413
  list = await subscriptions();
409
414
  } catch (err) {
410
415
  reportError(err, "subscriptions");
416
+ showGlobal(root, { "subscriptions-loading": false, "subscriptions-error": true });
417
+ return;
411
418
  }
412
- showGlobal(root, { "subscriptions-loading": false, "subscriptions-empty": list.length === 0 });
419
+ showGlobal(root, { "subscriptions-loading": false, "subscriptions-empty": list.length === 0, "subscriptions-error": false });
413
420
  boxes.forEach((box) => repeat(box, list, (row, c) => {
414
421
  row.dataset.tetherSubscription = c.id;
415
422
  row.setAttribute(attr("subscription-status"), lower(c.status));
@@ -464,6 +471,7 @@
464
471
  }
465
472
  var fieldsOf = (form) => Object.fromEntries([...form.elements].filter((i) => i.name && i.type !== "submit" && i.type !== "button" && i.type !== "checkbox").map((i) => [i.name, i.value]));
466
473
  async function act(el, fn, { error } = {}) {
474
+ if (el.getAttribute("aria-busy") === "true") return void 0;
467
475
  el.classList.add("is-busy");
468
476
  el.setAttribute("aria-busy", "true");
469
477
  el.setAttribute(attr("form-state"), "pending");
@@ -488,7 +496,10 @@
488
496
  const f = e.target;
489
497
  if (f.matches?.(sel("profile-form"))) {
490
498
  e.preventDefault();
491
- act(f, () => updateProfile(fieldsOf(f)));
499
+ act(f, async () => {
500
+ await updateProfile(fieldsOf(f));
501
+ await ctx.bindCustomer?.(document);
502
+ });
492
503
  } else if (f.matches?.(sel("address-form"))) {
493
504
  e.preventDefault();
494
505
  const id = f.dataset.tetherAddressId || void 0;
@@ -500,7 +511,7 @@
500
511
  await renderAddresses(document);
501
512
  });
502
513
  }
503
- });
514
+ }, true);
504
515
  document.addEventListener("input", (e) => {
505
516
  if (e.target.closest?.(sel("profile-form"))) e.target.dataset.tetherTouched = "1";
506
517
  });
@@ -547,12 +558,14 @@
547
558
  const sub = btn.closest("[data-tether-subscription]");
548
559
  const a = get(btn, "subscription-action");
549
560
  if (!sub || !SUB_ACTIONS.includes(a) || btn.disabled || !confirmOk(btn)) return;
561
+ const id = sub.dataset.tetherSubscription;
550
562
  sub.setAttribute(attr("subscription-state"), "pending");
551
563
  act(sub, async () => {
552
- await subscriptionAction(sub.dataset.tetherSubscription, a);
564
+ await subscriptionAction(id, a);
553
565
  await renderSubscriptions(document);
554
566
  }).then(() => {
555
- sub.setAttribute(attr("subscription-state"), sub.getAttribute(attr("form-state")) === "error" ? "error" : "done");
567
+ const state = sub.getAttribute(attr("form-state")) === "error" ? "error" : "done";
568
+ qsa(document, "[data-tether-subscription]").filter((r) => r === sub || r.dataset.tetherSubscription === id).forEach((r) => r.setAttribute(attr("subscription-state"), state));
556
569
  });
557
570
  } else if (btn = t.closest?.(sel("order-return"))) {
558
571
  e.preventDefault();