UNPKG

@appmate/wishlist

Version:

Wishlist King SDK

122 lines 52.7 kB
var Kt=o=>{throw TypeError(o)};var Ct=(o,t,e)=>t.has(o)||Kt("Cannot "+e);var c=(o,t,e)=>(Ct(o,t,"read from private field"),e?e.call(o):t.get(o)),u=(o,t,e)=>t.has(o)?Kt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(o):t.set(o,e),m=(o,t,e,i)=>(Ct(o,t,"write to private field"),i?i.call(o,e):t.set(o,e),e),I=(o,t,e)=>(Ct(o,t,"access private method"),e);var Bt="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Jt=(o=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(o|=0));for(;o--;)t+=Bt[e[o]&63];return t};var F=class o{constructor(t){this.element=t}replace(t){var e;return(e=this.element)==null||e.replaceWith(t),t}append(t){var e;return(e=this.element)==null||e.append(t),t}prepend(t){var e;return(e=this.element)==null||e.prepend(t),t}insertBefore(t){var e;return(e=this.element)==null||e.before(t),t}insertAfter(t){var e;return(e=this.element)==null||e.after(t),t}closest(t,e=5){if(!this.element)return new o;if(typeof t=="object")return this.searchByStyle(t,this.element,s=>s.parentElement,e);let i=this.element.closest(t);return i?new o(i):new o}find(t){var i;let e=(i=this.element)==null?void 0:i.querySelector(t);return e?new o(e):new o}searchByStyle(t,e,i,s=5){if(s<0||!e)return null;let r=getComputedStyle(e);if(Object.entries(t).every(([l,h])=>r.getPropertyValue(l)===h))return new o(e);let a=i(e);return a?this.searchByStyle(t,a,i,s-1):null}};var Ut,w=o=>(!!localStorage.getItem("debug")&&(Ut=import("https://cdn.jsdelivr.net/npm/debug@4.3.7/+esm")),(e,...i)=>{Ut&&Ut.then(({default:s})=>{s(o)(e,...i)})});var Y=w("wk:theme"),X,V,L,pt=class{constructor({routeUtil:t}){u(this,X);u(this,V);u(this,L);m(this,V,[]),m(this,L,t),m(this,X,new MutationObserver(e=>{e.reduce((i,s)=>i.concat(Array.from(s.addedNodes)),[]).filter(i=>i instanceof Element&&!i.hasAttribute("wk-skip")).forEach(i=>{i instanceof Element&&this.scan(i)})})),c(this,X).observe(document,{subtree:!0,childList:!0,attributes:!1})}isNearViewport(t){let e=t.getBoundingClientRect(),i=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth,r=-i,n=2*i,a=-s,l=2*s;return(e.top>r&&e.top<i||e.bottom>n&&e.bottom<i)&&(e.left>a&&e.left<s||e.right>l&&e.right<s)}watch(t,e){Y("Watch theme for target",{target:t});let i={target:t,callback:e};c(this,V).push(i),Qt(i,c(this,L).parse(window.location.pathname))&&this.scan(document)}scan(t){t&&c(this,V).filter(e=>Qt(e,c(this,L).parse(window.location.pathname))).forEach(e=>{t instanceof Element&&t.matches(e.target.selector)&&this.notify(e,t);let s=t.querySelectorAll(e.target.selector);for(let r of s)this.notify(e,r)})}notify(t,e){e.hasAttribute("wk-skip")||(e.setAttribute("wk-skip",""),Y("Found watched element",{target:t.target,element:e,lazy:t.target.lazy,isNearViewport:this.isNearViewport(e)}),t.target.lazy&&!this.isNearViewport(e)?(Y("Lazy target not in viewport",{target:t.target,element:e}),new IntersectionObserver(function([i]){i.isIntersecting&&(Y("Lazy target entered viewport, notify subscriber",{target:t.target,element:e}),this.disconnect(),t.callback(new F(e)))},{root:null,rootMargin:"100% 100% 100% 100%"}).observe(e)):(Y("Notify subscriber about watched element",{target:t.target,element:e}),t.callback(new F(e))))}};X=new WeakMap,V=new WeakMap,L=new WeakMap;function Qt({target:o},t){if(!o.pageType)return!0;if(!t.pageType)return!1;let e=Array.isArray(o.pageType)?o.pageType:[o.pageType];return e.includes("all")?!0:e.includes(t.pageType)}var oe=[{pageType:"product",match:o=>o.includes("/products/")},{pageType:"collection",match:o=>o.includes("/collections/")&&!o.includes("/products/")},{pageType:"account",match:o=>o.includes("/account/")||o.endsWith("/account")},{pageType:"challenge",match:o=>o.endsWith("/account")},{pageType:"blog",match:o=>o.includes("/blog/")},{pageType:"cart",match:o=>o.includes("/cart/")||o.endsWith("/cart")},{pageType:"wishlist",match:(o,{wishlistUrl:t})=>o.includes(t)},{pageType:"page",match:o=>o.includes("/pages/")},{pageType:"search",match:o=>o.includes("/search")},{pageType:"home",match:o=>o.length<4}],ut=class{constructor({wishlistUrl:t}){this.wishlistUrl=t}parse(t){for(let e of oe)if(e.match(t,{wishlistUrl:this.wishlistUrl}))return{pageType:e.pageType};return{pageType:"unknown"}}};var mt=class{constructor(t){this.locale={};var e;this.setLocale((e=t==null?void 0:t.locale)!=null?e:{})}setLocale(t){this.locale=this.decodeLocale(t)}decodeHtmlEntities(t){return t.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'")}decodeLocale(t){let e={};for(let i in t){e[i]={};for(let s in t[i])e[i][s]=this.decodeHtmlEntities(t[i][s])}return e}translate(t,e){var n;let[i,s]=t.split("."),r=(n=this.locale[i])==null?void 0:n[s];return r?e?Object.entries(e).reduce((a,[l,h])=>a.replace(new RegExp(`{{\\s*${l}\\s*}}`,"g"),h),r):r:`translation missing: ${t}`}};var gt=class{constructor({rootUrl:t,wishlistUrl:e}){this._rootUrl=t,this.route=new ut({wishlistUrl:e}),this.observer=new pt({routeUtil:this.route}),this.locale=new mt,this.watch=this.observer.watch.bind(this.observer)}getPageType(t=window.location.pathname){return this.route.parse(t).pageType}getWishlistId(t){if(!t)return null;t instanceof URL&&(t=t.pathname),t.endsWith("/")&&(t=t.substring(0,t.length-1));let e=t.replace(this._rootUrl,"/").split("/");return e.length===4?e.pop():"mine"}getProductHandle(t){var e,i;return t?(t instanceof URL&&(t=t.pathname),t.endsWith("/")&&(t=t.slice(0,-1)),(i=(e=window.decodeURI(t).split("/").pop())==null?void 0:e.split("?")[0])==null?void 0:i.split("#")[0]):null}getVariantId(t,e){var s;let i=null;if(t&&(t instanceof URL&&(t=t.pathname),i=new URLSearchParams(t.split("?")[1]).get("variant")),!i&&e)try{i=new FormData((s=e.element)!=null?s:e).get("id")}catch(r){console.warn("Failed to parse variant from product form.",r)}return i}translate(t,e){return this.locale.translate(t,e)}createComponent(t,e){var s;let i=document.createElement(t);if(e!=null&&e.dataset&&Object.entries(e==null?void 0:e.dataset).forEach(([r,n])=>{n&&(typeof n=="boolean"?i.dataset[r]="":typeof n=="object"?i.dataset[r]=JSON.stringify(n):i.dataset[r]=n)}),e!=null&&e.props&&Object.entries(e==null?void 0:e.props).forEach(([r,n])=>{if(r==="floating"&&n){let a=n,l=(a==null?void 0:a.reference)instanceof F?a.reference.element:a.reference;if(typeof l=="object"&&"id"in l){l.setAttribute("wk-id",Jt()),i[r]={...a,reference:`[wk-id="${l.getAttribute("wk-id")}"]`};return}}i[r]=n}),(s=e==null?void 0:e.wrap)!=null&&s.name){let r=this.createElement(e.wrap.name,e.wrap.props,i);return r.setAttribute("wk-skip",""),r}return i}createHeadlessComponent(t,e){var r;let i=e.host.element?e.host.element:e.host;if(!i)throw new Error("Headless host is undefined");e.dataset&&Object.entries(e.dataset).forEach(([n,a])=>{a&&(typeof a=="boolean"?i.dataset[n]="":typeof a=="object"?i.dataset[n]=JSON.stringify(a):i.dataset[n]=a)});let s=(r=window.headlessElements)==null?void 0:r.get(t);if(!s)throw new Error(`Headless element not found: ${t}`);return new s(i)}createElement(t,e={},...i){let s=Object.assign(document.createElement(t),e);return i&&s.append(...i),s}};var Gt=w("wk:events"),ft=class{constructor(){this.dispatcher=document}publish(t){let e=new CustomEvent(`wk:${t.name}`,{detail:t,bubbles:!1,cancelable:!1});Gt(`Publish: ${t.name}`,{message:t,event:e}),this.dispatcher.dispatchEvent(e)}once(t,e){this.subscribe(t,e,{once:!0})}subscribe(t,e,i){t.startsWith("wk:")&&(t=t.replace("wk:","")),Gt(`Subscribe: ${t}`,{handler:e,options:i}),this.dispatcher.addEventListener(`wk:${t}`,s=>{let r=s;e({name:r.type.replace("wk:",""),data:r.detail.data})},{once:!!(i!=null&&i.once)})}subscribeMany(t){return Object.entries(t).map(([e,i])=>this.subscribe(e,i))}};function Zt(o,t){let e=o.items.map(i=>{let s=t.find(r=>r==null?void 0:r.id.endsWith(i.productId.toString()));return s?{id:i.id,variantId:i.variantId,product:{...Rt(s),hidden:!1},metafields:void 0}:null}).filter(i=>!!i);return{id:o.isMine?"mine":o.id,publicId:o.publicId,isMine:o.isMine,numItems:e.length,items:e}}function Yt({wishlistItem:o,productHandle:t,variantId:e}){return o?{productHandle:t,wishlistItemId:o.id,productId:o.product.id,variantId:o.variantId,inWishlist:!0}:{productHandle:t,wishlistItemId:void 0,productId:0,variantId:e,inWishlist:!1}}var Rt=o=>{var t,e,i,s;return{id:parseInt(o.id.split("/").pop()),available:o.availableForSale,compare_at_price_max:parseFloat(o.compareAtPriceRange.maxVariantPrice.amount)*100,compare_at_price_min:parseFloat(o.compareAtPriceRange.minVariantPrice.amount)*100,compare_at_price_varies:o.compareAtPriceRange.maxVariantPrice.amount!==o.compareAtPriceRange.minVariantPrice.amount,featured_image:(e=(t=o.featuredImage)==null?void 0:t.url)!=null?e:null,handle:o.handle,images:o.images.nodes.map(r=>r.url),options:o.options,price_max:parseFloat(o.priceRange.maxVariantPrice.amount)*100,price_min:parseFloat(o.priceRange.minVariantPrice.amount)*100,price_varies:o.priceRange.maxVariantPrice.amount!==o.priceRange.minVariantPrice.amount,tags:o.tags,title:o.title,type:o.productType,url:`${window.Shopify.routes.root}products/${o.handle}`,variants:o.variants.nodes.map(r=>{var n,a,l,h,d,p;return{available:r.availableForSale,currentlyNotInStock:r.currentlyNotInStock,compare_at_price:r.compareAtPrice?parseFloat(r.compareAtPrice.amount)*100:null,featured_image:r.image?{alt:r.image.altText,src:r.image.url}:null,id:parseInt(r.id.split("/").pop()),option1:r.selectedOptions[0].value,option2:(a=(n=r.selectedOptions[1])==null?void 0:n.value)!=null?a:null,option3:(h=(l=r.selectedOptions[2])==null?void 0:l.value)!=null?h:null,price:parseFloat(r.price.amount)*100,sku:r.sku,title:r.title,metafields:(p=(d=r.metafields)==null?void 0:d.reduce((g,f)=>{var b;return f!=null&&f.value?{...g,[f.namespace]:{...(b=g[f.namespace])!=null?b:{},[f.key]:f.value}}:g},{}))!=null?p:{}}}),vendor:o.vendor,metafields:(s=(i=o.metafields)==null?void 0:i.reduce((r,n)=>{var a;return n!=null&&n.value?{...r,[n.namespace]:{...(a=r[n.namespace])!=null?a:{},[n.key]:n.value}}:r},{}))!=null?s:{}}};function Ot({wishlist:o,productHandle:t,productId:e,variantId:i,mulitVariantMode:s}){return o.items.find(r=>{let n=e&&r.product.id===e,a=t&&r.product.handle===t;return(n||a)&&(!i||!s||r.variantId===i)})}var Ft=1,Xt={shopify:`wk-shopify-v${Ft}`,storefront:`wk-storefront-v${Ft}`,wishlist:`wk-wishlist-v${Ft}`};var ae=()=>{let o=w("wk:cache"),t=Object.values(Xt);caches.keys().then(e=>Promise.all(e.map(i=>{if(!t.includes(i))return o("Delete old cache",{cacheName:i}),caches.delete(i)})))};ae();var P,A,x,W,O,D=class{constructor(t){u(this,P);u(this,A);u(this,x,new Map);u(this,W);u(this,O);m(this,O,Xt[t.name]),m(this,W,w(`wk:cache:${t.name}`)),this.initCache({name:c(this,O)})}async initCache({name:t}){if(!c(this,P)){if(c(this,A))return c(this,A);try{m(this,A,caches.open(t)),m(this,P,await c(this,A)),m(this,A,void 0),c(this,W).call(this,"Cache initialised")}catch(e){console.warn("Failed to open cache.",e)}}}async withCache(t,e,i){c(this,A)&&await c(this,A);let s=this.hashKey(t),r=d=>i(d).then(async p=>(c(this,W).call(this,"Fetched from remote",{cacheKey:s,strategy:e,value:p}),c(this,x).delete(s),await this.setItemInCache(s,e,p),p)),n=d=>this.getItemInCache(s).then(async p=>{if(p){let g=this.getCacheInfo(p.headers);if(g.stale&&g.revalidate)return c(this,W).call(this,"Revalidate while stale",{cacheKey:s,strategy:e,cacheInfo:g}),c(this,x).delete(s),r(d),p.json().then(({value:f})=>f);if(!g.stale)return c(this,W).call(this,"Serve cached value",{cacheKey:s,strategy:e,cacheInfo:g}),c(this,x).delete(s),p.json().then(({value:f})=>f)}return c(this,W).call(this,"Missed cache",{cacheKey:s,strategy:e}),r(d)}),a=c(this,x).get(s);if(a)return a.promise;let l=new AbortController,h=n(l.signal);return c(this,x).set(s,{promise:h,controller:l}),h}async setItemInCache(t,e,i){if(!c(this,P)||e==="no-store")return i;let s=`https://wishlistking.dev/${t}`,r=new Request(s),n=new Response(JSON.stringify({value:i}));return n.headers.set("cache-control",e),n.headers.set("cache-put-date",new Date().toUTCString()),await c(this,P).put(r,n),i}async getItemInCache(t){if(!c(this,P))return;let e=`https://wishlistking.dev/${t}`,i=new Request(e);return c(this,P).match(i)}getCacheInfo(t){var r;let e={stale:!0,revalidate:!1},i=t.get("cache-control"),s=t.get("cache-put-date");return!i||!s?e:(r=i.toLocaleLowerCase().split(",").map(n=>n.trim()).reduce((n,a)=>{var l,h;if(a.startsWith("max-age=")){let d=parseInt((l=a.split("=").pop())!=null?l:"0")*1e3;return{...n,stale:Date.now()-new Date(s).getTime()>d}}if(a.startsWith("stale-while-revalidate=")){let d=parseInt((h=a.split("=").pop())!=null?h:"0")*1e3;return{...n,revalidate:Date.now()-new Date(s).getTime()<d}}return n},e))!=null?r:e}hashKey(t){let e=Array.isArray(t)?t:[t],i="";for(let s of e)s!=null&&(typeof s=="object"?i+=JSON.stringify(s):i+=s.toString());return encodeURIComponent(i)}async clear(t=!1){if(c(this,A)&&await c(this,A),!c(this,P))return;c(this,W).call(this,"Clear cache",{name:c(this,O),force:t}),t&&(c(this,x).forEach(i=>{c(this,W).call(this,"Abort pending request",{name:c(this,O)}),i.controller.abort("Forced cache clear")}),c(this,x).clear());let e=await c(this,P).keys();for(let i of e)await c(this,P).delete(i),c(this,W).call(this,"Deleted from cache",{name:c(this,O),key:i})}};P=new WeakMap,A=new WeakMap,x=new WeakMap,W=new WeakMap,O=new WeakMap;var z,H=class{constructor(t){u(this,z);m(this,z,t)}subscribe(t){let e=c(this,z).call(this,new Nt(t));return new Mt(()=>{e==null||e()})}};z=new WeakMap;var tt,Nt=class{constructor(t){u(this,tt);m(this,tt,t)}next(t){c(this,tt).call(this,t)}};tt=new WeakMap;var et,Mt=class{constructor(t){u(this,et);m(this,et,t)}unsubscribe(){var t;(t=c(this,et))==null||t.call(this)}};et=new WeakMap;var S=w("wk:state"),v,C,N,T,M,st,E,y,it,zt,te,_,yt=class{constructor({wishlistApi:t,shopifyApi:e,storefrontApi:i,settings:s,events:r,utils:n}){u(this,y);u(this,v);u(this,C);u(this,N);u(this,T);u(this,M);u(this,st);u(this,E);m(this,v,t),m(this,C,e),m(this,N,i),m(this,M,s),m(this,T,r),m(this,st,n)}async revalidate(t=!1){S("Revalidate wishlist state"),await this.clearCache(t),c(this,T).publish({name:"state:refetch"})}observeWishlist({wishlistId:t}){return new H(e=>{let i={id:t,isMine:t==="mine",items:[],numItems:0},s=()=>{c(this,v).loadWishlist({wishlistId:t}).then(({wishlist:n})=>{JSON.stringify(n)!==JSON.stringify(i)&&(i=n,S("Update wishlist state",{wishlistId:t,nextState:n}),e.next(n)),m(this,E,void 0)})},r=n=>{var l;if(!i||!((l=n.data)!=null&&l.stateAction))return;let a=I(this,y,zt).call(this,i,n.data.stateAction);S("Update wishlist state (optimistic)",{wishlistId:t,optimisticState:a}),e.next(a)};c(this,T).subscribe("state:refetch",s),c(this,T).subscribe("state:action",r),s()})}observeProductInfo({productHandle:t,variantId:e}){return new H(i=>{let s;this.observeWishlist({wishlistId:"mine"}).subscribe(r=>{let n=Ot({wishlist:r,productHandle:t,variantId:e,mulitVariantMode:c(this,M).general.wishlistMode==="VARIANT"}),a=Yt({wishlistItem:n,productHandle:t,variantId:e});JSON.stringify(a)!==JSON.stringify(s)&&(s=a,i.next(a))})})}observeShopifyCart({cacheStrategy:t}){let e={token:"",total_price:0,total_weight:0,item_count:0,items:[],requires_shipping:!0,currency:"USD",items_subtotal_price:0};return new H(i=>{let s=()=>{S("Refetch cart"),c(this,C).loadCart({cacheStrategy:t}).then(r=>{JSON.stringify(r)!==JSON.stringify(e)&&(e=r,S("Update cart state (remote)",{nextState:r}),i.next(r))})};c(this,T).subscribe("state:refetch",s),s()})}async addWishlistItem(t){if(c(this,E))return;S("Add wishlist item",{params:t});let e=typeof t.variantId=="string"?parseInt(t.variantId):t.variantId,i=t.productHandle;if(!i)throw new Error("Product handle is required");I(this,y,_).call(this,"wishlist:add",{productHandle:i,variantId:e}),I(this,y,it).call(this,{name:"wishlist:add",state:"submitting",body:{productHandle:i,variantId:e}});let s=await c(this,N).loadProductIdByHandle({productHandle:i}),{wishlistItem:r,sessionId:n}=await c(this,v).addItem({productId:s,variantId:e}).catch(a=>{throw console.error(a),this.revalidate(),a});return n&&c(this,T).publish({name:"app:init-sid",data:{sessionId:n}}),S("Added wishlist item",{params:t,wishlistItem:r}),this.revalidate(),this.publishEvent({eventName:"wishlist:add:success",wishlistId:"mine",productId:s,variantId:e}),{wishlistItem:r}}async saveForLater(t){var l;if(c(this,E))return;let e=typeof t.variantId=="string"?parseInt(t.variantId):t.variantId,i=t.productHandle;if(S("Save for later",{params:t}),!i)throw new Error("Product handle is required");if(!e)throw new Error("Variant ID is required");I(this,y,_).call(this,"wishlist:save-for-later",{productHandle:i,variantId:e});let[s,{wishlist:r}]=await Promise.all([c(this,N).loadProductIdByHandle({productHandle:i}),c(this,v).loadWishlist({wishlistId:"mine"})]),n=Ot({wishlist:r,productHandle:i,variantId:e,mulitVariantMode:!0}),a;if(n!=null&&n.variantId||(a=await this.addWishlistItem(t).then(h=>h==null?void 0:h.wishlistItem)),!(n!=null&&n.id)&&!(a!=null&&a.id))throw new Error("Could not save for later");return S("Saved for later",{params:t,wishlistItem:n}),this.publishEvent({eventName:"wishlist:save-for-later:success",wishlistId:"mine",productId:s,variantId:e}),{id:(l=n==null?void 0:n.id)!=null?l:a==null?void 0:a.id,productId:s,variantId:e}}async updateWishlistItem({wishlistItemId:t,changes:e}){if(c(this,E))return;S("Update wishlist item",{wishlistItemId:t,changes:e});let i=typeof e.variantId=="string"?parseInt(e.variantId):e.variantId;I(this,y,_).call(this,"wishlist:change-variant",{wishlistItemId:t,variantId:i}),I(this,y,it).call(this,{name:"wishlist:change-variant",state:"submitting",body:{wishlistItemId:t,variantId:i}});let{wishlistItem:s}=await c(this,v).updateItem({wishlistItemId:t,changes:{variantId:i}}).catch(r=>{throw console.error(r),this.revalidate(),r});return S("Updated wishlist item",{wishlistItemId:t,changes:e,wishlistItem:s}),this.revalidate(),this.publishEvent({eventName:"wishlist:change-variant:success",wishlistId:"mine",productId:s.product.id,variantId:i}),{wishlistItem:s}}async removeWishlistItem({wishlistItemId:t}){if(c(this,E))return;S("Remove wishlist item",{wishlistItemId:t}),I(this,y,_).call(this,"wishlist:remove",{wishlistItemId:t}),I(this,y,it).call(this,{name:"wishlist:remove",state:"submitting",body:{wishlistItemId:t}});let{wishlistItem:e}=await c(this,v).removeItem({wishlistId:"mine",wishlistItemId:t}).catch(i=>{throw console.error(i),this.revalidate(),i});return S("Removed wishlist item",{wishlistItemId:t,wishlistItem:e}),this.revalidate(),this.publishEvent({eventName:"wishlist:remove:success",wishlistId:"mine",productId:e.product.id,variantId:e.selectedVariantId}),{wishlistItem:e}}async clearWishlist(){c(this,E)||(S("Clear wishlist"),I(this,y,_).call(this,"wishlist:clear"),I(this,y,it).call(this,{name:"wishlist:clear",state:"submitting"}),await c(this,v).clearWishlist().catch(t=>{throw console.error(t),this.revalidate(),t}),S("Cleared wishlist"),this.revalidate(),this.publishEvent({eventName:"wishlist:clear:success",wishlistId:"mine"}))}async clearCache(t=!1){S("Clear cache"),await c(this,C).clearCache(t),await c(this,v).clearCache(t)}async addToCart({wishlistId:t,wishlistItemId:e,variantId:i,quantity:s=1,properties:r,sectionsToRender:n,sectionsUrl:a}){t==="mine"&&I(this,y,_).call(this,"wishlist:add-to-cart");let l=await c(this,C).addToCart({id:i,quantity:s,properties:r,sections:n,sections_url:a?encodeURI(a):void 0}),[{wishlist:h},d]=await Promise.all([c(this,v).loadWishlist({wishlistId:t,cacheStrategy:"no-store"}),c(this,C).loadCart({cacheStrategy:"no-store"})]),p=h.items.find(g=>g.id===e);return this.revalidate(),this.publishEvent({eventName:"wishlist:add-to-cart:success",wishlistId:t,productId:p.product.id,variantId:i}),{wishlist:h,wishlistItem:p,cart:d,cartResponse:l}}async addAllToCart({wishlistId:t,sectionsToRender:e,sectionsUrl:i}){var l;if(c(this,E))return;t==="mine"&&I(this,y,_).call(this,"wishlist:add-to-cart");let{wishlist:r}=await c(this,v).loadWishlist({wishlistId:t,cacheStrategy:"no-store"}),n=r.items.filter(h=>!!h.variantId).filter(h=>{let d=h.product.variants.find(p=>p.id===h.variantId);return!!(d!=null&&d.available)});if(!n.length)return{cartResponse:null,wishlistItems:[]};let a=await c(this,C).addToCart({items:(l=n.map(h=>({id:h.variantId,quantity:1})))!=null?l:[],sections:e,sections_url:i?encodeURI(i):void 0});return this.revalidate(),this.publishEvent({eventName:"wishlist:add-all-to-cart:success",wishlistId:"mine"}),{cartResponse:a,wishlistItems:n}}async shareWishlist({wishlistId:t,title:e,text:i}){if(c(this,E))return;t==="mine"&&I(this,y,_).call(this,"wishlist:share");let s={url:c(this,st).url.getPublicWishlistUrl(t),title:e,text:i},r={webShare:!1,clipboard:!1};try{/Mobile|Android|BlackBerry/i.test(navigator.userAgent)&&(await navigator.share(s),r.webShare=!0)}catch(n){r.webShare=!1}if(!r.webShare)try{await navigator.clipboard.writeText(s.url),r.clipboard=!0}catch(n){r.clipboard=!1}return this.publishEvent({eventName:"wishlist:share:success",wishlistId:t}),r}async publishEvent({eventName:t,wishlistId:e,productId:i,variantId:s}){let[r,n]=await Promise.all([e?c(this,v).loadWishlist({wishlistId:e}).then(({wishlist:l})=>l):Promise.resolve(void 0),i?c(this,N).loadProduct({productId:i}).then(l=>l?Rt(l):null):Promise.resolve(void 0)]),a=s?n==null?void 0:n.variants.find(l=>l.id===s):void 0;c(this,T).publish({name:t,data:{wishlist:r,product:n,variant:a}})}};v=new WeakMap,C=new WeakMap,N=new WeakMap,T=new WeakMap,M=new WeakMap,st=new WeakMap,E=new WeakMap,y=new WeakSet,it=function(t){m(this,E,t),c(this,T).publish({name:"state:action",data:{stateAction:t}})},zt=function(t,e){var i,s,r,n,a,l;switch(e.name){case"wishlist:add":return{...t,items:[{id:`temp-${Date.now()}`,variantId:(s=(i=e.body)==null?void 0:i.variantId)!=null?s:0,product:{id:(n=(r=e.body)==null?void 0:r.productId)!=null?n:0,handle:(l=(a=e.body)==null?void 0:a.productHandle)!=null?l:"",variants:[]}},...t.items],numItems:t.items.length+1};case"wishlist:remove":return{...t,items:t.items.filter(h=>{var d;return h.id!==((d=e.body)==null?void 0:d.wishlistItemId)}),numItems:t.items.length-1};default:return t}},te=function(t,e){var s;if(c(this,M).general.wishlistAccessMode==="UNRESTRICTED"||c(this,v).hasCustomer)return!1;if((s=ce[c(this,M).general.wishlistAccessMode])==null?void 0:s.includes(t))return["wishlist:load"].includes(t)||c(this,T).publish({name:"wishlist:login-required",data:{action:t,...e}}),!0},_=function(t,e){if(I(this,y,te).call(this,t,e))throw new Error("Wishlist requires login")};var ce={REQUIRE_LOGIN_BEFORE_USE:["wishlist:load","wishlist:add","wishlist:remove","wishlist:change-variant","wishlist:clear","wishlist:add-to-cart","wishlist:share","wishlist:view","wishlist:save-for-later"],REQUIRE_LOGIN_TO_VIEW_LIST:["wishlist:view"]};var wt=class{constructor(t){this.rootUrl=t.rootUrl,this.shopDomain=t.shopDomain,this.wishlistUrl=t.wishlistUrl,this.placeholderImageUrl=t.placeholderImageUrl,this.fileUrl=t.fileUrl}getPublicWishlistUrl(t){return`https://${this.shopDomain}${this.wishlistUrl}/${t}`}getFileUrl(t=""){return`https:${this.fileUrl.split("?")[0]}${t}`}getImageUrl(t,e){var s,r;if(!t)return(s=this.placeholderImageUrl)!=null?s:"";let i=this.getImage(t);return i!=null&&i.src?this.appendSize(i.src,e):(r=this.placeholderImageUrl)!=null?r:""}getImage(t){var e,i,s;if(t.hasOwnProperty("sku"))return{src:(i=(e=t.featured_image)==null?void 0:e.src)!=null?i:""};if(t.variants){let r=t;return{src:(s=r.featured_image)!=null?s:r.images[0]}}else if(t.hasOwnProperty("src"))return{src:t.src};return null}appendSize(t,e){let i=new URL(t.startsWith("//")?`https://${t}`:t);return e!=null&&e.width&&i.searchParams.set("width",e==null?void 0:e.width.toString()),e!=null&&e.height&&i.searchParams.set("height",e==null?void 0:e.height.toString()),i.href}getVariantUrl(t,e){if(t)return e?t+`?variant=${e}`:t}handlelize(t){return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/([^\w]+|\s+)/g,"-").replace(/\-\-+/g,"-").replace(/(^-+|-+$)/g,"").toLowerCase()}};var bt=class{constructor(t){this.placeholderRegex=/\{\{\s*(\w+)\s*\}\}/;var e,i;this.moneyFormat=(e=t.moneyFormat)!=null?e:"${{amount}}",this.moneyFormatWithCurrency=(i=t.moneyFormatWithCurrency)!=null?i:"${{amount}} USD"}formatMoney(t,e){var r,n;let i=(r=e==null?void 0:e.withCurrency)!=null?r:!1;typeof t=="string"&&(t=parseInt(t.replace(".","")));let s=this.formatCents(t,(n=this.moneyFormat.match(this.placeholderRegex))==null?void 0:n[1],e==null?void 0:e.withoutTrailingZeros);return(i?this.moneyFormatWithCurrency:this.moneyFormat).replace(this.placeholderRegex,s)}formatCents(t,e,i){switch(e){case"amount_no_decimals":return this.formatWithDelimiters(t,0);case"amount_with_comma_separator":return i?this.formatWithDelimiters(t,2,".",",").replace(",00",""):this.formatWithDelimiters(t,2,".",",");case"amount_no_decimals_with_comma_separator":return this.formatWithDelimiters(t,0,".",",");case"amount":default:return i?this.formatWithDelimiters(t,2).replace(".00",""):this.formatWithDelimiters(t,2)}}formatWithDelimiters(t,e=2,i=",",s="."){if(isNaN(t)||t==null)return"0";let n=(t/100).toFixed(e).split("."),a=n[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,`$1${i}`),l=n[1]?s+n[1]:"";return a+l}};var St=class{getFormState({product:t,options:e,autoSelect:i=!1,change:s}){let r=this.getSelectedOptions({product:t,options:e,change:s,autoSelect:i}),n=r&&Object.values(r).every(h=>!!h),a=this.getOptionsWithValues({product:t,selectedOptions:r});return{selectedVariant:this.getVariantByOptions({product:t,options:r,optionsWithValues:a}),selectedOptions:r,hasSelection:n,optionsWithValues:a,hasOnlyDefaultVariant:t.options.length===1&&t.options[0].name==="Title"&&t.options[0].values.length==1}}getSelectedOptions({product:t,options:e,autoSelect:i,change:s={}}){let r=Object.fromEntries(Object.entries({...e,...s}).map(([d,p],g)=>{var f;return!p&&((f=t.options[g])==null?void 0:f.values.length)===1?[d,t.options[g].values[0]]:[d,p]}));if(!i)return r;let n=Object.keys(s).pop(),a=Object.fromEntries(n?Object.entries(r).filter(([d])=>n>d):Object.entries(e).filter(([,d])=>!!d)),l=Object.fromEntries(Object.entries(r).filter(([d])=>!(d in a)));return Object.keys(l).reduce((d,p)=>{var f;let g=this.getAllVariantsByOptions({product:t,options:d});return g.length?{...d,[p]:((f=g.find(b=>b.available))!=null?f:g[0])[p]}:{...d,[p]:null}},a)}getVariantOptions({variant:t}){var e,i,s;return{option1:(e=t==null?void 0:t.option1)!=null?e:null,option2:(i=t==null?void 0:t.option2)!=null?i:null,option3:(s=t==null?void 0:t.option3)!=null?s:null}}getOptionsWithValues({product:t,selectedOptions:e={}}){return t.options.map((i,s)=>{var h;let r=`option${s+1}`,n=this.getUnavailableOptionValues({product:t,optionKey:r,selectedOptions:e,values:i.values}),a=this.getSoldoutOptionValues({product:t,optionKey:r,selectedOptions:e,values:i.values}),l=(h=e==null?void 0:e[r])!=null?h:null;return{...i,selectedValue:l,soldoutValues:a,unavailableValues:n}})}getSoldoutOptionValues({product:t,optionKey:e,values:i,selectedOptions:s={}}){let r=Object.fromEntries(Object.entries(s).filter(([n])=>n<e));return i.filter(n=>{let a=t.variants.filter(l=>this.matchesVariant({variant:l,options:{...r,[e]:n}}));return a.length?a.every(l=>!l.available):!1})}getUnavailableOptionValues({product:t,optionKey:e,values:i,selectedOptions:s={}}){let r=Object.fromEntries(Object.entries(s).filter(([n])=>n<e));return i.filter(n=>t.variants.every(a=>!this.matchesVariant({variant:a,options:{...r,[e]:n}})))}getFirstAvailableVariant({product:t}){var e;return(e=t.variants.find(i=>i.available))!=null?e:null}getSelectedVariant({product:t,variantId:e}){var i;return(i=t.variants.find(s=>s.id===e))!=null?i:null}matchesVariant({variant:t,options:e}){return(!(e!=null&&e.option1)||e.option1===t.option1)&&(!(e!=null&&e.option2)||e.option2===t.option2)&&(!(e!=null&&e.option3)||e.option3===t.option3)}getFormData({form:t,product:e}){let i=new FormData(t);return{quantity:this.getFormQuantity({form:t}),options:this.getFormOptions({formData:i,product:e})}}getFormQuantity({form:t}){var s;let i=(s=new FormData(t).get("quantity"))==null?void 0:s.toString();return i?parseInt(i):1}getFormProperties({form:t}){let e=new FormData(t);return Array.from(e.entries()).reduce((i,s)=>{if(!s[0].startsWith("properties["))return i;let r=s[0].replace("properties[","").replace("]","");return{...i,[r]:`${s[1]}`}},{})}getVariantByOptions({product:t,options:e,optionsWithValues:i}){var r;let s=Object.entries(e).reduce((n,[,a],l)=>(n[l]=a,n),new Array(3).fill(null));return(r=t.variants.find(n=>s.every((a,l)=>i[l]?n[`option${l+1}`]===a:!0)))!=null?r:null}getAllVariantsByOptions({product:t,options:e}){var s;let i=Object.entries(e).reduce((r,[,n],a)=>(r[a]=n,r),new Array(3).fill(null));return(s=t.variants.filter(r=>i.every((n,a)=>!n||r[`option${a+1}`]===n)))!=null?s:[]}getFormOptions({formData:t,product:e}){return Array.from(t.entries()).reduce((i,[s,r])=>{var l;let n=(l=s.match(/\[(.*?)\]/))==null?void 0:l[1];if(!n)return i;let a=e.options.findIndex(h=>h.name===n)+1;if(a>0){let h=`option${a}`;i[h]=r.toString()||null}return i},{})}getInputOption({input:t,product:e}){var r;let i=(r=t.name.match(/\[(.*?)\]/))==null?void 0:r[1];if(!i)return null;let s=e.options.findIndex(n=>n.name===i)+1;return s>0?{[`option${s}`]:t.value.toString()}:null}};var j,rt,$,q,nt,ot,at,It=class{constructor(t){u(this,j);u(this,rt);u(this,$);u(this,q);u(this,nt);u(this,ot,[]);u(this,at,[]);m(this,q,t.country),m(this,$,t.language),m(this,j,`https://${t.storeName}.myshopify.com/api/${t.version}/graphql.json`),m(this,rt,{accept:"application/json","content-type":"application/json","x-shopify-storefront-access-token":t.accessToken}),m(this,nt,new D({name:"storefront"}))}setFields({productMetafields:t,variantMetafields:e}){t&&m(this,ot,t),e&&m(this,at,e)}loadProduct({productId:t,cacheStrategy:e="public, max-age=1, stale-while-revalidate=10"}){let i=` fragment productMetafields on Product { metafields(identifiers: [${c(this,ot).map(r=>`{namespace: "${r.namespace}", key: "${r.key}"}`).join(",")}]) { key value namespace } } `,s=` fragment variantMetafields on ProductVariant { metafields(identifiers: [${c(this,at).map(r=>`{namespace: "${r.namespace}", key: "${r.key}"}`).join(",")}]) { key value namespace } } `;return this.fetch({cacheStrategy:e,body:JSON.stringify({query:` query @inContext(language: ${c(this,$)}, country: ${c(this,q)}) { product(id: "gid://shopify/Product/${t}") { ...productFields ...productMetafields } } ${he} ${i} ${s} `})}).then(({data:r,errors:n})=>n?(console.warn("Could not load product data",n),null):r.product)}loadProductIdByHandle({productHandle:t}){return this.fetch({cacheStrategy:"public, max-age=3600, stale-while-revalidate=86400",body:JSON.stringify({query:` query @inContext(language: ${c(this,$)}, country: ${c(this,q)}) { productByHandle(handle: "${t}") { id } } `})}).then(({data:e,errors:i})=>{var s;return i?(console.warn("Could not load product id",i),0):e.productByHandle?parseInt((s=e.productByHandle)==null?void 0:s.id.split("/").pop()):0})}fetch(t){let e={...c(this,rt),...t.headers},i=t.body,s=[c(this,j),i,e];return c(this,nt).withCache(s,t.cacheStrategy,async r=>{let n=await window.fetch(c(this,j),{method:"POST",headers:e,body:i,signal:r});if(n.ok)return n.json();throw Error(`Error ${n.status}`)})}};j=new WeakMap,rt=new WeakMap,$=new WeakMap,q=new WeakMap,nt=new WeakMap,ot=new WeakMap,at=new WeakMap;var le=` fragment variantFields on ProductVariant { availableForSale compareAtPrice { amount } currentlyNotInStock id image { altText url } price { amount } selectedOptions { name value } title unitPrice { amount } sku } `,he=` ${le} fragment productFields on Product { availableForSale compareAtPriceRange { maxVariantPrice { amount } minVariantPrice { amount } } featuredImage { altText url } handle id onlineStoreUrl options { name values optionValues { id name swatch { color image { id alt ...on MediaImage { image { url } } } } } } priceRange { maxVariantPrice { amount } minVariantPrice { amount } } productType tags title vendor images(first: 100) { nodes { altText url } } variants(first: 250) { nodes { ...variantFields ...variantMetafields } } } `;var ct,K,B=class{constructor(t){u(this,ct);u(this,K);this.host=t.host,this.headers={"content-type":"application/json"},m(this,K,new D({name:t.name})),m(this,ct,w(`wk:api:${t.name}`))}fetch(t){var d;let{method:e="GET",path:i,query:s,body:r}=t,n=this.host+i+this.getQuerystring(s),a={...this.headers,...t.headers},l=[e,n,r,a],h=(d=t.cacheStrategy)!=null?d:"no-store";return c(this,K).withCache(l,h,async p=>{c(this,ct).call(this,"Fetch from remote",{method:e,url:n,headers:a});let g=await window.fetch(n,{method:e,headers:a,body:r,signal:p});if(g.ok)return g.json();throw Error(`Error ${g.status}`)})}getQuerystring(t){if(!t)return"";let e=new URLSearchParams;return Object.entries(t).forEach(([i,s])=>{Array.isArray(s)?s.forEach(r=>e.append(i,r)):s&&e.append(i,s)}),"?"+e.toString()}get({path:t,query:e,headers:i,cacheStrategy:s}){return this.fetch({method:"GET",path:t,query:e,headers:i,cacheStrategy:s})}post({path:t,query:e,body:i,headers:s}){return this.fetch({method:"POST",path:t,query:e,body:i?JSON.stringify(i):void 0,headers:s})}put({path:t,query:e,body:i,headers:s}){return this.fetch({method:"PUT",path:t,query:e,body:i?JSON.stringify(i):void 0,headers:s})}delete({path:t,query:e,body:i,headers:s}){return this.fetch({method:"DELETE",path:t,query:e,body:i?JSON.stringify(i):void 0,headers:s})}clearCache(t=!1){return c(this,K).clear(t)}};ct=new WeakMap,K=new WeakMap;var de=new Promise((o,t)=>{window.Shopify.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],e=>{e||!window.Shopify.customerPrivacy?t(e||new Error("Shopify.customerPrivacy not available")):o(window.Shopify.customerPrivacy)})}),vt=o=>{de.then(t=>{o({marketingAllowed:t.marketingAllowed(),saleOfDataAllowed:t.saleOfDataAllowed(),analyticsAllowed:t.analyticsProcessingAllowed(),preferencesAllowed:t.preferencesProcessingAllowed()})}).catch(t=>{console.warn("Failed to load Customer Privacy API",t)}),document.addEventListener("visitorConsentCollected",t=>{"detail"in t&&o(t.detail)})};var lt,At,Pt=class extends B{constructor(e){super({...e,name:"wishlist"});u(this,lt);u(this,At);m(this,lt,e.storefrontApi),this.headers={"content-type":"application/json"},e.shop&&(this.headers["x-appmate-shp"]=e.shop),e.sessionId&&(this.headers["x-appmate-sid"]=e.sessionId),e.customerId&&(this.headers["x-appmate-cid"]=e.customerId.toString()),e.trackingSource&&(this.headers["x-appmate-src"]=e.trackingSource),vt(i=>{m(this,At,i),this.headers["x-appmate-vca"]=i.analyticsAllowed.toString(),this.headers["x-appmate-vcm"]=i.marketingAllowed.toString()})}get hasSession(){return!!this.headers["x-appmate-sid"]||!!this.headers["x-appmate-cid"]}get hasCustomer(){return!!this.headers["x-appmate-cid"]}setSessionId(e){this.headers["x-appmate-sid"]=e}clearSessionId(){delete this.headers["x-appmate-sid"]}async loadWishlist({wishlistId:e,cacheStrategy:i="public, max-age=60, stale-while-revalidate=86400"}){return e==="mine"&&!this.hasSession?{wishlist:{id:e,isMine:!0,numItems:0,items:[]}}:this.get({path:`/wishlists/${e}`,cacheStrategy:i}).then(({wishlist:r})=>Promise.all(r.items.map(n=>c(this,lt).loadProduct({productId:n.productId,cacheStrategy:i}))).then(n=>({wishlist:Zt(r,n.filter(a=>!!a))})))}addItem({productId:e,variantId:i}){if(typeof e=="string"&&(e=parseInt(e)),typeof i=="string"&&(i=parseInt(i)),!this.hasSession&&this._pendingSessionId)return this._pendingSessionId.then(()=>this.addItem({productId:e,variantId:i}));let s=this.post({path:"/wishlists/mine/items",body:{productId:e,variantId:i}}).then(r=>(r.sessionId&&(this.setSessionId(r.sessionId),this._pendingSessionId=void 0),r));return this.hasSession||(this._pendingSessionId=s),s}updateItem({wishlistItemId:e,changes:i}){return this.put({path:"/wishlists/mine/items",body:{changes:{...i,wishlistItemId:e}}})}removeItem({wishlistId:e,wishlistItemId:i}){return this.delete({path:`/wishlists/${e}/items`,body:{wishlistItemId:i}})}clearWishlist(){return this.delete({path:"/wishlists/mine"})}};lt=new WeakMap,At=new WeakMap;var Wt=class extends B{constructor(t){super({...t,name:"shopify"})}loadCart(t){if(this.pendingCart)return this.pendingCart;let e=this.get({path:"/cart.js",cacheStrategy:t==null?void 0:t.cacheStrategy}).then(i=>(this.pendingCart=void 0,i));return this.pendingCart=e,e}addToCart(t){return this.post({path:"/cart/add.js",body:t})}};var Tt,J=class{constructor({host:t,shop:e,sessionId:i,customerId:s}){u(this,Tt);this.host=t,this.shop=e,this.customerId=s,this.sessionId=i,this.eventNames=new Map([["viewWishlist","wishlist_viewed"],["addToCart","product_added_to_cart"],["shareWishlist","wishlist_shared"]]),vt(r=>{m(this,Tt,r)})}setSession(t){this.sessionId=t}clearSession(){this.sessionId=void 0}async track({eventName:t,wishlist:e,product:i,variant:s,quantity:r,source:n}){var l,h;if(!this.sessionId&&!this.customerId)return!1;let a=this.eventNames.get(t);return!a||!e?!1:window.fetch(this.host+"/notify",{method:"POST",headers:{"content-type":"application/json","x-appmate-shp":this.shop,"x-appmate-sid":(l=this.sessionId)!=null?l:"","x-appmate-cid":(h=this.customerId)!=null?h:""},body:JSON.stringify({event:a,wid:e.publicId,pid:i==null?void 0:i.id,vid:s==null?void 0:s.id,qty:r,src:n})}).then(()=>!0).catch(d=>!1)}getQuerystring(t){if(!t)return"";let e=new URLSearchParams;return Object.entries(t).forEach(([i,s])=>{Array.isArray(s)?s.forEach(r=>e.append(i,r)):s&&e.append(i,s)}),"?"+e.toString()}};Tt=new WeakMap;var{gtag:ee,dataLayer:ie}=window,Et=class{constructor({currency:t}){this.currency=t,this.eventNames=new Map([["addToWishlist","add_to_wishlist"]])}async track({eventName:t,product:e,variant:i,quantity:s=1}){var a,l,h;let r=this.eventNames.get(t);if(!r||!e)return!1;let n=((a=i==null?void 0:i.price)!=null?a:e.variants[0].price)/100;return ee?(ee("event",r,{currency:this.currency,value:n,items:[{item_id:(l=(i==null?void 0:i.sku)||(i==null?void 0:i.id))!=null?l:e.id,item_name:e.title,affiliation:"Wishlist King",item_category:e.type,item_brand:e.vendor,item_variant:i==null?void 0:i.title,item_quantity:s,item_price:n}]}),!0):ie?(ie.push({event:r,ecommerce:{currency:this.currency,value:n,items:[{item_id:(h=(i==null?void 0:i.sku)||(i==null?void 0:i.id))!=null?h:e.id,item_name:e.title,affiliation:"Wishlist King",item_category:e.type,item_brand:e.vendor,item_variant:i==null?void 0:i.title,item_quantity:s,item_price:n}]}}),!0):!1}};var se=w("wk:tracking:klaviyo"),kt=class{constructor({customerEmail:t,urlUtil:e,moneyUtil:i}){this.customerEmail=t,this.urlUtil=e,this.moneyUtil=i,this.eventNames=new Map([["addToWishlist","Added To Wishlist"],["removeFromWishlist","Removed From Wishlist"],["clearWishlist","Cleared Wishlist"]])}async track({eventName:t,wishlist:e,product:i,variant:s,quantity:r=1}){var p,g,f,b,k,U,R,G,Z;let n=this.eventNames.get(t);if(!n||!e||!i)return!1;let a=e.items.slice().reverse().map(dt=>dt.product.id),l={$email:this.customerEmail,WishlistUrl:this.urlUtil.getPublicWishlistUrl(e.id),WishlistProductIDs:a};se("Identify",l),(p=window.klaviyo)==null||p.push(["identify",l]);let h=((g=s==null?void 0:s.price)!=null?g:!i.price_varies)?i.price_min:void 0,d={URL:this.urlUtil.getVariantUrl(i.url,s==null?void 0:s.id),Name:i.title,ProductID:i.id,VariantID:(f=s==null?void 0:s.id)!=null?f:null,SKU:(b=s==null?void 0:s.sku)!=null?b:null,Tags:i.tags,Brand:i.vendor,ImageURL:this.urlUtil.getImageUrl((k=s==null?void 0:s.featured_image)!=null&&k.src?s:i,{width:1e3}),Price:h?h/100:null,PriceFormatted:h?this.moneyUtil.formatMoney(h):null,CurrencyCode:(G=(R=(U=window.Shopify)==null?void 0:U.currency)==null?void 0:R.active)!=null?G:null,Quantity:r,WishlistUrl:this.urlUtil.getPublicWishlistUrl(e.id),WishlistProductIDs:a};return se("Track",n,d),(Z=window.klaviyo)==null||Z.push(["track",n,d]),!0}};var{fbq:re}=window,xt=class{constructor({currency:t}){this.currency=t,this.eventNames=new Map([["addToWishlist","AddToWishlist"]])}async track({eventName:t,product:e,variant:i}){let s=this.eventNames.get(t);return!s||typeof re!="function"||!e?!1:(re("track",s,{value:i==null?void 0:i.price,currency:this.currency,content_ids:[e.id],content_name:[e.title,i==null?void 0:i.title].filter(r=>!!r).join(" - "),content_category:e.type,content_type:"product_group",num_items:1}),!0)}};var ht=w("wk:tracking"),_t=class{constructor({settings:t,events:e,notifyHost:i,utils:s,theme:r,shop:n,sessionId:a,customerId:l,customerEmail:h}){this.utils=s,this.theme=r,this.services=[],ht("Init tracking"),t.integrations.wishlistAnalytics.enabled&&this.services.push(new J({host:i,shop:n,customerId:l,sessionId:a})),t.integrations.klaviyo.enabled&&h&&(ht("Add Klaviyo integration"),this.services.push(new kt({urlUtil:this.utils.url,moneyUtil:this.utils.money,customerEmail:h}))),t.integrations.metaPixel.enabled&&(ht("Add Meta Pixel integration"),this.services.push(new xt({currency:window.Shopify.currency.active}))),t.integrations.googleAnalytics.enabled&&(ht("Add Google Analytics integration"),this.services.push(new Et({currency:window.Shopify.currency.active})));let d=this.theme.getPageType(),p=g=>f=>{var b,k,U,R;return this.track({eventName:g,source:d,wishlist:(b=f.data)==null?void 0:b.wishlist,product:(k=f.data)==null?void 0:k.product,variant:(U=f.data)==null?void 0:U.variant,quantity:(R=f.data)==null?void 0:R.quantity})};e.subscribeMany({"wishlist:add-to-cart:success":p("addToCart"),"wishlist:add:success":p("addToWishlist"),"wishlist:change-variant:success":p("changeVariant"),"wishlist:clear:success":p("clearWishlist"),"wishlist:remove:success":p("removeFromWishlist"),"wishlist:share:success":p("shareWishlist"),"wishlist:page-view":p("viewWishlist")})}async track(t){return ht("Track",t),this.services.length?Promise.all(this.services.map(e=>e.track(t))):[]}setSessionId(t){let e=this.services.find(i=>i instanceof J);e&&e.setSession(t)}clearSessionId(){let t=this.services.find(e=>e instanceof J);t&&t.clearSession()}};var Q=w("wk:app"),ne=class{constructor(t){this.addToCart=t=>this.state.addToCart(t);this.addAllToCart=t=>this.state.addAllToCart(t);this.addWishlistItem=t=>this.state.addWishlistItem(t);this.saveForLater=t=>this.state.saveForLater(t);this.clearWishlist=()=>this.state.clearWishlist();this.removeWishlistItem=t=>this.state.removeWishlistItem(t);this.shareWishlist=t=>this.state.shareWishlist(t);this.updateWishlistItem=t=>this.state.updateWishlistItem(t);var i,s,r;this.config=this.parseConfig(t),this.settings=this.parseSettings(t),this.routes=this.parseRoutes(),this.customer=this.config.customer.id?{id:this.config.customer.id,email:this.config.customer.email,name:this.config.customer.name,tags:this.config.customer.tags}:null,Q("Create app",{config:this.config,settings:this.settings,customer:this.customer}),this.events=new ft,this.theme=new gt({rootUrl:this.routes.rootUrl,wishlistUrl:this.routes.wishlistUrl}),this._utils={url:new wt({rootUrl:this.routes.rootUrl,wishlistUrl:this.routes.wishlistUrl,shopDomain:this.config.shop.domain,placeholderImageUrl:this.config.products.fallbackImage,fileUrl:this.routes.fileUrl}),money:new bt({moneyFormat:this.config.shop.moneyFormat,moneyFormatWithCurrency:this.config.shop.moneyFormatWithCurrency}),product:new St};let e=new It({accessToken:this.config.storefront.accessToken,version:this.config.storefront.version,country:window.Shopify.country.toUpperCase(),language:this.config.storefront.language,storeName:this.config.shop.permanentDomain.replace(".myshopify.com","")});this._apis={wishlist:new Pt({host:this.config.routes.apiHost,shop:this.config.shop.permanentDomain,customerId:(i=this.config.customer.id)!=null?i:void 0,sessionId:this.getSessionId(),trackingSource:this.theme.getPageType(),storefrontApi:e}),shopify:new Wt({host:window.Shopify.routes.root.substring(0,window.Shopify.routes.root.length-1)}),storefront:e,tracking:new _t({notifyHost:this.config.routes.apiHost,events:this.events,shop:this.config.shop.permanentDomain,customerId:(s=this.config.customer.id)!=null?s:void 0,customerEmail:(r=this.config.customer.email)!=null?r:void 0,sessionId:this.getSessionId(),utils:this.utils,theme:this.theme,settings:this.settings})},this._state=new yt({wishlistApi:this.apis.wishlist,shopifyApi:this.apis.shopify,storefrontApi:this.apis.storefront,settings:this.settings,events:this.events,utils:this.utils}),this.initCustomerSession(),this.initUrlChangeEvents(),this.trackCurrentPage(),this.initLoginRedirect(),window.WishlistKing=this,Q("App ready"),this.events.publish({name:"app:ready",data:{}})}get state(){return this._state}get apis(){return this._apis}get utils(){return this._utils}get hasSession(){return!!this.getSessionId()||!!this.customer}get isLoggedIn(){var t;return!!((t=this.customer)!=null&&t.id)}getSessionId(){let t=window.localStorage.getItem("wk_session_id");if(t)return t;let e=window.localStorage.getItem("appmate-session");if(e)try{let i=JSON.parse(e).state.sid;return this.setSessionId(i)}catch(i){console.error(i)}}setSessionId(t){var e;return window.localStorage.setItem("wk_session_id",t),(e=this._apis)==null||e.tracking.setSessionId(t),t}clearSessionId(){var t,e;window.localStorage.removeItem("wk_session_id"),(t=this._apis)==null||t.tracking.clearSessionId(),(e=this._apis)==null||e.wishlist.clearSessionId()}async showDialog(t,e){var l;this.currentDialog&&(this.currentDialog.close(),this.currentDialog=null);let i=this.config.dialogs[t];if(!i){console.warn(`Dialog ${t} not found`);return}let{default:s,appSettings:r}=await import(window.WishlistKingAppLoaderURL),n=`wishlist-${t}-dialog`;await s.load({type:"lit-component",name:n,url:i,dependencies:[{url:r.assets.componentAccountDialogCss,order:5}]});let a=customElements.get(n);if(!a){console.warn(`Dialog ${t} not defined`);return}this.currentDialog=new a,e&&Object.assign(this.currentDialog,e),(l=this.currentDialog)==null||l.show()}initLoginRedirect(){var e,i;if(this.theme.getPageType()==="account"){let s=this.getPendingWishlistAction();if(s){Q("Inject redirect for pending action",{pending:s});let r=document.getElementById("customer_login"),n=document.getElementById("create_customer");(i=r!=null?r:n)==null||i.insertAdjacentHTML("beforeend",`<input type="hidden" name="return_to" value="${(e=s.origin)!=null?e:this.routes.wishlistUrl}">`)}}}trackCurrentPage(){if(this.theme.getPageType()==="wishlist"){let e=this.theme.getWishlistId(window.location.pathname);e&&this.state.publishEvent({eventName:"wishlist:page-view",wishlistId:e}).catch(i=>{console.warn("Failed to track wishlist page view",i)})}}async initLoginActionQueue(){Q("Init customer events");let t=!!window.localStorage.getItem("wk_logged_in");if(this.events.subscribe("wishlist:login-required",e=>{var s;let i=["wishlist:add","wishlist:view","wishlist:save-for-later"];(s=e.data)!=null&&s.action&&i.includes(e.data.action)&&window.localStorage.setItem("wk_pending",JSON.stringify({...e.data,origin:window.location.pathname+window.location.search}))}),!t&&this.isLoggedIn){Q("Customer logged in"),window.localStorage.setItem("wk_logged_in","1");let e=this.getPendingWishlistAction();this.events.publish({name:"customer:login",data:{pending:e}})}else t&&!this.isLoggedIn&&(Q("Customer logged out"),window.localStorage.removeItem("wk_logged_in"),this.events.publish({name:"customer:logout",data:{}}));["challenge","account"].includes(this.theme.getPageType())||window.localStorage.removeItem("wk_pending")}initCustomerSession(){this.hasSession||this.events.once("app:init-sid",t=>{var e,i;(e=t.data)!=null&&e.sessionId&&this.setSessionId((i=t.data)==null?void 0:i.sessionId)})}async clearCustomerSession(){window.localStorage.removeItem("wk_pending"),this.clearSessionId(),this.initCustomerSession(),await this.state.revalidate(!0)}getPendingWishlistAction(){try{let t=window.localStorage.getItem("wk_pending");if(t)return JSON.parse(t)}catch(t){console.warn("Could not parse pending wishlist action",t)}}initUrlChangeEvents(){let t=({productHandle:i,variantId:s})=>{this.events.publish({name:"product:change-variant:success",data:{productHandle:i,variantId:s}})},e=i=>(...s)=>{var p;let r=i.apply(history,s),n=typeof s[2]=="string"?s[2]:(p=s[2])==null?void 0:p.toString();if(!n)return r;n.startsWith("?")&&(n=window.location.pathname+n);let a=`${window.location.protocol}//${window.location.host}`,l=new URL(n,a),h=this.theme.getProductHandle(l),d=l.searchParams.get("variant");if(!h)return r;t({productHandle:h,variantId:d?parseInt(d):void 0})};history.replaceState=e(history.replaceState),history.pushState=e(history.pushState)}parseConfig({config:t}){var i,s,r,n,a,l,h,d,p,g,f,b,k;let e=(s=(i=t.localeIsoCode)==null?void 0:i.toUpperCase().replace(/-/g,"_"))!=null?s:"EN";return e.startsWith("ZH")||(e=e.split("_")[0]),{storefront:{accessToken:t.storefrontAccessToken,version:(r=window.__SWISH_STOREFRONT_API_VERSION)!=null?r:t.storefrontVersion,language:e},customer:{id:t.customerId?t.customerId:null,email:(n=t.customerEmail)!=null?n:"",name:(a=t.customerName)!=null?a:"",tags:(l=t.customerTags)!=null?l:[]},shop:{id:t.shopId,name:(h=t.shopName)!=null?h:"",domain:(d=t.shopDomain)!=null?d:"",permanentDomain:(p=t.shopPermanentDomain)!=null?p:"",moneyFormat:(g=t.shopMoneyFormat)!=null?g:"",moneyFormatWithC