import.meta;var Za=Object.defineProperty,Yt=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),$r=t=>{throw TypeError(t)},ei=(t,e,r)=>e in t?Za(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,d=(t,e,r)=>ei(t,typeof e!="symbol"?e+"":e,r),Vr=(t,e,r)=>e.has(t)||$r("Cannot "+r),w=(t,e,r)=>(Vr(t,e,"read from private field"),r?r.call(t):e.get(t)),G=(t,e,r)=>e.has(t)?$r("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),M=(t,e,r,n)=>(Vr(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),te=function(t,e){this[0]=t,this[1]=e},Me=(t,e,r)=>{var n=(o,s,l,c)=>{try{var u=r[o](s),h=(s=u.value)instanceof te,g=u.done;Promise.resolve(h?s[0]:s).then(m=>h?n(o==="return"?o:"next",s[1]?{done:m.done,value:m.value}:m,l,c):l({value:m,done:g})).catch(m=>n("throw",m,l,c))}catch(m){c(m)}},a=o=>i[o]=s=>new Promise((l,c)=>n(o,s,l,c)),i={};return r=r.apply(t,e),i[Yt("asyncIterator")]=()=>i,a("next"),a("throw"),a("return"),i},re=(t,e,r)=>(e=t[Yt("asyncIterator")])?e.call(t):(t=t[Yt("iterator")](),e={},r=(n,a)=>(a=t[n])&&(e[n]=i=>new Promise((o,s,l)=>(i=a.call(t,i),l=i.done,Promise.resolve(i.value).then(c=>o({value:c,done:l}),s)))),r("next"),r("return"),e);const ti=":host{display:flex;align-items:center;justify-content:center}";class ri extends HTMLElement{constructor(){super(...arguments),d(this,"size","18px"),d(this,"color","gray")}connectedCallback(){var e,r;this.attachShadow({mode:"open"}),this.size=(e=this.getAttribute("size"))!=null?e:this.size,this.color=(r=this.getAttribute("color"))!=null?r:this.color,this.render();const n=document.createElement("style");n.textContent=ti,this.shadowRoot.appendChild(n)}render(){const e=this.shadowRoot,r='\n width="'.concat(this.size,'"\n height="').concat(this.size,'"\n xmlns="http://www.w3.org/2000/svg"\n aria-hidden="true"\n ');e.innerHTML="\n \n \n \n ')}}const ni="#overlay{position:fixed;width:100%;height:100%;background:#0006;top:0;left:0;z-index:2147483647;animation:modalPop .3s ease-out}#modal{position:fixed;top:20%;left:50%;width:100%;max-width:383px;transform:translate(-50%,-100%);background:#fff;color:#000;border-radius:5px;animation:modalSlideInFromTop .3s forwards}@keyframes modalPop{0%{opacity:0}to{opacity:1}}@keyframes modalSlideInFromTop{0%{transform:translate(-50%,-100%)}to{transform:translate(-50%)}}@keyframes modalSlideInFromBottom{0%{transform:translate(-50%,100%)}to{transform:translate(-50%)}}@media only screen and (max-width: 640px){#modal{top:auto;bottom:0;animation:modalSlideInFromBottom .3s forwards}}#modal footer{padding:0 21px 21px}#modal header{display:flex;justify-content:space-between;padding:21px 21px 16px}#title{font-size:21px;font-weight:600;line-height:25.2px;margin:0;word-wrap:break-word;overflow-wrap:break-word}.capitalize:first-letter{display:inline-block;text-transform:capitalize}#content{text-align:left;padding:0 21px 16px;overflow:auto;max-height:50vh}#modal #content p{margin:0;font-size:14px;line-height:21px}#close-icon,#close-button{cursor:pointer}#close-icon{min-width:24px;background:transparent;padding:0;border:none}#close-button{width:100%;padding:16px 21px;color:#fff;background-color:#1773b0;border:none;border-radius:5px;font-size:14px;line-height:21px;font-family:inherit}#close-button:hover,#close-button:active{background:#136f99}#close-button:active,#close-button:focus{box-shadow:0 0 0 4px #1990c640}";function ai(t){return kn(t).map(e=>e instanceof Error?e:new Mn("[".concat(typeof e,"] ").concat(ii(e).slice(0,10240))))}function kn(t,e=0){return e>=20?[t,"Truncated cause stack"]:t instanceof Error&&t.cause?[t,...kn(t.cause,e+1)]:[t]}function ii(t){var e;if(typeof t=="function")return"".concat(t.name||"anonymous");if(typeof t!="string")try{return(e=JSON.stringify(t))!=null?e:typeof t}catch(r){}return"".concat(t)}var Mn=class extends Error{constructor(){super(...arguments),d(this,"name","BugsnagInvalidError")}},xn=/^\s*at .*(\S+:\d+|\(native\))/m,oi=/^(eval@)?(\[native code])?$/;function si(t){return t.stack?t.stack.match(xn)?li(t):ci(t):[]}function Fn(t){if(t.indexOf(":")===-1)return[t];let e=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(t.replace(/[()]/g,""));return[e[1],e[2]?Number(e[2]):void 0,e[3]?Number(e[3]):void 0]}function li(t){return t.stack.split("\n").filter(e=>!!e.match(xn)).map(e=>{let r=e.replace(/^\s+/,"").replace(/^.*?\s+/,""),n=r.match(/ (\(.+\)$)/);r=n?r.replace(n[0],""):r;let a=Fn(n?n[1]:r),i=n&&r||void 0,o=["eval",""].indexOf(a[0])>-1?void 0:a[0];return{method:i,file:o,lineNumber:a[1],columnNumber:a[2]}})}function ci(t){return t.stack.split("\n").filter(e=>!e.match(oi)).map(e=>{if(e.indexOf("@")===-1&&e.indexOf(":")===-1)return{method:e};let r=/((.*".+"[^@]*)?[^@]*)(?:@)/,n=e.match(r),a=n&&n[1]?n[1]:void 0,i=Fn(e.replace(r,""));return{method:a,file:i[0],lineNumber:i[1],columnNumber:i[2]}})}var qt="5",di=class{constructor(t){d(this,"breadcrumbs",[]),d(this,"apiKey"),d(this,"plugins"),d(this,"appId"),d(this,"appType"),d(this,"appVersion"),d(this,"releaseStage"),d(this,"locale"),d(this,"userAgent"),d(this,"metadata"),d(this,"persistedMetadata"),d(this,"onError"),d(this,"onPostErrorListeners",[]),d(this,"endpoints"),d(this,"session");var e,r,n;this.apiKey=t.apiKey,this.appType=t.appType,this.appId=t.appId,this.appVersion=t.appVersion,this.releaseStage=t.releaseStage,this.locale=t.locale,this.userAgent=t.userAgent,this.metadata=t.metadata,this.onError=t.onError,this.persistedMetadata={},this.endpoints=(e=t.endpoints)!=null?e:{notify:"https://error-analytics-production.shopifysvc.com",sessions:"https://error-analytics-sessions-production.shopifysvc.com/observeonly"},this.plugins=(r=t.plugins)!=null?r:[],this.plugins.forEach(a=>a.load(this)),this.leaveBreadcrumb("Bugsnag started",void 0,"state"),((n=t.withSessionTracking)==null||n)&&(this.session={id:this.getRandomUUID(),startedAt:new Date().toISOString(),events:{handled:0,unhandled:0}},this.startSession())}addMetadata(t){for(let e of Object.keys(t))this.persistedMetadata[e]=t[e]}getSessionId(){var t;return(t=this.session)==null?void 0:t.id}leaveBreadcrumb(t,e,r="manual"){this.breadcrumbs.push({name:t,metaData:e,type:r,timestamp:new Date().toISOString()})}notify(t,{errorClass:e,severity:r,severityType:n,handled:a=!0,metadata:i,context:o,groupingHash:s}={}){var l,c;let u=ai(t),h={...this.metadata,...this.persistedMetadata,...i},g=this.buildBugsnagEvent(u,{errorClass:e,severityType:n,handled:a,severity:r,metadata:h,context:o,groupingHash:s});if(((c=(l=this.onError)==null?void 0:l.call(this,g,t))==null||c)&&this.releaseStage!=="development"){this.updateAndAppendSessionInformation(g);let m=this.sendToBugsnag(g);return this.onPostErrorListeners.forEach(b=>b(g,t)),m}return Promise.resolve()}addOnPostError(t){this.onPostErrorListeners.push(t)}updateAndAppendSessionInformation(t){this.session&&(t.unhandled?this.session.events.unhandled++:this.session.events.handled++,t.session=this.session)}buildBugsnagEvent(t,{errorClass:e,severity:r="error",severityType:n="handledException",handled:a,metadata:i={},context:o,groupingHash:s}){let l=new Date().toISOString(),{breadcrumbs:c,appId:u,appType:h,appVersion:g,releaseStage:m,locale:b,userAgent:_}=this,A=t.map((v,$)=>({errorClass:$===0&&e!=null?e:v.name,stacktrace:Un(u,v),message:v.message,type:"browserjs"}));return{payloadVersion:qt,exceptions:A,severity:r,severityReason:{type:n},unhandled:!a,app:{id:u,type:h,version:g,releaseStage:m},device:{time:l,locale:b,userAgent:_},breadcrumbs:c,context:o,metaData:i,groupingHash:s}}async startSession(){var t,e;if(this.releaseStage==="development"){console.log("Skipping error logging session tracking in development mode");return}let{apiKey:r}=this,n={notifier:{name:"Bugsnag JavaScript",version:"7.22.2",url:"https://github.com/bugsnag/bugsnag-js"},app:{version:this.appVersion,releaseStage:this.releaseStage,type:this.appType},device:{id:this.appId,locale:this.locale,userAgent:this.userAgent},sessions:[this.session]};try{await fetch(this.endpoints.sessions,{method:"POST",headers:{"Content-Type":"application/json","Bugsnag-Api-Key":r,"Bugsnag-Payload-Version":qt,"Bugsnag-Sent-At":(e=(t=this.session)==null?void 0:t.startedAt)!=null?e:new Date().toISOString()},body:JSON.stringify(n,Wr())})}catch(a){console.warn("[bugsnag-light] failed to start session"),console.warn(a)}}async sendToBugsnag(t){let{apiKey:e}=this,r={apiKey:e,notifier:{name:"Bugsnag JavaScript",version:"7.22.2",url:"https://github.com/bugsnag/bugsnag-js"},events:[t]};try{await fetch(this.endpoints.notify,{method:"POST",headers:{"Content-Type":"application/json","Bugsnag-Api-Key":e,"Bugsnag-Payload-Version":qt,"Bugsnag-Sent-At":t.device.time},body:JSON.stringify(r,Wr())})}catch(n){console.warn("[bugsnag-light] failed to send an event"),console.warn(n)}}getRandomUUID(){try{return crypto.randomUUID()}catch(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}}};function Un(t,e){let r=si(e).map(n=>{var a,i,o,s;let l=(a=n.file)==null?void 0:a.includes(t);return{method:(i=n.method)!=null?i:"",file:(o=n.file)!=null?o:"",lineNumber:(s=n.lineNumber)!=null?s:0,columnNumber:n.columnNumber,inProject:l}});if(e instanceof Mn){let n=r.findIndex(a=>a.method.endsWith("notify"));n>-1&&(r=r.slice(n+1))}return r}function Wr(){let t=new WeakSet;return function(e,r){if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r}}var ui=class kh extends Error{constructor(e){super(e),d(this,"reason"),this.name="BreadcrumbsPluginFetchError",Object.setPrototypeOf(this,kh.prototype)}};function hi(t,{metadata:e}={}){let r=window.onerror;window.onerror=(n,a,i,o,s)=>{s&&t.notify(s,{severityType:"unhandledException",handled:!1,metadata:e}),typeof r=="function"&&r.apply(window.onerror,[n,a,i,o,s])}}function pi(t,{metadata:e}={}){window.addEventListener("unhandledrejection",r=>{r.reason&&r.reason instanceof Error&&r.reason.stack&&!(r.reason instanceof ui)&&t.notify(r.reason,{severityType:"unhandledPromiseRejection",handled:!1,metadata:e})})}function ut(t){try{const e=new RegExp("(^| )".concat(t,"=([^;]+)")).exec(document.cookie);if(e){const r=e[2];try{return decodeURIComponent(r)}catch(n){return r}}return null}catch(e){return null}}const or={BRANDED_BUTTON:"shopify-payment-button__button shopify-payment-button__button--branded",UNBRANDED_BUTTON:"shopify-payment-button__button shopify-payment-button__button--unbranded",MORE_PAYMENT_OPTION_BUTTON:"shopify-payment-button__more-options"},mi={DARK:"apple-pay--dark",LIGHT:"apple-pay--light"},yi=44,gi="_shopify_y",Hn=6,fi="discount_code",Ar="https://static-na.payments-amazon.com",br="".concat(Ar,"/checkout.js"),Gn="https://www.paypal.com",zn="https://pay.google.com",x={CURRENCY_CHANGE:"wallet_currency_change",CAPTCHA_REQUIRED:"wallet_captcha_required",NOT_ENOUGH_STOCK:"wallet_not_enough_stock",CART_NOT_READY:"wallet_cart_not_ready",DYNAMIC_TAX:"wallet_dynamic_tax",PAYMENT_METHOD_NOT_APPLICABLE:"wallet_payment_method_not_applicable",INVALID_PAYMENT_DEFERRED_PAYMENT_REQUIRED:"wallet_invalid_payment_deferred_payment_required",LOCALIZATION_EXTENSION_FIELD_ERROR:"wallet_localization_extension_field_error",ACCOUNT_INFO_MISMATCH:"wallet_account_info_mismatch",WALLET_PROCESSING_FAILED:"wallet_processing_failed",UNSUPPORTED_APPLE_PAY_PAYMENT_METHOD:"wallet_unsupported_apple_pay_payment_method",UNSUPPORTED_GOOGLE_PAY_PAYMENT_METHOD:"wallet_unsupported_google_pay_payment_method",PAYMENTS_COUNTRY_INVALID:"wallet_payments_country_invalid"},Ct="VALIDATION_CUSTOM",$n="portable-wallets",Le={BUTTON:"accelerated-checkout-button",CONTAINER:"accelerated-checkout-button-container"},Vn="unknown",Wn={name:"buy_it_now",wallet_params:{}};function Yn(t){try{return!t.toString().includes("[native code]")}catch(e){return!0}}const jt=new Map,_i={checkDuplicate({errorClass:t,message:e}){if(jt.has(t)){const r=jt.get(t);if(r.has(e))return!0;r.add(e)}else jt.set(t,new Set([e]));return!1},reset(){}};var mt;class oe extends Error{constructor(e,{groupingHash:r,...n}={}){super(e,n),G(this,mt),d(this,"autogenerateHash",!1),d(this,"useHashPrefix",!1),M(this,mt,r)}get groupingHash(){var e;const r=(e=w(this,mt))!=null?e:this.autogenerateHash?Ei(this.message):"";return(this.useHashPrefix?"".concat(this.name,"-").concat(r):r)||void 0}}mt=new WeakMap;function Ei(t){return t.toLowerCase().slice(0,100).replace(/[^a-z0-9\s]/g,"").trim().split(/\s+/).slice(0,5).join("-")}const _t="DeveloperError";class Y extends Error{constructor({code:e,message:r},n){const a="An unexpected error happened likely because of customizations made to HTML/JavaScript on this site ".concat(r);super("[".concat(e,"]: ").concat(a),n),d(this,"name",_t),d(this,"code"),this.code=e}}const qn="SilencedError";class ee extends Error{constructor(){super(...arguments),d(this,"name",qn)}}class Ai extends Error{constructor(){super(...arguments),d(this,"name","MissingConfigError")}}class ue extends oe{constructor(){super(...arguments),d(this,"name","NoResponseError"),d(this,"useHashPrefix",!0),d(this,"autogenerateHash",!0)}}class Et extends oe{constructor(e,{errorDetails:r}){const n=Et.generateGraphQLGroupingHash(e,r);super(e,{groupingHash:n}),d(this,"errorDetails"),d(this,"useHashPrefix",!0),this.name="GraphQLResponseError",this.errorDetails=r}static generateGraphQLGroupingHash(e,r){const{operationName:n}=r,a=this.getErrorMessageCategoryFromMessage(e);return n?"".concat(n,"-").concat(a):a}static getErrorMessageCategoryFromMessage(e){const r=[[/Variable \$\w+ of type \w+!? was provided invalid value/i,"graphql-input-validation"],[/Cannot read propert(?:y|ies)(?: .+)? of (?:null|undefined)/i,"null-property-access"],[/(?:null|undefined) is not an object/i,"null-not-object"]];for(const[i,o]of r){const s=e.match(i);if(s){const l=s[1];return l?"".concat(o,"-").concat(l):o}}let n=e;const a=[/^GraphQL response error for \w+:\s*(with status \d+\s*=>\s*|=>\s*)?/i,/^GraphQL\s+Client:\s*/i,/^GraphQL\s+response\s+error\s+for\s+\w+:\s*with\s+status\s+\d+\s*=>\s*/i,/An error occurred while fetching from the API. Review 'graphQLErrors' for details./i];for(const i of a)n=n.replace(i,"");return n=n.slice(0,100),n.toLowerCase().replace(/[^a-z0-9\s]/g,"").trim().split(/\s+/).slice(0,5).join("-")||"unknown-error"}}const jn="IgnoredGraphQLResponseError";class ht extends Et{constructor(e,{reason:r,errorDetails:n}){super(e,{errorDetails:n}),d(this,"reason"),this.name=jn,this.reason=r}}class Qn extends oe{constructor(e){const r="[".concat(e,"] completion returned null result");super(r,{groupingHash:"".concat(e,"-expected-completion-null-result")})}}function T(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var bi=0;function _e(t){return"__private_"+bi+++"_"+t}function Ut(t){return Object.entries(t).map(([e,r])=>({key:e,value:{stringValue:String(r)}}))}function Pi(t){return Object.entries(t).map(([e,r])=>({key:e,value:Kn(r)}))}function Kn(t){if(Array.isArray(t))return{arrayValue:{values:t.map(e=>Kn(e))}};switch(typeof t){case"boolean":return{boolValue:!!t};case"number":return{doubleValue:Number(t)};case"string":default:return{stringValue:String(t)}}}const Pr=1,wi=Si(5,2,12);function Si(t,e,r){const n=[0];for(let a=0;a{switch(n.attributes={...T(this,J)[J],...n.attributes},n.type){case"histogram":Ci(e,n);break;case"exponential_histogram":Di(e,n);break;case"counter":Ri(e,n);break;case"gauge":Ti(e,n);break}});const r=Object.values(e);r.length!==0&&(T(this,W)[W]=[],await T(this,Pe)[Pe].exportMetrics(r))}async exportLogs(){const e=T(this,we)[we].map(r=>{const n={timeUnixNano:r.timeUnixNano,observedTimeUnixNano:r.timeUnixNano,attributes:Pi({...T(this,J)[J],...r.attributes})};return r.body&&(n.body={stringValue:r.body}),n});e.length!==0&&(T(this,we)[we]=[],await T(this,Pe)[Pe].exportLogs(e))}}function Ci(t,e){var r;const{name:n,value:a,unit:i,timeUnixNano:o,attributes:s}=e,l=(r=e.bounds)!==null&&r!==void 0?r:wi,c=new Array(l.length+1).fill(0);t[n]||(t[n]={name:n,unit:i||"1",histogram:{aggregationTemporality:Pr,dataPoints:[]}});for(let u=0;u0?h:0,bucketCounts:n>0?[1]:[]};t[r].exponentialHistogram.dataPoints.push({attributes:Ut(o!=null?o:{}),startTimeUnixNano:i,timeUnixNano:i,count:1,sum:l,scale:c,zeroCount:g,positive:b,negative:m,min:l,max:l,zeroThreshold:0})}function Ri(t,e){const{name:r,value:n,unit:a,timeUnixNano:i,attributes:o}=e;t[r]||(t[r]={name:r,unit:a||"1",sum:{aggregationTemporality:Pr,isMonotonic:!0,dataPoints:[]}}),t[r].sum.dataPoints.push({startTimeUnixNano:i,timeUnixNano:i,asDouble:n,attributes:Ut(o!=null?o:{})})}function Ti(t,e){const{name:r,value:n,unit:a,timeUnixNano:i,attributes:o}=e;t[r]||(t[r]={name:r,unit:a||"1",gauge:{dataPoints:[]}}),t[r].gauge.dataPoints.push({startTimeUnixNano:i,timeUnixNano:i,asDouble:n,attributes:Ut(o!=null?o:{})})}var Ze=_e("url"),Se=_e("serviceName"),et=_e("logger"),tt=_e("fetchFn");class Ni{constructor(e,r,n){Object.defineProperty(this,Ze,{writable:!0,value:void 0}),Object.defineProperty(this,Se,{writable:!0,value:void 0}),Object.defineProperty(this,et,{writable:!0,value:void 0}),Object.defineProperty(this,tt,{writable:!0,value:void 0}),T(this,Ze)[Ze]=e.replace(/\/v1\/(logs|metrics|traces)\/?$/,""),T(this,Se)[Se]=r,T(this,et)[et]=n==null?void 0:n.logger,T(this,tt)[tt]=n==null?void 0:n.fetchFn}async exportMetrics(e){const r={resourceMetrics:[{resource:{attributes:[{key:"service.name",value:{stringValue:T(this,Se)[Se]}}]},scopeMetrics:[{scope:{name:"open-telemetry-mini-client",version:"1.1.0",attributes:[]},metrics:e}]}]};await this.exportTo(r,"/v1/metrics")}async exportLogs(e){const r={resourceLogs:[{resource:{attributes:[{key:"service.name",value:{stringValue:T(this,Se)[Se]}}]},scopeLogs:[{scope:{name:"open-telemetry-mini-client",version:"1.1.0",attributes:[]},logRecords:e}]}]};await this.exportTo(r,"/v1/logs")}async exportTo(e,r){var n;const a=await this.exporterFetch()("".concat(T(this,Ze)[Ze]).concat(r),{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if((n=T(this,et)[et])===null||n===void 0||n.log({status:a.status}),!a.ok){if(a.status===400){const i=await a.text();throw new ot("Invalid OpenTelemetry Data: ".concat(i))}if(a.status===429||a.status===503){const i=await a.text(),o=a.headers.get("Retry-After"),s=o?{seconds:Number(o)}:void 0;throw new ot("Server did not accept data",{errorData:i,retryAfter:s,body:e})}throw new ot("Server responded with ".concat(a.status))}}exporterFetch(){return T(this,tt)[tt]||fetch}}class ot extends Error{constructor(e,r){super(e),this.metadata=void 0,this.name="OpenTelemetryClientError",this.metadata=r}}const vi="https://otlp-http-production.shopifysvc.com",Li="portable_wallets";var ze;class Oi{constructor(e){G(this,ze),M(this,ze,e)}async exportMetrics(e){var r;try{await w(this,ze).exportMetrics(e)}catch(n){if(n instanceof ot){const a=(r=n.metadata)==null?void 0:r.retryAfter;if(a){await new Promise(i=>{setTimeout(()=>{this.exportMetrics(e),i()},a.seconds*1e3)});return}}throw new Yr("Unable to export metrics",{cause:n})}}async exportLogs(e){var r;try{await w(this,ze).exportLogs(e)}catch(n){if(n instanceof ot){const a=(r=n.metadata)==null?void 0:r.retryAfter;if(a){await new Promise(i=>{setTimeout(()=>{this.exportLogs(e),i()},a.seconds*1e3)});return}}throw new Yr("Unable to export logs",{cause:n})}}}ze=new WeakMap;const ki=new Ni(vi,Li),Mi=new Oi(ki),S=new Ii({exporter:Mi}),Xn="TelemetryExportError";class Yr extends Error{constructor(){super(...arguments),d(this,"name",Xn)}}const Jn="LimitedCartQueryError";class xi extends Error{constructor(){super(...arguments),d(this,"name",Jn)}}const Zn=["OpenTelemetryClientError",qn,Xn,jn,_t],Fi=["Load failed","Failed to fetch","when attempting to fetch resource","GraphQL mutation failed with status 404","Component closed",...Zn],qr=new Map([["TypeError","Illegal constructor"],["BugsnagInvalidError",'"isTrusted":true'],[Jn,"Limited cart query returned no response"],["AbortError","Fetch is aborted"],["SyntaxError","The string did not match the expected pattern."]]),Ui=["chrome-lighthouse","meta-externalads","crawler","spider","scraper","facebookexternalhit","bot"];function Bi(t){const e=t.exceptions[0];return Hi()?"silenced-user-agent":Gi(t)?"empty-stack-trace":zi(e)?"spin":$i()?"monkey-patch":Yi(t)?"external-error":ji(t)?"developer-error":qi(e.message)?"discarded-message":Qi(t)?"discarded-error-class":Ki(e)?"discarded-class-message":Xi(t)?"unactionable-invalid-error":Vi(t)||null}function Hi(){const t=navigator.userAgent.toLowerCase();return Ui.some(e=>t.includes(e))}function Gi(t){return t.exceptions[0].stacktrace.length===0}function zi(t){return t.stacktrace.some(e=>{var r;return(r=e.file)==null?void 0:r.includes("spin.dev")})}function $i(){return[HTMLElement,Event,document.createElement].some(Yn)}function Vi(t){const e=t.exceptions.map(r=>r.stacktrace.filter(n=>!Wi(n)));return e.some(r=>{var n;return!((n=r[0])!=null&&n.inProject)})?"external-trigger":e.some(r=>r.filter(n=>n.inProject).every(n=>[Gn,Ar,zn].some(a=>n.file.startsWith(a))))?"wallet-sdk-stack-trace":null}function Wi(t){return t.file.includes("native code")||t.file.includes("/cdn/wpm/")}function Yi(t){return!t.exceptions[0].stacktrace.some(e=>e.inProject)}function qi(t){return Fi.some(e=>t==null?void 0:t.includes(e))}function ji(t){const e=t.exceptions.some(r=>r.errorClass===_t);return e&&console.error(t.exceptions[0]),e}function Qi(t){return t.exceptions.some(e=>Zn.includes(e.errorClass))}function Ki(t){const e=t.errorClass,r=t.message;return qr.has(e)&&(r==null?void 0:r.includes(qr.get(e)))}function Xi(t){return t.exceptions[0].errorClass==="BugsnagInvalidError"&&t.unhandled}var R=(t=>(t.ButtonRender="portable_wallets_button_render",t.Decelerated="portable_wallets_decelerated",t.InitCompleted="portable_wallets_init_completed",t.InstrumentLoadEligibility="portable_wallets_instrument_load_eligibility",t.InstrumentLoadTime="portable_wallets_instrument_load_time",t.InstrumentLoadTimeFromPageLoad="portable_wallets_instrument_load_time_from_page_load",t.MonorailProduceError="portable_wallets_monorail_produce_error",t.SheetClicked="portable_wallets_sheet_clicked",t.SheetCancelled="portable_wallets_sheet_cancelled",t.SheetFailed="portable_wallets_sheet_failed",t.UpdateFailed="portable_wallets_update_failed",t.PayPalTokenCreationError="portable_wallets_paypal_token_creation_error",t.AuthorizationAttempt="portable_wallets_authorization_attempt",t.AuthorizationComplete="portable_wallets_authorization_complete",t.CartTokenMissing="portable_wallets_cart_token_missing",t.RemovePersonalDataResult="portable_wallets_cart_remove_personal_data_result",t.GooglePayNotEligibleWebview="portable_wallets_google_pay_not_eligible_webview",t.WalletConfigDeveloperError="portable_wallets_wallet_config_developer_error",t.LegacyCartCookie="portable_wallets_legacy_cart_cookie",t.StyleBackwardsCompatibility="portable_wallets_style_backwards_compatibility",t.StyleBackwardsCompatibilityExecutionTime="portable_wallets_style_backwards_compatibility_execution_time",t.StyleBackwardsCompatibilityRules="portable_wallets_style_backwards_compatibility_rules",t.AmazonPayLoadRetries="portable_wallets_amazon_pay_sdk_load_retries",t.DynamicTaxFailed="portable_wallets_dynamic_tax_failed",t.DynamicShippingFailed="portable_wallets_dynamic_shipping_failed",t.SheetLoaded="portable_wallets_sheet_loaded",t.ErrorTriggered="portable_wallets_error_triggered",t.GooglePayNullCartOnAuthorize="portable_wallets_google_pay_null_cart_on_authorize",t.UnrecoverableCartError="portable_wallets_unrecoverable_cart_error",t.ShopPayPersonalizedIframeLoadTime="portable_wallets_shop_pay_personalized_iframe_load_time",t.ShopPayPersonalizedIframeLoadTimeFromPageLoad="portable_wallets_shop_pay_personalized_iframe_load_time_from_page_load",t.PaymentCompletedAfterAbort="portable_wallets_payment_completed_after_abort",t.WalletSessionAbortError="portable_wallets_wallet_session_abort_error",t.CartPaymentUpdateRetryResult="portable_wallets_cart_payment_update_retry_result",t))(R||{}),Re=(t=>(t.InstrumentSdkLoaded="portable_wallets_instrument_sdk_loaded",t.InstrumentSdkFailed="portable_wallets_instrument_sdk_failed",t.InstrumentSdkEligible="portable_wallets_instrument_sdk_eligible",t.InstrumentSdkNotEligible="portable_wallets_instrument_sdk_not_eligible",t))(Re||{}),f=(t=>(t.BuyItNow="BuyItNow",t.MoreOptions="MoreOptions",t.ApplePay="ApplePay",t.PayPal="PayPal",t.Venmo="Venmo",t.GooglePay="GooglePay",t.ShopPay="ShopPay",t.MetaPay="FacebookPay",t.BuyWithPrime="BuyWithPrime",t.AmazonPay="AmazonPay",t.Unknown="Unknown",t))(f||{}),k=(t=>(t.InvalidQuantity="InvalidQuantity",t.VariantRequiresSellingPlan="VariantRequiresSellingPlan",t.SellingPlanNotApplicable="SellingPlanNotApplicable",t.MerchandiseIdInvalid="MerchandiseIdInvalid",t.IgnoredResponseError="IgnoredGraphQLResponseError",t.NoResponse="NoResponse",t.InvalidInput="InvalidInput",t.MerchandiseNotApplicable="MerchandiseNotApplicable",t))(k||{}),C=(t=>(t.CartPage="cart_page",t.CartAjax="cart_ajax",t.ProductPage="product",t.Checkout="checkout",t.Unknown="unknown",t))(C||{}),nt=(t=>(t.CartChange="/cart/change",t.CartUpdate="/cart/update",t.CartAdd="/cart/add",t.CartClear="/cart/clear",t))(nt||{}),Ne=(t=>(t.OneTimePurchase="ONE_TIME_PURCHASE",t.Subscription="SUBSCRIPTION",t))(Ne||{});let Bt=Ji();function Ji(){return{shop_id:Vn,debug:!1,pageType:C.Unknown}}function Zi(t){Object.assign(Bt,t)}function wr(){const{debug:t,...e}=Bt;return e}function eo(){return Bt.debug}function Sr(){return Bt.pageType}function to(t,e){const r=t.exceptions[0];if(!r||!r.message||_i.checkDuplicate(r))return!1;const n=ao(e);ro(t,n);let a=null;try{a=Bi(t)}catch(o){const s=o;console.error(s);const l={errorClass:"UnfilterableError",message:"Could not properly filter error with message: ".concat(s.message),stacktrace:Un($n,s)};t.exceptions.unshift(l)}so(a);const i=a==null;return(i||eo())&&lo({errorClass:r.errorClass,message:r.message,stacktrace:JSON.stringify(r.stacktrace),filterResult:a,metadata:JSON.stringify(t.metaData)}),i}function ro(t,e){var r,n,a,i,o;const s=(a=(n=(r=window.ShopifyAnalytics)==null?void 0:r.lib)==null?void 0:n.trekkie)==null?void 0:a.defaultAttributes;t.context=window.location.pathname,t.request||(t.request={}),t.request.url=window.location.href,t.device.orientation=(o=(i=window.screen)==null?void 0:i.orientation)==null?void 0:o.type,io(t),oo(t),t.groupingHash=no(e);const{shop_id:l,...c}=wr();t.metaData={...t.metaData,shop:{shopId:l,...c,...t.metaData.shop},custom:{...t.metaData.custom,customFetch:Yn(fetch)},error_source:{shop_id:l},monorail:s},e[0]instanceof Et&&(t.metaData.graphql={...e[0].errorDetails},e[0]instanceof ht&&(t.metaData.graphql.reason=e[0].reason))}function no(t){for(const e of t)if("groupingHash"in e&&e.groupingHash)return e.groupingHash.toString()}function ao(t){const e=[];let r=t;for(;r instanceof Error&&e.length<20;){e.push(r);const n="cause"in r?r.cause:null;if(!n)break;r=n}return e}function io(t){for(const e of t.exceptions)for(const r of e.stacktrace)[Gn,Ar,zn].some(n=>r.file.startsWith(n))&&(r.inProject=!0)}function oo(t){var e;for(const r of t.exceptions)for(const n of r.stacktrace)(e=n.file)!=null&&e.includes("portable-wallets")&&(n.file=n.file.split("#")[0].split("?")[0])}function so(t){S.counter({name:R.ErrorTriggered,value:1,attributes:{filterResult:t||"valid-error"}})}function lo(t){const e=wr();S.log({body:"Bugsnag Error",attributes:{...e,shop_id:e.shop_id,shopId:e.shop_id,...t}})}var On;const co={apiKey:"e6b446c1ebe782e2b2fc7eb8ef0dc791",appId:$n,appVersion:"0.1.12",releaseStage:"production",locale:"en",userAgent:navigator.userAgent,metadata:{user:{id:(On=ut(gi))!=null?On:"unknown"},app:{release:"38a63730d1718ed564b434a4a62eee4277c07870"}},onError:to},E=new di(co);E.addOnPostError(t=>{E.leaveBreadcrumb("Bugsnag Error Notified",{errorClass:t.exceptions[0].errorClass,message:t.exceptions[0].message},"error")});const uo={en:{express_checkout:"Express checkout",instruments_copy:{checkout:{buy_now:"Buy it now"}},error_dialogs:{checkout:{title:"Transaction failed",generic_error:"Checkout is currently unavailable due to technical problems. Please try again in a few minutes.",button_text:"Close"},product:{out_of_stock:"This item is no longer available."},wallet:{title:"%{wallet} unavailable",generic_error:"There was an issue with %{wallet}. Try again or use a different payment method.",eligibility_error:"Items that were eligible for %{wallet} are no longer in your cart."}},more_payment_options:"More payment options",action:{view:"View %{content}"},subscriptions:{cancellation_policy:"Cancellation policy",policy_not_found:"The subscription policy could not be found. Refresh the page or contact us for more information."},managed_markets:{terms_and_conditions:"Merchant of Record Terms and Conditions",privacy_policy:"Merchant of Record Privacy Policy",policy_not_found:"The policy could not be found. Refresh the page or contact us for more information"},shipping_methods:{connect_shipping_methods:"%{methodOne} and %{methodTwo}",choose_delivery_strategy:"Choose a delivery method"},delivery_promises:{connect_delivery_promises:"%{promiseOne} and %{promiseTwo}"},order_summary:{total:"Total",subtotal:"Subtotal",duties:"Duties",taxes:"Estimated taxes",shipping:"Shipping",shipping_one_time_purchase:"Shipping (One-time purchase)",shipping_subscription:"Shipping (Subscription)",discount:"Discount",subscriptions:{recurring_total_tooltip_line:"Does not include shipping, tax, duties, or any applicable discounts",recurring_totals:"%{fixedPrice} every %{interval}",recurring_totals_with_policies:{one:"First payment %{fixedPrice}, then %{recurringPrice} every %{interval}",other:"First %{count} payments %{fixedPrice} each, then %{recurringPrice} every %{interval}"},recurring_total_intervals:{day:{one:"day",other:"%{count} days"},month:{one:"month",other:"%{count} months"},week:{one:"week",other:"%{count} weeks"},year:{one:"year",other:"%{count} years"}}}},brand:{amazon_pay:"Amazon Pay",apple_pay:"Apple Pay",buy_with_prime:"Buy with Prime",paypal:"PayPal",google_pay:"Google Pay",shop_pay:"Shop Pay"},buy_with_button_content:"Buy with %{wallet}",shop_promise_delivery:{same_day:"Same-day delivery",next_day:"Next-day delivery",two_day:"2-day delivery"},errors:{address_unserviceable:"%{shopName} does not currently deliver to this address. Use a different address to complete your purchase.",missing:{email:"Enter an email address",first_name:"Enter a first name",last_name:"Enter a last name",address1:"Enter an address",address2:"Enter an apartment, suite, etc.",city:"Enter a city",zone:"Select a state / province",country:"Select a country",phone:"Enter a phone number",postal_code:"Enter a ZIP / postal code",shipping_option:"Select a shipping method",emirate:"Enter an emirate"},invalid:{email:"Enter a valid email",first_name:"Enter a valid first name",last_name:"Enter a valid last name",address1:"Enter a valid address",address2:"Enter a valid apartment, suite, etc.",city:"Enter a valid city",zone:"Select a valid state / province",country:"Select a country / region",phone:"Enter a valid phone number",postal_code:"Enter a valid zip / postal code",billing_address:"Invalid billing address",shipping_address:"Invalid shipping address",payment_method:"Invalid payment method",discount:"Invalid discount",emirate:"Enter a valid emirate"},emojis:{first_name:"First name cannot contain emojis",last_name:"Last name cannot contain emojis",city:"City cannot contain emojis",address1:"Address line cannot contain emojis",address2:"Second address line cannot contain emojis",postal_code:"Postal code/zip cannot contain emojis",phone:"Phone number cannot contain emojis"},too_long:{address1:"Address line is too long",address2:"Second address line is too long",first_name:"First name is too long",last_name:"Last name is too long",city:"City is too long"},url:{first_name:"First name cannot contain a URL",last_name:"Last name cannot contain a URL"},html_tags:{first_name:"First name cannot contain HTML tags",last_name:"Last name cannot contain HTML tags",city:"City cannot contain HTML tags",address1:"Address line cannot contain HTML tags",address2:"Second address line cannot contain HTML tags"},currency:{mismatch:"Your cart and currency has been updated based on your shipping country."}}}};let Qt;class jr extends Error{constructor(e,r){const n="i18n: Missing or invalid translation '".concat(e,"' in '").concat(r,"'");super(n)}}class ho extends Error{constructor(e,r,n){const a="i18n: Missing translation template key '".concat(e,"' for '").concat(r,"' in '").concat(n,"'");super(a)}}class po extends Error{constructor(e,r,n){const a="i18n: Invalid pluralization for '".concat(e,"':'").concat(r,"' in '").concat(n,"'");super(a)}}function Ht(){return Qt==null&&(Qt=mo(uo)),Qt}function mo(t){const e=(i,o)=>typeof i!="string"&&o.count!=="undefined",r=(i,o)=>{let s=o===1?"one":"other";return o===0&&typeof i!="string"&&i.zero!=="undefined"&&(s="zero"),s},n=(i,o={})=>{const s=i.match(/%\{.+?\}/g);return s?s.reduce((l,c)=>{const u=c.replace(/%\{(.*)\}/,"$1");return o[u]?l.replace(c,o[u]):(E.notify(new ho(u,i,a)),l)},i):i},a=yo();return{locale:a,translate(i,o={}){var s;const l=i.split(".");let c=t[a];try{for(const u of l)switch(typeof c){case"object":c=c[u];break;case"string":case"undefined":throw new jr(i,a)}if(e(c,o)){if(typeof c=="string")throw new po(i,c,a);c=c[r(c,o.count)]}if(typeof c!="string")throw new jr(i,a);return n(c,o)}catch(u){return E.notify(u),(s=o.defaultValue)!=null?s:i}}}}function yo(){return"en"}function Qr(t){const e=document.querySelectorAll("shopify-accelerated-checkout .shopify-payment-button__skeleton, shopify-accelerated-checkout-cart .wallet-cart-button__skeleton"),r=document.getElementById("shopify-buyer-consent");for(let n=0;nt=e),t]}function ra(){return!!document.querySelector('[data-source-attribution="shopify.shop-promise-pdp"]')}function ae(){return new Date().getTime()}function Ir(t){return t.find(e=>typeof e=="object"&&(e==null?void 0:e.code)===Ct)}function Kr(){const t=window.navigator.userAgent,e=t.includes("iPhone OS 26_0"),r=t.includes("Version/26.0"),n=t.includes("iPhone OS");return e||r&&n}function fo(){var t;return(t=window.scheduler)!=null&&t.yield?window.scheduler.yield():new Promise(e=>{var r;(r=window.scheduler)!=null&&r.postTask?window.scheduler.postTask(e):setTimeout(e,0)})}class _o extends HTMLElement{constructor(){super(...arguments),d(this,"originalStyle",{position:"",overflow:"",top:""}),d(this,"scrollPosition",0),d(this,"formerFocus",null)}connectedCallback(){this.attachShadow({mode:"open"}),this.formerFocus=document.activeElement;const e=Ht();this.render(e);const r=this.shadowRoot,n=r.getElementById("modal");r.querySelectorAll("button").forEach(o=>o.addEventListener("click",this.closeModal.bind(this)));const a=r.getElementById("overlay");a==null||a.addEventListener("click",o=>this.handleOutsideClick(o,n)),document.addEventListener("keydown",this.handleEscapeKey.bind(this));const i=document.createElement("style");i.textContent=ni,r.appendChild(i),this.applyScrollLock(),this.trapFocus(n,r),ce("svg-icon",ri)}trapFocus(e,r){if(!e)return;const n=e.querySelectorAll("a[href], button"),a=Array.from(n),i=a[0],o=a[a.length-1];e.addEventListener("keydown",s=>{s.key==="Tab"&&!s.shiftKey&&r.activeElement===o&&(s.preventDefault(),i.focus()),s.key==="Tab"&&s.shiftKey&&r.activeElement===i&&(s.preventDefault(),o.focus())}),i.focus()}handleOutsideClick(e,r){r&&(r.contains(e.target)||this.closeModal())}handleEscapeKey(e){e.key==="Escape"&&this.closeModal()}closeModal(){var e;this.removeScrollLock(),this.remove(),this.formerFocus&&"focus"in(this==null?void 0:this.formerFocus)&&typeof this.formerFocus.focus=="function"&&((e=this.formerFocus)==null||e.focus())}applyScrollLock(){this.originalStyle={position:document.body.style.position,overflow:document.body.style.overflow,top:document.body.style.top},document.body.style.overflow="hidden",Kr()&&(this.scrollPosition=window.scrollY,document.body.style.position="fixed",document.body.style.top="-".concat(this.scrollPosition,"px"))}removeScrollLock(){var e,r,n,a,i,o;document.body.style.overflow=(r=(e=this.originalStyle)==null?void 0:e.overflow)!=null?r:"",Kr()&&(document.body.style.position=(a=(n=this.originalStyle)==null?void 0:n.position)!=null?a:"",document.body.style.top=(o=(i=this.originalStyle)==null?void 0:i.top)!=null?o:"",window.scrollTo({top:this.scrollPosition,behavior:"instant"}))}render(e){const r=this.getAttribute("title"),n=this.getAttribute("has-close-button"),a=e.translate("error_dialogs.checkout.button_text"),i='\n \n ");this.shadowRoot.innerHTML='\n \n
\n
\n \n '.concat(r,' \n \n \n \n \n \n
\n ').concat(n?i:"","\n
\n
\n ")}}const Eo="@keyframes topLevelModalLoadingSkeleton{50%{opacity:1}75%{opacity:.5}to{opacity:1}}top-level-modal .text-skeleton{display:inline-block;width:100%;height:14px;margin-bottom:7px;animation:topLevelModalLoadingSkeleton 4s ease infinite;animation-delay:-.168s;text-decoration:none!important;background-color:#dedede}top-level-modal .text-skeleton:last-of-type{width:50%}";function Gt({type:t="button",label:e=void 0}={}){const r=document.createElement("button");return r.type=t,e&&r.setAttribute("aria-label",e),r}function At(t,e){for(const[r,n]of Object.entries(e))t.setAttribute(r,n)}function st(t,e){for(const[r,n]of Object.entries(e))t.style.setProperty(r,n)}function na(){return"\n \n \n \n \n \n \n ')}function Ao(){const t=document.querySelector("top-level-modal");t&&"closeModal"in t&&typeof t.closeModal=="function"&&t.closeModal()}function aa(t){Ao();const e=document.createElement("top-level-modal");return At(e,{"data-testid":"top-level-modal",title:t}),e}function bo(t,e){t.innerHTML=''.concat(e,"
")}function bt(t,e){const r=document.createElement("top-level-modal");r.textContent=e,At(r,{"data-testid":"top-level-modal","has-close-button":"true",title:t}),document.body.appendChild(r)}function Cr(t,e,r){const n=aa(t);e instanceof Promise?(n.innerHTML=na(),e.then(a=>{a&&a!==""?n.innerHTML=a:n.innerHTML=r!=null?r:""}).catch(()=>{n.innerHTML=r!=null?r:""})):n.innerHTML=e,document.body.appendChild(n)}function ie(t,e){bt(e.translate("error_dialogs.wallet.title",{wallet:t}),e.translate("error_dialogs.wallet.generic_error",{wallet:t}))}function je(t){bt(t.translate("error_dialogs.checkout.title"),t.translate("error_dialogs.checkout.generic_error"))}function Oe(t,e){bt(t.translate("error_dialogs.checkout.title"),e)}function ke(t,e){switch(e){case k.InvalidQuantity:case k.VariantRequiresSellingPlan:case k.SellingPlanNotApplicable:case k.MerchandiseIdInvalid:case k.IgnoredResponseError:case k.NoResponse:je(t);break}}function ge(t){bt(t.translate("error_dialogs.checkout.title"),t.translate("error_dialogs.product.out_of_stock"))}ce("top-level-modal",_o);class Pt extends HTMLElement{get buyerCountry(){return this.getAttribute("buyer-country")}get recommendedInstrument(){return this.getAttribute("recommended-instrument")}get buyerCurrency(){const e=this.getAttribute("buyer-currency");if(e==null)throw new Error("WalletElement buyer-currency is null");return e}get accessToken(){return this.getAttribute("access-token")}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get hasSellingPlan(){const e=this.getAttribute("has-selling-plan");return e==="true"||e===""}set hasSellingPlan(e){e?this.setAttribute("has-selling-plan",""):this.removeAttribute("has-selling-plan")}get isShippingRequired(){const e=this.getAttribute("requires-shipping");return e==="true"||e===""}set isShippingRequired(e){e?this.setAttribute("requires-shipping",""):this.removeAttribute("requires-shipping")}get pciEnabled(){return this.hasAttribute("pci-enabled")}}const Po="#more-payment-options-link{cursor:pointer}";function wo(t,e,r){return(e=Io(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Xr(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,n)}return r}function Jr(t){for(var e=1;ee.toString(16)).join("")}function To(t,e=!0){return t&&Object.keys(t).length&&e?Object.keys(t).map(r=>({[No(r)]:t[r]})).reduce((r,n)=>Jr(Jr({},r),n)):t}function No(t){return t.split(/(?=[A-Z])/).join("_").toLowerCase()}function vo(t){const e={"Content-Type":"application/json; charset=utf-8","X-Monorail-Edge-Event-Created-At-Ms":(t&&t.eventCreatedAtMs||Date.now()).toString(),"X-Monorail-Edge-Event-Sent-At-Ms":Date.now().toString(),"X-Monorail-Edge-Client-Message-Id":(t&&t.clientMessageId||Ro()).toString()};return t&&t.userAgent&&(e["User-Agent"]=t.userAgent),t&&t.remoteIp&&(e["X-Forwarded-For"]=t.remoteIp),t&&t.deviceInstallId&&(e["X-Monorail-Edge-Device-Install-Id"]=t.deviceInstallId),t&&t.client&&(e["X-Monorail-Edge-Client"]=t.client),t&&t.clientOs&&(e["X-Monorail-Edge-Client-OS"]=t.clientOs),e}async function Lo({endpoint:t,event:e,keepalive:r}){var n,a,i,o,s;const l=e.metadata?{clientMessageId:(n=e.metadata)===null||n===void 0?void 0:n.clientMessageId,eventCreatedAtMs:(a=e.metadata)===null||a===void 0?void 0:a.eventCreatedAtMs,consent:(i=e.metadata)===null||i===void 0?void 0:i.consent,consent_provider:(o=e.metadata)===null||o===void 0?void 0:o.consent_provider,consent_version:(s=e.metadata)===null||s===void 0?void 0:s.consent_version}:void 0;return fetch(t!=null?t:Co+Do,{method:"post",headers:vo(e.metadata),body:JSON.stringify({schema_id:e.schemaId,payload:e.payload,metadata:l&&To(l,!0)}),keepalive:r})}const Oo="2.1",ko="3",Kt={NO_VALUE:"",ACCEPTED:"1",DECLINED:"0"},Q={PREFERENCES:"p",ANALYTICS:"a",MARKETING:"m",SALE_OF_DATA:"t"},de={MARKETING:"m",ANALYTICS:"a",PREFERENCES:"p",SALE_OF_DATA:"s"},Mo=()=>typeof __CtaTestEnv__>"u"?!1:__CtaTestEnv__==="true",xo="_tracking_consent";function Zr(t){try{return decodeURIComponent(t)}catch(e){return""}}function ia(t,e=!1){const r=document.cookie?document.cookie.split("; "):[];for(let n=0;nm.charCodeAt(0).toString(16).padStart(2,"0")).join("");l=[8,13,18,23].reduce((m,b)=>m.slice(0,b)+"-"+m.slice(b),g)}function c(h){const g=r.split(".")[0];return g.includes(h.toLowerCase())?Kt.DECLINED:g.includes(h.toUpperCase())?Kt.ACCEPTED:Kt.NO_VALUE}function u(h){return r.includes(h.replace("t","s").toUpperCase())}return{v:ko,con:{CMP:{[de.ANALYTICS]:c(de.ANALYTICS),[de.PREFERENCES]:c(de.PREFERENCES),[de.MARKETING]:c(de.MARKETING),[de.SALE_OF_DATA]:c(de.SALE_OF_DATA)}},region:n||"",cus:s,purposes:{[Q.ANALYTICS]:u(Q.ANALYTICS),[Q.PREFERENCES]:u(Q.PREFERENCES),[Q.MARKETING]:u(Q.MARKETING),[Q.SALE_OF_DATA]:u(Q.SALE_OF_DATA)},sale_of_data_region:i=="t",display_banner:a=="t",consent_id:l}}function zt(t){const e=Go();if(!e||!e.purposes)return!0;const r=e.purposes[t];return typeof r=="boolean"?r:!0}function Wo(){return zt(Q.PREFERENCES)}function Yo(){return zt(Q.ANALYTICS)}function qo(){return zt(Q.MARKETING)}function jo(){return zt(Q.SALE_OF_DATA)}function Qo(){return Yo()}function Ko(){return Wo()}function Xo(){return qo()}function Jo(){return jo()}function Zo(){return Xo()}function es(){return Qo()}function ts(){return Ko()}function rs(){return Jo()}function ns(){const t=[];return es()&&t.push("analytics"),Zo()&&t.push("marketing"),rs()&&t.push("sale_of_data"),ts()&&t.push("preferences"),t}function as(t,e){switch(e){case"v1":{const r=ns();return{...t,metadata:{...t==null?void 0:t.metadata,consent:r,consent_provider:"consent-tracking-api",consent_version:e}}}default:throw new Dr(e)}}class Dr extends Error{constructor(e){super("Version ".concat(e," is not supported by the consent-tracking-api provider")),this.name="MonorailConsentTrackingApiProviderVersionError",Object.setPrototypeOf(this,Dr.prototype)}}const is=["Chrome-Lighthouse","Googlebot"];function os(){const t=navigator.userAgent;return is.some(e=>t.includes(e))}async function ss(t){if(os())return;const e=as(t,"v1");let r;try{r=await Lo({event:e})}catch(n){}if(!(r!=null&&r.ok))try{S.counter({name:R.MonorailProduceError,value:1,attributes:{schemaId:e.schemaId}})}catch(n){}}const Xt="shopify_wallet_checkout_track/6.3";async function z(t){var e,r,n,a,i,o,s;const l=await ls();if(!l)return;const c={schemaId:Xt,payload:{app_name:"storefront",page_type:go(),checkout_one:!0,event:t.event,event_subtype:t.eventSubtype,checkout_token:t.checkoutToken,instrument_id:t.instrumentId,ttl:t.ttl,error_reason:t.errorReason,uniq_token:(e=l==null?void 0:l.uniqToken)!=null?e:"",visit_token:(r=l==null?void 0:l.visitToken)!=null?r:"",micro_session_id:(n=l==null?void 0:l.microSessionId)!=null?n:"",micro_session_count:(a=l==null?void 0:l.microSessionCount)!=null?a:0,shop_id:(i=l==null?void 0:l.shopId)!=null?i:0,theme_id:l==null?void 0:l.themeId,theme_city_hash:(o=l==null?void 0:l.themeCityHash)!=null?o:"",content_language:(s=l==null?void 0:l.contentLanguage)!=null?s:"",referer:l==null?void 0:l.referer}};E.leaveBreadcrumb("monorail event produced to ".concat(Xt),{schemaId:Xt,payload:t});try{await ss(c)}catch(u){E.notify(new cs("Failed to send monorail event: ".concat(u),{cause:u}),{metadata:{request:{monorail:{payload:JSON.stringify(c)}}}})}}async function ls(){var t,e,r,n,a;return(e=(t=window==null?void 0:window.ShopifyAnalytics)==null?void 0:t.lib)!=null&&e.trekkie||await new Promise(i=>{const o=setInterval(()=>{var l,c;(c=(l=window==null?void 0:window.ShopifyAnalytics)==null?void 0:l.lib)!=null&&c.trekkie&&(clearInterval(o),i())},100),s=setTimeout(()=>{clearInterval(o),clearTimeout(s),i()},7e3)}),(a=(n=(r=window.ShopifyAnalytics)==null?void 0:r.lib)==null?void 0:n.trekkie)==null?void 0:a.defaultAttributes}class cs extends Error{constructor(){super(...arguments),d(this,"name","MonorailError")}}var B=(t=>(t.CartInitCalled="portable_wallets_cart_init_called",t.ClickSheetCancelled="portable_wallets_instrument_click_sheet_cancelled",t.ClickSheetFailed="portable_wallets_instrument_click_sheet_failure",t.ClickSheetSuccess="portable_wallets_instrument_click_sheet_success",t.SheetFailed="portable_wallets_instrument_sheet_failed",t.AuthorizationAttempt="portable_wallets_authorization_attempt",t.AuthorizationComplete="portable_wallets_authorization_complete",t.InitCalled="portable_wallets_init_called",t.InitFailed="portable_wallets_init_failed",t.InitSuccess="portable_wallets_init_success",t.UpdateFailed="portable_wallets_instrument_update_failed",t.InstrumentLoaded="portable_wallets_instrument_loaded",t.InstrumentLoadFailed="portable_wallets_instrument_load_failed",t.FirstVisible="portable_wallets_first_visible",t.FirstVisibleNotAvailable="portable_wallets_first_visible_not_available",t.SheetLoaded="portable_wallets_sheet_loaded",t.ShopPayButtonInView="portable_wallets_shop_pay_button_in_view",t))(B||{});const en={[C.Checkout]:"bwp_checkout_widget_click",[C.CartAjax]:"bwp_cart_widget_click",[C.CartPage]:"bwp_cart_widget_click",[C.ProductPage]:"bwp_widget_click",[C.Unknown]:"bwp_widget_click"};function ds({apiClientId:t,skus:e,pageType:r}){var n;if(!((n=window.Shopify)!=null&&n.analytics))return;const a=r&&en[r]||"bwp_widget_click";a===en[C.Checkout]&&window.Shopify.analytics.publish("shopify:app:pixels:load:".concat(t),{},{sendTo:"PIXEL-LOADER"}),e&&window.Shopify.analytics.publish(a,{skus:e},{sendTo:t})}function N(t){return{pageType:Sr(),...t}}function us(){const t=Sr()===C.CartPage?B.CartInitCalled:B.InitCalled;z({event:t})}function hs(t){var e,r;const n=t?"Failed":"Success",a=t&&Ls(t)?"[".concat(t.name,"]: ").concat(t.code):void 0,i=B["Init".concat(n)];z({event:i,eventSubtype:a}),S.counter({name:R.InitCompleted,value:1,attributes:N({result:n.toLowerCase(),eventType:a,recoveredFailure:!!((r=(e=window.Shopify)==null?void 0:e.PaymentButton)!=null&&r.failedToLoad)})})}function ps({instrumentOrComponentName:t,result:e,measurement:r}){z({event:e==="success"?B.InstrumentLoaded:B.InstrumentLoadFailed,instrumentId:t,ttl:r}),r!=null&&(S.histogram({name:R.InstrumentLoadTime,value:r,attributes:N({instrument:t}),unit:"ms"}),S.histogram({name:R.InstrumentLoadTimeFromPageLoad,value:window.performance.now(),attributes:N({instrument:t}),unit:"ms"}))}function ms({instrument:t,measurement:e,result:r}){const n=r==="success"?Re.InstrumentSdkLoaded:Re.InstrumentSdkFailed;z({event:n,instrumentId:t,ttl:e,errorReason:r==="success"?void 0:r}),e!=null&&S.histogram({name:Re.InstrumentSdkLoaded,value:e,attributes:N({instrument:t,result:r}),unit:"ms"})}function ys({instrument:t,result:e,reason:r}){const n=e==="success"?Re.InstrumentSdkEligible:Re.InstrumentSdkNotEligible;z({event:n,instrumentId:t}),S.counter({name:Re.InstrumentSdkEligible,value:1,attributes:N({instrument:t,reason:r,result:e})})}function gs({instrument:t,result:e,reason:r}){S.counter({name:R.InstrumentLoadEligibility,value:1,attributes:N({instrument:t,result:e,reason:r})})}function fs(t){S.counter({name:R.ButtonRender,value:1,attributes:N({result:"success",instrument:t})})}function _s(t){S.counter({name:R.ButtonRender,value:1,attributes:N({result:"failed",instrument:t})})}function Es({instrument:t,result:e,webPixelMetaData:r,reason:n}){z({event:e==="success"?B.ClickSheetSuccess:B.ClickSheetFailed,instrumentId:t}),S.counter({name:R.SheetClicked,value:1,attributes:N({instrument:t,result:e,...n&&{reason:n}})}),t===f.BuyWithPrime&&r&&ds(r)}function As(t,e){z({event:"".concat(B.UpdateFailed,"-").concat(e),instrumentId:t}),S.counter({name:R.UpdateFailed,value:1,attributes:N({instrument:t,request:e})})}function bs({errorCode:t}){S.counter({name:R.PayPalTokenCreationError,value:1,attributes:N({errorCode:t})})}function Ps(t){z({event:B.ClickSheetCancelled,instrumentId:t}),S.counter({name:R.SheetCancelled,value:1,attributes:N({instrument:t})})}function ws(t,e){z({event:B.SheetFailed,instrumentId:t,errorReason:e==null?void 0:e.message}),S.counter({name:R.SheetFailed,value:1,attributes:N({instrument:t})})}function Ss(t){z({event:B.AuthorizationAttempt,instrumentId:t}),S.counter({name:R.AuthorizationAttempt,value:1,attributes:N({instrument:t})})}function Is({instrument:t,measurement:e,result:r}){z({event:B.AuthorizationComplete,eventSubtype:r,ttl:e,instrumentId:t}),e!=null&&S.histogram({name:R.AuthorizationComplete,value:e,attributes:N({instrument:t,result:r}),unit:"ms"})}function Cs({instrument:t,reason:e}){S.counter({name:R.Decelerated,value:1,attributes:N({instrument:t,reason:e})}),p.flushTelemetry()}function Ds({reason:t}){S.counter({name:R.CartTokenMissing,value:1,attributes:{reason:t}})}function Rs({success:t}){S.counter({name:R.RemovePersonalDataResult,value:1,attributes:N({success:t})})}function Ts(){S.counter({name:R.WalletConfigDeveloperError,value:1})}function Ns(){S.counter({name:R.LegacyCartCookie,value:1})}function vs(){window.setInterval(()=>{oa()},1e3)}function Ls(t){return(t==null?void 0:t.name)===_t}function oa(){S.exportMetrics(),S.exportLogs()}function Os(t){const{body:e,attributes:r}=t,n=wr();S.log({body:e,attributes:{...n,shopId:n.shop_id,...r}})}function ks({usedBackwardsCompatibility:t}){S.counter({name:R.StyleBackwardsCompatibility,value:1,attributes:{usedBackwardsCompatibility:t}})}function Ms({measurement:t,pageType:e,stylesWritten:r}){S.histogram({name:R.StyleBackwardsCompatibilityExecutionTime,value:t,attributes:N({pageType:e,stylesWritten:r}),unit:"ms"})}function xs({rule:t,count:e,pageType:r}){S.counter({name:R.StyleBackwardsCompatibilityRules,value:e,attributes:N({rule:t,pageType:r})})}function Fs({retries:t}){S.counter({name:R.AmazonPayLoadRetries,value:1,attributes:{retries:t}})}function Us({instrument:t}){S.counter({name:R.DynamicTaxFailed,value:1,attributes:{instrument:t}}),p.log({body:"Dynamic tax failed",attributes:{instrument:t}})}function Bs({instrument:t}){S.counter({name:R.DynamicShippingFailed,value:1,attributes:{instrument:t}}),p.log({body:"Dynamic shipping failed",attributes:{instrument:t}})}function Hs({instrument:t,measurement:e}){S.histogram({name:R.SheetLoaded,value:e,attributes:N({instrument:t}),unit:"ms"})}function Gs({instrument:t,errorName:e}){S.counter({name:R.UnrecoverableCartError,value:1,attributes:N({instrument:t,errorName:e})}),p.log({body:"Unrecoverable error detected",attributes:{instrument:t,errorName:e}})}function zs({instrument:t,error:e}){S.counter({name:R.PaymentCompletedAfterAbort,value:1,attributes:N({instrument:t,error:e})})}function $s(){S.counter({name:R.GooglePayNullCartOnAuthorize,value:1,attributes:N({instrument:f.GooglePay})})}function Vs({instrument:t,errorName:e,methodName:r}){S.counter({name:R.WalletSessionAbortError,value:1,attributes:N({instrument:t,errorName:e,methodName:r})}),p.log({body:"Wallet session abort error: ".concat(e),attributes:{instrument:t,methodName:r}})}function Ws({instrument:t,retryCount:e,retryDuration:r,success:n,totalAmountChange:a,...i}){S.histogram({name:R.CartPaymentUpdateRetryResult,value:r,attributes:N({instrument:t,retryCount:e,success:n,totalAmountChange:a}),unit:"ms"}),p.log({body:"Cart payment update retry completed",attributes:{instrument:t,retryCount:e,retryDuration:r,success:n,totalAmountChange:a,...i}})}const p={initStarted:D(us),initCompleted:D(hs),instrumentLoaded:D(ps),instrumentLoadEligibility:D(gs),instrumentSDKLoaded:D(ms),instrumentSDKEligible:D(ys),renderSucceeded:D(fs),renderFailed:D(_s),sheetClicked:D(Es),sheetCancelled:D(Ps),sheetFailed:D(ws),updateFailed:D(As),authorizationAttempt:D(Ss),authorizationComplete:D(Is),startExporter:D(vs),decelerated:D(Cs),cartTokenMissing:D(Ds),removePersonalDataResult:D(Rs),walletConfigDeveloperError:D(Ts),legacyCartCookie:D(Ns),flushTelemetry:D(oa),styleBackwardsCompatibility:D(ks),styleBackwardsCompatibilityExecutionTime:D(Ms),styleBackwardsCompatibilityRules:D(xs),amazonPaySDKLoadRetries:D(Fs),dynamicTaxFailed:D(Us),dynamicShippingFailed:D(Bs),sheetLoaded:D(Hs),unrecoverableCartError:D(Gs),paymentCompletedAfterAbort:D(zs),googlePayNullCartOnAuthorize:D($s),log:D(Os,{logErrors:!1}),paypalTokenCreationError:D(bs),walletSessionAbortError:D(Vs),cartPaymentUpdateRetryResult:D(Ws)};function D(t,{logErrors:e=!0}={}){return(...r)=>{try{t(...r)}catch(n){e&&p.log({body:"Error calling telemetry function",attributes:{error:"".concat(n)}})}}}function Ys(t){const e=r=>{r.persisted&&(t(),window.removeEventListener("pageshow",e))};window.addEventListener("pageshow",e)}var y=(t=>(t.InvalidLanguage="Variable $language of type LanguageCode was provided invalid value",t.InvalidCountry="Variable $country of type CountryCode was provided invalid value",t.MissingCartId="Variable $cartId of type ID! was provided invalid value",t.BuyerIdentityInvalidCountry="Variable $buyerIdentity of type CartBuyerIdentityInput! was provided invalid value for countryCode",t.BuyerIdentityInvalidPhone="INVALID: buyerIdentity.phone",t.BuyerIdentityEmailRequired="BUYER_IDENTITY_EMAIL_REQUIRED",t.BuyerIdentityEmailDomainInvalid="BUYER_IDENTITY_EMAIL_DOMAIN_IS_INVALID",t.BuyerIdentityEmailNotExpectedPattern="BUYER_IDENTITY_EMAIL_DOES_NOT_MATCH_EXPECTED_PATTERN",t.BuyerIdentityEmailInvalid="INVALID: buyerIdentity.email",t.CaptchaCompletionRequired="CAPTCHA_COMPLETION_REQUIRED",t.CustomValidation="".concat(Ct),t.RedirectToCheckoutRequired="REDIRECT_TO_CHECKOUT_REQUIRED",t.InvalidInput="INVALID: input",t.DeliveryFirstNameInvalid="DELIVERY_FIRST_NAME_INVALID",t.DeliveryFirstNameRequired="DELIVERY_FIRST_NAME_REQUIRED",t.BuyerIdentityDeliveryFirstNameRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName",t.DeliveryFirstNameContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName",t.DeliveryFirstNameTooLong="ADDRESS_FIELD_IS_TOO_LONG: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName",t.DeliveryFirstNameContainsUrl="ADDRESS_FIELD_CONTAINS_URL: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName",t.DeliveryFirstNameContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName",t.DeliveryFirstNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName",t.DeliveryLastNameInvalid="DELIVERY_LAST_NAME_INVALID",t.DeliveryLastNameRequired="DELIVERY_LAST_NAME_REQUIRED",t.BuyerIdentityDeliveryLastNameRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName",t.DeliveryLastNameContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName",t.DeliveryLastNameTooLong="ADDRESS_FIELD_IS_TOO_LONG: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName",t.DeliveryLastNameContainsUrl="ADDRESS_FIELD_CONTAINS_URL: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName",t.DeliveryLastNameContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName",t.DeliveryLastNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName",t.BuyerIdentityDeliveryAddress1Required="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1",t.DeliveryAddress1Required="DELIVERY_ADDRESS1_REQUIRED",t.DeliveryAddress1Invalid="DELIVERY_ADDRESS1_INVALID",t.DeliveryAddress1TooLong="ADDRESS_FIELD_IS_TOO_LONG: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1",t.DeliveryAddress1ContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1",t.DeliveryAddress1ContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1",t.DeliveryAddress2Required="DELIVERY_ADDRESS2_REQUIRED",t.DeliveryAddress2AddressFieldRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2",t.DeliveryAddress2Invalid="DELIVERY_ADDRESS2_INVALID",t.DeliveryAddress2TooLong="ADDRESS_FIELD_IS_TOO_LONG: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2",t.DeliveryAddress2ContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2",t.DeliveryAddress2ContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2",t.DeliveryCityRequired="DELIVERY_CITY_REQUIRED",t.DeliveryCityAddressFieldRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city",t.DeliveryCityInvalid="DELIVERY_CITY_INVALID",t.DeliveryCityTooLong="ADDRESS_FIELD_IS_TOO_LONG: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city",t.DeliveryCityContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city",t.DeliveryCityContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city",t.DeliveryZoneNotFound="DELIVERY_ZONE_NOT_FOUND",t.DeliveryZoneRequiredForCountry="DELIVERY_ZONE_REQUIRED_FOR_COUNTRY",t.DeliveryProvinceRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.province",t.DeliveryPostalCodeInvalid="DELIVERY_POSTAL_CODE_INVALID",t.DeliveryInvalidPostalCodeForZone="DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE",t.DeliveryInvalidPostalCodeForCountry="DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY",t.DeliveryPostalCodeRequired="DELIVERY_POSTAL_CODE_REQUIRED",t.DeliveryPostalCodeAddressFieldRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip",t.DeliveryZipInvalidForProvince="INVALID_ZIP_CODE_FOR_PROVINCE",t.BuyerIdentityDeliveryZipInvalidForProvince="INVALID_ZIP_CODE_FOR_PROVINCE: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip",t.DeliveryZipInvalidForCountry="INVALID_ZIP_CODE_FOR_COUNTRY: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip",t.DeliveryPostalCodeContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip",t.DeliveryCountryRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country",t.DeliveryCountryInvalid="INVALID: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country",t.DeliveryPhoneNumberRequired="DELIVERY_PHONE_NUMBER_REQUIRED",t.BuyerIdentityDeliveryPhoneNumberRequired="ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone",t.DeliveryOptionsPhoneNumberRequired="DELIVERY_OPTIONS_PHONE_NUMBER_REQUIRED",t.DeliveryPhoneNumberInvalid="DELIVERY_PHONE_NUMBER_INVALID",t.DeliveryPhoneDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone",t.MerchandiseOutOfStock="MERCHANDISE_OUT_OF_STOCK",t.MerchandiseNotEnoughStock="MERCHANDISE_NOT_ENOUGH_STOCK",t.InvalidQuantity="INVALID: input.lines.0.quantity",t.DeliveryOutOfStockAtOrigin="DELIVERY_OUT_OF_STOCK_AT_ORIGIN_LOCATION",t.DeliveryExternalPromiseUnfulfillable="DELIVERY_EXTERNAL_PROMISE_UNFULFILLABLE",t.MerchandiseNotApplicable="MERCHANDISE_NOT_APPLICABLE",t.MerchandiseNotApplicableForMerchandiseId="MERCHANDISE_NOT_APPLICABLE: input.lines.0.merchandiseId",t.MerchandiseVariantNotFound="MERCHANDISE_PRODUCT_VARIANT_NOT_FOUND",t.MerchandiseNotFound="MERCHANDISE_NOT_FOUND",t.MerchandiseNotPublished="MERCHANDISE_PRODUCT_NOT_PUBLISHED",t.MerchandiseNotSupportedForB2B="MERCHANDISE_SELLING_PLANS_NOT_SUPPORTED_FOR_B2B",t.MerchandiseBundleRequiresComponents="MERCHANDISE_BUNDLE_REQUIRES_COMPONENTS",t.MerchandiseGiftCardsNotSupported="MERCHANDISE_GIFT_CARDS_COMPONENTS_NOT_SUPPORTED",t.MerchandiseGiftCardGreaterThanZero="MERCHANDISE_GIFT_CARD_PRICE_MUST_BE_GREATER_THAN_ZERO",t.MerchandiseGiftCardCannotExceedLimit="MERCHANDISE_GIFT_CARD_PRICE_MUST_NOT_EXCEED_LIMIT",t.MerchandiseIdInvalid="INVALID: input.lines.0.merchandiseId",t.UnacceptablePaymentsAmount="PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT",t.DiscountNotApplicable="DISCOUNT_NOT_APPLICABLE",t.DeliveryNotAvailable="DELIVERY_NO_DELIVERY_AVAILABLE",t.DeliveryNoStrategyAvailable="DELIVERY_NO_DELIVERY_STRATEGY_AVAILABLE",t.DeliveryNoLocalPickupStrategyAvailable="DELIVERY_LOCAL_PICKUP_NO_DELIVERY_STRATEGY_AVAILABLE",t.DeliveryLineChanged="DELIVERY_DELIVERY_LINE_DETAIL_CHANGED",t.DeliveryLocalPickupLineChanged="DELIVERY_LOCAL_PICKUP_DELIVERY_LINE_DETAIL_CHANGED",t.DeliveryNoDeliveryAvailableForMerchandise="DELIVERY_NO_DELIVERY_STRATEGY_AVAILABLE_FOR_MERCHANDISE_LINE",t.DeliveryFulfillmentConstraintNotSatisfied="DELIVERY_MUST_FULFILL_FROM_CONSTRAINT_NOT_SATISFIED",t.DeliveryFulfillmentLocationConstraint="DELIVERY_MUST_FULFILL_FROM_SAME_LOCATION_CONSTRAINT_NOT_SATISFIED",t.NoDeliveryGroupSelected="NO_DELIVERY_GROUP_SELECTED",t.DeliveryOptionInvalid="INVALID_DELIVERY_OPTION: selectedDeliveryOptions",t.DeliveryGroupInvalid="INVALID_DELIVERY_GROUP: selectedDeliveryOptions",t.DeliveryDetailChanged="DELIVERY_DETAIL_CHANGED",t.PendingDeliveryGroups="PENDING_DELIVERY_GROUPS",t.InvalidPaymentAmount="INVALID_PAYMENT: amount",t.InvalidPaymentPaymentAmount="INVALID_PAYMENT: payment.amount",t.InvalidPaymentPayment="INVALID_PAYMENT: payment",t.InvalidPaymentEmptyCart="INVALID_PAYMENT_EMPTY_CART: payment",t.NewTaxMustBeAccepted="TAX_NEW_TAX_MUST_BE_ACCEPTED",t.MerchandiseExpectedPriceMismatch="MERCHANDISE_EXPECTED_PRICE_MISMATCH",t.InvalidPaymentApplePayBillingAddress="INVALID_PAYMENT: payment.walletPaymentMethod.applePayWalletContent.billingAddress",t.InvalidPaymentApplePayBillingAddressRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress",t.InvalidPaymentGooglePayBillingAddress="INVALID_PAYMENT: payment.walletPaymentMethod.googlePayWalletContent.billingAddress",t.InvalidPaymentBillingAddress="INVALID_PAYMENT: payment.freePaymentMethod.billingAddress",t.UnspecifiedBillingAddressError="UNSPECIFIED_ADDRESS_ERROR: payment.walletPaymentMethod.applePayWalletContent.billingAddress",t.ApplePayBillingZipInvalidForProvince="INVALID_ZIP_CODE_FOR_PROVINCE: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip",t.ApplePayBillingZipInvalidForCountry="INVALID_ZIP_CODE_FOR_COUNTRY: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip",t.GooglePayBillingZipInvalidForProvince="INVALID_ZIP_CODE_FOR_PROVINCE: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip",t.GooglePayBillingZipInvalidForCountry="INVALID_ZIP_CODE_FOR_COUNTRY: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip",t.FreePaymentBillingZipInvalidForProvince="INVALID_ZIP_CODE_FOR_PROVINCE: payment.freePaymentMethod.billingAddress.zip",t.FreePaymentBillingZipInvalidForCountry="INVALID_ZIP_CODE_FOR_COUNTRY: payment.freePaymentMethod.billingAddress.zip",t.FreePaymentBillingFirstNameRequired="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.firstName",t.FreePaymentBillingLastNameRequired="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.lastName",t.FreePaymentBillingAddress1Required="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address1",t.FreePaymentBillingAddress2Required="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address2",t.FreePaymentBillingCityRequired="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.city",t.FreePaymentBillingPhoneRequired="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.phone",t.FreePaymentBillingZipRequired="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.zip",t.FreePaymentBillingProvinceRequired="ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.province",t.FreePaymentBillingFirstNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.firstName",t.FreePaymentBillingLastNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.lastName",t.FreePaymentBillingCompanyDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.company",t.FreePaymentBillingAddress1DoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address1",t.FreePaymentBillingAddress2DoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address2",t.FreePaymentBillingCityDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.city",t.FreePaymentBillingPhoneDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.phone",t.FreePaymentBillingZipDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.zip",t.ApplePayBillingFirstNameRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName",t.ApplePayBillingLastNameRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName",t.ApplePayBillingAddress1Required="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1",t.ApplePayBillingAddress2Required="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2",t.ApplePayBillingCityRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city",t.ApplePayBillingPhoneRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.phone",t.ApplePayBillingZipRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip",t.ApplePayBillingProvinceRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.province",t.ApplePayBillingFirstNameContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName",t.ApplePayBillingLastNameContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName",t.ApplePayBillingCompanyContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.company",t.ApplePayBillingAddress1ContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1",t.ApplePayBillingAddress2ContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2",t.ApplePayBillingCityContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city",t.ApplePayBillingPhoneContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.phone",t.ApplePayBillingZipContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip",t.ApplePayBillingFirstNameContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName",t.ApplePayBillingLastNameContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName",t.ApplePayBillingCompanyContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.company",t.ApplePayBillingAddress1ContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1",t.ApplePayBillingAddress2ContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2",t.ApplePayBillingCityContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city",t.ApplePayBillingFirstNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName",t.ApplePayBillingLastNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName",t.ApplePayBillingCompanyDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.company",t.ApplePayBillingAddress1DoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1",t.ApplePayBillingAddress2DoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2",t.ApplePayBillingCityDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city",t.ApplePayBillingPhoneDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.phone",t.ApplePayBillingZipDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip",t.GooglePayBillingFirstNameRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName",t.GooglePayBillingLastNameRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName",t.GooglePayBillingAddress1Required="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1",t.GooglePayBillingAddress2Required="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2",t.GooglePayBillingCityRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city",t.GooglePayBillingPhoneRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.phone",t.GooglePayBillingZipRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip",t.GooglePayBillingProvinceRequired="ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.province",t.GooglePayBillingFirstNameContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName",t.GooglePayBillingLastNameContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName",t.GooglePayBillingCompanyContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.company",t.GooglePayBillingAddress1ContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1",t.GooglePayBillingAddress2ContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2",t.GooglePayBillingCityContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city",t.GooglePayBillingPhoneContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.phone",t.GooglePayBillingZipContainsEmojis="ADDRESS_FIELD_CONTAINS_EMOJIS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip",t.GooglePayBillingFirstNameContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName",t.GooglePayBillingLastNameContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName",t.GooglePayBillingCompanyContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.company",t.GooglePayBillingAddress1ContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1",t.GooglePayBillingAddress2ContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2",t.GooglePayBillingCityContainsHtmlTags="ADDRESS_FIELD_CONTAINS_HTML_TAGS: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city",t.GooglePayBillingFirstNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName",t.GooglePayBillingLastNameDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName",t.GooglePayBillingCompanyDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.company",t.GooglePayBillingAddress1DoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1",t.GooglePayBillingAddress2DoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2",t.GooglePayBillingCityDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city",t.GooglePayBillingPhoneDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.phone",t.GooglePayBillingZipDoesNotMatchExpectedPattern="ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip",t.UnsupportedGooglePayPaymentMethod="PAYMENT_METHOD_NOT_SUPPORTED: payment.walletPaymentMethod.googlePayWalletContent",t.UnsupportedApplePayPaymentMethod="PAYMENT_METHOD_NOT_SUPPORTED: payment.walletPaymentMethod.applePayWalletContent",t.PaymentMethodNotApplicable="PAYMENT_METHOD_NOT_APPLICABLE: payment",t.InvalidPaymentDeferredPaymentRequired="INVALID_PAYMENT_DEFERRED_PAYMENT_REQUIRED: payment",t.PaymentsMethodRequired="PAYMENTS_METHOD_REQUIRED",t.PaymentsMethodUnavailable="PAYMENTS_METHOD_UNAVAILABLE",t.SellingPlanNotApplicable="SELLING_PLAN_NOT_APPLICABLE: input.lines.0.sellingPlanId",t.VariantRequiresSellingPlan="VARIANT_REQUIRES_SELLING_PLAN: input.lines.0",t.PaymentsCountryInvalid="PAYMENTS_COUNTRY_INVALID",t.LocalizationExtensionFieldError="LOCALIZATION_EXTENSION_FIELD_ERROR",t.NoResponse="NO_RESPONSE",t.GenericError="ERROR",t.ContactInfoDoesNotMatchCustomerProfile="BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE",t))(y||{});const qs=["DELIVERY_FIRST_NAME_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName"],js=["DELIVERY_FIRST_NAME_INVALID","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName"],Qs=["DELIVERY_LAST_NAME_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName"],Ks=["DELIVERY_LAST_NAME_INVALID","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName"],Xs=["DELIVERY_ADDRESS1_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1"],Js=["DELIVERY_ADDRESS2_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2"],Zs=["DELIVERY_CITY_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city"],el=["DELIVERY_POSTAL_CODE_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],sa=["DELIVERY_POSTAL_CODE_INVALID","INVALID_ZIP_CODE_FOR_COUNTRY: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip","INVALID_ZIP_CODE_FOR_PROVINCE","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE","DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","INVALID_ZIP_CODE_FOR_PROVINCE: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],tl=["DELIVERY_PHONE_NUMBER_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],rl=["INVALID: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country","Variable $buyerIdentity of type CartBuyerIdentityInput! was provided invalid value for countryCode"],nl=["DELIVERY_PHONE_NUMBER_INVALID","INVALID: buyerIdentity.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],la=["INVALID_DELIVERY_OPTION: selectedDeliveryOptions","INVALID_DELIVERY_GROUP: selectedDeliveryOptions","DELIVERY_NO_DELIVERY_AVAILABLE","DELIVERY_DETAIL_CHANGED","NO_DELIVERY_GROUP_SELECTED","DELIVERY_NO_DELIVERY_STRATEGY_AVAILABLE","DELIVERY_LOCAL_PICKUP_NO_DELIVERY_STRATEGY_AVAILABLE"],ca=["INVALID_PAYMENT: amount","INVALID_PAYMENT: payment.amount","INVALID_PAYMENT: payment"],Rr=["TAX_NEW_TAX_MUST_BE_ACCEPTED","PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"],al=["DELIVERY_DELIVERY_LINE_DETAIL_CHANGED","DELIVERY_LOCAL_PICKUP_DELIVERY_LINE_DETAIL_CHANGED"],il=["INVALID_PAYMENT: payment.freePaymentMethod.billingAddress","INVALID_PAYMENT: payment.walletPaymentMethod.applePayWalletContent.billingAddress","ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress","UNSPECIFIED_ADDRESS_ERROR: payment.walletPaymentMethod.applePayWalletContent.billingAddress"],ol=["INVALID_ZIP_CODE_FOR_PROVINCE: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip","INVALID_ZIP_CODE_FOR_COUNTRY: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip","INVALID_ZIP_CODE_FOR_PROVINCE: payment.freePaymentMethod.billingAddress.zip","INVALID_ZIP_CODE_FOR_COUNTRY: payment.freePaymentMethod.billingAddress.zip"],sl=["INVALID_ZIP_CODE_FOR_PROVINCE: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip","INVALID_ZIP_CODE_FOR_COUNTRY: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip","INVALID_ZIP_CODE_FOR_PROVINCE: payment.freePaymentMethod.billingAddress.zip","INVALID_ZIP_CODE_FOR_COUNTRY: payment.freePaymentMethod.billingAddress.zip"],Tr=["MERCHANDISE_NOT_APPLICABLE","MERCHANDISE_PRODUCT_VARIANT_NOT_FOUND","MERCHANDISE_NOT_FOUND","MERCHANDISE_PRODUCT_NOT_PUBLISHED"],da=["MERCHANDISE_NOT_ENOUGH_STOCK","DELIVERY_NO_DELIVERY_STRATEGY_AVAILABLE_FOR_MERCHANDISE_LINE","DELIVERY_OUT_OF_STOCK_AT_ORIGIN_LOCATION","DELIVERY_MUST_FULFILL_FROM_CONSTRAINT_NOT_SATISFIED","DELIVERY_MUST_FULFILL_FROM_SAME_LOCATION_CONSTRAINT_NOT_SATISFIED","DELIVERY_EXTERNAL_PROMISE_UNFULFILLABLE","MERCHANDISE_SELLING_PLANS_NOT_SUPPORTED_FOR_B2B","MERCHANDISE_BUNDLE_REQUIRES_COMPONENTS","MERCHANDISE_GIFT_CARDS_COMPONENTS_NOT_SUPPORTED","MERCHANDISE_GIFT_CARD_PRICE_MUST_BE_GREATER_THAN_ZERO","MERCHANDISE_GIFT_CARD_PRICE_MUST_NOT_EXCEED_LIMIT","INVALID: input.lines.0.quantity"],ll=["MERCHANDISE_OUT_OF_STOCK",...Tr],cl=["MERCHANDISE_OUT_OF_STOCK",...Tr],dl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.firstName"],ul=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.lastName"],hl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address1"],pl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address2"],ml=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.city"],yl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.phone","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.phone"],gl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.zip"],fl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.province","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.province"],_l=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.firstName"],El=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.lastName"],Al=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address1"],bl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address2"],Pl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.city"],wl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.phone"],Sl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.zip"],Il=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.firstName"],Cl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.lastName"],Dl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address1"],Rl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address2"],Tl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.city"],Nl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.phone","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.phone"],vl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.zip"],Ll=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.province","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.province"],Ol=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.firstName"],kl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.lastName"],Ml=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address1"],xl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address2"],Fl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.city"],Ul=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.phone"],Bl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.zip"],Hl=["DELIVERY_POSTAL_CODE_INVALID","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE","DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","INVALID_ZIP_CODE_FOR_COUNTRY: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],Gl=["BUYER_IDENTITY_EMAIL_DOMAIN_IS_INVALID","BUYER_IDENTITY_EMAIL_DOES_NOT_MATCH_EXPECTED_PATTERN","INVALID: buyerIdentity.email"],zl=["DELIVERY_PHONE_NUMBER_INVALID","INVALID: buyerIdentity.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],$l=["Variable $buyerIdentity of type CartBuyerIdentityInput! was provided invalid value for countryCode","INVALID: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country"],Vl=["DELIVERY_ADDRESS2_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2"],Wl=["ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city","DELIVERY_CITY_REQUIRED"],Yl=["DELIVERY_POSTAL_CODE_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],ql=["PAYMENTS_METHOD_REQUIRED","PAYMENTS_METHOD_UNAVAILABLE"],jl=["MERCHANDISE_EXPECTED_PRICE_MISMATCH","DELIVERY_DELIVERY_LINE_DETAIL_CHANGED","DELIVERY_LOCAL_PICKUP_DELIVERY_LINE_DETAIL_CHANGED",...ql,y.CustomValidation,...Tr];class Ql extends oe{constructor(e){e instanceof Error?(super("[".concat(e.name,"] ").concat(e.message),{cause:e.cause,groupingHash:e instanceof oe?e.groupingHash:void 0}),this.stack=e.stack):super("[HandleCreateCartError] ".concat(String(e))),this.name="HandleCreateCartError"}}async function Ee({element:t,instrumentName:e,dataSource:r}){try{const n=await r.getInitialCart(e),{cart:a,errors:i,abortReason:o,decelerationReason:s}=n;Ys(()=>{t&&(t.disabled=!1)});const l=Ir(i),c=Xl(i),u=c||l;if(c&&p.unrecoverableCartError({instrument:e,errorName:c}),!a&&!u)throw new Error("[".concat(e,"] Failed to create cart: ").concat(JSON.stringify(i)));if(a){if(!a.id)throw new Error("[".concat(e,"] received invalid cart"));if(!a.checkoutUrl)throw new Error("[".concat(e,"] Created cart with no checkout URL"))}if(i.length>0&&!u)throw new Error("Errors present after cart creation: ".concat(JSON.stringify(i)));return{cart:a,customValidationError:l,decelerationReason:s,abortReason:o,...c?{unrecoverableError:c}:{}}}catch(n){if(n instanceof ht)return{cart:null,customValidationError:void 0,unrecoverableError:k.IgnoredResponseError,abortReason:void 0,decelerationReason:void 0};throw new Ql(n)}finally{t.disabled=!1}}const Kl={[y.InvalidQuantity]:k.InvalidQuantity,[y.VariantRequiresSellingPlan]:k.VariantRequiresSellingPlan,[y.SellingPlanNotApplicable]:k.SellingPlanNotApplicable,[y.MerchandiseIdInvalid]:k.MerchandiseIdInvalid,[y.NoResponse]:k.NoResponse,[y.InvalidInput]:k.InvalidInput,[y.MerchandiseNotApplicableForMerchandiseId]:k.MerchandiseNotApplicable};function Xl(t){if(t.length!==1)return null;const[e]=t;return typeof e=="object"?null:Kl[e]||null}const Jl={force_shop_pay_product:"direct_checkout_product",force_shop_pay_cart:"direct_checkout_cart"};function fe(t,e="no_redirect_for_checkout"){p.flushTelemetry();const r=new URL(t);switch(e){case"skip_shop_pay":r.searchParams.set("skip_shop_pay","true");break;case"no_redirect_for_checkout":r.searchParams.set("storefront_wallet","true");break;case"force_shop_pay_cart":case"force_shop_pay_product":case"force_shop_pay":{r.searchParams.set("payment","shop_pay");const n=Jl[e];n&&r.searchParams.set("redirect_source",n);break}}window.location.assign(r.toString())}const Zl={currency_changed:x.CURRENCY_CHANGE,captcha_required:x.CAPTCHA_REQUIRED,not_enough_stock:x.NOT_ENOUGH_STOCK,cart_not_ready:x.CART_NOT_READY,dynamic_tax:x.DYNAMIC_TAX,payment_method_not_applicable:x.PAYMENT_METHOD_NOT_APPLICABLE,invalid_payment_deferred_payment_required:x.INVALID_PAYMENT_DEFERRED_PAYMENT_REQUIRED,localization_extension_field_error:x.LOCALIZATION_EXTENSION_FIELD_ERROR,account_info_mismatch:x.ACCOUNT_INFO_MISMATCH,invalid_language:x.WALLET_PROCESSING_FAILED,invalid_country:x.WALLET_PROCESSING_FAILED,missing_cart_id:x.WALLET_PROCESSING_FAILED,redirect_to_checkout_required:x.WALLET_PROCESSING_FAILED,invalid_payment_amount:x.WALLET_PROCESSING_FAILED,unsupported_apple_pay_payment_method:x.UNSUPPORTED_APPLE_PAY_PAYMENT_METHOD,unsupported_google_pay_payment_method:x.UNSUPPORTED_GOOGLE_PAY_PAYMENT_METHOD,custom_validation:x.WALLET_PROCESSING_FAILED,cart_empty:x.WALLET_PROCESSING_FAILED,payments_country_invalid:x.PAYMENTS_COUNTRY_INVALID,generic_error:x.WALLET_PROCESSING_FAILED,cart_throttled:null};function tn({cart:t,warnings:e}){const r=t&&t.lineItems.length>0&&t.lineItems.every(n=>n.quantity===0);if(e!=null&&e.includes("MERCHANDISE_OUT_OF_STOCK")&&r)return"out_of_stock"}function Jt({warnings:t,cart:e,cartStatus:r,errors:n}){if(n!=null&&n.includes(y.PaymentMethodNotApplicable))return"payment_method_not_applicable";if(n!=null&&n.includes(y.InvalidPaymentDeferredPaymentRequired))return"invalid_payment_deferred_payment_required";if(r==="CartStatusNotReady")return"cart_not_ready";if(r==="CartThrottled")return"cart_throttled";if(!t||t.length===0)return;if(t.includes("MERCHANDISE_NOT_ENOUGH_STOCK"))return"not_enough_stock";const a=e==null?void 0:e.lineItems.some(i=>i.quantity>0);if(t.includes("MERCHANDISE_OUT_OF_STOCK")&&a)return"not_enough_stock"}function Nr({currentCartTotal:t,initialBuyerCurrency:e}){const r=t.amount;return!(!r||Number(r)===0||e.toUpperCase()===t.currencyCode.toUpperCase())}function F({checkoutUrl:t,instrumentName:e,reason:r}){if(!t)throw new Error("Invalid Checkout URL");const n=new URL(t),a=Zl[r];a&&n.searchParams.set(a,"true"),p.decelerated({instrument:e,reason:r}),fe(n.toString())}class ec extends Pt{constructor(){super(),d(this,"name",f.MoreOptions),d(this,"anchor"),d(this,"i18n"),d(this,"dataSource"),d(this,"classNames"),d(this,"setI18n"),d(this,"setDataSource"),d(this,"setClassNames"),[this.i18n,this.setI18n]=he(),[this.dataSource,this.setDataSource]=he(),[this.classNames,this.setClassNames]=he()}static get observedAttributes(){return["disabled"]}connectedCallback(){this.anchor||this.render()}attributeChangedCallback(e,r,n){r!==n&&e==="disabled"&&this.anchor&&(n===""?this.anchor.setAttribute("aria-disabled","true"):this.anchor.removeAttribute("aria-disabled"),this.setAccessibilityAttributes())}async handleClick(e){var r,n;if(e.preventDefault(),this.disabled||!this.anchor)return;this.disabled=!0;const[a,i]=await Promise.all([this.i18n,this.dataSource]);try{const{decelerationReason:o,cart:s,customValidationError:l,unrecoverableError:c,abortReason:u}=await Ee({element:this,instrumentName:f.MoreOptions,dataSource:i});if(c){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),p.log({body:"Unrecoverable error detected in More Options sheet clicked",attributes:{unrecoverableError:c}}),ke(a,c);return}if(l){p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),p.log({body:"Custom validation error detected in More Options sheet clicked",attributes:{errorMessage:l==null?void 0:l.message}}),Oe(a,l.message);return}if(u==="out_of_stock"){p.sheetClicked({instrument:this.name,result:"rejected",reason:"out_of_stock"}),ge(a);return}if(o){p.sheetClicked({instrument:f.MoreOptions,result:"success",reason:"deceleration"}),F({checkoutUrl:(r=s==null?void 0:s.checkoutUrl)!=null?r:"",instrumentName:f.MoreOptions,reason:o});return}const h=this.recommendedInstrument===f.ShopPay?"skip_shop_pay":"allow_redirect";p.sheetClicked({instrument:f.MoreOptions,result:"success"}),fe((n=s==null?void 0:s.checkoutUrl)!=null?n:"",h)}catch(o){p.sheetClicked({instrument:f.MoreOptions,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in More Options sheet clicked",attributes:{error:String(o)}}),E.notify(o),je(a)}}async render(){const e=await this.i18n,r=await this.classNames;this.anchor=document.createElement("a"),this.anchor.textContent=e.translate("more_payment_options"),this.anchor.className=r,this.anchor.setAttribute("id","more-payment-options-link"),this.anchor.onclick=a=>this.handleClick(a),this.setAccessibilityAttributes(),this.appendChild(this.anchor);const n=document.createElement("style");n.textContent=Po,this.appendChild(n)}setAccessibilityAttributes(){this.anchor&&(this.disabled?(this.anchor.removeAttribute("href"),this.anchor.role="link"):(this.anchor.removeAttribute("role"),this.anchor.href="#"))}}var O=(t=>(t.ButtonDisplay="buttonDisplay",t.LoadInstrument="loadInstrument",t.LoadSdk="loadSDK",t.AuthorizationLatency="authorizationLatency",t.SheetLoad="sheetLoad",t.StyleExtract="styleExtract",t))(O||{});function ua(){var t,e;return!!((t=window.performance)!=null&&t.mark)&&!!((e=window.performance)!=null&&e.measure)}function Qe(t,e){return Xe(t,e),()=>K(t,e)}function Xe(t,e){ua()&&window.performance.mark("".concat(t,"-").concat(e,"-start"))}function K(t,e){var r,n;if(ua())try{const a="".concat(t,"-").concat(e,"-start"),i="".concat(t,"-").concat(e,"-end"),o="".concat(t,"-").concat(e,"-duration");window.performance.mark(i);const s=(n=window.performance.measure(o,a,i))!=null?n:(r=window.performance.getEntriesByName(o,"measure"))==null?void 0:r[0],l=s==null?void 0:s.duration;return l==null?void 0:l}catch(a){return}}function vr(t,e,r){if(at!=null&&at.length){const n=at.join(",");t.querySelectorAll(n).forEach(a=>{r===null?a.removeAttribute(e):a.setAttribute(e,r)})}}function tc(t,e){try{const r=JSON.parse(t!=null?t:"[]");if(!(r instanceof Array))throw new Y({code:"invalid-wallet-configs",message:"[".concat(e,"] invalid walletConfigs found")});return r}catch(r){throw new Y({code:"invalid-wallet-configs",message:"[".concat(e,"] Error while parsing walletConfigs JSON: ").concat(r)},{cause:r})}}function rc(t,e){try{return t?JSON.parse(t):null}catch(r){throw new Y({code:"invalid-wallet-config",message:"[".concat(e,"] Error while parsing walletConfig JSON: ").concat(r)},{cause:r})}}function Rt(t,e){var r;const n=e==null?void 0:e.getLoadEligibility(t);return p.instrumentLoadEligibility({instrument:e==null?void 0:e.getInstrumentName(),result:n!=null&&n.eligible?"success":"failed",reason:n!=null&&n.eligible||n==null?void 0:n.reason}),(r=n==null?void 0:n.eligible)!=null?r:!1}function nc(t,e){return e.filter(r=>Rt(t,r))}async function ha({walletInstrument:t,instanceNumber:e}){const r=t.getInstrumentName(),n=Qe(O.LoadSdk,"".concat(r,":").concat(e));try{await t.loadWalletSDK(),p.instrumentSDKLoaded({instrument:r,measurement:n(),result:"success"})}catch(i){return E.leaveBreadcrumb("Failed to load wallet SDK",{instrumentName:r,instanceNumber:e},"error"),E.notify(i),p.instrumentSDKLoaded({instrument:r,measurement:n(),result:"failed"}),null}let a;try{a=t.getPartnerSDKEligibility()}catch(i){E.notify(i),a={eligible:!1,reason:"uncaught exception"}}return a.eligible?(p.instrumentSDKEligible({instrument:r,result:"success"}),t):(p.instrumentSDKEligible({instrument:r,reason:a.reason,result:"failed"}),null)}function ve(t,...e){try{const r=window[t];if(typeof r=="function")return new r(...e)}catch(r){}return null}var $e;class Lr extends Pt{constructor(){super(...arguments),d(this,"apiClient"),d(this,"i18n"),d(this,"policy"),d(this,"isFetchingPolicy",!1),d(this,"intersectionObserver",null),G(this,$e),d(this,"handleIntersection",(e,r)=>{e.some(n=>n.isIntersecting)&&(this.apiClient&&this.apiClient.setVisible(),r.disconnect(),z({event:B.FirstVisible}))})}connectedCallback(){this.mountIntersectionObserver()}get shopId(){return this.getAttribute("shop-id")}get cartId(){return this.getAttribute("cart-id")}get walletConfigs(){return this.getAttribute("wallet-configs")}get recommendedWallet(){return this.getAttribute("recommended")}get fallbackWallet(){return this.getAttribute("fallback")}get variantParams(){var e;try{return JSON.parse((e=this.getAttribute("variant-params"))!=null?e:"[]")}catch(r){throw new Y({code:"invalid-variant-params",message:"variant-params must be a valid JSON string. Received variant-params: ".concat(this.getAttribute("variant-params"),", received error: ").concat(r)})}}get styleExtractorDisabled(){return this.hasAttribute("disable-compat")}get onlySdk(){return this.hasAttribute("only-sdk")}get debug(){return this.hasAttribute("debug")}triggerLoadedEvent(){document.dispatchEvent(new Event("shopify:payment_button:loaded",{bubbles:!0,cancelable:!0}))}async attributeChangedCallback(e,r,n){r!==n&&vr(this,e,n)}showBuyerConsent(e,r){var n,a,i;if(e){if(!r)throw new Y({code:"invalid-i18n",message:"i18n is required"});(i=(a=(n=window.Shopify)==null?void 0:n.PaymentButton)==null?void 0:a.showBuyerConsent)==null||i.call(a,o=>this.onClickSubscriptionPolicy(o,e,r))}}hideBuyerConsent(){var e,r,n;(n=(r=(e=window.Shopify)==null?void 0:e.PaymentButton)==null?void 0:r.hideBuyerConsent)==null||n.call(r)}clearUI(){this.innerHTML=""}isFlagEnabled(e){return w(this,$e)==null&&M(this,$e,this.getEnabledFlags()),w(this,$e).includes(e)}setupManagedMarketsHandlers(e){if(!e)throw new Y({code:"invalid-i18n",message:"i18n is required"});const r=document.getElementById("shopify-buyer-consent");if((r==null?void 0:r.getAttribute("data-consent-type"))!=="managed-markets")return;const n=document.getElementById("shopify-managed-markets-terms-and-conditions-button"),a=document.getElementById("shopify-managed-markets-privacy-policy-button");if(!n||!a)return;const i=o=>{const s=o.target;if(s.id==="shopify-managed-markets-terms-and-conditions-button"){o.preventDefault(),o.stopImmediatePropagation(),this.showModalWithIframe("https://content.global-e.com/shopper-terms",e.translate("managed_markets.terms_and_conditions"),e);return}s.id==="shopify-managed-markets-privacy-policy-button"&&(o.preventDefault(),o.stopImmediatePropagation(),this.showModalWithIframe("https://content.global-e.com/privacy-policy",e.translate("managed_markets.privacy_policy"),e))};document.addEventListener("click",i,!0)}showModalWithIframe(e,r,n){const a=n.translate("managed_markets.policy_not_found"),i=1e4,o=800,s=aa(r);document.body.appendChild(s);const l=document.createElement("div");st(l,{position:"relative",width:"100%"});const c=document.createElement("iframe");At(c,{width:"100%",height:"100%",title:r,frameborder:"no"}),st(c,{border:"none","min-height":"50vh",display:"none"});const u=document.createElement("div");u.className="skeleton-overlay",u.innerHTML=na(),st(u,{background:"white"}),l.appendChild(c),l.appendChild(u),s.appendChild(l);let h=!1,g=!1,m=!1;const b=()=>{!m&&h&&g&&(u.remove(),c.style.display="block")},_=setTimeout(()=>{h||(m=!0,bo(s,a))},i);c.addEventListener("load",()=>{clearTimeout(_),h=!0,b()}),setTimeout(()=>{g=!0,b()},o),c.src=e}getEnabledFlags(){const e=this.getAttribute("enabled-flags");if(!e)return[];try{return JSON.parse(e)}catch(r){return console.warn("Invalid enabled-flags attribute value:",e),[]}}async onClickSubscriptionPolicy(e,r,n){if(e.preventDefault(),this.isFetchingPolicy)return;if(this.policy){this.showPolicy(this.policy,n);return}this.isFetchingPolicy=!0;const a=this.fetchSubscriptionPolicy(r).then(i=>(this.policy=i,i)).catch(i=>(E.notify(i),n.translate("subscriptions.policy_not_found"))).finally(()=>{this.isFetchingPolicy=!1});this.showPolicy(a,n)}async fetchSubscriptionPolicy(e){const r=await e.fetchSubscriptionPolicy();return this.policy=r,r}showPolicy(e,r){Cr(r.translate("subscriptions.cancellation_policy"),e,r.translate("subscriptions.policy_not_found"))}mountIntersectionObserver(){this.intersectionObserver=ve("IntersectionObserver",this.handleIntersection),this.intersectionObserver?this.intersectionObserver.observe(this):z({event:B.FirstVisibleNotAvailable})}}$e=new WeakMap;function Or(t){var e,r;Zi({shop_id:(e=t.shopId)!=null?e:Vn,cartId:(r=t.cartId)!=null?r:void 0,debug:t.debug,pageType:t.pageType})}function pa({type:t,form:e}){if(!e)return[];const r=document.querySelectorAll('[name^="'.concat(t,'"][form^="').concat(CSS.escape(e.getAttribute("id")||""),'"]')),n=e.querySelectorAll('[name^="'.concat(t,'"]')),a=Array.from(r).concat(Array.from(n)),i={};return a.forEach(o=>{const s=ac(o),l=ic(o);s&&typeof l<"u"&&l.trim()!==""&&(i[s]=l)}),Object.entries(i!=null?i:{}).map(([o,s])=>({key:o,value:s}))}function $t({page:t,element:e}){const r=t==="product"?'[data-shopify="payment-button"]':'[data-shopify="dynamic-checkout-cart"]',n=rn(e,r)||document.querySelector(r);return rn(n,"form")}const rt=Element.prototype;function rn(t,e){if(rt.matches=rt.matches||rt.webkitMatchesSelector||rt.msMatchesSelector||rt.mozMatchesSelector,!t||t.matches(e))return t;let r=t;for(;r&&r!==document.body;)if(r=r.parentElement,r&&r.matches(e))return r;return null}function ac(t){const e=t.getAttribute("name");if(e===null)return null;const r=e.indexOf("["),n=e.lastIndexOf("]");return r===-1||n===-1?null:e.substring(r+1,n)}function ic(t){if(!(["radio","checkbox"].includes(t.type)&&!t.checked))try{return t.value===""||typeof t.value>"u"?void 0:t.value}catch(e){return}}function kr(t){const e=$t({page:"product",element:t});return ma(e)}function ma(t){var e;const r=t==null?void 0:t.elements;if(!r)return E.leaveBreadcrumb("[ProductForm] No form elements found"),null;const n=Tt(r,"id");if(!n||isNaN(Number(n))||Number(n)<=0)return E.leaveBreadcrumb("[ProductForm] Invalid variant ID found",{variantId:n}),null;const a=Number((e=Tt(r,"quantity"))!=null?e:"1"),i="gid://shopify/ProductVariant/".concat(n),o=sc(r),s=pa({type:"properties",form:t});return{variantId:n,quantity:a,merchandiseId:i,sellingPlanId:o,lineItemProperties:s}}function oc(t){const e=t==null?void 0:t.elements;return e?!!Tt(e,"selling_plan"):!1}function Tt(t,e){var r,n;let a=t.namedItem(e);if(a instanceof HTMLSelectElement)try{return(r=a.value)!=null?r:null}catch(i){return null}if(a&&"length"in a&&(a=a.item(0)),a instanceof HTMLInputElement||a instanceof HTMLSelectElement)try{return(n=a.value)!=null?n:null}catch(i){return null}return null}function sc(t){const e=Tt(t,"selling_plan");if(!(!e||e==="undefined"))return"gid://shopify/SellingPlan/".concat(e)}class Mr{constructor(e,r){d(this,"addToCartMutationObserver"),d(this,"addToCartForm"),d(this,"addToCartButtons"),this.element=e,this.onFormChanged=r,this.addToCartMutationObserver=null,this.addToCartForm=null,this.addToCartButtons=[]}setupMutationObservers(){if(this.findAndSetAddToCartButtons(),!this.addToCartForm)return;this.syncComponentStateWithForm();const e=new MutationObserver(()=>this.reobserveOnFormChanges());this.addToCartMutationObserver=new MutationObserver(()=>this.syncComponentStateWithForm()),e.observe(this.addToCartForm,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),this.observeAddToCartButtons()}syncComponentStateWithForm(){if(!this.addToCartForm){this.onFormChanged({disabled:!0,hasSellingPlan:!1});return}const e=ma(this.addToCartForm),r=!!(this.addToCartButtons.length>0&&this.addToCartButtons.every(n=>n.hasAttribute("disabled")||n.getAttribute("aria-disabled")==="true"));this.onFormChanged({disabled:r||e===null,hasSellingPlan:oc(this.addToCartForm),variantId:e==null?void 0:e.variantId,sellingPlanId:e==null?void 0:e.sellingPlanId})}observeAddToCartButtons(){this.addToCartButtons.forEach(e=>{this.addToCartMutationObserver.observe(e,{attributes:!0})})}reobserveOnFormChanges(){var e;(e=this.addToCartMutationObserver)==null||e.disconnect(),this.findAndSetAddToCartButtons(),this.observeAddToCartButtons(),this.syncComponentStateWithForm()}findAndSetAddToCartButtons(){if(this.addToCartForm=$t({page:"product",element:this.element}),this.addToCartForm){const e=this.addToCartForm.querySelectorAll("[type=submit]");e instanceof NodeList&&(this.addToCartButtons=[...e])}}}function lc(t,e,r){try{const n=JSON.parse(t!=null?t:"{}"),a=JSON.parse(e!=null?e:JSON.stringify(Wn));if(n===null||Object.keys(n).length===0){if(!(a instanceof Object))throw p.walletConfigDeveloperError(),new Y({code:"invalid-fallback-wallet-config",message:"[".concat(r,"] Invalid fallback wallet configs JSON")});return{recommendedWallet:null,fallbackWallet:a}}return{recommendedWallet:n,fallbackWallet:a}}catch(n){throw p.walletConfigDeveloperError(),new Y({code:"invalid-recommended-fallback-config",message:"[".concat(r,"] Error while parsing recommended/fallback JSON: ").concat(n)},{cause:n})}}const cc=".shopify-payment-button__button--hidden{visibility:hidden}.shopify-payment-button__button{height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 44px),55px);min-height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 44px),55px);border-radius:var(--shopify-accelerated-checkout-button-border-radius, 0px);width:100%;border:none;box-shadow:0 0 0 0 transparent;color:#fff;cursor:pointer;display:block;font-size:1em;font-weight:500;line-height:1;text-align:center;transition:background .2s ease-in-out}.shopify-payment-button__button[disabled]{opacity:.6;cursor:default}.shopify-payment-button__button--unbranded{background-color:#1990c6;padding:1em 2em}.shopify-payment-button__button--unbranded:hover:not([disabled]){background-color:#136f99}.shopify-payment-button__more-options{background:transparent;border:0 none;cursor:pointer;display:block;font-size:1em;margin-top:1em;text-align:center;text-decoration:underline;width:100%}.shopify-payment-button__more-options.shopify-payment-button__skeleton{height:auto!important;min-height:0!important;border-radius:4px!important;width:50%;margin-left:25%;margin-right:25%}.shopify-payment-button__more-options[disabled]{opacity:.6;cursor:default!important}.shopify-payment-button__button.shopify-payment-button__button--branded{display:flex;flex-direction:column;position:relative;z-index:1}.shopify-payment-button__button.shopify-payment-button__button--branded .shopify-cleanslate{flex:1!important;display:flex!important;flex-direction:column!important}.shopify-payment-button__button.button.loading{position:relative;color:transparent}.shopify-payment-button__button.button.loading>.loading-overlay__spinner{top:50%;left:50%;transform:translate(-50%,-50%);position:absolute;height:100%;display:flex;align-items:center}.shopify-payment-button__button.button.loading>.loading-overlay__spinner .spinner{width:-moz-fit-content;width:-webkit-fit-content;width:fit-content}.button.loading>.loading-overlay__spinner .path{stroke:#fff}.shopify-payment-button__button .loading-overlay__spinner{width:1.8rem;display:inline-block}.shopify-payment-button__button .spinner{animation:shopify-rotator 1.4s linear infinite}@keyframes shopify-rotator{0%{transform:rotate(0)}to{transform:rotate(270deg)}}.shopify-payment-button__button .path{stroke-dasharray:280;stroke-dashoffset:0;transform-origin:center;stroke:#121212;animation:shopify-dash 1.4s ease-in-out infinite}@media screen and (forced-colors: active){.shopify-payment-button__button .path{stroke:CanvasText}}@keyframes shopify-dash{0%{stroke-dashoffset:280}50%{stroke-dashoffset:75;transform:rotate(135deg)}to{stroke-dashoffset:280;transform:rotate(450deg)}}#shopify-buyer-consent{margin-top:1em;display:inline-block;width:100%}#shopify-buyer-consent.hidden{display:none}#shopify-subscription-policy-button,#shopify-managed-markets-terms-and-conditions-button,#shopify-managed-markets-privacy-policy-button{background:none;border:none;padding:0;text-decoration:underline;font-size:inherit;cursor:pointer}#shopify-subscription-policy-button:before,#shopify-managed-markets-terms-and-conditions-button:before,#shopify-managed-markets-privacy-policy-button:before{box-shadow:none}@keyframes acceleratedCheckoutLoadingSkeleton{50%{opacity:var(--shopify-accelerated-checkout-skeleton-animation-opacity-start, 1)}75%{opacity:var(--shopify-accelerated-checkout-skeleton-animation-opacity-end, .5)}to{opacity:var(--shopify-accelerated-checkout-skeleton-animation-opacity-start, 1)}}.shopify-payment-button__skeleton{animation:acceleratedCheckoutLoadingSkeleton var(--shopify-accelerated-checkout-skeleton-animation-duration, 4s) var(--shopify-accelerated-checkout-skeleton-animation-timing-function, ease) infinite;animation-delay:-.168s;background-color:var(--shopify-accelerated-checkout-skeleton-background-color, #dedede);box-sizing:border-box;text-decoration:none!important;height:var(--shopify-accelerated-checkout-button-block-size, inherit);min-height:25px;max-height:55px;border-radius:var( --shopify-accelerated-checkout-button-border-radius, inherit )}",dc='.accelerated-checkout-button{height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 44px),55px);min-height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 44px),55px);border-radius:var(--shopify-accelerated-checkout-button-border-radius, 0px);box-shadow:var(--shopify-accelerated-checkout-button-box-shadow)}:host([page-type="cart_page"]) .accelerated-checkout-button{height:100%;width:100%;border-radius:var(--shopify-accelerated-checkout-button-border-radius, 4px);box-shadow:var(--shopify-accelerated-checkout-button-box-shadow)}:host([page-type="product"]) .accelerated-checkout-button{min-width:150px}@media (forced-colors: active){.accelerated-checkout-button{border:1px solid transparent!important}:host([page-type="cart_page"]) .accelerated-checkout-button{border:1px solid transparent!important}}',uc=70;class lt{constructor(e,r,n,a){d(this,"red"),d(this,"green"),d(this,"blue"),d(this,"opacity"),this.red=e||0,this.green=r||0,this.blue=n||0,this.opacity=typeof a>"u"?1:a}getLuminance(){const e=this.red&255,r=this.green&255,n=this.blue&255;return e*.2126+r*.7152+n*.0722}isDark(){return this.opacity===0?!1:this.getLuminance()/this.opacity0&&a.opacity>0?(n=new lt(0,0,0,0),n.blendWith(a,r)):a.opacity>0?n=a:n=r,r=n,a=e.shift();return n}const lr=new lt(255,255,255,1);function pc(t){const e=[];let r=t;for(;r.parentElement;){r=r.parentElement;const n=window.getComputedStyle(r).backgroundColor,a=mc(n);if(n&&e.push(a),a.opacity===1)break}try{return hc(e.reverse())}catch(n){return E.notify(new ya("[BackgroundDetection] Failed to blend colors for element ".concat(t.outerHTML),{cause:n})),lr}}function mc(t){if(!t)return lr;try{const e=t.split("(")[1].split(")")[0].replace(" ","").split(",");return new lt(Number(e[0]),Number(e[1]),Number(e[2]),typeof e[3]>"u"?1:Number(e[3]))}catch(e){E.notify(new ya("[BackgroundDetection] Failed to convert rgbString to array ".concat(t),{cause:e}))}return lr}class ya extends Error{constructor(){super(...arguments),d(this,"name","ColorProcessingError")}}var pe;class Ae extends Pt{constructor(){super(),d(this,"name",f.Unknown),d(this,"i18n"),d(this,"dataSource"),d(this,"apiClient"),d(this,"classNames"),d(this,"containerInstanceNumber"),d(this,"onRendered"),d(this,"setI18n"),d(this,"setDataSource"),d(this,"setApiClient"),d(this,"setClassNames"),d(this,"setContainerInstanceNumber"),d(this,"parsedWalletParams"),G(this,pe),this.onRendered=()=>{},[this.i18n,this.setI18n]=he(),[this.dataSource,this.setDataSource]=he(),[this.apiClient,this.setApiClient]=he(),[this.classNames,this.setClassNames]=he(),[this.containerInstanceNumber,this.setContainerInstanceNumber]=he()}async cleanupOnFailure(e,r){var n;try{await e()}catch(a){E.notify(new yc("An error occurred requiring cleanup when attempting to render the ".concat(r," instrument: ").concat(a),{cause:a}));const i=await this.containerInstanceNumber;p.instrumentLoaded({instrumentOrComponentName:r,result:"failed",measurement:K(O.ButtonDisplay,"".concat(r,":").concat(i))}),(n=this.parentElement)==null||n.remove()}}attributeChangedCallback(e,r,n,a){r!==n&&e==="disabled"&&a&&(n===""?(a.setAttribute("aria-disabled","true"),a.setAttribute("disabled","")):(a.removeAttribute("aria-disabled"),a.removeAttribute("disabled")))}get pageType(){return this.getAttribute("page-type")||C.Unknown}get buttonTheme(){return pc(this).isDark()?"LIGHT":"DARK"}get isCTA(){return this.hasAttribute("call-to-action")}get walletParams(){var e;if(this.parsedWalletParams===void 0)try{this.parsedWalletParams=JSON.parse((e=this.getAttribute("wallet-params"))!=null?e:"{}")}catch(r){throw new Y({code:"invalid-wallet-params",message:"[".concat(this.name,"] Error while parsing wallet-params JSON: ").concat(r)},{cause:r})}return this.parsedWalletParams}async initializeShadowStyles(e,r=""){const n=document.createElement("style");n.innerHTML=[dc,r].join("\n"),e.appendChild(n)}async ensureLightDOMIsNotEmpty(){this.textContent="\xA0"}dispatchWalletEvent({eventName:e,detail:r={}}){var n;(n=this.parentElement)==null||n.dispatchEvent(new CustomEvent(e,{detail:r}))}getOrCreateShadowRoot(){return w(this,pe)||M(this,pe,this.attachShadow({mode:"closed"})),w(this,pe)}clearShadowRoot(){w(this,pe)&&(w(this,pe).innerHTML="")}}pe=new WeakMap;class yc extends Error{constructor(){super(...arguments),d(this,"name","CleanupOnFailureError")}}class gc extends Ae{constructor(){super(...arguments),d(this,"name",f.BuyItNow),d(this,"button",null)}static get observedAttributes(){return["disabled"]}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}attributeChangedCallback(e,r,n){super.attributeChangedCallback(e,r,n,this.button)}async handleClick(){var e,r;if(this.disabled||!this.button||this.button.getAttribute("aria-disabled"))return;this.disabled=!0;const[n,a]=await Promise.all([this.i18n,this.dataSource]);try{const{decelerationReason:i,cart:o,customValidationError:s,unrecoverableError:l,abortReason:c}=await Ee({element:this,instrumentName:this.name,dataSource:a});if(l){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),ke(n,l);return}if(c==="out_of_stock"){p.sheetClicked({instrument:this.name,result:"rejected",reason:"out_of_stock"}),ge(n);return}if(s){p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),Oe(n,s.message);return}if(i){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),F({checkoutUrl:(e=o==null?void 0:o.checkoutUrl)!=null?e:"",instrumentName:this.name,reason:i});return}p.sheetClicked({instrument:this.name,result:"success"}),fe((r=o==null?void 0:o.checkoutUrl)!=null?r:"","allow_redirect")}catch(i){E.notify(i),p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in Buy It Now Button click",attributes:{error:String(i)}}),je(n)}}async render(){var e;this.button||(this.button=Gt());const r=await this.classNames;this.button.textContent=(await this.i18n).translate("instruments_copy.checkout.buy_now"),this.button.className=r,this.disabled&&this.button.setAttribute("aria-disabled","true"),this.button.onclick=()=>this.handleClick(),this.appendChild(this.button),(e=this.onRendered)==null||e.call(this)}}const fc=1e3;function _c(){const t=navigator.userAgent,e=t.indexOf("Android")>-1,r=t.indexOf("Chrome/")>-1,n=parseInt((/Chrome\/([0-9]+)/.exec(t)||["0","0"])[1],10);return e&&r&&n===114}function Ec(t){return Promise.race([t,new Promise((e,r)=>setTimeout(()=>r(new Error("timed out")),fc))])}class be{constructor(e){d(this,"walletParams"),this.walletParams=e.wallet_params}static walletName(){throw new Error("Must define walletName for WalletInstrument subclass")}async createWebComponent({walletContainer:e,dataSource:r,i18n:n,apiClient:a,containerInstanceNumber:i,classNames:o="",callToAction:s,pageType:l=C.ProductPage,slot:c="button",onRendered:u=()=>{}}){var h,g,m;const b=this.getWebComponentName();if(!ce(b,this.getWebComponentClass(),{isChildCustomElement:!0}))throw new ee("Failed to define custom element ".concat(b,", aborting execution"));try{await Ec(customElements.whenDefined(b))}catch(v){throw new ee("Timeout waiting for custom element ".concat(b," to be defined"))}const _=document.createElement(b);if(!(_ instanceof Ae))throw new ee("Failed to create web component instance for ".concat(b,", element is not a WalletButtonElement"));const A={"access-token":(h=e.accessToken)!=null?h:"","buyer-country":(g=e.buyerCountry)!=null?g:"","buyer-currency":e.buyerCurrency,"wallet-params":JSON.stringify((m=this.walletParams)!=null?m:{}),"page-type":l,slot:c};try{e.disabled&&_.setAttribute("disabled",""),At(_,A),e.isShippingRequired&&_.setAttribute("requires-shipping",""),e.hasSellingPlan&&_.setAttribute("has-selling-plan",""),e.pciEnabled&&_.setAttribute("pci-enabled","")}catch(v){const $=v;throw $.message.includes("setAttribute is not a function")&&_c()?new ee($.message):$}if(s&&_.setAttribute("call-to-action",""),typeof _.setDataSource!="function")throw new ee("Custom element ".concat(b," is not properly upgraded, aborting execution"));return _.setDataSource(r),_.setApiClient(a),_.setI18n(n),_.setClassNames(o),_.setContainerInstanceNumber(i),_.onRendered=u,_}loadWalletSDK(){return Promise.resolve()}getLoadEligibility(e){return{eligible:!0}}getPartnerSDKEligibility(){return{eligible:!0}}}class Ac extends be{static walletName(){return"buy_it_now"}getWebComponentName(){return"shopify-buy-it-now-button"}getInstrumentName(){return f.BuyItNow}getWebComponentClass(){return gc}}const bc="shopify-paypal-button[disabled]{opacity:.5;cursor:not-allowed}shopify-paypal-button div.paypal-buttons>iframe{z-index:auto!important;border-radius:0!important;box-shadow:none}",Pc='::slotted(div){height:100%}:host([page-type="cart_page"]) ::slotted(div){width:100%;min-width:100px;display:flex;justify-content:center}:host([page-type="cart_page"]) .accelerated-checkout-button{overflow:hidden;display:flex;justify-content:center}';async function Ge(t){const{cartId:e,cartClient:r,instrumentName:n,abortSignal:a}=t;try{if(!e)throw new Error("[".concat(n,"] provided no cart ID when updating buyer identity"));if(!r)throw new Error("[".concat(n,"] provided invalid cart client when updating buyer identity"));return await r.updateCartBuyerIdentity(t,a)}catch(i){throw p.updateFailed(n,"updateBuyerIdentity"),i}}async function xr({cartId:t,totalAmount:e,paymentMethod:r,billingAddress:n,cartClient:a,instrumentName:i,abortSignal:o,hasSellingPlan:s,canUsePaymentMethodForFreeOrder:l}){try{if(!t)throw new Error("[".concat(i,"] provided no cart ID when updating payment"));if(!e)throw new Error("[".concat(i,"] provided no total amount when updating payment"));if(!r)throw new Error("[".concat(i,"] provided no apple pay wallet content when updating payment"));if(!a)throw new Error("[".concat(i,"] provided invalid cart client when updating payment"));const c={freePaymentMethod:{billingAddress:n}};return await a.updateCartPayment(t,{amount:{amount:e.amount,currencyCode:e.currencyCode},...Number(e.amount)<=0&&!l&&!s?c:r},i,o)}catch(c){throw p.updateFailed(i,"updatePayment"),c}}function ga(t){return window[fa(t)]}function fa(t){return"paypal-".concat(t.replace(/[^a-zA-Z0-9]/g,""))}const wc="RESTRICTED_WALLET_ACCOUNT",Sc="GENERIC_ERROR",Ic="NO_PENDING_TASK",Cc="WALLET_SERVICE_DISABLED",Dc="FAILED_TO_ENQUEUE_BACKGROUND_JOB",Rc="REQUEST_MISSING_VALID_MERCHANDISE_SOURCE",Tc="THROTTLE_EXCEEDED",Nc="INTERNAL_SERVER_ERROR",vc=[Sc,Ic,Cc,Dc,Rc,Tc,Nc];function nn(t){return t==null?void 0:t.map(e=>{var r,n;return{code:(r=e.extensions)==null?void 0:r.code,isLoggable:vc.includes((n=e.extensions)==null?void 0:n.code)}}).find(({code:e,isLoggable:r})=>e===wc||r)}function Nt(t){if(!t)return null;const e=getComputedStyle(t).borderRadius;return e.includes("px")?parseInt(e,10):null}function vt(t){if(!t)return null;const e=getComputedStyle(t).height;return e.includes("px")?parseInt(e,10):null}const Zt=25,an=55,Lc=["cart_not_ready","cart_throttled","payment_method_not_applicable","invalid_payment_deferred_payment_required"],er="PAYPAL_CALLBACK_HANDLED_ERROR";var me;class Oc extends Ae{constructor(){super(...arguments),d(this,"name",f.PayPal),d(this,"abortController",null),d(this,"cartId"),d(this,"sdkButtonsComponent"),d(this,"container",null),d(this,"resizeObserver",null),d(this,"buttonHeight"),d(this,"rendering",!1),d(this,"prevBorderRadius",0),d(this,"prevHeight",0),G(this,me,!1)}connectedCallback(){this.resizeObserver=ve("ResizeObserver",()=>this.onResize()),this.cleanupOnFailure(this.render.bind(this),this.name)}async disconnectedCallback(){var e;this.innerHTML="",this.clearShadowRoot(),await this.teardownPayPalButton(),(e=this.resizeObserver)==null||e.disconnect()}async teardownPayPalButton(){var e;try{await((e=this.sdkButtonsComponent)==null?void 0:e.close().catch(()=>{}))}catch(r){}finally{this.sdkButtonsComponent=void 0}}async onResize(){const e=Nt(this.container),r=vt(this.container),n=e!==null&&this.prevBorderRadius!==e||r!==null&&this.prevHeight!==r;!this.rendering&&n&&(await this.teardownPayPalButton(),this.container.innerHTML="",await this.cleanupOnFailure(()=>this.renderFromPayPalSDK(),this.name))}async render(){var e;const r=this.getOrCreateShadowRoot(),n=document.createElement("div");n.className=Le.BUTTON;const a=document.createElement("style");a.innerHTML=bc,this.appendChild(a),await this.initializeShadowStyles(r,Pc),r.appendChild(n),this.container=n,await fo(),this.renderFromPayPalSDK(),(e=this.resizeObserver)==null||e.observe(this.container)}getHeight(){const e=vt(this.container);return e?e>=Zt&&e<=an?e:ethis.createToken({apiClientPromise:this.apiClient,requiresBillingAgreement:a});let o,s;a?s=i:o=i;const l=Nt(this.container),c=this.getHeight();this.prevHeight=c;const u={color:"gold",label:this.isCTA?"pay":"paypal",disableMaxWidth:!0,height:c,shape:"sharp"};l&&l>0&&(u.borderRadius=l,this.prevBorderRadius=l);const h=await this.i18n;this.sdkButtonsComponent=(r=(e=ga(this.walletParams.sdkUrl))==null?void 0:e.Buttons)==null?void 0:r.call(e,{fundingSource:"paypal",style:u,createOrder:o,createBillingAgreement:s,onApprove:async m=>{await this.onApprove(m)},onCancel:()=>{this.cancelPaymentSheet("Payment sheet cancelled")},onClick:this.onClick.bind(this),onError:m=>{this.onError(m,h)}});let g=!1;try{await((n=this.sdkButtonsComponent)==null?void 0:n.render(this.container)),g=!0}catch(m){p.renderFailed(this.name),p.log({body:"PayPal Button not able to render into container.",attributes:{pageType:this.pageType,error:m==null?void 0:m.toString()}})}finally{this.rendering=!1}g&&this.onRendered()}cancelPaymentSheet(e){var r;M(this,me,!0),p.sheetCancelled(this.name),(r=this.abortController)==null||r.abort("[PayPal] ".concat(e))}async onClick(e,r){var n,a;if(this.disabled)return r.reject();M(this,me,!1),this.abortController=ve("AbortController");const i=this.getBoundingClientRect(),o=i.left+i.width/2,s=i.top+i.height/2,l=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1,clientX:o,clientY:s,screenX:window.screenX+o,screenY:window.screenY+s});this.dispatchEvent(l);const[c,u]=await Promise.all([this.dataSource,this.i18n]);try{const{decelerationReason:h,cart:g,customValidationError:m,unrecoverableError:b,abortReason:_}=await Ee({element:this,instrumentName:this.name,dataSource:c});if(b)return p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),p.log({body:"Unrecoverable error detected in PayPal sheet clicked",attributes:{unrecoverableError:b}}),ke(u,b),r.reject();if(_==="out_of_stock")return p.sheetClicked({instrument:this.name,result:"rejected",reason:"out_of_stock"}),ge(u),r.reject();if(m)return p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),p.log({body:"Custom validation error detected in PayPal sheet clicked",attributes:{errorMessage:m==null?void 0:m.message}}),Oe(u,m.message),r.reject();const{hasManagedSellingPlanState:A}=this.walletParams;return A!=null&&A!==this.hasSellingPlan?(p.sheetClicked({instrument:this.name,result:"success",reason:"redirected_to_checkout"}),fe((n=g==null?void 0:g.checkoutUrl)!=null?n:""),r.reject()):h?(p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),F({checkoutUrl:(a=g==null?void 0:g.checkoutUrl)!=null?a:"",instrumentName:this.name,reason:h}),r.reject()):(this.cartId=g.id,r.resolve())}catch(h){return p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in PayPal sheet clicked",attributes:{error:String(h),location:"onClick",...this.cartId&&{cartId:sr(this.cartId)}}}),E.notify(h),je(u),r.reject()}}async createToken({apiClientPromise:e,requiresBillingAgreement:r}){const n=await e;try{if(!this.cartId)throw new Error("cartId not found when creating token");const a=await n.paypalTokenCreate({cartId:this.cartId,billingAgreement:r});return p.sheetClicked({instrument:this.name,result:"success"}),a}catch(a){throw w(this,me)||(a instanceof ee?p.sheetClicked({instrument:this.name,result:"rejected",reason:"silenced_error"}):(p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in PayPal sheet clicked",attributes:{error:String(a),location:"createToken",...this.cartId&&{cartId:sr(this.cartId)}}}),E.notify(a))),je(await this.i18n),new Error(er)}}async onApprove({orderID:e,payerID:r,billingToken:n}){var a;try{if(p.authorizationAttempt(this.name),Xe(O.AuthorizationLatency,this.name),!this.cartId)throw new Error("Cart not found");const i=await this.apiClient,o=this.requiresBillingAgreement()&&n!=null?n:e,{billingAddress:s,destinationAddress:l,expiresAt:c,email:u,remoteOrderId:h,payerApprovedAmount:g}=await i.paypalBuyerDetailsFetch(o,this.cartId),m=await Ge({cartId:this.cartId,cartClient:i,instrumentName:this.name,emailAddress:u,streetAddress:l});if(!(m!=null&&m.data))throw new Error("Cart not found");if(await this.decelerateOrAbort(m))return;const{id:b,totalAmount:_,checkoutUrl:A}=m.data,v=await xr({abortSignal:(a=this.abortController)==null?void 0:a.signal,cartClient:i,cartId:b,instrumentName:f.PayPal,billingAddress:s!=null?s:l,paymentMethod:{walletPaymentMethod:{paypalWalletContent:{billingAddress:s!=null?s:l,email:u,expiresAt:c,payerId:r,token:h!=null?h:e,acceptedSubscriptionTerms:!1,vaultingAgreement:!1,merchantId:this.walletParams.merchantId,...g&&{payerApprovedAmount:g}}}},canUsePaymentMethodForFreeOrder:!0,totalAmount:_});if(await this.decelerateOrAbort(v))return;p.authorizationComplete({instrument:this.name,result:"success",measurement:K(O.AuthorizationLatency,this.name)}),fe(A)}catch(i){throw w(this,me)||(p.authorizationComplete({instrument:this.name,result:"failed",measurement:K(O.AuthorizationLatency,this.name)}),E.notify(i)),new Error(er)}}onError(e,r){var n;if(w(this,me)||e.message.includes(er))return;if(e.message==="Window is closed, can not determine type"){this.cancelPaymentSheet("Window Closed Error");return}if(e.message==="Detected popup close"){this.cancelPaymentSheet("Popup Closed Error");return}e.message==="RESTRICTED_WALLET_ACCOUNT"?p.log({body:"PayPal modal closed due to error: ".concat(e)}):E.notify(new Fr(e)),p.sheetFailed(this.name,e),(n=this.abortController)==null||n.abort("[PayPal] Error occurred");const a=r.translate("brand.paypal");ie(a,r)}requiresBillingAgreement(){return this.walletParams.hasManagedSellingPlanState||this.walletParams.requiresBillingAgreement}shouldDecelerate(e){return!!(e&&Lc.includes(e))}async decelerateOrAbort(e){if(e.abortReason==="out_of_stock")return await this.handleOutOfStock(),!0;if(!e.data)return!1;const{totalAmount:r,checkoutUrl:n}=e.data;let a;return this.shouldDecelerate(e.decelerationReason)?a=e.decelerationReason:Nr({currentCartTotal:r,initialBuyerCurrency:this.buyerCurrency})&&(a="currency_changed"),a?(F({checkoutUrl:n,instrumentName:this.name,reason:a}),!0):!1}async handleOutOfStock(){p.authorizationComplete({instrument:this.name,result:"failed",measurement:K(O.AuthorizationLatency,this.name)}),ge(await this.i18n)}}me=new WeakMap;class Fr extends oe{constructor(e){var r;super(e.message,{cause:e.cause}),d(this,"name","PayPalError"),d(this,"useHashPrefix",!0);try{this.stack=e.stack}catch(n){(r=Error.captureStackTrace)==null||r.call(Error,this,Fr)}}}const xe=class Ih extends be{static walletName(){return"paypal"}constructor(e){super(e)}getWebComponentName(){return"shopify-paypal-button"}getInstrumentName(){return f.PayPal}getWebComponentClass(){return Oc}loadWalletSDK(){let e=Ih.paypalSDKPromiseByUrl.get(this.walletParams.sdkUrl);if(e)return e;const r=document.createElement("script");return r.setAttribute("src",this.walletParams.sdkUrl),e=new Promise((n,a)=>{r.setAttribute("data-namespace",fa(this.walletParams.sdkUrl)),r.onload=()=>n(),r.onerror=i=>{Ih.paypalSDKPromiseByUrl.delete(this.walletParams.sdkUrl),r&&document.body.contains(r)&&document.body.removeChild(r),a(i)},document.body.appendChild(r)}),Ih.paypalSDKPromiseByUrl.set(this.walletParams.sdkUrl,e),e}getLoadEligibility(){return{eligible:!0}}getPartnerSDKEligibility(){var e,r;try{return(r=(e=ga(this.walletParams.sdkUrl))==null?void 0:e.Buttons)!=null&&r.call(e).isEligible()?{eligible:!0}:{eligible:!1,reason:"PayPal SDK not eligible"}}catch(n){throw new Y({code:"paypal-sdk-eligibility-check-failed",message:"PayPal SDK 'isEligible' method failed unexpectedly: ".concat(n)})}}};d(xe,"paypalSDKPromiseByUrl",new Map);let cr=xe;const kc=".apple-pay-button{display:flex;align-items:center;justify-content:center;width:100%;padding:0!important;cursor:pointer;border:none}.apple-pay-button:hover:not(:disabled){filter:brightness(92%)}.apple-pay-button:disabled{opacity:.5;cursor:not-allowed}.apple-pay-button svg{height:100%;flex-shrink:0}.apple-pay--content{font-size:16px;font-family:San Francisco,sans-serif;width:100%;height:100%;flex-grow:1;display:flex;align-items:center;justify-content:center;white-space:pre}.apple-pay--light{background:#fff;color:#000}.apple-pay--light svg{fill:#000}.apple-pay--dark{background:#000;color:#fff}.apple-pay--dark svg{fill:#fff}",dr={UK:"GB",JA:"JP"},_a=["AS","GU","MP","PR","VI"];_a.forEach(t=>{dr[t]="US"});function wt(t){var e,r;const n=t.countryCode,a={firstName:t.givenName||void 0,lastName:t.familyName||void 0,address1:(e=t==null?void 0:t.addressLines)==null?void 0:e[0],address2:((r=t==null?void 0:t.addressLines)==null?void 0:r[1])||void 0,city:t.locality||void 0,zip:t.postalCode||void 0,province:t.administrativeArea||t.subLocality||void 0,country:Mc(t.countryCode),phone:t.phoneNumber||void 0};return a.country==="HK"&&(a.zip=void 0,a.province=t.postalCode),n&&_a.includes(n)&&(a.province=n),a.lastName||(a.lastName=a.firstName),a}function Mc(t){if(!t)return"ZZ";const e=t.toUpperCase();return Object.keys(dr).includes(e)?dr[e]:e}function xc(t,e){return t.map(r=>{const{title:n,deliveryPromise:a}=Bc(r,e);return{title:n,estimatedCost:{amount:Uc(r),currencyCode:r[0].estimatedCost.currencyCode},handle:Aa(r),deliveryPromise:a}})}function Fc(t,e){return t.map(r=>{const{title:n,description:a}=Hc(r,e);return{title:n,description:a,handle:Aa(r)}})}function Ea({deliveryGroups:t}){return t.map(e=>e.deliveryOptions.filter(({deliveryMethodType:r})=>r==="SHIPPING").map(r=>({...r,groupType:e.groupType}))).reduce((e,r)=>e.flatMap(n=>r.map(a=>[...n,a])),[[]])}function Uc(t){return t.reduce((e,r)=>e+Number(r.estimatedCost.amount),0).toFixed(2)}function Bc(t,e){const r=t.find(l=>l.groupType===Ne.OneTimePurchase),n=t.find(l=>l.groupType===Ne.Subscription),a=[...new Set([r==null?void 0:r.title,n==null?void 0:n.title])].filter(Boolean),i=[...new Set([r==null?void 0:r.deliveryPromise,n==null?void 0:n.deliveryPromise])].filter(Boolean),o=a.length===2?e.translate("shipping_methods.connect_shipping_methods",{methodOne:a[0],methodTwo:a[1]}):a[0],s=i.length===2?e.translate("delivery_promises.connect_delivery_promises",{promiseOne:i[0],promiseTwo:i[1]}):i[0];return{title:o,deliveryPromise:s}}function Hc(t,e){const r=t.find(o=>o.groupType===Ne.OneTimePurchase),n=t.find(o=>o.groupType===Ne.Subscription),a=t.map(Gc).filter(Boolean).join(", ");let i=(r==null?void 0:r.title)||(n==null?void 0:n.title);return r&&n&&(i=e.translate("shipping_methods.connect_shipping_methods",{methodOne:r.title,methodTwo:n.title})),{title:i,description:a}}function Gc(t){const e=Number(t.estimatedCost.amount).toFixed(2),r=t.estimatedCost.currencyCode,n=t.deliveryPromise;return n?"(".concat(n,") ").concat(e," ").concat(r):"".concat(e," ").concat(r)}function Aa(t){return t.map(e=>e.handle).join(",")}function ba({deliveryGroups:t,i18n:e}){const r=t.some(n=>n.groupType===Ne.Subscription);return t.map(n=>{var a;let i=e.translate("order_summary.shipping");return r&&(i=n.groupType===Ne.Subscription?e.translate("order_summary.shipping_subscription"):e.translate("order_summary.shipping_one_time_purchase")),{label:i,amount:Te(((a=n.selectedDeliveryOption)==null?void 0:a.estimatedCost.amount)||0)}})}function zc(t,e){return it({label:t,possibleLines:[e]})[0]}function $c({subtotal:t,deliveryGroups:e,duties:r,taxes:n,discountAllocations:a,i18n:i,formattedRecurringTotals:o}){var s;const l=it({label:i.translate("order_summary.subtotal"),possibleLines:[t]}),c=ba({deliveryGroups:e,i18n:i}),u=it({label:i.translate("order_summary.duties"),possibleLines:[r]}),h=it({label:i.translate("order_summary.taxes"),possibleLines:[n]}),g=o.map(_=>({label:_,amount:"0.00",type:"pending"})),m=g.length?[{label:i.translate("order_summary.subscriptions.recurring_total_tooltip_line"),amount:"0.00",type:"pending"}]:[],b=(s=a==null?void 0:a.flatMap(_=>{var A;const v=(A=_.title)!=null?A:_.code;return it({label:v!=null?v:i.translate("order_summary.discount"),possibleLines:[_.discountedAmount],isDiscount:!0})}))!=null?s:[];return[...l,...c,...u,...h,...b,...g,...m]}function it({label:t,possibleLines:e,isDiscount:r=!1}){return e.filter(n=>(n==null?void 0:n.amount)!==void 0).map(n=>({label:t,amount:r?"-".concat(Te(n.amount)):Te(n.amount)}))}function on(t,e){if(!t.length)return[];const r=Ea({deliveryGroups:t});return xc(r,e).map(n=>{var a;return{label:n.title||"",amount:n.estimatedCost.amount,identifier:n.handle,detail:(a=n.deliveryPromise)!=null?a:""}})}const Vc=["decelerate","abort","show_error","complete","update"];class Lt extends oe{constructor(){super(...arguments),d(this,"name","UnhandledActionError")}}class Pa{constructor(){d(this,"generatePrioritizedPaymentSheetAction",(e,r)=>{let n;const a=[],i=[],o=[],s=r.filter(c=>c!==y.UnacceptablePaymentsAmount).some(c=>e[c]!==void 0);for(const c of Object.keys(e))if(!(c===y.UnacceptablePaymentsAmount&&s)){const u=e[c]();u.effects&&i.push(...u.effects),u.action!=="complete"&&u.errors&&o.push(...u.errors),a.push(u)}const l=(c=>Vc.map(u=>c.find(h=>h.action===u)).find(u=>!!u))(a);return l&&(n=l,n.effects=i,n.action!=="complete"&&(n.errors=o)),n})}getMergedPaymentSheetAction({result:e,errorActions:r}){const n={};r.forEach(i=>{i.errors.forEach(o=>{e.errors.includes(o)&&(n[o]=i.generateAction)})});let a;for(const i of e.errors){const o=n[i];if(o){a=o();break}}return{firstPaymentSheetAction:a,prioritizedPaymentSheetAction:this.generatePrioritizedPaymentSheetAction(n,e.errors)}}getUnhandledErrors(e,r){const n=r.flatMap(a=>a.errors);return e.filter(a=>!n.includes(a))}decelerateOrAbort({reason:e,instrumentName:r,errorOrWarning:n,checkoutUrl:a,requestType:i}){return a?{action:"decelerate",redirectUrl:a,reason:e}:{action:"abort",effects:[()=>{E.notify(new Error("[".concat(r,"] unexpected ").concat(n," received in ").concat(i," response, aborting")))}]}}}class Wc extends Pa{constructor(e){super(),this.i18n=e}mapMutationResultToPaymentSheetAction({result:e,context:r,checkoutUrl:n,requestType:a}){var i;const o=this.mapCustomValidationFunctionErrorToAction(e.errors);if(o)return o;const s=this.getErrorActions({shippingCountryCode:r==null?void 0:r.shippingCountryCode,billingCountryCode:r==null?void 0:r.billingCountryCode,checkoutUrl:n,requestType:a}),l=e.errors,c=this.getUnhandledErrors(l,s);if(c.forEach(h=>{E.notify(new Lt("[".concat(f.ApplePay,"] mutation result error not handled: ").concat(h),{groupingHash:"UnhandledActionError:".concat(f.ApplePay,":").concat(h)}))}),((i=e.data)==null?void 0:i.deliveryGroups.length)===0&&r!=null&&r.shippingRequired)return{action:"show_error",errors:[new ApplePayError("addressUnserviceable")]};const{firstPaymentSheetAction:u}=this.getMergedPaymentSheetAction({result:e,errorActions:s});return u||(c.length>0?{action:"abort",effects:[()=>{ie(this.i18n.translate("brand.apple_pay"),this.i18n)}]}:{action:"update",errors:[]})}mapCompletionResultToPaymentSheetAction({result:e,context:r,checkoutUrl:n}){if(!e.data)throw new Qn(f.ApplePay);switch(e.data.__typename){case"SubmitSuccess":return{action:"complete",redirectUrl:e.data.redirectUrl};case"SubmitAlreadyAccepted":case"SubmitThrottled":case"SubmitFailed":{const a=this.mapCustomValidationFunctionErrorToAction(e.errors);if(a)return a;const i=this.getErrorActions({shippingCountryCode:r==null?void 0:r.shippingCountryCode,billingCountryCode:r==null?void 0:r.billingCountryCode,checkoutUrl:n,requestType:"completion"}),o=e.errors;this.getUnhandledErrors(o,i).forEach(l=>{E.notify(new Lt("[".concat(f.ApplePay,"] completion result error not handled: ").concat(l),{groupingHash:"UnhandledActionError:".concat(f.ApplePay,":").concat(l)}))});const{prioritizedPaymentSheetAction:s}=this.getMergedPaymentSheetAction({result:e,errorActions:i});return s||{action:"abort",effects:[()=>{ie(this.i18n.translate("brand.apple_pay"),this.i18n)}]}}default:throw new Error("[".concat(f.ApplePay,"] unknown completion result type: ").concat(e.data.__typename))}}decelerateOrAbort(...e){var r;const n=super.decelerateOrAbort(...e);return n.action==="abort"&&((r=n.effects)==null||r.push(()=>{ie(this.i18n.translate("brand.apple_pay"),this.i18n)})),n}getErrorActions({shippingCountryCode:e,billingCountryCode:r,checkoutUrl:n,requestType:a}){return[{errors:[y.CaptchaCompletionRequired],generateAction:()=>this.decelerateOrAbort({reason:"captcha_required",instrumentName:f.ApplePay,errorOrWarning:y.CaptchaCompletionRequired,checkoutUrl:n,requestType:a})},{errors:[y.ContactInfoDoesNotMatchCustomerProfile],generateAction:()=>this.decelerateOrAbort({reason:"account_info_mismatch",instrumentName:f.ApplePay,errorOrWarning:y.ContactInfoDoesNotMatchCustomerProfile,checkoutUrl:n,requestType:a})},{errors:[y.InvalidLanguage],generateAction:()=>this.decelerateOrAbort({reason:"invalid_language",instrumentName:f.ApplePay,errorOrWarning:y.InvalidLanguage,checkoutUrl:n,requestType:a})},{errors:[y.InvalidCountry],generateAction:()=>this.decelerateOrAbort({reason:"invalid_country",instrumentName:f.ApplePay,errorOrWarning:y.InvalidCountry,checkoutUrl:n,requestType:a})},{errors:[y.MissingCartId],generateAction:()=>this.decelerateOrAbort({reason:"missing_cart_id",instrumentName:f.ApplePay,errorOrWarning:y.MissingCartId,checkoutUrl:n,requestType:a})},{errors:[y.RedirectToCheckoutRequired],generateAction:()=>this.decelerateOrAbort({reason:"redirect_to_checkout_required",instrumentName:f.ApplePay,errorOrWarning:y.RedirectToCheckoutRequired,checkoutUrl:n,requestType:a})},{errors:ca,generateAction:()=>this.decelerateOrAbort({reason:"invalid_payment_amount",instrumentName:f.ApplePay,errorOrWarning:y.InvalidPaymentAmount,checkoutUrl:n,requestType:a})},{errors:[y.InvalidPaymentEmptyCart],generateAction:()=>this.decelerateOrAbort({reason:"cart_empty",instrumentName:f.ApplePay,errorOrWarning:y.InvalidPaymentEmptyCart,checkoutUrl:n,requestType:a})},{errors:[y.PaymentsCountryInvalid],generateAction:()=>this.decelerateOrAbort({reason:"payments_country_invalid",instrumentName:f.ApplePay,errorOrWarning:y.PaymentsCountryInvalid,checkoutUrl:n,requestType:a})},{errors:Rr,generateAction:()=>this.decelerateOrAbort({reason:"dynamic_tax",instrumentName:f.ApplePay,errorOrWarning:y.NewTaxMustBeAccepted,checkoutUrl:n,requestType:a})},{errors:[y.GenericError],generateAction:()=>this.decelerateOrAbort({reason:"generic_error",instrumentName:f.ApplePay,errorOrWarning:y.GenericError,checkoutUrl:n,requestType:a})},{errors:[y.MerchandiseExpectedPriceMismatch],generateAction:()=>this.decelerateOrAbort({reason:"generic_error",instrumentName:f.ApplePay,errorOrWarning:y.MerchandiseExpectedPriceMismatch,checkoutUrl:n,requestType:a})},{errors:da,generateAction:()=>this.decelerateOrAbort({reason:"not_enough_stock",instrumentName:f.ApplePay,errorOrWarning:y.MerchandiseNotEnoughStock,checkoutUrl:n,requestType:a})},{errors:ll,generateAction:()=>({action:"abort",effects:[()=>ge(this.i18n)]})},{errors:la,generateAction:()=>({action:"show_error",errors:[new ApplePayError("addressUnserviceable")]})},{errors:[y.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","emailAddress",this.i18n.translate("errors.missing.email"))]})},{errors:qs,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.missing.first_name"))]})},{errors:js,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.invalid.first_name"))]})},{errors:Qs,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.missing.last_name"))]})},{errors:Ks,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.invalid.last_name"))]})},{errors:Xs,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.missing.address1"))]})},{errors:[y.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address1"))]})},{errors:Js,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.missing.address2"))]})},{errors:[y.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address2"))]})},{errors:Zs,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.missing.city"))]})},{errors:[y.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.invalid.city"))]})},{errors:[y.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.missing.zone"),this.i18n.translate("errors.missing.emirate"),"shippingContactInvalid",e)]})},{errors:[y.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.invalid.zone"),this.i18n.translate("errors.invalid.emirate"),"shippingContactInvalid",e)]})},{errors:el,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.missing.postal_code"))]})},{errors:sa,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.invalid.postal_code"))]})},{errors:[y.DeliveryCountryRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","country",this.i18n.translate("errors.missing.country"))]})},{errors:tl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.missing.phone"))]})},{errors:nl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.invalid.phone"))]})},{errors:rl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","country",this.i18n.translate("errors.invalid.country"))]})},{errors:[y.DeliveryProvinceRequired],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.missing.zone"),this.i18n.translate("errors.missing.emirate"),"shippingContactInvalid",e)]})},{errors:il,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid")]})},{errors:ol,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","postalCode",this.i18n.translate("errors.invalid.postal_code"))]})},{errors:dl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.missing.first_name"))]})},{errors:ul,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.missing.last_name"))]})},{errors:hl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.missing.address1"))]})},{errors:pl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.missing.address2"))]})},{errors:ml,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","locality",this.i18n.translate("errors.missing.city"))]})},{errors:yl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","phoneNumber",this.i18n.translate("errors.missing.phone"))]})},{errors:gl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","postalCode",this.i18n.translate("errors.missing.postal_code"))]})},{errors:fl,generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.missing.zone"),this.i18n.translate("errors.missing.emirate"),"billingContactInvalid",r)]})},{errors:[y.ApplePayBillingFirstNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.emojis.first_name"))]})},{errors:[y.ApplePayBillingFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.html_tags.first_name"))]})},{errors:_l,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.invalid.first_name"))]})},{errors:[y.ApplePayBillingLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.emojis.last_name"))]})},{errors:[y.ApplePayBillingLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.html_tags.last_name"))]})},{errors:El,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.invalid.last_name"))]})},{errors:[y.ApplePayBillingAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address1"))]})},{errors:[y.ApplePayBillingAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address1"))]})},{errors:Al,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address1"))]})},{errors:[y.ApplePayBillingAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address2"))]})},{errors:[y.ApplePayBillingAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address2"))]})},{errors:bl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address2"))]})},{errors:[y.ApplePayBillingCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","locality",this.i18n.translate("errors.emojis.city"))]})},{errors:[y.ApplePayBillingCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","locality",this.i18n.translate("errors.html_tags.city"))]})},{errors:Pl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","locality",this.i18n.translate("errors.invalid.city"))]})},{errors:[y.ApplePayBillingPhoneContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","phoneNumber",this.i18n.translate("errors.emojis.phone"))]})},{errors:wl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","phoneNumber",this.i18n.translate("errors.invalid.phone"))]})},{errors:[y.ApplePayBillingZipContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","postalCode",this.i18n.translate("errors.emojis.postal_code"))]})},{errors:Sl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","postalCode",this.i18n.translate("errors.invalid.postal_code"))]})},{errors:[y.UnsupportedApplePayPaymentMethod],generateAction:()=>this.decelerateOrAbort({reason:"unsupported_apple_pay_payment_method",instrumentName:f.ApplePay,errorOrWarning:y.UnsupportedApplePayPaymentMethod,checkoutUrl:n,requestType:a})},{errors:[y.PaymentsMethodRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("unknown")]})},{errors:[y.CustomValidation],generateAction:()=>this.decelerateOrAbort({reason:"custom_validation",instrumentName:f.ApplePay,errorOrWarning:y.CustomValidation,checkoutUrl:n,requestType:a})},{errors:[y.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.emojis.last_name"))]})},{errors:[y.DeliveryFirstNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.emojis.first_name"))]})},{errors:[y.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.too_long.address1"))]})},{errors:[y.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.too_long.address2"))]})},{errors:[y.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.too_long.first_name"))]})},{errors:[y.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.too_long.last_name"))]})},{errors:[y.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.too_long.city"))]})},{errors:[y.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.url.first_name"))]})},{errors:[y.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.url.last_name"))]})},{errors:[y.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address1"))]})},{errors:[y.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address2"))]})},{errors:[y.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.html_tags.city"))]})},{errors:[y.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.html_tags.first_name"))]})},{errors:[y.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.html_tags.last_name"))]})},{errors:[y.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.emojis.city"))]})},{errors:[y.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address1"))]})},{errors:[y.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address2"))]})},{errors:[y.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.emojis.postal_code"))]})},{errors:[y.BuyerIdentityEmailInvalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","emailAddress",this.i18n.translate("errors.invalid.email"))]})},{errors:[y.DiscountNotApplicable],generateAction:()=>({action:"show_error",errors:[new ApplePayError("couponCodeInvalid",void 0,this.i18n.translate("errors.invalid.discount"))]})},{errors:[y.LocalizationExtensionFieldError],generateAction:()=>this.decelerateOrAbort({reason:"localization_extension_field_error",instrumentName:f.ApplePay,errorOrWarning:y.CaptchaCompletionRequired,checkoutUrl:n,requestType:a})}]}mapCustomValidationFunctionErrorToAction(e){const r=Ir(e);return r?{action:"abort",effects:[()=>{const n=this.i18n.translate("brand.apple_pay");Cr(this.i18n.translate("error_dialogs.wallet.title",{wallet:n}),r.message)}]}:null}createApplePayZoneError(e,r,n,a){const i=a==="AE"?"subLocality":"administrativeArea";return new ApplePayError(n,i,a==="AE"?r:e)}}const sn=["name","postalAddress"];function Yc({shippingRequired:t,walletParams:e,buyerCurrency:r}){const{phoneRequired:n,emailRequired:a}=e,i=[...a?["email"]:[],...n?["phone"]:[]],o=t?[...sn,...i]:i;return{countryCode:e.countryCode,currencyCode:r,merchantCapabilities:e.merchantCapabilities,supportedNetworks:e.supportedNetworks,total:{type:"pending",label:e.merchantName,amount:"1.00"},requiredBillingContactFields:sn,requiredShippingContactFields:o,shippingType:e.shippingType}}const qc=t=>{const e=t.lineItems.flatMap(r=>r.discountAllocations);return[...t.discountCodes.filter(r=>r.applicable&&t.discountAllocations.findIndex(n=>n.code===r.code)===-1&&e.findIndex(n=>n.code===r.code)===-1).map(r=>({code:r.code,discountedAmount:{amount:"0",currencyCode:t.totalAmount.currencyCode}})),...t.discountAllocations,...e]};class jc extends oe{constructor(){super(...arguments),d(this,"name","ApplePaySessionCreationError"),d(this,"useHashPrefix",!0),d(this,"autogenerateHash",!0)}}const wa=t=>{const e=t.lineItems.reduce((r,n)=>r+Number(n.subtotalAmount.amount),0);return{amount:String(e),currencyCode:t.totalAmount.currencyCode}};function Qc(t,e){return t.reduce((r,n)=>{if(!n.sellingPlanAllocation)return r;const{sellingPlanAllocation:{sellingPlan:a,priceAdjustments:i},quantity:o}=n;if(!a.recurringDeliveries||!a.billingPolicy)return r;const s=Kc({billingPolicy:a.billingPolicy,i18n:e});if(i.length===0){const l=St({price:Number(n.subtotalAmount.amount)*o,currencyCode:n.subtotalAmount.currencyCode,locale:e.locale});return[...r,e.translate("order_summary.subscriptions.recurring_totals",{fixedPrice:l,interval:s})]}else if(i.length===1){const l=St({price:Number(i[0].price.amount)*o,currencyCode:i[0].price.currencyCode,locale:e.locale});return[...r,e.translate("order_summary.subscriptions.recurring_totals",{fixedPrice:l,interval:s})]}else if(i.length===2){const l=St({price:Number(i[0].price.amount)*o,currencyCode:i[0].price.currencyCode,locale:e.locale}),c=St({price:Number(i[1].price.amount)*o,currencyCode:i[1].price.currencyCode,locale:e.locale}),u=a.priceAdjustments[0].orderCount;return[...r,e.translate("order_summary.subscriptions.recurring_totals_with_policies",{count:u,fixedPrice:l,recurringPrice:c,interval:s})]}return r},[])}function St({price:t,currencyCode:e,locale:r}){return Intl.NumberFormat(r,{style:"currency",currency:e,currencyDisplay:"narrowSymbol"}).format(t)}function Kc({billingPolicy:t,i18n:e}){const{interval:r,intervalCount:n}=t,a={YEAR:"order_summary.subscriptions.recurring_total_intervals.year",MONTH:"order_summary.subscriptions.recurring_total_intervals.month",WEEK:"order_summary.subscriptions.recurring_total_intervals.week",DAY:"order_summary.subscriptions.recurring_total_intervals.day"}[r];if(!a)throw new Error("Unknown selling plan interval provided: ".concat(r));return e.translate(a,{count:n})}const Vt="GraphQL Client",ln=0,cn=3,Sa="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",Ia="Response returned unexpected Content-Type:",Ca="An unknown error has occurred. The API did not return a data object or any errors in its response.",ur={json:"application/json",multipart:"multipart/mixed"},dn="X-SDK-Variant",un="X-SDK-Version",Xc="shopify-graphql-client",Jc="1.4.1",Da=1e3,Zc=[429,503],Ra=/@(defer)\b/i,hn="\r\n",ed=/boundary="?([^=";]+)"?/i,pn=hn+hn;function ye(t,e=Vt){return t.startsWith("".concat(e))?t:"".concat(e,": ").concat(t)}function Je(t){return t instanceof Error?t.message:JSON.stringify(t)}function Ta(t){return t instanceof Error&&t.cause?t.cause:void 0}function Na(t){return t.flatMap(({errors:e})=>e!=null?e:[])}function va({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||ecn))throw new Error("".concat(t,': The provided "retries" value (').concat(e,") is invalid - it cannot be less than ").concat(ln," or greater than ").concat(cn))}function V(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}function La(t,e){if(t.length===0)return e;const r={[t.pop()]:e};return t.length===0?r:La(t,r)}function Oa(t,e){return Object.keys(e||{}).reduce((r,n)=>(typeof e[n]=="object"||Array.isArray(e[n]))&&t[n]?(r[n]=Oa(t[n],e[n]),r):(r[n]=e[n],r),Array.isArray(t)?[...t]:{...t})}function ka([t,...e]){return e.reduce(Oa,{...t})}function td({clientLogger:t,customFetchApi:e=fetch,client:r=Vt,defaultRetryWaitTime:n=Da,retriableCodes:a=Zc}){const i=async(o,s,l)=>{const c=s+1,u=l+1;let h;try{if(h=await e(...o),t({type:"HTTP-Response",content:{requestParams:o,response:h}}),!h.ok&&a.includes(h.status)&&c<=u)throw new Error;const g=(h==null?void 0:h.headers.get("X-Shopify-API-Deprecated-Reason"))||"";return g&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:o,deprecationNotice:g}}),h}catch(g){if(c<=u){const m=h==null?void 0:h.headers.get("Retry-After");return await rd(m?parseInt(m,10):n),t({type:"HTTP-Retry",content:{requestParams:o,lastResponse:h,retryAttempt:s,maxRetries:l}}),i(o,c,l)}throw new Error(ye("".concat(l>0?"Attempted maximum number of ".concat(l," network retries. Last message - "):"").concat(Je(g)),r))}};return i}async function rd(t){return new Promise(e=>setTimeout(e,t))}function nd({headers:t,url:e,customFetchApi:r=fetch,retries:n=0,logger:a}){va({client:Vt,retries:n});const i={headers:t,url:e,retries:n},o=ad(a),s=td({customFetchApi:r,clientLogger:o,defaultRetryWaitTime:Da}),l=id(s,i),c=od(l),u=pd(l);return{config:i,fetch:l,request:c,requestStream:u}}function ad(t){return e=>{t&&t(e)}}async function Ma(t){const{errors:e,data:r,extensions:n}=await t.json();return{...V("data",r),...V("extensions",n),headers:t.headers,...e||!r?{errors:{networkStatusCode:t.status,message:ye(e?Sa:Ca),...V("graphQLErrors",e),response:t}}:{}}}function id(t,{url:e,headers:r,retries:n}){return async(a,i={})=>{const{variables:o,headers:s,url:l,retries:c,keepalive:u,signal:h}=i,g=JSON.stringify({query:a,variables:o});va({client:Vt,retries:c});const m=Object.entries({...r,...s}).reduce((_,[A,v])=>(_[A]=Array.isArray(v)?v.join(", "):v.toString(),_),{});!m[dn]&&!m[un]&&(m[dn]=Xc,m[un]=Jc);const b=[l!=null?l:e,{method:"POST",headers:m,body:g,signal:h,keepalive:u}];return t(b,1,c!=null?c:n)}}function od(t){return async(...e)=>{if(Ra.test(e[0]))throw new Error(ye("This operation will result in a streamable response - use requestStream() instead."));let r=null;try{r=await t(...e);const{status:n,statusText:a}=r,i=r.headers.get("content-type")||"";return r.ok?i.includes(ur.json)?await Ma(r):{errors:{networkStatusCode:n,message:ye("".concat(Ia," ").concat(i)),response:r}}:{errors:{networkStatusCode:n,message:ye(a),response:r}}}catch(n){return{errors:{message:Je(n),...r==null?{}:{networkStatusCode:r.status,response:r}}}}}}function sd(t){return Me(this,null,function*(){const e=new TextDecoder;if(t.body[Symbol.asyncIterator])try{for(var r=re(t.body),n,a,i;n=!(a=yield new te(r.next())).done;n=!1){const o=a.value;yield e.decode(o)}}catch(o){i=[o]}finally{try{n&&(a=r.return)&&(yield new te(a.call(r)))}finally{if(i)throw i[0]}}else{const o=t.body.getReader();let s;try{for(;!(s=yield new te(o.read())).done;)yield e.decode(s.value)}finally{o.cancel()}}})}function ld(t,e){return{[Symbol.asyncIterator](){return Me(this,null,function*(){try{let o="";try{for(var r=re(t),n,a,i;n=!(a=yield new te(r.next())).done;n=!1){const s=a.value;if(o+=s,o.indexOf(e)>-1){const l=o.lastIndexOf(e),c=o.slice(0,l).split(e).filter(u=>u.trim().length>0).map(u=>u.slice(u.indexOf(pn)+pn.length).trim());c.length>0&&(yield c),o=o.slice(l+e.length),o.trim()==="--"&&(o="")}}}catch(s){i=[s]}finally{try{n&&(a=r.return)&&(yield new te(a.call(r)))}finally{if(i)throw i[0]}}}catch(o){throw new Error("Error occured while processing stream payload - ".concat(Je(o)))}})}}}function cd(t){return{[Symbol.asyncIterator](){return Me(this,null,function*(){yield{...yield new te(Ma(t)),hasNext:!1}})}}}function dd(t){return t.map(e=>{try{return JSON.parse(e)}catch(r){throw new Error("Error in parsing multipart response - ".concat(Je(r)))}}).map(e=>{const{data:r,incremental:n,hasNext:a,extensions:i,errors:o}=e;if(!n)return{data:r||{},...V("errors",o),...V("extensions",i),hasNext:a};const s=n.map(({data:l,path:c,errors:u})=>({data:l&&c?La(c,l):{},...V("errors",u)}));return{data:s.length===1?s[0].data:ka([...s.map(({data:l})=>l)]),...V("errors",Na(s)),hasNext:a}})}function ud(t,e){if(t.length>0)throw new Error(Sa,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(Ca)}function hd(t,e){var r,n;const a=(e!=null?e:"").match(ed),i="--".concat(a?a[1]:"-");if(!((r=t.body)!=null&&r.getReader)&&!((n=t.body)!=null&&n[Symbol.asyncIterator]))throw new Error("API multipart response did not return an iterable body",{cause:t});const o=sd(t);let s={},l;return{[Symbol.asyncIterator](){return Me(this,null,function*(){var c,u;try{let _=!0;try{for(var h=re(ld(o,i)),g,m,b;g=!(m=yield new te(h.next())).done;g=!1){const A=m.value,v=dd(A);l=(u=(c=v.find(I=>I.extensions))==null?void 0:c.extensions)!=null?u:l;const $=Na(v);s=ka([s,...v.map(({data:I})=>I)]),_=v.slice(-1)[0].hasNext,ud($,s),yield{...V("data",s),...V("extensions",l),hasNext:_}}}catch(A){b=[A]}finally{try{g&&(m=h.return)&&(yield new te(m.call(h)))}finally{if(b)throw b[0]}}if(_)throw new Error("Response stream terminated unexpectedly")}catch(_){const A=Ta(_);yield{...V("data",s),...V("extensions",l),errors:{message:ye(Je(_)),networkStatusCode:t.status,...V("graphQLErrors",A==null?void 0:A.graphQLErrors),response:t},hasNext:!1}}})}}}function pd(t){return async(...e)=>{if(!Ra.test(e[0]))throw new Error(ye("This operation does not result in a streamable response - use request() instead."));try{const r=await t(...e),{statusText:n}=r;if(!r.ok)throw new Error(n,{cause:r});const a=r.headers.get("content-type")||"";switch(!0){case a.includes(ur.json):return cd(r);case a.includes(ur.multipart):return hd(r,a);default:throw new Error("".concat(Ia," ").concat(a),{cause:r})}}catch(r){return{[Symbol.asyncIterator](){return Me(this,null,function*(){const n=Ta(r);yield{errors:{message:ye(Je(r)),...V("networkStatusCode",n==null?void 0:n.status),...V("response",n)},hasNext:!1}})}}}}}const md="mutation cartCreate($input:CartInput!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false)@inContext(country:$country language:$language){result:cartCreate(input:$input){...@defer(if:$withCarrierRates){cart{...CartParts}errors:userErrors{...on CartUserError{message field code}}warnings:warnings{...on CartWarning{code}}}}}",yd="mutation cartAttributesUpdate($cartId:ID!$attributes:[AttributeInput!]!$country:CountryCode=CA$language:LanguageCode=EN$withCarrierRates:Boolean=false$prepareCart:Boolean=false)@inContext(country:$country language:$language){result:cartAttributesUpdate(cartId:$cartId attributes:$attributes){...@defer(if:$withCarrierRates)@skip(if:$prepareCart){cart{...CartParts}errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}...@include(if:$prepareCart){errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}}...PreparedCartFragment}",gd="mutation cartBillingAddressUpdate($cartId:ID!$billingAddress:MailingAddressInput$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false$prepareCart:Boolean=false)@inContext(country:$country language:$language){result:cartBillingAddressUpdate(cartId:$cartId billingAddress:$billingAddress){...@defer(if:$withCarrierRates)@skip(if:$prepareCart){cart{...CartParts}errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}...@include(if:$prepareCart){errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}}...PreparedCartFragment}",fd="mutation cartBuyerIdentityUpdate($cartId:ID!$buyerIdentity:CartBuyerIdentityInput!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false$prepareCart:Boolean=false)@inContext(country:$country language:$language){result:cartBuyerIdentityUpdate(cartId:$cartId buyerIdentity:$buyerIdentity){...@defer(if:$withCarrierRates)@skip(if:$prepareCart){cart{...CartParts}errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}...@include(if:$prepareCart){errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}}...PreparedCartFragment}",_d="mutation cartSelectedDeliveryOptionsUpdate($cartId:ID!$selectedDeliveryOptions:[CartSelectedDeliveryOptionInput!]!$country:CountryCode=CA$language:LanguageCode=EN$withCarrierRates:Boolean=false$prepareCart:Boolean=false)@inContext(country:$country language:$language){result:cartSelectedDeliveryOptionsUpdate(cartId:$cartId selectedDeliveryOptions:$selectedDeliveryOptions){...@defer(if:$withCarrierRates)@skip(if:$prepareCart){cart{...CartParts}errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}...@include(if:$prepareCart){errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}}...PreparedCartFragment}",Ed="mutation applePaySessionCreate($validationUrl:URL!){applePaySessionCreate(validationUrl:$validationUrl){...@defer{applePaySession{body}}}}",Ad="mutation PayPalBuyerDetailsFetch($token:String!$cartId:ID){paypalBuyerDetailsFetch(token:$token cartId:$cartId){...@defer{paypalDetails{email expiresAt remoteOrderId destinationAddress{...on MailingAddress{address1 address2 city company country firstName lastName phone province zip}}billingAddress{...on MailingAddress{address1 address2 city company country firstName lastName phone province zip}}payerApprovedAmount{currencyCode amount}}}}}",bd="mutation PayPalTokenCreate($cartId:ID!$billingAgreement:Boolean!){paypalTokenCreate(cartId:$cartId billingAgreement:$billingAgreement){...@defer{paypalToken{token}}}}",Pd="query cartQuery($id:ID!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false)@inContext(country:$country language:$language){cart(id:$id){...@defer(if:$withCarrierRates){...CartParts}}}",wd="query limitedCartQuery($id:ID!$country:CountryCode$language:LanguageCode)@inContext(country:$country language:$language){cart(id:$id){id lines(first:50){edges{node{merchandise{...on ProductVariant{requiresShipping}}sellingPlanAllocation{sellingPlan{id}}}}}}}",Sd="query subscriptionPolicyQuery($country:CountryCode$language:LanguageCode)@inContext(country:$country language:$language){shop{subscriptionPolicy(sanitized:true){body}}}",Id="mutation cartPaymentUpdate($cartId:ID!$input:CartPaymentInput!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false$prepareCart:Boolean=false)@inContext(country:$country language:$language){result:cartPaymentUpdate(cartId:$cartId payment:$input){...@defer(if:$withCarrierRates)@skip(if:$prepareCart){cart{...CartParts}errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}...@include(if:$prepareCart){errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}}...PreparedCartFragment}",It="fragment CartParts on Cart{id checkoutUrl deliveryGroups(first:10 withCarrierRates:$withCarrierRates){edges{node{id groupType selectedDeliveryOption{code title handle deliveryPromise deliveryMethodType estimatedCost{amount currencyCode}}deliveryOptions{code title handle deliveryPromise deliveryMethodType estimatedCost{amount currencyCode}}}}}cost{subtotalAmount{amount currencyCode}totalAmount{amount currencyCode}totalTaxAmount{amount currencyCode}totalDutyAmount{amount currencyCode}}discountAllocations{discountedAmount{amount currencyCode}...on CartCodeDiscountAllocation{code}...on CartAutomaticDiscountAllocation{title}...on CartCustomDiscountAllocation{title}}discountCodes{code applicable}lines(first:10){edges{node{quantity cost{subtotalAmount{amount currencyCode}totalAmount{amount currencyCode}}discountAllocations{discountedAmount{amount currencyCode}...on CartCodeDiscountAllocation{code}...on CartAutomaticDiscountAllocation{title}...on CartCustomDiscountAllocation{title}}merchandise{...on ProductVariant{requiresShipping}}sellingPlanAllocation{priceAdjustments{price{amount currencyCode}}sellingPlan{billingPolicy{...on SellingPlanRecurringBillingPolicy{interval intervalCount}}priceAdjustments{orderCount}recurringDeliveries}}}}}}",tr="fragment CartErrorParts on CartUserError{message field code}",mn="fragment PreparedCartFragment on Mutation{preparedCart:cartPrepareForCompletion(cartId:$cartId)@include(if:$prepareCart){...@defer{result{__typename ...on CartStatusReady{cart{...CartParts}}...on CartStatusNotReady{cart{...CartParts}errors{code message}}...on CartThrottled{cart{...CartParts}pollAfter}}errors:userErrors{...CartErrorParts}}}}",Cd="mutation prepareCart($cartId:ID!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false$prepareCart:Boolean=true)@inContext(country:$country language:$language){...PreparedCartFragment}",Dd="mutation cartSubmitForCompletion($cartId:ID!$attemptToken:String!$country:CountryCode$language:LanguageCode)@inContext(country:$country language:$language){cartSubmitForCompletion(cartId:$cartId attemptToken:$attemptToken){result{__typename ...on SubmitSuccess{redirectUrl}...on SubmitThrottled{pollAfterV2:pollAfter}...on SubmitFailed{errors{code message}checkoutUrl}}errors:userErrors{...on CartUserError{code field message}}}}",Rd="mutation cartRemovePersonalData($cartId:ID!){cartRemovePersonalData(cartId:$cartId){errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}}";async function Td(t,e){var r,n;if(!e.errors)return;const a=Ud(e.errors,t),i=await Fd(e.errors.response),o=((n=(r=e.errors.response)==null?void 0:r.headers)==null?void 0:n.get("content-type"))||void 0,s=[];if(e.errors.graphQLErrors)for(const l of e.errors.graphQLErrors)l.code&&s.push(l.code);return{operationName:t,statusCode:e.errors.networkStatusCode,contentType:o,message:a,responseBody:i,errorCodes:s}}const Nd=[/API multipart response did not return an iterable body/,/Error in parsing multipart response/,/GraphQL Client: Response returned unexpected Content-Type:/,/GraphQL Client: (?:null|undefined) is not an object/i,/Internal error/,/Carrier-calculated rates through @defer is temporarily unavailable/,/Throttled/,/Request blocked/,/Network request failed/,/Load failed/,/Failed to fetch/,/when attempting to fetch resource/],vd=[/signal is aborted/i,/fetch is aborted/i,/operation was aborted/i,/\[Apple Pay\] Payment sheet cancelled/],Ld=[/timed?.out/i,/error occured while processing stream payload/i,/response stream terminated/i],Od=/provided invalid value/,kd=["quantity","sellingPlanId","attributes"];function Md(t){var e;return Od.test(t)&&(e=kd.find(r=>t.includes(r)))!=null?e:null}function xd(t,{hasBeenVisible:e=!1}={}){if(t.statusCode&&t.statusCode!==200)return{isIgnorable:!0,reason:"statusCode-".concat(t.statusCode)};if(t.message){if(Ld.some(n=>n.test(t.message)))return{isIgnorable:!0,reason:"timeout"};if(vd.some(n=>n.test(t.message)))return{isIgnorable:!0,reason:"abort"};if(Nd.some(n=>n.test(t.message)))return{isIgnorable:!0,reason:"message"};const r=Md(t.message);if(r)return{isIgnorable:!0,reason:"graphql-input-validation-".concat(r)}}return e?{isIgnorable:!1,reason:void 0}:{isIgnorable:!0,reason:"component-not-visible"}}async function Fd(t){if(!t||t.bodyUsed)return"";try{return(await t.text()).slice(0,1024)}catch(e){return console.error("Failed to read response body:",e),""}}function Ud(t,e){var r,n;if(!t)return"";const a=(n=(r=t.graphQLErrors)==null?void 0:r.map(s=>s.message).join(", "))!=null?n:"",i="".concat(t.message).concat(a.length>0?" - ".concat(a):""),o=t.networkStatusCode?"with status ".concat(t.networkStatusCode," => ").concat(i):"=> ".concat(i);return"GraphQL response error for ".concat(e,": ").concat(o)}const yn="UNKNOWN";function Bd({url:t,accessToken:e}){return{headers:{"Content-Type":"application/json",Accept:"application/json","X-Shopify-Storefront-Access-Token":e,"X-SDK-Variant":"portable-wallets"},url:t,retries:0,customFetchApi:(r,n)=>(E.leaveBreadcrumb("Request ".concat((n==null?void 0:n.method)||yn,": ").concat(r),{url:r,method:n==null?void 0:n.method},"request"),fetch(r,n)),logger:r=>{try{switch(r.type){case"HTTP-Response":{const[n,a]=r.content.requestParams,{status:i,statusText:o,headers:s,type:l}=r.content.response;E.leaveBreadcrumb("Response ".concat((a==null?void 0:a.method)||yn,": ").concat(n),{statusCode:i,statusText:o,responseHeaders:Hd(s),responseType:l,url:n,method:a==null?void 0:a.method,headers:a==null?void 0:a.headers,body:a==null?void 0:a.body},"log");break}case"HTTP-Retry":{const{retryAttempt:n,maxRetries:a,lastResponse:i,requestParams:[o,s]=[]}=r.content;E.leaveBreadcrumb("GraphQL Retry Attempt ".concat(n,"/").concat(a,": ").concat(o),{retryAttempt:n,maxRetries:a,url:o,method:s==null?void 0:s.method,lastResponseStatus:i==null?void 0:i.status},"log");break}case"HTTP-Response-GraphQL-Deprecation-Notice":{const{deprecationNotice:n,requestParams:a}=r.content,[i,o]=a||[];E.leaveBreadcrumb("GraphQL Deprecation Notice: ".concat(i),{deprecationNotice:n,url:i,method:o==null?void 0:o.method},"log");break}default:{const n=r;E.leaveBreadcrumb("GraphQL Logger: ".concat(n.type),{type:n.type,content:n.content},"log")}}}catch(n){}}}}function Hd(t){if("fromEntries"in Object)return Object.fromEntries(t);const e={};for(const[r,n]of t.entries())e[r]=n;return e}const Gd="unstable";class Wt{constructor({accessToken:e,country:r,locale:n,apiVersion:a=Gd,withCarrierRates:i=!1,cartPrepareMigrationEnabled:o=!1}){if(d(this,"OPERATION_NAME_REGEX",/[^ ]+ (\w+)/),d(this,"LANGUAGES_WITH_REGION",["zh-CN","zh-TW","pt-BR","pt-PT"]),d(this,"client"),d(this,"country"),d(this,"url"),d(this,"locale"),d(this,"withCarrierRates"),d(this,"lastValidCart"),d(this,"cartPrepareMigrationEnabled"),d(this,"hasBeenVisible",!1),!e||!r)throw new Y({code:"invalid-webcomponent",message:"accelerated checkout rendered without required webcomponent attributes"});if(!n)throw new Error("StorefrontApiClient constructed with no locale");this.country=r,this.locale=n,this.withCarrierRates=i,this.cartPrepareMigrationEnabled=o,this.url="/api/".concat(a,"/graphql.json"),this.client=nd(Bd({url:this.url,accessToken:e}))}async createCart(e){var r,n,a;const i=await this.requestStream([md,It],{input:{lines:[{merchandiseId:e.merchandiseId,quantity:e.quantity,sellingPlanId:e.sellingPlanId,attributes:this.stringifyAttributes(e.lineItemProperties)}],discountCodes:e.discountCodes,buyerIdentity:e.buyerIdentity},country:this.country,language:this.formatLanguage(this.locale)},{instrumentName:e.instrumentName,startingCheckout:!0,operationName:"createCart"});try{for(var o=re(i),s,l,c;s=!(l=await o.next()).done;s=!1){const u=l.value;u.errors&&await this.onError({operationName:"createCart",response:u});const h=(r=u.data)==null?void 0:r.result;if(h&&!u.hasNext){h.errors.length>0&&this.onResultError(h.errors);const g=this.parseMutationWarnings((a=(n=u.data)==null?void 0:n.result)==null?void 0:a.warnings),m=h.cart?this.parseCartResponse(h.cart):null;return{data:m,errors:this.parseMutationErrors({result:u,key:"result",operationName:"cartCreate"}),warnings:g,decelerationReason:Jt({cart:m,warnings:g}),abortReason:tn({cart:m,warnings:g})}}}}catch(u){c=[u]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(c)throw c[0]}}throw new ue("Cart create operation returned no response")}async updateCartBillingAddress(e){const{cartId:r,billingAddress:n,instrumentName:a}=e;return this.requestDeferredCart(gd,{cartId:r,billingAddress:n},{instrumentName:a,operationName:"updateCartBillingAddress"})}async updateCartBuyerIdentity(e,r){const{cartId:n,instrumentName:a}=e;return this.requestDeferredCart(fd,{cartId:n,buyerIdentity:$d(e)},{instrumentName:a,operationName:"updateCartBuyerIdentity",abortSignal:r})}async updateSelectedDeliveryOptions(e,r,n,a){let i=r;const o=ae()+2e4;for(;ae()typeof c=="string"&&c.startsWith(y.PendingDeliveryGroups))))return s;const l=s.data.deliveryGroups.flatMap(c=>c.deliveryOptions.map(u=>({deliveryOptionHandle:u.handle,deliveryGroupId:c.id})));i=i.map(c=>{var u;return(u=l.find(h=>h.deliveryOptionHandle===c.deliveryOptionHandle))!=null?u:c})}throw new Error("Selected delivery options update operation timed out")}async applePaySessionCreate(e){var r,n,a;const i=await this.requestStream([Ed],{validationUrl:e.toString()},{instrumentName:f.ApplePay,operationName:"applePaySessionCreate"});try{for(var o=re(i),s,l,c;s=!(l=await o.next()).done;s=!1){const u=l.value;u.errors&&await this.onError({operationName:"applePaySessionCreate",response:u});const h=(a=(n=(r=u.data)==null?void 0:r.applePaySessionCreate)==null?void 0:n.applePaySession)==null?void 0:a.body;if(h)return h}}catch(u){c=[u]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(c)throw c[0]}}throw new ue("Apple Pay session create operation returned no response")}async paypalBuyerDetailsFetch(e,r){var n,a;const i=await this.requestStream([Ad],{token:e,cartId:r},{instrumentName:f.PayPal,operationName:"paypalBuyerDetailsFetch"});try{for(var o=re(i),s,l,c;s=!(l=await o.next()).done;s=!1){const u=l.value;if(u.hasNext)continue;if(u.errors){if(u.errors.graphQLErrors){const g=nn(u.errors.graphQLErrors);if(g!=null&&g.code)throw new ee(g.code)}await this.onError({operationName:"paypalBuyerDetailsFetch",response:u})}const h=(a=(n=u.data)==null?void 0:n.paypalBuyerDetailsFetch)==null?void 0:a.paypalDetails;if(h)return h}}catch(u){c=[u]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(c)throw c[0]}}throw new ue("PayPal buyer details fetch operation returned no response")}async paypalTokenCreate({cartId:e,billingAgreement:r}){var n,a,i;const o=await this.requestStream([bd],{cartId:e,billingAgreement:r},{instrumentName:f.PayPal,operationName:"paypalTokenCreate"});try{for(var s=re(o),l,c,u;l=!(c=await s.next()).done;l=!1){const h=c.value;if(h.errors){if(h.errors.graphQLErrors){const m=nn(h.errors.graphQLErrors);if(m!=null&&m.code)throw m.isLoggable&&(p.log({body:"PayPal Token Create ".concat(m.code," Error")}),p.paypalTokenCreationError({errorCode:m.code})),new ee(m.code)}await this.onError({operationName:"paypalTokenCreate",response:h})}const g=(i=(a=(n=h.data)==null?void 0:n.paypalTokenCreate)==null?void 0:a.paypalToken)==null?void 0:i.token;if(g)return g}}catch(h){u=[h]}finally{try{l&&(c=s.return)&&await c.call(s)}finally{if(u)throw u[0]}}throw new ue("PayPal token create operation returned no response")}async fetchLimitedCart({id:e,startingCheckout:r,instrumentName:n}){var a,i;const o=await this.request([wd],{id:e},{instrumentName:n,startingCheckout:r});if(o.errors&&await this.onError({operationName:"limitedCartQuery",response:o}),!((a=o.data)!=null&&a.cart))throw new xi("Limited cart query returned no response");return E.leaveBreadcrumb("limitedCartQuery response",{operationName:"limitedCartQuery",body:(i=o.data)==null?void 0:i.cart},"log"),{id:o.data.cart.id,shippingRequired:o.data.cart.lines.edges.some(s=>s.node.merchandise.requiresShipping),sellingPlan:o.data.cart.lines.edges.some(s=>s.node.sellingPlanAllocation!=null)}}async fetchCart({id:e,startingCheckout:r,instrumentName:n}){var a;const i=this.formatLanguage(this.locale),o=this.cartPrepareMigrationEnabled?"Prepare cart":"Fetch cart",s=this.cartPrepareMigrationEnabled?Cd:Pd,l=this.cartPrepareMigrationEnabled?[It,tr,mn]:[It],c=this.cartPrepareMigrationEnabled?{cartId:e,country:this.country,language:i,withCarrierRates:this.withCarrierRates,prepareCart:!0}:{id:e,country:this.country,language:i,withCarrierRates:this.withCarrierRates},u=await this.requestStream([s,...l],c,{instrumentName:n,startingCheckout:r,operationName:"fetchCart"});try{for(var h=re(u),g,m,b;g=!(m=await h.next()).done;g=!1){const _=m.value;_.errors&&await this.onError({operationName:"fetchCart",response:_});let A=null,v;if(!_.data)throw new ue("".concat(o," operation returned no data in response"));if(zd(_.data)){const $=_.data.preparedCart;A=(a=$==null?void 0:$.result)==null?void 0:a.cart,v=this.parsePreparedCartMutationErrors(_.errors,this.extractPreparedCartMutationErrors($),"prepareCart")}else A=_.data.cart;if(E.leaveBreadcrumb("".concat(o," response"),{operationName:o,body:A,errors:v,hasNext:_.hasNext},"log"),A&&!_.hasNext){const $=this.parseCartResponse(A);return this.lastValidCart=$,$}}}catch(_){b=[_]}finally{try{g&&(m=h.return)&&await m.call(h)}finally{if(b)throw b[0]}}throw new ue("".concat(o," operation returned no response"))}async updateCartPayment(e,r,n,a){var i,o,s,l,c,u,h,g,m,b;const _={cartId:e,input:r},{amount:A,currencyCode:v}=r.amount;let $,I,U=!1,L;try{const q=ae()+1e4;for(;ae()setTimeout(H,500)),_.input.amount={amount:P.data.totalAmount.amount,currencyCode:P.data.totalAmount.currencyCode},L!=null||(L={retryCount:0,retryStartTime:ae()}),L.retryCount++;continue}return(P.data.totalAmount.amount===A||parseFloat(P.data.totalAmount.amount)<=parseFloat(A))&&P.data.totalAmount.currencyCode===v?(U=!0,P):$}throw new Error("Payment update operation timed out")}finally{if(L){const q=ae()-L.retryStartTime,P=(s=I==null?void 0:I.data)==null?void 0:s.totalAmount.amount;let H;if(P&&A){const X=parseFloat(A),se=parseFloat(P);se>X?H="inc":se0){this.onResultError(U);const P=this.parseMutationWarnings((g=(h=I.data)==null?void 0:h.result)==null?void 0:g.warnings);return{data:this.lastValidCart,errors:this.parsePreparedCartMutationErrors(I.errors,U,n.operationName),warnings:P,decelerationReason:Jt({warnings:P,cart:this.lastValidCart})}}}}catch(I){$=[I]}finally{try{A&&(v=_.return)&&await v.call(_)}finally{if($)throw $[0]}}throw new ue("Deferred cart operation returned no response")}async handleGraphQLErrorResponse(e,r){const n=await Td(e,r);if(!n)return;const{message:a,...i}=n,{isIgnorable:o,reason:s}=xd(n,{hasBeenVisible:this.hasBeenVisible});if(E.leaveBreadcrumb(a,{ignored:o,ignoredReason:s,...r,...i},"error"),o)throw p.log({body:"Ignored GraphQL response error",attributes:{message:a,reason:s,...i}}),new ht(a,{reason:s,errorDetails:i});return{message:a,errorDetails:i}}async onError({operationName:e,response:r,abortSignal:n}){if(n!=null&&n.aborted)throw p.log({body:"Request aborted",attributes:{operationName:e,reason:n.reason}}),new ht("Request aborted",{reason:"abort",errorDetails:{operationName:e}});const a=await this.handleGraphQLErrorResponse(e,r);if(!a)return;const{message:i,errorDetails:o}=a;throw new Et(i,{errorDetails:o})}onResultError(e){E.leaveBreadcrumb("GraphQL result error",e,"error")}formatLanguage(e){return e.includes("-")?this.LANGUAGES_WITH_REGION.includes(e)?e.toUpperCase().replace("-","_"):e.split("-")[0].toUpperCase():e.toUpperCase()}parseCartResponse(e){var r,n,a;const i=e.lines.edges.map(s=>{var l,c;const u=s.node;return{quantity:u.quantity,totalAmount:{amount:u.cost.totalAmount.amount,currencyCode:u.cost.totalAmount.currencyCode},subtotalAmount:{amount:(l=u.cost.subtotalAmount)==null?void 0:l.amount,currencyCode:(c=u.cost.subtotalAmount)==null?void 0:c.currencyCode},merchandise:{requiresShipping:u.merchandise.requiresShipping},discountAllocations:u.discountAllocations,sellingPlanAllocation:u.sellingPlanAllocation}}),o=e.deliveryGroups.edges.map(s=>s.node);return{id:e.id,totalAmount:e.cost.totalAmount,subtotalAmount:(r=e.cost.subtotalAmount)!=null?r:void 0,totalTaxAmount:(n=e.cost.totalTaxAmount)!=null?n:void 0,totalDutyAmount:(a=e.cost.totalDutyAmount)!=null?a:void 0,discountAllocations:e.discountAllocations,discountCodes:e.discountCodes,lineItems:i,deliveryGroups:o,checkoutUrl:e.checkoutUrl}}parseGraphQlErrors(e){var r,n;return(n=(r=e==null?void 0:e.graphQLErrors)==null?void 0:r.map(a=>a.message.replace(/\(Expected.*\)/,"").trim()))!=null?n:[]}parseMutationError(e){return e.code===Ct?{code:Ct,message:e.message}:e.field&&e.field.length>0?"".concat(e.code,": ").concat(e.field.join(".")):e.code}parseMutationErrors({result:e,key:r,operationName:n}){var a,i,o;const s=this.parseGraphQlErrors(e.errors),l=((o=(i=(a=e.data)==null?void 0:a[r])==null?void 0:i.errors)==null?void 0:o.map(this.parseMutationError).filter(u=>u))||[],c=[...s,...l];return c.length>0&&E.leaveBreadcrumb("GraphQL errors on mutation '".concat(n,"'"),c,"error"),c}parseMutationWarnings(e){return!e||e.length===0?[]:e.map(r=>r.code)}stringifyAttributes(e){return e&&e.map(r=>({key:r.key,value:typeof r.value=="string"?r.value:JSON.stringify(r.value)}))}filterErrors(e){var r;return!((r=e.code)!=null&&r.startsWith("PENDING_DELIVERY_GROUPS")||e.code==="INVALID_PAYMENT")}extractPreparedCartMutationErrors(e){var r,n;const a=(r=e==null?void 0:e.errors)!=null?r:[];return((n=e==null?void 0:e.result)==null?void 0:n.__typename)==="CartStatusNotReady"&&a.push(...e.result.errors),a}extractMutationErrors(e){var r,n,a,i;let o=(a=(n=(r=e.data)==null?void 0:r.result)==null?void 0:n.errors)!=null?a:[];return this.cartPrepareMigrationEnabled&&(o=o.filter(this.filterErrors)),[...o,...this.extractPreparedCartMutationErrors((i=e.data)==null?void 0:i.preparedCart)]}parsePreparedCartMutationErrors(e,r,n){const a=this.parseGraphQlErrors(e),i=r.map(this.parseMutationError).filter(s=>s),o=[...a,...i];return o.length>0&&E.leaveBreadcrumb("GraphQL errors on mutation '".concat(n,"'"),o,"error"),o}parseCompletionErrors(e){var r,n,a,i,o,s;const l=this.parseGraphQlErrors(e.errors);let c=[];((a=(n=(r=e.data)==null?void 0:r.cartSubmitForCompletion)==null?void 0:n.result)==null?void 0:a.__typename)==="SubmitFailed"&&(c=(i=e.data.cartSubmitForCompletion.result.errors.map(h=>h.code))!=null?i:[]);const u=[...l,...c];return u.length>0?E.leaveBreadcrumb("GraphQL errors on completion",u,"error"):e.errors&&E.leaveBreadcrumb("Errors on submitForCompletion",{errors:e.errors,hasData:!!e.data,hasResult:!!((s=(o=e.data)==null?void 0:o.cartSubmitForCompletion)!=null&&s.result)},"error"),u}}function zd(t){return!("cart"in t)}function $d({emailAddress:t,countryCode:e,phone:r,streetAddress:n,validateAddress:a,preferences:i}){return{email:t,countryCode:e!=null?e:n==null?void 0:n.country,phone:r!=null?r:n==null?void 0:n.phone,deliveryAddressPreferences:n?[{deliveryAddressValidationStrategy:a?"STRICT":"COUNTRY_CODE_ONLY",deliveryAddress:n}]:[],preferences:i}}function gn({instrumentName:t,startingCheckout:e}){const r={};return t&&(r["X-Wallet-Name"]="".concat(t)),e&&(r["X-Start-Wallet-Checkout"]="".concat(e)),r}async function xa({cartId:t,cartClient:e,instrumentName:r,selectedDeliveryOptions:n,abortSignal:a}){try{if(!t)throw new Error("[".concat(r,"] provided no cart ID when updating shipping method"));if(!e)throw new Error("[".concat(r,"] provided invalid cart client when updating shipping method"));return await e.updateSelectedDeliveryOptions(t,n,r,a)}catch(i){throw p.updateFailed(r,"updateSelectedDeliveryOptions"),i}}async function Fa({cartId:t,token:e,cartClient:r,instrumentName:n}){try{if(!t)throw new Error("[".concat(n,"] provided no cart ID when submitting for completion"));if(!r)throw new Error("[".concat(n,"] provided invalid cart client when submitting for completion"));if(!e)throw new Error("[".concat(n,"] provided no token when submitting for completion"));return await r.submitForCompletion(t,e,n)}catch(a){throw p.updateFailed(n,"submitForCompletion"),a}}function Ua({selectedDeliveryOptionHandles:t,deliveryGroups:e,instrumentName:r}){return e.map(n=>{const a=n.deliveryOptions.filter(i=>t.includes(i.handle));if(!a.length)return{deliveryGroupId:"",deliveryOptionHandle:""};if(a.length>1)throw new Vd("[".concat(r,"] found multiple delivery options with selectedDeliverOptionHandle in group: ").concat(n.id),{groupingHash:"getSelectedDeliveryOptions::MultipleOptions"});return{deliveryGroupId:n.id,deliveryOptionHandle:a[0].handle}}).filter(n=>!!n.deliveryGroupId)}class Vd extends oe{constructor(){super(...arguments),d(this,"name","GetSelectedDeliveryOptionsError")}}async function Wd(t){const{cartClient:e,instrumentName:r}=t;try{if(!t.cartId)throw new Error("[".concat(r,"] provided no cart ID when updating billing address"));if(!e)throw new Error("[".concat(r,"] provided invalid cart client when updating billing address"));return await e.updateCartBillingAddress(t)}catch(n){throw p.updateFailed(r,"updateBillingAddress"),n}}function fn(t,e){return t.some(r=>e.includes(r))}function ct({result:t,instrument:e}){var r;const n=(r=t.errors)!=null?r:[];fn(n,Rr)&&p.dynamicTaxFailed({instrument:e}),fn(n,al)&&p.dynamicShippingFailed({instrument:e})}const _n=["cart_not_ready","cart_throttled","not_enough_stock","payment_method_not_applicable","account_info_mismatch"];class Yd{constructor({accessToken:e,buyerCountry:r,buyerCurrency:n,button:a,i18n:i,merchantName:o,dataSource:s,apiClient:l,walletParams:c}){d(this,"name",f.ApplePay),d(this,"accessToken"),d(this,"button"),d(this,"buyerCountry"),d(this,"cart"),d(this,"apiClient"),d(this,"dataSource"),d(this,"i18n"),d(this,"merchantName"),d(this,"session"),d(this,"paymentSheetActionGenerator"),d(this,"cancelled"),d(this,"buyerCurrency"),d(this,"customerAccountEmail"),d(this,"abortController",null),d(this,"isPersonalDataCleared",!1),d(this,"isSheetLoaded",!1),d(this,"walletParams"),d(this,"onvalidatemerchant",async u=>{var h,g,m;try{const b=new URL(u.validationURL),_=this.getMerchantSession(b),{cart:A,decelerationReason:v,customValidationError:$,unrecoverableError:I}=await Ee({element:this.button,instrumentName:this.name,dataSource:this.dataSource});if(I){E.leaveBreadcrumb("ApplePay Session unrecoverable error",{unrecoverableError:I},"error"),p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),this.withActiveSession("abort",()=>this.session.abort()),(h=this.abortController)==null||h.abort("[Apple Pay] Unrecoverable error ".concat(I)),ke(this.i18n,I);return}if($){E.leaveBreadcrumb("ApplePay Session custom validation error",{customValidationError:$},"error"),p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),this.withActiveSession("abort",()=>this.session.abort()),(g=this.abortController)==null||g.abort("[Apple Pay] Custom validation error"),Oe(this.i18n,$.message);return}this.cart=A;const U=await _;if(E.leaveBreadcrumb("ApplePay Session completeMerchantValidation",{session:U},"log"),v&&_n.includes(v)){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),await this.terminateSession(),F({checkoutUrl:(m=A==null?void 0:A.checkoutUrl)!=null?m:"",instrumentName:this.name,reason:v});return}if(this.sessionIsCancelled()){p.sheetClicked({instrument:this.name,result:"rejected",reason:"cancelled"});return}this.withActiveSession("completeMerchantValidation",()=>this.session.completeMerchantValidation(U)),p.sheetClicked({instrument:this.name,result:"success"})}catch(b){p.sheetClicked({instrument:f.ApplePay,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in Apple Pay sheet clicked",attributes:{error:String(b),location:"onvalidatemerchant"}}),this.terminateSession({error:b})}}),d(this,"onshippingcontactselected",async u=>{if(!this.sessionIsCancelled())try{const h=wt(u.shippingContact),g=await Ge({cartId:this.cart.id,streetAddress:h,cartClient:this.apiClient,instrumentName:this.name});if(await this.decelerateOrAbort(g))return;await this.applyPaymentSheetActions({result:g,onProceed:m=>this.completeShippingContactSelection(g.data,m),context:{shippingRequired:this.isShippingRequired,shippingCountryCode:h.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onShippingContactSelected::updateBuyerIdentity",afterAuthorization:!1})}catch(h){this.terminateSession({error:h})}}),d(this,"onshippingmethodselected",async u=>{var h;if(!this.sessionIsCancelled())try{const g=u.shippingMethod.identifier.split(","),m=Ua({selectedDeliveryOptionHandles:g,deliveryGroups:this.cart.deliveryGroups,instrumentName:this.name});if(m.length===0){this.handleShippingMethodNotFoundInCart(g);return}const b=await xa({cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name,selectedDeliveryOptions:m,abortSignal:(h=this.abortController)==null?void 0:h.signal});if(await this.decelerateOrAbort(b))return;await this.applyPaymentSheetActions({result:b,onProceed:()=>this.completeShippingMethodSelection(b.data),context:{shippingRequired:this.isShippingRequired,shippingCountryCode:void 0},checkoutUrl:this.cart.checkoutUrl,requestType:"onShippingMethodSelected::updateSelectedDeliveryOptions",afterAuthorization:!1}),this.onSheetLoaded()}catch(g){this.terminateSession({error:g})}}),d(this,"onpaymentmethodselected",async u=>{if(!this.sessionIsCancelled())try{const{billingContact:h}=u.paymentMethod,g=this.cart.id;if(!this.isShippingRequired&&h){const _=wt(h),A=await Ge({cartId:this.cart.id,countryCode:_.country,cartClient:this.apiClient,instrumentName:this.name});if(await this.decelerateOrAbort(A))return;await this.applyPaymentSheetActions({result:A,onProceed:()=>{this.cart=A.data},context:{shippingRequired:this.isShippingRequired,shippingCountryCode:_.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentMethodSelected::updateBuyerIdentity",afterAuthorization:!1});const v=await Wd({billingAddress:_,cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name});if(await this.decelerateOrAbort(v))return;await this.applyPaymentSheetActions({result:v,onProceed:()=>{this.cart=v.data},context:{shippingRequired:this.isShippingRequired,shippingCountryCode:_.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentMethodSelected::updateBillingAddress",afterAuthorization:!1}),this.cart||p.log({body:"[ApplePay] Cart is null after onPaymentMethodSelected::updateBillingAddress",attributes:{cartId:g,result:v,walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,session:this.sessionIsCancelled()}})}const{newTotal:m,newLineItems:b}=this.getNewTotalAndLineItems(this.cart);if(E.leaveBreadcrumb("ApplePay Session completePaymentMethodSelection",{newTotal:m,newLineItems:b},"log"),this.sessionIsCancelled())return;this.withActiveSession("completePaymentMethodSelection",()=>this.session.completePaymentMethodSelection({newTotal:m,newLineItems:b})),this.isShippingRequired||this.onSheetLoaded()}catch(h){this.terminateSession({error:h})}}),d(this,"oncancel",()=>{var u;this.cancelled=!0,this.removePersonalData(),K(O.SheetLoad,this.name),p.sheetCancelled(this.name),this.button.disabled=!1,(u=this.abortController)==null||u.abort("[Apple Pay] Payment sheet cancelled")}),d(this,"onpaymentauthorized",async u=>{p.authorizationAttempt(this.name),Xe(O.AuthorizationLatency,this.name);const h=async U=>{var L,q;switch((L=U.effects)==null||L.forEach(P=>P()),U.action){case"complete":{const P=ApplePaySession.STATUS_SUCCESS;try{await this.completePayment(P),fe(U.redirectUrl)}catch(H){this.terminateSession({error:H,afterAuthorization:!0})}break}case"show_error":{const P=(q=U.errors)!=null?q:[];try{await this.completePayment(ApplePaySession.STATUS_FAILURE,P)}catch(H){this.terminateSession({error:H,afterAuthorization:!0})}break}case"abort":{try{this.abortPaymentSheetAndShowError(),this.removePersonalData()}catch(P){this.terminateSession({error:P,afterAuthorization:!0})}break}case"decelerate":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),await this.removePersonalData(),F({checkoutUrl:U.redirectUrl,instrumentName:this.name,reason:U.reason})}catch(P){this.terminateSession({error:P,afterAuthorization:!0})}break}default:this.terminateSession({error:new Error("[".concat(this.name,"] completion action not handled: ").concat(U.action)),afterAuthorization:!0})}},{token:g,billingContact:m,shippingContact:b}=u.payment;let _=null,A=null;try{if(!m){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}if(_=wt({...m,phoneNumber:b==null?void 0:b.phoneNumber}),this.isShippingRequired){if(!b){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}A=wt(b)}}catch(U){this.terminateSession({error:U,afterAuthorization:!0});return}const v=async()=>{var U,L;try{const q=this.isShippingRequired?{validateAddress:!0,streetAddress:A}:{},P=(U=this.customerAccountEmail)!=null?U:b==null?void 0:b.emailAddress,H=await Ge({cartId:this.cart.id,emailAddress:P,cartClient:this.apiClient,instrumentName:this.name,...q});if(ct({result:H,instrument:this.name}),await this.decelerateOrAbort(H))return;const X=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction({result:H,context:{shippingRequired:this.isShippingRequired,shippingCountryCode:A==null?void 0:A.country,billingCountryCode:_==null?void 0:_.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updateBuyerIdentity"});(L=X.effects)==null||L.forEach(se=>se()),await this.handlePaymentSheetAction({paymentSheetAction:X,onProceed:async se=>{se&&se.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,se):await $()},afterAuthorization:!0})}catch(q){this.terminateSession({error:q,afterAuthorization:!0})}},$=async()=>{var U,L;try{const q=this.cart.lineItems.some(X=>!!X.sellingPlanAllocation),P=await xr({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{applePayWalletContent:{billingAddress:_,data:g.paymentData.data,header:g.paymentData.header,lastDigits:g.paymentMethod.displayName.split(" ")[1],signature:g.paymentData.signature,version:g.paymentData.version}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:_,cartClient:this.apiClient,instrumentName:this.name,hasSellingPlan:q,abortSignal:(U=this.abortController)==null?void 0:U.signal});if(ct({result:P,instrument:this.name}),await this.decelerateOrAbort(P))return;const H=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction({result:P,context:{shippingRequired:this.isShippingRequired,shippingCountryCode:A==null?void 0:A.country,billingCountryCode:_==null?void 0:_.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updatePayment"});(L=H.effects)==null||L.forEach(X=>X()),await this.handlePaymentSheetAction({paymentSheetAction:H,onProceed:async X=>{X&&X.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,X):await I()},afterAuthorization:!0})}catch(q){this.terminateSession({error:q,afterAuthorization:!0})}},I=async()=>{var U;try{const L=await Fa({cartId:this.cart.id,token:g.transactionIdentifier,cartClient:this.apiClient,instrumentName:this.name});ct({result:L,instrument:this.name}),(U=L.errors)!=null&&U.includes(y.GenericError)&&(E.leaveBreadcrumb("ApplePay Generic ERROR encountered during completion",{errorCodes:L.errors},"error"),p.log({body:"[ApplePay] Generic ERROR code encountered during completion",attributes:{errorCodes:L.errors}}));const q=this.paymentSheetActionGenerator.mapCompletionResultToPaymentSheetAction({result:L,context:{shippingRequired:this.isShippingRequired,shippingCountryCode:A==null?void 0:A.country,billingCountryCode:_==null?void 0:_.country},checkoutUrl:L.data&&"checkoutUrl"in L.data&&L.data.checkoutUrl?L.data.checkoutUrl:this.cart.checkoutUrl});await h(q)}catch(L){this.terminateSession({error:L,afterAuthorization:!0})}};await v()}),d(this,"terminateSession",async({error:u,afterAuthorization:h=!1}={})=>{var g;try{this.button.disabled=!1,u&&E.notify(u),h?p.authorizationComplete({instrument:this.name,measurement:K(O.AuthorizationLatency,this.name),result:"failed"}):(K(O.SheetLoad,this.name),p.sheetFailed(this.name,u)),E.leaveBreadcrumb("ApplePay Session abort",{afterAuthorization:h},"log");try{this.withActiveSession("abort",()=>this.session.abort()),(g=this.abortController)==null||g.abort("[Apple Pay] Payment sheet terminated")}catch(m){}if(u){const m=this.i18n.translate("brand.apple_pay");ie(m,this.i18n)}}finally{await this.removePersonalData()}}),d(this,"getMostRecentNonNullCart",(u,h)=>u?(this.cart=u,u):h),d(this,"handleNullCart",u=>{if(!u)throw new Error("[".concat(this.name,"] no cart returned on mutation, aborting"))}),d(this,"completeShippingContactSelection",(u,h)=>{try{const g=this.getMostRecentNonNullCart(u,this.cart),{newTotal:m,newLineItems:b}=this.getNewTotalAndLineItems(g),_=on(g.deliveryGroups,this.i18n);E.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{errors:h,newTotal:m,newLineItems:b,newShippingMethods:_},"log"),this.withActiveSession("completeShippingContactSelection",()=>this.session.completeShippingContactSelection({errors:h!=null?h:[],newTotal:m,newLineItems:b,newShippingMethods:_}))}catch(g){this.terminateSession({error:g})}}),d(this,"completeShippingMethodSelection",u=>{try{this.handleNullCart(u),this.cart=u;const{newTotal:h,newLineItems:g}=this.getNewTotalAndLineItems(u);E.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{newTotal:h,newLineItems:g},"log"),this.withActiveSession("completeShippingMethodSelection",()=>this.session.completeShippingMethodSelection({newTotal:h,newLineItems:g}))}catch(h){this.terminateSession({error:h})}}),d(this,"sessionIsCancelled",()=>this.cancelled),this.accessToken=e,this.buyerCountry=r,this.button=a,this.cart=null,this.apiClient=l,this.dataSource=s,this.i18n=i,this.merchantName=o,this.cancelled=!1,this.buyerCurrency=n,this.customerAccountEmail=c.customerAccountEmail,this.walletParams=c;try{this.session=new ApplePaySession(Hn,Yc({shippingRequired:this.isShippingRequired,walletParams:c,buyerCurrency:n}))}catch(u){throw new jc(String(u),{cause:u})}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 Wc(i)}begin(){E.leaveBreadcrumb("ApplePay Session begin",{shippingRequired:this.isShippingRequired,buyerCurrency:this.buyerCurrency,walletParams:this.walletParams},"log"),this.abortController=ve("AbortController"),this.session.begin()}handleShippingMethodNotFoundInCart(e){var r,n;const a=on((n=(r=this.cart)==null?void 0:r.deliveryGroups)!=null?n:[],this.i18n);E.leaveBreadcrumb("ApplePay Session selected shipping method(s) not found in current cart, updating payment sheet",{attemptedDeliveryOptionHandles:e,currentShippingMethods:a},"log"),this.completeShippingMethodSelection(this.cart)}async applyPaymentSheetActions({result:e,onProceed:r,context:n,checkoutUrl:a,requestType:i,afterAuthorization:o}){var s;const l=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction({result:e,context:n,checkoutUrl:a,requestType:i});(s=l.effects)==null||s.forEach(c=>c()),!this.sessionIsCancelled()&&await this.handlePaymentSheetAction({paymentSheetAction:l,onProceed:r,afterAuthorization:o})}async getMerchantSession(e){const r=await new Wt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,apiVersion:"unstable"}).applePaySessionCreate(e);return JSON.parse(r)}abortPaymentSheetAndShowError(){E.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.withActiveSession("abort",()=>this.session.abort()),this.button.disabled=!1,this.emitPaymentCompleteTelemetry(ApplePaySession.STATUS_FAILURE)}abortPaymentSheetAndShowOutOfStockModal(){E.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.withActiveSession("abort",()=>this.session.abort()),this.button.disabled=!1,ge(this.i18n),this.emitPaymentCompleteTelemetry(ApplePaySession.STATUS_FAILURE)}emitPaymentCompleteTelemetry(e){p.authorizationComplete({instrument:this.name,measurement:K(O.AuthorizationLatency,this.name),result:e===ApplePaySession.STATUS_SUCCESS?"success":"failed"})}async completePayment(e,r=void 0){E.leaveBreadcrumb("ApplePay Session completePayment",{status:e,errors:r},"log");const n=this.withActiveSession("completePayment",()=>{this.session.completePayment({status:e,errors:r})});this.emitPaymentCompleteTelemetry(e),n===void 0&&e===ApplePaySession.STATUS_SUCCESS&&p.paymentCompletedAfterAbort({instrument:this.name,error:"Session already terminated"})}getNewTotalAndLineItems(e){return{newTotal:zc(this.merchantName,e.totalAmount),newLineItems:$c({subtotal:wa(e),discountAllocations:qc(e),deliveryGroups:e.deliveryGroups,duties:e.totalDutyAmount,taxes:e.totalTaxAmount,i18n:this.i18n,formattedRecurringTotals:Qc(this.cart.lineItems,this.i18n)})}}async decelerateOrAbort(e){return e.abortReason==="out_of_stock"?(p.sheetClicked({instrument:this.name,result:"rejected",reason:"out_of_stock"}),this.abortPaymentSheetAndShowOutOfStockModal(),!0):this.decelerateIfNeeded(e)}async decelerateIfNeeded(e){if(!e.data)return!1;const{checkoutUrl:r,totalAmount:n}=e.data;let a;if(e.decelerationReason&&_n.includes(e.decelerationReason)?a=e.decelerationReason:Nr({currentCartTotal:n,initialBuyerCurrency:this.buyerCurrency})&&(a="currency_changed"),a){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"});try{await this.terminateSession()}finally{F({checkoutUrl:r,instrumentName:this.name,reason:a})}return!0}return!1}get isShippingRequired(){return this.button.isShippingRequired}async removePersonalData(){this.isPersonalDataCleared||!this.cart||(await this.apiClient.cartRemovePersonalData({cartId:this.cart.id,instrumentName:this.name}),this.isPersonalDataCleared=!0)}onSheetLoaded(){if(this.isSheetLoaded)return;this.isSheetLoaded=!0;const e=K(O.SheetLoad,this.name);e&&(z({event:B.SheetLoaded,ttl:e}),p.sheetLoaded({instrument:this.name,measurement:e}))}withActiveSession(e,r){var n,a;if((a=(n=this.abortController)==null?void 0:n.signal)!=null&&a.aborted){p.walletSessionAbortError({instrument:this.name,errorName:"SessionAlreadyTerminated",methodName:e});return}try{return r()}catch(i){if(i instanceof Error&&i.name==="InvalidAccessError"){p.walletSessionAbortError({instrument:this.name,errorName:"InvalidAccessError",methodName:e});return}throw i}}async handlePaymentSheetAction({paymentSheetAction:e,onProceed:r,afterAuthorization:n}){switch(e.action){case"abort":this.terminateSession({afterAuthorization:n});break;case"show_error":await r(e.errors);break;case"update":await r(e.errors);break;case"decelerate":try{await this.terminateSession({afterAuthorization:n})}finally{F({instrumentName:this.name,checkoutUrl:e.redirectUrl,reason:e.reason})}break;default:throw new Error('Missing handler for payment sheet action "'.concat(e.action,'"'))}}}function Ur({translate:t,logoElement:e,setAriaHidden:r}){const n=document.createElement("div");return t("buy_with_button_content",{wallet:"LOGO_PLACEHOLDER"}).split(new RegExp("(LOGO_PLACEHOLDER)")).filter(Boolean).forEach(a=>{let i;a==="LOGO_PLACEHOLDER"?i=e:(i=document.createElement("span"),i.innerText=a,r&&i.setAttribute("aria-hidden","true")),n.appendChild(i)}),n}const Ot=new Map;function qd({instrumentName:t,logoType:e="LIGHT",logoContent:r}){const n=Ot.get(t)||{};n[e]||(n[e]=r,Ot.set(t,n))}function pt({instrumentName:t,logoType:e="LIGHT"}){var r;const n=(r=Ot.get(t))==null?void 0:r[e];if(!n)throw new Error("".concat(t," ").concat(e," logo not loaded"));return n}class jd extends Ae{constructor(){super(...arguments),d(this,"name",f.ApplePay),d(this,"button",null)}static get observedAttributes(){return["disabled"]}get merchantName(){return this.walletParams.merchantName}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}attributeChangedCallback(e,r,n){super.attributeChangedCallback(e,r,n,this.button)}async handleClick(e){if(e.preventDefault(),this.disabled||!this.button||this.button.hasAttribute("aria-disabled"))return;this.disabled=!0;const[r,n,a]=await Promise.all([this.i18n,this.dataSource,this.apiClient]);Xe(O.SheetLoad,this.name);let i;try{if(i=new Yd({accessToken:this.accessToken,buyerCountry:this.buyerCountry,buyerCurrency:this.buyerCurrency,button:this,i18n:r,merchantName:this.merchantName,dataSource:n,apiClient:a,walletParams:this.walletParams}),!i)throw new Error("missing ApplePaySession");i.begin()}catch(o){E.leaveBreadcrumb("Failed to create ApplePay Session",{error:o},"error"),i||(p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in Apple Pay session creation",attributes:{error:String(o),location:"handleClick"}})),i==null||i.terminateSession(),ie(r.translate("brand.apple_pay"),r),this.disabled=!1}}async render(){var e;const r=this.getOrCreateShadowRoot(),{translate:n}=await this.i18n,a=pt({instrumentName:f.ApplePay}),i=new DOMParser().parseFromString(a,"image/svg+xml").documentElement;if(!this.button){const o=this.isCTA?n("buy_with_button_content",{wallet:n("brand.apple_pay")}):n("brand.apple_pay");if(this.button=Gt({label:o}),this.button.onclick=s=>this.handleClick(s),this.button.classList.add("apple-pay-button",mi[this.buttonTheme],Le.BUTTON),this.isCTA){const s=Ur({translate:n,logoElement:i,setAriaHidden:!0});s.classList.add("apple-pay--content"),this.button.appendChild(s)}else this.button.appendChild(i);this.initializeShadowStyles(r,kc),r.appendChild(this.button),this.ensureLightDOMIsNotEmpty(),(e=this.onRendered)==null||e.call(this)}this.disabled&&(this.button.setAttribute("disabled",""),this.button.setAttribute("aria-disabled","true"))}}function Br(t){return function(e,r,n){const a=n.value;return n.value=function(...i){const o=a.apply(this,i);return o.eligible||console.debug("[DEBUG] ".concat(t," could not be rendered. Reason: ").concat(o.reason)),o},n}}async function Ke({svg:t,instrumentName:e,logoType:r="LIGHT"}){var n;if((n=Ot.get(e))!=null&&n[r])return;let a,i,o;try{if(o=Qd(t),a=await fetch(o,{headers:{Accept:"image/svg+xml"}}),!a.ok)throw new Error("Failed to fetch SVG: ".concat(a.status," ").concat(a.statusText));if(i=await a.text(),!i||!i.includes("{for(var a=Xd(e,r),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,r,a)||a);return a&&Kd(e,r,a),a};class Hr extends be{constructor(e){super(e),d(this,"companyFieldRequired"),this.companyFieldRequired=!!this.walletParams.companyRequired}static walletName(){return"apple_pay"}getWebComponentName(){return"shopify-apple-pay-button"}getWebComponentClass(){return jd}getInstrumentName(){return f.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 e,r,n,a;if(typeof window>"u"||window.ApplePaySession===void 0)return{eligible:!1,reason:"window or ApplePaySession is undefined"};try{if(!((r=(e=window.ApplePaySession).supportsVersion)!=null&&r.call(e,Hn)))return{eligible:!1,reason:"SDK does not meet minimum version requirement"};if(!((a=(n=window.ApplePaySession).canMakePayments)!=null&&a.call(n)))return{eligible:!1,reason:"failed SDK eligibility check"}}catch(i){return{eligible:!1,reason:"error in SDK eligibility checks"}}return{eligible:!0}}async loadWalletSDK(){await this.loadAppleLogo()}async loadAppleLogo(){await Ke({svg:"apple-pay-logo.svg",instrumentName:f.ApplePay})}}Ba([Br("Apple Pay")],Hr.prototype,"getLoadEligibility"),Ba([Br("Apple Pay")],Hr.prototype,"getPartnerSDKEligibility");const Jd=".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}.buy-with-prime-button>svg{min-width:85px}";class kt extends Error{constructor(){super(...arguments),d(this,"name","MissingAccessTokenError")}}class Gr extends Error{constructor(){super(...arguments),d(this,"name","FetchingWalletsPlatformConfigError")}}class zr extends Error{constructor(){super(...arguments),d(this,"name","EmptyLineItemsWalletsPlatformConfigError")}}async function Ha({configOptionsEndpoint:t,checkoutUrl:e,sourceId:r,accessToken:n,instrument:a}){try{const i=JSON.stringify({checkout_url:e,checkout_cancel_url:window.location.href,cart_id:r}),o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":n},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 zr("[Fetch Pay Config][".concat(a,"] No eligible line items provided in the config request."));default:throw new Gr("[Fetch Pay Config][".concat(a,"] ").concat(o))}}}const Zd={[C.Checkout]:"Checkout",[C.CartAjax]:"Cart",[C.CartPage]:"Cart",[C.ProductPage]:"Product",[C.Unknown]:"Product"},Fe=class Dh extends Ae{constructor(){super(...arguments),d(this,"name",f.BuyWithPrime),d(this,"button",null),d(this,"apiClientId","")}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name),this.handleOnSendCheckoutAction=this.handleOnSendCheckoutAction.bind(this)}async createButton(){const{translate:e}=await this.i18n,r=Gt({label:e("brand.buy_with_prime")});return r.type="button",r.className="buy-with-prime-button",this.applyEnabledStyles(r),r}applyEnabledStyles(e){const r=pt({instrumentName:f.BuyWithPrime});e.innerHTML=r,e.disabled=!1,st(e,{"background-color":"#1A98FF",color:"#FFFFFF",cursor:"pointer"})}applyDisabledStyles(e){const r=pt({instrumentName:f.BuyWithPrime,logoType:"DARK"});e.innerHTML=r,e.disabled=!0,st(e,{"background-color":"#C0E3FF",color:"#7292AC",cursor:"not-allowed"})}async handleClick(){var e,r,n;if(!this.button)return;const[a,i]=await Promise.all([this.i18n,this.dataSource]);let o;try{this.applyDisabledStyles(this.button);let s=this.walletParams;if(this.apiClientId=this.apiClientId||s.appId||"",o=this.apiClientId?{apiClientId:this.apiClientId,pageType:this.pageType}:void 0,!s.createCheckoutSessionConfig){const{cart:u,decelerationReason:h,customValidationError:g,unrecoverableError:m}=await Ee({element:this,instrumentName:this.name,dataSource:i});if(m){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error",webPixelMetaData:o}),ke(a,m);return}if(g){p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error",webPixelMetaData:o}),Oe(a,g.message);return}if(h){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration",webPixelMetaData:o}),F({checkoutUrl:(e=u==null?void 0:u.checkoutUrl)!=null?e:"",instrumentName:this.name,reason:h});return}if(!this.accessToken)throw new kt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");s={...await Ha({configOptionsEndpoint:Dh.OPTIMUS_CONFIG_REST_API_URL,checkoutUrl:(r=u==null?void 0:u.checkoutUrl)!=null?r:"",sourceId:(n=ta(u))!=null?n:"",accessToken:this.accessToken,instrument:this.name})}}s.placement=this.getPlacement();const l=this.extractSKUs(s);o&&l&&(o.skus=l),delete s.checkoutSupportsSplitCart,delete s.appId;const c=s;this.pciEnabled&&(c.onSendCheckoutAction=this.handleOnSendCheckoutAction),window.amazon.buywithprime.initCheckout({amazonPayOptions:c}),p.sheetClicked({instrument:this.name,result:"success",webPixelMetaData:o})}catch(s){o&&(o.skus=o.skus||[]),Dh.EXPECTED_ERRORS.some(u=>s instanceof u)?p.sheetClicked({instrument:this.name,result:"rejected",reason:"expected_error",webPixelMetaData:o}):(p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error",webPixelMetaData:o}),p.log({body:"Unhandled error detected in Buy with Prime sheet clicked",attributes:{error:String(s),location:"handleClick"}}),E.notify(s));const{name:l}=s!=null?s:{name:"unknown"},{translate:c}=a;bt(c("error_dialogs.wallet.title",{wallet:c("brand.buy_with_prime")}),this.getModalContent(l,c))}finally{this.applyEnabledStyles(this.button)}}getModalContent(e,r){return e==="EmptyLineItemsWalletsPlatformConfigError"?r("error_dialogs.wallet.eligibility_error",{wallet:r("brand.buy_with_prime")}):r("error_dialogs.wallet.generic_error",{wallet:r("brand.buy_with_prime")})}extractSKUs(e){var r;return(r=e.createCheckoutSessionConfig)!=null&&r.payloadJSON?JSON.parse(e.createCheckoutSessionConfig.payloadJSON).cartDetails.lineItems.map(n=>n&&n.sku).filter(n=>n):[]}getPlacement(){return this.pageType&&Zd[this.pageType]||"Other"}async render(){var e;const r=this.getOrCreateShadowRoot();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(Le.BUTTON),await this.initializeShadowStyles(r,Jd),r.appendChild(this.button),(e=this.onRendered)==null||e.call(this))}buildBwpEventData(e){const r={};return e.createCheckoutSessionConfig&&(r.skus=this.extractSKUs(e),r.apiClientId=this.apiClientId),r}async handleOnSendCheckoutAction(e){const{eventName:r,redirect:n,redirectUrl:a,requestPayload:i}=e;if(n&&a){this.dispatchWalletEvent({eventName:"wallet-redirect",detail:{redirectUrl:a,requestPayload:i}});return}switch(r){case"initCheckout":{const o=this.walletParams;this.dispatchWalletEvent({eventName:"wallet-clicked",detail:{bwpEventData:this.buildBwpEventData(o)}});break}case"initChange":this.dispatchWalletEvent({eventName:"wallet-clicked"});break;case"cancelCheckout":this.dispatchWalletEvent({eventName:"wallet-cancel"});break}}};d(Fe,"OPTIMUS_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/optimus")),d(Fe,"EXPECTED_ERRORS",[Gr,kt,zr]);let hr=Fe;async function Ga({fn:t,maxRetries:e=3,delay:r=1e3,retryPolicyFn:n=()=>!0,onFinishedFn:a=()=>{}}){const i=()=>new Promise(l=>{setTimeout(l,r)});let o=0;const s=async()=>{try{return await t()}catch(l){if(o++,o{if(document.querySelector('script[src="'.concat(t,'"]'))&&window.amazon){e();return}const n=document.createElement("script");n.src=t,n.onload=()=>{window.amazon?e():r(new Error("Amazon SDK not present after loading"))},n.onerror=a=>{const i=a instanceof Event?a.type:String(a);r(new ee("Error loading Amazon SDK: ".concat(i)))},document.head.append(n)})}async function za({sdkUrl:t=br,maxRetries:e=3}){return Ga({fn:()=>eu(t),maxRetries:e,delay:200,retryPolicyFn:()=>!0,onFinishedFn:r=>{p.amazonPaySDKLoadRetries({retries:r})}})}const Ue=class Nh extends be{static walletName(){return"buy_with_prime"}constructor(e){super(e)}getWebComponentName(){return"shopify-buy-with-prime-button"}getInstrumentName(){return f.BuyWithPrime}getWebComponentClass(){return hr}async loadWalletSDK(){await za({sdkUrl:Nh.SDK_URL,maxRetries:Nh.MAX_RETRIES}),await this.loadLogos()}async loadLogos(){await Promise.all([this.loadPrimeLogo(),this.loadPrimeLogoDark()])}async loadPrimeLogo(){await Ke({svg:"prime-logo.svg",instrumentName:f.BuyWithPrime})}async loadPrimeLogoDark(){await Ke({svg:"prime-logo-dark.svg",instrumentName:f.BuyWithPrime,logoType:"DARK"})}};d(Ue,"MAX_RETRIES",3),d(Ue,"SDK_URL",br);let pr=Ue;const tu="shopify-amazon-pay-button div[role=button][slot=amazon-pay-slot][data-testid=amazon-pay-button]{border-radius:0!important;width:100%!important}",ru=':host([page-type="cart_page"]) .accelerated-checkout-button{overflow:hidden;display:flex;justify-content:center}',En="amazon-pay-slot";var yt,gt,Ve,j,le,De;const Be=class Th extends Ae{constructor(){super(...arguments),d(this,"name",f.AmazonPay),d(this,"resizeObserver",null),G(this,yt,0),G(this,gt,0),G(this,Ve,!1),G(this,j,null),G(this,le,null),G(this,De,null),d(this,"sdkButton",null)}connectedCallback(){this.resizeObserver=ve("ResizeObserver",()=>this.onResize()),this.cleanupOnFailure(this.render.bind(this),this.name)}async disconnectedCallback(){var e;this.innerHTML="",this.clearShadowRoot(),this.teardownAmazonButtonContainer(),(e=this.resizeObserver)==null||e.disconnect()}async handleClick(e){var r,n;const[a,i]=await Promise.all([this.i18n,this.dataSource]);try{const{cart:o,decelerationReason:s,customValidationError:l,unrecoverableError:c}=await Ee({element:this,instrumentName:this.name,dataSource:i});if(c){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),ke(a,c);return}if(l){p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),Oe(a,l.message);return}if(s){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),F({checkoutUrl:(r=o==null?void 0:o.checkoutUrl)!=null?r:"",instrumentName:this.name,reason:s});return}const{totalAmount:{amount:u},checkoutUrl:h}=o;let g=this.walletParams;if(!g.createCheckoutSessionConfig){if(!this.accessToken)throw new kt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");g={...await Ha({configOptionsEndpoint:Th.CV2_CONFIG_REST_API_URL,checkoutUrl:h,sourceId:(n=ta(o))!=null?n:"",accessToken:this.accessToken,instrument:this.name}),placement:this.pageType===C.ProductPage?"Product":"Cart"}}delete g.appId,e.initCheckout({...g,...Number(u)!==0&&{estimatedOrderAmount:{amount:u,currencyCode:this.buyerCurrency}}}),p.sheetClicked({instrument:this.name,result:"success"})}catch(o){Th.EXPECTED_ERRORS.some(l=>o instanceof l)?p.sheetClicked({instrument:this.name,result:"rejected",reason:"expected_error"}):(p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in Amazon Pay sheet clicked",attributes:{error:String(o),location:"handleClick"}}),E.notify(o));const s=a.translate("brand.amazon_pay");ie(s,a)}}createContainer({containerID:e,height:r}){const n=document.createElement("div");return n.id=e,n.style.display="flex",n.style.minWidth="140px",r!=null&&(n.style.height="".concat(r,"px")),n.slot=En,n.setAttribute("data-testid","amazon-pay-button"),n}async onResize(){const e=Nt(w(this,j))||0,r=vt(w(this,j))||0,n=w(this,yt)!==e||w(this,gt)!==r;!w(this,Ve)&&n&&(this.teardownAmazonButtonContainer(),await this.cleanupOnFailure(()=>this.renderFromAmazonSDK(),this.name))}async render(){var e;const r=this.getOrCreateShadowRoot();try{const n=document.createElement("slot");n.name=En;const a=document.createElement("style");a.textContent=tu,this.appendChild(a),await this.initializeShadowStyles(r,ru);const i=await this.containerInstanceNumber;M(this,le,"AcceleratedCheckoutAmazonPayButtonContainer".concat(this.pageType).concat(i)),M(this,j,document.createElement("div")),w(this,j).classList.add(Le.BUTTON),w(this,j).appendChild(n),r.appendChild(w(this,j)),(e=this.resizeObserver)==null||e.observe(w(this,j)),await this.renderFromAmazonSDK()}catch(n){E.notify(n)}}async renderFromAmazonSDK(){var e;M(this,Ve,!0);const r=vt(w(this,j))||0;M(this,De,this.createContainer({containerID:w(this,le),height:r})),this.appendChild(w(this,De));const n=Nt(w(this,j))||0,a={buttonBorderRadius:"".concat(n,"px")};let i=!1;try{if(this.sdkButton=window.amazon.Pay.renderButton("#".concat(w(this,le)),{...this.walletParams,style:a,placement:this.pageType===C.ProductPage?"Product":"Cart"}),this.sdkButton){const o=this.sdkButton;this.sdkButton.onClick(()=>this.handleClick(o))}else p.log({body:"Amazon Pay Button rendered null SDK button",attributes:{pageType:this.pageType,containerID:w(this,le)}});M(this,gt,r),M(this,yt,n),p.renderSucceeded(this.name),i=!0}catch(o){p.renderFailed(this.name);const s="Amazon Pay Button not able to render into container #".concat(w(this,le),".");console.error(s),p.log({body:s,attributes:{pageType:this.pageType,containerID:w(this,le),error:o==null?void 0:o.toString()}})}finally{M(this,Ve,!1)}i&&((e=this.onRendered)==null||e.call(this))}teardownAmazonButtonContainer(){var e;(e=w(this,De))==null||e.remove(),M(this,De,null)}};yt=new WeakMap,gt=new WeakMap,Ve=new WeakMap,j=new WeakMap,le=new WeakMap,De=new WeakMap,d(Be,"CV2_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/amazon_pay")),d(Be,"EXPECTED_ERRORS",[Gr,kt,zr]);let mr=Be;const He=class Rh extends be{static walletName(){return"amazon_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-amazon-pay-button"}getInstrumentName(){return f.AmazonPay}getWebComponentClass(){return mr}async loadWalletSDK(){await za({sdkUrl:Rh.SDK_URL,maxRetries:Rh.MAX_RETRIES})}getLoadEligibility(e){return e.getRootNode()instanceof ShadowRoot?{eligible:!1,reason:"Cannot load Amazon Pay within Shadow DOM"}:{eligible:!0}}};d(He,"MAX_RETRIES",3),d(He,"SDK_URL",br);let yr=He;var rr={Purple:{D50:"#4524DB",P40:"#5433EB"},Grayscale:{L0:"#FFFFFF"}},nu={16:16},An="gravity-font-faces",au="\n@font-face {\n font-family: 'GTStandard-M';\n src: url('https://cdn.shopify.com/shop-assets/static_uploads/shoplift/GTStandard-MRegular.woff2')\n format('woff2');\n font-style: normal;\n font-weight: 450;\n font-display: fallback;\n}\n\n@font-face {\n font-family: 'GTStandard-M';\n src: url('https://cdn.shopify.com/shop-assets/static_uploads/shoplift/GTStandard-MMedium.woff2')\n format('woff2');\n font-style: normal;\n font-weight: 500;\n font-display: fallback;\n}\n\n@font-face {\n font-family: 'GTStandard-M';\n src: url('https://cdn.shopify.com/shop-assets/static_uploads/shoplift/GTStandard-MSemibold.woff2')\n format('woff2');\n font-style: normal;\n font-weight: 600;\n font-display: fallback;\n}",iu=class extends HTMLElement{static get observedAttributes(){return["disabled"]}connectedCallback(){this._loadFonts(),this._updateButton()}attributeChangedCallback(){this._updateButton()}_loadFonts(){if(document.querySelector('style[data-description="'.concat(An,'"], style[data-description="shop-js-font-faces"]')))return;let t=document.createElement("style");t.dataset.description=An,t.appendChild(document.createTextNode(au)),document.head.appendChild(t)}_updateButton(){var t;let e=this._getOrCreateShadowRoot();e.innerHTML=su,this.hasAttribute("disabled")&&((t=e.querySelector("button"))==null||t.setAttribute("disabled",""))}_getOrCreateShadowRoot(){return this.shadowRoot||this.attachShadow({mode:"open"}),this.shadowRoot}};function ou(){window.customElements&&(customElements.get("gravity-button")||customElements.define("gravity-button",iu))}var su="\n\n\n\n \n \n');const lu=".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}.button-content>span{font-size:16px}.ShopPromise>.separator{margin:0 8px}@container bc (width <= 338px){.ShopPromise{display:none!important}}gravity-button{display:block}shop-pay-iframe-content{height:100%}.credit-card-iframe-container{position:relative;height:100%;left:0;width:0px;transition:width .35s cubic-bezier(.33,0,0,1) .2s;visibility:hidden;opacity:0}shop-pay-iframe-content,.credit-card-iframe-container>iframe.credit-card-iframe{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.credit-card-iframe-visible{width:72px;opacity:1;visibility:visible}.credit-card-iframe{position:absolute;top:0;left:0;object-position:left top;object-fit:none;height:100%;width:80px}",cu='.accelerated-checkout-button{height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 44px),55px);min-height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 44px),55px);border-radius:var(--shopify-accelerated-checkout-button-border-radius, 0px);box-shadow:var(--shopify-accelerated-checkout-button-box-shadow)}:host([page-type="cart_page"]) .accelerated-checkout-button{height:100%;width:100%;border-radius:var(--shopify-accelerated-checkout-button-border-radius, 4px);box-shadow:var(--shopify-accelerated-checkout-button-box-shadow)}:host([page-type="product"]) .accelerated-checkout-button{min-width:150px}@media (forced-colors: active){.accelerated-checkout-button{border:1px solid transparent!important}:host([page-type="cart_page"]) .accelerated-checkout-button{border:1px solid transparent!important}}.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 $a extends Error{constructor(){const e="DeliveryEstimatesResponseIsNullError";super("deliveryEstimates is null or undefined"),this.name=e}}class nr extends Error{constructor(){const e="DeliveryPromiseAPIClientError";super("window.Shopify.ShopPromise.deliveryPromiseAPIClient is undefined"),this.name=e}}const du=15,uu=200;class hu{constructor(e){d(this,"storefrontAPIToken"),this.storefrontAPIToken=e}async fetchDeliveryPromise({variant:e,postalCode:r,defaultPostalCode:n,sellingPlanId:a}){const i=await Ga({fn:async()=>this.fetchDeliveryOptions(e,r,n,a),maxRetries:du,delay:uu,retryPolicyFn:o=>o instanceof nr}).catch(o=>{if(o instanceof nr)throw o;return null});if(!i)throw new $a;return i}async fetchDeliveryOptions(e,r,n,a){var i,o;const s={variantId:e,sellingPlanId:a,postalCode:r||n,isPostalCodeOverride:!!r},l=(o=(i=window==null?void 0:window.Shopify)==null?void 0:i.ShopPromise)==null?void 0:o.deliveryPromiseAPIClient;if(!l)throw new nr;return l(s,this.storefrontAPIToken)}}function pu(t,e){switch(t){case 0:return(e==null?void 0:e.translate("shop_promise_delivery.same_day"))||null;case 1:return(e==null?void 0:e.translate("shop_promise_delivery.next_day"))||null;case 2:return(e==null?void 0:e.translate("shop_promise_delivery.two_day"))||null;default:return null}}const mu="delivery_promise_default_address",yu="delivery_promise_postal_code";class gu extends Pt{constructor(){super(...arguments),d(this,"lastFetchedProductVariantId"),d(this,"lastFetchSellingPlan"),d(this,"fetching",!1),d(this,"i18n",null),d(this,"daysToDelivery"),d(this,"formObserver",null)}async connectedCallback(){this.formObserver=new Mr(this,({variantId:e,sellingPlanId:r})=>{this.fetchDeliveryPromise(e,r)}),this.formObserver.setupMutationObservers()}setTranslations(e){this.i18n=e,this.render()}get postalCode(){try{return JSON.parse(ut(yu)||"null")||null}catch(e){return null}}get defaultDeliveryAddress(){try{return JSON.parse(ut(mu)||"null")}catch(e){return null}}async fetchDeliveryPromise(e,r){var n,a,i,o;if(!(!e||!this.accessToken)&&!(e===this.lastFetchedProductVariantId&&r===this.lastFetchSellingPlan))try{this.lastFetchedProductVariantId=e,this.lastFetchSellingPlan=r;const s=((n=this.defaultDeliveryAddress)==null?void 0:n.zip)||"",l=await new hu(this.accessToken).fetchDeliveryPromise({variant:e,postalCode:this.postalCode||"",defaultPostalCode:s,sellingPlanId:r||""}),c=kr(this),u=(i=(a=l==null?void 0:l.selectedShippingOption)==null?void 0:a.brandedPromise)==null?void 0:i.handle;if((c==null?void 0:c.sellingPlanId)!==r||(c==null?void 0:c.variantId)!==e||u!=="shop_promise")return;this.daysToDelivery=(o=l==null?void 0:l.selectedShippingOption)==null?void 0:o.maxCalendarDaysToDelivery,this.render()}catch(s){s instanceof $a&&(this.daysToDelivery=null)}}render(){const e=pu(this.daysToDelivery,this.i18n);this.classList.add("ShopPromise"),this.innerHTML=e?'| '.concat(e," "):""}}function fu({flow:t="default"}){const e=new URLSearchParams({target_origin:window.location.origin,flow:t});return"".concat(window.location.origin,"/services/login_with_shop/authorize?").concat(e.toString())}function _u(t,e,r){const n=r!=null?r:window.location.origin;if(t.origin!==n||!e)return!1;try{return t.source===e.contentWindow}catch(a){return!1}}class Eu extends Pt{constructor(){super(...arguments),d(this,"_userRecognized"),d(this,"iframe",null),d(this,"iframeContainer",null),d(this,"iframeCreationStart",null),d(this,"iframeOrigin",null),d(this,"shopLogo",null),d(this,"iframeState","hidden"),d(this,"impressionTracked",!1),d(this,"pendingAnimation",!1),d(this,"handleMessage",e=>{var r;if(_u(e,this.iframe,e.origin)&&((r=e.data)==null?void 0:r.type)==="loaded"&&(this.iframeOrigin!==e.origin&&(this.iframeOrigin=e.origin),e.data.type==="loaded")){const n=e.data.recognized===!0;if(this._userRecognized=n,this.iframeCreationStart){const a=ae()-this.iframeCreationStart,i={instrument:f.ShopPay,pageType:Sr()};S.histogram({name:R.ShopPayPersonalizedIframeLoadTime,value:a,attributes:i,unit:"ms"}),S.histogram({name:R.ShopPayPersonalizedIframeLoadTimeFromPageLoad,value:window.performance.now(),attributes:i,unit:"ms"})}if(n){this.handleRecognizedUser();return}this.handleUnrecognizedUser()}})}get userRecognized(){return this._userRecognized}async createIframe(){if(this.iframeContainer)return this.iframeContainer;const e=ae();return this.iframeCreationStart=e,this.iframeContainer=document.createElement("div"),this.iframeContainer.classList.add("credit-card-iframe-container"),this.iframeContainer.setAttribute("data-test-id","shop-pay-iframe-container"),this.iframe=document.createElement("iframe"),this.iframe.src=fu({flow:"shop_pay_button"}),this.iframe.setAttribute("scrolling","no"),this.iframe.setAttribute("frameborder","no"),this.iframe.setAttribute("loading","lazy"),this.iframe.setAttribute("allowtransparency","true"),this.iframe.setAttribute("allowfullscreen","false"),this.iframe.classList.add("credit-card-iframe"),this.iframeContainer.appendChild(this.iframe),this.iframeContainer}async connectedCallback(){const e=await this.createIframe();this.appendChild(e),this.setupMessageListener()}disconnectedCallback(){this.cleanup()}setShopLogo(e){this.shopLogo=e}setDisabled(e){this.disabled=e,e&&this.iframeState!=="personalized"&&this.hideIframe()}hasPersonalizationOccurred(){return this.iframeState==="personalized"}triggerAnimation(e){const r=this.style.display!=="none";if(!(this.disabled||this.iframeState==="personalized"||!r)){if(this.iframeState==="loaded"){this.trackButtonImpression();return}if(this.iframeState==="ready"){this.showIframe(e);return}this.pendingAnimation=!0}}stopPendingAnimation(){this.pendingAnimation=!1}resetToOriginalState(){var e;this.iframeState="hidden",this.pendingAnimation=!1,(e=this.iframeContainer)==null||e.classList.remove("credit-card-iframe-visible")}trackButtonImpression(){this.impressionTracked||(z({event:B.ShopPayButtonInView,instrumentId:f.ShopPay,eventSubtype:this.userRecognized?"personalized":"not_personalized"}),this.impressionTracked=!0)}setupMessageListener(){window.addEventListener("message",this.handleMessage)}handleRecognizedUser(){const e=this.iframeState==="hidden";e&&(this.iframeState="ready"),this.style.display!=="none"&&e&&!this.disabled&&this.pendingAnimation&&(this.pendingAnimation=!1,this.showIframe())}handleUnrecognizedUser(){this.iframeState="loaded",this.pendingAnimation&&this.trackButtonImpression(),this.cleanup()}animateIn(){this.disabled||!this.iframeContainer||this.iframeState!=="ready"||!this.shopLogo||(this.iframeContainer.classList.add("credit-card-iframe-visible"),this.sendMessageToIframe(),this.iframeState="personalized")}showIframe(e){if(this.trackButtonImpression(),!e){this.animateIn();return}const r=setTimeout(()=>{this.animateIn()},500);return()=>clearTimeout(r)}hideIframe(){var e;this.iframeState!=="hidden"&&this.iframeState!=="personalized"&&(this.iframeState="hidden",(e=this.iframeContainer)==null||e.classList.remove("credit-card-iframe-visible"))}cleanup(){var e;window.removeEventListener("message",this.handleMessage),(e=this.iframeContainer)==null||e.remove(),this.iframeContainer=null,this.iframe=null,this.iframeOrigin=null,this.shopLogo=null}sendMessageToIframe(){var e;if(!((e=this.iframe)!=null&&e.contentWindow)||!this.iframeOrigin)return;const r={timestamp:ae(),type:"animate-in"};this.iframe.contentWindow.postMessage(r,this.iframeOrigin)}}function Au(t){const e=t.querySelector(".button-content span");if(!e)return 0;const r=window.getComputedStyle(e);return parseFloat(r.fontSize)}const Ie=220;class bu{constructor({element:e,isCTA:r,onFormStateChange:n,personalized:a,shopPromiseEligible:i,shopPromiseProductPageContent:o}){d(this,"element"),d(this,"formObserver",null),d(this,"formState",{disabled:!1,variantId:void 0}),d(this,"initialWidth",null),d(this,"isCTA"),d(this,"lockedNonPersonalized",!1),d(this,"onFormStateChange"),d(this,"personalized"),d(this,"resizeObserver",null),d(this,"shopPromiseEligible"),d(this,"shopPromiseProductPageContent");var s;this.element=e,this.isCTA=r,this.onFormStateChange=n,this.personalized=a,this.shopPromiseEligible=i,this.shopPromiseProductPageContent=o,this.personalized&&(this.formObserver=new Mr(this.element,({disabled:l,variantId:c})=>{var u;this.formState={disabled:l,variantId:c},(u=this.onFormStateChange)==null||u.call(this)}),this.formObserver.setupMutationObservers(),this.resizeObserver=ve("ResizeObserver",()=>this.handleResize()),(s=this.resizeObserver)==null||s.observe(this.element))}cleanup(){var e,r,n;(r=(e=this.formObserver)==null?void 0:e.addToCartMutationObserver)==null||r.disconnect(),(n=this.resizeObserver)==null||n.disconnect()}shouldRender(){var e;if(!this.personalized)return!1;const r=(e=this.element.offsetWidth)!=null?e:0;let n=this.lockedNonPersonalized;if(this.initialWidth===null&&r>0&&(this.initialWidth=r,this.initialWidth=Ie&&r>0&&r18)return!1}return!0}get locked(){return this.lockedNonPersonalized}get soldOut(){return this.formState.disabled&&this.formState.variantId!==void 0}handleResize(){var e,r,n,a;const i=(e=this.element.offsetWidth)!=null?e:0;if(this.initialWidth===null&&i>0){this.initialWidth=i,this.initialWidth=Ie&&i>0&&i{ou(),await this.render()},this.name)}disconnectedCallback(){var e,r;(e=this.intersectionObserver)==null||e.disconnect(),this.intersectionObserver=null,(r=this.iframeRenderEligibility)==null||r.cleanup(),this.iframeRenderEligibility=null}attributeChangedCallback(e,r,n){super.attributeChangedCallback(e,r,n,this.button),e==="disabled"&&this.onDisabledChanged(n)}setupIntersectionObserver(){var e,r;if("IntersectionObserver"in window){const n=((r=(e=this.button)==null?void 0:e.offsetHeight)!=null?r:46)*-1;this.intersectionObserver=new IntersectionObserver(a=>{a.forEach(i=>{var o;i.isIntersecting&&!this.inView&&(this.inView=!0,this.onButtonInView(!0),(o=this.intersectionObserver)==null||o.unobserve(this))})},{threshold:.1,rootMargin:"".concat(n,"px")}),this.intersectionObserver.observe(this)}else this.inView=!0,this.onButtonInView()}onButtonInView(e){var r;const n=(r=this.iframeRenderEligibility)==null?void 0:r.shouldRender();if(n&&this.iframeContent){this.iframeContent.triggerAnimation(e);return}if(n){this.createAndAttachIframe();return}this.impressionTracked||(z({event:B.ShopPayButtonInView,instrumentId:f.ShopPay,eventSubtype:"not_personalized"}),this.impressionTracked=!0)}onDisabledChanged(e){var r;(r=this.iframeContent)==null||r.setDisabled(e!==null)}async addButtonContent(){if(!this.button)return;let e;const r=await this.i18n,n=pt({instrumentName:f.ShopPay}),a=new DOMParser().parseFromString(n,"image/svg+xml").documentElement;this.shopLogo=a,this.isCTA?e=Ur({translate:r.translate,logoElement:a,setAriaHidden:!1}):(e=document.createElement("div"),e.appendChild(a)),e.classList.add("button-content"),this.shopPromiseEligible&&!this.shopPromiseProductPageContent&&(this.shopPromiseProductPageContent=document.createElement("shop-promise-product-page-content"),this.shopPromiseProductPageContent.setTranslations(r),this.shopPromiseProductPageContent.setAttribute("access-token",this.accessToken||""),e.appendChild(this.shopPromiseProductPageContent));const i=this.getAttribute("personalized")==="true",o=()=>{const s=this.iframeContent,l=this.iframeRenderEligibility,c=(l==null?void 0:l.shouldRender())||!1;if(!s){c&&this.createAndAttachIframe();return}if(!c){if(s.hasPersonalizationOccurred()&&l!=null&&l.soldOut&&!(l!=null&&l.locked)){s.style.display="";return}s.style.display="none",l!=null&&l.locked?s.resetToOriginalState():s.stopPendingAnimation();return}s.style.display="",this.inView&&s.triggerAnimation()};this.iframeRenderEligibility=new bu({element:this.button,isCTA:this.isCTA,onFormStateChange:o,personalized:i,shopPromiseEligible:this.shopPromiseEligible,shopPromiseProductPageContent:this.shopPromiseProductPageContent}),this.buttonContentDiv=e,this.button.appendChild(e)}createAndAttachIframe(){!this.buttonContentDiv||this.iframeContent||(this.iframeContent=document.createElement("shop-pay-iframe-content"),this.iframeContent.setShopLogo(this.shopLogo),this.iframeContent.setDisabled(this.disabled),this.shopLogo.insertAdjacentElement("afterend",this.iframeContent),this.inView&&this.iframeContent.triggerAnimation())}handleIframeRenderLogic(){if(!this.iframeRenderEligibility)return;const e=this.iframeRenderEligibility.shouldRender();if(!this.iframeContent&&e){this.createAndAttachIframe();return}this.iframeContent&&(this.iframeContent.style.display=e?"":"none",e&&this.inView?this.iframeContent.triggerAnimation():e||this.iframeContent.stopPendingAnimation())}getShopPayBehavior(){return this.pageType===C.ProductPage?"force_shop_pay_product":this.pageType===C.CartPage?"force_shop_pay_cart":"force_shop_pay"}async handleClick(e){var r,n;if(e.preventDefault(),this.disabled||!this.button||this.button.getAttribute("disabled"))return;this.disabled=!0;const[a,i]=await Promise.all([this.i18n,this.dataSource]);try{const{decelerationReason:o,cart:s,customValidationError:l,unrecoverableError:c}=await Ee({element:this,instrumentName:f.ShopPay,dataSource:i});if(c){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),p.log({body:"Unrecoverable error detected in Shop Pay Button click",attributes:{pageType:this.pageType,error:c}}),ke(a,c);return}if(l){p.log({body:"Custom validation error detected in Shop Pay Button click",attributes:{pageType:this.pageType,errorCode:l.code,errorMessage:l.message}}),p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),Oe(a,l.message);return}if(o){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),F({checkoutUrl:(r=s==null?void 0:s.checkoutUrl)!=null?r:"",instrumentName:this.name,reason:o});return}p.sheetClicked({instrument:this.name,result:"success"}),fe((n=s==null?void 0:s.checkoutUrl)!=null?n:"",this.getShopPayBehavior())}catch(o){E.notify(new wu("An error occurred when attempting to create a cart using the Shop Pay Button. Details: ".concat(o),{cause:o})),p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in Shop Pay sheet clicked",attributes:{error:String(o),location:"handleClick"}}),je(a)}}async render(){const e=this.getOrCreateShadowRoot();if(e.innerHTML)return;this.button||(this.button=document.createElement("gravity-button"));const r=document.createElement("style");r.innerHTML=[cu,lu].join("\n"),e.appendChild(r),await this.addButtonContent(),this.disabled&&this.button.setAttribute("disabled",""),this.button.classList.add(Le.BUTTON),this.button.onclick=n=>this.handleClick(n),e.appendChild(this.button),this.ensureLightDOMIsNotEmpty(),this.handleIframeRenderLogic(),this.onRendered()}}ce("shop-promise-product-page-content",gu),ce("shop-pay-iframe-content",Eu);class wu extends Error{constructor(){super(...arguments),d(this,"name","ShopPayButtonError")}}var Su=Object.defineProperty,Iu=Object.getOwnPropertyDescriptor,Cu=(t,e,r,n)=>{for(var a=Iu(e,r),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,r,a)||a);return a&&Su(e,r,a),a};class Va extends be{static walletName(){return"shop_pay"}constructor(e){super(e)}getWebComponentName(){return"shop-pay-wallet-button"}getWebComponentClass(){return Pu}getInstrumentName(){return f.ShopPay}async createWebComponent(e){var r;const n=await super.createWebComponent(e);return(r=this.walletParams)!=null&&r.personalized&&n.setAttribute("personalized","true"),n}async loadWalletSDK(){await this.loadLogo()}getLoadEligibility(){return{eligible:!0}}async loadLogo(){await Ke({svg:"shop-logo.svg",instrumentName:f.ShopPay})}}Cu([Br("Shop Pay")],Va.prototype,"getLoadEligibility");const Du=".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}.button:focus-visible{box-shadow:inset 0 0 0 2px #1773b0,inset 0 0 0 3px #f8f8f8!important;outline:none}.logo-only>svg{width:50px}.dark{background:#000;color:#fff}.light{background:#fff;color:#000;outline:1px solid #3c4043}@media (forced-colors: active){.light{outline:none}}@media (prefers-contrast: high),(forced-colors: active){.button:focus-visible{outline:.2rem solid;outline-offset:.1rem}}.content{display:flex;justify-content:center;align-items:center;white-space:pre}";function ar({cart:t,i18n:e}){var r,n,a,i;const o=wa(t),s={label:e.translate("order_summary.subtotal"),type:"SUBTOTAL",price:Te(o.amount)},l=ba({deliveryGroups:t.deliveryGroups,i18n:e}).map(m=>Ru({lineItem:m,type:"LINE_ITEM"})),c=Tu(t,e),u=[s,...l,...c];if(t.totalDutyAmount){const m={label:e.translate("order_summary.duties"),type:"LINE_ITEM",price:Te(t.totalDutyAmount.amount)};u.push(m)}if(t.totalTaxAmount){const m={label:e.translate("order_summary.taxes"),type:"TAX",price:Te(t.totalTaxAmount.amount)};u.push(m)}let h;try{const m=(i=(a=(n=(r=window.ShopifyAnalytics)==null?void 0:r.lib)==null?void 0:n.trekkie)==null?void 0:a.defaultAttributes)==null?void 0:i.microSessionId;h=m?"pw-".concat(m):void 0}catch(m){}const g={totalPrice:t.totalAmount.amount,currencyCode:t.totalAmount.currencyCode,totalPriceStatus:"ESTIMATED",totalPriceLabel:e.translate("order_summary.total"),displayItems:u};return h&&(g.transactionId=h),g}function Ru({lineItem:t,type:e,status:r="FINAL"}){return{label:t.label,type:e,price:t.amount,status:r}}function Tu(t,e){return[...t.lineItems.flatMap(r=>r.discountAllocations),...t.discountAllocations].flatMap(r=>{var n;const a=(n=r.title)!=null?n:r.code;return{label:a!=null?a:e.translate("order_summary.discount"),type:"LINE_ITEM",price:"-".concat(Te(Number(r.discountedAmount.amount)))}})}const Wa=["PAYMENT_AUTHORIZATION"],Nu=Wa.concat(["SHIPPING_ADDRESS","SHIPPING_OPTION"]),vu=["PAN_ONLY"];function Lu({walletParams:t,isShippingRequired:e,hasSellingPlan:r,i18n:n,buyerCurrency:a,authJwt:i}){var o,s,l,c;let u;try{const m=(c=(l=(s=(o=window.ShopifyAnalytics)==null?void 0:o.lib)==null?void 0:s.trekkie)==null?void 0:l.defaultAttributes)==null?void 0:c.microSessionId;u=m?"pw-".concat(m):void 0}catch(m){}const h={totalPrice:"0.01",currencyCode:a,totalPriceStatus:"ESTIMATED",totalPriceLabel:n.translate("order_summary.total"),displayItems:[{label:n.translate("order_summary.subtotal"),type:"SUBTOTAL",price:"0.01"}]};u&&(h.transactionId=u);const g={...t.paymentData,shippingAddressRequired:e,shippingOptionRequired:e,transactionInfo:h};return g.merchantInfo.authJwt=i,e||delete g.shippingAddressParameters,g.callbackIntents=e?Nu:Wa,r&&Ou(g),g}function Ou(t){t.allowedPaymentMethods.forEach(e=>{e.parameters.allowedAuthMethods=e.parameters.allowedAuthMethods.filter(r=>vu.includes(r))})}class ku extends Pa{constructor(e){super(),d(this,"brandName"),d(this,"completionResult"),this.i18n=e,this.brandName=this.i18n.translate("brand.google_pay"),this.completionResult=void 0}mapMutationResultToPaymentSheetAction({result:e,checkoutUrl:r,requestType:n}){const a=this.mapCustomValidationFunctionErrorToAction(e.errors);if(a)return a;const i=this.getErrorActions({checkoutUrl:r,requestType:n}),o=e.errors,s=this.getUnhandledErrors(o,i);s.forEach(c=>{E.notify(new Lt("[".concat(f.GooglePay,"] mutation result error not handled: ").concat(c),{groupingHash:"UnhandledActionError:".concat(f.GooglePay,":").concat(c)}))});const{firstPaymentSheetAction:l}=this.getMergedPaymentSheetAction({result:e,errorActions:i});return l||(s.length>0?{action:"abort"}:{action:"update",errors:[]})}mapCompletionResultToPaymentSheetAction({result:e,checkoutUrl:r,requestType:n}){if(!e.data)throw new Qn(f.GooglePay);switch(this.completionResult=e,e.data.__typename){case"SubmitSuccess":return{action:"complete",redirectUrl:e.data.redirectUrl};case"SubmitAlreadyAccepted":case"SubmitThrottled":case"SubmitFailed":{const a=this.mapCustomValidationFunctionErrorToAction(e.errors);if(a)return a;const i=this.getErrorActions({checkoutUrl:r,requestType:n}),o=e.errors;this.getUnhandledErrors(o,i).forEach(l=>{E.notify(new Lt("[".concat(f.GooglePay,"] completion result error not handled: ").concat(l),{groupingHash:"UnhandledActionError:".concat(f.GooglePay,":").concat(l)}))});const{prioritizedPaymentSheetAction:s}=this.getMergedPaymentSheetAction({result:e,errorActions:i});return s||(ie(this.brandName,this.i18n),{action:"abort"})}default:throw new Error("[".concat(f.GooglePay,"] unknown completion result type: ").concat(e.data.__typename))}}getErrorActions({checkoutUrl:e,requestType:r}){return[{errors:[y.CaptchaCompletionRequired],generateAction:()=>this.decelerateOrAbort({reason:"captcha_required",instrumentName:f.GooglePay,errorOrWarning:y.CaptchaCompletionRequired,checkoutUrl:e,requestType:r})},{errors:[y.InvalidLanguage],generateAction:()=>this.decelerateOrAbort({reason:"invalid_language",instrumentName:f.GooglePay,errorOrWarning:y.InvalidLanguage,checkoutUrl:e,requestType:r})},{errors:[y.InvalidCountry],generateAction:()=>this.decelerateOrAbort({reason:"invalid_country",instrumentName:f.GooglePay,errorOrWarning:y.InvalidCountry,checkoutUrl:e,requestType:r})},{errors:[y.MissingCartId],generateAction:()=>this.decelerateOrAbort({reason:"missing_cart_id",instrumentName:f.GooglePay,errorOrWarning:y.MissingCartId,checkoutUrl:e,requestType:r})},{errors:[y.RedirectToCheckoutRequired],generateAction:()=>this.decelerateOrAbort({reason:"redirect_to_checkout_required",instrumentName:f.GooglePay,errorOrWarning:y.RedirectToCheckoutRequired,checkoutUrl:e,requestType:r})},{errors:Rr,generateAction:()=>this.decelerateOrAbort({reason:"dynamic_tax",instrumentName:f.GooglePay,errorOrWarning:y.NewTaxMustBeAccepted,checkoutUrl:e,requestType:r})},{errors:[y.UnsupportedGooglePayPaymentMethod],generateAction:()=>this.decelerateOrAbort({reason:"unsupported_google_pay_payment_method",instrumentName:f.GooglePay,errorOrWarning:y.UnsupportedGooglePayPaymentMethod,checkoutUrl:e,requestType:r})},{errors:ca,generateAction:()=>this.decelerateOrAbort({reason:"invalid_payment_amount",instrumentName:f.GooglePay,errorOrWarning:y.InvalidPaymentAmount,checkoutUrl:e,requestType:r})},{errors:jl,generateAction:()=>({action:"abort",effects:[()=>ie(this.brandName,this.i18n)]})},{errors:cl,generateAction:()=>({action:"abort",effects:[()=>ge(this.i18n)]})},{errors:da,generateAction:()=>this.decelerateOrAbort({reason:"not_enough_stock",instrumentName:f.GooglePay,errorOrWarning:y.MerchandiseNotEnoughStock,checkoutUrl:e,requestType:r})},{errors:la,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.shipping_address")}]})},{errors:sa,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[y.NoDeliveryGroupSelected],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_OPTION_INVALID",intent:"SHIPPING_OPTION",message:this.i18n.translate("errors.missing.shipping_option")}]})},{errors:Gl,generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.email")}]})},{errors:[y.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.email")}]})},{errors:Vl,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address2")}]})},{errors:[y.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address2")}]})},{errors:Wl,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.city")}]})},{errors:[y.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.city")}]})},{errors:[y.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.zone")}]})},{errors:[y.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.zone")}]})},{errors:Yl,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:Hl,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[y.DeliveryPhoneNumberRequired],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.phone_number")}]})},{errors:zl,generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.phone_number")}]})},{errors:$l,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.country")}]})},{errors:[y.DeliveryFirstNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.first_name")}]})},{errors:[y.DeliveryFirstNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.first_name")}]})},{errors:[y.DeliveryLastNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.last_name")}]})},{errors:[y.DeliveryLastNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.last_name")}]})},{errors:[y.DeliveryAddress1Required],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address1")}]})},{errors:[y.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address1")}]})},{errors:[y.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.last_name")}]})},{errors:[y.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.city")}]})},{errors:[y.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address1")}]})},{errors:[y.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address2")}]})},{errors:[y.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.postal_code")}]})},{errors:[y.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address1")}]})},{errors:[y.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address2")}]})},{errors:[y.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.first_name")}]})},{errors:[y.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.last_name")}]})},{errors:[y.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.city")}]})},{errors:[y.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.first_name")}]})},{errors:[y.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.last_name")}]})},{errors:[y.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address1")}]})},{errors:[y.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address2")}]})},{errors:[y.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.city")}]})},{errors:[y.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.first_name")}]})},{errors:[y.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.last_name")}]})},{errors:[y.InvalidPaymentGooglePayBillingAddress],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.billing_address")}]})},{errors:[y.LocalizationExtensionFieldError],generateAction:()=>this.decelerateOrAbort({reason:"localization_extension_field_error",instrumentName:f.GooglePay,errorOrWarning:y.LocalizationExtensionFieldError,checkoutUrl:e,requestType:r})},{errors:Il,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.first_name")}]})},{errors:Cl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.last_name")}]})},{errors:Dl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.address1")}]})},{errors:Rl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.address2")}]})},{errors:Tl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.city")}]})},{errors:Nl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.phone")}]})},{errors:vl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:sl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:Ll,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.zone")}]})},{errors:[y.GooglePayBillingFirstNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.emojis.first_name")}]})},{errors:[y.GooglePayBillingFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.html_tags.first_name")}]})},{errors:Ol,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.first_name")}]})},{errors:[y.GooglePayBillingLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.emojis.last_name")}]})},{errors:[y.GooglePayBillingLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.html_tags.last_name")}]})},{errors:kl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.last_name")}]})},{errors:[y.GooglePayBillingAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.emojis.address1")}]})},{errors:[y.GooglePayBillingAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.html_tags.address1")}]})},{errors:Ml,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.address1")}]})},{errors:[y.GooglePayBillingAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.emojis.address2")}]})},{errors:[y.GooglePayBillingAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.html_tags.address2")}]})},{errors:xl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.address2")}]})},{errors:[y.GooglePayBillingCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.emojis.city")}]})},{errors:[y.GooglePayBillingCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.html_tags.city")}]})},{errors:Fl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.city")}]})},{errors:[y.GooglePayBillingPhoneContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.emojis.phone")}]})},{errors:Ul,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.phone")}]})},{errors:[y.GooglePayBillingZipContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.emojis.postal_code")}]})},{errors:Bl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.postal_code")}]})}]}mapCustomValidationFunctionErrorToAction(e){const r=Ir(e);return r?(E.notify(new Error("[".concat(f.GooglePay,"] custom validation function error: ").concat(JSON.stringify(e)))),Cr(this.i18n.translate("error_dialogs.wallet.title",{wallet:this.brandName}),r.message),{action:"abort"}):null}}function Mu({deliveryGroups:t,i18n:e}){var r;const n=Fc(Ea({deliveryGroups:t}),e),a=n.map(({handle:o,title:s,description:l})=>({id:o,label:s!=null?s:"",description:l})),i=(r=n.find(o=>{var s;return o.handle.includes(((s=t[0].selectedDeliveryOption)==null?void 0:s.handle)||"")}))==null?void 0:r.handle;return{shippingOptions:a,defaultSelectedOptionId:i}}function ir(t){let e=t.administrativeArea,r=t.locality;t.countryCode==="AE"&&(r=t.administrativeArea,t.administrativeArea in bn&&(e=bn[t.administrativeArea])),t.countryCode==="MX"&&e&&(e=xu(e));let n,a;if(t.name){const[i,...o]=(t.name||"").split(" ");o.length===0?a=i:a=o.join(" "),n=i}return{firstName:n,lastName:a,address1:t.address1,address2:t.address2,city:r,province:e,country:t.countryCode,phone:t.phoneNumber,zip:t.postalCode}}const bn={"\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","\u0625\u0645\u0627\u0631\u0629 \u0631\u0623\u0633 \u0627\u0644\u062E\u064A\u0645\u0629":"RK","\u0623\u0645 \u0627\u0644\u0642\u064A\u0648\u064A\u0646":"UQ","\u0627\u0645 \u0627\u0644\u0642\u064A\u0648\u064A\u0646":"UQ",\u062F\u0628\u064A:"DU","\u0625\u0645\u0627\u0631\u0629 \u062F\u0628\u064A\u0651":"DU"},xu=t=>t==="M\xE9x."?"MEX":t==="Q.R."?"Q ROO":t.replace(/\./g,"").toUpperCase();class Pn extends Error{constructor(){super(...arguments),d(this,"name","GooglePayError")}}function Ya(t){const e=t.auth;if(!(Array.isArray(e)&&e.length>0))return{result:"error",reason:"invalidAuthParams"};const r=ae();for(const n of e)if(r{var m,b;const{callbackTrigger:_,shippingAddress:A,shippingOptionData:v}=g,{translate:$}=this.i18n;switch(E.leaveBreadcrumb("Google Pay onPaymentDataChanged",{callbackTrigger:_},"log"),_){case"INITIALIZE":{if(!this.cart)try{const{cart:U,customValidationError:L,decelerationReason:q,unrecoverableError:P}=await Ee({element:this.button,instrumentName:f.GooglePay,dataSource:this.dataSource});if(L||P)return p.sheetClicked({instrument:this.name,result:"rejected",reason:L?"custom_validation_error":"unrecoverable_error"}),this.terminalCartCreationError=L?L.message:Hu(this.i18n,P),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:this.terminalCartCreationError,intent:"SHIPPING_ADDRESS"}});if(q)return p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),F({checkoutUrl:(m=U==null?void 0:U.checkoutUrl)!=null?m:"",instrumentName:this.name,reason:q}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:""}});this.cart=U,p.sheetClicked({instrument:this.name,result:"success"})}catch(U){return p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in Google Pay sheet clicked",attributes:{error:String(U),location:"onPaymentDataChanged_INITIALIZE"}}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}let I=!1;if(A)try{return await this.handleShippingAddressChange(this.cart.id,A)}catch(U){I=!0}return{newTransactionInfo:ar({cart:this.cart,i18n:this.i18n}),...I?this.showPaymentDataRequestError():{}}}case"SHIPPING_ADDRESS":return this.terminalCartCreationError?this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:this.terminalCartCreationError,intent:"SHIPPING_ADDRESS"}}):this.cart?A?this.handleShippingAddressChange(this.cart.id,A):{newTransactionInfo:ar({cart:this.cart,i18n:this.i18n})}:this.showPaymentDataRequestError({intent:_});case"SHIPPING_OPTION":{if(!this.cart)return this.showPaymentDataRequestError({intent:_});if(!v||!v.id)return{error:{reason:"SHIPPING_OPTION_INVALID",message:$("shipping_methods.choose_delivery_strategy"),intent:"SHIPPING_OPTION"}};const I=await this.handleDeliveryOptionChange(v.id.split(","));return I.data?(this.cart=I.data,I.abortReason==="out_of_stock"?this.showPaymentDataRequestError({error:{intent:"SHIPPING_OPTION",reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.product.out_of_stock")}}):I.decelerationReason?(F({checkoutUrl:(b=this.cart.checkoutUrl)!=null?b:"",instrumentName:this.name,reason:I.decelerationReason}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_OPTION",reason:"OTHER_ERROR",message:""}})):this.handlePaymentDataRequestUpdate({result:I,intent:_,checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentDataChanged::updateCartDeliveryOptions"})):this.showPaymentDataRequestError({intent:_})}default:return this.logException("Payment data changed callback returned unexpected intent: ".concat(_),{severity:"warning"}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}}),d(this,"onPaymentAuthorized",async g=>{var m,b,_;if(p.authorizationAttempt(this.name),Xe(O.AuthorizationLatency,this.name),!this.cart)return p.googlePayNullCartOnAuthorize(),this.handlePaymentAuthorizationError();const A=(m=g.paymentMethodData.info)==null?void 0:m.billingAddress,v=g.shippingAddress,{signature:$,signedMessage:I,protocolVersion:U}=JSON.parse(g.paymentMethodData.tokenizationData.token);if(!A)return this.handlePaymentAuthorizationError({error:{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_AUTHORIZATION",message:this.i18n.translate("errors.invalid.billing_address")}});if(this.isShippingRequired&&!v)return this.handlePaymentAuthorizationError({error:{reason:"SHIPPING_ADDRESS_INVALID",intent:"PAYMENT_AUTHORIZATION",message:this.i18n.translate("errors.invalid.shipping_address")}});const L=async()=>{var H,X;const se=(H=w(this,ft))!=null?H:g.email,vh=this.isShippingRequired?{validateAddress:!0,streetAddress:ir(v)}:{};return await Ge({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:this.name,emailAddress:se,abortSignal:(X=w(this,ne))==null?void 0:X.signal,...vh})},q=async()=>{var H;const X=ir(A);return await xr({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{googlePayWalletContent:{billingAddress:X,signature:$,signedMessage:I,protocolVersion:U}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:X,cartClient:this.cartClient,instrumentName:this.name,hasSellingPlan:this.hasSellingPlan,abortSignal:(H=w(this,ne))==null?void 0:H.signal})},P=setTimeout(()=>{var H;(H=w(this,ne))==null||H.abort("[Google Pay] Timeout")},Fu);try{const H=await L(),X=this.handleIntermediatePaymentAuthorizationResult({result:H,checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updateBuyerIdentity"});if(X)return X;const se=await q(),vh=this.handleIntermediatePaymentAuthorizationResult({result:se,checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updateCartPayment"});if(vh)return vh;if(clearTimeout(P),(_=(b=w(this,ne))==null?void 0:b.signal)!=null&&_.aborted)return this.handlePaymentAuthorizationError();const Bn=await Fa({cartId:this.cart.id,token:$,cartClient:this.cartClient,instrumentName:this.name});ct({result:Bn,instrument:this.name});const xh=this.actionGenerator.mapCompletionResultToPaymentSheetAction({result:Bn,checkoutUrl:Bn.data&&"checkoutUrl"in Bn.data&&Bn.data.checkoutUrl?Bn.data.checkoutUrl:this.cart.checkoutUrl,requestType:"completion"});return this.handlePaymentAuthorizationResult(xh)}catch(H){clearTimeout(P);const{message:X}=H;return X!=null&&X.includes(Uu)?this.handlePaymentAuthorizationError({status:"timeout"}):(H instanceof ht||this.logException(X),this.handlePaymentAuthorizationError())}}),d(this,"handlePaymentAuthorizationResult",async g=>{var m,b;switch((m=g.effects)==null||m.forEach(_=>_()),g.action){case"complete":return this.emitAuthorizationCompleteMetric("success"),fe(g.redirectUrl),{transactionState:"SUCCESS"};case"show_error":return this.handlePaymentAuthorizationError({error:(b=g.errors)==null?void 0:b[0]});case"decelerate":return F({checkoutUrl:g.redirectUrl,instrumentName:this.name,reason:g.reason}),this.emitAuthorizationCompleteMetric("failed"),{transactionState:"SUCCESS"};case"abort":default:return this.emitAuthorizationCompleteMetric("failed"),{transactionState:"SUCCESS"}}}),this.walletParams=e,this.isShippingRequired=r,this.hasSellingPlan=n,this.dataSource=a,this.button=i,this.i18n=o,this.cartClient=s,this.initialBuyerCurrency=l,M(this,ft,e.customerAccountEmail),M(this,ne,c);const u=Ya(this.walletParams);if(u.result==="error")throw E.leaveBreadcrumb("Google Pay Invalid AuthJwt detected on click",{reason:u.reason,walletParams:this.walletParams},"error"),new Pn(u.reason);M(this,We,u.jwt);const h={environment:this.walletParams.environment,merchantInfo:{...this.walletParams.paymentData.merchantInfo,authJwt:w(this,We)},paymentDataCallbacks:{onPaymentDataChanged:this.isShippingRequired?this.onPaymentDataChanged:void 0,onPaymentAuthorized:this.onPaymentAuthorized}};this.paymentsClient=new window.google.payments.api.PaymentsClient(h),this.actionGenerator=new ku(this.i18n)}async handleClick(){if(!this.isShippingRequired)throw new ee("Google Pay checkout started for digital cart");const e=Lu({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,i18n:this.i18n,buyerCurrency:this.initialBuyerCurrency,authJwt:w(this,We)});E.leaveBreadcrumb("Google Pay handleClick",{paymentDataRequest:e},"log"),await this.paymentsClient.loadPaymentData(e)}showPaymentDataRequestError({error:e,intent:r="SHIPPING_ADDRESS"}={}){return e?{error:e}:{error:{intent:r,reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.wallet.generic_error",{wallet:this.i18n.translate("brand.google_pay")})}}}handlePaymentAuthorizationError({error:e,status:r="failed"}={}){return this.emitAuthorizationCompleteMetric(r),{transactionState:"ERROR",...this.showPaymentDataRequestError({error:e,intent:"PAYMENT_AUTHORIZATION"})}}handlePaymentDataRequestUpdate({result:e,intent:r,checkoutUrl:n,requestType:a}){var i,o,s;const l=this.actionGenerator.mapMutationResultToPaymentSheetAction({result:e,checkoutUrl:n,requestType:a});switch((i=l.effects)==null||i.forEach(c=>c()),l.action){case"update":{const c=l,{data:u,decelerationReason:h}=e;return u?h?(F({checkoutUrl:u.checkoutUrl,instrumentName:this.name,reason:h}),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:"",intent:"OFFER"}})):this.isShippingRequired&&u.deliveryGroups.length===0?this.showPaymentDataRequestError({error:{reason:"SHIPPING_ADDRESS_INVALID",message:this.i18n.translate("errors.address_unserviceable",{shopName:this.walletParams.paymentData.merchantInfo.merchantName}),intent:"SHIPPING_ADDRESS"}}):{newTransactionInfo:ar({cart:u,i18n:this.i18n}),newShippingOptionParameters:this.isShippingRequired?Mu({deliveryGroups:u.deliveryGroups,i18n:this.i18n}):void 0,error:(o=c.errors)==null?void 0:o[0]}:this.showPaymentDataRequestError({intent:r})}case"show_error":return{error:(s=l.errors)==null?void 0:s[0]};case"decelerate":return F({checkoutUrl:l.redirectUrl,instrumentName:this.name,reason:l.reason}),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:"",intent:"OFFER"}});case"abort":return this.showPaymentDataRequestError({intent:r});default:return this.logException("Payment sheet update returned unexpected action (see request tab for details)",{metadata:{request:{action:l.action,intent:r}}}),this.showPaymentDataRequestError({intent:r})}}handleIntermediatePaymentAuthorizationResult({result:e,checkoutUrl:r,requestType:n}){var a,i,o,s,l;if(ct({result:e,instrument:this.name}),e.abortReason==="out_of_stock")return ge(this.i18n),{transactionState:"SUCCESS"};if(e.decelerationReason)return F({checkoutUrl:(i=(a=e.data)==null?void 0:a.checkoutUrl)!=null?i:"",instrumentName:this.name,reason:e.decelerationReason}),{transactionState:"SUCCESS"};const c=this.actionGenerator.mapMutationResultToPaymentSheetAction({result:e,checkoutUrl:r,requestType:n});switch((o=c.effects)==null||o.forEach(u=>u()),c.action){case"show_error":return this.handlePaymentAuthorizationError({error:(s=c.errors)==null?void 0:s[0]});case"abort":return this.handlePaymentAuthorizationError({error:(l=c.errors)==null?void 0:l.at(0)});case"decelerate":return this.emitAuthorizationCompleteMetric("success"),F({checkoutUrl:c.redirectUrl,instrumentName:this.name,reason:c.reason}),{transactionState:"SUCCESS"};default:return}}handleCurrencyChange(e,r){Nr({currentCartTotal:r,initialBuyerCurrency:this.initialBuyerCurrency})&&F({checkoutUrl:e,instrumentName:this.name,reason:"currency_changed"})}async handleShippingAddressChange(e,r){var n,a;let i=await Ge({cartClient:this.cartClient,cartId:e,streetAddress:r?ir(r):{},instrumentName:f.GooglePay,abortSignal:(n=w(this,ne))==null?void 0:n.signal});if(!i.data)return this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"});if(this.cart=i.data,i.abortReason==="out_of_stock")return this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.product.out_of_stock")}});if(i.decelerationReason)return F({checkoutUrl:(a=this.cart.checkoutUrl)!=null?a:"",instrumentName:this.name,reason:i.decelerationReason}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:""}});const o=this.cart.deliveryGroups.map(({selectedDeliveryOption:s,deliveryOptions:l})=>{var c;return s!=null&&s.handle&&s.deliveryMethodType!=="LOCAL"?s.handle:(c=l.filter(({deliveryMethodType:u})=>u==="SHIPPING")[0])==null?void 0:c.handle}).filter(Boolean);if(o.length>0){if(i=await this.handleDeliveryOptionChange(o),!i.data)return this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"});this.cart=i.data}return this.handleCurrencyChange(this.cart.checkoutUrl,this.cart.totalAmount),this.handlePaymentDataRequestUpdate({result:i,intent:"SHIPPING_ADDRESS",checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentDataChanged::updateBuyerIdentity"})}async handleDeliveryOptionChange(e){var r;const n=Ua({deliveryGroups:this.cart.deliveryGroups,instrumentName:f.GooglePay,selectedDeliveryOptionHandles:e});return await xa({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:f.GooglePay,selectedDeliveryOptions:n,abortSignal:(r=w(this,ne))==null?void 0:r.signal})}logException(e,{severity:r,metadata:n}={}){E.notify(new Pn(e),{severity:r!=null?r:"error",metadata:n})}emitAuthorizationCompleteMetric(e){p.authorizationComplete({instrument:this.name,measurement:K(O.AuthorizationLatency,this.name),result:e})}}ft=new WeakMap,ne=new WeakMap,We=new WeakMap;function Hu(t,e){switch(e){case k.VariantRequiresSellingPlan:case k.SellingPlanNotApplicable:case k.InvalidQuantity:case k.MerchandiseIdInvalid:case k.IgnoredResponseError:case k.NoResponse:return t.translate("error_dialogs.checkout.generic_error");default:return t.translate("error_dialogs.checkout.generic_error")}}const Gu={LIGHT:"light",DARK:"dark"};class zu extends Ae{constructor(){super(...arguments),d(this,"name",f.GooglePay),d(this,"paymentsClient",null),d(this,"button",null),d(this,"handleClick",async()=>{if(this.disabled)return;this.disabled=!0;const e=ve("AbortController");let r=!1;try{await this.createPaymentsClient(e),r=!0,await this.paymentsClient.handleClick()}catch(n){if(this.disabled=!1,n.statusCode==="CANCELED"){e==null||e.abort("[Google Pay] Payment sheet cancelled"),p.sheetCancelled(f.GooglePay);return}e==null||e.abort("[Google Pay] Payment sheet failure"),this.expectedError(n)?p.sheetClicked({instrument:this.name,result:"failed",reason:"expected_error"}):E.notify(n),r||(p.sheetClicked({instrument:this.name,result:"failed",reason:"unhandled_error"}),p.log({body:"Unhandled error detected in Google Pay client creation",attributes:{error:String(n),location:"handleClick"}}));const a=await this.i18n,i=a.translate("brand.google_pay");ie(i,a)}})}static get observedAttributes(){return["disabled"]}attributeChangedCallback(e,r,n){super.attributeChangedCallback(e,r,n,this.button)}async connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async createPaymentsClient(e){this.paymentsClient=new Bu({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:e})}async render(){const e=this.getOrCreateShadowRoot();if(this.button)return;await this.initializeShadowStyles(e,Du);const{translate:r}=await this.i18n,n=this.isCTA?r("buy_with_button_content",{wallet:r("brand.google_pay")}):r("brand.google_pay"),a=Gt({label:n});this.disabled&&a.setAttribute("disabled",""),a.classList.add("button",Le.BUTTON,Gu[this.buttonTheme]),a.onclick=this.handleClick,await this.renderButtonContent(a,r),this.button=a,e.appendChild(a),this.ensureLightDOMIsNotEmpty(),this.onRendered()}async renderButtonContent(e,r){const n=pt({instrumentName:f.GooglePay,logoType:this.buttonTheme}),a=new DOMParser().parseFromString(n,"image/svg+xml").documentElement;if(e.style.font=window.getComputedStyle(this).font,this.isCTA){const i=Ur({translate:r,logoElement:a,setAriaHidden:!0});i.classList.add("content"),e.appendChild(i)}else e.classList.add("logo-only"),e.appendChild(a)}expectedError(e){return e==="failed to open window"}}const Ce=class Ch extends be{static walletName(){return"google_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-google-pay-button"}getInstrumentName(){return f.GooglePay}getWebComponentClass(){return zu}async loadWalletSDK(){if(Ch.googlePaySDKPromise)return Ch.googlePaySDKPromise;const e=document.createElement("script");e.setAttribute("src",this.walletParams.sdkUrl);const r=new Promise((n,a)=>{e.onload=()=>n(),e.onerror=i=>{e.remove(),a(i)},document.body.appendChild(e)});return Ch.googlePaySDKPromise=Promise.all([r,this.loadLogos()]),Ch.googlePaySDKPromise}getLoadEligibility(){const e=Ya(this.walletParams);switch(e.result){case"success":return{eligible:!0};case"error":return{eligible:!1,reason:e.reason}}}getPartnerSDKEligibility(){return{eligible:!0}}async loadLogos(){return Promise.all([this.loadGooglePayLogo(),this.loadGooglePayLogoDark()])}async loadGooglePayLogo(){await Ke({svg:"google-pay-logo.svg",instrumentName:f.GooglePay})}async loadGooglePayLogoDark(){await Ke({svg:"google-pay-logo-dark.svg",instrumentName:f.GooglePay,logoType:"DARK"})}};d(Ce,"googlePaySDKPromise");let gr=Ce;const $u=[Ac,cr,Hr,gr,pr,yr,Va],Vu=new Map($u.map(t=>[t.walletName(),e=>new t(e)]));function dt(t){if(!t)return null;const e=Vu.get(t.name);return e?e(t):(console.debug("Can't build wallet with name ".concat(t.name)),null)}function Wu(t){return t.map(e=>dt(e)).filter(e=>e!=null)}const qa="*{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 Yu{constructor(e,r,n){this.element=e,this.apiClient=r,this.instrumentName=n}async getInitialCart(e){const r=kr(this.element);if(!r)throw new qu("[".concat(this.instrumentName,"] unable to find product form"),{groupingHash:"unable-to-find-product-form"});const n=ut(fi),{data:a,errors:i,abortReason:o,decelerationReason:s}=await this.apiClient.createCart({...r,discountCodes:n?[n]:[],instrumentName:e});return{cart:a,errors:i,abortReason:o,decelerationReason:s}}}class qu extends oe{constructor(){super(...arguments),d(this,"name","ProductFormError"),d(this,"useHashPrefix",!0)}}function ju({styleId:t,styles:e,cssFileName:r}){var n,a;(a=(n=window.Shopify)==null?void 0:n.PaymentButton)!=null&&a.isStorefrontPortableWallets&&(Qu({styleId:t})||Ku({styleId:t,styles:e}))}function Qu({styleId:t}){const e=document.querySelector("style#".concat(t)),r=document.querySelector("link#".concat(t));return!!(e||r)}function Ku({styleId:t,styles:e}){const r=document.createElement("style");r.id=t,r.innerHTML=e,document.head.insertBefore(r,document.head.firstChild)}const Z={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 wn(t){let e=0,r=0,n=0;const a=t.split(/\s+/);for(let i=0;i"&&(o.includes("#")&&(e+=(o.match(/#/g)||[]).length),o.includes(".")&&(r+=(o.match(/\./g)||[]).length),o.includes("[")&&(r+=(o.match(/\[/g)||[]).length),o.includes(":")&&(r+=(o.match(/:[^:]/g)||[]).length),/^[A-Za-z]/.test(o)&&(n+=1))}return[e,r,n]}function Xu(t,e){for(let r=0;r<3;r++)if(t[r]!==e[r])return e[r]-t[r];return 0}function Sn(t){return[...t].sort((e,r)=>{const n=wn(e.selector),a=wn(r.selector);return Xu(n,a)})}const Ju=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*(>\s*)?li(?![a-zA-Z0-9_.:#-])/,Zu=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*\[role="?button"?\](?![:\w-])/,eh=/\.additional-checkout-buttons\s*(?:div\s*)?\[role="?button"?\](?![:\w-])/,ja=/\[data-shopify-buttoncontainer\](?![:\w-])/,Qa=/.dynamic-checkout-buttons .shopify-payment-button__button/,th=/(?!.*\.shopify-cleanslate)\.shopify-payment-button__button(?:--branded)?(?![\w-:.#>])/,rh=/\.(shopify-payment-button|shopify-payment-button__button|shopify-payment-button__button--branded)\s*\[role="?button"?\](?![:\w-])/,nh=/(?:only\s+)?(?:screen\s+and\s+)?\((?:min|max)-(?:width|height):\s*\d+px\)/,ah=[Zu,ja,Ju,eh,Qa],ih=[th,rh,Qa],oh=.001;function In(t){return t.split(",").map(e=>e.trim())}function Ka(t){const e=t.pageType,r=e===C.ProductPage?ih:ah,n=[...document.styleSheets].filter(sh),a=new Set;function i(L){for(const q of r){const P=L.match(q);if(P)return a.add(P[0]),!0}return!1}const o=[],s=[];n.forEach(L=>{try{for(const q of L.cssRules)if(q instanceof CSSMediaRule){const P=q;if(!nh.test(P.conditionText))continue;for(const H of P.cssRules){if(!(H instanceof CSSStyleRule))continue;const X=In(H.selectorText);for(const se of X)i(se)&&s.push({selector:se,conditionText:P.conditionText,...Nn(H)})}}else if(q instanceof CSSStyleRule){const P=q,H=In(P.selectorText);for(const X of H)i(X)&&o.push({selector:X,...Nn(P)})}}catch(q){Dt()("shopify-support-debug")&&(console.debug("[shopify-support-debug] stylesheet origin: ".concat(L.href)),console.debug(q))}});const l=Dt()("shopify-support-debug");l&&console.table(Array.from(a));const c=o.reverse(),u=s.reverse(),h=Sn(c),g=Sn(u),m={},b=Cn(e)?document.querySelector(".cart__blocks .button"):document.querySelector(".product-form__buttons .button");b&&(m.boxShadow=getComputedStyle(b,":before").boxShadow);for(const L of h){const q=["height","minHeight","borderRadius","marginTop"];Cn(e)&&L.selector.match(ja)&&q.push("justifyContent");for(const P of q)m[P]=uh({rule:L,property:P,currentPropertyValue:m[P]})}const{height:_,borderRadius:A,minHeight:v,marginTop:$,justifyContent:I,boxShadow:U}=m;return l&&console.table([{property:"height",value:_},{property:"borderRadius",value:A},{property:"minHeight",value:v},{property:"marginTop",value:$},{property:"justifyContent",value:I},{property:"boxShadow",value:U}]),e===C.ProductPage?Tn({styles:{height:_,minHeight:v,borderRadius:A,marginTop:$,boxShadow:U},mediaRules:g,element:t}):Tn({styles:{borderRadius:A,boxShadow:U,justifyContent:I},mediaRules:g,element:t})}function Xa({element:t,styles:e,debug:r=!1}){if(!e)return;ph(e,t,r);const n="global-".concat(t.tagName.toLowerCase(),"-styles");if(document.head.querySelector("style#".concat(n))==null){const a=document.createElement("style");a.id=n,a.innerHTML=e,document.head.appendChild(a)}}function sh(t){const e=t.ownerNode instanceof HTMLLinkElement&&(t.ownerNode.getAttribute("crossorigin")==="anonymous"||t.ownerNode.getAttribute("crossorigin")==="");return t.href==null||t.href.startsWith(window.location.origin)||e}function Cn(t){return t===C.CartPage||t===C.CartAjax}function Dn({height:t,minHeight:e}){let r=t,n=e;return(r!=null&&r.includes("var(".concat(Z.buttonBlockSize))||r==="auto")&&(r=null),(n!=null&&n.includes("var(".concat(Z.buttonBlockSize))||n==="auto")&&(n=null),r===n?r:n&&r?"max(".concat(r,",").concat(n,")"):r||n}function Rn({existingProperties:t,mediaCondition:e,selector:r,styles:n}){const a={...n};for(const i of t)delete a[i];for(const[i,o]of Object.entries(a))o!=null&&o.startsWith("var(".concat(i))&&delete a[i];for(const[i,o]of Object.entries(a))(o==null||o==="")&&delete a[i];return Object.keys(a).length===0?"":lh({mediaCondition:e,selector:r,styles:a})}function lh({mediaCondition:t,selector:e,styles:r}){let n="".concat(t?"@media ".concat(t," { "):"").concat(e," {");for(const[a,i]of Object.entries(r))i&&(n+="\n ".concat(a,": ").concat(i,";"));return n+="\n}",t&&(n+="}"),n+="\n",n}function Tn({styles:t,element:e,mediaRules:r}){const{height:n,minHeight:a,borderRadius:i,marginTop:o,justifyContent:s,boxShadow:l}=t,c=e.tagName.toLowerCase(),u=getComputedStyle(e),h=new Set;for(const m of Object.values(Z))u.getPropertyValue(m)&&h.add(m);let g=Rn({existingProperties:h,selector:c,styles:{[Z.buttonBlockSize]:Dn({height:n,minHeight:a}),[Z.buttonBorderRadius]:i,[Z.buttonBoxShadow]:l,[Z.inlineAlignment]:s,"margin-top":o,display:o?"block":void 0}});return r.forEach(m=>{(m.height||m.minHeight||m.borderRadius||m.boxShadow||m.justifyContent||m.marginTop)&&(g+=Rn({existingProperties:h,mediaCondition:m.conditionText,selector:c,styles:{[Z.buttonBlockSize]:Dn({height:m.height,minHeight:m.minHeight}),[Z.buttonBorderRadius]:m.borderRadius,[Z.buttonBoxShadow]:m.boxShadow,[Z.inlineAlignment]:m.justifyContent,"margin-top":m.marginTop,display:m.marginTop?"block":void 0}}))}),g.trim()}const ch=[["height"],["minHeight","min-height"],["borderRadius","border-radius"],["marginTop","margin-top"],["justifyContent","justify-content"]];function Nn(t){return ch.reduce((e,[r,n])=>(e[r]=dh({rule:t,property:n!=null?n:r}),e),{})}function dh({rule:t,property:e}){const r=t.style.getPropertyValue(e);return r!==""&&t.style.getPropertyPriority(e)?"".concat(r," !important"):r||null}function uh({rule:t,property:e,currentPropertyValue:r}){const n=t[e];return!(r!=null&&r.includes("!important"))&&n!=null&&n.includes("!important")?n:r!=null?r:n}function hh(t){const e=/(--[\w-]+)\s*:/g;let r;const n={};for(;(r=e.exec(t))!==null;){const l=r[1];n[l]=(n[l]||0)+1}const a=/@media\s+([^{]+)/g,i=(t.match(a)||[]).length,o=/margin-top\s*:/g,s=(t.match(o)||[]).length;return{properties:n,mediaQueryCount:i,marginTopCount:s}}function ph(t,e,r){var n,a,i;const o=(i=(a=(n=window.ShopifyAnalytics)==null?void 0:n.lib)==null?void 0:a.trekkie)==null?void 0:i.defaultAttributes,s=o==null?void 0:o.themeId;if(s&&(r&&p.log({body:"Style backwards compatibility used",attributes:{themeId:"".concat(s)}}),Math.random()0&&p.styleBackwardsCompatibilityRules({rule:"@media",count:l.mediaQueryCount,pageType:e.pageType}),l.marginTopCount>0&&p.styleBackwardsCompatibilityRules({rule:"margin-top",count:l.marginTopCount,pageType:e.pageType}),p.log({body:"Style backwards compatibility details",attributes:{themeId:"".concat(s),pageType:e.pageType,stylesString:t.length>2e3?t.substring(0,2e3):t}})}}const Ja="d6d12da0",vn=2e3;class Ln extends Error{constructor(){super(...arguments),d(this,"name","AcceleratedCheckoutError")}}var Ye;const Mt=class Lh extends Lr{constructor(){super(...arguments),d(this,"instanceNumber",++Lh.instanceCount),d(this,"pageType",C.ProductPage),d(this,"formObserver"),d(this,"dataSource"),d(this,"wrapper"),d(this,"shopPromiseEligible",!1),d(this,"didInitiateRender",!1),G(this,Ye)}static get observedAttributes(){return["access-token","disabled","has-selling-plan","requires-shipping"]}async connectedCallback(){var e,r;super.connectedCallback();try{if((r=(e=this.wrapper)==null?void 0:e.children)!=null&&r.length||this.didInitiateRender)return;if(!this.validateRenderingSurface()){this.clearUI();return}this.instanceNumber===1&&(Or(this),p.initStarted(),ju({styleId:"shopify-accelerated-checkout-styles",styles:cc,cssFileName:"AcceleratedCheckout.css"}),this.extractStyles()),this.shopPromiseEligible=ra();const n=Qe(O.ButtonDisplay,"dc:".concat(this.instanceNumber));this.i18n=Ht(),this.setupFormObserver(),this.didInitiateRender=!0;const a=await this.loadWallet(),i=a.getInstrumentName();this.apiClient=new Wt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,withCarrierRates:!0,cartPrepareMigrationEnabled:this.isFlagEnabled(Ja)}),this.dataSource=new Yu(this,this.apiClient,i);const o=await this.getWebComponentInstance({wallet:a,instrumentName:i,dataSource:this.dataSource,i18n:this.i18n,apiClient:this.apiClient,buttonDisplayBenchmark:n});this.render(o,i),p.initCompleted(),this.instanceNumber===1&&this.triggerLoadedEvent()}catch(n){if(this.clearUI(),p.initCompleted(n),n.name===_t)throw n;E.notify(new Ln("An error occurred while attempting to render AcceleratedCheckout: ".concat(n),{cause:n}))}}async attributeChangedCallback(e,r,n){r!==n&&(vr(this,e,n),e==="has-selling-plan"&&n===""?this.showBuyerConsent(this.apiClient,this.i18n):e==="has-selling-plan"&&n===null&&this.hideBuyerConsent())}async getWebComponentInstance({wallet:e,instrumentName:r,dataSource:n,i18n:a,apiClient:i,buttonDisplayBenchmark:o}){const s=await e.createWebComponent({walletContainer:this,dataSource:n,i18n:a,apiClient:i,classNames:mh(r),callToAction:"true",pageType:this.pageType,containerInstanceNumber:this.instanceNumber,onRendered:()=>p.instrumentLoaded({instrumentOrComponentName:r,result:"success",measurement:o()})});if(!s)throw new Ln("No web component instance found for instrument ".concat(r));return s}async render(e,r){this.clearUI();const n=this.getOrCreateShadowRoot(),a=document.createElement("style");a.innerHTML=qa,n.appendChild(a),this.wrapper=document.createElement("div"),this.wrapper.className="wallet-button-fade-in wallet-button-wrapper";const i=document.createElement("slot");i.name="button",this.wrapper.appendChild(i);const o=document.createElement("slot");o.name="promise",this.wrapper.appendChild(o);const s=document.createElement("slot");s.name="more-options",this.wrapper.appendChild(s),n==null||n.appendChild(this.wrapper),this.hasSellingPlan?this.showBuyerConsent(this.apiClient,this.i18n):this.hideBuyerConsent(),this.setupManagedMarketsHandlers(this.i18n);const l=new DocumentFragment;e&&l.appendChild(e);const c=this.getShopPromiseSlot();c&&l.appendChild(c);const u=this.getMorePaymentOptionsLink(r);u&&l.appendChild(u),this.appendChild(l)}getMorePaymentOptionsLink(e){var r,n;if(e===f.BuyItNow)return null;const a=document.createElement("more-payment-options-link");return At(a,{"buyer-country":(r=this.buyerCountry)!=null?r:"","access-token":(n=this.accessToken)!=null?n:"","recommended-instrument":e,slot:"more-options"}),a.disabled=this.disabled,a.setDataSource(this.dataSource),a.setI18n(this.i18n),a.setClassNames(or.MORE_PAYMENT_OPTION_BUTTON),a}getShopPromiseSlot(){if(!this.shopPromiseEligible)return null;const e=document.createElement("div");return e.setAttribute("data-shopify","shop-promise-payment-button-slot"),e.style.height="100%",e.slot="promise",e}validateRenderingSurface(){return $t({page:"product",element:this})!=null}async loadWallet(){const e=this.recommendedWallet,r=lc(e,this.fallbackWallet,"AcceleratedCheckout");return await gh(this,{...r,instanceNumber:this.instanceNumber})}setupFormObserver(){this.formObserver||(this.formObserver=new Mr(this,({disabled:e,hasSellingPlan:r})=>{this.disabled=e,this.hasSellingPlan=r,this.isShippingRequired=yh(this,this.variantParams)}),this.formObserver.setupMutationObservers())}getOrCreateShadowRoot(){return w(this,Ye)||M(this,Ye,this.attachShadow({mode:"closed"})),w(this,Ye)}extractStyles(){if(this.styleExtractorDisabled){Dt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled"),p.styleBackwardsCompatibility({usedBackwardsCompatibility:!1});return}const e=Qe(O.StyleExtract,"dc:".concat(this.instanceNumber)),r=Ka(this);r&&Xa({element:this,styles:r,debug:this.debug});const n=e();n&&p.styleBackwardsCompatibilityExecutionTime({measurement:n,pageType:this.pageType,stylesWritten:!!r}),p.styleBackwardsCompatibility({usedBackwardsCompatibility:!!r})}};Ye=new WeakMap,d(Mt,"instanceCount",0);let fr=Mt;function mh(t){return t===f.BuyItNow?or.UNBRANDED_BUTTON:or.BRANDED_BUTTON}function yh(t,e){var r;const n=kr(t);return!!((r=e.find(a=>a.id===Number(n==null?void 0:n.variantId)))!=null&&r.requiresShipping)}async function gh(t,{recommendedWallet:e,fallbackWallet:r,instanceNumber:n}){const a=e?dt(e):null,i=dt(r),o=async s=>{const l=ha({walletInstrument:s,instanceNumber:n}),c="timeout",u=await Promise.race([l,new Promise(h=>setTimeout(()=>h(c),vn))]);if(u===c)p.instrumentSDKLoaded({instrument:s.getInstrumentName(),measurement:vn,result:"timeout"});else if(u instanceof be)return u;return null};if(Rt(t,a)){const s=await o(a);if(s)return s}if(Rt(t,i)){const s=await o(i);if(s)return s}return dt(Wn)}ce("shopify-accelerated-checkout",fr),ce("more-payment-options-link",ec,{isChildCustomElement:!0});const fh=t=>{if(typeof PerformanceObserver>"u")return null;const e=new PerformanceObserver(r=>{r.getEntriesByType("resource").some(n=>n.name.includes(nt.CartUpdate)||n.name.includes(nt.CartChange)||n.name.includes(nt.CartAdd)||n.name.includes(nt.CartClear))&&t()});return e.observe({entryTypes:["resource"]}),e},_h=".wallet-cart-button__skeleton{animation:acceleratedCheckoutLoadingSkeleton var(--shopify-accelerated-checkout-skeleton-animation-duration, 4s) var(--shopify-accelerated-checkout-skeleton-animation-timing-function, ease) infinite;animation-delay:-.168s;background-color:var(--shopify-accelerated-checkout-skeleton-background-color, #dedede)}.wallet-button-wrapper{container-type:inline-size;container-name:wrapper;width:100%}.wallet-cart-grid{margin:0 -5px -5px;padding:0;display:flex;flex-direction:row;justify-content:var(--shopify-accelerated-checkout-inline-alignment, start)}.wallet-cart-button-container{position:relative;margin:0 5px 5px}.wallet-cart-button-container,.wallet-cart-button{width:auto;flex:1 1 0px;min-width:100px;height:clamp(25px,var(--shopify-accelerated-checkout-button-inline-size, 42px),55px);border-radius:var(--shopify-accelerated-checkout-button-border-radius, 4px);list-style-type:none!important;text-align:center}.wallet-cart-grid.wallet-cart-grid--vertical,.additional-checkout-buttons--vertical .wallet-cart-grid{justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid.wallet-cart-grid--vertical .wallet-cart-button-container,.additional-checkout-buttons--vertical .wallet-cart-grid .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid.wallet-cart-grid--vertical .wallet-cart-button-container:first-child,.additional-checkout-buttons--vertical .wallet-cart-grid .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid.wallet-cart-grid--vertical .wallet-cart-button,.additional-checkout-buttons--vertical .wallet-cart-grid .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}.wallet-cart-grid.wallet-cart-grid--horizontal,.additional-checkout-buttons--horizontal .wallet-cart-grid{justify-content:stretch}.wallet-cart-grid.wallet-cart-grid--horizontal .wallet-cart-button-container,.additional-checkout-buttons--horizontal .wallet-cart-grid .wallet-cart-button-container,.wallet-cart-grid.wallet-cart-grid--horizontal .wallet-cart-button,.additional-checkout-buttons--horizontal .wallet-cart-grid .wallet-cart-button{min-width:0}@container wrapper (width >= 100px) and (width <= 500px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))) .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 210px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))) .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 320px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))) .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 430px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))) .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 540px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))) .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}@media screen and (max-width: 750px){.wallet-cart-grid{justify-content:stretch}.wallet-cart-button-container,.wallet-cart-button{min-width:0}}@supports (not (container-type: inline-size)) or (not (selector(:has(*)))){.wallet-cart-grid{justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-button-container:first-child{margin:0}.wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}.screen-reader-text{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}",Eh=".wallet-cart-button__skeleton{animation:acceleratedCheckoutLoadingSkeleton var(--shopify-accelerated-checkout-skeleton-animation-duration, 4s) var(--shopify-accelerated-checkout-skeleton-animation-timing-function, ease) infinite;animation-delay:-.168s;background-color:var(--shopify-accelerated-checkout-skeleton-background-color, #dedede)}.wallet-button-wrapper{container-type:inline-size;container-name:wrapper;width:100%}.wallet-cart-grid{margin:0 -5px -5px;padding:0;display:flex;flex-direction:row;justify-content:var(--shopify-accelerated-checkout-inline-alignment, start)}.wallet-cart-button-container{position:relative;margin:0 5px 5px}.wallet-cart-button-container,.wallet-cart-button{width:auto;flex:1 1 0px;min-width:100px;height:clamp(25px,var(--shopify-accelerated-checkout-button-inline-size, 42px),55px);border-radius:var(--shopify-accelerated-checkout-button-border-radius, 4px);list-style-type:none!important;text-align:center}.wallet-cart-grid.wallet-cart-grid--vertical,.additional-checkout-buttons--vertical .wallet-cart-grid{justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid.wallet-cart-grid--vertical .wallet-cart-button-container,.additional-checkout-buttons--vertical .wallet-cart-grid .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid.wallet-cart-grid--vertical .wallet-cart-button-container:first-child,.additional-checkout-buttons--vertical .wallet-cart-grid .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid.wallet-cart-grid--vertical .wallet-cart-button,.additional-checkout-buttons--vertical .wallet-cart-grid .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}.wallet-cart-grid.wallet-cart-grid--horizontal,.additional-checkout-buttons--horizontal .wallet-cart-grid{justify-content:stretch}.wallet-cart-grid.wallet-cart-grid--horizontal .wallet-cart-button-container,.additional-checkout-buttons--horizontal .wallet-cart-grid .wallet-cart-button-container,.wallet-cart-grid.wallet-cart-grid--horizontal .wallet-cart-button,.additional-checkout-buttons--horizontal .wallet-cart-grid .wallet-cart-button{min-width:0}@container wrapper (width >= 100px) and (width <= 500px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))) .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(1)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(2))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 210px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))) .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(2)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(3))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 320px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))) .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(3)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(4))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 430px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))) .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(4)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(5))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}@container wrapper (width <= 540px){.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))) .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(5)).wallet-cart-grid:not(:has(>.wallet-cart-button-container:nth-of-type(6))) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid:not(.wallet-cart-grid--horizontal):has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}@media screen and (max-width: 750px){.wallet-cart-grid{justify-content:stretch}.wallet-cart-button-container,.wallet-cart-button{min-width:0}}@supports (not (container-type: inline-size)) or (not (selector(:has(*)))){.wallet-cart-grid{justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:var(--shopify-accelerated-checkout-row-gap, 8px) 0 0 0}.wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}}.screen-reader-text{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}";function Ah(t){const e=$t({page:"cart",element:t});return pa({type:"attributes",form:e})}class bh{constructor(e,r,n){this.element=e,this.cartToken=r,this.apiClient=n}async getInitialCart(e){try{const r="gid://shopify/Cart/".concat(this.cartToken),n=Ah(this.element);let a,i=[];if(n.length){const o=await this.apiClient.updateCartAttributes({cartId:r,attributes:n,instrumentName:e,startingCheckout:!0});a=o.data,i=o.errors}else a=await this.apiClient.fetchCart({id:r,instrumentName:e,startingCheckout:!0});return{cart:a,errors:i}}catch(r){if(r instanceof ue)return{cart:null,errors:[y.NoResponse]};throw r}}}var qe;const xt=class Oh extends Lr{constructor(){super(),d(this,"instanceNumber",++Oh.instanceCount),d(this,"pageType",C.CartPage),d(this,"cartObserver",null),d(this,"dataSource",null),d(this,"wrapper"),d(this,"didInitiateRender",!1),G(this,qe)}static get observedAttributes(){return["access-token","has-selling-plan","requires-shipping"]}createDataSource(){if(!this.cartToken){p.cartTokenMissing({reason:"createDataSource"});return}this.i18n=Ht(),this.apiClient=new Wt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,withCarrierRates:!0,cartPrepareMigrationEnabled:this.isFlagEnabled(Ja)}),this.dataSource=new bh(this,this.cartToken,this.apiClient)}async createWebComponents({shouldRefetchCartAttributes:e}){if(!this.walletConfigs)throw new Y({code:"invalid-wallet-configs",message:"[AcceleratedCheckoutCart] walletConfigs does not exist"});const r=tc(this.walletConfigs,"AcceleratedCheckoutCart");if(!(r instanceof Array))throw new Y({code:"invalid-wallet-configs",message:"[AcceleratedCheckoutCart] invalid walletConfigs found"});const n=O.ButtonDisplay,a=o=>"".concat(o,":").concat(this.instanceNumber),i=await Ph(this,{walletConfigs:r,startButtonDisplayBenchmark:o=>Xe(n,a(o))});return this.createDataSource(),this.dataSource?(e&&await this.updateAttributes(),await Promise.all(i.map(async o=>{const s=o.getInstrumentName();return await o.createWebComponent({walletContainer:this,dataSource:this.dataSource,i18n:this.i18n,apiClient:this.apiClient,pageType:this.pageType,containerInstanceNumber:this.instanceNumber,slot:"button-".concat(o.getInstrumentName()),onRendered:(()=>{let l=!1;return()=>{l||(l=!0,p.instrumentLoaded({instrumentOrComponentName:s,result:"success",measurement:K(n,a(s))}))}})()})}))):[]}async cartChangedCallback(){try{if(!this.dataSource&&this.cartToken){await this.render({shouldRefetchCartAttributes:!0}),p.initCompleted();return}else if(!this.cartToken){p.cartTokenMissing({reason:"cartChangedCallback"});return}await this.updateAttributes()}catch(e){this.clearUI(),E.notify(e)}}async updateAttributes(){var e,r;if(!this.cartToken||!this.apiClient)return;const n=await this.apiClient.fetchLimitedCart({id:"gid://shopify/Cart/".concat(this.cartToken),instrumentName:f.Unknown});this.hasSellingPlan=(e=n.sellingPlan)!=null?e:!1,this.isShippingRequired=(r=n.shippingRequired)!=null?r:!1}async connectedCallback(){super.connectedCallback();try{if(this.didInitiateRender)return;if(this.instanceNumber===1&&Or(this),p.initStarted(),this.cartObserver=fh(()=>this.cartChangedCallback()),!this.cartObserver){p.log({body:"Cart observer unavailable - PerformanceObserver not supported",attributes:{userAgent:navigator.userAgent}}),this.clearUI();return}if(!this.cartToken){p.cartTokenMissing({reason:"connectedCallback"});return}await this.render({shouldRefetchCartAttributes:!1}),p.initCompleted()}catch(e){this.clearUI(),p.initCompleted(e),E.notify(e)}}disconnectedCallback(){var e;(e=this.cartObserver)==null||e.disconnect()}async attributeChangedCallback(e,r,n){r!==n&&(vr(this,e,n),e==="has-selling-plan"&&n===""?this.showBuyerConsent(this.apiClient,this.i18n):e==="has-selling-plan"&&n===null&&this.hideBuyerConsent())}get cartToken(){return ut("cart")}async render({shouldRefetchCartAttributes:e}){var r;if(this.hasLegacyCartCookie()){p.legacyCartCookie(),this.clearUI();return}this.didInitiateRender=!0;const n=Qe(O.ButtonDisplay,"cart:".concat(this.instanceNumber)),a=await this.createWebComponents({shouldRefetchCartAttributes:e});if(this.clearUI(),a.length===0)return;const i=new DocumentFragment,o=this.getOrCreateShadowRoot(),s=document.createElement("style");s.innerHTML=[qa,_h].join("\n"),o.appendChild(s),this.extractStyles(),this.wrapper=document.createElement("div"),this.wrapper.className="wallet-button-fade-in wallet-button-wrapper";const l=document.createElement("h2");l.className="screen-reader-text",l.textContent=((r=this.i18n)==null?void 0:r.translate("express_checkout"))||"",this.wrapper.appendChild(l);const c=document.createElement("div");c.className="wallet-cart-grid ".concat(Le.CONTAINER),Object.entries(wh).forEach(([u,h])=>{document.querySelector(u)&&c.classList.add(h)}),a.forEach(u=>{const h=document.createElement("div"),g=document.createElement("div"),m=document.createElement("slot");m.name="button-".concat(u.name),h.className="wallet-cart-button-container",g.className="wallet-cart-button",h.setAttribute("data-testid","grid-cell"),h.appendChild(g),g.appendChild(m),c.appendChild(h),i.appendChild(u)}),this.wrapper.appendChild(c),this.hasSellingPlan?this.showBuyerConsent(this.apiClient,this.i18n):this.hideBuyerConsent(),this.setupManagedMarketsHandlers(this.i18n),o.appendChild(this.wrapper),this.appendChild(i),p.instrumentLoaded({instrumentOrComponentName:"AcceleratedCheckoutCart",result:"success",measurement:n()})}getOrCreateShadowRoot(){return w(this,qe)||M(this,qe,this.attachShadow({mode:"closed"})),w(this,qe)}hasLegacyCartCookie(){var e;return this.cartToken?(e=this.cartToken)==null?void 0:e.match(/^[a-z0-9]+$/):!1}extractStyles(){if(this.styleExtractorDisabled){Dt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled"),p.styleBackwardsCompatibility({usedBackwardsCompatibility:!1});return}const e=Qe(O.StyleExtract,"cart:".concat(this.instanceNumber)),r=Ka(this);if(r){Xa({element:this,styles:r,debug:this.debug});const a=this.getOrCreateShadowRoot(),i=document.createElement("style");i.innerHTML=Eh,a.appendChild(i)}const n=e();n&&p.styleBackwardsCompatibilityExecutionTime({measurement:n,pageType:this.pageType,stylesWritten:!!r}),p.styleBackwardsCompatibility({usedBackwardsCompatibility:!!r})}};qe=new WeakMap,d(xt,"instanceCount",0);let _r=xt;async function Ph(t,{walletConfigs:e,startButtonDisplayBenchmark:r=()=>{}}){const n=nc(t,Wu(e));return(await Promise.all(n.map(a=>(r(a.getInstrumentName()),ha({walletInstrument:a,instanceNumber:t.instanceNumber}))))).filter(a=>a!=null)}const wh={".additional-checkout-buttons--vertical shopify-accelerated-checkout-cart":"wallet-cart-grid--vertical",".additional-checkout-buttons--horizontal shopify-accelerated-checkout-cart":"wallet-cart-grid--horizontal"};ce("shopify-accelerated-checkout-cart",_r);class Sh{getInitialCart(){throw new Error('[NoOpDataSource] Unexpected call to "getCart"')}}const Ft=class Mh extends Lr{constructor(){super(...arguments),d(this,"instanceNumber",++Mh.instanceCount),d(this,"pageType",C.Checkout)}get walletConfig(){return this.getAttribute("wallet-config")}async connectedCallback(){var e;super.connectedCallback();try{if(this.children.length)return;this.instanceNumber===1&&(Or(this),p.initStarted());const r=Qe(O.ButtonDisplay,"dc:".concat(this.instanceNumber)),n=rc(this.walletConfig,"WalletButton");if(!n)throw new Ai("[WalletButton] No config provided.");const a=dt(n);if(!a)return;if(!await this.eligibleToShow(a)){this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"failure",message:"ineligible"}}));return}if(this.onlySdk){p.initCompleted(),this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"success"}}));return}const i=a.getInstrumentName();this.i18n=Ht(),this.apiClient=new Wt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale});const o=await this.createWebComponent(a,this.i18n,this.apiClient,i,r);this.innerHTML="",this.appendChild(o),p.initCompleted(),this.instanceNumber===1&&this.triggerLoadedEvent()}catch(r){this.innerHTML="",this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"failure",message:(e=r.message)!=null?e:"Error loading wallet SDK"}})),p.initCompleted(r),E.notify(r)}}async createWebComponent(e,r,n,a,i){const o=await e.createWebComponent({walletContainer:this,dataSource:new Sh,i18n:r,apiClient:n,containerInstanceNumber:this.instanceNumber,pageType:this.pageType});return o.onRendered=()=>{this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"success"}})),p.instrumentLoaded({instrumentOrComponentName:a,result:"success",measurement:i()})},o}async eligibleToShow(e){return!(!Rt(this,e)||(await e.loadWalletSDK(),!e.getPartnerSDKEligibility().eligible))}};d(Ft,"instanceCount",0);let Er=Ft;ce("shopify-wallet-button",Er),hi(E,{metadata:{custom:{"notify-origin":"window-onerror"}}}),pi(E,{metadata:{custom:{"notify-origin":"unhandled-promise-rejection-handler"}}}),p.startExporter();