ui.shipaid.com 0.3.141 → 0.3.142

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/dist/widget.es.js CHANGED
@@ -6046,19 +6046,14 @@ class ShipAidCheckoutPlus extends s$1 {
6046
6046
  _prepareParentContainer(btn) {
6047
6047
  if (!btn) return;
6048
6048
  try {
6049
- let el = btn.parentElement;
6050
- let depth = 0;
6051
- while (el && depth < 3) {
6052
- const cs = window.getComputedStyle(el);
6053
- const display = (cs.display || "").toLowerCase();
6054
- const isFlex = display === "flex" || display === "inline-flex";
6055
- const isGrid = display === "grid" || display === "inline-grid";
6056
- if (isFlex && cs.flexDirection !== "column" || isGrid) {
6057
- el.setAttribute("shipaid-parent-container", "");
6058
- return;
6059
- }
6060
- el = el.parentElement;
6061
- depth++;
6049
+ const el = btn.parentElement;
6050
+ if (!el) return;
6051
+ const cs = window.getComputedStyle(el);
6052
+ const display = (cs.display || "").toLowerCase();
6053
+ const isFlex = display === "flex" || display === "inline-flex";
6054
+ const isGrid = display === "grid" || display === "inline-grid";
6055
+ if (isFlex && cs.flexDirection !== "column" || isGrid) {
6056
+ el.setAttribute("shipaid-parent-container", "");
6062
6057
  }
6063
6058
  } catch {
6064
6059
  }
@@ -1934,7 +1934,7 @@ function yA(A,e,t){return A?e():null==t?void 0:t()}const GA=nA`
1934
1934
  <div class="shipaid">
1935
1935
  ${yA(this._hasFinishedSetup,()=>{var A,e,t,d,n;const r=null==(d=null==(t=null==(e=null==(A=this._store)?void 0:A.widgetConfigurations)?void 0:e.widget)?void 0:t.theme_checkout)?void 0:d.checkoutButtonSelector,a=sessionStorage.getItem("shipaidWidgetTheme");!a&&r&&sessionStorage.setItem("shipaidWidgetTheme",r),!this.useShipAidCheckout&&r||sessionStorage.removeItem("shipaidWidgetTheme");return this._shouldShowWidget&&this.planActive&&(null==(n=this._store)?void 0:n.widgetShowCart)?a?this.contactlessCheckoutButtonTemplate():this.promptTemplate():(this.useShipAidCheckout||document.querySelectorAll('[id*="shipaid-checkout-container"]').forEach(A=>A.remove()),this.getElementsBySelector(sessionStorage.getItem("shipaidWidgetTheme")||this.dataSelector).forEach(A=>A.removeAttribute("shipaid-hidden")),E)},()=>sessionStorage.getItem("shipaidWidgetTheme")?this.contactlessCheckoutButtonTemplate():this.promptTemplate())}
1936
1936
  </div>
1937
- `}};We.styles=_A;let Ke=We;xe([a({type:String,attribute:!0})],Ke.prototype,"env"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"useCustomStoreFront"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeDomain"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeAccessToken"),xe([a({type:String,attribute:!0})],Ke.prototype,"cartId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disablePolling"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableActions"),xe([a({type:Number,attribute:!0})],Ke.prototype,"pollingInterval"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableRefresh"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"refreshCart"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"persistPopup"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"defaultToggleButton"),xe([a({type:String,attribute:!0})],Ke.prototype,"lang"),xe([a({type:String,attribute:!0})],Ke.prototype,"currency"),xe([a({type:String,attribute:!0})],Ke.prototype,"customerId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"supportSubscriptions"),xe([a({type:String,attribute:"data-selector"})],Ke.prototype,"dataSelector"),xe([a({type:String,attribute:"button-id"})],Ke.prototype,"buttonId"),xe([a({type:String,attribute:"button-title"})],Ke.prototype,"buttonTitle"),xe([a({type:String,attribute:"widget-title"})],Ke.prototype,"widgetTitle"),xe([a({type:String,attribute:"button-classes"})],Ke.prototype,"buttonClasses"),xe([a({type:String,attribute:"shadow-root-selector"})],Ke.prototype,"shadowRootSelector"),xe([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ke.prototype,"useShipAidCheckout"),xe([a({type:Boolean,attribute:"preview-green-shipaid"})],Ke.prototype,"previewGreenShipAid"),xe([g()],Ke.prototype,"_storeDomain"),xe([g()],Ke.prototype,"_store"),xe([g()],Ke.prototype,"_cart"),xe([g()],Ke.prototype,"_protectionProduct"),xe([g()],Ke.prototype,"_cartLastUpdated"),xe([g()],Ke.prototype,"_hasFinishedSetup"),xe([g()],Ke.prototype,"_shouldShowWidget"),xe([g()],Ke.prototype,"_hasProtectionInCart"),xe([g()],Ke.prototype,"_protectionCartItem"),xe([g()],Ke.prototype,"_protectionVariant"),xe([g()],Ke.prototype,"_isBenefitsOpen"),xe([g()],Ke.prototype,"hasLoadedStrings"),xe([g()],Ke.prototype,"fetchInterceptorCleanup"),xe([g()],Ke.prototype,"intervalId"),xe([g()],Ke.prototype,"_sellingPlanId"),xe([g()],Ke.prototype,"_state"),xe([g()],Ke.prototype,"_popup");var he=Object.defineProperty,Ye=(A,e,t,d)=>{for(var n,r=void 0,a=A.length-1;a>=0;a--)(n=A[a])&&(r=n(e,t,r)||r);return r&&he(e,t,r),r};class Fe extends cA{constructor(){super(...arguments),this.env="prod",this.lang="en",this.currency=void 0,this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=A=>{var e,t;if("shipaid-widget"===(null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source))return;const d=Date.now();if(!(d-this._lastCartEventAt<500)){this._lastCartEventAt=d;try{this.updateCart().catch(()=>{})}catch{}}},this._onShipAidInternalCartUpdated=A=>{var e,t,d,n;if("shipaid-widget"===((null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source)||(null==(d=null==A?void 0:A.detail)?void 0:d.source)))return;const r=null==(n=null==A?void 0:A.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch(()=>{}):this.updateCart().catch(()=>{})}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:A=>be(A),post:(A,e)=>be(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const A=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(A,{credentials:"same-origin"});if(!e.ok)return;const t=await e.json().catch(()=>null);if(!t||"object"!=typeof t)return;this._isReplacingCartSections=!0;for(const d of Object.keys(t)){const A=t[d];if("string"!=typeof A)continue;const e=document.createElement("div");if(e.innerHTML=A,"cart-drawer"===d){try{const A=e.querySelector("cart-drawer"),t=document.querySelector("cart-drawer");if(A&&t){A.classList.contains("is-empty")?t.classList.add("is-empty"):t.classList.remove("is-empty")}}catch{}try{const A=e.querySelector("cart-drawer-items"),t=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");A&&t&&(t.outerHTML=A.outerHTML)}catch{}const A=e.querySelector("#CartDrawer-CartItems"),t=document.getElementById("CartDrawer-CartItems");A&&t&&(t.outerHTML=A.outerHTML);const d=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");d&&n&&(n.outerHTML=d.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML);continue}if("main-cart-items"===d){const t=e.querySelector("#main-cart-items"),d=document.getElementById("main-cart-items");if(t&&d)d.outerHTML=t.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=A)}continue}if("cart-icon-bubble"===d){const A=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),t=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");A&&t&&t.replaceWith(A);continue}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await mA(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",()=>{this._aboutToUnload=!0})}catch{}try{const[A,e,t]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=A,this._cart=e,this._protectionProduct=t,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const d={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(oe.LOADED,d))}catch(A){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var A,e,t,d;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var A;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(A=this._store.checkoutPlus)?void 0:A.enabled))}updated(A){if(A.has("dataSelector")||A.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}A.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach(A=>{var e;try{null==(e=A.parentNode)||e.removeChild(A)}catch{}})}catch{}}_getConfiguredShadowRoots(){var A,e;const t=[];try{const d=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.shadowRootSelector,n=Array.isArray(d)?d.filter(Boolean):"string"==typeof d&&d.trim()?[d.trim()]:[];for(const A of n){const e=document.querySelector(A);(null==e?void 0:e.shadowRoot)&&t.push(e.shadowRoot)}}catch{}return t}_prepareParentContainer(A){if(A)try{let e=A.parentElement,t=0;for(;e&&t<3;){const A=window.getComputedStyle(e),d=(A.display||"").toLowerCase(),n="grid"===d||"inline-grid"===d;if(("flex"===d||"inline-flex"===d)&&"column"!==A.flexDirection||n)return void e.setAttribute("shipaid-parent-container","");e=e.parentElement,t++}}catch{}}_applyButtonStylesFrom(A,e={}){if(A)try{const t=window.getComputedStyle(A),d=t.color,n=t.backgroundColor,r=t.borderTopStyle,a=t.borderTopColor,g=t.borderTopWidth;this.style.setProperty("--cp-primary-color",d||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",g||""),Object.entries(e).forEach(([A,e])=>{this.style.setProperty(A,e)})}catch{}}_enterToggleMode(A){const e="toggle"!==this._uiMode;this._uiMode="toggle",A&&(this._persistTogglePreference(A),this._desiredProtection="checked"===A),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(A){try{sessionStorage.setItem(ce,A)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(ce)}catch{}}_readTogglePreference(){try{const A=sessionStorage.getItem(ce);return"checked"===A||"unchecked"===A?A:null}catch{return null}}_normalizeVariantId(A){if(!A)return null;if("number"==typeof A)return String(Math.trunc(A));if("string"==typeof A){const e=A.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const t=e.match(/\d+/g);if(null==t?void 0:t.length)return t[t.length-1]}if("object"==typeof A){if("id"in A)return this._normalizeVariantId(A.id);if("variant_id"in A)return this._normalizeVariantId(A.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const A=this._readTogglePreference();A?(this._uiMode="toggle",this._desiredProtection="checked"===A):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var A,e,t,d,n,r;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,u=this.getRootNode()||document,f=new Set([document]);u&&f.add(u);for(const A of this._getConfiguredShadowRoots())f.add(A);for(const A of Array.from(f))if(A.host)try{const e="shipaid-styles";if(!(null==(r=A.querySelector)?void 0:r.call(A,`#${e}`))){const t=document.createElement("style");t.id=e,t.textContent="\n [shipaid-hidden] { display: none !important; }\n [shipaid-parent-container] { flex-wrap: wrap !important; }\n [shipaid-parent-container] > shipaid-widget-v2,\n [shipaid-parent-container] > shipaid-checkout-plus { flex: 1 0 100% !important; max-width: 100% !important; grid-column: 1 / -1 !important; }\n ",A.appendChild(t)}}catch{}const D=[];for(const A of Array.from(f))try{const e=Array.from(A.querySelectorAll(v.join(", ")));D.push(...e)}catch{}if(!D.length)return;if(this.isClone){const A=D[0];return this._originalCheckoutButton=A,this._applyButtonStylesFrom(A,g||{}),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden",""),this._prepareParentContainer(A),void(this.previousElementSibling!==A&&this.nextElementSibling!==A&&A.insertAdjacentElement("beforebegin",this))}const[B,...Q]=D;B&&(this._originalCheckoutButton=B,this._applyButtonStylesFrom(B,g||{}),B.setAttribute("data-shipaid-replaced","true"),B.hasAttribute("shipaid-hidden")||B.setAttribute("shipaid-hidden",""),this._prepareParentContainer(B),this.previousElementSibling!==B&&this.nextElementSibling!==B&&B.insertAdjacentElement("beforebegin",this));for(const A of Q){if("true"===A.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;A.setAttribute("data-shipaid-anchor",e),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden","");const t=document.createElement("shipaid-widget-v2");t.setAttribute("data-clone","true"),t.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{t.setAttribute("env",this.env)}catch{}try{t.setAttribute("lang",this.lang)}catch{}this._prepareParentContainer(A),A.insertAdjacentElement("beforebegin",t)}}catch{}}}_startObserver(){var A;try{null==(A=this._observer)||A.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const A=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{var A,e,t,d,n;const r=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,u=document.querySelectorAll(v.join(", "));let f=null;u.forEach((A,e)=>{const t=A;0===e&&(f=t),t.setAttribute("data-shipaid-replaced","true"),t.setAttribute("shipaid-hidden","")}),!this._originalCheckoutButton&&f&&this._applyButtonStylesFrom(f,g||{}),f&&this._prepareParentContainer(f);const D=u.length>0;r&&!D||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)},150)};this._observer=new MutationObserver(A),this._observer.observe(document.body,{childList:!0,subtree:!0});try{const A=[];for(const e of this._getConfiguredShadowRoots()){const t=new MutationObserver(()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{this._mountNearCheckoutButton()},150)});t.observe(e,{childList:!0,subtree:!0}),A.push(t)}this._shadowObservers=A}catch{}}catch{}}disconnectedCallback(){var A,e,t;super.disconnectedCallback();try{null==(A=this._originalCheckoutButton)||A.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}try{const A=this._shadowObservers;Array.isArray(A)&&A.forEach(A=>{try{A.disconnect()}catch{}}),this._shadowObservers=[]}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(t=this._itemsObserver)||t.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout(()=>this._mountNearCheckoutButton(),0))}catch{}try{document.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(A=!1){var e;try{A&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(A&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const t=(()=>{const A=(this.itemsSelector||"").trim();if(A)return document.querySelector(A);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const t of e){const A=document.querySelector(t);if(A)return A}return null})();if(t){this._itemsTargetEl=t;try{this._itemsObserver=new MutationObserver(()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout(()=>{this._updateCartInFlight||this.updateCart().catch(()=>{})},500)}}),this._itemsObserver.observe(t,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var A,e,t,d,n;const r=(null==(A=window.Shopify)?void 0:A.shop)??(null==(t=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:t.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const g={query:Me,variables:{store:r}},o=await this._fetch.post(a.toString(),g);if(null==(d=null==o?void 0:o.errors)?void 0:d.length)throw new Error(o.errors[0].message);const v=null==(n=null==o?void 0:o.data)?void 0:n.store;if(!v)throw new Error("Missing store from store query response.");return v}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${Ce}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(A,e){if(this._updateCartInFlight&&!A&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var t,d;A||(A=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=A,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(ve.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:A}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout(()=>this._mountNearCheckoutButton(),0)}catch{}})().finally(()=>{this._updateCartInFlight=null}),this._updateCartInFlight}async _fetchCartThrottled(A=1e3){const e=Date.now();return A>0&&this._cartCache&&e-this._cartFetchLastAt<A?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then(A=>(this._cartCache=A,this._cartFetchLastAt=Date.now(),A)).finally(()=>{this._cartFetchPromise=null})),this._cartFetchPromise)}async calculateProtectionTotal(A){if(A||(A=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,A)}getProtectionVariantForFee(A){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,A)}async calculateProtectionFeeForCartPlusAmountCents(A){if(!Number.isFinite(A)||A<=0)return{fee:0,variant:void 0};const e={total_price:Number(A),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(A),quantity:1,isVirtualProduct:!1}]},t=await this.calculateProtectionTotal(e);return{fee:t,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0}}async addProtection(){var A;if(!(null==(A=this._protectionVariant)?void 0:A.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(!e)return;const t={updates:{[String(e.id)]:0}},d=await this._fetch.post("/cart/update.js",t);await this.updateCart(d,{forceFetch:!1})}_currencyFormat(A){var e,t,d;const n=this.currency||(null==(e=this._store)?void 0:e.currency)||(null==(d=null==(t=window.Shopify)?void 0:t.currency)?void 0:d.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(A))}async updateProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);if(this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart){this._uiMode="toggle";this._readTogglePreference()||this._persistTogglePreference("checked")}else this._maybeRevertToLegacy();const t=await this.calculateProtectionTotal(this._cart),d=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0;this._protectionVariant=d,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(oe.CART_UPDATED,r))}render(){var A,e,t,d,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return E;const r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled),g=r||a?ae:ge,o=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,v=q`<style>
1937
+ `}};We.styles=_A;let Ke=We;xe([a({type:String,attribute:!0})],Ke.prototype,"env"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"useCustomStoreFront"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeDomain"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeAccessToken"),xe([a({type:String,attribute:!0})],Ke.prototype,"cartId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disablePolling"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableActions"),xe([a({type:Number,attribute:!0})],Ke.prototype,"pollingInterval"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableRefresh"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"refreshCart"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"persistPopup"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"defaultToggleButton"),xe([a({type:String,attribute:!0})],Ke.prototype,"lang"),xe([a({type:String,attribute:!0})],Ke.prototype,"currency"),xe([a({type:String,attribute:!0})],Ke.prototype,"customerId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"supportSubscriptions"),xe([a({type:String,attribute:"data-selector"})],Ke.prototype,"dataSelector"),xe([a({type:String,attribute:"button-id"})],Ke.prototype,"buttonId"),xe([a({type:String,attribute:"button-title"})],Ke.prototype,"buttonTitle"),xe([a({type:String,attribute:"widget-title"})],Ke.prototype,"widgetTitle"),xe([a({type:String,attribute:"button-classes"})],Ke.prototype,"buttonClasses"),xe([a({type:String,attribute:"shadow-root-selector"})],Ke.prototype,"shadowRootSelector"),xe([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ke.prototype,"useShipAidCheckout"),xe([a({type:Boolean,attribute:"preview-green-shipaid"})],Ke.prototype,"previewGreenShipAid"),xe([g()],Ke.prototype,"_storeDomain"),xe([g()],Ke.prototype,"_store"),xe([g()],Ke.prototype,"_cart"),xe([g()],Ke.prototype,"_protectionProduct"),xe([g()],Ke.prototype,"_cartLastUpdated"),xe([g()],Ke.prototype,"_hasFinishedSetup"),xe([g()],Ke.prototype,"_shouldShowWidget"),xe([g()],Ke.prototype,"_hasProtectionInCart"),xe([g()],Ke.prototype,"_protectionCartItem"),xe([g()],Ke.prototype,"_protectionVariant"),xe([g()],Ke.prototype,"_isBenefitsOpen"),xe([g()],Ke.prototype,"hasLoadedStrings"),xe([g()],Ke.prototype,"fetchInterceptorCleanup"),xe([g()],Ke.prototype,"intervalId"),xe([g()],Ke.prototype,"_sellingPlanId"),xe([g()],Ke.prototype,"_state"),xe([g()],Ke.prototype,"_popup");var he=Object.defineProperty,Ye=(A,e,t,d)=>{for(var n,r=void 0,a=A.length-1;a>=0;a--)(n=A[a])&&(r=n(e,t,r)||r);return r&&he(e,t,r),r};class Fe extends cA{constructor(){super(...arguments),this.env="prod",this.lang="en",this.currency=void 0,this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=A=>{var e,t;if("shipaid-widget"===(null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source))return;const d=Date.now();if(!(d-this._lastCartEventAt<500)){this._lastCartEventAt=d;try{this.updateCart().catch(()=>{})}catch{}}},this._onShipAidInternalCartUpdated=A=>{var e,t,d,n;if("shipaid-widget"===((null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source)||(null==(d=null==A?void 0:A.detail)?void 0:d.source)))return;const r=null==(n=null==A?void 0:A.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch(()=>{}):this.updateCart().catch(()=>{})}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:A=>be(A),post:(A,e)=>be(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const A=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(A,{credentials:"same-origin"});if(!e.ok)return;const t=await e.json().catch(()=>null);if(!t||"object"!=typeof t)return;this._isReplacingCartSections=!0;for(const d of Object.keys(t)){const A=t[d];if("string"!=typeof A)continue;const e=document.createElement("div");if(e.innerHTML=A,"cart-drawer"===d){try{const A=e.querySelector("cart-drawer"),t=document.querySelector("cart-drawer");if(A&&t){A.classList.contains("is-empty")?t.classList.add("is-empty"):t.classList.remove("is-empty")}}catch{}try{const A=e.querySelector("cart-drawer-items"),t=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");A&&t&&(t.outerHTML=A.outerHTML)}catch{}const A=e.querySelector("#CartDrawer-CartItems"),t=document.getElementById("CartDrawer-CartItems");A&&t&&(t.outerHTML=A.outerHTML);const d=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");d&&n&&(n.outerHTML=d.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML);continue}if("main-cart-items"===d){const t=e.querySelector("#main-cart-items"),d=document.getElementById("main-cart-items");if(t&&d)d.outerHTML=t.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=A)}continue}if("cart-icon-bubble"===d){const A=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),t=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");A&&t&&t.replaceWith(A);continue}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await mA(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",()=>{this._aboutToUnload=!0})}catch{}try{const[A,e,t]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=A,this._cart=e,this._protectionProduct=t,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const d={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(oe.LOADED,d))}catch(A){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var A,e,t,d;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var A;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(A=this._store.checkoutPlus)?void 0:A.enabled))}updated(A){if(A.has("dataSelector")||A.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}A.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach(A=>{var e;try{null==(e=A.parentNode)||e.removeChild(A)}catch{}})}catch{}}_getConfiguredShadowRoots(){var A,e;const t=[];try{const d=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.shadowRootSelector,n=Array.isArray(d)?d.filter(Boolean):"string"==typeof d&&d.trim()?[d.trim()]:[];for(const A of n){const e=document.querySelector(A);(null==e?void 0:e.shadowRoot)&&t.push(e.shadowRoot)}}catch{}return t}_prepareParentContainer(A){if(A)try{const e=A.parentElement;if(!e)return;const t=window.getComputedStyle(e),d=(t.display||"").toLowerCase(),n="grid"===d||"inline-grid"===d;(("flex"===d||"inline-flex"===d)&&"column"!==t.flexDirection||n)&&e.setAttribute("shipaid-parent-container","")}catch{}}_applyButtonStylesFrom(A,e={}){if(A)try{const t=window.getComputedStyle(A),d=t.color,n=t.backgroundColor,r=t.borderTopStyle,a=t.borderTopColor,g=t.borderTopWidth;this.style.setProperty("--cp-primary-color",d||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",g||""),Object.entries(e).forEach(([A,e])=>{this.style.setProperty(A,e)})}catch{}}_enterToggleMode(A){const e="toggle"!==this._uiMode;this._uiMode="toggle",A&&(this._persistTogglePreference(A),this._desiredProtection="checked"===A),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(A){try{sessionStorage.setItem(ce,A)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(ce)}catch{}}_readTogglePreference(){try{const A=sessionStorage.getItem(ce);return"checked"===A||"unchecked"===A?A:null}catch{return null}}_normalizeVariantId(A){if(!A)return null;if("number"==typeof A)return String(Math.trunc(A));if("string"==typeof A){const e=A.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const t=e.match(/\d+/g);if(null==t?void 0:t.length)return t[t.length-1]}if("object"==typeof A){if("id"in A)return this._normalizeVariantId(A.id);if("variant_id"in A)return this._normalizeVariantId(A.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const A=this._readTogglePreference();A?(this._uiMode="toggle",this._desiredProtection="checked"===A):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var A,e,t,d,n,r;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,u=this.getRootNode()||document,f=new Set([document]);u&&f.add(u);for(const A of this._getConfiguredShadowRoots())f.add(A);for(const A of Array.from(f))if(A.host)try{const e="shipaid-styles";if(!(null==(r=A.querySelector)?void 0:r.call(A,`#${e}`))){const t=document.createElement("style");t.id=e,t.textContent="\n [shipaid-hidden] { display: none !important; }\n [shipaid-parent-container] { flex-wrap: wrap !important; }\n [shipaid-parent-container] > shipaid-widget-v2,\n [shipaid-parent-container] > shipaid-checkout-plus { flex: 1 0 100% !important; max-width: 100% !important; grid-column: 1 / -1 !important; }\n ",A.appendChild(t)}}catch{}const D=[];for(const A of Array.from(f))try{const e=Array.from(A.querySelectorAll(v.join(", ")));D.push(...e)}catch{}if(!D.length)return;if(this.isClone){const A=D[0];return this._originalCheckoutButton=A,this._applyButtonStylesFrom(A,g||{}),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden",""),this._prepareParentContainer(A),void(this.previousElementSibling!==A&&this.nextElementSibling!==A&&A.insertAdjacentElement("beforebegin",this))}const[B,...Q]=D;B&&(this._originalCheckoutButton=B,this._applyButtonStylesFrom(B,g||{}),B.setAttribute("data-shipaid-replaced","true"),B.hasAttribute("shipaid-hidden")||B.setAttribute("shipaid-hidden",""),this._prepareParentContainer(B),this.previousElementSibling!==B&&this.nextElementSibling!==B&&B.insertAdjacentElement("beforebegin",this));for(const A of Q){if("true"===A.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;A.setAttribute("data-shipaid-anchor",e),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden","");const t=document.createElement("shipaid-widget-v2");t.setAttribute("data-clone","true"),t.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{t.setAttribute("env",this.env)}catch{}try{t.setAttribute("lang",this.lang)}catch{}this._prepareParentContainer(A),A.insertAdjacentElement("beforebegin",t)}}catch{}}}_startObserver(){var A;try{null==(A=this._observer)||A.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const A=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{var A,e,t,d,n;const r=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,u=document.querySelectorAll(v.join(", "));let f=null;u.forEach((A,e)=>{const t=A;0===e&&(f=t),t.setAttribute("data-shipaid-replaced","true"),t.setAttribute("shipaid-hidden","")}),!this._originalCheckoutButton&&f&&this._applyButtonStylesFrom(f,g||{}),f&&this._prepareParentContainer(f);const D=u.length>0;r&&!D||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)},150)};this._observer=new MutationObserver(A),this._observer.observe(document.body,{childList:!0,subtree:!0});try{const A=[];for(const e of this._getConfiguredShadowRoots()){const t=new MutationObserver(()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{this._mountNearCheckoutButton()},150)});t.observe(e,{childList:!0,subtree:!0}),A.push(t)}this._shadowObservers=A}catch{}}catch{}}disconnectedCallback(){var A,e,t;super.disconnectedCallback();try{null==(A=this._originalCheckoutButton)||A.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}try{const A=this._shadowObservers;Array.isArray(A)&&A.forEach(A=>{try{A.disconnect()}catch{}}),this._shadowObservers=[]}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(t=this._itemsObserver)||t.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout(()=>this._mountNearCheckoutButton(),0))}catch{}try{document.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(A=!1){var e;try{A&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(A&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const t=(()=>{const A=(this.itemsSelector||"").trim();if(A)return document.querySelector(A);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const t of e){const A=document.querySelector(t);if(A)return A}return null})();if(t){this._itemsTargetEl=t;try{this._itemsObserver=new MutationObserver(()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout(()=>{this._updateCartInFlight||this.updateCart().catch(()=>{})},500)}}),this._itemsObserver.observe(t,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var A,e,t,d,n;const r=(null==(A=window.Shopify)?void 0:A.shop)??(null==(t=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:t.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const g={query:Me,variables:{store:r}},o=await this._fetch.post(a.toString(),g);if(null==(d=null==o?void 0:o.errors)?void 0:d.length)throw new Error(o.errors[0].message);const v=null==(n=null==o?void 0:o.data)?void 0:n.store;if(!v)throw new Error("Missing store from store query response.");return v}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${Ce}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(A,e){if(this._updateCartInFlight&&!A&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var t,d;A||(A=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=A,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(ve.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:A}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout(()=>this._mountNearCheckoutButton(),0)}catch{}})().finally(()=>{this._updateCartInFlight=null}),this._updateCartInFlight}async _fetchCartThrottled(A=1e3){const e=Date.now();return A>0&&this._cartCache&&e-this._cartFetchLastAt<A?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then(A=>(this._cartCache=A,this._cartFetchLastAt=Date.now(),A)).finally(()=>{this._cartFetchPromise=null})),this._cartFetchPromise)}async calculateProtectionTotal(A){if(A||(A=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,A)}getProtectionVariantForFee(A){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,A)}async calculateProtectionFeeForCartPlusAmountCents(A){if(!Number.isFinite(A)||A<=0)return{fee:0,variant:void 0};const e={total_price:Number(A),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(A),quantity:1,isVirtualProduct:!1}]},t=await this.calculateProtectionTotal(e);return{fee:t,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0}}async addProtection(){var A;if(!(null==(A=this._protectionVariant)?void 0:A.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(!e)return;const t={updates:{[String(e.id)]:0}},d=await this._fetch.post("/cart/update.js",t);await this.updateCart(d,{forceFetch:!1})}_currencyFormat(A){var e,t,d;const n=this.currency||(null==(e=this._store)?void 0:e.currency)||(null==(d=null==(t=window.Shopify)?void 0:t.currency)?void 0:d.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(A))}async updateProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);if(this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart){this._uiMode="toggle";this._readTogglePreference()||this._persistTogglePreference("checked")}else this._maybeRevertToLegacy();const t=await this.calculateProtectionTotal(this._cart),d=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0;this._protectionVariant=d,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(oe.CART_UPDATED,r))}render(){var A,e,t,d,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return E;const r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled),g=r||a?ae:ge,o=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,v=q`<style>
1938
1938
  :host {
1939
1939
  --cp-border:#111;
1940
1940
  --cp-text:#111;
@@ -1934,7 +1934,7 @@ function yA(A,e,t){return A?e():null==t?void 0:t()}const GA=nA`
1934
1934
  <div class="shipaid">
1935
1935
  ${yA(this._hasFinishedSetup,()=>{var A,e,t,d,n;const r=null==(d=null==(t=null==(e=null==(A=this._store)?void 0:A.widgetConfigurations)?void 0:e.widget)?void 0:t.theme_checkout)?void 0:d.checkoutButtonSelector,a=sessionStorage.getItem("shipaidWidgetTheme");!a&&r&&sessionStorage.setItem("shipaidWidgetTheme",r),!this.useShipAidCheckout&&r||sessionStorage.removeItem("shipaidWidgetTheme");return this._shouldShowWidget&&this.planActive&&(null==(n=this._store)?void 0:n.widgetShowCart)?a?this.contactlessCheckoutButtonTemplate():this.promptTemplate():(this.useShipAidCheckout||document.querySelectorAll('[id*="shipaid-checkout-container"]').forEach(A=>A.remove()),this.getElementsBySelector(sessionStorage.getItem("shipaidWidgetTheme")||this.dataSelector).forEach(A=>A.removeAttribute("shipaid-hidden")),E)},()=>sessionStorage.getItem("shipaidWidgetTheme")?this.contactlessCheckoutButtonTemplate():this.promptTemplate())}
1936
1936
  </div>
1937
- `}};We.styles=_A;let Ke=We;xe([a({type:String,attribute:!0})],Ke.prototype,"env"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"useCustomStoreFront"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeDomain"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeAccessToken"),xe([a({type:String,attribute:!0})],Ke.prototype,"cartId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disablePolling"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableActions"),xe([a({type:Number,attribute:!0})],Ke.prototype,"pollingInterval"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableRefresh"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"refreshCart"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"persistPopup"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"defaultToggleButton"),xe([a({type:String,attribute:!0})],Ke.prototype,"lang"),xe([a({type:String,attribute:!0})],Ke.prototype,"currency"),xe([a({type:String,attribute:!0})],Ke.prototype,"customerId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"supportSubscriptions"),xe([a({type:String,attribute:"data-selector"})],Ke.prototype,"dataSelector"),xe([a({type:String,attribute:"button-id"})],Ke.prototype,"buttonId"),xe([a({type:String,attribute:"button-title"})],Ke.prototype,"buttonTitle"),xe([a({type:String,attribute:"widget-title"})],Ke.prototype,"widgetTitle"),xe([a({type:String,attribute:"button-classes"})],Ke.prototype,"buttonClasses"),xe([a({type:String,attribute:"shadow-root-selector"})],Ke.prototype,"shadowRootSelector"),xe([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ke.prototype,"useShipAidCheckout"),xe([a({type:Boolean,attribute:"preview-green-shipaid"})],Ke.prototype,"previewGreenShipAid"),xe([g()],Ke.prototype,"_storeDomain"),xe([g()],Ke.prototype,"_store"),xe([g()],Ke.prototype,"_cart"),xe([g()],Ke.prototype,"_protectionProduct"),xe([g()],Ke.prototype,"_cartLastUpdated"),xe([g()],Ke.prototype,"_hasFinishedSetup"),xe([g()],Ke.prototype,"_shouldShowWidget"),xe([g()],Ke.prototype,"_hasProtectionInCart"),xe([g()],Ke.prototype,"_protectionCartItem"),xe([g()],Ke.prototype,"_protectionVariant"),xe([g()],Ke.prototype,"_isBenefitsOpen"),xe([g()],Ke.prototype,"hasLoadedStrings"),xe([g()],Ke.prototype,"fetchInterceptorCleanup"),xe([g()],Ke.prototype,"intervalId"),xe([g()],Ke.prototype,"_sellingPlanId"),xe([g()],Ke.prototype,"_state"),xe([g()],Ke.prototype,"_popup");var he=Object.defineProperty,Ye=(A,e,t,d)=>{for(var n,r=void 0,a=A.length-1;a>=0;a--)(n=A[a])&&(r=n(e,t,r)||r);return r&&he(e,t,r),r};class Fe extends cA{constructor(){super(...arguments),this.env="prod",this.lang="en",this.currency=void 0,this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=A=>{var e,t;if("shipaid-widget"===(null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source))return;const d=Date.now();if(!(d-this._lastCartEventAt<500)){this._lastCartEventAt=d;try{this.updateCart().catch(()=>{})}catch{}}},this._onShipAidInternalCartUpdated=A=>{var e,t,d,n;if("shipaid-widget"===((null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source)||(null==(d=null==A?void 0:A.detail)?void 0:d.source)))return;const r=null==(n=null==A?void 0:A.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch(()=>{}):this.updateCart().catch(()=>{})}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:A=>be(A),post:(A,e)=>be(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const A=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(A,{credentials:"same-origin"});if(!e.ok)return;const t=await e.json().catch(()=>null);if(!t||"object"!=typeof t)return;this._isReplacingCartSections=!0;for(const d of Object.keys(t)){const A=t[d];if("string"!=typeof A)continue;const e=document.createElement("div");if(e.innerHTML=A,"cart-drawer"===d){try{const A=e.querySelector("cart-drawer"),t=document.querySelector("cart-drawer");if(A&&t){A.classList.contains("is-empty")?t.classList.add("is-empty"):t.classList.remove("is-empty")}}catch{}try{const A=e.querySelector("cart-drawer-items"),t=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");A&&t&&(t.outerHTML=A.outerHTML)}catch{}const A=e.querySelector("#CartDrawer-CartItems"),t=document.getElementById("CartDrawer-CartItems");A&&t&&(t.outerHTML=A.outerHTML);const d=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");d&&n&&(n.outerHTML=d.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML);continue}if("main-cart-items"===d){const t=e.querySelector("#main-cart-items"),d=document.getElementById("main-cart-items");if(t&&d)d.outerHTML=t.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=A)}continue}if("cart-icon-bubble"===d){const A=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),t=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");A&&t&&t.replaceWith(A);continue}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await mA(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",()=>{this._aboutToUnload=!0})}catch{}try{const[A,e,t]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=A,this._cart=e,this._protectionProduct=t,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const d={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(oe.LOADED,d))}catch(A){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var A,e,t,d;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var A;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(A=this._store.checkoutPlus)?void 0:A.enabled))}updated(A){if(A.has("dataSelector")||A.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}A.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach(A=>{var e;try{null==(e=A.parentNode)||e.removeChild(A)}catch{}})}catch{}}_getConfiguredShadowRoots(){var A,e;const t=[];try{const d=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.shadowRootSelector,n=Array.isArray(d)?d.filter(Boolean):"string"==typeof d&&d.trim()?[d.trim()]:[];for(const A of n){const e=document.querySelector(A);(null==e?void 0:e.shadowRoot)&&t.push(e.shadowRoot)}}catch{}return t}_prepareParentContainer(A){if(A)try{let e=A.parentElement,t=0;for(;e&&t<3;){const A=window.getComputedStyle(e),d=(A.display||"").toLowerCase(),n="grid"===d||"inline-grid"===d;if(("flex"===d||"inline-flex"===d)&&"column"!==A.flexDirection||n)return void e.setAttribute("shipaid-parent-container","");e=e.parentElement,t++}}catch{}}_applyButtonStylesFrom(A,e={}){if(A)try{const t=window.getComputedStyle(A),d=t.color,n=t.backgroundColor,r=t.borderTopStyle,a=t.borderTopColor,g=t.borderTopWidth;this.style.setProperty("--cp-primary-color",d||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",g||""),Object.entries(e).forEach(([A,e])=>{this.style.setProperty(A,e)})}catch{}}_enterToggleMode(A){const e="toggle"!==this._uiMode;this._uiMode="toggle",A&&(this._persistTogglePreference(A),this._desiredProtection="checked"===A),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(A){try{sessionStorage.setItem(ce,A)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(ce)}catch{}}_readTogglePreference(){try{const A=sessionStorage.getItem(ce);return"checked"===A||"unchecked"===A?A:null}catch{return null}}_normalizeVariantId(A){if(!A)return null;if("number"==typeof A)return String(Math.trunc(A));if("string"==typeof A){const e=A.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const t=e.match(/\d+/g);if(null==t?void 0:t.length)return t[t.length-1]}if("object"==typeof A){if("id"in A)return this._normalizeVariantId(A.id);if("variant_id"in A)return this._normalizeVariantId(A.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const A=this._readTogglePreference();A?(this._uiMode="toggle",this._desiredProtection="checked"===A):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var A,e,t,d,n,r;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,f=this.getRootNode()||document,u=new Set([document]);f&&u.add(f);for(const A of this._getConfiguredShadowRoots())u.add(A);for(const A of Array.from(u))if(A.host)try{const e="shipaid-styles";if(!(null==(r=A.querySelector)?void 0:r.call(A,`#${e}`))){const t=document.createElement("style");t.id=e,t.textContent="\n [shipaid-hidden] { display: none !important; }\n [shipaid-parent-container] { flex-wrap: wrap !important; }\n [shipaid-parent-container] > shipaid-widget-v2,\n [shipaid-parent-container] > shipaid-checkout-plus { flex: 1 0 100% !important; max-width: 100% !important; grid-column: 1 / -1 !important; }\n ",A.appendChild(t)}}catch{}const D=[];for(const A of Array.from(u))try{const e=Array.from(A.querySelectorAll(v.join(", ")));D.push(...e)}catch{}if(!D.length)return;if(this.isClone){const A=D[0];return this._originalCheckoutButton=A,this._applyButtonStylesFrom(A,g||{}),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden",""),this._prepareParentContainer(A),void(this.previousElementSibling!==A&&this.nextElementSibling!==A&&A.insertAdjacentElement("beforebegin",this))}const[B,...Q]=D;B&&(this._originalCheckoutButton=B,this._applyButtonStylesFrom(B,g||{}),B.setAttribute("data-shipaid-replaced","true"),B.hasAttribute("shipaid-hidden")||B.setAttribute("shipaid-hidden",""),this._prepareParentContainer(B),this.previousElementSibling!==B&&this.nextElementSibling!==B&&B.insertAdjacentElement("beforebegin",this));for(const A of Q){if("true"===A.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;A.setAttribute("data-shipaid-anchor",e),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden","");const t=document.createElement("shipaid-widget-v2");t.setAttribute("data-clone","true"),t.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{t.setAttribute("env",this.env)}catch{}try{t.setAttribute("lang",this.lang)}catch{}this._prepareParentContainer(A),A.insertAdjacentElement("beforebegin",t)}}catch{}}}_startObserver(){var A;try{null==(A=this._observer)||A.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const A=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{var A,e,t,d,n;const r=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,f=document.querySelectorAll(v.join(", "));let u=null;f.forEach((A,e)=>{const t=A;0===e&&(u=t),t.setAttribute("data-shipaid-replaced","true"),t.setAttribute("shipaid-hidden","")}),!this._originalCheckoutButton&&u&&this._applyButtonStylesFrom(u,g||{}),u&&this._prepareParentContainer(u);const D=f.length>0;r&&!D||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)},150)};this._observer=new MutationObserver(A),this._observer.observe(document.body,{childList:!0,subtree:!0});try{const A=[];for(const e of this._getConfiguredShadowRoots()){const t=new MutationObserver(()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{this._mountNearCheckoutButton()},150)});t.observe(e,{childList:!0,subtree:!0}),A.push(t)}this._shadowObservers=A}catch{}}catch{}}disconnectedCallback(){var A,e,t;super.disconnectedCallback();try{null==(A=this._originalCheckoutButton)||A.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}try{const A=this._shadowObservers;Array.isArray(A)&&A.forEach(A=>{try{A.disconnect()}catch{}}),this._shadowObservers=[]}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(t=this._itemsObserver)||t.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout(()=>this._mountNearCheckoutButton(),0))}catch{}try{document.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(A=!1){var e;try{A&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(A&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const t=(()=>{const A=(this.itemsSelector||"").trim();if(A)return document.querySelector(A);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const t of e){const A=document.querySelector(t);if(A)return A}return null})();if(t){this._itemsTargetEl=t;try{this._itemsObserver=new MutationObserver(()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout(()=>{this._updateCartInFlight||this.updateCart().catch(()=>{})},500)}}),this._itemsObserver.observe(t,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var A,e,t,d,n;const r=(null==(A=window.Shopify)?void 0:A.shop)??(null==(t=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:t.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const g={query:Me,variables:{store:r}},o=await this._fetch.post(a.toString(),g);if(null==(d=null==o?void 0:o.errors)?void 0:d.length)throw new Error(o.errors[0].message);const v=null==(n=null==o?void 0:o.data)?void 0:n.store;if(!v)throw new Error("Missing store from store query response.");return v}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${Ce}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(A,e){if(this._updateCartInFlight&&!A&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var t,d;A||(A=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=A,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(ve.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:A}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout(()=>this._mountNearCheckoutButton(),0)}catch{}})().finally(()=>{this._updateCartInFlight=null}),this._updateCartInFlight}async _fetchCartThrottled(A=1e3){const e=Date.now();return A>0&&this._cartCache&&e-this._cartFetchLastAt<A?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then(A=>(this._cartCache=A,this._cartFetchLastAt=Date.now(),A)).finally(()=>{this._cartFetchPromise=null})),this._cartFetchPromise)}async calculateProtectionTotal(A){if(A||(A=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,A)}getProtectionVariantForFee(A){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,A)}async calculateProtectionFeeForCartPlusAmountCents(A){if(!Number.isFinite(A)||A<=0)return{fee:0,variant:void 0};const e={total_price:Number(A),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(A),quantity:1,isVirtualProduct:!1}]},t=await this.calculateProtectionTotal(e);return{fee:t,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0}}async addProtection(){var A;if(!(null==(A=this._protectionVariant)?void 0:A.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(!e)return;const t={updates:{[String(e.id)]:0}},d=await this._fetch.post("/cart/update.js",t);await this.updateCart(d,{forceFetch:!1})}_currencyFormat(A){var e,t,d;const n=this.currency||(null==(e=this._store)?void 0:e.currency)||(null==(d=null==(t=window.Shopify)?void 0:t.currency)?void 0:d.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(A))}async updateProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);if(this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart){this._uiMode="toggle";this._readTogglePreference()||this._persistTogglePreference("checked")}else this._maybeRevertToLegacy();const t=await this.calculateProtectionTotal(this._cart),d=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0;this._protectionVariant=d,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(oe.CART_UPDATED,r))}render(){var A,e,t,d,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return E;const r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled),g=r||a?ae:ge,o=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,v=q`<style>
1937
+ `}};We.styles=_A;let Ke=We;xe([a({type:String,attribute:!0})],Ke.prototype,"env"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"useCustomStoreFront"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeDomain"),xe([a({type:String,attribute:!0})],Ke.prototype,"storeAccessToken"),xe([a({type:String,attribute:!0})],Ke.prototype,"cartId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disablePolling"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableActions"),xe([a({type:Number,attribute:!0})],Ke.prototype,"pollingInterval"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"disableRefresh"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"refreshCart"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"persistPopup"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"defaultToggleButton"),xe([a({type:String,attribute:!0})],Ke.prototype,"lang"),xe([a({type:String,attribute:!0})],Ke.prototype,"currency"),xe([a({type:String,attribute:!0})],Ke.prototype,"customerId"),xe([a({type:Boolean,attribute:!0})],Ke.prototype,"supportSubscriptions"),xe([a({type:String,attribute:"data-selector"})],Ke.prototype,"dataSelector"),xe([a({type:String,attribute:"button-id"})],Ke.prototype,"buttonId"),xe([a({type:String,attribute:"button-title"})],Ke.prototype,"buttonTitle"),xe([a({type:String,attribute:"widget-title"})],Ke.prototype,"widgetTitle"),xe([a({type:String,attribute:"button-classes"})],Ke.prototype,"buttonClasses"),xe([a({type:String,attribute:"shadow-root-selector"})],Ke.prototype,"shadowRootSelector"),xe([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ke.prototype,"useShipAidCheckout"),xe([a({type:Boolean,attribute:"preview-green-shipaid"})],Ke.prototype,"previewGreenShipAid"),xe([g()],Ke.prototype,"_storeDomain"),xe([g()],Ke.prototype,"_store"),xe([g()],Ke.prototype,"_cart"),xe([g()],Ke.prototype,"_protectionProduct"),xe([g()],Ke.prototype,"_cartLastUpdated"),xe([g()],Ke.prototype,"_hasFinishedSetup"),xe([g()],Ke.prototype,"_shouldShowWidget"),xe([g()],Ke.prototype,"_hasProtectionInCart"),xe([g()],Ke.prototype,"_protectionCartItem"),xe([g()],Ke.prototype,"_protectionVariant"),xe([g()],Ke.prototype,"_isBenefitsOpen"),xe([g()],Ke.prototype,"hasLoadedStrings"),xe([g()],Ke.prototype,"fetchInterceptorCleanup"),xe([g()],Ke.prototype,"intervalId"),xe([g()],Ke.prototype,"_sellingPlanId"),xe([g()],Ke.prototype,"_state"),xe([g()],Ke.prototype,"_popup");var he=Object.defineProperty,Ye=(A,e,t,d)=>{for(var n,r=void 0,a=A.length-1;a>=0;a--)(n=A[a])&&(r=n(e,t,r)||r);return r&&he(e,t,r),r};class Fe extends cA{constructor(){super(...arguments),this.env="prod",this.lang="en",this.currency=void 0,this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=A=>{var e,t;if("shipaid-widget"===(null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source))return;const d=Date.now();if(!(d-this._lastCartEventAt<500)){this._lastCartEventAt=d;try{this.updateCart().catch(()=>{})}catch{}}},this._onShipAidInternalCartUpdated=A=>{var e,t,d,n;if("shipaid-widget"===((null==(t=null==(e=null==A?void 0:A.detail)?void 0:e.data)?void 0:t.source)||(null==(d=null==A?void 0:A.detail)?void 0:d.source)))return;const r=null==(n=null==A?void 0:A.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch(()=>{}):this.updateCart().catch(()=>{})}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:A=>be(A),post:(A,e)=>be(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const A=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(A,{credentials:"same-origin"});if(!e.ok)return;const t=await e.json().catch(()=>null);if(!t||"object"!=typeof t)return;this._isReplacingCartSections=!0;for(const d of Object.keys(t)){const A=t[d];if("string"!=typeof A)continue;const e=document.createElement("div");if(e.innerHTML=A,"cart-drawer"===d){try{const A=e.querySelector("cart-drawer"),t=document.querySelector("cart-drawer");if(A&&t){A.classList.contains("is-empty")?t.classList.add("is-empty"):t.classList.remove("is-empty")}}catch{}try{const A=e.querySelector("cart-drawer-items"),t=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");A&&t&&(t.outerHTML=A.outerHTML)}catch{}const A=e.querySelector("#CartDrawer-CartItems"),t=document.getElementById("CartDrawer-CartItems");A&&t&&(t.outerHTML=A.outerHTML);const d=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");d&&n&&(n.outerHTML=d.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML);continue}if("main-cart-items"===d){const t=e.querySelector("#main-cart-items"),d=document.getElementById("main-cart-items");if(t&&d)d.outerHTML=t.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=A)}continue}if("cart-icon-bubble"===d){const A=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),t=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");A&&t&&t.replaceWith(A);continue}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await mA(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",()=>{this._aboutToUnload=!0})}catch{}try{const[A,e,t]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=A,this._cart=e,this._protectionProduct=t,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const d={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(oe.LOADED,d))}catch(A){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var A,e,t,d;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var A;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(A=this._store.checkoutPlus)?void 0:A.enabled))}updated(A){if(A.has("dataSelector")||A.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}A.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach(A=>{var e;try{null==(e=A.parentNode)||e.removeChild(A)}catch{}})}catch{}}_getConfiguredShadowRoots(){var A,e;const t=[];try{const d=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.shadowRootSelector,n=Array.isArray(d)?d.filter(Boolean):"string"==typeof d&&d.trim()?[d.trim()]:[];for(const A of n){const e=document.querySelector(A);(null==e?void 0:e.shadowRoot)&&t.push(e.shadowRoot)}}catch{}return t}_prepareParentContainer(A){if(A)try{const e=A.parentElement;if(!e)return;const t=window.getComputedStyle(e),d=(t.display||"").toLowerCase(),n="grid"===d||"inline-grid"===d;(("flex"===d||"inline-flex"===d)&&"column"!==t.flexDirection||n)&&e.setAttribute("shipaid-parent-container","")}catch{}}_applyButtonStylesFrom(A,e={}){if(A)try{const t=window.getComputedStyle(A),d=t.color,n=t.backgroundColor,r=t.borderTopStyle,a=t.borderTopColor,g=t.borderTopWidth;this.style.setProperty("--cp-primary-color",d||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",g||""),Object.entries(e).forEach(([A,e])=>{this.style.setProperty(A,e)})}catch{}}_enterToggleMode(A){const e="toggle"!==this._uiMode;this._uiMode="toggle",A&&(this._persistTogglePreference(A),this._desiredProtection="checked"===A),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(A){try{sessionStorage.setItem(ce,A)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(ce)}catch{}}_readTogglePreference(){try{const A=sessionStorage.getItem(ce);return"checked"===A||"unchecked"===A?A:null}catch{return null}}_normalizeVariantId(A){if(!A)return null;if("number"==typeof A)return String(Math.trunc(A));if("string"==typeof A){const e=A.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const t=e.match(/\d+/g);if(null==t?void 0:t.length)return t[t.length-1]}if("object"==typeof A){if("id"in A)return this._normalizeVariantId(A.id);if("variant_id"in A)return this._normalizeVariantId(A.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const A=this._readTogglePreference();A?(this._uiMode="toggle",this._desiredProtection="checked"===A):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var A,e,t,d,n,r;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,f=this.getRootNode()||document,u=new Set([document]);f&&u.add(f);for(const A of this._getConfiguredShadowRoots())u.add(A);for(const A of Array.from(u))if(A.host)try{const e="shipaid-styles";if(!(null==(r=A.querySelector)?void 0:r.call(A,`#${e}`))){const t=document.createElement("style");t.id=e,t.textContent="\n [shipaid-hidden] { display: none !important; }\n [shipaid-parent-container] { flex-wrap: wrap !important; }\n [shipaid-parent-container] > shipaid-widget-v2,\n [shipaid-parent-container] > shipaid-checkout-plus { flex: 1 0 100% !important; max-width: 100% !important; grid-column: 1 / -1 !important; }\n ",A.appendChild(t)}}catch{}const D=[];for(const A of Array.from(u))try{const e=Array.from(A.querySelectorAll(v.join(", ")));D.push(...e)}catch{}if(!D.length)return;if(this.isClone){const A=D[0];return this._originalCheckoutButton=A,this._applyButtonStylesFrom(A,g||{}),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden",""),this._prepareParentContainer(A),void(this.previousElementSibling!==A&&this.nextElementSibling!==A&&A.insertAdjacentElement("beforebegin",this))}const[B,...Q]=D;B&&(this._originalCheckoutButton=B,this._applyButtonStylesFrom(B,g||{}),B.setAttribute("data-shipaid-replaced","true"),B.hasAttribute("shipaid-hidden")||B.setAttribute("shipaid-hidden",""),this._prepareParentContainer(B),this.previousElementSibling!==B&&this.nextElementSibling!==B&&B.insertAdjacentElement("beforebegin",this));for(const A of Q){if("true"===A.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;A.setAttribute("data-shipaid-anchor",e),A.setAttribute("data-shipaid-replaced","true"),A.hasAttribute("shipaid-hidden")||A.setAttribute("shipaid-hidden","");const t=document.createElement("shipaid-widget-v2");t.setAttribute("data-clone","true"),t.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{t.setAttribute("env",this.env)}catch{}try{t.setAttribute("lang",this.lang)}catch{}this._prepareParentContainer(A),A.insertAdjacentElement("beforebegin",t)}}catch{}}}_startObserver(){var A;try{null==(A=this._observer)||A.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const A=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{var A,e,t,d,n;const r=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),a=(null==(t=null==(e=null==(A=this._store)?void 0:A.checkoutPlus)?void 0:e.selectors)?void 0:t.join(","))||"",g=(null==(n=null==(d=this._store)?void 0:d.checkoutPlus)?void 0:n.styles)||{},o=(a||this.dataSelector||"").trim(),v=o?o.split(",").map(A=>A.trim()).filter(Boolean):Te,f=document.querySelectorAll(v.join(", "));let u=null;f.forEach((A,e)=>{const t=A;0===e&&(u=t),t.setAttribute("data-shipaid-replaced","true"),t.setAttribute("shipaid-hidden","")}),!this._originalCheckoutButton&&u&&this._applyButtonStylesFrom(u,g||{}),u&&this._prepareParentContainer(u);const D=f.length>0;r&&!D||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)},150)};this._observer=new MutationObserver(A),this._observer.observe(document.body,{childList:!0,subtree:!0});try{const A=[];for(const e of this._getConfiguredShadowRoots()){const t=new MutationObserver(()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout(()=>{this._mountNearCheckoutButton()},150)});t.observe(e,{childList:!0,subtree:!0}),A.push(t)}this._shadowObservers=A}catch{}}catch{}}disconnectedCallback(){var A,e,t;super.disconnectedCallback();try{null==(A=this._originalCheckoutButton)||A.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}try{const A=this._shadowObservers;Array.isArray(A)&&A.forEach(A=>{try{A.disconnect()}catch{}}),this._shadowObservers=[]}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(t=this._itemsObserver)||t.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout(()=>this._mountNearCheckoutButton(),0))}catch{}try{document.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(ve.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(oe.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(A=!1){var e;try{A&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(A&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const t=(()=>{const A=(this.itemsSelector||"").trim();if(A)return document.querySelector(A);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const t of e){const A=document.querySelector(t);if(A)return A}return null})();if(t){this._itemsTargetEl=t;try{this._itemsObserver=new MutationObserver(()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout(()=>{this._updateCartInFlight||this.updateCart().catch(()=>{})},500)}}),this._itemsObserver.observe(t,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var A,e,t,d,n;const r=(null==(A=window.Shopify)?void 0:A.shop)??(null==(t=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:t.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const g={query:Me,variables:{store:r}},o=await this._fetch.post(a.toString(),g);if(null==(d=null==o?void 0:o.errors)?void 0:d.length)throw new Error(o.errors[0].message);const v=null==(n=null==o?void 0:o.data)?void 0:n.store;if(!v)throw new Error("Missing store from store query response.");return v}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${Ce}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(A,e){if(this._updateCartInFlight&&!A&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var t,d;A||(A=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=A,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(ve.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:A}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout(()=>this._mountNearCheckoutButton(),0)}catch{}})().finally(()=>{this._updateCartInFlight=null}),this._updateCartInFlight}async _fetchCartThrottled(A=1e3){const e=Date.now();return A>0&&this._cartCache&&e-this._cartFetchLastAt<A?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then(A=>(this._cartCache=A,this._cartFetchLastAt=Date.now(),A)).finally(()=>{this._cartFetchPromise=null})),this._cartFetchPromise)}async calculateProtectionTotal(A){if(A||(A=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,A)}getProtectionVariantForFee(A){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,A)}async calculateProtectionFeeForCartPlusAmountCents(A){if(!Number.isFinite(A)||A<=0)return{fee:0,variant:void 0};const e={total_price:Number(A),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(A),quantity:1,isVirtualProduct:!1}]},t=await this.calculateProtectionTotal(e);return{fee:t,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0}}async addProtection(){var A;if(!(null==(A=this._protectionVariant)?void 0:A.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(!e)return;const t={updates:{[String(e.id)]:0}},d=await this._fetch.post("/cart/update.js",t);await this.updateCart(d,{forceFetch:!1})}_currencyFormat(A){var e,t,d;const n=this.currency||(null==(e=this._store)?void 0:e.currency)||(null==(d=null==(t=window.Shopify)?void 0:t.currency)?void 0:d.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(A))}async updateProtection(){var A;if(!(null==(A=this._cart)?void 0:A.items))return;const e=this._cart.items.find(A=>(null==A?void 0:A.handle)===Ce);if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);if(this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart){this._uiMode="toggle";this._readTogglePreference()||this._persistTogglePreference("checked")}else this._maybeRevertToLegacy();const t=await this.calculateProtectionTotal(this._cart),d=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,t):void 0;this._protectionVariant=d,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(oe.CART_UPDATED,r))}render(){var A,e,t,d,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return E;const r=Boolean(null==(e=null==(A=this._store)?void 0:A.greenProtection)?void 0:e.enabled),a=Boolean(null==(d=null==(t=this._store)?void 0:t.freeGifts)?void 0:d.enabled),g=r||a?ae:ge,o=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,v=q`<style>
1938
1938
  :host {
1939
1939
  --cp-border:#111;
1940
1940
  --cp-text:#111;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ui.shipaid.com",
3
3
  "private": false,
4
- "version": "0.3.141",
4
+ "version": "0.3.142",
5
5
  "type": "module",
6
6
  "main": "dist/widget.umd.js",
7
7
  "unpkg": "dist/widget.iife.js",