import.meta;var Za=Object.defineProperty,Qt=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Wr=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),Yr=(t,e,r)=>e.has(t)||Wr("Cannot "+r),w=(t,e,r)=>(Yr(t,e,"read from private field"),r?r.call(t):e.get(t)),B=(t,e,r)=>e.has(t)?Wr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),O=(t,e,r,n)=>(Yr(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Z=function(t,e){this[0]=t,this[1]=e},xe=(t,e,r)=>{var n=(o,s,l,u)=>{try{var c=r[o](s),h=(s=c.value)instanceof Z,m=c.done;Promise.resolve(h?s[0]:s).then(g=>h?n(o==="return"?o:"next",s[1]?{done:g.done,value:g.value}:g,l,u):l({value:g,done:m})).catch(g=>n("throw",g,l,u))}catch(g){u(g)}},a=o=>i[o]=s=>new Promise((l,u)=>n(o,s,l,u)),i={};return r=r.apply(t,e),i[Qt("asyncIterator")]=()=>i,a("next"),a("throw"),a("return"),i},ee=(t,e,r)=>(e=t[Qt("asyncIterator")])?e.call(t):(t=t[Qt("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(u=>o({value:u,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 Mn(t).map(e=>e instanceof Error?e:new xn("[".concat(typeof e,"] ").concat(ii(e).slice(0,10240))))}function Mn(t,e=0){return e>=20?[t,"Truncated cause stack"]:t instanceof Error&&t.cause?[t,...Mn(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 xn=class extends Error{constructor(){super(...arguments),d(this,"name","BugsnagInvalidError")}},Fn=/^\s*at .*(\S+:\d+|\(native\))/m,oi=/^(eval@)?(\[native code])?$/;function si(t){return t.stack?t.stack.match(Fn)?li(t):ci(t):[]}function Un(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(Fn)).map(e=>{let r=e.replace(/^\s+/,"").replace(/^.*?\s+/,""),n=r.match(/ (\(.+\)$)/);r=n?r.replace(n[0],""):r;let a=Un(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=Un(e.replace(r,""));return{method:a,file:i[0],lineNumber:i[1],columnNumber:i[2]}})}var Kt="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,u;let c=ai(t),h={...this.metadata,...this.persistedMetadata,...i},m=this.buildBugsnagEvent(c,{errorClass:e,severityType:n,handled:a,severity:r,metadata:h,context:o,groupingHash:s});if(((u=(l=this.onError)==null?void 0:l.call(this,m,t))==null||u)&&this.releaseStage!=="development"){this.updateAndAppendSessionInformation(m);let g=this.sendToBugsnag(m);return this.onPostErrorListeners.forEach(b=>b(m,t)),g}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:u,appId:c,appType:h,appVersion:m,releaseStage:g,locale:b,userAgent:_}=this,A=t.map((v,se)=>({errorClass:se===0&&e!=null?e:v.name,stacktrace:Bn(c,v),message:v.message,type:"browserjs"}));return{payloadVersion:Kt,exceptions:A,severity:r,severityReason:{type:n},unhandled:!a,app:{id:c,type:h,version:m,releaseStage:g},device:{time:l,locale:b,userAgent:_},breadcrumbs:u,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":Kt,"Bugsnag-Sent-At":(e=(t=this.session)==null?void 0:t.startedAt)!=null?e:new Date().toISOString()},body:JSON.stringify(n,qr())})}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":Kt,"Bugsnag-Sent-At":t.device.time},body:JSON.stringify(r,qr())})}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 Bn(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 xn){let n=r.findIndex(a=>a.method.endsWith("notify"));n>-1&&(r=r.slice(n+1))}return r}function qr(){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 Nh extends Error{constructor(e){super(e),d(this,"reason"),this.name="BreadcrumbsPluginFetchError",Object.setPrototypeOf(this,Nh.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 ht(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 cr={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",Gn=6,fi="discount_code",wr="https://static-na.payments-amazon.com",Sr="".concat(wr,"/checkout.js"),zn="https://www.paypal.com",$n="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"},Dt="VALIDATION_CUSTOM",Vn="portable-wallets",Oe={BUTTON:"accelerated-checkout-button",CONTAINER:"accelerated-checkout-button-container"},Wn="unknown",Yn={name:"buy_it_now",wallet_params:{}};function qn(t){try{return!t.toString().includes("[native code]")}catch(e){return!0}}const Xt=new Map,_i={checkDuplicate({errorClass:t,message:e}){if(Xt.has(t)){const r=Xt.get(t);if(r.has(e))return!0;r.add(e)}else Xt.set(t,new Set([e]));return!1},reset(){}};var yt;class ne extends Error{constructor(e,{groupingHash:r,...n}={}){super(e,n),B(this,yt),d(this,"autogenerateHash",!1),d(this,"useHashPrefix",!1),O(this,yt,r)}get groupingHash(){var e;const r=(e=w(this,yt))!=null?e:this.autogenerateHash?Ei(this.message):"";return(this.useHashPrefix?"".concat(this.name,"-").concat(r):r)||void 0}}yt=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 Et="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",Et),d(this,"code"),this.code=e}}const jn="SilencedError";class J extends Error{constructor(){super(...arguments),d(this,"name",jn)}}class Ai extends Error{constructor(){super(...arguments),d(this,"name","MissingConfigError")}}class de extends ne{constructor(){super(...arguments),d(this,"name","NoResponseError"),d(this,"useHashPrefix",!0),d(this,"autogenerateHash",!0)}}class At extends ne{constructor(e,{errorDetails:r}){const n=At.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 Qn="IgnoredGraphQLResponseError";class pt extends At{constructor(e,{reason:r,errorDetails:n}){super(e,{errorDetails:n}),d(this,"reason"),this.name=Qn,this.reason=r}}class Kn extends ne{constructor(e){const r="[".concat(e,"] completion returned null result");super(r,{groupingHash:"".concat(e,"-expected-completion-null-result")})}}function R(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 Bt(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:Xn(r)}))}function Xn(t){if(Array.isArray(t))return{arrayValue:{values:t.map(e=>Xn(e))}};switch(typeof t){case"boolean":return{boolValue:!!t};case"number":return{doubleValue:Number(t)};case"string":default:return{stringValue:String(t)}}}const Ir=1,wi=Si(5,2,12);function Si(t,e,r){const n=[0];for(let a=0;a{switch(n.attributes={...R(this,K)[K],...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&&(R(this,W)[W]=[],await R(this,Pe)[Pe].exportMetrics(r))}async exportLogs(){const e=R(this,we)[we].map(r=>{const n={timeUnixNano:r.timeUnixNano,observedTimeUnixNano:r.timeUnixNano,attributes:Pi({...R(this,K)[K],...r.attributes})};return r.body&&(n.body={stringValue:r.body}),n});e.length!==0&&(R(this,we)[we]=[],await R(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,u=new Array(l.length+1).fill(0);t[n]||(t[n]={name:n,unit:i||"1",histogram:{aggregationTemporality:Ir,dataPoints:[]}});for(let c=0;c0?h:0,bucketCounts:n>0?[1]:[]};t[r].exponentialHistogram.dataPoints.push({attributes:Bt(o!=null?o:{}),startTimeUnixNano:i,timeUnixNano:i,count:1,sum:l,scale:u,zeroCount:m,positive:b,negative:g,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:Ir,isMonotonic:!0,dataPoints:[]}}),t[r].sum.dataPoints.push({startTimeUnixNano:i,timeUnixNano:i,asDouble:n,attributes:Bt(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:Bt(o!=null?o:{})})}var et=_e("url"),Se=_e("serviceName"),tt=_e("logger"),rt=_e("fetchFn");class Ni{constructor(e,r,n){Object.defineProperty(this,et,{writable:!0,value:void 0}),Object.defineProperty(this,Se,{writable:!0,value:void 0}),Object.defineProperty(this,tt,{writable:!0,value:void 0}),Object.defineProperty(this,rt,{writable:!0,value:void 0}),R(this,et)[et]=e.replace(/\/v1\/(logs|metrics|traces)\/?$/,""),R(this,Se)[Se]=r,R(this,tt)[tt]=n==null?void 0:n.logger,R(this,rt)[rt]=n==null?void 0:n.fetchFn}async exportMetrics(e){const r={resourceMetrics:[{resource:{attributes:[{key:"service.name",value:{stringValue:R(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:R(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(R(this,et)[et]).concat(r),{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if((n=R(this,tt)[tt])===null||n===void 0||n.log({status:a.status}),!a.ok){if(a.status===400){const i=await a.text();throw new st("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 st("Server did not accept data",{errorData:i,retryAfter:s,body:e})}throw new st("Server responded with ".concat(a.status))}}exporterFetch(){return R(this,rt)[rt]||fetch}}class st 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 $e;class Oi{constructor(e){B(this,$e),O(this,$e,e)}async exportMetrics(e){var r;try{await w(this,$e).exportMetrics(e)}catch(n){if(n instanceof st){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 jr("Unable to export metrics",{cause:n})}}async exportLogs(e){var r;try{await w(this,$e).exportLogs(e)}catch(n){if(n instanceof st){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 jr("Unable to export logs",{cause:n})}}}$e=new WeakMap;const ki=new Ni(vi,Li),Mi=new Oi(ki),S=new Ii({exporter:Mi}),Jn="TelemetryExportError";class jr extends Error{constructor(){super(...arguments),d(this,"name",Jn)}}const Zn="LimitedCartQueryError";class xi extends Error{constructor(){super(...arguments),d(this,"name",Zn)}}const ea=["OpenTelemetryClientError",jn,Jn,Qn,Et],Fi=["Load failed","Failed to fetch","when attempting to fetch resource","GraphQL mutation failed with status 404","Component closed",...ea],Qr=new Map([["TypeError","Illegal constructor"],["BugsnagInvalidError",'"isTrusted":true'],[Zn,"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(qn)}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=>[zn,wr,$n].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===Et);return e&&console.error(t.exceptions[0]),e}function Qi(t){return t.exceptions.some(e=>ea.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 D=(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))(D||{}),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||{}),F=(t=>(t.InvalidQuantity="InvalidQuantity",t.VariantRequiresSellingPlan="VariantRequiresSellingPlan",t.SellingPlanNotApplicable="SellingPlanNotApplicable",t.MerchandiseIdInvalid="MerchandiseIdInvalid",t.IgnoredResponseError="IgnoredGraphQLResponseError",t.NoResponse="NoResponse",t))(F||{}),I=(t=>(t.CartPage="cart_page",t.CartAjax="cart_ajax",t.ProductPage="product",t.Checkout="checkout",t.Unknown="unknown",t))(I||{}),at=(t=>(t.CartChange="/cart/change",t.CartUpdate="/cart/update",t.CartAdd="/cart/add",t.CartClear="/cart/clear",t))(at||{}),Ne=(t=>(t.OneTimePurchase="ONE_TIME_PURCHASE",t.Subscription="SUBSCRIPTION",t))(Ne||{});let Ht=Ji();function Ji(){return{shop_id:Wn,debug:!1,pageType:I.Unknown}}function Zi(t){Object.assign(Ht,t)}function Cr(){const{debug:t,...e}=Ht;return e}function eo(){return Ht.debug}function Dr(){return Ht.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:Bn(Vn,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,...u}=Cr();t.metaData={...t.metaData,shop:{shopId:l,...u,...t.metaData.shop},custom:{...t.metaData.custom,customFetch:qn(fetch)},error_source:{shop_id:l},monorail:s},e[0]instanceof At&&(t.metaData.graphql={...e[0].errorDetails},e[0]instanceof pt&&(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)[zn,wr,$n].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:D.ErrorTriggered,value:1,attributes:{filterResult:t||"valid-error"}})}function lo(t){const e=Cr();S.log({body:"Bugsnag Error",attributes:{...e,shop_id:e.shop_id,shopId:e.shop_id,...t}})}var kn;const co={apiKey:"e6b446c1ebe782e2b2fc7eb8ef0dc791",appId:Vn,appVersion:"0.0.4",releaseStage:"production",locale:"en",userAgent:navigator.userAgent,metadata:{user:{id:(kn=ht(gi))!=null?kn:"unknown"},app:{release:"6481f1bed5831448413693ac02f1e9e26c5af2ae"}},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:"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 Jt;class Kr 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 Gt(){return Jt==null&&(Jt=mo(uo)),Jt}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,u)=>{const c=u.replace(/%\{(.*)\}/,"$1");return o[c]?l.replace(u,o[c]):(E.notify(new ho(c,i,a)),l)},i):i},a=yo();return{locale:a,translate(i,o={}){var s;const l=i.split(".");let u=t[a];try{for(const c of l)switch(typeof u){case"object":u=u[c];break;case"string":case"undefined":throw new Kr(i,a)}if(e(u,o)){if(typeof u=="string")throw new po(i,u,a);u=u[r(u,o.count)]}if(typeof u!="string")throw new Kr(i,a);return n(u,o)}catch(c){return E.notify(c),(s=o.defaultValue)!=null?s:i}}}}function yo(){return"en"}function Xr(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 na(){return!!document.querySelector('[data-source-attribution="shopify.shop-promise-pdp"]')}function me(){return new Date().getTime()}function Rr(t){return t.find(e=>typeof e=="object"&&(e==null?void 0:e.code)===Dt)}function Jr(){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}class fo 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=Gt();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),ie("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",Jr()&&(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:"",Jr()&&(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 _o="@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 zt({type:t="button",label:e=void 0}={}){const r=document.createElement("button");return r.type=t,e&&r.setAttribute("aria-label",e),r}function bt(t,e){for(const[r,n]of Object.entries(e))t.setAttribute(r,n)}function lt(t,e){for(const[r,n]of Object.entries(e))t.style.setProperty(r,n)}function aa(){return"\n \n \n \n \n \n \n ')}function Eo(){const t=document.querySelector("top-level-modal");t&&"closeModal"in t&&typeof t.closeModal=="function"&&t.closeModal()}function ia(t){Eo();const e=document.createElement("top-level-modal");return bt(e,{"data-testid":"top-level-modal",title:t}),e}function Ao(t,e){t.innerHTML=''.concat(e,"
")}function Pt(t,e){const r=document.createElement("top-level-modal");r.textContent=e,bt(r,{"data-testid":"top-level-modal","has-close-button":"true",title:t}),document.body.appendChild(r)}function Tr(t,e,r){const n=ia(t);e instanceof Promise?(n.innerHTML=aa(),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 re(t,e){Pt(e.translate("error_dialogs.wallet.title",{wallet:t}),e.translate("error_dialogs.wallet.generic_error",{wallet:t}))}function Qe(t){Pt(t.translate("error_dialogs.checkout.title"),t.translate("error_dialogs.checkout.generic_error"))}function ke(t,e){Pt(t.translate("error_dialogs.checkout.title"),e)}function Me(t,e){switch(e){case F.InvalidQuantity:case F.VariantRequiresSellingPlan:case F.SellingPlanNotApplicable:case F.MerchandiseIdInvalid:case F.IgnoredResponseError:case F.NoResponse:Qe(t);break}}function ge(t){Pt(t.translate("error_dialogs.checkout.title"),t.translate("error_dialogs.product.out_of_stock"))}ie("top-level-modal",fo);class wt 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 bo="#more-payment-options-link{cursor:pointer}";function Po(t,e,r){return(e=So(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Zr(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 en(t){for(var e=1;ee.toString(16)).join("")}function Ro(t,e=!0){return t&&Object.keys(t).length&&e?Object.keys(t).map(r=>({[To(r)]:t[r]})).reduce((r,n)=>en(en({},r),n)):t}function To(t){return t.split(/(?=[A-Z])/).join("_").toLowerCase()}function No(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||Do()).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 vo({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:Io+Co,{method:"post",headers:No(e.metadata),body:JSON.stringify({schema_id:e.schemaId,payload:e.payload,metadata:l&&Ro(l,!0)}),keepalive:r})}const Lo="2.1",Oo="3",Zt={NO_VALUE:"",ACCEPTED:"1",DECLINED:"0"},j={PREFERENCES:"p",ANALYTICS:"a",MARKETING:"m",SALE_OF_DATA:"t"},ce={MARKETING:"m",ANALYTICS:"a",PREFERENCES:"p",SALE_OF_DATA:"s"},ko=()=>typeof __CtaTestEnv__>"u"?!1:__CtaTestEnv__==="true",Mo="_tracking_consent";function tn(t){try{return decodeURIComponent(t)}catch(e){return""}}function oa(t,e=!1){const r=document.cookie?document.cookie.split("; "):[];for(let n=0;ng.charCodeAt(0).toString(16).padStart(2,"0")).join("");l=[8,13,18,23].reduce((g,b)=>g.slice(0,b)+"-"+g.slice(b),m)}function u(h){const m=r.split(".")[0];return m.includes(h.toLowerCase())?Zt.DECLINED:m.includes(h.toUpperCase())?Zt.ACCEPTED:Zt.NO_VALUE}function c(h){return r.includes(h.replace("t","s").toUpperCase())}return{v:Oo,con:{CMP:{[ce.ANALYTICS]:u(ce.ANALYTICS),[ce.PREFERENCES]:u(ce.PREFERENCES),[ce.MARKETING]:u(ce.MARKETING),[ce.SALE_OF_DATA]:u(ce.SALE_OF_DATA)}},region:n||"",cus:s,purposes:{[j.ANALYTICS]:c(j.ANALYTICS),[j.PREFERENCES]:c(j.PREFERENCES),[j.MARKETING]:c(j.MARKETING),[j.SALE_OF_DATA]:c(j.SALE_OF_DATA)},sale_of_data_region:i=="t",display_banner:a=="t",consent_id:l}}function $t(t){const e=Ho();if(!e||!e.purposes)return!0;const r=e.purposes[t];return typeof r=="boolean"?r:!0}function Vo(){return $t(j.PREFERENCES)}function Wo(){return $t(j.ANALYTICS)}function Yo(){return $t(j.MARKETING)}function qo(){return $t(j.SALE_OF_DATA)}function jo(){return Wo()}function Qo(){return Vo()}function Ko(){return Yo()}function Xo(){return qo()}function Jo(){return Ko()}function Zo(){return jo()}function es(){return Qo()}function ts(){return Xo()}function rs(){const t=[];return Zo()&&t.push("analytics"),Jo()&&t.push("marketing"),ts()&&t.push("sale_of_data"),es()&&t.push("preferences"),t}function ns(t,e){switch(e){case"v1":{const r=rs();return{...t,metadata:{...t==null?void 0:t.metadata,consent:r,consent_provider:"consent-tracking-api",consent_version:e}}}default:throw new Nr(e)}}class Nr extends Error{constructor(e){super("Version ".concat(e," is not supported by the consent-tracking-api provider")),this.name="MonorailConsentTrackingApiProviderVersionError",Object.setPrototypeOf(this,Nr.prototype)}}const as=["Chrome-Lighthouse","Googlebot"];function is(){const t=navigator.userAgent;return as.some(e=>t.includes(e))}async function os(t){if(is())return;const e=ns(t,"v1");let r;try{r=await vo({event:e})}catch(n){}if(!(r!=null&&r.ok))try{S.counter({name:D.MonorailProduceError,value:1,attributes:{schemaId:e.schemaId}})}catch(n){}}const er="shopify_wallet_checkout_track/6.3";async function z(t){var e,r,n,a,i,o,s;const l=await ss();if(!l)return;const u={schemaId:er,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(er),{schemaId:er,payload:t});try{await os(u)}catch(c){E.notify(new ls("Failed to send monorail event: ".concat(c),{cause:c}),{metadata:{request:{monorail:{payload:JSON.stringify(u)}}}})}}async function ss(){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,u;(u=(l=window==null?void 0:window.ShopifyAnalytics)==null?void 0:l.lib)!=null&&u.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 ls extends Error{constructor(){super(...arguments),d(this,"name","MonorailError")}}var U=(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))(U||{});const rn={[I.Checkout]:"bwp_checkout_widget_click",[I.CartAjax]:"bwp_cart_widget_click",[I.CartPage]:"bwp_cart_widget_click",[I.ProductPage]:"bwp_widget_click",[I.Unknown]:"bwp_widget_click"};function cs({apiClientId:t,skus:e,pageType:r}){var n;if(!((n=window.Shopify)!=null&&n.analytics))return;const a=r&&rn[r]||"bwp_widget_click";a===rn[I.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 T(t){return{pageType:Dr(),...t}}function ds(){const t=Dr()===I.CartPage?U.CartInitCalled:U.InitCalled;z({event:t})}function us(t){var e,r;const n=t?"Failed":"Success",a=t&&vs(t)?"[".concat(t.name,"]: ").concat(t.code):void 0,i=U["Init".concat(n)];z({event:i,eventSubtype:a}),S.counter({name:D.InitCompleted,value:1,attributes:T({result:n.toLowerCase(),eventType:a,recoveredFailure:!!((r=(e=window.Shopify)==null?void 0:e.PaymentButton)!=null&&r.failedToLoad)})})}function hs({instrumentOrComponentName:t,result:e,measurement:r}){z({event:e==="success"?U.InstrumentLoaded:U.InstrumentLoadFailed,instrumentId:t,ttl:r}),r!=null&&(S.histogram({name:D.InstrumentLoadTime,value:r,attributes:T({instrument:t}),unit:"ms"}),S.histogram({name:D.InstrumentLoadTimeFromPageLoad,value:window.performance.now(),attributes:T({instrument:t}),unit:"ms"}))}function ps({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:T({instrument:t,result:r}),unit:"ms"})}function ms({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:T({instrument:t,reason:r,result:e})})}function ys({instrument:t,result:e,reason:r}){S.counter({name:D.InstrumentLoadEligibility,value:1,attributes:T({instrument:t,result:e,reason:r})})}function gs(t){S.counter({name:D.ButtonRender,value:1,attributes:T({result:"success",instrument:t})})}function fs(t){S.counter({name:D.ButtonRender,value:1,attributes:T({result:"failed",instrument:t})})}function _s({instrument:t,result:e,webPixelMetaData:r,reason:n}){z({event:e==="success"?U.ClickSheetSuccess:U.ClickSheetFailed,instrumentId:t}),S.counter({name:D.SheetClicked,value:1,attributes:T({instrument:t,result:e,...n&&{reason:n}})}),t===f.BuyWithPrime&&r&&cs(r)}function Es(t,e){z({event:"".concat(U.UpdateFailed,"-").concat(e),instrumentId:t}),S.counter({name:D.UpdateFailed,value:1,attributes:T({instrument:t,request:e})})}function As({errorCode:t}){S.counter({name:D.PayPalTokenCreationError,value:1,attributes:T({errorCode:t})})}function bs(t){z({event:U.ClickSheetCancelled,instrumentId:t}),S.counter({name:D.SheetCancelled,value:1,attributes:T({instrument:t})})}function Ps(t,e){z({event:U.SheetFailed,instrumentId:t,errorReason:e==null?void 0:e.message}),S.counter({name:D.SheetFailed,value:1,attributes:T({instrument:t})})}function ws(t){z({event:U.AuthorizationAttempt,instrumentId:t}),S.counter({name:D.AuthorizationAttempt,value:1,attributes:T({instrument:t})})}function Ss({instrument:t,measurement:e,result:r}){z({event:U.AuthorizationComplete,eventSubtype:r,ttl:e,instrumentId:t}),e!=null&&S.histogram({name:D.AuthorizationComplete,value:e,attributes:T({instrument:t,result:r}),unit:"ms"})}function Is({instrument:t,reason:e}){S.counter({name:D.Decelerated,value:1,attributes:T({instrument:t,reason:e})}),p.flushTelemetry()}function Cs({reason:t}){S.counter({name:D.CartTokenMissing,value:1,attributes:{reason:t}})}function Ds({success:t}){S.counter({name:D.RemovePersonalDataResult,value:1,attributes:T({success:t})})}function Rs(){S.counter({name:D.WalletConfigDeveloperError,value:1})}function Ts(){S.counter({name:D.LegacyCartCookie,value:1})}function Ns(){window.setInterval(()=>{sa()},1e3)}function vs(t){return(t==null?void 0:t.name)===Et}function sa(){S.exportMetrics(),S.exportLogs()}function Ls(t){const{body:e,attributes:r}=t,n=Cr();S.log({body:e,attributes:{...n,shopId:n.shop_id,...r}})}function Os({usedBackwardsCompatibility:t}){S.counter({name:D.StyleBackwardsCompatibility,value:1,attributes:{usedBackwardsCompatibility:t}})}function ks({measurement:t,pageType:e,stylesWritten:r}){S.histogram({name:D.StyleBackwardsCompatibilityExecutionTime,value:t,attributes:T({pageType:e,stylesWritten:r}),unit:"ms"})}function Ms({rule:t,count:e,pageType:r}){S.counter({name:D.StyleBackwardsCompatibilityRules,value:e,attributes:T({rule:t,pageType:r})})}function xs({retries:t}){S.counter({name:D.AmazonPayLoadRetries,value:1,attributes:{retries:t}})}function Fs({instrument:t}){S.counter({name:D.DynamicTaxFailed,value:1,attributes:{instrument:t}}),p.log({body:"Dynamic tax failed",attributes:{instrument:t}})}function Us({instrument:t}){S.counter({name:D.DynamicShippingFailed,value:1,attributes:{instrument:t}}),p.log({body:"Dynamic shipping failed",attributes:{instrument:t}})}function Bs({instrument:t,measurement:e}){S.histogram({name:D.SheetLoaded,value:e,attributes:T({instrument:t}),unit:"ms"})}function Hs({instrument:t,errorName:e}){S.counter({name:D.UnrecoverableCartError,value:1,attributes:T({instrument:t,errorName:e})}),p.log({body:"Unrecoverable error detected",attributes:{instrument:t,errorName:e}})}function Gs({instrument:t,error:e}){S.counter({name:D.PaymentCompletedAfterAbort,value:1,attributes:T({instrument:t,error:e})})}function zs(){S.counter({name:D.GooglePayNullCartOnAuthorize,value:1,attributes:T({instrument:f.GooglePay})})}function $s({instrument:t,errorName:e,methodName:r}){S.counter({name:D.WalletSessionAbortError,value:1,attributes:T({instrument:t,errorName:e,methodName:r})}),p.log({body:"Wallet session abort error: ".concat(e),attributes:{instrument:t,methodName:r}})}const p={initStarted:C(ds),initCompleted:C(us),instrumentLoaded:C(hs),instrumentLoadEligibility:C(ys),instrumentSDKLoaded:C(ps),instrumentSDKEligible:C(ms),renderSucceeded:C(gs),renderFailed:C(fs),sheetClicked:C(_s),sheetCancelled:C(bs),sheetFailed:C(Ps),updateFailed:C(Es),authorizationAttempt:C(ws),authorizationComplete:C(Ss),startExporter:C(Ns),decelerated:C(Is),cartTokenMissing:C(Cs),removePersonalDataResult:C(Ds),walletConfigDeveloperError:C(Rs),legacyCartCookie:C(Ts),flushTelemetry:C(sa),styleBackwardsCompatibility:C(Os),styleBackwardsCompatibilityExecutionTime:C(ks),styleBackwardsCompatibilityRules:C(Ms),amazonPaySDKLoadRetries:C(xs),dynamicTaxFailed:C(Fs),dynamicShippingFailed:C(Us),sheetLoaded:C(Bs),unrecoverableCartError:C(Hs),paymentCompletedAfterAbort:C(Gs),googlePayNullCartOnAuthorize:C(zs),log:C(Ls,{logErrors:!1}),paypalTokenCreationError:C(As),walletSessionAbortError:C($s)};function C(t,{logErrors:e=!0}={}){return(...r)=>{try{t(...r)}catch(n){e&&p.log({body:"Error calling telemetry function",attributes:{error:"".concat(n)}})}}}function Vs(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(Dt),t.RedirectToCheckoutRequired="REDIRECT_TO_CHECKOUT_REQUIRED",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.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 Ws=["DELIVERY_FIRST_NAME_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName"],Ys=["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"],js=["DELIVERY_LAST_NAME_INVALID","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName"],Qs=["DELIVERY_ADDRESS1_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1"],Ks=["DELIVERY_ADDRESS2_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2"],Xs=["DELIVERY_CITY_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city"],Js=["DELIVERY_POSTAL_CODE_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],la=["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"],Zs=["DELIVERY_PHONE_NUMBER_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],el=["INVALID: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country","Variable $buyerIdentity of type CartBuyerIdentityInput! was provided invalid value for countryCode"],tl=["DELIVERY_PHONE_NUMBER_INVALID","INVALID: buyerIdentity.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],ca=["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"],vr=["INVALID_PAYMENT: amount","INVALID_PAYMENT: payment.amount","INVALID_PAYMENT: payment"],Lr=["TAX_NEW_TAX_MUST_BE_ACCEPTED","PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"],rl=["DELIVERY_DELIVERY_LINE_DETAIL_CHANGED","DELIVERY_LOCAL_PICKUP_DELIVERY_LINE_DETAIL_CHANGED"],nl=["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"],al=["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"],il=["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"],Vt=["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"],ol=["MERCHANDISE_OUT_OF_STOCK",...Vt],sl=["MERCHANDISE_OUT_OF_STOCK",...Vt],ll=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.firstName"],cl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.lastName"],dl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address1"],ul=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address2"],hl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.city"],pl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.phone","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.phone"],ml=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.zip"],yl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.applePayWalletContent.billingAddress.province","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.province"],gl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.firstName"],fl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.lastName"],_l=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address1","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address1"],El=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.address2","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address2"],Al=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.city","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.city"],bl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.phone"],Pl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.applePayWalletContent.billingAddress.zip","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.zip"];[...vr,...Vt];const wl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.firstName"],Sl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.lastName"],Il=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address1"],Cl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.address2"],Dl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.city"],Rl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.phone","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.phone"],Tl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.zip"],Nl=["ADDRESS_FIELD_IS_REQUIRED: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.province","ADDRESS_FIELD_IS_REQUIRED: payment.freePaymentMethod.billingAddress.province"],vl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.firstName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.firstName"],Ll=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.lastName","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.lastName"],Ol=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address1","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address1"],kl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.address2","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.address2"],Ml=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.city","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.city"],xl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.phone"],Fl=["ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.walletPaymentMethod.googlePayWalletContent.billingAddress.zip","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: payment.freePaymentMethod.billingAddress.zip"],Ul=["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"],Bl=["BUYER_IDENTITY_EMAIL_DOMAIN_IS_INVALID","BUYER_IDENTITY_EMAIL_DOES_NOT_MATCH_EXPECTED_PATTERN","INVALID: buyerIdentity.email"],Hl=["DELIVERY_PHONE_NUMBER_INVALID","INVALID: buyerIdentity.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],Gl=["Variable $buyerIdentity of type CartBuyerIdentityInput! was provided invalid value for countryCode","INVALID: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country"],zl=["DELIVERY_ADDRESS2_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2"],$l=["ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city","DELIVERY_CITY_REQUIRED"],Vl=["DELIVERY_POSTAL_CODE_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],Wl=["PAYMENTS_METHOD_REQUIRED","PAYMENTS_METHOD_UNAVAILABLE"],Yl=["MERCHANDISE_EXPECTED_PRICE_MISMATCH","DELIVERY_DELIVERY_LINE_DETAIL_CHANGED","DELIVERY_LOCAL_PICKUP_DELIVERY_LINE_DETAIL_CHANGED",...Wl,y.CustomValidation,...Vt];class ql extends ne{constructor(e){e instanceof Error?(super("[".concat(e.name,"] ").concat(e.message),{cause:e.cause,groupingHash:e instanceof ne?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;Vs(()=>{t&&(t.disabled=!1)});const l=Rr(i),u=Ql(i),c=u||l;if(u&&p.unrecoverableCartError({instrument:e,errorName:u}),!a&&!c)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&&!c)throw new Error("Errors present after cart creation: ".concat(JSON.stringify(i)));return{cart:a,customValidationError:l,decelerationReason:s,abortReason:o,...u?{unrecoverableError:u}:{}}}catch(n){if(n instanceof pt)return{cart:null,customValidationError:void 0,unrecoverableError:F.IgnoredResponseError,abortReason:void 0,decelerationReason:void 0};throw new ql(n)}finally{t.disabled=!1}}const jl={[y.InvalidQuantity]:F.InvalidQuantity,[y.VariantRequiresSellingPlan]:F.VariantRequiresSellingPlan,[y.SellingPlanNotApplicable]:F.SellingPlanNotApplicable,[y.MerchandiseIdInvalid]:F.MerchandiseIdInvalid,[y.NoResponse]:F.NoResponse};function Ql(t){if(t.length!==1)return null;const[e]=t;return typeof e=="object"?null:jl[e]||null}const Kl={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=Kl[e];n&&r.searchParams.set("redirect_source",n);break}}window.location.assign(r.toString())}const Xl={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,cart_throttled:null};function nn({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 tr({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 Or({currentCartTotal:t,initialBuyerCurrency:e}){const r=t.amount;return!(!r||Number(r)===0||e.toUpperCase()===t.currencyCode.toUpperCase())}function k({checkoutUrl:t,instrumentName:e,reason:r}){if(!t)throw new Error("Invalid Checkout URL");const n=new URL(t),a=Xl[r];a&&n.searchParams.set(a,"true"),p.decelerated({instrument:e,reason:r}),fe(n.toString())}class Jl extends wt{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]=ue(),[this.dataSource,this.setDataSource]=ue(),[this.classNames,this.setClassNames]=ue()}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:u,abortReason:c}=await Ee({element:this,instrumentName:f.MoreOptions,dataSource:i});if(u){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),p.log({body:"Unrecoverable error detected in More Options sheet clicked",attributes:{unrecoverableError:u}}),Me(a,u);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}}),ke(a,l.message);return}if(c==="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"}),k({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),Qe(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=bo,this.appendChild(n)}setAccessibilityAttributes(){this.anchor&&(this.disabled?(this.anchor.removeAttribute("href"),this.anchor.role="link"):(this.anchor.removeAttribute("role"),this.anchor.href="#"))}}var N=(t=>(t.ButtonDisplay="buttonDisplay",t.LoadInstrument="loadInstrument",t.LoadSdk="loadSDK",t.AuthorizationLatency="authorizationLatency",t.SheetLoad="sheetLoad",t.StyleExtract="styleExtract",t))(N||{});function ua(){var t,e;return!!((t=window.performance)!=null&&t.mark)&&!!((e=window.performance)!=null&&e.measure)}function Ke(t,e){return Je(t,e),()=>Q(t,e)}function Je(t,e){ua()&&window.performance.mark("".concat(t,"-").concat(e,"-start"))}function Q(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 kr(t,e,r){if(it!=null&&it.length){const n=it.join(",");t.querySelectorAll(n).forEach(a=>{r===null?a.removeAttribute(e):a.setAttribute(e,r)})}}function Zl(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 ec(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 Tt(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 tc(t,e){return e.filter(r=>Tt(t,r))}async function ha({walletInstrument:t,instanceNumber:e}){const r=t.getInstrumentName(),n=Ke(N.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}const pa="d6d12da0",rc="2d75a54c";var Ve;class Mr extends wt{constructor(){super(...arguments),d(this,"apiClient"),d(this,"i18n"),d(this,"policy"),d(this,"isFetchingPolicy",!1),d(this,"intersectionObserver",null),B(this,Ve),d(this,"handleIntersection",(e,r)=>{e.some(n=>n.isIntersecting)&&(this.apiClient&&this.apiClient.setVisible(),r.disconnect(),z({event:U.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 publicAssetsEnabled(){return this.isFlagEnabled(rc)}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&&kr(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,Ve)==null&&O(this,Ve,this.getEnabledFlags()),w(this,Ve).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=ia(r);document.body.appendChild(s);const l=document.createElement("div");lt(l,{position:"relative",width:"100%"});const u=document.createElement("iframe");bt(u,{width:"100%",height:"100%",title:r,frameborder:"no"}),lt(u,{border:"none","min-height":"50vh",display:"none"});const c=document.createElement("div");c.className="skeleton-overlay",c.innerHTML=aa(),lt(c,{background:"white"}),l.appendChild(u),l.appendChild(c),s.appendChild(l);let h=!1,m=!1,g=!1;const b=()=>{!g&&h&&m&&(c.remove(),u.style.display="block")},_=setTimeout(()=>{h||(g=!0,Ao(s,a))},i);u.addEventListener("load",()=>{clearTimeout(_),h=!0,b()}),setTimeout(()=>{m=!0,b()},o),u.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){Tr(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:U.FirstVisibleNotAvailable})}}Ve=new WeakMap;function xr(t){var e,r;Zi({shop_id:(e=t.shopId)!=null?e:Wn,cartId:(r=t.cartId)!=null?r:void 0,debug:t.debug,pageType:t.pageType})}function ma({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=nc(o),l=ac(o);s&&typeof l<"u"&&l.trim()!==""&&(i[s]=l)}),Object.entries(i!=null?i:{}).map(([o,s])=>({key:o,value:s}))}function Wt({page:t,element:e}){const r=t==="product"?'[data-shopify="payment-button"]':'[data-shopify="dynamic-checkout-cart"]',n=an(e,r)||document.querySelector(r);return an(n,"form")}const nt=Element.prototype;function an(t,e){if(nt.matches=nt.matches||nt.webkitMatchesSelector||nt.msMatchesSelector||nt.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 nc(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 ac(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 Fr(t){const e=Wt({page:"product",element:t});return ya(e)}function ya(t){var e;const r=t==null?void 0:t.elements;if(!r)return null;const n=Nt(r,"id");if(!n||isNaN(Number(n))||Number(n)<=0)return null;const a=Number((e=Nt(r,"quantity"))!=null?e:"1"),i="gid://shopify/ProductVariant/".concat(n),o=oc(r),s=ma({type:"properties",form:t});return{variantId:n,quantity:a,merchandiseId:i,sellingPlanId:o,lineItemProperties:s}}function ic(t){const e=t==null?void 0:t.elements;return e?!!Nt(e,"selling_plan"):!1}function Nt(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 oc(t){const e=Nt(t,"selling_plan");if(!(!e||e==="undefined"))return"gid://shopify/SellingPlan/".concat(e)}class Ur{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=ya(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:ic(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=Wt({page:"product",element:this.element}),this.addToCartForm){const e=this.addToCartForm.querySelectorAll("[type=submit]");e instanceof NodeList&&(this.addToCartButtons=[...e])}}}function sc(t,e,r){try{const n=JSON.parse(t!=null?t:"{}"),a=JSON.parse(e!=null?e:JSON.stringify(Yn));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 lc=".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 )}",cc='.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}}',dc=70;class ct{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 ct(0,0,0,0),n.blendWith(a,r)):a.opacity>0?n=a:n=r,r=n,a=e.shift();return n}const ur=new ct(255,255,255,1);function hc(t){const e=[];let r=t;for(;r.parentElement;){r=r.parentElement;const n=window.getComputedStyle(r).backgroundColor,a=pc(n);if(n&&e.push(a),a.opacity===1)break}try{return uc(e.reverse())}catch(n){return E.notify(new ga("[BackgroundDetection] Failed to blend colors for element ".concat(t.outerHTML),{cause:n})),ur}}function pc(t){if(!t)return ur;try{const e=t.split("(")[1].split(")")[0].replace(" ","").split(",");return new ct(Number(e[0]),Number(e[1]),Number(e[2]),typeof e[3]>"u"?1:Number(e[3]))}catch(e){E.notify(new ga("[BackgroundDetection] Failed to convert rgbString to array ".concat(t),{cause:e}))}return ur}class ga extends Error{constructor(){super(...arguments),d(this,"name","ColorProcessingError")}}var he;class Ae extends wt{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"),B(this,he),this.onRendered=()=>{},[this.i18n,this.setI18n]=ue(),[this.dataSource,this.setDataSource]=ue(),[this.apiClient,this.setApiClient]=ue(),[this.classNames,this.setClassNames]=ue(),[this.containerInstanceNumber,this.setContainerInstanceNumber]=ue()}async cleanupOnFailure(e,r){var n;try{await e()}catch(a){E.notify(new mc("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:Q(N.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")||I.Unknown}get buttonTheme(){return hc(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=[cc,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,he)||O(this,he,this.attachShadow({mode:"closed"})),w(this,he)}clearShadowRoot(){w(this,he)&&(w(this,he).innerHTML="")}}he=new WeakMap;class mc extends Error{constructor(){super(...arguments),d(this,"name","CleanupOnFailureError")}}class yc 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:u}=await Ee({element:this,instrumentName:this.name,dataSource:a});if(l){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),Me(n,l);return}if(u==="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"}),ke(n,s.message);return}if(i){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),k({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)}}),Qe(n)}}async render(){var e;this.button||(this.button=zt());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 gc=1e3;function fc(){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 _c(t){return Promise.race([t,new Promise((e,r)=>setTimeout(()=>r(new Error("timed out")),gc))])}class be{constructor(e){d(this,"publicAssetsEnabled",!1),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=I.ProductPage,slot:u="button",onRendered:c=()=>{}}){var h,m,g;const b=this.getWebComponentName();if(!ie(b,this.getWebComponentClass(),{isChildCustomElement:!0}))throw new J("Failed to define custom element ".concat(b,", aborting execution"));try{await _c(customElements.whenDefined(b))}catch(v){throw new J("Timeout waiting for custom element ".concat(b," to be defined"))}const _=document.createElement(b);if(!(_ instanceof Ae))throw new J("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":(m=e.buyerCountry)!=null?m:"","buyer-currency":e.buyerCurrency,"wallet-params":JSON.stringify((g=this.walletParams)!=null?g:{}),"page-type":l,slot:u};try{e.disabled&&_.setAttribute("disabled",""),bt(_,A),e.isShippingRequired&&_.setAttribute("requires-shipping",""),e.hasSellingPlan&&_.setAttribute("has-selling-plan",""),e.pciEnabled&&_.setAttribute("pci-enabled","")}catch(v){const se=v;throw se.message.includes("setAttribute is not a function")&&fc()?new J(se.message):se}if(s&&_.setAttribute("call-to-action",""),typeof _.setDataSource!="function")throw new J("Custom element ".concat(b," is not properly upgraded, aborting execution"));return _.setDataSource(r),_.setApiClient(a),_.setI18n(n),_.setClassNames(o),_.setContainerInstanceNumber(i),_.onRendered=c,_}loadWalletSDK(){return Promise.resolve()}getLoadEligibility(e){return{eligible:!0}}getPartnerSDKEligibility(){return{eligible:!0}}}class Ec extends be{static walletName(){return"buy_it_now"}getWebComponentName(){return"shopify-buy-it-now-button"}getInstrumentName(){return f.BuyItNow}getWebComponentClass(){return yc}}const Ac="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}",bc='::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 ze(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 Br({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 u={freePaymentMethod:{billingAddress:n}};return await a.updateCartPayment(t,{amount:{amount:e.amount,currencyCode:e.currencyCode},...Number(e.amount)<=0&&!l&&!s?u:r},i,o)}catch(u){throw p.updateFailed(i,"updatePayment"),u}}function fa(t){return window[_a(t)]}function _a(t){return"paypal-".concat(t.replace(/[^a-zA-Z0-9]/g,""))}const Pc="RESTRICTED_WALLET_ACCOUNT",wc="GENERIC_ERROR",Sc="NO_PENDING_TASK",Ic="WALLET_SERVICE_DISABLED",Cc="FAILED_TO_ENQUEUE_BACKGROUND_JOB",Dc="REQUEST_MISSING_VALID_MERCHANDISE_SOURCE",Rc="THROTTLE_EXCEEDED",Tc="INTERNAL_SERVER_ERROR",Nc=[wc,Sc,Ic,Cc,Dc,Rc,Tc];function on(t){return t==null?void 0:t.map(e=>{var r,n;return{code:(r=e.extensions)==null?void 0:r.code,isLoggable:Nc.includes((n=e.extensions)==null?void 0:n.code)}}).find(({code:e,isLoggable:r})=>e===Pc||r)}function vt(t){if(!t)return null;const e=getComputedStyle(t).borderRadius;return e.includes("px")?parseInt(e,10):null}function Lt(t){if(!t)return null;const e=getComputedStyle(t).height;return e.includes("px")?parseInt(e,10):null}const rr=25,sn=55,vc=["cart_not_ready","cart_throttled","payment_method_not_applicable","invalid_payment_deferred_payment_required"],nr="PAYPAL_CALLBACK_HANDLED_ERROR";var pe;class Lc 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),B(this,pe,!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=vt(this.container),r=Lt(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=Oe.BUTTON;const a=document.createElement("style");a.innerHTML=Ac,this.appendChild(a),await this.initializeShadowStyles(r,bc),r.appendChild(n),this.container=n,this.renderFromPayPalSDK(),(e=this.resizeObserver)==null||e.observe(this.container)}getHeight(){const e=Lt(this.container);return e?e>=rr&&e<=sn?e:ethis.createToken({apiClientPromise:this.apiClient,requiresBillingAgreement:a});let o,s;a?s=i:o=i;const l=vt(this.container),u=this.getHeight();this.prevHeight=u;const c={color:"gold",label:this.isCTA?"pay":"paypal",disableMaxWidth:!0,height:u,shape:"sharp"};l&&l>0&&(c.borderRadius=l,this.prevBorderRadius=l);const h=await this.i18n;this.sdkButtonsComponent=(r=(e=fa(this.walletParams.sdkUrl))==null?void 0:e.Buttons)==null?void 0:r.call(e,{fundingSource:"paypal",style:c,createOrder:o,createBillingAgreement:s,onApprove:async g=>{await this.onApprove(g)},onCancel:()=>{this.cancelPaymentSheet("Payment sheet cancelled")},onClick:this.onClick.bind(this),onError:g=>{this.onError(g,h)}});let m=!1;try{await((n=this.sdkButtonsComponent)==null?void 0:n.render(this.container)),m=!0}catch(g){p.renderFailed(this.name),p.log({body:"PayPal Button not able to render into container.",attributes:{pageType:this.pageType,error:g==null?void 0:g.toString()}})}finally{this.rendering=!1}m&&this.onRendered()}cancelPaymentSheet(e){var r;O(this,pe,!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();O(this,pe,!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[u,c]=await Promise.all([this.dataSource,this.i18n]);try{const{decelerationReason:h,cart:m,customValidationError:g,unrecoverableError:b,abortReason:_}=await Ee({element:this,instrumentName:this.name,dataSource:u});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}}),Me(c,b),r.reject();if(_==="out_of_stock")return p.sheetClicked({instrument:this.name,result:"rejected",reason:"out_of_stock"}),ge(c),r.reject();if(g)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:g==null?void 0:g.message}}),ke(c,g.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=m==null?void 0:m.checkoutUrl)!=null?n:""),r.reject()):h?(p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),k({checkoutUrl:(a=m==null?void 0:m.checkoutUrl)!=null?a:"",instrumentName:this.name,reason:h}),r.reject()):(this.cartId=m.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:dr(this.cartId)}}}),E.notify(h),Qe(c),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,pe)||(a instanceof J?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:dr(this.cartId)}}}),E.notify(a))),Qe(await this.i18n),new Error(nr)}}async onApprove({orderID:e,payerID:r,billingToken:n}){var a;try{if(p.authorizationAttempt(this.name),Je(N.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:u,email:c,remoteOrderId:h,payerApprovedAmount:m}=await i.paypalBuyerDetailsFetch(o,this.cartId),g=await ze({cartId:this.cartId,cartClient:i,instrumentName:this.name,emailAddress:c,streetAddress:l});if(!(g!=null&&g.data))throw new Error("Cart not found");if(await this.decelerateOrAbort(g))return;const{id:b,totalAmount:_,checkoutUrl:A}=g.data,v=await Br({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:c,expiresAt:u,payerId:r,token:h!=null?h:e,acceptedSubscriptionTerms:!1,vaultingAgreement:!1,merchantId:this.walletParams.merchantId,...m&&{payerApprovedAmount:m}}}},canUsePaymentMethodForFreeOrder:!0,totalAmount:_});if(await this.decelerateOrAbort(v))return;p.authorizationComplete({instrument:this.name,result:"success",measurement:Q(N.AuthorizationLatency,this.name)}),fe(A)}catch(i){throw w(this,pe)||(p.authorizationComplete({instrument:this.name,result:"failed",measurement:Q(N.AuthorizationLatency,this.name)}),E.notify(i)),new Error(nr)}}onError(e,r){var n;if(w(this,pe)||e.message.includes(nr))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 Oc(e)),p.sheetFailed(this.name,e),(n=this.abortController)==null||n.abort("[PayPal] Error occurred");const a=r.translate("brand.paypal");re(a,r)}requiresBillingAgreement(){return this.walletParams.hasManagedSellingPlanState||this.walletParams.requiresBillingAgreement}shouldDecelerate(e){return!!(e&&vc.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:Or({currentCartTotal:r,initialBuyerCurrency:this.buyerCurrency})&&(a="currency_changed"),a?(k({checkoutUrl:n,instrumentName:this.name,reason:a}),!0):!1}async handleOutOfStock(){p.authorizationComplete({instrument:this.name,result:"failed",measurement:Q(N.AuthorizationLatency,this.name)}),ge(await this.i18n)}}pe=new WeakMap;class Oc extends ne{constructor(e){super(e.message,{cause:e.cause}),d(this,"name","PayPalError"),d(this,"useHashPrefix",!0),this.stack=e.stack}}const Fe=class Ch extends be{static walletName(){return"paypal"}constructor(e){super(e)}getWebComponentName(){return"shopify-paypal-button"}getInstrumentName(){return f.PayPal}getWebComponentClass(){return Lc}loadWalletSDK(){let e=Ch.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",_a(this.walletParams.sdkUrl)),r.onload=()=>n(),r.onerror=i=>{Ch.paypalSDKPromiseByUrl.delete(this.walletParams.sdkUrl),r&&document.body.contains(r)&&document.body.removeChild(r),a(i)},document.body.appendChild(r)}),Ch.paypalSDKPromiseByUrl.set(this.walletParams.sdkUrl,e),e}getLoadEligibility(){return{eligible:!0}}getPartnerSDKEligibility(){var e,r;try{return(r=(e=fa(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(Fe,"paypalSDKPromiseByUrl",new Map);let hr=Fe;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}",pr={UK:"GB",JA:"JP"},Ea=["AS","GU","MP","PR","VI"];Ea.forEach(t=>{pr[t]="US"});function St(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&&Ea.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(pr).includes(e)?pr[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:ba(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:ba(r)}})}function Aa({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 ba(t){return t.map(e=>e.handle).join(",")}function Pa({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 ot({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=ot({label:i.translate("order_summary.subtotal"),possibleLines:[t]}),u=Pa({deliveryGroups:e,i18n:i}),c=ot({label:i.translate("order_summary.duties"),possibleLines:[r]}),h=ot({label:i.translate("order_summary.taxes"),possibleLines:[n]}),m=o.map(_=>({label:_,amount:"0.00",type:"pending"})),g=m.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 ot({label:v!=null?v:i.translate("order_summary.discount"),possibleLines:[_.discountedAmount],isDiscount:!0})}))!=null?s:[];return[...l,...u,...c,...h,...b,...m,...g]}function ot({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 ln(t,e){if(!t.length)return[];const r=Aa({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 Ot extends ne{constructor(){super(...arguments),d(this,"name","UnhandledActionError")}}class wa{constructor(){d(this,"generatePrioritizedPaymentSheetAction",(e,r)=>{let n;const a=[],i=[],o=[],s=r.filter(u=>u!==y.UnacceptablePaymentsAmount).some(u=>e[u]!==void 0);for(const u of Object.keys(e))if(!(u===y.UnacceptablePaymentsAmount&&s)){const c=e[u]();c.effects&&i.push(...c.effects),c.action!=="complete"&&c.errors&&o.push(...c.errors),a.push(c)}const l=(u=>Vc.map(c=>u.find(h=>h.action===c)).find(c=>!!c))(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 wa{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,u=this.getUnhandledErrors(l,s);if(u.forEach(h=>{E.notify(new Ot("[".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:c}=this.getMergedPaymentSheetAction({result:e,errorActions:s});return c||(u.length>0?{action:"abort",effects:[()=>{re(this.i18n.translate("brand.apple_pay"),this.i18n)}]}:{action:"update",errors:[]})}mapCompletionResultToPaymentSheetAction({result:e,context:r,checkoutUrl:n}){if(!e.data)throw new Kn(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 Ot("[".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:[()=>{re(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(()=>{re(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:vr,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:Lr,generateAction:()=>this.decelerateOrAbort({reason:"dynamic_tax",instrumentName:f.ApplePay,errorOrWarning:y.NewTaxMustBeAccepted,checkoutUrl:n,requestType:a})},{errors:da,generateAction:()=>this.decelerateOrAbort({reason:"not_enough_stock",instrumentName:f.ApplePay,errorOrWarning:y.MerchandiseNotEnoughStock,checkoutUrl:n,requestType:a})},{errors:ol,generateAction:()=>({action:"abort",effects:[()=>ge(this.i18n)]})},{errors:ca,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:Ws,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.missing.first_name"))]})},{errors:Ys,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:js,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.invalid.last_name"))]})},{errors:Qs,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:Ks,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:Xs,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:Js,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.missing.postal_code"))]})},{errors:la,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:Zs,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.missing.phone"))]})},{errors:tl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.invalid.phone"))]})},{errors:el,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:nl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid")]})},{errors:al,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","postalCode",this.i18n.translate("errors.invalid.postal_code"))]})},{errors:ll,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.missing.first_name"))]})},{errors:cl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","name",this.i18n.translate("errors.missing.last_name"))]})},{errors:dl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.missing.address1"))]})},{errors:ul,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","addressLines",this.i18n.translate("errors.missing.address2"))]})},{errors:hl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","locality",this.i18n.translate("errors.missing.city"))]})},{errors:pl,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","phoneNumber",this.i18n.translate("errors.missing.phone"))]})},{errors:ml,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid","postalCode",this.i18n.translate("errors.missing.postal_code"))]})},{errors:yl,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:gl,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:fl,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:_l,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:El,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:Al,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:bl,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:Pl,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=Rr(e);return r?{action:"abort",effects:[()=>{const n=this.i18n.translate("brand.apple_pay");Tr(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 cn=["name","postalAddress"];function Yc({shippingRequired:t,walletParams:e,buyerCurrency:r}){const{phoneRequired:n,emailRequired:a}=e,i=[...a?["email"]:[],...n?["phone"]:[]],o=t?[...cn,...i]:i;return{countryCode:e.countryCode,currencyCode:r,merchantCapabilities:e.merchantCapabilities,supportedNetworks:e.supportedNetworks,total:{type:"pending",label:e.merchantName,amount:"1.00"},requiredBillingContactFields:cn,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 ne{constructor(){super(...arguments),d(this,"name","ApplePaySessionCreationError"),d(this,"useHashPrefix",!0),d(this,"autogenerateHash",!0)}}const Sa=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=It({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=It({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=It({price:Number(i[0].price.amount)*o,currencyCode:i[0].price.currencyCode,locale:e.locale}),u=It({price:Number(i[1].price.amount)*o,currencyCode:i[1].price.currencyCode,locale:e.locale}),c=a.priceAdjustments[0].orderCount;return[...r,e.translate("order_summary.subscriptions.recurring_totals_with_policies",{count:c,fixedPrice:l,recurringPrice:u,interval:s})]}return r},[])}function It({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 Yt="GraphQL Client",dn=0,un=3,Ia="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",Ca="Response returned unexpected Content-Type:",Da="An unknown error has occurred. The API did not return a data object or any errors in its response.",mr={json:"application/json",multipart:"multipart/mixed"},hn="X-SDK-Variant",pn="X-SDK-Version",Xc="shopify-graphql-client",Jc="1.4.1",Ra=1e3,Zc=[429,503],Ta=/@(defer)\b/i,mn="\r\n",ed=/boundary="?([^=";]+)"?/i,yn=mn+mn;function ye(t,e=Yt){return t.startsWith("".concat(e))?t:"".concat(e,": ").concat(t)}function Ze(t){return t instanceof Error?t.message:JSON.stringify(t)}function Na(t){return t instanceof Error&&t.cause?t.cause:void 0}function va(t){return t.flatMap(({errors:e})=>e!=null?e:[])}function La({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||eun))throw new Error("".concat(t,': The provided "retries" value (').concat(e,") is invalid - it cannot be less than ").concat(dn," or greater than ").concat(un))}function V(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}function Oa(t,e){if(t.length===0)return e;const r={[t.pop()]:e};return t.length===0?r:Oa(t,r)}function ka(t,e){return Object.keys(e||{}).reduce((r,n)=>(typeof e[n]=="object"||Array.isArray(e[n]))&&t[n]?(r[n]=ka(t[n],e[n]),r):(r[n]=e[n],r),Array.isArray(t)?[...t]:{...t})}function Ma([t,...e]){return e.reduce(ka,{...t})}function td({clientLogger:t,customFetchApi:e=fetch,client:r=Yt,defaultRetryWaitTime:n=Ra,retriableCodes:a=Zc}){const i=async(o,s,l)=>{const u=s+1,c=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)&&u<=c)throw new Error;const m=(h==null?void 0:h.headers.get("X-Shopify-API-Deprecated-Reason"))||"";return m&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:o,deprecationNotice:m}}),h}catch(m){if(u<=c){const g=h==null?void 0:h.headers.get("Retry-After");return await rd(g?parseInt(g,10):n),t({type:"HTTP-Retry",content:{requestParams:o,lastResponse:h,retryAttempt:s,maxRetries:l}}),i(o,u,l)}throw new Error(ye("".concat(l>0?"Attempted maximum number of ".concat(l," network retries. Last message - "):"").concat(Ze(m)),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}){La({client:Yt,retries:n});const i={headers:t,url:e,retries:n},o=ad(a),s=td({customFetchApi:r,clientLogger:o,defaultRetryWaitTime:Ra}),l=id(s,i),u=od(l),c=pd(l);return{config:i,fetch:l,request:u,requestStream:c}}function ad(t){return e=>{t&&t(e)}}async function xa(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?Ia:Da),...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:u,keepalive:c,signal:h}=i,m=JSON.stringify({query:a,variables:o});La({client:Yt,retries:u});const g=Object.entries({...r,...s}).reduce((_,[A,v])=>(_[A]=Array.isArray(v)?v.join(", "):v.toString(),_),{});!g[hn]&&!g[pn]&&(g[hn]=Xc,g[pn]=Jc);const b=[l!=null?l:e,{method:"POST",headers:g,body:m,signal:h,keepalive:c}];return t(b,1,u!=null?u:n)}}function od(t){return async(...e)=>{if(Ta.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(mr.json)?await xa(r):{errors:{networkStatusCode:n,message:ye("".concat(Ca," ").concat(i)),response:r}}:{errors:{networkStatusCode:n,message:ye(a),response:r}}}catch(n){return{errors:{message:Ze(n),...r==null?{}:{networkStatusCode:r.status,response:r}}}}}}function sd(t){return xe(this,null,function*(){const e=new TextDecoder;if(t.body[Symbol.asyncIterator])try{for(var r=ee(t.body),n,a,i;n=!(a=yield new Z(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 Z(a.call(r)))}finally{if(i)throw i[0]}}else{const o=t.body.getReader();let s;try{for(;!(s=yield new Z(o.read())).done;)yield e.decode(s.value)}finally{o.cancel()}}})}function ld(t,e){return{[Symbol.asyncIterator](){return xe(this,null,function*(){try{let o="";try{for(var r=ee(t),n,a,i;n=!(a=yield new Z(r.next())).done;n=!1){const s=a.value;if(o+=s,o.indexOf(e)>-1){const l=o.lastIndexOf(e),u=o.slice(0,l).split(e).filter(c=>c.trim().length>0).map(c=>c.slice(c.indexOf(yn)+yn.length).trim());u.length>0&&(yield u),o=o.slice(l+e.length),o.trim()==="--"&&(o="")}}}catch(s){i=[s]}finally{try{n&&(a=r.return)&&(yield new Z(a.call(r)))}finally{if(i)throw i[0]}}}catch(o){throw new Error("Error occured while processing stream payload - ".concat(Ze(o)))}})}}}function cd(t){return{[Symbol.asyncIterator](){return xe(this,null,function*(){yield{...yield new Z(xa(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(Ze(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:u,errors:c})=>({data:l&&u?Oa(u,l):{},...V("errors",c)}));return{data:s.length===1?s[0].data:Ma([...s.map(({data:l})=>l)]),...V("errors",va(s)),hasNext:a}})}function ud(t,e){if(t.length>0)throw new Error(Ia,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(Da)}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 xe(this,null,function*(){var u,c;try{let _=!0;try{for(var h=ee(ld(o,i)),m,g,b;m=!(g=yield new Z(h.next())).done;m=!1){const A=g.value,v=dd(A);l=(c=(u=v.find(H=>H.extensions))==null?void 0:u.extensions)!=null?c:l;const se=va(v);s=Ma([s,...v.map(({data:H})=>H)]),_=v.slice(-1)[0].hasNext,ud(se,s),yield{...V("data",s),...V("extensions",l),hasNext:_}}}catch(A){b=[A]}finally{try{m&&(g=h.return)&&(yield new Z(g.call(h)))}finally{if(b)throw b[0]}}if(_)throw new Error("Response stream terminated unexpectedly")}catch(_){const A=Na(_);yield{...V("data",s),...V("extensions",l),errors:{message:ye(Ze(_)),networkStatusCode:t.status,...V("graphQLErrors",A==null?void 0:A.graphQLErrors),response:t},hasNext:!1}}})}}}function pd(t){return async(...e)=>{if(!Ta.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(mr.json):return cd(r);case a.includes(mr.multipart):return hd(r,a);default:throw new Error("".concat(Ca," ").concat(a),{cause:r})}}catch(r){return{[Symbol.asyncIterator](){return xe(this,null,function*(){const n=Na(r);yield{errors:{message:ye(Ze(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}",Ct="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}}}}}}",ar="fragment CartErrorParts on CartUserError{message field code}",gn="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:/,/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 fn="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)||fn,": ").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)||fn,": ").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 qt{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,Ct],{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=ee(i),s,l,u;s=!(l=await o.next()).done;s=!1){const c=l.value;c.errors&&await this.onError({operationName:"createCart",response:c});const h=(r=c.data)==null?void 0:r.result;if(h&&!c.hasNext){h.errors.length>0&&this.onResultError(h.errors);const m=this.parseMutationWarnings((a=(n=c.data)==null?void 0:n.result)==null?void 0:a.warnings),g=h.cart?this.parseCartResponse(h.cart):null;return{data:g,errors:this.parseMutationErrors({result:c,key:"result",operationName:"cartCreate"}),warnings:m,decelerationReason:tr({cart:g,warnings:m}),abortReason:nn({cart:g,warnings:m})}}}}catch(c){u=[c]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(u)throw u[0]}}throw new de("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=me()+2e4;for(;me()typeof u=="string"&&u.startsWith(y.PendingDeliveryGroups))))return s;const l=s.data.deliveryGroups.flatMap(u=>u.deliveryOptions.map(c=>({deliveryOptionHandle:c.handle,deliveryGroupId:u.id})));i=i.map(u=>{var c;return(c=l.find(h=>h.deliveryOptionHandle===u.deliveryOptionHandle))!=null?c:u})}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=ee(i),s,l,u;s=!(l=await o.next()).done;s=!1){const c=l.value;c.errors&&await this.onError({operationName:"applePaySessionCreate",response:c});const h=(a=(n=(r=c.data)==null?void 0:r.applePaySessionCreate)==null?void 0:n.applePaySession)==null?void 0:a.body;if(h)return h}}catch(c){u=[c]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(u)throw u[0]}}throw new de("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=ee(i),s,l,u;s=!(l=await o.next()).done;s=!1){const c=l.value;if(c.hasNext)continue;if(c.errors){if(c.errors.graphQLErrors){const m=on(c.errors.graphQLErrors);if(m!=null&&m.code)throw new J(m.code)}await this.onError({operationName:"paypalBuyerDetailsFetch",response:c})}const h=(a=(n=c.data)==null?void 0:n.paypalBuyerDetailsFetch)==null?void 0:a.paypalDetails;if(h)return h}}catch(c){u=[c]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(u)throw u[0]}}throw new de("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=ee(o),l,u,c;l=!(u=await s.next()).done;l=!1){const h=u.value;if(h.errors){if(h.errors.graphQLErrors){const g=on(h.errors.graphQLErrors);if(g!=null&&g.code)throw g.isLoggable&&(p.log({body:"PayPal Token Create ".concat(g.code," Error")}),p.paypalTokenCreationError({errorCode:g.code})),new J(g.code)}await this.onError({operationName:"paypalTokenCreate",response:h})}const m=(i=(a=(n=h.data)==null?void 0:n.paypalTokenCreate)==null?void 0:a.paypalToken)==null?void 0:i.token;if(m)return m}}catch(h){c=[h]}finally{try{l&&(u=s.return)&&await u.call(s)}finally{if(c)throw c[0]}}throw new de("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?[Ct,ar,gn]:[Ct],u=this.cartPrepareMigrationEnabled?{cartId:e,country:this.country,language:i,withCarrierRates:this.withCarrierRates,prepareCart:!0}:{id:e,country:this.country,language:i,withCarrierRates:this.withCarrierRates},c=await this.requestStream([s,...l],u,{instrumentName:n,startingCheckout:r,operationName:"fetchCart"});try{for(var h=ee(c),m,g,b;m=!(g=await h.next()).done;m=!1){const _=g.value;_.errors&&await this.onError({operationName:"fetchCart",response:_});let A=null,v;if(!_.data)throw new de("".concat(o," operation returned no data in response"));if(zd(_.data)){const se=_.data.preparedCart;A=(a=se==null?void 0:se.result)==null?void 0:a.cart,v=this.parsePreparedCartMutationErrors(_.errors,this.extractPreparedCartMutationErrors(se),"prepareCart")}else A=_.data.cart;if(E.leaveBreadcrumb("".concat(o," response"),{operationName:o,body:A,errors:v,hasNext:_.hasNext},"log"),A&&!_.hasNext){const se=this.parseCartResponse(A);return this.lastValidCart=se,se}}}catch(_){b=[_]}finally{try{m&&(g=h.return)&&await g.call(h)}finally{if(b)throw b[0]}}throw new de("".concat(o," operation returned no response"))}async updateCartPayment(e,r,n,a){var i,o;const s={cartId:e,input:r},{amount:l,currencyCode:u}=r.amount;let c;const h=me()+1e4;for(;me()setTimeout(g,500)),s.input.amount={amount:m.data.totalAmount.amount,currencyCode:m.data.totalAmount.currencyCode};continue}return(m.data.totalAmount.amount===l||parseFloat(m.data.totalAmount.amount)<=parseFloat(l))&&m.data.totalAmount.currencyCode===u?m:c}throw new Error("Payment update operation timed out")}async updateCartAttributes({cartId:e,attributes:r,instrumentName:n,startingCheckout:a}){const i={cartId:e,attributes:r};return await this.requestDeferredCart(yd,i,{instrumentName:n,operationName:"updateCartAttributes",startingCheckout:a})}async submitForCompletion(e,r,n){var a,i;const o=this.formatLanguage(this.locale),s=await this.request([Dd],{cartId:e,attemptToken:r,country:this.country,language:o,withCarrierRates:this.withCarrierRates},{instrumentName:n,operationName:"submitForCompletion"});return{data:(i=(a=s.data)==null?void 0:a.cartSubmitForCompletion)==null?void 0:i.result,errors:this.parseCompletionErrors(s)}}async fetchSubscriptionPolicy(){var e,r;const{data:n}=await this.request([Sd],{country:this.country,language:this.formatLanguage(this.locale)},{operationName:"fetchSubscriptionPolicy"});return(r=(e=n==null?void 0:n.shop)==null?void 0:e.subscriptionPolicy)==null?void 0:r.body}async cartRemovePersonalData({cartId:e,instrumentName:r}){var n,a;let i,o,s;try{const u=await this.request([Rd,ar],{cartId:e},{instrumentName:r,keepalive:!0});i=this.parseMutationWarnings((a=(n=u.data)==null?void 0:n.cartRemovePersonalData)==null?void 0:a.warnings),o=this.parseMutationErrors({result:u,key:"cartRemovePersonalData",operationName:"cartRemovePersonalData"})}catch(u){s=u.toString()}const l=!(i!=null&&i.length||o!=null&&o.length||s);p.removePersonalDataResult({success:l}),l||p.log({body:"cartRemovePersonalData failed",attributes:{cartId:e,warnings:i,errors:o,exception:s}})}setVisible(){this.hasBeenVisible=!0}generateURLWithOperationName(e){const r=e.match(this.OPERATION_NAME_REGEX);if(r){const n=this.url.includes("?")?"&":"?",a="operation_name=".concat(r[1]);return"".concat(this.url).concat(n).concat(a)}return this.url}async request(e,r,n){return this.client.request(e.join(""),{variables:r,headers:_n(n),url:this.generateURLWithOperationName(e[0]),keepalive:n.keepalive})}async requestStream(e,r,n){return this.client.requestStream(e.join(""),{variables:r,headers:_n(n),url:this.generateURLWithOperationName(e[0]),signal:n.abortSignal})}async requestDeferredCart(e,r,n){var a,i,o,s,l,u,c,h,m;const g=this.formatLanguage(this.locale),b=await this.requestStream([e,Ct,ar,gn],{...r,country:this.country,language:g,withCarrierRates:this.withCarrierRates,prepareCart:this.cartPrepareMigrationEnabled},n);try{for(var _=ee(b),A,v,se;A=!(v=await _.next()).done;A=!1){const H=v.value;H.errors&&await this.onError({operationName:n.operationName,response:H,abortSignal:n.abortSignal});const M=this.extractMutationErrors(H),P=(i=(a=H.data)==null?void 0:a.preparedCart)==null?void 0:i.result,oe=(l=(s=(o=H.data)==null?void 0:o.result)==null?void 0:s.cart)!=null?l:P==null?void 0:P.cart;if(oe&&!H.hasNext){let G;this.cartPrepareMigrationEnabled||(G=await this.fetchCart({id:oe.id,instrumentName:n.instrumentName,startingCheckout:!1}));const L=this.parseMutationWarnings((c=(u=H.data)==null?void 0:u.result)==null?void 0:c.warnings),$=this.parsePreparedCartMutationErrors(H.errors,M,n.operationName),le=G!=null?G:this.parseCartResponse(oe);return{data:le,errors:$,warnings:L,abortReason:nn({cart:le,warnings:L}),decelerationReason:tr({warnings:L,cart:le,cartStatus:P==null?void 0:P.__typename,errors:$})}}if(this.lastValidCart&&M.length>0){this.onResultError(M);const G=this.parseMutationWarnings((m=(h=H.data)==null?void 0:h.result)==null?void 0:m.warnings);return{data:this.lastValidCart,errors:this.parsePreparedCartMutationErrors(H.errors,M,n.operationName),warnings:G,decelerationReason:tr({warnings:G,cart:this.lastValidCart})}}}}catch(H){se=[H]}finally{try{A&&(v=_.return)&&await v.call(_)}finally{if(se)throw se[0]}}throw new de("Deferred cart operation returned no response")}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 pt("Request aborted",{reason:"abort",errorDetails:{operationName:e}});const a=await Td(e,r);if(!a)return;const{message:i,...o}=a,{isIgnorable:s,reason:l}=xd(a,{hasBeenVisible:this.hasBeenVisible});throw E.leaveBreadcrumb(i,{ignored:s,ignoredReason:l,...r,...o},"error"),s?(p.log({body:"Ignored GraphQL response error",attributes:{message:i,reason:l,...o}}),new pt(i,{reason:l,errorDetails:o})):new At(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,u;const c=s.node;return{quantity:c.quantity,totalAmount:{amount:c.cost.totalAmount.amount,currencyCode:c.cost.totalAmount.currencyCode},subtotalAmount:{amount:(l=c.cost.subtotalAmount)==null?void 0:l.amount,currencyCode:(u=c.cost.subtotalAmount)==null?void 0:u.currencyCode},merchandise:{requiresShipping:c.merchandise.requiresShipping},discountAllocations:c.discountAllocations,sellingPlanAllocation:c.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===Dt?{code:Dt,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(c=>c))||[],u=[...s,...l];return u.length>0&&E.leaveBreadcrumb("GraphQL errors on mutation '".concat(n,"'"),u,"error"),u}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 u=[];((a=(n=(r=e.data)==null?void 0:r.cartSubmitForCompletion)==null?void 0:n.result)==null?void 0:a.__typename)==="SubmitFailed"&&(u=(i=e.data.cartSubmitForCompletion.result.errors.map(h=>h.code))!=null?i:[]);const c=[...l,...u];return c.length>0?E.leaveBreadcrumb("GraphQL errors on completion",c,"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"),c}}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 _n({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 Fa({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 Ua({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 Ba({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 ne{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 En(t,e){return t.some(r=>e.includes(r))}function dt({result:t,instrument:e}){var r;const n=(r=t.errors)!=null?r:[];En(n,Lr)&&p.dynamicTaxFailed({instrument:e}),En(n,rl)&&p.dynamicShippingFailed({instrument:e})}const An=["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:u}){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,"onvalidatemerchant",async c=>{var h,m,g;try{const b=new URL(c.validationURL),_=this.getMerchantSession(b),{cart:A,decelerationReason:v,customValidationError:se,unrecoverableError:H}=await Ee({element:this.button,instrumentName:this.name,dataSource:this.dataSource});if(H){E.leaveBreadcrumb("ApplePay Session unrecoverable error",{unrecoverableError:H},"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(H)),Me(this.i18n,H);return}if(se){E.leaveBreadcrumb("ApplePay Session custom validation error",{customValidationError:se},"error"),p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),this.withActiveSession("abort",()=>this.session.abort()),(m=this.abortController)==null||m.abort("[Apple Pay] Custom validation error"),ke(this.i18n,se.message);return}this.cart=A;const M=await _;if(E.leaveBreadcrumb("ApplePay Session completeMerchantValidation",{session:M},"log"),v&&An.includes(v)){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),await this.terminateSession(),k({checkoutUrl:(g=A==null?void 0:A.checkoutUrl)!=null?g:"",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(M)),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 c=>{if(!this.sessionIsCancelled())try{const h=St(c.shippingContact),m=await ze({cartId:this.cart.id,streetAddress:h,cartClient:this.apiClient,instrumentName:this.name});if(!m.data)throw new Error("Missing cart during Apple Pay Session creation");if(await this.decelerateOrAbort(m))return;await this.applyPaymentSheetActions({result:m,onProceed:g=>this.completeShippingContactSelection(m.data,g),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 c=>{var h;if(!this.sessionIsCancelled())try{const m=c.shippingMethod.identifier.split(","),g=Ba({selectedDeliveryOptionHandles:m,deliveryGroups:this.cart.deliveryGroups,instrumentName:this.name});if(g.length===0){this.handleShippingMethodNotFoundInCart(m);return}const b=await Fa({cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name,selectedDeliveryOptions:g,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(m){this.terminateSession({error:m})}}),d(this,"onpaymentmethodselected",async c=>{if(!this.sessionIsCancelled())try{const{billingContact:h}=c.paymentMethod;if(!this.isShippingRequired&&h){const b=St(h),_=await ze({cartId:this.cart.id,countryCode:b.country,cartClient:this.apiClient,instrumentName:this.name});if(!_.data)throw new Error("Missing cart during Apple Pay Session creation");if(await this.decelerateOrAbort(_))return;await this.applyPaymentSheetActions({result:_,onProceed:()=>{this.cart=_.data},context:{shippingRequired:this.isShippingRequired,shippingCountryCode:b.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentMethodSelected::updateBuyerIdentity",afterAuthorization:!1});const A=await Wd({billingAddress:b,cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name});await this.applyPaymentSheetActions({result:A,onProceed:()=>{this.cart=A.data},context:{shippingRequired:this.isShippingRequired,shippingCountryCode:b.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentMethodSelected::updateBillingAddress",afterAuthorization:!1})}const{newTotal:m,newLineItems:g}=this.getNewTotalAndLineItems(this.cart);if(E.leaveBreadcrumb("ApplePay Session completePaymentMethodSelection",{newTotal:m,newLineItems:g},"log"),this.sessionIsCancelled())return;this.withActiveSession("completePaymentMethodSelection",()=>this.session.completePaymentMethodSelection({newTotal:m,newLineItems:g})),this.isShippingRequired||this.onSheetLoaded()}catch(h){this.terminateSession({error:h})}}),d(this,"oncancel",()=>{var c;this.cancelled=!0,this.removePersonalData(),Q(N.SheetLoad,this.name),p.sheetCancelled(this.name),this.button.disabled=!1,(c=this.abortController)==null||c.abort("[Apple Pay] Payment sheet cancelled")}),d(this,"onpaymentauthorized",async c=>{p.authorizationAttempt(this.name),Je(N.AuthorizationLatency,this.name);const h=async M=>{var P,oe;switch((P=M.effects)==null||P.forEach(G=>G()),M.action){case"complete":{const G=ApplePaySession.STATUS_SUCCESS;try{await this.completePayment(G),fe(M.redirectUrl)}catch(L){this.terminateSession({error:L,afterAuthorization:!0})}break}case"show_error":{const G=(oe=M.errors)!=null?oe:[];try{await this.completePayment(ApplePaySession.STATUS_FAILURE,G)}catch(L){this.terminateSession({error:L,afterAuthorization:!0})}break}case"abort":{try{this.abortPaymentSheetAndShowError(),this.removePersonalData()}catch(G){this.terminateSession({error:G,afterAuthorization:!0})}break}case"decelerate":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),await this.removePersonalData(),k({checkoutUrl:M.redirectUrl,instrumentName:this.name,reason:M.reason})}catch(G){this.terminateSession({error:G,afterAuthorization:!0})}break}default:this.terminateSession({error:new Error("[".concat(this.name,"] completion action not handled: ").concat(M.action)),afterAuthorization:!0})}},{token:m,billingContact:g,shippingContact:b}=c.payment;let _=null,A=null;try{if(!g){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}if(_=St({...g,phoneNumber:b==null?void 0:b.phoneNumber}),this.isShippingRequired){if(!b){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}A=St(b)}}catch(M){this.terminateSession({error:M,afterAuthorization:!0});return}const v=async()=>{var M,P;try{const oe=this.isShippingRequired?{validateAddress:!0,streetAddress:A}:{},G=(M=this.customerAccountEmail)!=null?M:b==null?void 0:b.emailAddress,L=await ze({cartId:this.cart.id,emailAddress:G,cartClient:this.apiClient,instrumentName:this.name,...oe});if(dt({result:L,instrument:this.name}),await this.decelerateOrAbort(L))return;const $=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction({result:L,context:{shippingRequired:this.isShippingRequired,shippingCountryCode:A==null?void 0:A.country,billingCountryCode:_==null?void 0:_.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updateBuyerIdentity"});(P=$.effects)==null||P.forEach(le=>le()),await this.handlePaymentSheetAction({paymentSheetAction:$,onProceed:async le=>{le&&le.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,le):await se()},afterAuthorization:!0})}catch(oe){this.terminateSession({error:oe,afterAuthorization:!0})}},se=async()=>{var M,P;try{const oe=this.cart.lineItems.some($=>!!$.sellingPlanAllocation),G=await Br({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{applePayWalletContent:{billingAddress:_,data:m.paymentData.data,header:m.paymentData.header,lastDigits:m.paymentMethod.displayName.split(" ")[1],signature:m.paymentData.signature,version:m.paymentData.version}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:_,cartClient:this.apiClient,instrumentName:this.name,hasSellingPlan:oe,abortSignal:(M=this.abortController)==null?void 0:M.signal});if(dt({result:G,instrument:this.name}),await this.decelerateOrAbort(G))return;const L=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction({result:G,context:{shippingRequired:this.isShippingRequired,shippingCountryCode:A==null?void 0:A.country,billingCountryCode:_==null?void 0:_.country},checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updatePayment"});(P=L.effects)==null||P.forEach($=>$()),await this.handlePaymentSheetAction({paymentSheetAction:L,onProceed:async $=>{$&&$.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,$):await H()},afterAuthorization:!0})}catch(oe){this.terminateSession({error:oe,afterAuthorization:!0})}},H=async()=>{var M;try{const P=await Ua({cartId:this.cart.id,token:m.transactionIdentifier,cartClient:this.apiClient,instrumentName:this.name});dt({result:P,instrument:this.name}),(M=P.errors)!=null&&M.includes(y.GenericError)&&(E.leaveBreadcrumb("ApplePay Generic ERROR encountered during completion",{errorCodes:P.errors},"error"),p.log({body:"[ApplePay] Generic ERROR code encountered during completion",attributes:{errorCodes:P.errors}}));const oe=this.paymentSheetActionGenerator.mapCompletionResultToPaymentSheetAction({result:P,context:{shippingRequired:this.isShippingRequired,shippingCountryCode:A==null?void 0:A.country,billingCountryCode:_==null?void 0:_.country},checkoutUrl:P.data&&"checkoutUrl"in P.data&&P.data.checkoutUrl?P.data.checkoutUrl:this.cart.checkoutUrl});await h(oe)}catch(P){this.terminateSession({error:P,afterAuthorization:!0})}};await v()}),d(this,"terminateSession",async({error:c,afterAuthorization:h=!1}={})=>{var m;try{this.button.disabled=!1,c&&E.notify(c),h?p.authorizationComplete({instrument:this.name,measurement:Q(N.AuthorizationLatency,this.name),result:"failed"}):(Q(N.SheetLoad,this.name),p.sheetFailed(this.name,c)),E.leaveBreadcrumb("ApplePay Session abort",{afterAuthorization:h},"log");try{this.withActiveSession("abort",()=>this.session.abort()),(m=this.abortController)==null||m.abort("[Apple Pay] Payment sheet terminated")}catch(g){}if(c){const g=this.i18n.translate("brand.apple_pay");re(g,this.i18n)}}finally{await this.removePersonalData()}}),d(this,"getMostRecentNonNullCart",(c,h)=>c?(this.cart=c,c):h),d(this,"handleNullCart",c=>{if(!c)throw new Error("[".concat(this.name,"] no cart returned on mutation, aborting"))}),d(this,"completeShippingContactSelection",(c,h)=>{try{const m=this.getMostRecentNonNullCart(c,this.cart),{newTotal:g,newLineItems:b}=this.getNewTotalAndLineItems(m),_=ln(m.deliveryGroups,this.i18n);E.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{errors:h,newTotal:g,newLineItems:b,newShippingMethods:_},"log"),this.withActiveSession("completeShippingContactSelection",()=>this.session.completeShippingContactSelection({errors:h!=null?h:[],newTotal:g,newLineItems:b,newShippingMethods:_}))}catch(m){this.terminateSession({error:m})}}),d(this,"completeShippingMethodSelection",c=>{try{this.handleNullCart(c),this.cart=c;const{newTotal:h,newLineItems:m}=this.getNewTotalAndLineItems(c);E.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{newTotal:h,newLineItems:m},"log"),this.withActiveSession("completeShippingMethodSelection",()=>this.session.completeShippingMethodSelection({newTotal:h,newLineItems:m}))}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=u.customerAccountEmail;try{this.session=new ApplePaySession(Gn,Yc({shippingRequired:this.isShippingRequired,walletParams:u,buyerCurrency:n}))}catch(c){throw new jc(String(c),{cause:c})}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",{},"log"),this.abortController=ve("AbortController"),this.session.begin()}handleShippingMethodNotFoundInCart(e){var r,n;const a=ln((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(u=>u()),!this.sessionIsCancelled()&&await this.handlePaymentSheetAction({paymentSheetAction:l,onProceed:r,afterAuthorization:o})}async getMerchantSession(e){const r=await new qt({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:Q(N.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:Sa(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&&An.includes(e.decelerationReason)?a=e.decelerationReason:Or({currentCartTotal:n,initialBuyerCurrency:this.buyerCurrency})&&(a="currency_changed"),a){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"});try{await this.terminateSession()}finally{k({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=Q(N.SheetLoad,this.name);e&&(z({event:U.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{k({instrumentName:this.name,checkoutUrl:e.redirectUrl,reason:e.reason})}break;default:throw new Error('Missing handler for payment sheet action "'.concat(e.action,'"'))}}}function Hr({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 kt=new Map;function Le({instrumentName:t,logoType:e="LIGHT",logoContent:r}){const n=kt.get(t)||{};n[e]||(n[e]=r,kt.set(t,n))}function mt({instrumentName:t,logoType:e="LIGHT"}){var r;const n=(r=kt.get(t))==null?void 0:r[e];if(!n)throw new Error("".concat(t," ").concat(e," logo not loaded"));return n}class qd 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]);Je(N.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(),re(r.translate("brand.apple_pay"),r),this.disabled=!1}}async render(){var e;const r=this.getOrCreateShadowRoot(),{translate:n}=await this.i18n,a=mt({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=zt({label:o}),this.button.onclick=s=>this.handleClick(s),this.button.classList.add("apple-pay-button",mi[this.buttonTheme],Oe.BUTTON),this.isCTA){const s=Hr({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 Gr(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 Xe({svg:t,instrumentName:e,logoType:r="LIGHT"}){var n;if((n=kt.get(e))!=null&&n[r])return;let a,i,o;try{if(o=jd(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=Kd(e,r),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,r,a)||a);return a&&Qd(e,r,a),a};class zr 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 qd}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,Gn)))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(){if(this.publicAssetsEnabled)await Xe({svg:"apple-pay-logo.svg",instrumentName:f.ApplePay});else{const e=await import("./apple-pay-logo-BZB6IYWC.js");if(e)Le({instrumentName:f.ApplePay,logoContent:e.default});else throw new Error("Apple Pay logo is empty")}}}Ha([Gr("Apple Pay")],zr.prototype,"getLoadEligibility"),Ha([Gr("Apple Pay")],zr.prototype,"getPartnerSDKEligibility");const Xd=".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 Mt extends Error{constructor(){super(...arguments),d(this,"name","MissingAccessTokenError")}}class $r extends Error{constructor(){super(...arguments),d(this,"name","FetchingWalletsPlatformConfigError")}}class Vr extends Error{constructor(){super(...arguments),d(this,"name","EmptyLineItemsWalletsPlatformConfigError")}}async function Ga({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 Vr("[Fetch Pay Config][".concat(a,"] No eligible line items provided in the config request."));default:throw new $r("[Fetch Pay Config][".concat(a,"] ").concat(o))}}}const Jd={[I.Checkout]:"Checkout",[I.CartAjax]:"Cart",[I.CartPage]:"Cart",[I.ProductPage]:"Product",[I.Unknown]:"Product"},Ue=class Sh 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=zt({label:e("brand.buy_with_prime")});return r.type="button",r.className="buy-with-prime-button",this.applyEnabledStyles(r),r}applyEnabledStyles(e){const r=mt({instrumentName:f.BuyWithPrime});e.innerHTML=r,e.disabled=!1,lt(e,{"background-color":"#1A98FF",color:"#FFFFFF",cursor:"pointer"})}applyDisabledStyles(e){const r=mt({instrumentName:f.BuyWithPrime,logoType:"DARK"});e.innerHTML=r,e.disabled=!0,lt(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:c,decelerationReason:h,customValidationError:m,unrecoverableError:g}=await Ee({element:this,instrumentName:this.name,dataSource:i});if(g){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error",webPixelMetaData:o}),Me(a,g);return}if(m){p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error",webPixelMetaData:o}),ke(a,m.message);return}if(h){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration",webPixelMetaData:o}),k({checkoutUrl:(e=c==null?void 0:c.checkoutUrl)!=null?e:"",instrumentName:this.name,reason:h});return}if(!this.accessToken)throw new Mt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");s={...await Ga({configOptionsEndpoint:Sh.OPTIMUS_CONFIG_REST_API_URL,checkoutUrl:(r=c==null?void 0:c.checkoutUrl)!=null?r:"",sourceId:(n=ra(c))!=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 u=s;this.pciEnabled&&(u.onSendCheckoutAction=this.handleOnSendCheckoutAction),window.amazon.buywithprime.initCheckout({amazonPayOptions:u}),p.sheetClicked({instrument:this.name,result:"success",webPixelMetaData:o})}catch(s){o&&(o.skus=o.skus||[]),Sh.EXPECTED_ERRORS.some(c=>s instanceof c)?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:u}=a;Pt(u("error_dialogs.wallet.title",{wallet:u("brand.buy_with_prime")}),this.getModalContent(l,u))}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&&Jd[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(Oe.BUTTON),await this.initializeShadowStyles(r,Xd),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(Ue,"OPTIMUS_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/optimus")),d(Ue,"EXPECTED_ERRORS",[$r,Mt,Vr]);let yr=Ue;async function za({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 J("Error loading Amazon SDK: ".concat(i)))},document.head.append(n)})}async function $a({sdkUrl:t=Sr,maxRetries:e=3}){return za({fn:()=>Zd(t),maxRetries:e,delay:200,retryPolicyFn:()=>!0,onFinishedFn:r=>{p.amazonPaySDKLoadRetries({retries:r})}})}const Be=class vh 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 yr}async loadWalletSDK(){await $a({sdkUrl:vh.SDK_URL,maxRetries:vh.MAX_RETRIES}),await this.loadLogos()}async loadLogos(){await Promise.all([this.loadPrimeLogo(),this.loadPrimeLogoDark()])}async loadPrimeLogo(){if(this.publicAssetsEnabled)await Xe({svg:"prime-logo.svg",instrumentName:f.BuyWithPrime});else{const e=await import("./prime-logo-DoVHKBSO.js");if(e)Le({instrumentName:f.BuyWithPrime,logoType:"LIGHT",logoContent:e.default});else throw new Error("Buy with Prime logo is empty")}}async loadPrimeLogoDark(){if(this.publicAssetsEnabled)await Xe({svg:"prime-logo-dark.svg",instrumentName:f.BuyWithPrime,logoType:"DARK"});else{const e=await import("./prime-logo-dark-DJIA6J0w.js");if(e)Le({instrumentName:f.BuyWithPrime,logoType:"DARK",logoContent:e.default});else throw new Error("Buy with Prime logo dark is empty")}}};d(Be,"MAX_RETRIES",3),d(Be,"SDK_URL",Sr);let gr=Be;const eu="shopify-amazon-pay-button div[role=button][slot=amazon-pay-slot][data-testid=amazon-pay-button]{border-radius:0!important;width:100%!important}",tu=':host([page-type="cart_page"]) .accelerated-checkout-button{overflow:hidden;display:flex;justify-content:center}',bn="amazon-pay-slot";var gt,ft,We,q,ae,De;const He=class Ih extends Ae{constructor(){super(...arguments),d(this,"name",f.AmazonPay),d(this,"resizeObserver",null),B(this,gt,0),B(this,ft,0),B(this,We,!1),B(this,q,null),B(this,ae,null),B(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:u}=await Ee({element:this,instrumentName:this.name,dataSource:i});if(u){p.sheetClicked({instrument:this.name,result:"rejected",reason:"unrecoverable_error"}),Me(a,u);return}if(l){p.sheetClicked({instrument:this.name,result:"rejected",reason:"custom_validation_error"}),ke(a,l.message);return}if(s){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),k({checkoutUrl:(r=o==null?void 0:o.checkoutUrl)!=null?r:"",instrumentName:this.name,reason:s});return}const{totalAmount:{amount:c},checkoutUrl:h}=o;let m=this.walletParams;if(!m.createCheckoutSessionConfig){if(!this.accessToken)throw new Mt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");m={...await Ga({configOptionsEndpoint:Ih.CV2_CONFIG_REST_API_URL,checkoutUrl:h,sourceId:(n=ra(o))!=null?n:"",accessToken:this.accessToken,instrument:this.name}),placement:this.pageType===I.ProductPage?"Product":"Cart"}}delete m.appId,e.initCheckout({...m,...Number(c)!==0&&{estimatedOrderAmount:{amount:c,currencyCode:this.buyerCurrency}}}),p.sheetClicked({instrument:this.name,result:"success"})}catch(o){Ih.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");re(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=bn,n.setAttribute("data-testid","amazon-pay-button"),n}async onResize(){const e=vt(w(this,q))||0,r=Lt(w(this,q))||0,n=w(this,gt)!==e||w(this,ft)!==r;!w(this,We)&&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=bn;const a=document.createElement("style");a.textContent=eu,this.appendChild(a),await this.initializeShadowStyles(r,tu);const i=await this.containerInstanceNumber;O(this,ae,"AcceleratedCheckoutAmazonPayButtonContainer".concat(this.pageType).concat(i)),O(this,q,document.createElement("div")),w(this,q).classList.add(Oe.BUTTON),w(this,q).appendChild(n),r.appendChild(w(this,q)),(e=this.resizeObserver)==null||e.observe(w(this,q)),await this.renderFromAmazonSDK()}catch(n){E.notify(n)}}async renderFromAmazonSDK(){var e;O(this,We,!0);const r=Lt(w(this,q))||0;O(this,De,this.createContainer({containerID:w(this,ae),height:r})),this.appendChild(w(this,De));const n=vt(w(this,q))||0,a={buttonBorderRadius:"".concat(n,"px")};let i=!1;try{if(this.sdkButton=window.amazon.Pay.renderButton("#".concat(w(this,ae)),{...this.walletParams,style:a,placement:this.pageType===I.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,ae)}});O(this,ft,r),O(this,gt,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,ae),".");console.error(s),p.log({body:s,attributes:{pageType:this.pageType,containerID:w(this,ae),error:o==null?void 0:o.toString()}})}finally{O(this,We,!1)}i&&((e=this.onRendered)==null||e.call(this))}teardownAmazonButtonContainer(){var e;(e=w(this,De))==null||e.remove(),O(this,De,null)}};gt=new WeakMap,ft=new WeakMap,We=new WeakMap,q=new WeakMap,ae=new WeakMap,De=new WeakMap,d(He,"CV2_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/amazon_pay")),d(He,"EXPECTED_ERRORS",[$r,Mt,Vr]);let fr=He;const Ge=class Dh extends be{static walletName(){return"amazon_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-amazon-pay-button"}getInstrumentName(){return f.AmazonPay}getWebComponentClass(){return fr}async loadWalletSDK(){await $a({sdkUrl:Dh.SDK_URL,maxRetries:Dh.MAX_RETRIES})}getLoadEligibility(e){return e.getRootNode()instanceof ShadowRoot?{eligible:!1,reason:"Cannot load Amazon Pay within Shadow DOM"}:{eligible:!0}}};d(Ge,"MAX_RETRIES",3),d(Ge,"SDK_URL",Sr);let _r=Ge;var ir={Purple:{D50:"#4524DB",P40:"#5433EB"},Grayscale:{L0:"#FFFFFF"}},ru={16:16},Pn="gravity-font-faces",nu="\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}",au=class extends HTMLElement{static get observedAttributes(){return["disabled"]}connectedCallback(){this._loadFonts(),this._updateButton()}attributeChangedCallback(){this._updateButton()}_loadFonts(){if(document.querySelector('style[data-description="'.concat(Pn,'"], style[data-description="shop-js-font-faces"]')))return;let t=document.createElement("style");t.dataset.description=Pn,t.appendChild(document.createTextNode(nu)),document.head.appendChild(t)}_updateButton(){var t;let e=this._getOrCreateShadowRoot();e.innerHTML=ou,this.hasAttribute("disabled")&&((t=e.querySelector("button"))==null||t.setAttribute("disabled",""))}_getOrCreateShadowRoot(){return this.shadowRoot||this.attachShadow({mode:"open"}),this.shadowRoot}};function iu(){window.customElements&&(customElements.get("gravity-button")||customElements.define("gravity-button",au))}var ou="\n\n\n\n \n \n');const su=".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}",lu='.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 Va extends Error{constructor(){const e="DeliveryEstimatesResponseIsNullError";super("deliveryEstimates is null or undefined"),this.name=e}}class or extends Error{constructor(){const e="DeliveryPromiseAPIClientError";super("window.Shopify.ShopPromise.deliveryPromiseAPIClient is undefined"),this.name=e}}const cu=15,du=200;class uu{constructor(e){d(this,"storefrontAPIToken"),this.storefrontAPIToken=e}async fetchDeliveryPromise({variant:e,postalCode:r,defaultPostalCode:n,sellingPlanId:a}){const i=await za({fn:async()=>this.fetchDeliveryOptions(e,r,n,a),maxRetries:cu,delay:du,retryPolicyFn:o=>o instanceof or}).catch(o=>{if(o instanceof or)throw o;return null});if(!i)throw new Va;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 or;return l(s,this.storefrontAPIToken)}}function hu(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 pu="delivery_promise_default_address",mu="delivery_promise_postal_code";class yu extends wt{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 Ur(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(ht(mu)||"null")||null}catch(e){return null}}get defaultDeliveryAddress(){try{return JSON.parse(ht(pu)||"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 uu(this.accessToken).fetchDeliveryPromise({variant:e,postalCode:this.postalCode||"",defaultPostalCode:s,sellingPlanId:r||""}),u=Fr(this),c=(i=(a=l==null?void 0:l.selectedShippingOption)==null?void 0:a.brandedPromise)==null?void 0:i.handle;if((u==null?void 0:u.sellingPlanId)!==r||(u==null?void 0:u.variantId)!==e||c!=="shop_promise")return;this.daysToDelivery=(o=l==null?void 0:l.selectedShippingOption)==null?void 0:o.maxCalendarDaysToDelivery,this.render()}catch(s){s instanceof Va&&(this.daysToDelivery=null)}}render(){const e=hu(this.daysToDelivery,this.i18n);this.classList.add("ShopPromise"),this.innerHTML=e?'| '.concat(e," "):""}}function gu({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 fu(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 _u extends wt{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(fu(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=me()-this.iframeCreationStart,i={instrument:f.ShopPay,pageType:Dr()};S.histogram({name:D.ShopPayPersonalizedIframeLoadTime,value:a,attributes:i,unit:"ms"}),S.histogram({name:D.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=me();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=gu({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:U.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:me(),type:"animate-in"};this.iframe.contentWindow.postMessage(r,this.iframeOrigin)}}function Eu(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 Au{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 Ur(this.element,({disabled:l,variantId:u})=>{var c;this.formState={disabled:l,variantId:u},(c=this.onFormStateChange)==null||c.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{iu(),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:U.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=mt({instrumentName:f.ShopPay}),a=new DOMParser().parseFromString(n,"image/svg+xml").documentElement;this.shopLogo=a,this.isCTA?e=Hr({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,u=(l==null?void 0:l.shouldRender())||!1;if(!s){u&&this.createAndAttachIframe();return}if(!u){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 Au({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===I.ProductPage?"force_shop_pay_product":this.pageType===I.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:u}=await Ee({element:this,instrumentName:f.ShopPay,dataSource:i});if(u){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:u}}),Me(a,u);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"}),ke(a,l.message);return}if(o){p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),k({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 Pu("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"}}),Qe(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=[lu,su].join("\n"),e.appendChild(r),await this.addButtonContent(),this.disabled&&this.button.setAttribute("disabled",""),this.button.classList.add(Oe.BUTTON),this.button.onclick=n=>this.handleClick(n),e.appendChild(this.button),this.ensureLightDOMIsNotEmpty(),this.handleIframeRenderLogic(),this.onRendered()}}ie("shop-promise-product-page-content",yu),ie("shop-pay-iframe-content",_u);class Pu extends Error{constructor(){super(...arguments),d(this,"name","ShopPayButtonError")}}var wu=Object.defineProperty,Su=Object.getOwnPropertyDescriptor,Iu=(t,e,r,n)=>{for(var a=Su(e,r),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,r,a)||a);return a&&wu(e,r,a),a};class Wa extends be{static walletName(){return"shop_pay"}constructor(e){super(e)}getWebComponentName(){return"shop-pay-wallet-button"}getWebComponentClass(){return bu}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(){if(this.publicAssetsEnabled)await Xe({svg:"shop-logo.svg",instrumentName:f.ShopPay});else{const e=await import("./shop-logo-51B0aRMe.js");if(e)Le({instrumentName:f.ShopPay,logoType:"LIGHT",logoContent:e.default});else throw new Error("Shop wordmark logo is empty")}}}Iu([Gr("Shop Pay")],Wa.prototype,"getLoadEligibility");const Cu=".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 sr({cart:t,i18n:e}){var r,n,a,i;const o=Sa(t),s={label:e.translate("order_summary.subtotal"),type:"SUBTOTAL",price:Te(o.amount)},l=Pa({deliveryGroups:t.deliveryGroups,i18n:e}).map(g=>Du({lineItem:g,type:"LINE_ITEM"})),u=Ru(t,e),c=[s,...l,...u];if(t.totalDutyAmount){const g={label:e.translate("order_summary.duties"),type:"LINE_ITEM",price:Te(t.totalDutyAmount.amount)};c.push(g)}if(t.totalTaxAmount){const g={label:e.translate("order_summary.taxes"),type:"TAX",price:Te(t.totalTaxAmount.amount)};c.push(g)}let h;try{const g=(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=g?"pw-".concat(g):void 0}catch(g){}const m={totalPrice:t.totalAmount.amount,currencyCode:t.totalAmount.currencyCode,totalPriceStatus:"ESTIMATED",totalPriceLabel:e.translate("order_summary.total"),displayItems:c};return h&&(m.transactionId=h),m}function Du({lineItem:t,type:e,status:r="FINAL"}){return{label:t.label,type:e,price:t.amount,status:r}}function Ru(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 Ya=["PAYMENT_AUTHORIZATION"],Tu=Ya.concat(["SHIPPING_ADDRESS","SHIPPING_OPTION"]),Nu=["PAN_ONLY"];function vu({walletParams:t,isShippingRequired:e,hasSellingPlan:r,i18n:n,buyerCurrency:a,authJwt:i}){var o,s,l,u;let c;try{const g=(u=(l=(s=(o=window.ShopifyAnalytics)==null?void 0:o.lib)==null?void 0:s.trekkie)==null?void 0:l.defaultAttributes)==null?void 0:u.microSessionId;c=g?"pw-".concat(g):void 0}catch(g){}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"}]};c&&(h.transactionId=c);const m={...t.paymentData,shippingAddressRequired:e,shippingOptionRequired:e,transactionInfo:h};return m.merchantInfo.authJwt=i,e||delete m.shippingAddressParameters,m.callbackIntents=e?Tu:Ya,r&&Lu(m),m}function Lu(t){t.allowedPaymentMethods.forEach(e=>{e.parameters.allowedAuthMethods=e.parameters.allowedAuthMethods.filter(r=>Nu.includes(r))})}class Ou extends wa{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(u=>{E.notify(new Ot("[".concat(f.GooglePay,"] mutation result error not handled: ").concat(u),{groupingHash:"UnhandledActionError:".concat(f.GooglePay,":").concat(u)}))});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 Kn(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 Ot("[".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||(re(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:Lr,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:vr,generateAction:()=>this.decelerateOrAbort({reason:"invalid_payment_amount",instrumentName:f.GooglePay,errorOrWarning:y.InvalidPaymentAmount,checkoutUrl:e,requestType:r})},{errors:Yl,generateAction:()=>({action:"abort",effects:[()=>re(this.brandName,this.i18n)]})},{errors:sl,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:ca,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.shipping_address")}]})},{errors:la,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:Bl,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:zl,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:$l,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:Vl,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:Ul,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:Hl,generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.phone_number")}]})},{errors:Gl,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:wl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.first_name")}]})},{errors:Sl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.last_name")}]})},{errors:Il,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.address1")}]})},{errors:Cl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.address2")}]})},{errors:Dl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.city")}]})},{errors:Rl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.phone")}]})},{errors:Tl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:il,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:Nl,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:vl,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:Ll,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:Ol,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:kl,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:Ml,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:xl,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:Fl,generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.postal_code")}]})}]}mapCustomValidationFunctionErrorToAction(e){const r=Rr(e);return r?(E.notify(new Error("[".concat(f.GooglePay,"] custom validation function error: ").concat(JSON.stringify(e)))),Tr(this.i18n.translate("error_dialogs.wallet.title",{wallet:this.brandName}),r.message),{action:"abort"}):null}}function ku({deliveryGroups:t,i18n:e}){var r;const n=Fc(Aa({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 lr(t){let e=t.administrativeArea,r=t.locality;t.countryCode==="AE"&&(r=t.administrativeArea,t.administrativeArea in wn&&(e=wn[t.administrativeArea])),t.countryCode==="MX"&&e&&(e=Mu(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 wn={"\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"},Mu=t=>t==="M\xE9x."?"MEX":t==="Q.R."?"Q ROO":t.replace(/\./g,"").toUpperCase();class Sn extends Error{constructor(){super(...arguments),d(this,"name","GooglePayError")}}function qa(t){const e=t.auth;if(!(Array.isArray(e)&&e.length>0))return{result:"error",reason:"invalidAuthParams"};const r=me();for(const n of e)if(r{var g,b;const{callbackTrigger:_,shippingAddress:A,shippingOptionData:v}=m,{translate:se}=this.i18n;switch(E.leaveBreadcrumb("Google Pay onPaymentDataChanged",{callbackTrigger:_},"log"),_){case"INITIALIZE":{if(!this.cart)try{const{cart:M,customValidationError:P,decelerationReason:oe,unrecoverableError:G}=await Ee({element:this.button,instrumentName:f.GooglePay,dataSource:this.dataSource});if(P||G)return p.sheetClicked({instrument:this.name,result:"rejected",reason:P?"custom_validation_error":"unrecoverable_error"}),this.terminalCartCreationError=P?P.message:Bu(this.i18n,G),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:this.terminalCartCreationError,intent:"SHIPPING_ADDRESS"}});if(oe)return p.sheetClicked({instrument:this.name,result:"success",reason:"deceleration"}),k({checkoutUrl:(g=M==null?void 0:M.checkoutUrl)!=null?g:"",instrumentName:this.name,reason:oe}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:""}});this.cart=M,p.sheetClicked({instrument:this.name,result:"success"})}catch(M){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(M),location:"onPaymentDataChanged_INITIALIZE"}}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}let H=!1;if(A)try{return await this.handleShippingAddressChange(this.cart.id,A)}catch(M){H=!0}return{newTransactionInfo:sr({cart:this.cart,i18n:this.i18n}),...H?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:sr({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:se("shipping_methods.choose_delivery_strategy"),intent:"SHIPPING_OPTION"}};const H=await this.handleDeliveryOptionChange(v.id.split(","));return H.data?(this.cart=H.data,H.abortReason==="out_of_stock"?this.showPaymentDataRequestError({error:{intent:"SHIPPING_OPTION",reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.product.out_of_stock")}}):H.decelerationReason?(k({checkoutUrl:(b=this.cart.checkoutUrl)!=null?b:"",instrumentName:this.name,reason:H.decelerationReason}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_OPTION",reason:"OTHER_ERROR",message:""}})):this.handlePaymentDataRequestUpdate({result:H,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 m=>{var g,b,_;if(p.authorizationAttempt(this.name),Je(N.AuthorizationLatency,this.name),!this.cart)return p.googlePayNullCartOnAuthorize(),this.handlePaymentAuthorizationError();const A=(g=m.paymentMethodData.info)==null?void 0:g.billingAddress,v=m.shippingAddress,{signature:se,signedMessage:H,protocolVersion:M}=JSON.parse(m.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 P=async()=>{var L,$;const le=(L=w(this,_t))!=null?L:m.email,wh=this.isShippingRequired?{validateAddress:!0,streetAddress:lr(v)}:{};return await ze({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:this.name,emailAddress:le,abortSignal:($=w(this,te))==null?void 0:$.signal,...wh})},oe=async()=>{var L;const $=lr(A);return await Br({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{googlePayWalletContent:{billingAddress:$,signature:se,signedMessage:H,protocolVersion:M}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:$,cartClient:this.cartClient,instrumentName:this.name,hasSellingPlan:this.hasSellingPlan,abortSignal:(L=w(this,te))==null?void 0:L.signal})},G=setTimeout(()=>{var L;(L=w(this,te))==null||L.abort("[Google Pay] Timeout")},xu);try{const L=await P(),$=this.handleIntermediatePaymentAuthorizationResult({result:L,checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updateBuyerIdentity"});if($)return $;const le=await oe(),wh=this.handleIntermediatePaymentAuthorizationResult({result:le,checkoutUrl:this.cart.checkoutUrl,requestType:"onPaymentAuthorized::updateCartPayment"});if(wh)return wh;if(clearTimeout(G),(_=(b=w(this,te))==null?void 0:b.signal)!=null&&_.aborted)return this.handlePaymentAuthorizationError();const jt=await Ua({cartId:this.cart.id,token:se,cartClient:this.cartClient,instrumentName:this.name});dt({result:jt,instrument:this.name});const Lh=this.actionGenerator.mapCompletionResultToPaymentSheetAction({result:jt,checkoutUrl:jt.data&&"checkoutUrl"in jt.data&&jt.data.checkoutUrl?jt.data.checkoutUrl:this.cart.checkoutUrl,requestType:"completion"});return this.handlePaymentAuthorizationResult(Lh)}catch(L){clearTimeout(G);const{message:$}=L;return $!=null&&$.includes(Fu)?this.handlePaymentAuthorizationError({status:"timeout"}):(L instanceof pt||this.logException($),this.handlePaymentAuthorizationError())}}),d(this,"handlePaymentAuthorizationResult",async m=>{var g,b;switch((g=m.effects)==null||g.forEach(_=>_()),m.action){case"complete":return this.emitAuthorizationCompleteMetric("success"),fe(m.redirectUrl),{transactionState:"SUCCESS"};case"show_error":return this.handlePaymentAuthorizationError({error:(b=m.errors)==null?void 0:b[0]});case"decelerate":return k({checkoutUrl:m.redirectUrl,instrumentName:this.name,reason:m.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,O(this,_t,e.customerAccountEmail),O(this,te,u);const c=qa(this.walletParams);if(c.result==="error")throw E.leaveBreadcrumb("Google Pay Invalid AuthJwt detected on click",{reason:c.reason,walletParams:this.walletParams},"error"),new Sn(c.reason);O(this,Ye,c.jwt);const h={environment:this.walletParams.environment,merchantInfo:{...this.walletParams.paymentData.merchantInfo,authJwt:w(this,Ye)},paymentDataCallbacks:{onPaymentDataChanged:this.isShippingRequired?this.onPaymentDataChanged:void 0,onPaymentAuthorized:this.onPaymentAuthorized}};this.paymentsClient=new window.google.payments.api.PaymentsClient(h),this.actionGenerator=new Ou(this.i18n)}async handleClick(){if(!this.isShippingRequired)throw new J("Google Pay checkout started for digital cart");const e=vu({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,i18n:this.i18n,buyerCurrency:this.initialBuyerCurrency,authJwt:w(this,Ye)});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(u=>u()),l.action){case"update":{const u=l,{data:c,decelerationReason:h}=e;return c?h?(k({checkoutUrl:c.checkoutUrl,instrumentName:this.name,reason:h}),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:"",intent:"OFFER"}})):this.isShippingRequired&&c.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:sr({cart:c,i18n:this.i18n}),newShippingOptionParameters:this.isShippingRequired?ku({deliveryGroups:c.deliveryGroups,i18n:this.i18n}):void 0,error:(o=u.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 k({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(dt({result:e,instrument:this.name}),e.abortReason==="out_of_stock")return ge(this.i18n),{transactionState:"SUCCESS"};if(e.decelerationReason)return k({checkoutUrl:(i=(a=e.data)==null?void 0:a.checkoutUrl)!=null?i:"",instrumentName:this.name,reason:e.decelerationReason}),{transactionState:"SUCCESS"};const u=this.actionGenerator.mapMutationResultToPaymentSheetAction({result:e,checkoutUrl:r,requestType:n});switch((o=u.effects)==null||o.forEach(c=>c()),u.action){case"show_error":return this.handlePaymentAuthorizationError({error:(s=u.errors)==null?void 0:s[0]});case"abort":return this.handlePaymentAuthorizationError({error:(l=u.errors)==null?void 0:l.at(0)});case"decelerate":return this.emitAuthorizationCompleteMetric("success"),k({checkoutUrl:u.redirectUrl,instrumentName:this.name,reason:u.reason}),{transactionState:"SUCCESS"};default:return}}handleCurrencyChange(e,r){Or({currentCartTotal:r,initialBuyerCurrency:this.initialBuyerCurrency})&&k({checkoutUrl:e,instrumentName:this.name,reason:"currency_changed"})}async handleShippingAddressChange(e,r){var n,a;let i=await ze({cartClient:this.cartClient,cartId:e,streetAddress:r?lr(r):{},instrumentName:f.GooglePay,abortSignal:(n=w(this,te))==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 k({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 u;return s!=null&&s.handle&&s.deliveryMethodType!=="LOCAL"?s.handle:(u=l.filter(({deliveryMethodType:c})=>c==="SHIPPING")[0])==null?void 0:u.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=Ba({deliveryGroups:this.cart.deliveryGroups,instrumentName:f.GooglePay,selectedDeliveryOptionHandles:e});return await Fa({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:f.GooglePay,selectedDeliveryOptions:n,abortSignal:(r=w(this,te))==null?void 0:r.signal})}logException(e,{severity:r,metadata:n}={}){E.notify(new Sn(e),{severity:r!=null?r:"error",metadata:n})}emitAuthorizationCompleteMetric(e){p.authorizationComplete({instrument:this.name,measurement:Q(N.AuthorizationLatency,this.name),result:e})}}_t=new WeakMap,te=new WeakMap,Ye=new WeakMap;function Bu(t,e){switch(e){case F.VariantRequiresSellingPlan:case F.SellingPlanNotApplicable:case F.InvalidQuantity:case F.MerchandiseIdInvalid:case F.IgnoredResponseError:case F.NoResponse:return t.translate("error_dialogs.checkout.generic_error");default:return t.translate("error_dialogs.checkout.generic_error")}}const Hu={LIGHT:"light",DARK:"dark"};class Gu 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"),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");re(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 Uu({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,Cu);const{translate:r}=await this.i18n,n=this.isCTA?r("buy_with_button_content",{wallet:r("brand.google_pay")}):r("brand.google_pay"),a=zt({label:n});this.disabled&&a.setAttribute("disabled",""),a.classList.add("button",Oe.BUTTON,Hu[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=mt({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=Hr({translate:r,logoElement:a,setAriaHidden:!0});i.classList.add("content"),e.appendChild(i)}else e.classList.add("logo-only"),e.appendChild(a)}}const Ce=class Hn extends be{static walletName(){return"google_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-google-pay-button"}getInstrumentName(){return f.GooglePay}getWebComponentClass(){return Gu}async loadWalletSDK(){if(Hn.googlePaySDKPromise)return Hn.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 Hn.googlePaySDKPromise=Promise.all([r,this.loadLogos()]),Hn.googlePaySDKPromise}getLoadEligibility(){const e=qa(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(){if(this.publicAssetsEnabled)await Xe({svg:"google-pay-logo.svg",instrumentName:f.GooglePay});else{const e=await import("./google-pay-logo-BgkSiJGq.js");if(e)Le({instrumentName:f.GooglePay,logoType:"LIGHT",logoContent:e.default});else throw new Error("Google Pay logo is empty")}}async loadGooglePayLogoDark(){if(this.publicAssetsEnabled)await Xe({svg:"google-pay-logo-dark.svg",instrumentName:f.GooglePay,logoType:"DARK"});else{const e=await import("./google-pay-logo-dark-DmTdfep2.js");if(e)Le({instrumentName:f.GooglePay,logoType:"DARK",logoContent:e.default});else throw new Error("Google Pay logo dark is empty")}}};d(Ce,"googlePaySDKPromise");let Er=Ce;const zu=[Ec,hr,zr,Er,gr,_r,Wa],$u=new Map(zu.map(t=>[t.walletName(),e=>new t(e)]));function ut(t){if(!t)return null;const e=$u.get(t.name);return e?e(t):(console.debug("Can't build wallet with name ".concat(t.name)),null)}function Vu(t){return t.map(e=>ut(e)).filter(e=>e!=null)}const ja="*{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 Wu{constructor(e,r,n){this.element=e,this.apiClient=r,this.instrumentName=n}async getInitialCart(e){const r=Fr(this.element);if(!r)throw new Yu("[".concat(this.instrumentName,"] unable to find product form"),{groupingHash:"unable-to-find-product-form"});const n=ht(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 Yu extends ne{constructor(){super(...arguments),d(this,"name","ProductFormError"),d(this,"useHashPrefix",!0)}}function qu({styleId:t,styles:e,cssFileName:r}){var n,a;(a=(n=window.Shopify)==null?void 0:n.PaymentButton)!=null&&a.isStorefrontPortableWallets&&(ju({styleId:t})||Qu({styleId:t,styles:e}))}function ju({styleId:t}){const e=document.querySelector("style#".concat(t)),r=document.querySelector("link#".concat(t));return!!(e||r)}function Qu({styleId:t,styles:e}){const r=document.createElement("style");r.id=t,r.innerHTML=e,document.head.insertBefore(r,document.head.firstChild)}const X={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 In(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 Ku(t,e){for(let r=0;r<3;r++)if(t[r]!==e[r])return e[r]-t[r];return 0}function Cn(t){return[...t].sort((e,r)=>{const n=In(e.selector),a=In(r.selector);return Ku(n,a)})}const Xu=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*(>\s*)?li(?![a-zA-Z0-9_.:#-])/,Ju=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*\[role="?button"?\](?![:\w-])/,Zu=/\.additional-checkout-buttons\s*(?:div\s*)?\[role="?button"?\](?![:\w-])/,Qa=/\[data-shopify-buttoncontainer\](?![:\w-])/,Ka=/.dynamic-checkout-buttons .shopify-payment-button__button/,eh=/(?!.*\.shopify-cleanslate)\.shopify-payment-button__button(?:--branded)?(?![\w-:.#>])/,th=/\.(shopify-payment-button|shopify-payment-button__button|shopify-payment-button__button--branded)\s*\[role="?button"?\](?![:\w-])/,rh=/(?:only\s+)?(?:screen\s+and\s+)?\((?:min|max)-(?:width|height):\s*\d+px\)/,nh=[Ju,Qa,Xu,Zu,Ka],ah=[eh,th,Ka],ih=.001;function Xa(t){const e=t.pageType,r=[...document.styleSheets].filter(oh),n=[],a=[];r.forEach(P=>{try{const oe=[...P.cssRules].filter(L=>L instanceof CSSMediaRule),G=[...P.cssRules].filter(L=>L instanceof CSSStyleRule);a.push(...oe.filter(L=>rh.test(L.conditionText)).flatMap(L=>[...L.cssRules].filter($=>$ instanceof CSSStyleRule).flatMap($=>$.selectorText.split(",").map(le=>le.trim()).map(le=>({selector:le,conditionText:L.conditionText,...vn($)}))))),n.push(...G.flatMap(L=>L.selectorText.split(",").map($=>$.trim()).map($=>({selector:$,...vn(L)}))))}catch(oe){Rt()("shopify-support-debug")&&(console.debug("[shopify-support-debug] stylesheet origin: ".concat(P.href)),console.debug(oe))}});const i=e===I.ProductPage?ah:nh,o=new Set;function s(P,oe){const G=oe.selector.match(P);return G?(o.add(G[0]),!0):!1}const l=n.filter(P=>i.some(oe=>s(oe,P))).reverse(),u=a.filter(P=>i.some(oe=>s(oe,P))).reverse(),c=Rt()("shopify-support-debug");c&&console.table(Array.from(o));const h=Cn(l),m=Cn(u),g={},b=Dn(e)?document.querySelector(".cart__blocks .button"):document.querySelector(".product-form__buttons .button");b&&(g.boxShadow=getComputedStyle(b,":before").boxShadow);for(const P of h){const oe=["height","minHeight","borderRadius","marginTop"];Dn(e)&&P.selector.match(Qa)&&oe.push("justifyContent");for(const G of oe)g[G]=ch({rule:P,property:G,currentPropertyValue:g[G]})}const{height:_,borderRadius:A,minHeight:v,marginTop:se,justifyContent:H,boxShadow:M}=g;return c&&console.table([{property:"height",value:_},{property:"borderRadius",value:A},{property:"minHeight",value:v},{property:"marginTop",value:se},{property:"justifyContent",value:H},{property:"boxShadow",value:M}]),e===I.ProductPage?Nn({styles:{height:_,minHeight:v,borderRadius:A,marginTop:se,boxShadow:M},mediaRules:m,element:t}):Nn({styles:{borderRadius:A,boxShadow:M,justifyContent:H},mediaRules:m,element:t})}function Ja({element:t,styles:e,debug:r=!1}){if(!e)return;uh(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 oh(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 Dn(t){return t===I.CartPage||t===I.CartAjax}function Rn({height:t,minHeight:e}){let r=t,n=e;return(r!=null&&r.includes("var(".concat(X.buttonBlockSize))||r==="auto")&&(r=null),(n!=null&&n.includes("var(".concat(X.buttonBlockSize))||n==="auto")&&(n=null),r===n?r:n&&r?"max(".concat(r,",").concat(n,")"):r||n}function Tn({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?"":sh({mediaCondition:e,selector:r,styles:a})}function sh({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 Nn({styles:t,element:e,mediaRules:r}){const{height:n,minHeight:a,borderRadius:i,marginTop:o,justifyContent:s,boxShadow:l}=t,u=e.tagName.toLowerCase(),c=getComputedStyle(e),h=new Set;for(const g of Object.values(X))c.getPropertyValue(g)&&h.add(g);let m=Tn({existingProperties:h,selector:u,styles:{[X.buttonBlockSize]:Rn({height:n,minHeight:a}),[X.buttonBorderRadius]:i,[X.buttonBoxShadow]:l,[X.inlineAlignment]:s,"margin-top":o,display:o?"block":void 0}});return r.forEach(g=>{(g.height||g.minHeight||g.borderRadius||g.boxShadow||g.justifyContent||g.marginTop)&&(m+=Tn({existingProperties:h,mediaCondition:g.conditionText,selector:u,styles:{[X.buttonBlockSize]:Rn({height:g.height,minHeight:g.minHeight}),[X.buttonBorderRadius]:g.borderRadius,[X.buttonBoxShadow]:g.boxShadow,[X.inlineAlignment]:g.justifyContent,"margin-top":g.marginTop,display:g.marginTop?"block":void 0}}))}),m.trim()}function vn(t){return[["height"],["minHeight","min-height"],["borderRadius","border-radius"],["marginTop","margin-top"],["justifyContent","justify-content"]].reduce((e,[r,n])=>(e[r]=lh({rule:t,property:n!=null?n:r}),e),{})}function lh({rule:t,property:e}){const r=t.style.getPropertyValue(e);return t.style.getPropertyPriority(e)?"".concat(r," !important"):r||null}function ch({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 dh(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 uh(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 Ln=2e3;class On extends Error{constructor(){super(...arguments),d(this,"name","AcceleratedCheckoutError")}}var qe;const xt=class Th extends Mr{constructor(){super(...arguments),d(this,"instanceNumber",++Th.instanceCount),d(this,"pageType",I.ProductPage),d(this,"formObserver"),d(this,"dataSource"),d(this,"wrapper"),d(this,"shopPromiseEligible",!1),d(this,"didInitiateRender",!1),B(this,qe)}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&&(xr(this),p.initStarted(),qu({styleId:"shopify-accelerated-checkout-styles",styles:lc,cssFileName:"AcceleratedCheckout.css"}),this.extractStyles()),this.shopPromiseEligible=na();const n=Ke(N.ButtonDisplay,"dc:".concat(this.instanceNumber));this.i18n=Gt(),this.setupFormObserver(),this.didInitiateRender=!0;const a=await this.loadWallet(),i=a.getInstrumentName();this.apiClient=new qt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,withCarrierRates:!0,cartPrepareMigrationEnabled:this.isFlagEnabled(pa)}),this.dataSource=new Wu(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===Et)throw n;E.notify(new On("An error occurred while attempting to render AcceleratedCheckout: ".concat(n),{cause:n}))}}async attributeChangedCallback(e,r,n){r!==n&&(kr(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:hh(r),callToAction:"true",pageType:this.pageType,containerInstanceNumber:this.instanceNumber,onRendered:()=>p.instrumentLoaded({instrumentOrComponentName:r,result:"success",measurement:o()})});if(!s)throw new On("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=ja,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 u=this.getShopPromiseSlot();u&&l.appendChild(u);const c=this.getMorePaymentOptionsLink(r);c&&l.appendChild(c),this.appendChild(l)}getMorePaymentOptionsLink(e){var r,n;if(e===f.BuyItNow)return null;const a=document.createElement("more-payment-options-link");return bt(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(cr.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 Wt({page:"product",element:this})!=null}async loadWallet(){const e=this.recommendedWallet,r=sc(e,this.fallbackWallet,"AcceleratedCheckout");return await mh(this,{...r,instanceNumber:this.instanceNumber})}setupFormObserver(){this.formObserver||(this.formObserver=new Ur(this,({disabled:e,hasSellingPlan:r})=>{this.disabled=e,this.hasSellingPlan=r,this.isShippingRequired=ph(this,this.variantParams)}),this.formObserver.setupMutationObservers())}getOrCreateShadowRoot(){return w(this,qe)||O(this,qe,this.attachShadow({mode:"closed"})),w(this,qe)}extractStyles(){if(this.styleExtractorDisabled){Rt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled"),p.styleBackwardsCompatibility({usedBackwardsCompatibility:!1});return}const e=Ke(N.StyleExtract,"dc:".concat(this.instanceNumber)),r=Xa(this);r&&Ja({element:this,styles:r,debug:this.debug});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 Ar=xt;function hh(t){return t===f.BuyItNow?cr.UNBRANDED_BUTTON:cr.BRANDED_BUTTON}function ph(t,e){var r;const n=Fr(t);return!!((r=e.find(a=>a.id===Number(n==null?void 0:n.variantId)))!=null&&r.requiresShipping)}async function mh(t,{recommendedWallet:e,fallbackWallet:r,instanceNumber:n}){const a=e?ut(e):null,i=ut(r),o=async s=>{s.publicAssetsEnabled=t.publicAssetsEnabled;const l=ha({walletInstrument:s,instanceNumber:n}),u="timeout",c=await Promise.race([l,new Promise(h=>setTimeout(()=>h(u),Ln))]);if(c===u)p.instrumentSDKLoaded({instrument:s.getInstrumentName(),measurement:Ln,result:"timeout"});else if(c instanceof be)return c;return null};if(Tt(t,a)){const s=await o(a);if(s)return s}if(Tt(t,i)){const s=await o(i);if(s)return s}return ut(Yn)}ie("shopify-accelerated-checkout",Ar),ie("more-payment-options-link",Jl,{isChildCustomElement:!0});const yh=t=>{if(typeof PerformanceObserver>"u")return null;const e=new PerformanceObserver(r=>{r.getEntriesByType("resource").some(n=>n.name.includes(at.CartUpdate)||n.name.includes(at.CartChange)||n.name.includes(at.CartAdd)||n.name.includes(at.CartClear))&&t()});return e.observe({entryTypes:["resource"]}),e},gh=".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}",fh=".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 _h(t){const e=Wt({page:"cart",element:t});return ma({type:"attributes",form:e})}class Eh{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=_h(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 de)return{cart:null,errors:[y.NoResponse]};throw r}}}var je;const Ft=class Rh extends Mr{constructor(){super(),d(this,"instanceNumber",++Rh.instanceCount),d(this,"pageType",I.CartPage),d(this,"cartObserver",null),d(this,"dataSource",null),d(this,"wrapper"),d(this,"didInitiateRender",!1),B(this,je)}static get observedAttributes(){return["access-token","has-selling-plan","requires-shipping"]}createDataSource(){if(!this.cartToken){p.cartTokenMissing({reason:"createDataSource"});return}this.i18n=Gt(),this.apiClient=new qt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,withCarrierRates:!0,cartPrepareMigrationEnabled:this.isFlagEnabled(pa)}),this.dataSource=new Eh(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=Zl(this.walletConfigs,"AcceleratedCheckoutCart");if(!(r instanceof Array))throw new Y({code:"invalid-wallet-configs",message:"[AcceleratedCheckoutCart] invalid walletConfigs found"});const n=N.ButtonDisplay,a=o=>"".concat(o,":").concat(this.instanceNumber),i=await Ah(this,{walletConfigs:r,startButtonDisplayBenchmark:o=>Je(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:Q(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&&xr(this),p.initStarted(),this.cartObserver=yh(()=>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&&(kr(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 ht("cart")}async render({shouldRefetchCartAttributes:e}){var r;if(this.hasLegacyCartCookie()){p.legacyCartCookie(),this.clearUI();return}this.didInitiateRender=!0;const n=Ke(N.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=[ja,gh].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 u=document.createElement("div");u.className="wallet-cart-grid ".concat(Oe.CONTAINER),Object.entries(bh).forEach(([c,h])=>{document.querySelector(c)&&u.classList.add(h)}),a.forEach(c=>{const h=document.createElement("div"),m=document.createElement("div"),g=document.createElement("slot");g.name="button-".concat(c.name),h.className="wallet-cart-button-container",m.className="wallet-cart-button",h.setAttribute("data-testid","grid-cell"),h.appendChild(m),m.appendChild(g),u.appendChild(h),i.appendChild(c)}),this.wrapper.appendChild(u),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,je)||O(this,je,this.attachShadow({mode:"closed"})),w(this,je)}hasLegacyCartCookie(){var e;return this.cartToken?(e=this.cartToken)==null?void 0:e.match(/^[a-z0-9]+$/):!1}extractStyles(){if(this.styleExtractorDisabled){Rt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled"),p.styleBackwardsCompatibility({usedBackwardsCompatibility:!1});return}const e=Ke(N.StyleExtract,"cart:".concat(this.instanceNumber)),r=Xa(this);if(r){Ja({element:this,styles:r,debug:this.debug});const a=this.getOrCreateShadowRoot(),i=document.createElement("style");i.innerHTML=fh,a.appendChild(i)}const n=e();n&&p.styleBackwardsCompatibilityExecutionTime({measurement:n,pageType:this.pageType,stylesWritten:!!r}),p.styleBackwardsCompatibility({usedBackwardsCompatibility:!!r})}};je=new WeakMap,d(Ft,"instanceCount",0);let br=Ft;async function Ah(t,{walletConfigs:e,startButtonDisplayBenchmark:r=()=>{}}){const n=tc(t,Vu(e));return(await Promise.all(n.map(a=>(r(a.getInstrumentName()),a.publicAssetsEnabled=t.publicAssetsEnabled,ha({walletInstrument:a,instanceNumber:t.instanceNumber}))))).filter(a=>a!=null)}const bh={".additional-checkout-buttons--vertical shopify-accelerated-checkout-cart":"wallet-cart-grid--vertical",".additional-checkout-buttons--horizontal shopify-accelerated-checkout-cart":"wallet-cart-grid--horizontal"};ie("shopify-accelerated-checkout-cart",br);class Ph{getInitialCart(){throw new Error('[NoOpDataSource] Unexpected call to "getCart"')}}const Ut=class kh extends Mr{constructor(){super(...arguments),d(this,"instanceNumber",++kh.instanceCount),d(this,"pageType",I.Checkout)}get walletConfig(){return this.getAttribute("wallet-config")}async connectedCallback(){var e;super.connectedCallback();try{if(this.children.length)return;this.instanceNumber===1&&(xr(this),p.initStarted());const r=Ke(N.ButtonDisplay,"dc:".concat(this.instanceNumber)),n=ec(this.walletConfig,"WalletButton");if(!n)throw new Ai("[WalletButton] No config provided.");const a=ut(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=Gt(),this.apiClient=new qt({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 Ph,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!(!Tt(this,e)||(await e.loadWalletSDK(),!e.getPartnerSDKEligibility().eligible))}};d(Ut,"instanceCount",0);let Pr=Ut;ie("shopify-wallet-button",Pr),hi(E,{metadata:{custom:{"notify-origin":"window-onerror"}}}),pi(E,{metadata:{custom:{"notify-origin":"unhandled-promise-rejection-handler"}}}),p.startExporter();