setTimeout(m,500)),s.input.amount={amount:y.data.totalAmount.amount,currencyCode:y.data.totalAmount.currencyCode};continue}return(y.data.totalAmount.amount===l||parseFloat(y.data.totalAmount.amount)<=parseFloat(l))&&y.data.totalAmount.currencyCode===u?y:d}throw new Error("Payment update operation timed out")}async updateCartAttributes({cartId:t,attributes:n,instrumentName:r,startingCheckout:a}){const i={cartId:t,attributes:n};return await this.requestDeferredCart(uo,i,{instrumentName:r,startingCheckout:a})}async submitForCompletion(t,n,r){var a,i;const o=this.formatLanguage(this.locale),s=await this.request([Ao],{cartId:t,attemptToken:n,country:this.country,language:o,withCarrierRates:this.withCarrierRates},{instrumentName:r});return{data:(i=(a=s.data)==null?void 0:a.cartSubmitForCompletion)==null?void 0:i.result,errors:this.parseCompletionErrors(s)}}async fetchSubscriptionPolicy(){var t,n;const{data:r}=await this.request([wo],{country:this.country,language:this.formatLanguage(this.locale)},{});return(n=(t=r==null?void 0:r.shop)==null?void 0:t.subscriptionPolicy)==null?void 0:n.body}generateURLWithOperationName(t){const n=t.match(this.OPERATION_NAME_REGEX);if(n){const r=this.url.includes("?")?"&":"?",a="operation_name=".concat(n[1]);return"".concat(this.url).concat(r).concat(a)}return this.url}async request(t,n,r){return this.client.request(t.join(""),{variables:n,headers:Cr(r),url:this.generateURLWithOperationName(t[0])})}async requestStream(t,n,r){return this.client.requestStream(t.join(""),{variables:n,headers:Cr(r),url:this.generateURLWithOperationName(t[0]),signal:r.abortSignal})}async requestDeferredCart(t,n,r){var a,i,o,s,l,u;const d=this.formatLanguage(this.locale),p=await this.requestStream([t,Se],D(A({},n),{country:this.country,language:d,withCarrierRates:this.withCarrierRates}),r);try{for(var y=z(p),m,v,f;m=!(v=await y.next()).done;m=!1){const S=v.value;S.errors&&this.onError(S.errors);const B=(i=(a=S.data)==null?void 0:a.result)==null?void 0:i.cart;if(B&&!S.hasNext)return{data:await this.fetchCart({id:B.id,instrumentName:r.instrumentName,startingCheckout:!1}),errors:this.parseMutationErrors(S,"result")};if(this.lastValidCart&&(s=(o=S.data)==null?void 0:o.result)!=null&&s.errors)return this.onResultError((u=(l=S.data)==null?void 0:l.result)==null?void 0:u.errors),{data:this.lastValidCart,errors:this.parseMutationErrors(S,"result")}}}catch(S){f=[S]}finally{try{m&&(v=y.return)&&await v.call(y)}finally{if(f)throw f[0]}}throw new bt("Deferred cart operation returned no response")}onError(t){var n,r;if(!t)return;w.leaveBreadcrumb("GraphQL response error",t,"error");const a=(r=(n=t.graphQLErrors)==null?void 0:n.map(s=>s.message).join(", "))!=null?r:"",i="".concat(t.message).concat(a.length>0?" - ".concat(a):""),o=t!=null&&t.networkStatusCode?"with status ".concat(t.networkStatusCode," => ").concat(i):"=> ".concat(i);throw new Error("GraphQL mutation failed ".concat(o))}onResultError(t){w.leaveBreadcrumb("GraphQL result error",t,"error")}formatLanguage(t){return t.includes("-")?t.split("-")[0].toUpperCase():t.toUpperCase()}parseCartResponse(t){var n,r,a;const i=t.lines.edges.map(s=>{var l,u;const d=s.node;return{quantity:d.quantity,totalAmount:{amount:d.cost.totalAmount.amount,currencyCode:d.cost.totalAmount.currencyCode},subtotalAmount:{amount:(l=d.cost.subtotalAmount)==null?void 0:l.amount,currencyCode:(u=d.cost.subtotalAmount)==null?void 0:u.currencyCode},merchandise:{requiresShipping:d.merchandise.requiresShipping},discountAllocations:d.discountAllocations,sellingPlanAllocation:d.sellingPlanAllocation}}),o=t.deliveryGroups.edges.map(s=>s.node);return{id:t.id,totalAmount:t.cost.totalAmount,subtotalAmount:(n=t.cost.subtotalAmount)!=null?n:void 0,totalTaxAmount:(r=t.cost.totalTaxAmount)!=null?r:void 0,totalDutyAmount:(a=t.cost.totalDutyAmount)!=null?a:void 0,discountAllocations:t.discountAllocations,discountCodes:t.discountCodes,lineItems:i,deliveryGroups:o,checkoutUrl:t.checkoutUrl}}parseGraphQlErrors(t){var n,r;return(r=(n=t==null?void 0:t.graphQLErrors)==null?void 0:n.map(a=>a.message.replace(/\(Expected.*\)/,"").trim()))!=null?r:[]}parseMutationErrors(t,n){var r,a,i;const o=this.parseGraphQlErrors(t.errors),s=((i=(a=(r=t.data)==null?void 0:r[n])==null?void 0:a.errors)==null?void 0:i.map(u=>u.code===Qt?{code:Qt,message:u.message}:u.field&&u.field.length>0?"".concat(u.code,": ").concat(u.field.join(".")):u.code).filter(u=>u))||[],l=[...o,...s];return w.leaveBreadcrumb("GraphQL errors on mutation",l,"error"),l}parseCompletionErrors(t){var n,r,a,i;const o=this.parseGraphQlErrors(t.errors);let s=[];((a=(r=(n=t.data)==null?void 0:n.cartSubmitForCompletion)==null?void 0:r.result)==null?void 0:a.__typename)==="SubmitFailed"&&(s=(i=t.data.cartSubmitForCompletion.result.errors.map(u=>u.code))!=null?i:[]);const l=[...o,...s];return w.leaveBreadcrumb("GraphQL errors on completion",l,"error"),l}}function Cr({instrumentName:e,startingCheckout:t}){const n={};return e&&(n["X-Wallet-Name"]="".concat(e)),t&&(n["X-Start-Wallet-Checkout"]="".concat(t)),n}async function bn({cartId:e,cartClient:t,instrumentName:n,selectedDeliveryOptions:r,abortSignal:a}){try{if(!e)throw new Error("[".concat(n,"] provided no cart ID when updating shipping method"));if(!t)throw new Error("[".concat(n,"] provided invalid cart client when updating shipping method"));return await t.updateSelectedDeliveryOptions(e,r,n,a)}catch(i){throw g.updateFailed(n,"updateSelectedDeliveryOptions"),i}}async function wn({cartId:e,token:t,cartClient:n,instrumentName:r}){try{if(!e)throw new Error("[".concat(r,"] provided no cart ID when submitting for completion"));if(!n)throw new Error("[".concat(r,"] provided invalid cart client when submitting for completion"));if(!t)throw new Error("[".concat(r,"] provided no token when submitting for completion"));return await n.submitForCompletion(e,t,r)}catch(a){throw g.updateFailed(r,"submitForCompletion"),a}}function _n({selectedDeliveryOptionHandles:e,deliveryGroups:t,instrumentName:n}){return t.map(r=>{const a=r.deliveryOptions.filter(i=>e.includes(i.handle));if(!a.length)throw new Error("[".concat(n,"] could not find delivery option for group: ").concat(r.id));if(a.length>1)throw new Error("[".concat(n,"] found multiple delivery options with selectedDeliverOptionHandle in group: ").concat(r.id));return{deliveryGroupId:r.id,deliveryOptionHandle:a[0].handle}})}async function Co(e){const{cartClient:t,instrumentName:n}=e;try{if(!e.cartId)throw new Error("[".concat(n,"] provided no cart ID when updating billing address"));if(!t)throw new Error("[".concat(n,"] provided invalid cart client when updating billing address"));return await t.updateCartBillingAddress(e)}catch(r){throw g.updateFailed(n,"updateBillingAddress"),r}}class Eo{constructor({accessToken:t,buyerCountry:n,buyerCurrency:r,button:a,i18n:i,merchantName:o,dataSource:s,apiClient:l,walletParams:u}){c(this,"name",b.ApplePay),c(this,"accessToken"),c(this,"button"),c(this,"buyerCountry"),c(this,"cart"),c(this,"apiClient"),c(this,"dataSource"),c(this,"i18n"),c(this,"merchantName"),c(this,"session"),c(this,"paymentSheetActionGenerator"),c(this,"cancelled"),c(this,"buyerCurrency"),c(this,"customerAccountEmail"),c(this,"abortController",null),c(this,"onvalidatemerchant",async d=>{try{const p=new URL(d.validationURL),y=this.getMerchantSession(p),{cart:m,outOfStock:v}=await nt({element:this.button,instrumentName:this.name,dataSource:this.dataSource});this.cart=m;const f=await y;if(w.leaveBreadcrumb("ApplePay Session completeMerchantValidation",{session:f},"log"),v){this.abortAndShowOutOfStockError();return}if(this.sessionIsCancelled())return;this.session.completeMerchantValidation(f)}catch(p){g.sheetClicked({instrument:b.ApplePay,result:"failed"}),this.terminateSession(p)}}),c(this,"onshippingcontactselected",async d=>{try{const p=Wt(d.shippingContact),y=await St({cartId:this.cart.id,streetAddress:p,cartClient:this.apiClient,instrumentName:this.name});if(!y.data)throw new Error("Missing cart during Apple Pay Session creation");if(this.shouldDecelerate(y.data))return;await this.applyPaymentSheetActions(y,m=>this.completeShippingContactSelection(y.data,m),{shippingRequired:this.isShippingRequired})}catch(p){this.terminateSession(p)}}),c(this,"onshippingmethodselected",async d=>{var p;try{const y=d.shippingMethod.identifier.split(","),m=_n({selectedDeliveryOptionHandles:y,deliveryGroups:this.cart.deliveryGroups,instrumentName:this.name}),v=await bn({cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name,selectedDeliveryOptions:m,abortSignal:(p=this.abortController)==null?void 0:p.signal});await this.applyPaymentSheetActions(v,()=>this.completeShippingMethodSelection(v.data))}catch(y){this.terminateSession(y)}}),c(this,"onpaymentmethodselected",async d=>{try{const{billingContact:p}=d.paymentMethod;if(!this.isShippingRequired&&p){const v=Wt(p),f=await St({cartId:this.cart.id,countryCode:v.country,cartClient:this.apiClient,instrumentName:this.name});if(!f.data)throw new Error("Missing cart during Apple Pay Session creation");if(this.shouldDecelerate(f.data))return;await this.applyPaymentSheetActions(f,()=>this.cart=f.data);const S=await Co({billingAddress:v,cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name});await this.applyPaymentSheetActions(S,()=>this.cart=S.data)}const{newTotal:y,newLineItems:m}=this.getNewTotalAndLineItems(this.cart);if(w.leaveBreadcrumb("ApplePay Session completePaymentMethodSelection",{newTotal:y,newLineItems:m},"log"),this.sessionIsCancelled())return;this.session.completePaymentMethodSelection({newTotal:y,newLineItems:m})}catch(p){this.terminateSession(p)}}),c(this,"oncancel",()=>{var d;this.cancelled=!0,g.sheetCancelled(this.name),this.button.disabled=!1,(d=this.abortController)==null||d.abort()}),c(this,"onpaymentauthorized",async d=>{g.authorizationAttempt(this.name),qt(N.AuthorizationLatency,this.name);const p=O=>{g.authorizationComplete({instrument:this.name,measurement:Y(N.AuthorizationLatency,this.name),result:"failure"}),this.terminateSession(O)},y=async O=>{var F,Nt;switch((F=O.effects)==null||F.forEach(_=>_()),O.action){case"complete":{const _=ApplePaySession.STATUS_SUCCESS;try{await this.completePayment(_),tt(O.redirectUrl)}catch(M){p(M)}break}case"show_error":{const _=(Nt=O.errors)!=null?Nt:[];try{await this.completePayment(ApplePaySession.STATUS_FAILURE,_)}catch(M){p(M)}break}case"abort":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),this.button.disabled=!1}catch(_){p(_)}break}default:p(new Error("[".concat(this.name,"] completion action not handled: ").concat(O.action)))}},{token:m,billingContact:v,shippingContact:f}=d.payment;let S=null,B=null;try{if(!v){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}if(S=Wt(D(A({},v),{phoneNumber:f==null?void 0:f.phoneNumber})),this.isShippingRequired){if(!f){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}B=Wt(f)}}catch(O){p(O);return}const K=async()=>{var O;try{const F=this.isShippingRequired?{validateAddress:!0,streetAddress:B}:{},Nt=(O=this.customerAccountEmail)!=null?O:f==null?void 0:f.emailAddress,_=await St(A({cartId:this.cart.id,emailAddress:Nt,cartClient:this.apiClient,instrumentName:this.name},F)),M=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(_);await Ae({paymentSheetAction:M,onProceed:async Rt=>{Rt&&Rt.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,Rt):await jt()},terminateSession:p})}catch(F){p(F)}},jt=async()=>{var O;try{const F=this.cart.lineItems.some(M=>!!M.sellingPlanAllocation),Nt=await Qe({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{applePayWalletContent:{billingAddress:S,data:m.paymentData.data,header:m.paymentData.header,lastDigits:m.paymentMethod.displayName.split(" ")[1],signature:m.paymentData.signature,version:m.paymentData.version}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:S,cartClient:this.apiClient,instrumentName:this.name,hasSellingPlan:F,abortSignal:(O=this.abortController)==null?void 0:O.signal}),_=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(Nt);await Ae({paymentSheetAction:_,onProceed:async M=>{M&&M.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,M):await ye()},terminateSession:p})}catch(F){p(F)}},ye=async()=>{try{const O=await wn({cartId:this.cart.id,token:m.transactionIdentifier,cartClient:this.apiClient,instrumentName:this.name}),F=this.paymentSheetActionGenerator.mapCompletionResultToPaymentSheetAction(O);await y(F)}catch(O){p(O)}};await K()}),c(this,"terminateSession",d=>{var p;this.button.disabled=!1,d&&w.notify(d),g.sheetFailed(this.name,d);try{w.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.session.abort(),(p=this.abortController)==null||p.abort()}catch(y){console.debug("[DEBUG] InvalidAccessError occurred during Apple Pay terminateSession")}if(d){const y=this.i18n.translate("brand.apple_pay");W(y,this.i18n)}}),c(this,"abortAndShowOutOfStockError",()=>{var d;this.session.abort(),(d=this.abortController)==null||d.abort(),et(this.i18n)}),c(this,"getMostRecentNonNullCart",(d,p)=>d?(this.cart=d,d):p),c(this,"handleNullCart",d=>{if(!d)throw new Error("[".concat(this.name,"] no cart returned on mutation, aborting"))}),c(this,"completeShippingContactSelection",(d,p)=>{try{const y=this.getMostRecentNonNullCart(d,this.cart),{newTotal:m,newLineItems:v}=this.getNewTotalAndLineItems(y),f=Bi(y.deliveryGroups,this.i18n);w.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{errors:p,newTotal:m,newLineItems:v,newShippingMethods:f},"log"),this.session.completeShippingContactSelection({errors:p!=null?p:[],newTotal:m,newLineItems:v,newShippingMethods:f})}catch(y){this.terminateSession(y)}}),c(this,"completeShippingMethodSelection",d=>{try{this.handleNullCart(d),this.cart=d;const{newTotal:p,newLineItems:y}=this.getNewTotalAndLineItems(d);w.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{newTotal:p,newLineItems:y},"log"),this.session.completeShippingMethodSelection({newTotal:p,newLineItems:y})}catch(p){this.terminateSession(p)}}),c(this,"sessionIsCancelled",()=>this.cancelled),this.accessToken=t,this.buyerCountry=n,this.button=a,this.cart=null,this.apiClient=l,this.dataSource=s,this.i18n=i,this.merchantName=o,this.cancelled=!1,this.buyerCurrency=r,this.customerAccountEmail=u.customerAccountEmail,this.session=new ApplePaySession(Br,Gi({shippingRequired:this.isShippingRequired,walletParams:u,buyerCurrency:r})),this.session.onvalidatemerchant=this.onvalidatemerchant,this.session.onshippingcontactselected=this.onshippingcontactselected,this.session.onshippingmethodselected=this.onshippingmethodselected,this.session.onpaymentmethodselected=this.onpaymentmethodselected,this.session.oncancel=this.oncancel,this.session.onpaymentauthorized=this.onpaymentauthorized,this.paymentSheetActionGenerator=new Hi(i)}begin(){w.leaveBreadcrumb("ApplePay Session begin",{},"log"),this.abortController=Ze(),this.session.begin()}async applyPaymentSheetActions(t,n,r){var a;const i=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(t,r);(a=i.effects)==null||a.forEach(o=>o()),!this.sessionIsCancelled()&&await Ae({paymentSheetAction:i,onProceed:n,terminateSession:this.terminateSession})}async getMerchantSession(t){const n=await new me({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,apiVersion:"unstable"}).applePaySessionCreate(t);return JSON.parse(n)}async completePayment(t,n=void 0){w.leaveBreadcrumb("ApplePay Session completePayment",{status:t,errors:n},"log"),this.session.completePayment({status:t,errors:n}),g.authorizationComplete({instrument:this.name,measurement:Y(N.AuthorizationLatency,this.name),result:t===ApplePaySession.STATUS_SUCCESS?"success":"failure"})}getNewTotalAndLineItems(t){return{newTotal:Fi(this.merchantName,t.totalAmount),newLineItems:Ui({subtotal:an(t),discountAllocations:zi(t),deliveryGroups:t.deliveryGroups,duties:t.totalDutyAmount,taxes:t.totalTaxAmount,i18n:this.i18n,formattedRecurringTotals:Vi(this.cart.lineItems,this.i18n)})}}shouldDecelerate(t){const{checkoutUrl:n,totalAmount:r}=t;return Xe({checkoutUrl:n,instrumentName:this.name,currentCartTotal:r,initialBuyerCurrency:this.buyerCurrency})?(this.terminateSession(),!0):!1}get isShippingRequired(){return this.button.isShippingRequired}}const vo='\n';function tr({translate:e,logoElement:t,setAriaHidden:n}){const r=document.createElement("div");return e("buy_with_button_content",{wallet:"LOGO_PLACEHOLDER"}).split(new RegExp("(LOGO_PLACEHOLDER)")).filter(Boolean).forEach(a=>{let i;a==="LOGO_PLACEHOLDER"?i=t:(i=document.createElement("span"),i.innerText=a,n&&i.setAttribute("aria-hidden","true")),r.appendChild(i)}),r}var Ct;class Io extends gt{constructor(){super(),c(this,"name",b.ApplePay),c(this,"button",null),c(this,"logoElement"),j(this,Ct,void 0),J(this,Ct,this.attachShadow({mode:"closed"})),this.logoElement=new DOMParser().parseFromString(vo,"image/svg+xml").documentElement}static get observedAttributes(){return["disabled"]}get merchantName(){return this.walletParams.merchantName}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}attributeChangedCallback(t,n,r){super.attributeChangedCallback(t,n,r,this.button)}async handleClick(t){if(t.preventDefault(),this.disabled||!this.button||this.button.hasAttribute("aria-disabled"))return;this.disabled=!0;const[n,r,a]=await Promise.all([this.i18n,this.dataSource,this.apiClient]);let i;try{if(i=new Eo({accessToken:this.accessToken,buyerCountry:this.buyerCountry,buyerCurrency:this.buyerCurrency,button:this,i18n:n,merchantName:this.merchantName,dataSource:r,apiClient:a,walletParams:this.walletParams}),!i)throw new Error("missing ApplePaySession");i.begin(),g.sheetClicked({instrument:this.name,result:"success"}),rt(this.name)}catch(o){w.notify(o),g.sheetClicked({instrument:this.name,result:"failed"}),i==null||i.terminateSession()}}async render(){var t;const{translate:n}=await this.i18n;if(!this.button){if(this.button=le({label:n("buy_with_button_content",{wallet:n("brand.apple_pay")})}),this.button.onclick=r=>this.handleClick(r),this.button.classList.add("apple-pay-button",Qn[this.buttonTheme],pt.BUTTON),this.isCTA){const r=tr({translate:n,logoElement:this.logoElement,setAriaHidden:!0});r.classList.add("apple-pay--content"),this.button.appendChild(r)}else this.button.appendChild(this.logoElement);this.initializeShadowStyles(I(this,Ct),Li),I(this,Ct).appendChild(this.button),(t=this.onRendered)==null||t.call(this)}this.disabled&&(this.button.setAttribute("disabled",""),this.button.setAttribute("aria-disabled","true"))}}Ct=new WeakMap;function er(e){return function(t,n,r){const a=r.value;return r.value=function(...i){const o=a.apply(this,i);return o.eligible||console.debug("[DEBUG] ".concat(e," could not be rendered. Reason: ").concat(o.reason)),o},r}}var Po=Object.defineProperty,Do=Object.getOwnPropertyDescriptor,An=(e,t,n,r)=>{for(var a=Do(t,n),i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=o(t,n,a)||a);return a&&Po(t,n,a),a};class rr extends at{constructor(t){super(t),c(this,"companyFieldRequired"),this.companyFieldRequired=!!this.walletParams.companyRequired}static walletName(){return"apple_pay"}getWebComponentName(){return"shopify-apple-pay-button"}getWebComponentClass(){return Io}getInstrumentName(){return b.ApplePay}applePayInIframe(){return typeof window>"u"||window.self!==window.top}getLoadEligibility(){return this.applePayInIframe()?{eligible:!1,reason:"cannot be loaded in an iframe"}:{eligible:!0}}getPartnerSDKEligibility(){var t,n,r,a;return typeof window>"u"||window.ApplePaySession===void 0?{eligible:!1,reason:"window or ApplePaySession is undefined"}:(n=(t=window.ApplePaySession).supportsVersion)!=null&&n.call(t,Br)?(a=(r=window.ApplePaySession).canMakePayments)!=null&&a.call(r)?{eligible:!0}:{eligible:!1,reason:"failed SDK eligibility check"}:{eligible:!1,reason:"SDK does not meet minimum version requirement"}}}An([er("Apple Pay")],rr.prototype,"getLoadEligibility"),An([er("Apple Pay")],rr.prototype,"getPartnerSDKEligibility");const To=".buy-with-prime-button{width:100%;height:100%;padding:12px 10px 8px;display:flex;align-items:center;justify-content:center;gap:5px;opacity:1;border-width:0px}.buy-with-prime-button:hover:enabled{background-color:#0684eb!important}.buy-with-prime-button:focus{box-shadow:0 0 0 2px #1a98ff,inset 0 0 0 2px rgb(var(--color-background))!important;outline:none!important}.buy-with-prime-button:active,.buy-with-prime-button:hover:enabled:active{background-color:#0066cd!important;box-shadow:none!important}";class Zt extends Error{constructor(){super(...arguments),c(this,"name","MissingAccessTokenError")}}class nr extends Error{constructor(){super(...arguments),c(this,"name","FetchingWalletsPlatformConfigError")}}class Sn extends Error{constructor(){super(...arguments),c(this,"name","EmptyLineItemsWalletsPlatformConfigError")}}async function Cn({configOptionsEndpoint:e,checkoutUrl:t,sourceId:n,accessToken:r,instrument:a}){try{const i=JSON.stringify({checkout_url:t,checkout_cancel_url:window.location.href,cart_id:n}),o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":r},body:i});if(o.ok)return o.json();const s=await o.json();throw s.error?new Error(s.error):new Error("Could not fetch wallets platform configs: [".concat(o.status,"] ").concat(o.statusText))}catch(i){const{message:o}=i!=null?i:{};switch(o){case"empty_line_items":throw new Sn("[Fetch Pay Config][".concat(a,"] No eligible line items provided in the config request."));default:throw new nr("[Fetch Pay Config][".concat(a,"] ").concat(o))}}}const No={[C.Checkout]:"Checkout",[C.CartAjax]:"Cart",[C.CartPage]:"Cart",[C.ProductPage]:"Product",[C.Unknown]:"Product"};var zt;const _t=class Ys extends gt{constructor(){super(...arguments),c(this,"name",b.BuyWithPrime),c(this,"button",null),c(this,"apiClientId",""),j(this,zt,this.attachShadow({mode:"closed"}))}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async createButton(){const{translate:t}=await this.i18n,n=le({label:t("buy_with_button_content",{wallet:t("brand.buy_with_prime")})});return n.type="button",n.className="buy-with-prime-button",this.applyEnabledStyles(n),n}applyEnabledStyles(t){t.innerHTML=Gt.primeLogo,t.disabled=!1,lr(t,{"background-color":"#1A98FF",color:"#FFFFFF",cursor:"pointer"})}applyDisabledStyles(t){t.innerHTML=Gt.primeLogoDark,t.disabled=!0,lr(t,{"background-color":"#C0E3FF",color:"#7292AC",cursor:"not-allowed"})}async handleClick(){var t;if(!this.button)return;const[n,r]=await Promise.all([this.i18n,this.dataSource]);let a=[];try{this.applyDisabledStyles(this.button);let i=this.walletParams;if(this.apiClientId=this.apiClientId||i.appId||"",!i.createCheckoutSessionConfig){const{cart:o,outOfStock:s}=await nt({element:this,instrumentName:this.name,dataSource:r});if(s){et(n);return}if(!this.accessToken)throw new Zt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");i=A({},await Cn({configOptionsEndpoint:Ys.OPTIMUS_CONFIG_REST_API_URL,checkoutUrl:o.checkoutUrl,sourceId:(t=se(o))!=null?t:"",accessToken:this.accessToken,instrument:this.name}))}i.placement=this.getPlacement(),a=this.extractSKUs(i),delete i.checkoutSupportsSplitCart,delete i.appId,window.amazon.buywithprime.initCheckout({amazonPayOptions:i}),g.sheetClicked({instrument:this.name,result:"success",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:a,pageType:this.pageType}:void 0}),rt(this.name)}catch(i){const{name:o}=i!=null?i:{};Ys.EXPECTED_ERRORS.includes(o)||w.notify(i),g.sheetClicked({instrument:this.name,result:"failed",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:a,pageType:this.pageType}:void 0});const{title:s,content:l}=this.getErrorCopies(o,n);yt(s,l)}finally{this.applyEnabledStyles(this.button)}}getErrorCopies(t,n){const r=n.translate("brand.buy_with_prime");switch(t){case"EmptyLineItemsWalletsPlatformConfigError":return{title:n.translate("error_dialogs.wallet.buy_with_prime.empty_line_items.title"),content:n.translate("error_dialogs.wallet.buy_with_prime.empty_line_items.content")};default:return{title:n.translate("error_dialogs.wallet.title",{wallet:r}),content:n.translate("error_dialogs.wallet.generic_error",{wallet:r})}}}extractSKUs(t){var n;return(n=t.createCheckoutSessionConfig)!=null&&n.payloadJSON?JSON.parse(t.createCheckoutSessionConfig.payloadJSON).cartDetails.lineItems.map(r=>r&&r.sku).filter(r=>r):[]}getPlacement(){return this.pageType&&No[this.pageType]||"Other"}async render(){var t;this.button||(this.button=await this.createButton(),this.button.onclick=()=>this.handleClick(),this.button.classList.add("buy-with-prime-button"),this.getPlacement().includes("Checkout")||this.button.classList.add(pt.BUTTON),await this.initializeShadowStyles(I(this,zt),To),I(this,zt).appendChild(this.button),(t=this.onRendered)==null||t.call(this))}};zt=new WeakMap,c(_t,"OPTIMUS_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/optimus")),c(_t,"EXPECTED_ERRORS",[nr.name,Zt.name,Sn.name]);let Me=_t;function En(e,t=3,n=1e3,r=()=>!0){const a=()=>new Promise(o=>{setTimeout(o,n)}),i=async o=>{try{return await e()}catch(s){if(o>0&&r(s))return await a(),i(o-1);throw s}};return i(t-1)}async function Ce(e){const t=e.createCheckoutSessionConfig,n=JSON.parse(t.payloadJSON),r=new URL(n.webCheckoutDetails.checkoutReviewReturnUrl),a=await(await fetch("https:///sandbox/v2/checkoutSessions",{method:"POST",body:JSON.stringify(e),headers:{Accept:"application/json","Content-Type":"application/json;charset=UTF-8"}})).json();r.searchParams.set("amazonCheckoutSessionId",a.checkoutSessionId||"testCheckoutSessionId"),r.searchParams.set("promiseId","testPromiseId"),tt(r.toString())}const vn={buywithprime:{initCheckout:async e=>{Ce(e.amazonPayOptions)}},Pay:{initCheckout:async e=>{Ce(e)},renderButton:()=>({initCheckout:Ce,onClick:()=>{}})}};async function Ro(){return window.amazon=vn,"loaded"}async function Lo(e){return new Promise((t,n)=>{if(document.querySelector('script[src="'.concat(e,'"]'))&&window.amazon){t();return}const r=document.createElement("script");r.src=e,r.onload=()=>{window.amazon?t():n(new Error("Amazon SDK not present after loading"))},r.onerror=()=>{n(new Vt("Error loading Amazon SDK"))},document.head.append(r)})}async function In({sdkUrl:e=ze,maxRetries:t=3,shouldMock:n=!1}){if(n){await Ro();return}await En(()=>Lo(e),t,200)}const V=class qs extends at{static walletName(){return"buy_with_prime"}constructor(t){super(t)}getWebComponentName(){return"shopify-buy-with-prime-button"}getInstrumentName(){return b.BuyWithPrime}isMockedAmazonServiceUsed(){return!1}getWebComponentClass(){return Me}async loadWalletSDK(){await In({sdkUrl:qs.SDK_URL,shouldMock:this.isMockedAmazonServiceUsed(),maxRetries:qs.MAX_RETRIES}),await this.loadLogos()}async loadLogos(){await Promise.all([this.loadPrimeLogo(),this.loadPrimeLogoDark()])}async loadPrimeLogo(){qs.primeLogo=(await import("./prime-logo-DoVHKBSO.js")).default}async loadPrimeLogoDark(){qs.primeLogoDark=(await import("./prime-logo-dark-DJIA6J0w.js")).default}};c(V,"MAX_RETRIES",3),c(V,"SDK_URL",ze),c(V,"primeLogo"),c(V,"primeLogoDark");let Gt=V;const ko="shopify-amazon-pay-button div[role=button][slot=amazon-pay-slot][data-testid=amazon-pay-button]{border-radius:0!important}",Oo=[nr.name,Zt.name],Er="amazon-pay-slot";var Et;const ee=class Qs extends gt{constructor(){super(),c(this,"name",b.AmazonPay),c(this,"container",null),j(this,Et,void 0),J(this,Et,this.attachShadow({mode:"closed"}))}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async handleClick(t){var n;const[r,a]=await Promise.all([this.i18n,this.dataSource]);try{const{cart:i,outOfStock:o}=await nt({element:this,instrumentName:this.name,dataSource:a});if(o){et(r);return}const{totalAmount:{amount:s},checkoutUrl:l}=i;let u=this.walletParams;if(!u.createCheckoutSessionConfig){if(!this.accessToken)throw new Zt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");u=D(A({},await Cn({configOptionsEndpoint:Qs.CV2_CONFIG_REST_API_URL,checkoutUrl:l,sourceId:(n=se(i))!=null?n:"",accessToken:this.accessToken,instrument:this.name})),{placement:this.pageType===C.ProductPage?"Product":"Cart"})}delete u.appId,t.initCheckout(A(A({},u),Number(s)!==0&&{estimatedOrderAmount:{amount:s,currencyCode:this.buyerCurrency}})),g.sheetClicked({instrument:this.name,result:"success"}),rt(this.name)}catch(i){const{name:o}=i!=null?i:{};Oo.includes(o)||w.notify(i),g.sheetClicked({instrument:this.name,result:"failed"});const s=r.translate("brand.amazon_pay");W(s,r)}}createContainer({containerID:t,height:n}){const r=document.createElement("div");return r.id=t,r.style.display="flex",n!=null&&(r.style.height="".concat(n,"px")),r.slot=Er,r.setAttribute("data-testid","amazon-pay-button"),r}async render(){var t;try{if(!this.container){const n=document.createElement("slot");n.name=Er;const r=document.createElement("style");r.textContent=ko,this.appendChild(r),await this.initializeShadowStyles(I(this,Et));const a=await this.containerInstanceNumber,i="AcceleratedCheckoutAmazonPayButtonContainer".concat(this.pageType).concat(a),o=document.createElement("div");o.classList.add(pt.BUTTON),o.style.overflow="hidden",o.appendChild(n),I(this,Et).appendChild(o);const s=Le(o);this.container=this.createContainer({containerID:i,height:s}),this.appendChild(this.container);const l=window.amazon.Pay.renderButton("#".concat(i),D(A({},this.walletParams),{placement:this.pageType===C.ProductPage?"Product":"Cart"}));l==null||l.onClick(()=>this.handleClick(l)),(t=this.onRendered)==null||t.call(this)}}catch(n){w.notify(n)}}};Et=new WeakMap,c(ee,"CV2_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/amazon_pay"));let Fe=ee;const At=class Ks extends at{static walletName(){return"amazon_pay"}constructor(t){super(t)}getWebComponentName(){return"shopify-amazon-pay-button"}getInstrumentName(){return b.AmazonPay}isMockedAmazonServiceUsed(){return!1}getWebComponentClass(){return Fe}async loadWalletSDK(){if(await In({sdkUrl:Ks.SDK_URL,shouldMock:!1,maxRetries:Ks.MAX_RETRIES}),this.isMockedAmazonServiceUsed()){const t=window.amazon.Pay.renderButton;window.amazon.Pay.renderButton=(n,r)=>{const a=t(n,r);return a.initCheckout=vn.Pay.initCheckout,a}}}};c(At,"MAX_RETRIES",3),c(At,"SDK_URL",ze);let Ue=At;var Ee={Purple:{D0:"#4524DB",D1:"#30368D",D2:"#1C234C",L0:"#6445ED",L1:"#9C83F8",L2:"#EEEAFF",L3:"#F7F5FF",Primary:"#5433EB",PrimaryLight:"#DBD1FF"},Grayscale:{Black:"#000000",D0:"#666666",D1:"#404040",D2:"#121212",D3:"#0B0B0C",D2D:"#2A2A2A",PrimaryLight:"#707070",L1:"#A8A8A7",L2:"#CBCBCA",L2L:"#E3E3E3",L3:"#F0F0F0",L4:"#F2F4F5",White:"#FFFFFF"},Green:{D1:"#008552",D2:"#004839",L1:"#BAEBCB",L2:"#D2F2DE",L3:"#E4F6EB",Primary:"#92D08D"},Poppy:{D0:"#F05D38",D1:"#D92A0F",D2:"#832711",L1:"#FFD2C2",L2:"#FFECE9",Primary:"#FF967D"},Ochre:{D0:"#F8DB67",D1:"#E3BE2B",D2:"#C29D05",D4:"#443600",L1:"#FFF4CB",L2:"#FFF9E2",Primary:"#FFEC9F"},Brand:{Aqua:"#8DC0C6",Lime:"#C7DE00",Magenta:"#D354FF",Olive:"#8B8F01",Sage:"#D8E59D",Sand:"#F4F4ED",Violet:"#A327C2"}},xo={0:0,none:0,xxxs:2,xxs:4,xs:8,"xs-s":12,s:16,gutter:20,m:24,l:32,section:36,xl:40,xxl:48,xxxl:64,auto:"auto"},Mo=class extends HTMLElement{static get observedAttributes(){return["disabled"]}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this._updateButton()}attributeChangedCallback(){this._updateButton()}_updateButton(){var e;let t=this.shadowRoot;t&&(t.innerHTML=Uo,this.hasAttribute("disabled")&&((e=this.shadowRoot.querySelector("button"))==null||e.setAttribute("disabled","")))}};function Fo(){window.customElements&&(customElements.get("gravity-button")||customElements.define("gravity-button",Mo))}var Uo="\n\n\n\n');const Bo=".button-content{display:flex;align-items:center;justify-content:center;width:100%;height:100%;gap:3px;white-space:nowrap;container-type:inline-size;container-name:bc}.ShopPromise>.separator{margin:0 8px}@container bc (width <= 338px){.ShopPromise{display:none!important}}gravity-button{display:block}",$o='.accelerated-checkout-button{--gravity-button-height: clamp( 25px, var(--shopify-accelerated-checkout-button-block-size, 44px), 55px );--gravity-button-min-height: clamp( 25px, var(--shopify-accelerated-checkout-button-block-size, 44px), 55px );--gravity-button-border-radius: var( --shopify-accelerated-checkout-button-border-radius, 0px );--gravity-button-padding: 0px 10px;--gravity-button-width: 100%}:host([page-type="cart_page"]) .accelerated-checkout-button{--gravity-button-height: 100%;--gravity-button-min-height: 100%;--gravity-button-border-radius: var( --shopify-accelerated-checkout-button-border-radius, 4px );--gravity-button-width: 100%}';class Pn extends Error{constructor(){const t="DeliveryEstimatesResponseIsNullError";super("deliveryEstimates is null or undefined"),this.name=t}}class ve extends Error{constructor(){const t="DeliveryPromiseAPIClientError";super("window.Shopify.ShopPromise.deliveryPromiseAPIClient is undefined"),this.name=t}}const Ho=15,Go=200;class zo{constructor(t){c(this,"storefrontAPIToken"),this.storefrontAPIToken=t}async fetchDeliveryPromise({variant:t,postalCode:n,defaultPostalCode:r,sellingPlanId:a}){const i=await En(async()=>this.fetchDeliveryOptions(t,n,r,a),Ho,Go,o=>o instanceof ve).catch(o=>{if(o instanceof ve)throw o;return null});if(!i)throw new Pn;return i}async fetchDeliveryOptions(t,n,r,a){var i,o;const s={variantId:t,sellingPlanId:a,postalCode:n||r,isPostalCodeOverride:!!n},l=(o=(i=window==null?void 0:window.Shopify)==null?void 0:i.ShopPromise)==null?void 0:o.deliveryPromiseAPIClient;if(!l)throw new ve;return l(s,this.storefrontAPIToken)}}function Vo(e,t){switch(e){case 0:return(t==null?void 0:t.translate("shop_promise_delivery.same_day"))||null;case 1:return(t==null?void 0:t.translate("shop_promise_delivery.next_day"))||null;case 2:return(t==null?void 0:t.translate("shop_promise_delivery.two_day"))||null;default:return null}}const qo="delivery_promise_default_address",jo="delivery_promise_postal_code";class Wo extends de{constructor(){super(...arguments),c(this,"lastFetchedProductVariantId"),c(this,"lastFetchSellingPlan"),c(this,"fetching",!1),c(this,"i18n",null),c(this,"daysToDelivery"),c(this,"formObserver",null)}async connectedCallback(){this.formObserver=new Yr(this,({variantId:t,sellingPlanId:n})=>{this.fetchDeliveryPromise(t,n)}),this.formObserver.setupMutationObservers()}setTranslations(t){this.i18n=t,this.render()}get postalCode(){try{return JSON.parse($t(jo)||"null")||null}catch(t){return null}}get defaultDeliveryAddress(){try{return JSON.parse($t(qo)||"null")}catch(t){return null}}async fetchDeliveryPromise(t,n){var r,a,i,o;if(!(!t||!this.accessToken)&&!(t===this.lastFetchedProductVariantId&&n===this.lastFetchSellingPlan))try{this.lastFetchedProductVariantId=t,this.lastFetchSellingPlan=n;const s=((r=this.defaultDeliveryAddress)==null?void 0:r.zip)||"",l=await new zo(this.accessToken).fetchDeliveryPromise({variant:t,postalCode:this.postalCode||"",defaultPostalCode:s,sellingPlanId:n||""}),u=Je(this),d=(i=(a=l==null?void 0:l.selectedShippingOption)==null?void 0:a.brandedPromise)==null?void 0:i.handle;if((u==null?void 0:u.sellingPlanId)!==n||(u==null?void 0:u.variantId)!==t||d!=="shop_promise")return;this.daysToDelivery=(o=l==null?void 0:l.selectedShippingOption)==null?void 0:o.maxCalendarDaysToDelivery,this.render()}catch(s){s instanceof Pn&&(this.daysToDelivery=null)}}render(){const t=Vo(this.daysToDelivery,this.i18n);this.classList.add("ShopPromise"),this.innerHTML=t?'|'.concat(t,""):""}}var dt;class Yo extends gt{constructor(){super(),c(this,"name",b.ShopPay),c(this,"button",null),c(this,"shopPromiseProductPageContent",null),c(this,"shopPromiseEligible",!1),j(this,dt,void 0),J(this,dt,this.attachShadow({mode:"closed"}))}static get observedAttributes(){return["disabled"]}connectedCallback(){this.shopPromiseEligible=Gr(),this.cleanupOnFailure(async()=>{Fo(),await this.render()},this.name)}attributeChangedCallback(t,n,r){super.attributeChangedCallback(t,n,r,this.button)}async addButtonContent(){if(!this.button)return;let t;const n=await this.i18n,r=new DOMParser().parseFromString(Tn.shopPayLogoElement,"image/svg+xml").documentElement;this.isCTA?t=tr({translate:n.translate,logoElement:r,setAriaHidden:!1}):(t=document.createElement("div"),t.appendChild(r)),t.classList.add("button-content"),this.shopPromiseEligible&&!this.shopPromiseProductPageContent&&(this.shopPromiseProductPageContent=document.createElement("shop-promise-product-page-content"),this.shopPromiseProductPageContent.setTranslations(n),this.shopPromiseProductPageContent.setAttribute("access-token",this.accessToken||""),t.appendChild(this.shopPromiseProductPageContent)),this.button.appendChild(t)}getShopPayBehavior(){return this.pageType===C.ProductPage?"force_shop_pay_product":this.pageType===C.CartPage?"force_shop_pay_cart":"force_shop_pay"}async handleClick(t){if(t.preventDefault(),this.disabled||!this.button||this.button.getAttribute("disabled"))return;this.disabled=!0;const[n,r]=await Promise.all([this.i18n,this.dataSource]);try{const{outOfStock:a,cart:i}=await nt({element:this,instrumentName:b.ShopPay,dataSource:r});if(g.sheetClicked({instrument:this.name,checkoutToken:se(i),result:"success"}),a){et(n);return}rt(this.name),tt(i.checkoutUrl,this.getShopPayBehavior())}catch(a){w.notify(new Ko("An error occurred when attempting to a cart using the Shop Pay Button. Details: ".concat(a))),g.sheetClicked({instrument:this.name,result:"failed"}),yt(n.translate("error_dialogs.checkout.title"),n.translate("error_dialogs.checkout.generic_error"))}}async render(){if(I(this,dt).innerHTML)return;this.button||(this.button=document.createElement("gravity-button"));const t=document.createElement("style");t.innerHTML=[Kr,$o,Bo].join("\n"),I(this,dt).appendChild(t),await this.addButtonContent(),this.disabled&&this.button.setAttribute("disabled",""),this.button.setAttribute("aria-hidden","true"),this.button.classList.add(pt.BUTTON),this.button.onclick=n=>this.handleClick(n),I(this,dt).appendChild(this.button),this.onRendered()}}dt=new WeakMap,Z("shop-promise-product-page-content",Wo);class Ko extends Error{constructor(){super(...arguments),c(this,"name","ShopPayButtonError")}}var Jo=Object.defineProperty,Qo=Object.getOwnPropertyDescriptor,Xo=(e,t,n,r)=>{for(var a=Qo(t,n),i=e.length-1,o;i>=0;i--)(o=e[i])&&(a=o(t,n,a)||a);return a&&Jo(t,n,a),a},vt;const Dn=(vt=class extends at{static walletName(){return"shop_pay"}constructor(e){super(e)}getWebComponentName(){return"shop-pay-wallet-button"}getWebComponentClass(){return Yo}getInstrumentName(){return b.ShopPay}async loadWalletSDK(){await this.loadLogo()}getLoadEligibility(){return{eligible:!0}}async loadLogo(){vt.shopPayLogoElement=(await import("./shop-pay-logo-CYhOC7ye.js")).default}},c(vt,"shopPayLogoElement"),vt);Xo([er("Shop Pay")],Dn.prototype,"getLoadEligibility");let Tn=Dn;const Zo=".button{display:flex;justify-content:center;align-items:center;width:100%;border:none}.button:hover:not(:disabled){filter:brightness(92%);cursor:pointer}.button:disabled{opacity:.5;cursor:not-allowed}.logo-only>svg{width:50px}.dark{background:#000;color:#fff}.dark svg{fill:#fff}.light{background:#fff;outline:1px solid #3c4043;color:#000}.light svg{fill:#0000008c}.content{display:flex;justify-content:center;align-items:center;white-space:pre}";function Ie({cart:e,i18n:t}){const n=an(e),r={label:t.translate("order_summary.subtotal"),type:"SUBTOTAL",price:ut(n.amount)},a=en({deliveryGroups:e.deliveryGroups,i18n:t}).map(s=>ts({lineItem:s,type:"LINE_ITEM"})),i=es(e,t),o=[r,...a,...i];if(e.totalDutyAmount){const s={label:t.translate("order_summary.duties"),type:"LINE_ITEM",price:ut(e.totalDutyAmount.amount)};o.push(s)}if(e.totalTaxAmount){const s={label:t.translate("order_summary.taxes"),type:"TAX",price:ut(e.totalTaxAmount.amount)};o.push(s)}return{totalPrice:e.totalAmount.amount,currencyCode:e.totalAmount.currencyCode,totalPriceStatus:"ESTIMATED",totalPriceLabel:t.translate("order_summary.total"),displayItems:o}}function ts({lineItem:e,type:t,status:n="FINAL"}){return{label:e.label,type:t,price:e.amount,status:n}}function es(e,t){return[...e.lineItems.flatMap(n=>n.discountAllocations),...e.discountAllocations].flatMap(n=>{var r;const a=(r=n.title)!=null?r:n.code;return{label:a!=null?a:t.translate("order_summary.discount"),type:"LINE_ITEM",price:"-".concat(ut(Number(n.discountedAmount.amount)))}})}const Nn=["PAYMENT_AUTHORIZATION"],rs=Nn.concat(["SHIPPING_ADDRESS","SHIPPING_OPTION"]),ns=["PAN_ONLY"];function as({walletParams:e,isShippingRequired:t,hasSellingPlan:n,i18n:r,buyerCurrency:a}){const i={totalPrice:"0.01",currencyCode:a,totalPriceStatus:"ESTIMATED",totalPriceLabel:r.translate("order_summary.total"),displayItems:[{label:r.translate("order_summary.subtotal"),type:"SUBTOTAL",price:"0.01"}]},o=D(A({},e.paymentData),{shippingAddressRequired:t,shippingOptionRequired:t,transactionInfo:i});return t||delete o.shippingAddressParameters,o.callbackIntents=t?rs:Nn,n&&is(o),o}function is(e){e.allowedPaymentMethods.forEach(t=>{t.parameters.allowedAuthMethods=t.parameters.allowedAuthMethods.filter(n=>ns.includes(n))})}class os extends nn{constructor(t){super(),c(this,"brandName"),this.i18n=t,this.brandName=this.i18n.translate("brand.google_pay")}mapMutationResultToPaymentSheetAction(t){const n=this.mapCustomValidationFunctionErrorToAction(t.errors);if(n)return n;const r=this.getErrorActions(),a=t.errors,i=this.getUnhandledErrors(a,r);i.forEach(s=>{w.notify(new rn("[".concat(b.GooglePay,"] mutation result error not handled: ").concat(s)))});const{firstPaymentSheetAction:o}=this.getMergedPaymentSheetAction({result:t,errorActions:r});return o||(i.length>0?{action:"abort"}:{action:"update",errors:[]})}mapCompletionResultToPaymentSheetAction(t){if(!t.data)throw new Error("[".concat(b.GooglePay,"] completion returned null result"));switch(t.data.__typename){case"SubmitSuccess":return{action:"complete",redirectUrl:t.data.redirectUrl};case"SubmitAlreadyAccepted":case"SubmitThrottled":case"SubmitFailed":{const n=this.mapCustomValidationFunctionErrorToAction(t.errors);if(n)return n;const r=this.getErrorActions(),a=t.errors;this.getUnhandledErrors(a,r).forEach(o=>{w.notify(new Error("[".concat(b.GooglePay,"] completion result error not handled: ").concat(o)))});const{prioritizedPaymentSheetAction:i}=this.getMergedPaymentSheetAction({result:t,errorActions:r});return i||(W(this.brandName,this.i18n),{action:"abort"})}default:throw new Error("[".concat(b.GooglePay,"] unknown completion result type: ").concat(t.data.__typename))}}getErrorActions(){return[{errors:[h.InvalidLanguage],generateAction:()=>({action:"abort",effects:[()=>{w.notify(new Error("[".concat(b.GooglePay,"] mutation provided invalid language, aborting")))},()=>W(this.brandName,this.i18n)]})},{errors:[h.InvalidCountry],generateAction:()=>({action:"abort",effects:[()=>{w.notify(new Error("[".concat(b.GooglePay,"] mutation provided invalid country, aborting")))},()=>W(this.brandName,this.i18n)]})},{errors:[h.MissingCartId],generateAction:()=>({action:"abort",effects:[()=>{w.notify(new Error("[".concat(b.GooglePay,"] mutation provided invalid cart ID, aborting")))},()=>W(this.brandName,this.i18n)]})},{errors:[h.UnacceptablePaymentsAmount,h.NewTaxMustBeAccepted,h.MerchandiseExpectedPriceMismatch,h.DeliveryLineChanged,h.DeliveryLocalPickupLineChanged,...zr],generateAction:()=>({action:"abort",effects:[()=>W(this.brandName,this.i18n)]})},{errors:Vr,generateAction:()=>({action:"abort",effects:[()=>et(this.i18n)]})},{errors:[h.DeliveryNoStrategyAvailable,h.DeliveryNoLocalPickupStrategyAvailable,h.DeliveryNotAvailable],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.shipping_address")}]})},{errors:[h.NoDeliveryGroupSelected],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_OPTION_INVALID",intent:"SHIPPING_OPTION",message:this.i18n.translate("errors.missing.shipping_option")}]})},{errors:[h.BuyerIdentityEmailDomainInvalid,h.BuyerIdentityEmailNotExpectedPattern,h.BuyerIdentityEmailInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.email")}]})},{errors:[h.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.email")}]})},{errors:[h.DeliveryAddress2Required,h.DeliveryAddress2AddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address2")}]})},{errors:[h.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address2")}]})},{errors:[h.DeliveryCityAddressFieldRequired,h.DeliveryCityRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.city")}]})},{errors:[h.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.city")}]})},{errors:[h.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.zone")}]})},{errors:[h.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.zone")}]})},{errors:[h.DeliveryPostalCodeRequired,h.DeliveryPostalCodeAddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:[h.DeliveryPostalCodeInvalid,h.DeliveryInvalidPostalCodeForZone,h.DeliveryInvalidPostalCodeForCountry,h.DeliveryZipInvalidForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[h.DeliveryPhoneNumberRequired],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.phone_number")}]})},{errors:[h.DeliveryPhoneNumberInvalid,h.BuyerIdentityInvalidPhone,h.DeliveryPhoneDoesNotMatchExpectedPattern],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.phone_number")}]})},{errors:[h.BuyerIdentityInvalidCountry,h.DeliveryCountryInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.country")}]})},{errors:[h.DeliveryFirstNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.first_name")}]})},{errors:[h.DeliveryFirstNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.first_name")}]})},{errors:[h.DeliveryLastNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.last_name")}]})},{errors:[h.DeliveryLastNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.last_name")}]})},{errors:[h.DeliveryAddress1Required],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address1")}]})},{errors:[h.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address1")}]})},{errors:[h.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.last_name")}]})},{errors:[h.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.city")}]})},{errors:[h.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address1")}]})},{errors:[h.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address2")}]})},{errors:[h.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.postal_code")}]})},{errors:[h.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address1")}]})},{errors:[h.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address2")}]})},{errors:[h.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.first_name")}]})},{errors:[h.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.last_name")}]})},{errors:[h.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.city")}]})},{errors:[h.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.first_name")}]})},{errors:[h.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.last_name")}]})},{errors:[h.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address1")}]})},{errors:[h.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address2")}]})},{errors:[h.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.city")}]})},{errors:[h.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.first_name")}]})},{errors:[h.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.last_name")}]})},{errors:[h.InvalidPaymentGooglePayBillingAddress],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.billing_address")}]})},{errors:[h.UnsupportedGooglePayPaymentMethod],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.payment_method")}]})}]}mapCustomValidationFunctionErrorToAction(t){const n=t.find(r=>typeof r=="object"&&(r==null?void 0:r.code)===Qt);return n?(w.notify(new Error("[".concat(b.GooglePay,"] custom validation function error: ").concat(t))),je(this.i18n.translate("error_dialogs.wallet.title",{wallet:this.brandName}),n.message),{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_AUTHORIZATION",message:this.i18n.translate("paymentSheet.errors.unknown")}]}):null}}function ss({deliveryGroups:e,i18n:t}){var n;const r=Zr(tn(e),t),a=r.map(o=>({id:o.handle,label:o.title||"",description:o.estimatedCost?"".concat(o.estimatedCost.amount.toString()," ").concat(o.estimatedCost.currencyCode):""})),i=(n=r.find(o=>{var s;return o.handle.includes(((s=e[0].selectedDeliveryOption)==null?void 0:s.handle)||"")}))==null?void 0:n.handle;return{shippingOptions:a,defaultSelectedOptionId:i}}function Pe(e){let t=e.administrativeArea,n=e.locality;e.countryCode==="AE"&&(n=e.administrativeArea,e.administrativeArea in vr&&(t=vr[e.administrativeArea]));let r,a;if(e.name){const[i,...o]=(e.name||"").split(" ");o.length===0?a=i:a=o.join(" "),r=i}return{firstName:r,lastName:a,address1:e.address1,address2:e.address2,city:n,province:t,country:e.countryCode,phone:e.phoneNumber,zip:e.postalCode}}const vr={"\u0623\u0628\u0648 \u0638\u0628\u064A":"AZ","\u0625\u0645\u0627\u0631\u0629 \u0627\u0644\u0634\u0627\u0631\u0642\u0629\u0651":"SH",\u0627\u0644\u0641\u062C\u064A\u0631\u0629:"FU",\u0639\u062C\u0645\u0627\u0646:"AJ","\u0631\u0623\u0633 \u0627\u0644\u062E\u064A\u0645\u0629":"RK","\u0623\u0645 \u0627\u0644\u0642\u064A\u0648\u064A\u0646":"UQ",\u062F\u0628\u064A:"DU"},ls=27e3;class cs extends Error{constructor(){super(...arguments),c(this,"name","GooglePayError")}}var q;class ds{constructor({walletParams:t,isShippingRequired:n,hasSellingPlan:r,dataSource:a,button:i,i18n:o,cartClient:s,buyerCurrency:l,abortController:u}){c(this,"name",b.GooglePay),c(this,"walletParams"),c(this,"cart",null),c(this,"isShippingRequired"),c(this,"hasSellingPlan"),c(this,"dataSource"),c(this,"button"),c(this,"paymentsClient"),c(this,"i18n"),c(this,"actionGenerator"),c(this,"cartClient"),c(this,"initialBuyerCurrency"),j(this,q,void 0),c(this,"onPaymentDataChanged",async p=>{var y;const{callbackTrigger:m,shippingAddress:v,shippingOptionData:f}=p,{translate:S}=this.i18n;switch(m){case"INITIALIZE":{if(!this.cart)try{const{cart:B}=await nt({element:this.button,instrumentName:b.GooglePay,dataSource:this.dataSource});this.cart=B,g.sheetClicked({instrument:this.name,result:"success"})}catch(B){return g.sheetClicked({instrument:this.name,result:"failed"}),this.showGooglePayError("SHIPPING_ADDRESS")}return v?this.handleShippingAddress(this.cart.id,v):{newTransactionInfo:Ie({cart:this.cart,i18n:this.i18n})}}case"SHIPPING_ADDRESS":return this.cart?v?this.handleShippingAddress(this.cart.id,v):{newTransactionInfo:Ie({cart:this.cart,i18n:this.i18n})}:this.showGooglePayError(m);case"SHIPPING_OPTION":{if(!this.cart)return this.showGooglePayError(m);if(!f||!f.id)return{error:{reason:"SHIPPING_OPTION_INVALID",message:S("shipping_methods.choose_delivery_strategy"),intent:"SHIPPING_OPTION"}};const B=_n({deliveryGroups:this.cart.deliveryGroups,instrumentName:b.GooglePay,selectedDeliveryOptionHandles:f.id.split(",")}),K=await bn({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:b.GooglePay,selectedDeliveryOptions:B,abortSignal:(y=I(this,q))==null?void 0:y.signal});return K.data?(this.cart=K.data,this.updatePaymentSheet({result:K,intent:m})):this.showGooglePayError(m)}default:return this.logException("Payment data changed callback returned unexpected intent: ".concat(m),{severity:"warning"}),this.showGooglePayError("SHIPPING_ADDRESS")}}),c(this,"onPaymentAuthorized",async p=>{var y,m,v;g.authorizationAttempt(this.name),qt(N.AuthorizationLatency,this.name);const f=async _=>{var M,Rt;switch((M=_.effects)==null||M.forEach(ge=>ge()),_.action){case"complete":return g.authorizationComplete({instrument:this.name,measurement:Y(N.AuthorizationLatency,this.name),result:"success"}),tt(_.redirectUrl),{transactionState:"SUCCESS"};case"show_error":return this.handlePaymentFailure((Rt=_.errors)==null?void 0:Rt[0]);case"abort":return{transactionState:"SUCCESS"};default:throw new Error("[".concat(this.name,"] completion action not handled: ").concat(_.action))}},S=_=>"error"in _&&_.error!==void 0,B=(y=p.paymentMethodData.info)==null?void 0:y.billingAddress,K=p.shippingAddress,{signature:jt,signedMessage:ye,protocolVersion:O}=JSON.parse(p.paymentMethodData.tokenizationData.token);if(!B)return this.handlePaymentFailure();if(this.isShippingRequired&&!K)return this.handlePaymentFailure();const F=async()=>{var _;const M=p.email,Rt=this.isShippingRequired?{validateAddress:!0,streetAddress:Pe(K)}:{},ge=await St(A({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:this.name,emailAddress:M,abortSignal:(_=I(this,q))==null?void 0:_.signal},Rt));return this.updatePaymentSheet({result:ge,intent:"PAYMENT_AUTHORIZATION"})},Nt=async()=>{var _;const M=Pe(B),Rt=await Qe({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{googlePayWalletContent:{billingAddress:M,signature:jt,signedMessage:ye,protocolVersion:O}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:M,cartClient:this.cartClient,instrumentName:this.name,hasSellingPlan:this.hasSellingPlan,abortSignal:(_=I(this,q))==null?void 0:_.signal});return this.updatePaymentSheet({result:Rt,intent:"PAYMENT_AUTHORIZATION"})};try{const _=setTimeout(()=>{var Js;(Js=I(this,q))==null||Js.abort("Google Pay Timeout")},ls),M=await F();if(S(M))return this.handlePaymentFailure(M.error);const Rt=await Nt();if(S(Rt))return this.handlePaymentFailure(Rt.error);if(clearTimeout(_),(v=(m=I(this,q))==null?void 0:m.signal)!=null&&v.aborted)return this.handlePaymentFailure();const ge=await wn({cartId:this.cart.id,token:jt,cartClient:this.cartClient,instrumentName:this.name}),el=this.actionGenerator.mapCompletionResultToPaymentSheetAction(ge);return f(el)}catch(_){const{message:M}=_;return this.logException(M),this.handlePaymentFailure()}}),this.walletParams=t,this.isShippingRequired=n,this.hasSellingPlan=r,this.dataSource=a,this.button=i,this.i18n=o,this.cartClient=s,this.initialBuyerCurrency=l,J(this,q,u);const d={environment:this.walletParams.environment,merchantInfo:this.walletParams.paymentData.merchantInfo,paymentDataCallbacks:{onPaymentDataChanged:this.isShippingRequired?this.onPaymentDataChanged:void 0,onPaymentAuthorized:this.onPaymentAuthorized}};this.paymentsClient=new window.google.payments.api.PaymentsClient(d),this.actionGenerator=new os(this.i18n)}async handleClick(){if(!this.isShippingRequired)throw new Vt("Google Pay checkout started for digital cart");const t=as({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,i18n:this.i18n,buyerCurrency:this.initialBuyerCurrency});await this.paymentsClient.loadPaymentData(t)}showGooglePayError(t,{error:n}={}){return n?{error:n}:{error:{reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.wallet.generic_error",{wallet:this.i18n.translate("brand.google_pay")}),intent:t!=null?t:"SHIPPING_ADDRESS"}}}updatePaymentSheet({result:t,intent:n}){var r,a;const i=this.actionGenerator.mapMutationResultToPaymentSheetAction(t);switch(i.action){case"update":{const o=i,{data:s}=t;return s?this.isShippingRequired&&s.deliveryGroups.length===0?this.showGooglePayError("SHIPPING_ADDRESS",{error:{reason:"SHIPPING_ADDRESS_INVALID",message:this.i18n.translate("errors.address_unserviceable",{shopName:this.walletParams.paymentData.merchantInfo.merchantName}),intent:"SHIPPING_ADDRESS"}}):{newTransactionInfo:Ie({cart:s,i18n:this.i18n}),newShippingOptionParameters:this.isShippingRequired?ss({deliveryGroups:s.deliveryGroups,i18n:this.i18n}):void 0,error:(r=o.errors)==null?void 0:r[0]}:this.showGooglePayError(n)}case"show_error":return{error:(a=i.errors)==null?void 0:a[0]};case"abort":return this.showGooglePayError(n);default:return this.logException("Payment sheet update returned unexpected action (see request tab for details)",{metadata:{request:{action:i.action,intent:n}}}),this.showGooglePayError(n)}}shouldDecelerate(t,n){return Xe({checkoutUrl:t,instrumentName:this.name,currentCartTotal:n,initialBuyerCurrency:this.initialBuyerCurrency})}async handleShippingAddress(t,n){var r;const a=await St({cartClient:this.cartClient,cartId:t,streetAddress:n?Pe(n):{},instrumentName:b.GooglePay,abortSignal:(r=I(this,q))==null?void 0:r.signal});return a.data?(this.cart=a.data,this.shouldDecelerate(this.cart.checkoutUrl,this.cart.totalAmount)?{error:{reason:"OTHER_ERROR",message:this.i18n.translate("errors.currency.mismatch"),intent:"SHIPPING_ADDRESS"}}:this.updatePaymentSheet({result:a,intent:"SHIPPING_ADDRESS"})):this.showGooglePayError("SHIPPING_ADDRESS")}handlePaymentFailure(t){return g.authorizationComplete({instrument:this.name,measurement:Y(N.AuthorizationLatency,this.name),result:"failure"}),A({transactionState:"ERROR"},t?{error:t}:this.showGooglePayError("PAYMENT_AUTHORIZATION"))}logException(t,{severity:n,metadata:r}={}){w.notify(new cs(t),{severity:n!=null?n:"error",metadata:r})}}q=new WeakMap;const us='\n',hs={LIGHT:"light",DARK:"dark"};var It;class ps extends gt{constructor(){super(),c(this,"name",b.GooglePay),c(this,"paymentsClient",null),c(this,"button",null),j(this,It,void 0),c(this,"handleClick",async()=>{if(this.disabled)return;this.disabled=!0;const t=Ze();try{await this.createPaymentsClient(t),await this.paymentsClient.handleClick(),rt(this.name)}catch(n){if(this.disabled=!1,n.statusCode==="CANCELED"){t==null||t.abort("Payment sheet cancelled"),g.sheetCancelled(b.GooglePay);return}t==null||t.abort("Payment sheet failure"),w.notify(n),g.sheetClicked({instrument:this.name,result:"failed"});const r=await this.i18n,a=r.translate("brand.google_pay");W(a,r)}}),J(this,It,this.attachShadow({mode:"closed"}))}static get observedAttributes(){return["disabled"]}attributeChangedCallback(t,n,r){super.attributeChangedCallback(t,n,r,this.button)}async connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async createPaymentsClient(t){this.paymentsClient=new ds({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,dataSource:await this.dataSource,button:this,cartClient:await this.apiClient,i18n:await this.i18n,buyerCurrency:this.buyerCurrency,abortController:t})}async render(){if(this.button)return;await this.initializeShadowStyles(I(this,It),Zo);const{translate:t}=await this.i18n,n=le({label:t("buy_with_button_content",{wallet:t("brand.google_pay")})});this.disabled&&n.setAttribute("disabled",""),n.classList.add("button",pt.BUTTON,hs[this.buttonTheme]),n.onclick=this.handleClick,await this.renderButtonContent(n,t),this.button=n,I(this,It).appendChild(n),this.onRendered()}async renderButtonContent(t,n){const r=new DOMParser().parseFromString(us,"image/svg+xml").documentElement;if(t.style.font=window.getComputedStyle(this).font,this.isCTA){const a=tr({translate:n,logoElement:r,setAriaHidden:!0});a.classList.add("content"),t.appendChild(a)}else t.classList.add("logo-only"),t.appendChild(r)}}It=new WeakMap;const lt=class js extends at{static walletName(){return"google_pay"}constructor(t){super(t)}getWebComponentName(){return"shopify-google-pay-button"}getInstrumentName(){return b.GooglePay}getWebComponentClass(){return ps}async loadWalletSDK(){if(js.googlePaySDKPromise)return js.googlePaySDKPromise;const t=document.createElement("script");return t.setAttribute("src",this.walletParams.sdkUrl),js.googlePaySDKPromise=new Promise((n,r)=>{t.onload=()=>n(),t.onerror=a=>{document.body.removeChild(t),r(a)},document.body.appendChild(t)}),js.googlePaySDKPromise}getLoadEligibility(){const t=this.walletParams.expiresAt*1e3;return Ft()<=t?{eligible:!0}:{eligible:!1,reason:"authJwtExpired"}}getPartnerSDKEligibility(){return{eligible:!0}}};c(lt,"googlePaySDKPromise");let Be=lt;const ms=[Di,ke,rr,Be,Gt,Ue,Tn],ys=new Map(ms.map(e=>[e.walletName(),t=>new e(t)]));function te(e){const t=ys.get(e.name);return t?t(e):(console.debug("Can't build wallet with name ".concat(e.name)),null)}function gs(e){return e.map(t=>te(t)).filter(t=>t!=null)}const Rn="*{box-sizing:border-box}.wallet-button-fade-in{animation:animation-fade-in .3s cubic-bezier(.1,.79,1,1)}@keyframes animation-fade-in{0%{opacity:0}to{opacity:1}}button[aria-disabled=true]{opacity:.5;cursor:not-allowed}";class fs{constructor(t,n,r){this.element=t,this.apiClient=n,this.instrumentName=r}async getInitialCart(t){const n=Je(this.element);if(!n)throw new Error("[".concat(this.instrumentName,"] unable to find product form"));const r=$t(ta),{data:a,errors:i}=await this.apiClient.createCart(D(A({},n),{discountCodes:r?[r]:[],instrumentName:t}));return{cart:a,errors:i}}}function bs({instanceNumber:e,styleId:t,styles:n,cssFileName:r}){var a,i;e===1&&(i=(a=window.Shopify)==null?void 0:a.PaymentButton)!=null&&i.isStorefrontPortableWallets&&(ws({styleId:t,styles:n,cssFileName:r})||_s({styleId:t,styles:n}))}function ws({styleId:e,styles:t,cssFileName:n}){return!!document.querySelector("style#".concat(e))}function _s({styleId:e,styles:t}){const n=document.createElement("style");n.id=e,n.innerHTML=t,document.head.appendChild(n)}const H={buttonBlockSize:"--shopify-accelerated-checkout-button-block-size",buttonBorderRadius:"--shopify-accelerated-checkout-button-border-radius",buttonBoxShadow:"--shopify-accelerated-checkout-button-box-shadow",inlineAlignment:"--shopify-accelerated-checkout-inline-alignment"};function Ir(e){let t=0,n=0,r=0;const a=e.split(/\s+/);for(let i=0;i