import.meta;var ti=Object.defineProperty,ri=Object.defineProperties,ni=Object.getOwnPropertyDescriptors,_t=Object.getOwnPropertySymbols,jr=Object.prototype.hasOwnProperty,Yr=Object.prototype.propertyIsEnumerable,Yt=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Kr=t=>{throw TypeError(t)},Kt=(t,e,n)=>e in t?ti(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,w=(t,e)=>{for(var n in e||(e={}))jr.call(e,n)&&Kt(t,n,e[n]);if(_t)for(var n of _t(e))Yr.call(e,n)&&Kt(t,n,e[n]);return t},k=(t,e)=>ri(t,ni(e)),Et=(t,e)=>{var n={};for(var r in t)jr.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&_t)for(var r of _t(t))e.indexOf(r)<0&&Yr.call(t,r)&&(n[r]=t[r]);return n},c=(t,e,n)=>Kt(t,typeof e!="symbol"?e+"":e,n),Qr=(t,e,n)=>e.has(t)||Kr("Cannot "+n),C=(t,e,n)=>(Qr(t,e,"read from private field"),n?n.call(t):e.get(t)),H=(t,e,n)=>e.has(t)?Kr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),U=(t,e,n,r)=>(Qr(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Z=function(t,e){this[0]=t,this[1]=e},xe=(t,e,n)=>{var r=(o,s,l,u)=>{try{var d=n[o](s),h=(s=d.value)instanceof Z,p=d.done;Promise.resolve(h?s[0]:s).then(m=>h?r(o==="return"?o:"next",s[1]?{done:m.done,value:m.value}:m,l,u):l({value:m,done:p})).catch(m=>r("throw",m,l,u))}catch(m){u(m)}},a=o=>i[o]=s=>new Promise((l,u)=>r(o,s,l,u)),i={};return n=n.apply(t,e),i[Yt("asyncIterator")]=()=>i,a("next"),a("throw"),a("return"),i},ee=(t,e,n)=>(e=t[Yt("asyncIterator")])?e.call(t):(t=t[Yt("iterator")](),e={},n=(r,a)=>(a=t[r])&&(e[r]=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)))),n("next"),n("return"),e);const ai=":host{display:flex;align-items:center;justify-content:center}";class ii extends HTMLElement{constructor(){super(...arguments),c(this,"size","18px"),c(this,"color","gray")}connectedCallback(){var e,n;this.attachShadow({mode:"open"}),this.size=(e=this.getAttribute("size"))!=null?e:this.size,this.color=(n=this.getAttribute("color"))!=null?n:this.color,this.render();const r=document.createElement("style");r.textContent=ai,this.shadowRoot.appendChild(r)}render(){const e=this.shadowRoot,n='\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 oi="#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}.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 si(t){return Un(t).map(e=>e instanceof Error?e:new Fn("[".concat(typeof e,"] ").concat(li(e).slice(0,10240))))}function Un(t,e=0){return e>=20?[t,"Truncated cause stack"]:t instanceof Error&&t.cause?[t,...Un(t.cause,e+1)]:[t]}function li(t){var e;if(typeof t!="string")try{return(e=JSON.stringify(t))!=null?e:typeof t}catch(n){}return"".concat(t)}var Fn=class extends Error{constructor(){super(...arguments),c(this,"name","BugsnagInvalidError")}},Bn=/^\s*at .*(\S+:\d+|\(native\))/m,ci=/^(eval@)?(\[native code])?$/;function di(t){return t.stack?t.stack.match(Bn)?ui(t):hi(t):[]}function $n(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 ui(t){return t.stack.split("\n").filter(e=>!!e.match(Bn)).map(e=>{let n=e.replace(/^\s+/,"").replace(/^.*?\s+/,""),r=n.match(/ (\(.+\)$)/);n=r?n.replace(r[0],""):n;let a=$n(r?r[1]:n),i=r&&n||void 0,o=["eval",""].indexOf(a[0])>-1?void 0:a[0];return{method:i,file:o,lineNumber:a[1],columnNumber:a[2]}})}function hi(t){return t.stack.split("\n").filter(e=>!e.match(ci)).map(e=>{if(e.indexOf("@")===-1&&e.indexOf(":")===-1)return{method:e};let n=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=e.match(n),a=r&&r[1]?r[1]:void 0,i=$n(e.replace(n,""));return{method:a,file:i[0],lineNumber:i[1],columnNumber:i[2]}})}var Qt="5",pi=class{constructor(t){c(this,"breadcrumbs",[]),c(this,"apiKey"),c(this,"plugins"),c(this,"appId"),c(this,"appType"),c(this,"appVersion"),c(this,"releaseStage"),c(this,"locale"),c(this,"userAgent"),c(this,"metadata"),c(this,"persistedMetadata"),c(this,"onError"),c(this,"onPostErrorListeners",[]),c(this,"endpoints"),c(this,"session");var e,n,r;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=(n=t.plugins)!=null?n:[],this.plugins.forEach(a=>a.load(this)),this.leaveBreadcrumb("Bugsnag started",void 0,"state"),((r=t.withSessionTracking)==null||r)&&(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,n="manual"){this.breadcrumbs.push({name:t,metaData:e,type:n,timestamp:new Date().toISOString()})}notify(t,{errorClass:e,severity:n,severityType:r,handled:a=!0,metadata:i,context:o,groupingHash:s}={}){var l,u;let d=si(t),h=w(w(w({},this.metadata),this.persistedMetadata),i),p=this.buildBugsnagEvent(d,{errorClass:e,severityType:r,handled:a,severity:n,metadata:h,context:o,groupingHash:s});if(((u=(l=this.onError)==null?void 0:l.call(this,p,t))==null||u)&&this.releaseStage!=="development"){this.updateAndAppendSessionInformation(p);let m=this.sendToBugsnag(p);return this.onPostErrorListeners.forEach(E=>E(p)),m}return Promise.resolve()}addOnPostError(t){this.onPostErrorListeners.push(t)}updateAndAppendSessionInformation(t){this.session&&(t.unhandled?this.session.events.unhandled++:this.session.events.handled++,t.session=this.session)}buildBugsnagEvent(t,{errorClass:e,severity:n="error",severityType:r="handledException",handled:a,metadata:i={},context:o,groupingHash:s}){let l=new Date().toISOString(),{breadcrumbs:u,appId:d,appType:h,appVersion:p,releaseStage:m,locale:E,userAgent:_}=this,A=t.map((P,$)=>({errorClass:$===0&&e!=null?e:P.name,stacktrace:zn(d,P),message:P.message,type:"browserjs"}));return{payloadVersion:Qt,exceptions:A,severity:n,severityReason:{type:r},unhandled:!a,app:{id:d,type:h,version:p,releaseStage:m},device:{time:l,locale:E,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:n}=this,r={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":n,"Bugsnag-Payload-Version":Qt,"Bugsnag-Sent-At":(e=(t=this.session)==null?void 0:t.startedAt)!=null?e:new Date().toISOString()},body:JSON.stringify(r)})}catch(a){console.warn("[bugsnag-light] failed to start session"),console.warn(a)}}async sendToBugsnag(t){let{apiKey:e}=this,n={apiKey:e,notifier:{name:"Bugsnag JavaScript",version:"7.22.2",url:"https://github.com/bugsnag/bugsnag-js"},events:[t]};try{await fetch(this.endpoints.notify,{method:"POST",headers:{"Content-Type":"application/json","Bugsnag-Api-Key":e,"Bugsnag-Payload-Version":Qt,"Bugsnag-Sent-At":t.device.time},body:JSON.stringify(n)})}catch(r){console.warn("[bugsnag-light] failed to send an event"),console.warn(r)}}getRandomUUID(){try{return crypto.randomUUID()}catch(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})}}};function zn(t,e){let n=di(e).map(r=>{var a,i,o,s;let l=(a=r.file)==null?void 0:a.includes(t);return{method:(i=r.method)!=null?i:"",file:(o=r.file)!=null?o:"",lineNumber:(s=r.lineNumber)!=null?s:0,columnNumber:r.columnNumber,inProject:l}});if(e instanceof Fn){let r=n.findIndex(a=>a.method.endsWith("notify"));r>-1&&(n=n.slice(r+1))}return n}var mi=class xu extends Error{constructor(e){super(e),c(this,"reason"),this.name="BreadcrumbsPluginFetchError",Object.setPrototypeOf(this,xu.prototype)}};function yi(t,{metadata:e}={}){let n=window.onerror;window.onerror=(r,a,i,o,s)=>{s&&t.notify(s,{severityType:"unhandledException",handled:!1,metadata:e}),typeof n=="function"&&n.apply(window.onerror,[r,a,i,o,s])}}function gi(t,{metadata:e}={}){window.addEventListener("unhandledrejection",n=>{n.reason&&!(n.reason instanceof mi)&&t.notify(n.reason,{severityType:"unhandledPromiseRejection",handled:!1,metadata:e})})}function ut(t){try{const e=new RegExp("(^| )".concat(t,"=([^;]+)")).exec(document.cookie);if(e){const n=e[2];try{return decodeURIComponent(n)}catch(r){return n}}return null}catch(e){return null}}const ur={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"},fi={DARK:"apple-pay--dark",LIGHT:"apple-pay--light"},bi=44,wi="_shopify_y",Gn=6,_i="discount_code",Sr="https://static-na.payments-amazon.com",Pr="".concat(Sr,"/checkout.js"),Vn="https://www.paypal.com",qn="https://pay.google.com",Ee={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"},Pt="VALIDATION_CUSTOM",Wn="portable-wallets",ke={BUTTON:"accelerated-checkout-button",CONTAINER:"accelerated-checkout-button-container"},jn="unknown",Yn={name:"buy_it_now",wallet_params:{}};function Kn(t){try{return!t.toString().includes("[native code]")}catch(e){return!0}}const Jt=new Map,Ei={checkDuplicate({errorClass:t,message:e}){if(Jt.has(t)){const n=Jt.get(t);if(n.has(e))return!0;n.add(e)}else Jt.set(t,new Set([e]));return!1},reset(){}},gt="DeveloperError";class X extends Error{constructor({code:e,message:n},r){const a="An unexpected error happened likely because of customizations made to HTML/JavaScript on this site ".concat(n);super("[".concat(e,"]: ").concat(a),r),c(this,"name",gt),c(this,"code"),this.code=e}}const Qn="SilencedError";class ae extends Error{constructor(){super(...arguments),c(this,"name",Qn)}}class Ai extends Error{constructor(){super(...arguments),c(this,"name","MissingConfigError")}}class Ae extends Error{constructor(){super(...arguments),c(this,"name","NoResponseError")}}class Ir extends Error{constructor(e,{errorDetails:n,groupingHash:r}){super(e),c(this,"errorDetails"),c(this,"groupingHash"),this.name="GraphQLResponseError",this.errorDetails=n,this.groupingHash=r}}const Jn="IgnoredGraphQLResponseError";class hr extends Ir{constructor(e,{reason:n,errorDetails:r}){super(e,{errorDetails:r}),c(this,"reason"),this.name=Jn,this.reason=n}}class Xn extends Error{constructor(e,n){var r=n,{groupingHash:a}=r,i=Et(r,["groupingHash"]);super(e,i),c(this,"groupingHash"),this.groupingHash=a}}function R(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var Ci=0;function fe(t){return"__private_"+Ci+++"_"+t}function Ft(t){return Object.entries(t).map(([e,n])=>({key:e,value:{stringValue:String(n)}}))}function Si(t){return Object.entries(t).map(([e,n])=>({key:e,value:Zn(n)}))}function Zn(t){if(Array.isArray(t))return{arrayValue:{values:t.map(e=>Zn(e))}};switch(typeof t){case"boolean":return{boolValue:!!t};case"number":return{doubleValue:Number(t)};case"string":default:return{stringValue:String(t)}}}const vr=1,Pi=Ii(5,2,12);function Ii(t,e,n){const r=[0];for(let a=0;a{switch(r.attributes=w(w({},R(this,Q)[Q]),r.attributes),r.type){case"histogram":Di(e,r);break;case"exponential_histogram":Ri(e,r);break;case"counter":Ti(e,r);break;case"gauge":Ni(e,r);break}});const n=Object.values(e);n.length!==0&&(R(this,W)[W]=[],await R(this,Ce)[Ce].exportMetrics(n))}async exportLogs(){const e=R(this,Se)[Se].map(n=>{const r={timeUnixNano:n.timeUnixNano,observedTimeUnixNano:n.timeUnixNano,attributes:Si(w(w({},R(this,Q)[Q]),n.attributes))};return n.body&&(r.body={stringValue:n.body}),r});e.length!==0&&(R(this,Se)[Se]=[],await R(this,Ce)[Ce].exportLogs(e))}}function Di(t,e){var n;const{name:r,value:a,unit:i,timeUnixNano:o,attributes:s}=e,l=(n=e.bounds)!==null&&n!==void 0?n:Pi,u=new Array(l.length+1).fill(0);t[r]||(t[r]={name:r,unit:i||"1",histogram:{aggregationTemporality:vr,dataPoints:[]}});for(let d=0;d0?h:0,bucketCounts:r>0?[1]:[]};t[n].exponentialHistogram.dataPoints.push({attributes:Ft(o!=null?o:{}),startTimeUnixNano:i,timeUnixNano:i,count:1,sum:l,scale:u,zeroCount:p,positive:E,negative:m,min:l,max:l,zeroThreshold:0})}function Ti(t,e){const{name:n,value:r,unit:a,timeUnixNano:i,attributes:o}=e;t[n]||(t[n]={name:n,unit:a||"1",sum:{aggregationTemporality:vr,isMonotonic:!0,dataPoints:[]}}),t[n].sum.dataPoints.push({startTimeUnixNano:i,timeUnixNano:i,asDouble:r,attributes:Ft(o!=null?o:{})})}function Ni(t,e){const{name:n,value:r,unit:a,timeUnixNano:i,attributes:o}=e;t[n]||(t[n]={name:n,unit:a||"1",gauge:{dataPoints:[]}}),t[n].gauge.dataPoints.push({startTimeUnixNano:i,timeUnixNano:i,asDouble:r,attributes:Ft(o!=null?o:{})})}var et=fe("url"),Pe=fe("serviceName"),tt=fe("logger"),rt=fe("fetchFn");class ki{constructor(e,n,r){Object.defineProperty(this,et,{writable:!0,value:void 0}),Object.defineProperty(this,Pe,{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,Pe)[Pe]=n,R(this,tt)[tt]=r==null?void 0:r.logger,R(this,rt)[rt]=r==null?void 0:r.fetchFn}async exportMetrics(e){const n={resourceMetrics:[{resource:{attributes:[{key:"service.name",value:{stringValue:R(this,Pe)[Pe]}}]},scopeMetrics:[{scope:{name:"open-telemetry-mini-client",version:"1.1.0",attributes:[]},metrics:e}]}]};await this.exportTo(n,"/v1/metrics")}async exportLogs(e){const n={resourceLogs:[{resource:{attributes:[{key:"service.name",value:{stringValue:R(this,Pe)[Pe]}}]},scopeLogs:[{scope:{name:"open-telemetry-mini-client",version:"1.1.0",attributes:[]},logRecords:e}]}]};await this.exportTo(n,"/v1/logs")}async exportTo(e,n){var r;const a=await this.exporterFetch()("".concat(R(this,et)[et]).concat(n),{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if((r=R(this,tt)[tt])===null||r===void 0||r.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,n){super(e),this.metadata=void 0,this.name="OpenTelemetryClientError",this.metadata=n}}const Li="https://otlp-http-production.shopifysvc.com",Oi="portable_wallets";var Ve;class xi{constructor(e){H(this,Ve),U(this,Ve,e)}async exportMetrics(e){var n;try{await C(this,Ve).exportMetrics(e)}catch(r){if(r instanceof st){const a=(n=r.metadata)==null?void 0:n.retryAfter;if(a){await new Promise(i=>{setTimeout(()=>{this.exportMetrics(e),i()},a.seconds*1e3)});return}}throw new Jr("Unable to export metrics",{cause:r})}}async exportLogs(e){var n;try{await C(this,Ve).exportLogs(e)}catch(r){if(r instanceof st){const a=(n=r.metadata)==null?void 0:n.retryAfter;if(a){await new Promise(i=>{setTimeout(()=>{this.exportLogs(e),i()},a.seconds*1e3)});return}}throw new Jr("Unable to export logs",{cause:r})}}}Ve=new WeakMap;const Mi=new ki(Li,Oi),Ui=new xi(Mi),S=new vi({exporter:Ui}),ea="TelemetryExportError";class Jr extends Error{constructor(){super(...arguments),c(this,"name",ea)}}const Bt="GraphQL Client",Xr=0,Zr=3,ta="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",ra="Response returned unexpected Content-Type:",na="An unknown error has occurred. The API did not return a data object or any errors in its response.",pr={json:"application/json",multipart:"multipart/mixed"},en="X-SDK-Variant",tn="X-SDK-Version",Fi="shopify-graphql-client",Bi="1.4.1",aa=1e3,$i=[429,503],ia=/@(defer)\b/i,rn="\r\n",zi=/boundary="?([^=";]+)"?/i,nn=rn+rn;function me(t,e=Bt){return t.startsWith("".concat(e))?t:"".concat(e,": ").concat(t)}function Xe(t){return t instanceof Error?t.message:JSON.stringify(t)}function oa(t){return t instanceof Error&&t.cause?t.cause:void 0}function sa(t){return t.flatMap(({errors:e})=>e!=null?e:[])}function la({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||eZr))throw new Error("".concat(t,': The provided "retries" value (').concat(e,") is invalid - it cannot be less than ").concat(Xr," or greater than ").concat(Zr))}function q(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}function ca(t,e){if(t.length===0)return e;const n={[t.pop()]:e};return t.length===0?n:ca(t,n)}function da(t,e){return Object.keys(e||{}).reduce((n,r)=>(typeof e[r]=="object"||Array.isArray(e[r]))&&t[r]?(n[r]=da(t[r],e[r]),n):(n[r]=e[r],n),Array.isArray(t)?[...t]:w({},t))}function ua([t,...e]){return e.reduce(da,w({},t))}function Hi({clientLogger:t,customFetchApi:e=fetch,client:n=Bt,defaultRetryWaitTime:r=aa,retriableCodes:a=$i}){const i=async(o,s,l)=>{const u=s+1,d=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<=d)throw new Error;const p=(h==null?void 0:h.headers.get("X-Shopify-API-Deprecated-Reason"))||"";return p&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:o,deprecationNotice:p}}),h}catch(p){if(u<=d){const m=h==null?void 0:h.headers.get("Retry-After");return await Gi(m?parseInt(m,10):r),t({type:"HTTP-Retry",content:{requestParams:o,lastResponse:h,retryAttempt:s,maxRetries:l}}),i(o,u,l)}throw new Error(me("".concat(l>0?"Attempted maximum number of ".concat(l," network retries. Last message - "):"").concat(Xe(p)),n))}};return i}async function Gi(t){return new Promise(e=>setTimeout(e,t))}function Vi({headers:t,url:e,customFetchApi:n=fetch,retries:r=0,logger:a}){la({client:Bt,retries:r});const i={headers:t,url:e,retries:r},o=qi(a),s=Hi({customFetchApi:n,clientLogger:o,defaultRetryWaitTime:aa}),l=Wi(s,i),u=ji(l),d=eo(l);return{config:i,fetch:l,request:u,requestStream:d}}function qi(t){return e=>{t&&t(e)}}async function ha(t){const{errors:e,data:n,extensions:r}=await t.json();return w(k(w(w({},q("data",n)),q("extensions",r)),{headers:t.headers}),e||!n?{errors:k(w({networkStatusCode:t.status,message:me(e?ta:na)},q("graphQLErrors",e)),{response:t})}:{})}function Wi(t,{url:e,headers:n,retries:r}){return async(a,i={})=>{const{variables:o,headers:s,url:l,retries:u,keepalive:d,signal:h}=i,p=JSON.stringify({query:a,variables:o});la({client:Bt,retries:u});const m=Object.entries(w(w({},n),s)).reduce((_,[A,P])=>(_[A]=Array.isArray(P)?P.join(", "):P.toString(),_),{});!m[en]&&!m[tn]&&(m[en]=Fi,m[tn]=Bi);const E=[l!=null?l:e,{method:"POST",headers:m,body:p,signal:h,keepalive:d}];return t(E,1,u!=null?u:r)}}function ji(t){return async(...e)=>{if(ia.test(e[0]))throw new Error(me("This operation will result in a streamable response - use requestStream() instead."));let n=null;try{n=await t(...e);const{status:r,statusText:a}=n,i=n.headers.get("content-type")||"";return n.ok?i.includes(pr.json)?await ha(n):{errors:{networkStatusCode:r,message:me("".concat(ra," ").concat(i)),response:n}}:{errors:{networkStatusCode:r,message:me(a),response:n}}}catch(r){return{errors:w({message:Xe(r)},n==null?{}:{networkStatusCode:n.status,response:n})}}}}function Yi(t){return xe(this,null,function*(){const e=new TextDecoder;if(t.body[Symbol.asyncIterator])try{for(var n=ee(t.body),r,a,i;r=!(a=yield new Z(n.next())).done;r=!1){const o=a.value;yield e.decode(o)}}catch(o){i=[o]}finally{try{r&&(a=n.return)&&(yield new Z(a.call(n)))}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 Ki(t,e){return{[Symbol.asyncIterator](){return xe(this,null,function*(){try{let o="";try{for(var n=ee(t),r,a,i;r=!(a=yield new Z(n.next())).done;r=!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(d=>d.trim().length>0).map(d=>d.slice(d.indexOf(nn)+nn.length).trim());u.length>0&&(yield u),o=o.slice(l+e.length),o.trim()==="--"&&(o="")}}}catch(s){i=[s]}finally{try{r&&(a=n.return)&&(yield new Z(a.call(n)))}finally{if(i)throw i[0]}}}catch(o){throw new Error("Error occured while processing stream payload - ".concat(Xe(o)))}})}}}function Qi(t){return{[Symbol.asyncIterator](){return xe(this,null,function*(){const e=yield new Z(ha(t));yield k(w({},e),{hasNext:!1})})}}}function Ji(t){return t.map(e=>{try{return JSON.parse(e)}catch(n){throw new Error("Error in parsing multipart response - ".concat(Xe(n)))}}).map(e=>{const{data:n,incremental:r,hasNext:a,extensions:i,errors:o}=e;if(!r)return k(w(w({data:n||{}},q("errors",o)),q("extensions",i)),{hasNext:a});const s=r.map(({data:l,path:u,errors:d})=>w({data:l&&u?ca(u,l):{}},q("errors",d)));return k(w({data:s.length===1?s[0].data:ua([...s.map(({data:l})=>l)])},q("errors",sa(s))),{hasNext:a})})}function Xi(t,e){if(t.length>0)throw new Error(ta,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(na)}function Zi(t,e){var n,r;const a=(e!=null?e:"").match(zi),i="--".concat(a?a[1]:"-");if(!((n=t.body)!=null&&n.getReader)&&!((r=t.body)!=null&&r[Symbol.asyncIterator]))throw new Error("API multipart response did not return an iterable body",{cause:t});const o=Yi(t);let s={},l;return{[Symbol.asyncIterator](){return xe(this,null,function*(){var u,d;try{let _=!0;try{for(var h=ee(Ki(o,i)),p,m,E;p=!(m=yield new Z(h.next())).done;p=!1){const A=m.value,P=Ji(A);l=(d=(u=P.find(M=>M.extensions))==null?void 0:u.extensions)!=null?d:l;const $=sa(P);s=ua([s,...P.map(({data:M})=>M)]),_=P.slice(-1)[0].hasNext,Xi($,s),yield k(w(w({},q("data",s)),q("extensions",l)),{hasNext:_})}}catch(A){E=[A]}finally{try{p&&(m=h.return)&&(yield new Z(m.call(h)))}finally{if(E)throw E[0]}}if(_)throw new Error("Response stream terminated unexpectedly")}catch(_){const A=oa(_);yield k(w(w({},q("data",s)),q("extensions",l)),{errors:k(w({message:me(Xe(_)),networkStatusCode:t.status},q("graphQLErrors",A==null?void 0:A.graphQLErrors)),{response:t}),hasNext:!1})}})}}}function eo(t){return async(...e)=>{if(!ia.test(e[0]))throw new Error(me("This operation does not result in a streamable response - use request() instead."));try{const n=await t(...e),{statusText:r}=n;if(!n.ok)throw new Error(r,{cause:n});const a=n.headers.get("content-type")||"";switch(!0){case a.includes(pr.json):return Qi(n);case a.includes(pr.multipart):return Zi(n,a);default:throw new Error("".concat(ra," ").concat(a),{cause:n})}}catch(n){return{[Symbol.asyncIterator](){return xe(this,null,function*(){const r=oa(n);yield{errors:w(w({message:me(Xe(n))},q("networkStatusCode",r==null?void 0:r.status)),q("response",r)),hasNext:!1}})}}}}}var g=(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(Pt),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.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.NewTaxMustBeAccepted="TAX_NEW_TAX_MUST_BE_ACCEPTED",t.MerchandiseExpectedPriceMismatch="MERCHANDISE_EXPECTED_PRICE_MISMATCH",t.InvalidPaymentApplePayBillingAddress="INVALID_PAYMENT: payment.walletPaymentMethod.applePayWalletContent.billingAddress",t.InvalidPaymentGooglePayBillingAddress="INVALID_PAYMENT: payment.walletPaymentMethod.googlePayWalletContent.billingAddress",t.InvalidPaymentBillingAddress="INVALID_PAYMENT: payment.freePaymentMethod.billingAddress",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))(g||{});const to=["DELIVERY_FIRST_NAME_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName"],ro=["DELIVERY_FIRST_NAME_INVALID","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName"],no=["DELIVERY_LAST_NAME_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName"],ao=["DELIVERY_LAST_NAME_INVALID","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName"],io=["DELIVERY_ADDRESS1_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1"],oo=["DELIVERY_ADDRESS2_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2"],so=["DELIVERY_CITY_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city"],lo=["DELIVERY_POSTAL_CODE_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],pa=["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"],co=["DELIVERY_PHONE_NUMBER_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],uo=["INVALID: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country","Variable $buyerIdentity of type CartBuyerIdentityInput! was provided invalid value for countryCode"],ho=["DELIVERY_PHONE_NUMBER_INVALID","INVALID: buyerIdentity.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],ma=["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"],ya=["INVALID_PAYMENT: amount","INVALID_PAYMENT: payment.amount","INVALID_PAYMENT: payment"],Dr=["TAX_NEW_TAX_MUST_BE_ACCEPTED","PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"],po=["DELIVERY_DELIVERY_LINE_DETAIL_CHANGED","DELIVERY_LOCAL_PICKUP_DELIVERY_LINE_DETAIL_CHANGED"],mo=["INVALID_PAYMENT: payment.freePaymentMethod.billingAddress","INVALID_PAYMENT: payment.walletPaymentMethod.applePayWalletContent.billingAddress"],ga=["MERCHANDISE_NOT_APPLICABLE","MERCHANDISE_PRODUCT_VARIANT_NOT_FOUND","MERCHANDISE_NOT_FOUND","MERCHANDISE_PRODUCT_NOT_PUBLISHED"],fa=["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"],yo="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}}}}}",go="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}",fo="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}",bo="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}",wo="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}",_o="mutation applePaySessionCreate($validationUrl:URL!){applePaySessionCreate(validationUrl:$validationUrl){...@defer{applePaySession{body}}}}",Eo="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}}}}}}",Ao="mutation PayPalTokenCreate($cartId:ID!){paypalTokenCreate(cartId:$cartId){...@defer{paypalToken{token}}}}",Co="query cartQuery($id:ID!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false)@inContext(country:$country language:$language){cart(id:$id){...@defer(if:$withCarrierRates){...CartParts}}}",So="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}}}}}}}",Po="query subscriptionPolicyQuery($country:CountryCode$language:LanguageCode)@inContext(country:$country language:$language){shop{subscriptionPolicy(sanitized:true){body}}}",Io="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}",At="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}}}}}}",Xt="fragment CartErrorParts on CartUserError{message field code}",an="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}}}}",vo="mutation prepareCart($cartId:ID!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false$prepareCart:Boolean=true)@inContext(country:$country language:$language){...PreparedCartFragment}",Do="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}}}}",Ro="mutation cartRemovePersonalData($cartId:ID!){cartRemovePersonalData(cartId:$cartId){errors:userErrors{...CartErrorParts}warnings:warnings{...on CartWarning{code}}}}";async function To(t,e){var n,r;if(!e.errors)return;const a=Mo(e.errors,t),i=await xo(e.errors.response),o=((r=(n=e.errors.response)==null?void 0:n.headers)==null?void 0:r.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 No=[/API multipart response did not return an iterable body/,/GraphQL Client: Response returned unexpected Content-Type:/,/Internal error/,/Carrier-calculated rates through @defer is temporarily unavailable/],ko=[/signal is aborted/i,/fetch is aborted/i,/operation was aborted/i,/\[Apple Pay\] Payment sheet cancelled/],Lo=[/timed?.out/i,/error occured while processing stream payload/i,/response stream terminated/i];function Oo(t,{hasBeenVisible:e=!1}={}){if(t.statusCode&&t.statusCode!==200)return{isIgnorable:!0,reason:"statusCode-".concat(t.statusCode)};if(t.message){if(Lo.some(n=>n.test(t.message)))return{isIgnorable:!0,reason:"timeout"};if(ko.some(n=>n.test(t.message)))return{isIgnorable:!0,reason:"abort"};if(No.some(n=>n.test(t.message)))return{isIgnorable:!0,reason:"message"}}return e?{isIgnorable:!1,reason:void 0}:{isIgnorable:!0,reason:"component-not-visible"}}async function xo(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 Mo(t,e){var n,r;if(!t)return"";const a=(r=(n=t.graphQLErrors)==null?void 0:n.map(s=>s.message).join(", "))!=null?r:"",i="".concat(t.message).concat(a.length>0?" - ".concat(a):""),o=t.networkStatusCode?"with status ".concat(t.networkStatusCode," => ").concat(i):"=> ".concat(i);return"GraphQL response error for ".concat(e,": ").concat(o)}function Uo(t){const{operationName:e,errorCodes:n}=t,r=n.join("-")||"unknown";return"".concat(e,"-").concat(r)}const on="UNKNOWN";function Fo({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:(n,r)=>(b.leaveBreadcrumb("Request ".concat((r==null?void 0:r.method)||on,": ").concat(n),{url:n,method:r==null?void 0:r.method},"request"),fetch(n,r)),logger:n=>{try{if(n.type==="HTTP-Response"){const[r,a]=n.content.requestParams,{status:i,statusText:o,headers:s,type:l}=n.content.response;b.leaveBreadcrumb("Response ".concat((a==null?void 0:a.method)||on,": ").concat(r),{statusCode:i,statusText:o,responseHeaders:Bo(s),responseType:l,url:r,method:a==null?void 0:a.method,headers:a==null?void 0:a.headers,body:a==null?void 0:a.body},"log")}}catch(r){}}}}function Bo(t){if("fromEntries"in Object)return Object.fromEntries(t);const e={};for(const[n,r]of t.entries())e[n]=r;return e}var 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||{}),ne=(t=>(t.InvalidQuantity="InvalidQuantity",t.VariantRequiresSellingPlan="VariantRequiresSellingPlan",t.SellingPlanNotApplicable="SellingPlanNotApplicable",t))(ne||{}),v=(t=>(t.CartPage="cart_page",t.CartAjax="cart_ajax",t.ProductPage="product",t.Checkout="checkout",t.Unknown="unknown",t))(v||{}),at=(t=>(t.CartChange="/cart/change",t.CartUpdate="/cart/update",t.CartAdd="/cart/add",t.CartClear="/cart/clear",t))(at||{}),Te=(t=>(t.OneTimePurchase="ONE_TIME_PURCHASE",t.Subscription="SUBSCRIPTION",t))(Te||{});function sn(t){const e=document.querySelectorAll("shopify-accelerated-checkout .shopify-payment-button__skeleton, shopify-accelerated-checkout-cart .wallet-cart-button__skeleton"),n=document.getElementById("shopify-buyer-consent");for(let r=0;re.toString(16)).join("")}function Wo(t,e=!0){return t&&Object.keys(t).length&&e?Object.keys(t).map(n=>({[jo(n)]:t[n]})).reduce((n,r)=>cn(cn({},n),r)):t}function jo(t){return t.split(/(?=[A-Z])/).join("_").toLowerCase()}function Yo(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||qo()).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 Ko({endpoint:t,event:e,keepalive:n}){var r,a,i,o,s;const l=e.metadata?{clientMessageId:(r=e.metadata)===null||r===void 0?void 0:r.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:Go+Vo,{method:"post",headers:Yo(e.metadata),body:JSON.stringify({schema_id:e.schemaId,payload:e.payload,metadata:l&&Wo(l,!0)}),keepalive:n})}const Qo="2.1",Jo="3",Zt={NO_VALUE:"",ACCEPTED:"1",DECLINED:"0"},Y={PREFERENCES:"p",ANALYTICS:"a",MARKETING:"m",SALE_OF_DATA:"t"},de={MARKETING:"m",ANALYTICS:"a",PREFERENCES:"p",SALE_OF_DATA:"s"},Xo=()=>typeof __CtaTestEnv__>"u"?!1:__CtaTestEnv__==="true",Zo="_tracking_consent";function dn(t){try{return decodeURIComponent(t)}catch(e){return""}}function wa(t,e=!1){const n=document.cookie?document.cookie.split("; "):[];for(let r=0;rm.charCodeAt(0).toString(16).padStart(2,"0")).join("");l=[8,13,18,23].reduce((m,E)=>m.slice(0,E)+"-"+m.slice(E),p)}function u(h){const p=n.split(".")[0];return p.includes(h.toLowerCase())?Zt.DECLINED:p.includes(h.toUpperCase())?Zt.ACCEPTED:Zt.NO_VALUE}function d(h){return n.includes(h.replace("t","s").toUpperCase())}return{v:Jo,con:{CMP:{[de.ANALYTICS]:u(de.ANALYTICS),[de.PREFERENCES]:u(de.PREFERENCES),[de.MARKETING]:u(de.MARKETING),[de.SALE_OF_DATA]:u(de.SALE_OF_DATA)}},region:r||"",cus:s,purposes:{[Y.ANALYTICS]:d(Y.ANALYTICS),[Y.PREFERENCES]:d(Y.PREFERENCES),[Y.MARKETING]:d(Y.MARKETING),[Y.SALE_OF_DATA]:d(Y.SALE_OF_DATA)},sale_of_data_region:i=="t",display_banner:a=="t",consent_id:l}}function $t(t){const e=as();if(!e||!e.purposes)return!0;const n=e.purposes[t];return typeof n=="boolean"?n:!0}function ls(){return $t(Y.PREFERENCES)}function cs(){return $t(Y.ANALYTICS)}function ds(){return $t(Y.MARKETING)}function us(){return $t(Y.SALE_OF_DATA)}function hs(){return cs()}function ps(){return ls()}function ms(){return ds()}function ys(){return us()}function gs(){return ms()}function fs(){return hs()}function bs(){return ps()}function ws(){return ys()}function _s(){const t=[];return fs()&&t.push("analytics"),gs()&&t.push("marketing"),ws()&&t.push("sale_of_data"),bs()&&t.push("preferences"),t}function Es(t,e){switch(e){case"v1":{const n=_s();return k(w({},t),{metadata:k(w({},t==null?void 0:t.metadata),{consent:n,consent_provider:"consent-tracking-api",consent_version:e})})}default:throw new Rr(e)}}class Rr extends Error{constructor(e){super("Version ".concat(e," is not supported by the consent-tracking-api provider")),this.name="MonorailConsentTrackingApiProviderVersionError",Object.setPrototypeOf(this,Rr.prototype)}}var I=(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.AmazonAdExperimentAcceleratedCheckoutButtonClicked="portable_wallets_amazon_ad_experiment_accelerated_checkout_button_clicked",t.AmazonAdExperimentAcceleratedCheckoutButtonSetup="portable_wallets_amazon_ad_experiment_accelerated_checkout_button_setup",t.AmazonAdExperimentPaymentButtonHidden="portable_wallets_amazon_ad_experiment_payment_button_hidden",t.AmazonAdExperimentRecommendedWalletOverriden="portable_wallets_amazon_ad_experiment_recommended_wallet_overriden",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))(I||{}),De=(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))(De||{});const As=["Chrome-Lighthouse","Googlebot"];function Cs(){const t=navigator.userAgent;return As.some(e=>t.includes(e))}async function Ss(t){if(Cs())return;const e=Es(t,"v1");let n;try{n=await Ko({event:e})}catch(r){}if(!(n!=null&&n.ok))try{S.counter({name:I.MonorailProduceError,value:1,attributes:{schemaId:e.schemaId}})}catch(r){}}const er="shopify_wallet_checkout_track/6.2";async function V(t){var e,n,r,a,i,o,s;const l=await Ps();if(!l)return;const u={schemaId:er,payload:{app_name:"storefront",page_type:hl(),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:(n=l==null?void 0:l.visitToken)!=null?n:"",micro_session_id:(r=l==null?void 0:l.microSessionId)!=null?r:"",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}};b.leaveBreadcrumb("monorail event produced to ".concat(er),{schemaId:er,payload:t});try{await Ss(u)}catch(d){b.notify(new Is("Failed to send monorail event: ".concat(d),{cause:d}),{metadata:{request:{monorail:{payload:JSON.stringify(u)}}}})}}async function Ps(){var t,e,n,r,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=(r=(n=window.ShopifyAnalytics)==null?void 0:n.lib)==null?void 0:r.trekkie)==null?void 0:a.defaultAttributes}class Is extends Error{constructor(){super(...arguments),c(this,"name","MonorailError")}}var B=(t=>(t.CartInitCalled="portable_wallets_cart_init_called",t.ClickSheetCancelled="portable_wallets_instrument_click_sheet_cancelled",t.ClickSheetFailed="portable_wallets_instrument_click_sheet_failure",t.ClickSheetSuccess="portable_wallets_instrument_click_sheet_success",t.SheetFailed="portable_wallets_instrument_sheet_failed",t.AuthorizationAttempt="portable_wallets_authorization_attempt",t.AuthorizationComplete="portable_wallets_authorization_complete",t.InitCalled="portable_wallets_init_called",t.InitFailed="portable_wallets_init_failed",t.InitSuccess="portable_wallets_init_success",t.UpdateFailed="portable_wallets_instrument_update_failed",t.InstrumentLoaded="portable_wallets_instrument_loaded",t.InstrumentLoadFailed="portable_wallets_instrument_load_failed",t.FirstVisible="portable_wallets_first_visible",t.FirstVisibleNotAvailable="portable_wallets_first_visible_not_available",t.SheetLoaded="portable_wallets_sheet_loaded",t.ShopPayButtonInView="portable_wallets_shop_pay_button_in_view",t))(B||{});const un={[v.Checkout]:"bwp_checkout_widget_click",[v.CartAjax]:"bwp_cart_widget_click",[v.CartPage]:"bwp_cart_widget_click",[v.ProductPage]:"bwp_widget_click",[v.Unknown]:"bwp_widget_click"};function vs({apiClientId:t,skus:e,pageType:n}){var r;if(!((r=window.Shopify)!=null&&r.analytics))return;const a=n&&un[n]||"bwp_widget_click";a===un[v.Checkout]&&window.Shopify.analytics.publish("shopify:app:pixels:load:".concat(t),{},{sendTo:"PIXEL-LOADER"}),e&&window.Shopify.analytics.publish(a,{skus:e},{sendTo:t})}let zt=Ds();function Ds(){return{shopId:jn,debug:!1,pageType:v.Unknown}}function Rs(t){Object.assign(zt,t)}function Tr(){const t=zt,{debug:e}=t;return Et(t,["debug"])}function Ts(){return zt.debug}function It(){return zt.pageType}function N(t){return w({pageType:It()},t)}function Ns(){const t=It()===v.CartPage?B.CartInitCalled:B.InitCalled;V({event:t})}function ks(t){var e,n;const r=t?"Failed":"Success",a=t&&Xs(t)?"[".concat(t.name,"]: ").concat(t.code):void 0,i=B["Init".concat(r)];V({event:i,eventSubtype:a}),S.counter({name:I.InitCompleted,value:1,attributes:N({result:r.toLowerCase(),eventType:a,recoveredFailure:!!((n=(e=window.Shopify)==null?void 0:e.PaymentButton)!=null&&n.failedToLoad)})})}function Ls({instrumentOrComponentName:t,result:e,measurement:n}){V({event:e==="success"?B.InstrumentLoaded:B.InstrumentLoadFailed,instrumentId:t,ttl:n}),n!=null&&(S.histogram({name:I.InstrumentLoadTime,value:n,attributes:N({instrument:t}),unit:"ms"}),S.histogram({name:I.InstrumentLoadTimeFromPageLoad,value:window.performance.now(),attributes:N({instrument:t}),unit:"ms"}))}function Os({instrument:t,measurement:e,result:n}){const r=n==="success"?De.InstrumentSdkLoaded:De.InstrumentSdkFailed;V({event:r,instrumentId:t,ttl:e,errorReason:n==="success"?void 0:n}),e!=null&&S.histogram({name:De.InstrumentSdkLoaded,value:e,attributes:N({instrument:t,result:n}),unit:"ms"})}function xs({instrument:t,result:e,reason:n}){const r=e==="success"?De.InstrumentSdkEligible:De.InstrumentSdkNotEligible;V({event:r,instrumentId:t}),S.counter({name:De.InstrumentSdkEligible,value:1,attributes:N({instrument:t,reason:n,result:e})})}function Ms({instrument:t,result:e,reason:n}){S.counter({name:I.InstrumentLoadEligibility,value:1,attributes:N({instrument:t,result:e,reason:n})})}function Us(t){S.counter({name:I.ButtonRender,value:1,attributes:N({result:"success",instrument:t})})}function Fs(t){S.counter({name:I.ButtonRender,value:1,attributes:N({result:"failed",instrument:t})})}function Bs({instrument:t,result:e,webPixelMetaData:n}){V({event:e==="success"?B.ClickSheetSuccess:B.ClickSheetFailed,instrumentId:t}),S.counter({name:I.SheetClicked,value:1,attributes:N({instrument:t,result:e})}),t===f.BuyWithPrime&&n&&vs(n)}function $s(t,e){V({event:"".concat(B.UpdateFailed,"-").concat(e),instrumentId:t}),S.counter({name:I.UpdateFailed,value:1,attributes:N({instrument:t,request:e})})}function zs({errorCode:t}){S.counter({name:I.PayPalTokenCreationError,value:1,attributes:N({errorCode:t})})}function Hs(t){V({event:B.ClickSheetCancelled,instrumentId:t}),S.counter({name:I.SheetCancelled,value:1,attributes:N({instrument:t})})}function Gs(t,e){V({event:B.SheetFailed,instrumentId:t,errorReason:e==null?void 0:e.message}),S.counter({name:I.SheetFailed,value:1,attributes:N({instrument:t})})}function Vs(t){V({event:B.AuthorizationAttempt,instrumentId:t}),S.counter({name:I.AuthorizationAttempt,value:1,attributes:N({instrument:t})})}function qs({instrument:t,measurement:e,result:n}){V({event:B.AuthorizationComplete,eventSubtype:n,ttl:e,instrumentId:t}),e!=null&&S.histogram({name:I.AuthorizationComplete,value:e,attributes:N({instrument:t,result:n}),unit:"ms"})}function Ws({instrument:t,reason:e}){S.counter({name:I.Decelerated,value:1,attributes:N({instrument:t,reason:e})}),y.flushTelemetry()}function js({reason:t}){S.counter({name:I.CartTokenMissing,value:1,attributes:{reason:t}})}function Ys({success:t}){S.counter({name:I.RemovePersonalDataResult,value:1,attributes:N({success:t})})}function Ks(){S.counter({name:I.WalletConfigDeveloperError,value:1})}function Qs(){S.counter({name:I.LegacyCartCookie,value:1})}function Js(){window.setInterval(()=>{_a()},1e3)}function Xs(t){return(t==null?void 0:t.name)===gt}function _a(){S.exportMetrics(),S.exportLogs()}function Zs(t){const{body:e,attributes:n}=t;S.log({body:e,attributes:w(w({},Tr()),n)})}function el({usedBackwardsCompatibility:t}){S.counter({name:I.StyleBackwardsCompatibility,value:1,attributes:{usedBackwardsCompatibility:t}})}function tl({measurement:t,pageType:e,stylesWritten:n}){S.histogram({name:I.StyleBackwardsCompatibilityExecutionTime,value:t,attributes:N({pageType:e,stylesWritten:n}),unit:"ms"})}function rl({rule:t,count:e,pageType:n}){S.counter({name:I.StyleBackwardsCompatibilityRules,value:e,attributes:N({rule:t,pageType:n})})}function nl({retries:t}){S.counter({name:I.AmazonPayLoadRetries,value:1,attributes:{retries:t}})}function al({instrument:t}){S.counter({name:I.DynamicTaxFailed,value:1,attributes:{instrument:t}}),y.log({body:"Dynamic tax failed",attributes:{instrument:t}})}function il({instrument:t}){S.counter({name:I.DynamicShippingFailed,value:1,attributes:{instrument:t}}),y.log({body:"Dynamic shipping failed",attributes:{instrument:t}})}function ol({instrument:t,measurement:e}){S.histogram({name:I.SheetLoaded,value:e,attributes:N({instrument:t}),unit:"ms"})}function sl({instrument:t,result:e}){S.counter({name:I.AmazonAdExperimentAcceleratedCheckoutButtonClicked,value:1,attributes:N({instrument:t,result:e})})}function ll({instrument:t,result:e}){S.counter({name:I.AmazonAdExperimentAcceleratedCheckoutButtonSetup,value:1,attributes:N({instrument:t,result:e})})}function cl({instrument:t}){S.counter({name:I.AmazonAdExperimentPaymentButtonHidden,value:1,attributes:{instrument:t}}),y.log({body:"Payment button hidden",attributes:{instrument:t}})}function dl({instrument:t}){S.counter({name:I.AmazonAdExperimentRecommendedWalletOverriden,value:1,attributes:{instrument:t}}),y.log({body:"Recommended wallet overriden",attributes:{instrument:t}})}function ul({instrument:t,errorName:e}){S.counter({name:I.UnrecoverableCartError,value:1,attributes:N({instrument:t,errorName:e})}),y.log({body:"Unrecoverable error detected",attributes:{instrument:t,errorName:e}})}const y={initStarted:D(Ns),initCompleted:D(ks),instrumentLoaded:D(Ls),instrumentLoadEligibility:D(Ms),instrumentSDKLoaded:D(Os),instrumentSDKEligible:D(xs),renderSucceeded:D(Us),renderFailed:D(Fs),sheetClicked:D(Bs),sheetCancelled:D(Hs),sheetFailed:D(Gs),updateFailed:D($s),authorizationAttempt:D(Vs),authorizationComplete:D(qs),startExporter:D(Js),decelerated:D(Ws),cartTokenMissing:D(js),removePersonalDataResult:D(Ys),walletConfigDeveloperError:D(Ks),legacyCartCookie:D(Qs),flushTelemetry:D(_a),styleBackwardsCompatibility:D(el),styleBackwardsCompatibilityExecutionTime:D(tl),styleBackwardsCompatibilityRules:D(rl),amazonPaySDKLoadRetries:D(nl),dynamicTaxFailed:D(al),dynamicShippingFailed:D(il),sheetLoaded:D(ol),amazonAdExperimentAcceleratedCheckoutButtonClicked:D(sl),amazonAdExperimentAcceleratedCheckoutButtonSetup:D(ll),amazonAdExperimentPaymentButtonHidden:D(cl),amazonAdExperimentRecommendedWalletOverriden:D(dl),unrecoverableCartError:D(ul),log:D(Zs,{logErrors:!1}),paypalTokenCreationError:D(zs)};function D(t,{logErrors:e=!0}={}){return(...n)=>{try{t(...n)}catch(r){e&&y.log({body:"Error calling telemetry function",attributes:{error:"".concat(r)}})}}}const it=[];function oe(t,e,n){if(window.customElements==null)return b.leaveBreadcrumb("customElements is null on window"),sn(),!1;try{const r=e;return window.customElements.get(t)||(window.customElements.define(t,r),n!=null&&n.isChildCustomElement&&it.push(t)),!0}catch(r){return b.notify(r),sn(),!1}}function vt(){const t=new URLSearchParams(window.location.search);return function(e){return!!t.get(e)}}function hl(){var t,e,n,r;const a=(t=window.Shopify)==null?void 0:t.CartType;if(a===v.CartAjax)return v.CartAjax;if(a===v.CartPage)return v.CartPage;const i=(r=(n=(e=window.ShopifyAnalytics)==null?void 0:e.meta)==null?void 0:n.page)==null?void 0:r.pageType;if(i)switch(i.toLowerCase()){case"product":return v.ProductPage;case"cart":return v.CartPage}const o=document.querySelector("#shop-js-analytics");if(o)try{const s=JSON.parse(o.textContent||"{}");if(s.pageType)switch(s.pageType.toLowerCase()){case"product":return v.ProductPage;case"cart":return v.CartPage}}catch(s){console.error("Error parsing JSON script tag:",s)}return v.Unknown}function Re(t){return Number(t).toFixed(2)}function Nr(t){if(!(!t||!t.id||!t.id.includes("gid://shopify/Cart/")))return t.id.replace("gid://shopify/Cart/","").split("?")[0]}function ue(){let t;return[new Promise(e=>t=e),t]}const pl={force_shop_pay_product:"direct_checkout_product",force_shop_pay_cart:"direct_checkout_cart"};function ye(t,e="no_redirect_for_checkout"){y.flushTelemetry();const n=new URL(t);switch(e){case"skip_shop_pay":n.searchParams.set("skip_shop_pay","true");break;case"no_redirect_for_checkout":n.searchParams.set("storefront_wallet","true");break;case"force_shop_pay_cart":case"force_shop_pay_product":case"force_shop_pay":{n.searchParams.set("payment","shop_pay");const r=pl[e];r&&n.searchParams.set("redirect_source",r);break}}window.location.assign(n.toString())}function Ea(){return!!document.querySelector('[data-source-attribution="shopify.shop-promise-pdp"]')}function ie(){return new Date().getTime()}function kr(t){return t.find(e=>typeof e=="object"&&(e==null?void 0:e.code)===Pt)}const ml={currency_changed:Ee.CURRENCY_CHANGE,captcha_required:Ee.CAPTCHA_REQUIRED,not_enough_stock:Ee.NOT_ENOUGH_STOCK,cart_not_ready:Ee.CART_NOT_READY,dynamic_tax:Ee.DYNAMIC_TAX,payment_method_not_applicable:Ee.PAYMENT_METHOD_NOT_APPLICABLE,invalid_payment_deferred_payment_required:Ee.INVALID_PAYMENT_DEFERRED_PAYMENT_REQUIRED,cart_throttled:null};function hn({cart:t,warnings:e}){const n=t&&t.lineItems.length>0&&t.lineItems.every(r=>r.quantity===0);if(e!=null&&e.includes("MERCHANDISE_OUT_OF_STOCK")&&n)return"out_of_stock"}function tr({warnings:t,cart:e,cartStatus:n,errors:r}){if(r!=null&&r.includes(g.PaymentMethodNotApplicable))return"payment_method_not_applicable";if(r!=null&&r.includes(g.InvalidPaymentDeferredPaymentRequired))return"invalid_payment_deferred_payment_required";if(n==="CartStatusNotReady")return"cart_not_ready";if(n==="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 Lr({currentCartTotal:t,initialBuyerCurrency:e}){const n=t.amount;return!(!n||Number(n)===0||e.toUpperCase()===t.currencyCode.toUpperCase())}function F({checkoutUrl:t,instrumentName:e,reason:n}){if(!t)throw new Error("Invalid Checkout URL");const r=new URL(t),a=ml[n];a&&r.searchParams.set(a,"true"),y.decelerated({instrument:e,reason:n}),ye(r.toString())}function Aa(t){return window[Ca(t)]}function Ca(t){return"paypal-".concat(t.replace(/[^a-zA-Z0-9]/g,""))}const yl="RESTRICTED_WALLET_ACCOUNT",gl="GENERIC_ERROR",fl="NO_PENDING_TASK",bl="WALLET_SERVICE_DISABLED",wl="FAILED_TO_ENQUEUE_BACKGROUND_JOB",_l="REQUEST_MISSING_VALID_MERCHANDISE_SOURCE",El="THROTTLE_EXCEEDED",Al="INTERNAL_SERVER_ERROR",Cl=[gl,fl,bl,wl,_l,El,Al];function pn(t){return t==null?void 0:t.map(e=>{var n,r;return{code:(n=e.extensions)==null?void 0:n.code,isLoggable:Cl.includes((r=e.extensions)==null?void 0:r.code)}}).find(({code:e,isLoggable:n})=>e===yl||n)}const Sl="unstable";class Ht{constructor({accessToken:e,country:n,locale:r,apiVersion:a=Sl,withCarrierRates:i=!1,cartPrepareMigrationEnabled:o=!1}){if(c(this,"OPERATION_NAME_REGEX",/[^ ]+ (\w+)/),c(this,"LANGUAGES_WITH_REGION",["zh-CN","zh-TW","pt-BR","pt-PT"]),c(this,"client"),c(this,"country"),c(this,"url"),c(this,"locale"),c(this,"withCarrierRates"),c(this,"lastValidCart"),c(this,"cartPrepareMigrationEnabled"),c(this,"hasBeenVisible",!1),!e||!n)throw new X({code:"invalid-webcomponent",message:"accelerated checkout rendered without required webcomponent attributes"});if(!r)throw new Error("StorefrontApiClient constructed with no locale");this.country=n,this.locale=r,this.withCarrierRates=i,this.cartPrepareMigrationEnabled=o,this.url="/api/".concat(a,"/graphql.json"),this.client=Vi(Fo({url:this.url,accessToken:e}))}async createCart(e){var n,r,a;const i=await this.requestStream([yo,At],{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 d=l.value;d.errors&&await this.onError({operationName:"createCart",response:d});const h=(n=d.data)==null?void 0:n.result;if(h&&!d.hasNext){h.errors&&this.onResultError(h.errors);const p=this.parseMutationWarnings((a=(r=d.data)==null?void 0:r.result)==null?void 0:a.warnings),m=h.cart?this.parseCartResponse(h.cart):null;return{data:m,errors:this.parseMutationErrors(d,"result"),warnings:p,decelerationReason:tr({cart:m,warnings:p}),abortReason:hn({cart:m,warnings:p})}}}}catch(d){u=[d]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(u)throw u[0]}}throw new Ae("Cart create operation returned no response")}async updateCartBillingAddress(e){const{cartId:n,billingAddress:r,instrumentName:a}=e;return this.requestDeferredCart(fo,{cartId:n,billingAddress:r},{instrumentName:a,operationName:"updateCartBillingAddress"})}async updateCartBuyerIdentity(e,n){const{cartId:r,instrumentName:a}=e;return this.requestDeferredCart(bo,{cartId:r,buyerIdentity:Il(e)},{instrumentName:a,operationName:"updateCartBuyerIdentity",abortSignal:n})}async updateSelectedDeliveryOptions(e,n,r,a){let i=n;const o=ie()+2e4;for(;ie()typeof u=="string"&&u.startsWith(g.PendingDeliveryGroups))))return s;const l=s.data.deliveryGroups.flatMap(u=>u.deliveryOptions.map(d=>({deliveryOptionHandle:d.handle,deliveryGroupId:u.id})));i=i.map(u=>{var d;return(d=l.find(h=>h.deliveryOptionHandle===u.deliveryOptionHandle))!=null?d:u})}throw new Error("Selected delivery options update operation timed out")}async applePaySessionCreate(e){var n,r,a;const i=await this.requestStream([_o],{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 d=l.value;d.errors&&await this.onError({operationName:"applePaySessionCreate",response:d});const h=(a=(r=(n=d.data)==null?void 0:n.applePaySessionCreate)==null?void 0:r.applePaySession)==null?void 0:a.body;if(h)return h}}catch(d){u=[d]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(u)throw u[0]}}throw new Ae("Apple Pay session create operation returned no response")}async paypalBuyerDetailsFetch(e,n){var r,a;const i=await this.requestStream([Eo],{token:e,cartId:n},{instrumentName:f.PayPal,operationName:"paypalBuyerDetailsFetch"});try{for(var o=ee(i),s,l,u;s=!(l=await o.next()).done;s=!1){const d=l.value;if(d.hasNext)continue;if(d.errors){if(d.errors.graphQLErrors){const p=pn(d.errors.graphQLErrors);if(p!=null&&p.code)throw new ae(p.code)}await this.onError({operationName:"paypalBuyerDetailsFetch",response:d})}const h=(a=(r=d.data)==null?void 0:r.paypalBuyerDetailsFetch)==null?void 0:a.paypalDetails;if(h)return h}}catch(d){u=[d]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(u)throw u[0]}}throw new Ae("PayPal buyer details fetch operation returned no response")}async paypalTokenCreate(e){var n,r,a;const i=await this.requestStream([Ao],{cartId:e},{instrumentName:f.PayPal,operationName:"paypalTokenCreate"});try{for(var o=ee(i),s,l,u;s=!(l=await o.next()).done;s=!1){const d=l.value;if(d.errors){if(d.errors.graphQLErrors){const p=pn(d.errors.graphQLErrors);if(p!=null&&p.code)throw p.isLoggable&&(y.log({body:"PayPal Token Create ".concat(p.code," Error")}),y.paypalTokenCreationError({errorCode:p.code})),new ae(p.code)}await this.onError({operationName:"paypalTokenCreate",response:d})}const h=(a=(r=(n=d.data)==null?void 0:n.paypalTokenCreate)==null?void 0:r.paypalToken)==null?void 0:a.token;if(h)return h}}catch(d){u=[d]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(u)throw u[0]}}throw new Ae("PayPal token create operation returned no response")}async fetchLimitedCart({id:e,startingCheckout:n,instrumentName:r}){var a,i;const o=await this.request([So],{id:e},{instrumentName:r,startingCheckout:n});if(o.errors&&await this.onError({operationName:"limitedCartQuery",response:o}),!((a=o.data)!=null&&a.cart))throw new vl("Limited cart query returned no response");return b.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:n,instrumentName:r}){var a;const i=this.formatLanguage(this.locale),o=this.cartPrepareMigrationEnabled?"Prepare cart":"Fetch cart",s=this.cartPrepareMigrationEnabled?vo:Co,l=this.cartPrepareMigrationEnabled?[At,Xt,an]:[At],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},d=await this.requestStream([s,...l],u,{instrumentName:r,startingCheckout:n,operationName:"fetchCart"});try{for(var h=ee(d),p,m,E;p=!(m=await h.next()).done;p=!1){const _=m.value;_.errors&&await this.onError({operationName:"fetchCart",response:_});let A=null,P;if(!_.data)throw new Ae("".concat(o," operation returned no data in response"));if(Pl(_.data)){const $=_.data.preparedCart;A=(a=$==null?void 0:$.result)==null?void 0:a.cart,P=this.parsePreparedCartMutationErrors(_.errors,this.extractPreparedCartMutationErrors($))}else A=_.data.cart;if(b.leaveBreadcrumb("".concat(o," response"),{operationName:o,body:A,errors:P,hasNext:_.hasNext},"log"),A&&!_.hasNext){const $=this.parseCartResponse(A);return this.lastValidCart=$,$}}}catch(_){E=[_]}finally{try{p&&(m=h.return)&&await m.call(h)}finally{if(E)throw E[0]}}throw new Ae("".concat(o," operation returned no response"))}async updateCartPayment(e,n,r,a){var i,o;const s={cartId:e,input:n},{amount:l,currencyCode:u}=n.amount;let d;const h=ie()+1e4;for(;ie()setTimeout(m,500)),s.input.amount={amount:p.data.totalAmount.amount,currencyCode:p.data.totalAmount.currencyCode};continue}return(p.data.totalAmount.amount===l||parseFloat(p.data.totalAmount.amount)<=parseFloat(l))&&p.data.totalAmount.currencyCode===u?p:d}throw new Error("Payment update operation timed out")}async updateCartAttributes({cartId:e,attributes:n,instrumentName:r,startingCheckout:a}){const i={cartId:e,attributes:n};return await this.requestDeferredCart(go,i,{instrumentName:r,operationName:"updateCartAttributes",startingCheckout:a})}async submitForCompletion(e,n,r){var a,i;const o=this.formatLanguage(this.locale),s=await this.request([Do],{cartId:e,attemptToken:n,country:this.country,language:o,withCarrierRates:this.withCarrierRates},{instrumentName:r,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,n;const{data:r}=await this.request([Po],{country:this.country,language:this.formatLanguage(this.locale)},{operationName:"fetchSubscriptionPolicy"});return(n=(e=r==null?void 0:r.shop)==null?void 0:e.subscriptionPolicy)==null?void 0:n.body}async cartRemovePersonalData({cartId:e,shopId:n,instrumentName:r}){var a,i;let o,s,l;try{const d=await this.request([Ro,Xt],{cartId:e},{instrumentName:r,keepalive:!0});o=this.parseMutationWarnings((i=(a=d.data)==null?void 0:a.cartRemovePersonalData)==null?void 0:i.warnings),s=this.parseMutationErrors(d,"cartRemovePersonalData")}catch(d){l=d.toString()}const u=!(o!=null&&o.length||s!=null&&s.length||l);y.removePersonalDataResult({success:u}),u||y.log({body:"cartRemovePersonalData failed",attributes:{cartId:e,shopId:n,warnings:o,errors:s,exception:l}})}setVisible(){this.hasBeenVisible=!0}generateURLWithOperationName(e){const n=e.match(this.OPERATION_NAME_REGEX);if(n){const r=this.url.includes("?")?"&":"?",a="operation_name=".concat(n[1]);return"".concat(this.url).concat(r).concat(a)}return this.url}async request(e,n,r){return this.client.request(e.join(""),{variables:n,headers:mn(r),url:this.generateURLWithOperationName(e[0]),keepalive:r.keepalive})}async requestStream(e,n,r){return this.client.requestStream(e.join(""),{variables:n,headers:mn(r),url:this.generateURLWithOperationName(e[0]),signal:r.abortSignal})}async requestDeferredCart(e,n,r){var a,i,o,s,l,u,d,h,p;const m=this.formatLanguage(this.locale),E=await this.requestStream([e,At,Xt,an],k(w({},n),{country:this.country,language:m,withCarrierRates:this.withCarrierRates,prepareCart:this.cartPrepareMigrationEnabled}),r);try{for(var _=ee(E),A,P,$;A=!(P=await _.next()).done;A=!1){const M=P.value;M.errors&&await this.onError({operationName:r.operationName,response:M,abortSignal:r.abortSignal});const le=this.extractMutationErrors(M),T=(i=(a=M.data)==null?void 0:a.preparedCart)==null?void 0:i.result,G=(l=(s=(o=M.data)==null?void 0:o.result)==null?void 0:s.cart)!=null?l:T==null?void 0:T.cart;if(G&&!M.hasNext){let z;this.cartPrepareMigrationEnabled||(z=await this.fetchCart({id:G.id,instrumentName:r.instrumentName,startingCheckout:!1}));const x=this.parseMutationWarnings((d=(u=M.data)==null?void 0:u.result)==null?void 0:d.warnings),se=this.parsePreparedCartMutationErrors(M.errors,le),ce=z!=null?z:this.parseCartResponse(G);return{data:ce,errors:se,warnings:x,abortReason:hn({cart:ce,warnings:x}),decelerationReason:tr({warnings:x,cart:ce,cartStatus:T==null?void 0:T.__typename,errors:se})}}if(this.lastValidCart&&le.length>0){this.onResultError(le);const z=this.parseMutationWarnings((p=(h=M.data)==null?void 0:h.result)==null?void 0:p.warnings);return{data:this.lastValidCart,errors:this.parsePreparedCartMutationErrors(M.errors,le),warnings:z,decelerationReason:tr({warnings:z,cart:this.lastValidCart})}}}}catch(M){$=[M]}finally{try{A&&(P=_.return)&&await P.call(_)}finally{if($)throw $[0]}}throw new Ae("Deferred cart operation returned no response")}async onError({operationName:e,response:n,abortSignal:r}){if(r!=null&&r.aborted)throw new hr("Request aborted",{reason:"abort",errorDetails:{operationName:e}});const a=await To(e,n);if(!a)return;const i=a,{message:o}=i,s=Et(i,["message"]),{isIgnorable:l,reason:u}=Oo(a,{hasBeenVisible:this.hasBeenVisible});throw b.leaveBreadcrumb(o,w(w({ignored:l,ignoredReason:u},n),s),"error"),l?new hr(o,{reason:u,errorDetails:s}):new Ir(o,{errorDetails:s,groupingHash:Uo(s)})}onResultError(e){b.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 n,r,a;const i=e.lines.edges.map(s=>{var l,u;const d=s.node;return{quantity:d.quantity,totalAmount:{amount:d.cost.totalAmount.amount,currencyCode:d.cost.totalAmount.currencyCode},subtotalAmount:{amount:(l=d.cost.subtotalAmount)==null?void 0:l.amount,currencyCode:(u=d.cost.subtotalAmount)==null?void 0:u.currencyCode},merchandise:{requiresShipping:d.merchandise.requiresShipping},discountAllocations:d.discountAllocations,sellingPlanAllocation:d.sellingPlanAllocation}}),o=e.deliveryGroups.edges.map(s=>s.node);return{id:e.id,totalAmount:e.cost.totalAmount,subtotalAmount:(n=e.cost.subtotalAmount)!=null?n:void 0,totalTaxAmount:(r=e.cost.totalTaxAmount)!=null?r: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 n,r;return(r=(n=e==null?void 0:e.graphQLErrors)==null?void 0:n.map(a=>a.message.replace(/\(Expected.*\)/,"").trim()))!=null?r:[]}parseMutationError(e){return e.code===Pt?{code:Pt,message:e.message}:e.field&&e.field.length>0?"".concat(e.code,": ").concat(e.field.join(".")):e.code}parseMutationErrors(e,n){var r,a,i;const o=this.parseGraphQlErrors(e.errors),s=((i=(a=(r=e.data)==null?void 0:r[n])==null?void 0:a.errors)==null?void 0:i.map(this.parseMutationError).filter(u=>u))||[],l=[...o,...s];return b.leaveBreadcrumb("GraphQL errors on mutation",l,"error"),l}parseMutationWarnings(e){return!e||e.length===0?[]:e.map(n=>n.code)}stringifyAttributes(e){return e&&e.map(n=>({key:n.key,value:typeof n.value=="string"?n.value:JSON.stringify(n.value)}))}filterErrors(e){var n;return!((n=e.code)!=null&&n.startsWith("PENDING_DELIVERY_GROUPS")||e.code==="INVALID_PAYMENT")}extractPreparedCartMutationErrors(e){var n,r;const a=(n=e==null?void 0:e.errors)!=null?n:[];return((r=e==null?void 0:e.result)==null?void 0:r.__typename)==="CartStatusNotReady"&&a.push(...e.result.errors),a}extractMutationErrors(e){var n,r,a,i;let o=(a=(r=(n=e.data)==null?void 0:n.result)==null?void 0:r.errors)!=null?a:[];return this.cartPrepareMigrationEnabled&&(o=o.filter(this.filterErrors)),[...o,...this.extractPreparedCartMutationErrors((i=e.data)==null?void 0:i.preparedCart)]}parsePreparedCartMutationErrors(e,n){const r=this.parseGraphQlErrors(e),a=n.map(this.parseMutationError).filter(o=>o),i=[...r,...a];return b.leaveBreadcrumb("GraphQL errors on mutation",i,"error"),i}parseCompletionErrors(e){var n,r,a,i;const o=this.parseGraphQlErrors(e.errors);let s=[];((a=(r=(n=e.data)==null?void 0:n.cartSubmitForCompletion)==null?void 0:r.result)==null?void 0:a.__typename)==="SubmitFailed"&&(s=(i=e.data.cartSubmitForCompletion.result.errors.map(u=>u.code))!=null?i:[]);const l=[...o,...s];return b.leaveBreadcrumb("GraphQL errors on completion",l,"error"),l}}function Pl(t){return!("cart"in t)}function Il({emailAddress:t,countryCode:e,phone:n,streetAddress:r,validateAddress:a,preferences:i}){return{email:t,countryCode:e!=null?e:r==null?void 0:r.country,phone:n!=null?n:r==null?void 0:r.phone,deliveryAddressPreferences:r?[{deliveryAddressValidationStrategy:a?"STRICT":"COUNTRY_CODE_ONLY",deliveryAddress:r}]:[],preferences:i}}function mn({instrumentName:t,startingCheckout:e}){const n={};return t&&(n["X-Wallet-Name"]="".concat(t)),e&&(n["X-Start-Wallet-Checkout"]="".concat(e)),n}const Sa="LimitedCartQueryError";class vl extends Error{constructor(){super(...arguments),c(this,"name",Sa)}}const Pa=["OpenTelemetryClientError",Qn,ea,Jn,gt],Dl=["Load failed","Failed to fetch","when attempting to fetch resource","GraphQL mutation failed with status 404","Component closed",...Pa],yn=new Map([["TypeError","Illegal constructor"],["BugsnagInvalidError",'"isTrusted":true'],[Sa,"Limited cart query returned no response"],["AbortError","Fetch is aborted"],["SyntaxError","The string did not match the expected pattern."]]),Rl=["chrome-lighthouse","meta-externalads","crawler","spider","scraper","facebookexternalhit","bot"];function Tl(t){const e=t.exceptions[0];return Nl()?"silenced-user-agent":kl(t)?"empty-stack-trace":Ll(e)?"spin":Ol()?"monkey-patch":Ul(t)?"external-error":Bl(t)?"developer-error":Fl(e.message)?"discarded-message":$l(t)?"discarded-error-class":zl(e)?"discarded-class-message":Hl(t)?"unactionable-invalid-error":xl(t)||null}function Nl(){const t=navigator.userAgent.toLowerCase();return Rl.some(e=>t.includes(e))}function kl(t){return t.exceptions[0].stacktrace.length===0}function Ll(t){return t.stacktrace.some(e=>{var n;return(n=e.file)==null?void 0:n.includes("spin.dev")})}function Ol(){return[HTMLElement,Event,document.createElement].some(Kn)}function xl(t){const e=t.exceptions.map(n=>n.stacktrace.filter(r=>!Ml(r)));return e.some(n=>{var r;return!((r=n[0])!=null&&r.inProject)})?"external-trigger":e.some(n=>n.filter(r=>r.inProject).every(r=>[Vn,Sr,qn].some(a=>r.file.startsWith(a))))?"wallet-sdk-stack-trace":null}function Ml(t){return t.file.includes("native code")||t.file.includes("/cdn/wpm/")}function Ul(t){return!t.exceptions[0].stacktrace.some(e=>e.inProject)}function Fl(t){return Dl.some(e=>t==null?void 0:t.includes(e))}function Bl(t){const e=t.exceptions.some(n=>n.errorClass===gt);return e&&console.error(t.exceptions[0]),e}function $l(t){return t.exceptions.some(e=>Pa.includes(e.errorClass))}function zl(t){const e=t.errorClass,n=t.message;return yn.has(e)&&(n==null?void 0:n.includes(yn.get(e)))}function Hl(t){return t.exceptions[0].errorClass==="BugsnagInvalidError"&&t.unhandled}function Gl(t,e){const n=t.exceptions[0];if(!n||!n.message||Ei.checkDuplicate(n))return!1;const r=Wl(e);Vl(t,r);let a=null;try{a=Tl(t)}catch(i){const o=i;console.error(o);const s={errorClass:"UnfilterableError",message:"Could not properly filter error with message: ".concat(o.message),stacktrace:zn(Wn,o)};t.exceptions.unshift(s)}return Kl(a),Ts()&&Ql({errorClass:n.errorClass,message:n.message,stacktrace:JSON.stringify(n.stacktrace),filterResult:a,metadata:JSON.stringify(t.metaData)}),a==null}function Vl(t,e){var n,r,a,i,o;const s=(a=(r=(n=window.ShopifyAnalytics)==null?void 0:n.lib)==null?void 0:r.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,jl(t),Yl(t),t.groupingHash=ql(e);const l=Tr();t.metaData=k(w({},t.metaData),{shop:w(w({},l),t.metaData.shop),custom:k(w({},t.metaData.custom),{customFetch:Kn(fetch)}),error_source:{shop_id:l.shopId},monorail:s}),e[0]instanceof Ir&&(t.metaData.graphql=w({},e[0].errorDetails),e[0]instanceof hr&&(t.metaData.graphql.reason=e[0].reason))}function ql(t){for(const e of t)if("groupingHash"in e&&e.groupingHash)return e.groupingHash.toString()}function Wl(t){const e=[];let n=t;for(;n instanceof Error&&e.length<20;){e.push(n);const r="cause"in n?n.cause:null;if(!r)break;n=r}return e}function jl(t){for(const e of t.exceptions)for(const n of e.stacktrace)[Vn,Sr,qn].some(r=>n.file.startsWith(r))&&(n.inProject=!0)}function Yl(t){var e;for(const n of t.exceptions)for(const r of n.stacktrace)(e=r.file)!=null&&e.includes("portable-wallets")&&(r.file=r.file.split("#")[0].split("?")[0])}function Kl(t){S.counter({name:I.ErrorTriggered,value:1,attributes:{filterResult:t||"valid-error"}})}function Ql(t){S.log({body:"Bugsnag Error",attributes:w(w({},Tr()),t)})}var Mn;const Jl={apiKey:"e6b446c1ebe782e2b2fc7eb8ef0dc791",appId:Wn,appVersion:"0.0.0-a7797b9aa032067919228087dfc7508e4b80cfec",releaseStage:"production",locale:"en",userAgent:navigator.userAgent,metadata:{user:{id:(Mn=ut(wi))!=null?Mn:"unknown"}},withSessionTracking:!1,onError:Gl},b=new pi(Jl);b.addOnPostError(t=>{b.leaveBreadcrumb("Bugsnag Error Notified",{errorClass:t.exceptions[0].errorClass,message:t.exceptions[0].message},"error")});var Ia={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."},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"},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."}}}};Ia.en;let rr;class gn extends Error{constructor(e,n){const r="i18n: Missing or invalid translation '".concat(e,"' in '").concat(n,"'");super(r)}}class Xl extends Error{constructor(e,n,r){const a="i18n: Missing translation template key '".concat(e,"' for '").concat(n,"' in '").concat(r,"'");super(a)}}class Zl extends Error{constructor(e,n,r){const a="i18n: Invalid pluralization for '".concat(e,"':'").concat(n,"' in '").concat(r,"'");super(a)}}function Gt(){return rr==null&&(rr=ec(Ia)),rr}function ec(t){const e=(i,o)=>typeof i!="string"&&o.count!=="undefined",n=(i,o)=>{let s=o===1?"one":"other";return o===0&&typeof i!="string"&&i.zero!=="undefined"&&(s="zero"),s},r=(i,o={})=>{const s=i.match(/%\{.+?\}/g);return s?s.reduce((l,u)=>{const d=u.replace(/%\{(.*)\}/,"$1");return o[d]?l.replace(u,o[d]):(b.notify(new Xl(d,i,a)),l)},i):i},a=tc();return{locale:a,translate(i,o={}){var s;const l=i.split(".");let u=t[a];try{for(const d of l)switch(typeof u){case"object":u=u[d];break;case"string":case"undefined":throw new gn(i,a)}if(e(u,o)){if(typeof u=="string")throw new Zl(i,u,a);u=u[n(u,o.count)]}if(typeof u!="string")throw new gn(i,a);return r(u,o)}catch(d){return b.notify(d),(s=o.defaultValue)!=null?s:i}}}}function tc(){return"en"}class rc extends HTMLElement{constructor(){super(...arguments),c(this,"overflow",""),c(this,"formerFocus",null)}connectedCallback(){this.attachShadow({mode:"open"}),this.formerFocus=document.activeElement;const e=Gt();this.render(e);const n=this.shadowRoot,r=n.getElementById("modal");n.querySelectorAll("button").forEach(o=>o.addEventListener("click",this.closeModal.bind(this)));const a=n.getElementById("overlay");a==null||a.addEventListener("click",o=>this.handleOutsideClick(o,r)),document.addEventListener("keydown",this.handleEscapeKey.bind(this));const i=document.createElement("style");i.textContent=oi,n.appendChild(i),this.overflow=document.body.style.overflow,document.body.style.overflow="hidden",this.trapFocus(r,n),oe("svg-icon",ii)}trapFocus(e,n){if(!e)return;const r=e.querySelectorAll("a[href], button"),a=Array.from(r),i=a[0],o=a[a.length-1];e.addEventListener("keydown",s=>{s.key==="Tab"&&!s.shiftKey&&n.activeElement===o&&(s.preventDefault(),i.focus()),s.key==="Tab"&&s.shiftKey&&n.activeElement===i&&(s.preventDefault(),o.focus())}),i.focus()}handleOutsideClick(e,n){n&&(n.contains(e.target)||this.closeModal())}handleEscapeKey(e){e.key==="Escape"&&this.closeModal()}closeModal(){var e;document.body.style.overflow=this.overflow,this.remove(),this.formerFocus&&"focus"in(this==null?void 0:this.formerFocus)&&typeof this.formerFocus.focus=="function"&&((e=this.formerFocus)==null||e.focus())}render(e){const n=this.getAttribute("title"),r=this.getAttribute("has-close-button"),a=e.translate("error_dialogs.checkout.button_text"),i='\n
\n \n
\n ");this.shadowRoot.innerHTML='\n
\n \n
\n ")}}const nc="@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 Vt({type:t="button",label:e=void 0}={}){const n=document.createElement("button");return n.type=t,e&&n.setAttribute("aria-label",e),n}function qt(t,e){for(const[n,r]of Object.entries(e))t.setAttribute(n,r)}function fn(t,e){for(const[n,r]of Object.entries(e))t.style.setProperty(n,r)}function ft(t,e){const n=document.createElement("top-level-modal");n.textContent=e,qt(n,{"data-testid":"top-level-modal","has-close-button":"true",title:t}),document.body.appendChild(n)}function Or(t,e,n){const r=document.createElement("top-level-modal");qt(r,{"data-testid":"top-level-modal",title:t}),e instanceof Promise?(r.innerHTML="\n \n  \n  \n  \n  \n  \n '),e.then(a=>{a&&a!==""?r.innerHTML=a:r.innerHTML=n!=null?n:""}).catch(()=>{r.innerHTML=n!=null?n:""})):r.innerHTML=e,document.body.appendChild(r)}function O(t,e){ft(e.translate("error_dialogs.wallet.title",{wallet:t}),e.translate("error_dialogs.wallet.generic_error",{wallet:t}))}function bt(t){ft(t.translate("error_dialogs.checkout.title"),t.translate("error_dialogs.checkout.generic_error"))}function Le(t,e){ft(t.translate("error_dialogs.checkout.title"),e)}function Oe(t,e){switch(e){case ne.InvalidQuantity:case ne.VariantRequiresSellingPlan:case ne.SellingPlanNotApplicable:bt(t);break}}function ge(t){ft(t.translate("error_dialogs.checkout.title"),t.translate("error_dialogs.product.out_of_stock"))}oe("top-level-modal",rc);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 ac="#more-payment-options-link{cursor:pointer}";function ic(t){const e=n=>{n.persisted&&(t(),window.removeEventListener("pageshow",e))};window.addEventListener("pageshow",e)}class oc extends Error{constructor(e){e instanceof Error?(super("[".concat(e.name,"] ").concat(e.message),{cause:e.cause}),this.stack=e.stack):super("[HandleCreateCartError] ".concat(String(e))),this.name="HandleCreateCartError"}}async function be({element:t,instrumentName:e,dataSource:n}){try{const r=await n.getInitialCart(e),{cart:a,errors:i,abortReason:o,decelerationReason:s}=r;ic(()=>{t&&(t.disabled=!1)});const l=kr(i),u=lc(i),d=u||l;if(u&&y.unrecoverableCartError({instrument:e,errorName:u}),!a&&!d)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&&!d)throw new Error("Errors present after cart creation: ".concat(JSON.stringify(i)));return w({cart:a,customValidationError:l,decelerationReason:s,abortReason:o},u?{unrecoverableError:u}:{})}catch(r){throw new oc(r)}finally{t.disabled=!1}}const sc={[g.InvalidQuantity]:ne.InvalidQuantity,[g.VariantRequiresSellingPlan]:ne.VariantRequiresSellingPlan,[g.SellingPlanNotApplicable]:ne.SellingPlanNotApplicable};function lc(t){if(t.length!==1)return null;const[e]=t;return typeof e=="object"?null:sc[e]||null}class cc extends wt{constructor(){super(),c(this,"name",f.MoreOptions),c(this,"anchor"),c(this,"i18n"),c(this,"dataSource"),c(this,"classNames"),c(this,"setI18n"),c(this,"setDataSource"),c(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,n,r){n!==r&&e==="disabled"&&this.anchor&&(r===""?this.anchor.setAttribute("aria-disabled","true"):this.anchor.removeAttribute("aria-disabled"),this.setAccessibilityAttributes())}async handleClick(e){var n,r;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:d}=await be({element:this,instrumentName:f.MoreOptions,dataSource:i});if(u){y.sheetClicked({instrument:this.name,result:"failed"}),Oe(a,u);return}if(l){Le(a,l.message);return}if(d==="out_of_stock"){y.sheetClicked({instrument:this.name,result:"failed"}),ge(a);return}if(o){F({checkoutUrl:(n=s==null?void 0:s.checkoutUrl)!=null?n:"",instrumentName:f.MoreOptions,reason:o});return}const h=this.recommendedInstrument===f.ShopPay?"skip_shop_pay":"allow_redirect";y.sheetClicked({instrument:f.MoreOptions,result:"success"}),ye((r=s==null?void 0:s.checkoutUrl)!=null?r:"",h)}catch(o){y.sheetClicked({instrument:f.MoreOptions,result:"failed"}),b.notify(o),bt(a)}}async render(){const e=await this.i18n,n=await this.classNames;this.anchor=document.createElement("a"),this.anchor.textContent=e.translate("more_payment_options"),this.anchor.className=n,this.anchor.setAttribute("id","more-payment-options-link"),this.anchor.onclick=a=>this.handleClick(a),this.setAccessibilityAttributes(),this.appendChild(this.anchor);const r=document.createElement("style");r.textContent=ac,this.appendChild(r)}setAccessibilityAttributes(){this.anchor&&(this.disabled?(this.anchor.removeAttribute("href"),this.anchor.role="link"):(this.anchor.removeAttribute("role"),this.anchor.href="#"))}}var L=(t=>(t.ButtonDisplay="buttonDisplay",t.LoadInstrument="loadInstrument",t.LoadSdk="loadSDK",t.AuthorizationLatency="authorizationLatency",t.SheetLoad="sheetLoad",t.StyleExtract="styleExtract",t))(L||{});function va(){var t,e;return!!((t=window.performance)!=null&&t.mark)&&!!((e=window.performance)!=null&&e.measure)}function Qe(t,e){return Ze(t,e),()=>K(t,e)}function Ze(t,e){va()&&window.performance.mark("".concat(t,"-").concat(e,"-start"))}function K(t,e){var n,r;if(va())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=(r=window.performance.measure(o,a,i))!=null?r:(n=window.performance.getEntriesByName(o,"measure"))==null?void 0:n[0],l=s==null?void 0:s.duration;return l==null?void 0:l}catch(a){return}}function xr(t,e,n){if(it!=null&&it.length){const r=it.join(",");t.querySelectorAll(r).forEach(a=>{n===null?a.removeAttribute(e):a.setAttribute(e,n)})}}function dc(t,e){try{const n=JSON.parse(t!=null?t:"[]");if(!(n instanceof Array))throw new X({code:"invalid-wallet-configs",message:"[".concat(e,"] invalid walletConfigs found")});return n}catch(n){throw new X({code:"invalid-wallet-configs",message:"[".concat(e,"] Error while parsing walletConfigs JSON: ").concat(n)},{cause:n})}}function uc(t,e){try{return t?JSON.parse(t):null}catch(n){throw new X({code:"invalid-wallet-config",message:"[".concat(e,"] Error while parsing walletConfig JSON: ").concat(n)},{cause:n})}}function Dt(t,e){var n;const r=e==null?void 0:e.getLoadEligibility(t);return y.instrumentLoadEligibility({instrument:e==null?void 0:e.getInstrumentName(),result:r!=null&&r.eligible?"success":"failed",reason:r!=null&&r.eligible||r==null?void 0:r.reason}),(n=r==null?void 0:r.eligible)!=null?n:!1}function hc(t,e){return e.filter(n=>Dt(t,n))}async function Da({walletInstrument:t,instanceNumber:e}){const n=t.getInstrumentName(),r=Qe(L.LoadSdk,"".concat(n,":").concat(e));try{await t.loadWalletSDK(),y.instrumentSDKLoaded({instrument:n,measurement:r(),result:"success"})}catch(i){return b.leaveBreadcrumb("Failed to load wallet SDK",{instrumentName:n,instanceNumber:e},"error"),b.notify(i),y.instrumentSDKLoaded({instrument:n,measurement:r(),result:"failed"}),null}let a;try{a=t.getPartnerSDKEligibility()}catch(i){b.notify(i),a={eligible:!1,reason:"uncaught exception"}}return a.eligible?(y.instrumentSDKEligible({instrument:n,result:"success"}),t):(y.instrumentSDKEligible({instrument:n,reason:a.reason,result:"failed"}),null)}function Ne(t,...e){try{const n=window[t];if(typeof n=="function")return new n(...e)}catch(n){}return null}const Ra="d6d12da0",Me="0402dc2d",pc="1b55bc27";var qe;class Mr extends wt{constructor(){super(...arguments),c(this,"apiClient"),c(this,"i18n"),c(this,"policy"),c(this,"isFetchingPolicy",!1),c(this,"intersectionObserver",null),H(this,qe),c(this,"handleIntersection",(e,n)=>{e.some(r=>r.isIntersecting)&&(this.apiClient&&this.apiClient.setVisible(),n.disconnect(),V({event:B.FirstVisible}))})}connectedCallback(){this.mountIntersectionObserver()}get shopId(){return this.getAttribute("shop-id")}get cartId(){return this.getAttribute("cart-id")}get walletConfigs(){return this.getAttribute("wallet-configs")}get recommendedWallet(){return this.getAttribute("recommended")}get amazonWallet(){return this.isFlagEnabled(Me)?this.getAttribute("amazon-wallet"):null}get fallbackWallet(){return this.getAttribute("fallback")}get isBuyWithPrimeEligible(){return this.isFlagEnabled(Me)?this.hasAttribute("is-buy-with-prime-eligible"):!1}get isShopPayPersonalizationEnabled(){return this.isFlagEnabled(pc)}get variantParams(){var e;try{return JSON.parse((e=this.getAttribute("variant-params"))!=null?e:"[]")}catch(n){throw new X({code:"invalid-variant-params",message:"variant-params must be a valid JSON string. Received variant-params: ".concat(this.getAttribute("variant-params"),", received error: ").concat(n)})}}get styleExtractorDisabled(){return this.hasAttribute("disable-compat")}get onlySdk(){return this.hasAttribute("only-sdk")}get debug(){return this.hasAttribute("debug")}get hidePaymentButton(){return this.isFlagEnabled(Me)?this.isBuyWithPrimeEligible&&this.isRedirectedFromAmazon:!1}get isRedirectedFromAmazon(){return this.isFlagEnabled(Me)?sessionStorage.getItem("shopify_amazon_referral")==="mShop":!1}triggerLoadedEvent(){document.dispatchEvent(new Event("shopify:payment_button:loaded",{bubbles:!0,cancelable:!0}))}async attributeChangedCallback(e,n,r){n!==r&&xr(this,e,r)}showBuyerConsent(e,n){var r,a,i;!e||!n||(i=(a=(r=window.Shopify)==null?void 0:r.PaymentButton)==null?void 0:a.showBuyerConsent)==null||i.call(a,o=>this.onClickSubscriptionPolicy(o,e,n))}hideBuyerConsent(){var e,n,r;(r=(n=(e=window.Shopify)==null?void 0:e.PaymentButton)==null?void 0:n.hideBuyerConsent)==null||r.call(n)}clearUI(){this.innerHTML=""}isFlagEnabled(e){return C(this,qe)==null&&U(this,qe,this.getEnabledFlags()),C(this,qe).includes(e)}getEnabledFlags(){const e=this.getAttribute("enabled-flags");if(!e)return[];try{return JSON.parse(e)}catch(n){return console.warn("Invalid enabled-flags attribute value:",e),[]}}async onClickSubscriptionPolicy(e,n,r){if(e.preventDefault(),this.isFetchingPolicy)return;if(this.policy){this.showPolicy(this.policy,r);return}this.isFetchingPolicy=!0;const a=this.fetchSubscriptionPolicy(n).then(i=>(this.policy=i,i)).catch(i=>(b.notify(i),r.translate("subscriptions.policy_not_found"))).finally(()=>{this.isFetchingPolicy=!1});this.showPolicy(a,r)}async fetchSubscriptionPolicy(e){const n=await e.fetchSubscriptionPolicy();return this.policy=n,n}showPolicy(e,n){Or(n.translate("subscriptions.cancellation_policy"),e,n.translate("subscriptions.policy_not_found"))}mountIntersectionObserver(){this.intersectionObserver=Ne("IntersectionObserver",this.handleIntersection),this.intersectionObserver?this.intersectionObserver.observe(this):V({event:B.FirstVisibleNotAvailable})}}qe=new WeakMap;function Ur(t){var e,n;Rs({shopId:(e=t.shopId)!=null?e:jn,cartId:(n=t.cartId)!=null?n:void 0,debug:t.debug,pageType:t.pageType})}function Ta({type:t,form:e}){if(!e)return[];const n=document.querySelectorAll('[name^="'.concat(t,'"][form^="').concat(CSS.escape(e.getAttribute("id")||""),'"]')),r=e.querySelectorAll('[name^="'.concat(t,'"]')),a=[...n,...r],i={};return a.forEach(o=>{const s=mc(o),l=yc(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 n=t==="product"?'[data-shopify="payment-button"]':'[data-shopify="dynamic-checkout-cart"]',r=bn(e,n)||document.querySelector(n);return bn(r,"form")}const nt=Element.prototype;function bn(t,e){if(nt.matches=nt.matches||nt.webkitMatchesSelector||nt.msMatchesSelector||nt.mozMatchesSelector,!t||t.matches(e))return t;let n=t;for(;n&&n!==document.body;)if(n=n.parentElement,n&&n.matches(e))return n;return null}function mc(t){const e=t.getAttribute("name");if(e===null)return null;const n=e.indexOf("["),r=e.lastIndexOf("]");return n===-1||r===-1?null:e.substring(n+1,r)}function yc(t){if(!(["radio","checkbox"].includes(t.type)&&!t.checked)&&!(t.value===""||typeof t.value>"u"))return t.value}function Fr(t){const e=Wt({page:"product",element:t});return Na(e)}function Na(t){var e;const n=t==null?void 0:t.elements;if(!n)return null;const r=Rt(n,"id");if(!r||isNaN(Number(r))||Number(r)<=0)return null;const a=Number((e=Rt(n,"quantity"))!=null?e:"1"),i="gid://shopify/ProductVariant/".concat(r),o=fc(n),s=Ta({type:"properties",form:t});return{variantId:r,quantity:a,merchandiseId:i,sellingPlanId:o,lineItemProperties:s}}function gc(t){const e=t==null?void 0:t.elements;return e?!!Rt(e,"selling_plan"):!1}function Rt(t,e){var n,r;let a=t.namedItem(e);return a instanceof HTMLSelectElement?(n=a.value)!=null?n:null:(a&&"length"in a&&(a=a.item(0)),(a instanceof HTMLInputElement||a instanceof HTMLSelectElement)&&(r=a.value)!=null?r:null)}function fc(t){const e=Rt(t,"selling_plan");if(!(!e||e==="undefined"))return"gid://shopify/SellingPlan/".concat(e)}class Br{constructor(e,n){c(this,"addToCartMutationObserver"),c(this,"addToCartForm"),c(this,"addToCartButtons"),this.element=e,this.onFormChanged=n,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=Na(this.addToCartForm),n=!!(this.addToCartButtons.length>0&&this.addToCartButtons.every(r=>r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true"));this.onFormChanged({disabled:n||e===null,hasSellingPlan:gc(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 bc(t,e,n){try{const r=JSON.parse(t!=null?t:"{}"),a=JSON.parse(e!=null?e:JSON.stringify(Yn));if(r===null||Object.keys(r).length===0){if(!(a instanceof Object))throw y.walletConfigDeveloperError(),new X({code:"invalid-fallback-wallet-config",message:"[".concat(n,"] Invalid fallback wallet configs JSON")});return{recommendedWallet:null,fallbackWallet:a}}return{recommendedWallet:r,fallbackWallet:a}}catch(r){throw y.walletConfigDeveloperError(),new X({code:"invalid-recommended-fallback-config",message:"[".concat(n,"] Error while parsing recommended/fallback JSON: ").concat(r)},{cause:r})}}const wc=".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{background:none;border:none;padding:0;text-decoration:underline;font-size:inherit;cursor:pointer}#shopify-subscription-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 )}",_c='.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}}',Ec=70;class lt{constructor(e,n,r,a){c(this,"red"),c(this,"green"),c(this,"blue"),c(this,"opacity"),this.red=e||0,this.green=n||0,this.blue=r||0,this.opacity=typeof a>"u"?1:a}getLuminance(){const e=this.red&255,n=this.green&255,r=this.blue&255;return e*.2126+n*.7152+r*.0722}isDark(){return this.opacity===0?!1:this.getLuminance()/this.opacity0&&a.opacity>0?(r=new lt(0,0,0,0),r.blendWith(a,n)):a.opacity>0?r=a:r=n,n=r,a=e.shift();return r}const mr=new lt(255,255,255,1);function Cc(t){const e=[];let n=t;for(;n.parentElement;){n=n.parentElement;const r=window.getComputedStyle(n).backgroundColor,a=Sc(r);if(r&&e.push(a),a.opacity===1)break}try{return Ac(e.reverse())}catch(r){return b.notify(new ka("[BackgroundDetection] Failed to blend colors for element ".concat(t.outerHTML),{cause:r})),mr}}function Sc(t){if(!t)return mr;try{const e=t.split("(")[1].split(")")[0].replace(" ","").split(",");return new lt(Number(e[0]),Number(e[1]),Number(e[2]),typeof e[3]>"u"?1:Number(e[3]))}catch(e){b.notify(new ka("[BackgroundDetection] Failed to convert rgbString to array ".concat(t),{cause:e}))}return mr}class ka extends Error{constructor(){super(...arguments),c(this,"name","ColorProcessingError")}}var he;class we extends wt{constructor(){super(),c(this,"name",f.Unknown),c(this,"i18n"),c(this,"dataSource"),c(this,"apiClient"),c(this,"classNames"),c(this,"containerInstanceNumber"),c(this,"onRendered"),c(this,"setI18n"),c(this,"setDataSource"),c(this,"setApiClient"),c(this,"setClassNames"),c(this,"setContainerInstanceNumber"),c(this,"parsedWalletParams"),H(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,n){var r;try{await e()}catch(a){b.notify(new Pc("An error occurred requiring cleanup when attempting to render the ".concat(n," instrument: ").concat(a),{cause:a}));const i=await this.containerInstanceNumber;y.instrumentLoaded({instrumentOrComponentName:n,result:"failed",measurement:K(L.ButtonDisplay,"".concat(n,":").concat(i))}),(r=this.parentElement)==null||r.remove()}}attributeChangedCallback(e,n,r,a){n!==r&&e==="disabled"&&a&&(r===""?(a.setAttribute("aria-disabled","true"),a.setAttribute("disabled","")):(a.removeAttribute("aria-disabled"),a.removeAttribute("disabled")))}get pageType(){return this.getAttribute("page-type")||v.Unknown}get buttonTheme(){return Cc(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(n){throw new X({code:"invalid-wallet-params",message:"[".concat(this.name,"] Error while parsing wallet-params JSON: ").concat(n)},{cause:n})}return this.parsedWalletParams}async initializeShadowStyles(e,n=""){const r=document.createElement("style");r.innerHTML=[_c,n].join("\n"),e.appendChild(r)}async ensureLightDOMIsNotEmpty(){this.textContent="\xA0"}dispatchWalletEvent({eventName:e,detail:n={}}){var r;(r=this.parentElement)==null||r.dispatchEvent(new CustomEvent(e,{detail:n}))}getOrCreateShadowRoot(){return C(this,he)||U(this,he,this.attachShadow({mode:"closed"})),C(this,he)}clearShadowRoot(){C(this,he)&&(C(this,he).innerHTML="")}}he=new WeakMap;class Pc extends Error{constructor(){super(...arguments),c(this,"name","CleanupOnFailureError")}}class Ic extends we{constructor(){super(...arguments),c(this,"name",f.BuyItNow),c(this,"button",null)}static get observedAttributes(){return["disabled"]}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}attributeChangedCallback(e,n,r){super.attributeChangedCallback(e,n,r,this.button)}async handleClick(){var e,n;if(this.disabled||!this.button||this.button.getAttribute("aria-disabled"))return;this.disabled=!0;const[r,a]=await Promise.all([this.i18n,this.dataSource]);try{const{decelerationReason:i,cart:o,customValidationError:s,unrecoverableError:l,abortReason:u}=await be({element:this,instrumentName:this.name,dataSource:a});if(l){y.sheetClicked({instrument:this.name,result:"failed"}),Oe(r,l);return}if(u==="out_of_stock"){y.sheetClicked({instrument:this.name,result:"failed"}),ge(r);return}if(y.sheetClicked({instrument:this.name,result:"success"}),s){Le(r,s.message);return}if(i){F({checkoutUrl:(e=o==null?void 0:o.checkoutUrl)!=null?e:"",instrumentName:this.name,reason:i});return}ye((n=o==null?void 0:o.checkoutUrl)!=null?n:"","allow_redirect")}catch(i){b.notify(i),y.sheetClicked({instrument:this.name,result:"failed"}),bt(r)}}async render(){var e;this.button||(this.button=Vt());const n=await this.classNames;this.button.textContent=(await this.i18n).translate("instruments_copy.checkout.buy_now"),this.button.className=n,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 vc=1e3;function Dc(){const t=navigator.userAgent,e=t.indexOf("Android")>-1,n=t.indexOf("Chrome/")>-1,r=parseInt((/Chrome\/([0-9]+)/.exec(t)||["0","0"])[1],10);return e&&n&&r===114}function Rc(t){return Promise.race([t,new Promise((e,n)=>setTimeout(()=>n(new Error("timed out")),vc))])}class _e{constructor(e){c(this,"walletParams"),this.walletParams=e.wallet_params}static walletName(){throw new Error("Must define walletName for WalletInstrument subclass")}async createWebComponent({walletContainer:e,dataSource:n,i18n:r,apiClient:a,containerInstanceNumber:i,classNames:o="",callToAction:s,pageType:l=v.ProductPage,slot:u="button",onRendered:d=()=>{}}){var h,p,m;const E=this.getWebComponentName();if(!oe(E,this.getWebComponentClass(),{isChildCustomElement:!0}))throw new ae("Failed to define custom element ".concat(E,", aborting execution"));try{await Rc(customElements.whenDefined(E))}catch(P){throw new ae("Timeout waiting for custom element ".concat(E," to be defined"))}const _=document.createElement(E);if(!(_ instanceof we))throw new ae("Failed to create web component instance for ".concat(E,", element is not a WalletButtonElement"));const A={"access-token":(h=e.accessToken)!=null?h:"","buyer-country":(p=e.buyerCountry)!=null?p:"","buyer-currency":e.buyerCurrency,"wallet-params":JSON.stringify((m=this.walletParams)!=null?m:{}),"page-type":l,slot:u};try{e.disabled&&_.setAttribute("disabled",""),qt(_,A),e.isShippingRequired&&_.setAttribute("requires-shipping",""),e.hasSellingPlan&&_.setAttribute("has-selling-plan",""),e.pciEnabled&&_.setAttribute("pci-enabled","")}catch(P){const $=P;throw $.message.includes("setAttribute is not a function")&&Dc()?new ae($.message):$}if(s&&_.setAttribute("call-to-action",""),typeof _.setDataSource!="function")throw new ae("Custom element ".concat(E," is not properly upgraded, aborting execution"));return _.setDataSource(n),_.setApiClient(a),_.setI18n(r),_.setClassNames(o),_.setContainerInstanceNumber(i),_.onRendered=d,_}loadWalletSDK(){return Promise.resolve()}getLoadEligibility(e){return{eligible:!0}}getPartnerSDKEligibility(){return{eligible:!0}}}class Tc extends _e{static walletName(){return"buy_it_now"}getWebComponentName(){return"shopify-buy-it-now-button"}getInstrumentName(){return f.BuyItNow}getWebComponentClass(){return Ic}}const Nc="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}",kc='::slotted(div){height:100%}:host([page-type="cart_page"]) ::slotted(div){width:100%;min-width:150px}:host([page-type="cart_page"]) .accelerated-checkout-button{overflow:hidden;display:flex;justify-content:center}';async function He(t){const{cartId:e,cartClient:n,instrumentName:r,abortSignal:a}=t;try{if(!e)throw new Error("[".concat(r,"] provided no cart ID when updating buyer identity"));if(!n)throw new Error("[".concat(r,"] provided invalid cart client when updating buyer identity"));return await n.updateCartBuyerIdentity(t,a)}catch(i){throw y.updateFailed(r,"updateBuyerIdentity"),i}}async function $r({cartId:t,totalAmount:e,paymentMethod:n,billingAddress:r,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(!n)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:r}};return await a.updateCartPayment(t,w({amount:{amount:e.amount,currencyCode:e.currencyCode}},Number(e.amount)<=0&&!l&&!s?u:n),i,o)}catch(u){throw y.updateFailed(i,"updatePayment"),u}}function Tt(t){if(!t)return null;const e=getComputedStyle(t).borderRadius;return e.includes("px")?parseInt(e,10):null}function Nt(t){if(!t)return null;const e=getComputedStyle(t).height;return e.includes("px")?parseInt(e,10):null}const nr=25,wn=55,Lc=["cart_not_ready","cart_throttled","payment_method_not_applicable","invalid_payment_deferred_payment_required"],ar="PAYPAL_CALLBACK_HANDLED_ERROR";var pe;class Oc extends we{constructor(){super(...arguments),c(this,"name",f.PayPal),c(this,"abortController",null),c(this,"cartId"),c(this,"sdkButtonsComponent"),c(this,"container",null),c(this,"resizeObserver",null),c(this,"buttonHeight"),c(this,"rendering",!1),c(this,"prevBorderRadius",0),c(this,"prevHeight",0),H(this,pe,!1)}connectedCallback(){this.resizeObserver=Ne("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(n){}finally{this.sdkButtonsComponent=void 0}}async onResize(){const e=Tt(this.container),n=Nt(this.container),r=e!==null&&this.prevBorderRadius!==e||n!==null&&this.prevHeight!==n;!this.rendering&&r&&(await this.teardownPayPalButton(),this.container.innerHTML="",await this.cleanupOnFailure(()=>this.renderFromPayPalSDK(),this.name))}async render(){var e;const n=this.getOrCreateShadowRoot(),r=document.createElement("div");r.className=ke.BUTTON;const a=document.createElement("style");a.innerHTML=Nc,this.appendChild(a),await this.initializeShadowStyles(n,kc),n.appendChild(r),this.container=r,this.renderFromPayPalSDK(),(e=this.resizeObserver)==null||e.observe(this.container)}getHeight(){const e=Nt(this.container);return e?e>=nr&&e<=wn?e:ethis.createToken(this.apiClient);let i,o;this.requiresBillingAgreement()?o=a:i=a;const s=Tt(this.container),l=this.getHeight();this.prevHeight=l;const u={color:"gold",label:this.isCTA?"pay":"paypal",disableMaxWidth:!0,height:l,shape:"sharp"};s&&s>0&&(u.borderRadius=s,this.prevBorderRadius=s);const d=await this.i18n;this.sdkButtonsComponent=(n=(e=Aa(this.walletParams.sdkUrl))==null?void 0:e.Buttons)==null?void 0:n.call(e,{fundingSource:"paypal",style:u,createOrder:i,createBillingAgreement:o,onApprove:async p=>{await this.onApprove(p)},onCancel:()=>{this.cancelPaymentSheet("Payment sheet cancelled")},onClick:this.onClick.bind(this),onError:p=>{this.onError(p,d)}});let h=!1;try{await((r=this.sdkButtonsComponent)==null?void 0:r.render(this.container)),h=!0}catch(p){y.renderFailed(this.name),y.log({body:"PayPal Button not able to render into container.",attributes:{pageType:this.pageType,error:p==null?void 0:p.toString()}})}finally{this.rendering=!1}h&&this.onRendered()}cancelPaymentSheet(e){var n;U(this,pe,!0),y.sheetCancelled(this.name),(n=this.abortController)==null||n.abort("[PayPal] ".concat(e))}async onClick(e,n){var r,a;if(this.disabled)return n.reject();U(this,pe,!1),this.abortController=Ne("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,d]=await Promise.all([this.dataSource,this.i18n]);try{const{decelerationReason:h,cart:p,customValidationError:m,unrecoverableError:E,abortReason:_}=await be({element:this,instrumentName:this.name,dataSource:u});if(E)return y.sheetClicked({instrument:this.name,result:"failed"}),Oe(d,E),n.reject();if(_==="out_of_stock")return y.sheetClicked({instrument:this.name,result:"failed"}),ge(d),n.reject();if(m)return Le(d,m.message),n.reject();const{hasManagedSellingPlanState:A}=this.walletParams;return A!=null&&A!==this.hasSellingPlan?(ye((r=p==null?void 0:p.checkoutUrl)!=null?r:""),n.reject()):h?(F({checkoutUrl:(a=p==null?void 0:p.checkoutUrl)!=null?a:"",instrumentName:this.name,reason:h}),n.reject()):(this.cartId=p.id,n.resolve())}catch(h){return y.sheetClicked({instrument:this.name,result:"failed"}),b.notify(h),bt(d),n.reject()}}async createToken(e){const n=await e;try{if(!this.cartId)throw new Error("cartId not found when creating token");const r=await n.paypalTokenCreate(this.cartId);return y.sheetClicked({instrument:this.name,result:"success"}),r}catch(r){throw C(this,pe)||(y.sheetClicked({instrument:this.name,result:"failed"}),b.notify(r)),new Error(ar)}}async onApprove({orderID:e,payerID:n,billingToken:r}){var a;try{if(y.authorizationAttempt(this.name),Ze(L.AuthorizationLatency,this.name),!this.cartId)throw new Error("Cart not found");const i=await this.apiClient,o=this.requiresBillingAgreement()&&r!=null?r:e,{billingAddress:s,destinationAddress:l,expiresAt:u,email:d,remoteOrderId:h}=await i.paypalBuyerDetailsFetch(o,this.cartId),p=await He({cartId:this.cartId,cartClient:i,instrumentName:this.name,emailAddress:d,streetAddress:l});if(!(p!=null&&p.data))throw new Error("Cart not found");if(await this.decelerateOrAbort(p))return;const{id:m,totalAmount:E,checkoutUrl:_}=p.data,A=await $r({abortSignal:(a=this.abortController)==null?void 0:a.signal,cartClient:i,cartId:m,instrumentName:f.PayPal,billingAddress:s!=null?s:l,paymentMethod:{walletPaymentMethod:{paypalWalletContent:{billingAddress:s!=null?s:l,email:d,expiresAt:u,payerId:n,token:h!=null?h:e,acceptedSubscriptionTerms:!1,vaultingAgreement:!1,merchantId:this.walletParams.merchantId}}},canUsePaymentMethodForFreeOrder:!0,totalAmount:E});if(await this.decelerateOrAbort(A))return;y.authorizationComplete({instrument:this.name,result:"success",measurement:K(L.AuthorizationLatency,this.name)}),ye(_)}catch(i){throw C(this,pe)||(y.authorizationComplete({instrument:this.name,result:"failed",measurement:K(L.AuthorizationLatency,this.name)}),b.notify(i)),new Error(ar)}}onError(e,n){if(C(this,pe)||e.message.includes(ar))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"?y.log({body:"PayPal modal closed due to error: ".concat(e)}):b.notify(new xc(e));const r=n.translate("brand.paypal");O(r,n)}requiresBillingAgreement(){return this.walletParams.hasManagedSellingPlanState||this.walletParams.requiresBillingAgreement}shouldDecelerate(e){return!!(e&&Lc.includes(e))}async decelerateOrAbort(e){if(e.abortReason==="out_of_stock")return await this.handleOutOfStock(),!0;if(!e.data)return!1;const{totalAmount:n,checkoutUrl:r}=e.data;let a;return this.shouldDecelerate(e.decelerationReason)?a=e.decelerationReason:Lr({currentCartTotal:n,initialBuyerCurrency:this.buyerCurrency})&&(a="currency_changed"),a?(F({checkoutUrl:r,instrumentName:this.name,reason:a}),!0):!1}async handleOutOfStock(){y.authorizationComplete({instrument:this.name,result:"failed",measurement:K(L.AuthorizationLatency,this.name)}),ge(await this.i18n)}}pe=new WeakMap;class xc extends Error{constructor(e){e instanceof Error?(super(e.message,{cause:e.cause}),this.stack=e.stack):super(String(e)),this.name="PayPalError"}}const Ue=class Hn extends _e{static walletName(){return"paypal"}constructor(e){super(e)}getWebComponentName(){return"shopify-paypal-button"}getInstrumentName(){return f.PayPal}getWebComponentClass(){return Oc}loadWalletSDK(){let e=Hn.paypalSDKPromiseByUrl.get(this.walletParams.sdkUrl);if(e)return e;const n=document.createElement("script");return n.setAttribute("src",this.walletParams.sdkUrl),e=new Promise((r,a)=>{n.setAttribute("data-namespace",Ca(this.walletParams.sdkUrl)),n.onload=()=>r(),n.onerror=i=>{Hn.paypalSDKPromiseByUrl.delete(this.walletParams.sdkUrl),n&&document.body.contains(n)&&document.body.removeChild(n),a(i)},document.body.appendChild(n)}),Hn.paypalSDKPromiseByUrl.set(this.walletParams.sdkUrl,e),e}getLoadEligibility(){return{eligible:!0}}getPartnerSDKEligibility(){var e,n;try{return(n=(e=Aa(this.walletParams.sdkUrl))==null?void 0:e.Buttons)!=null&&n.call(e).isEligible()?{eligible:!0}:{eligible:!1,reason:"PayPal SDK not eligible"}}catch(r){throw new X({code:"paypal-sdk-eligibility-check-failed",message:"PayPal SDK 'isEligible' method failed unexpectedly: ".concat(r)})}}};c(Ue,"paypalSDKPromiseByUrl",new Map);let yr=Ue;const Mc=".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}",gr={UK:"GB",JA:"JP"},La=["AS","GU","MP","PR","VI"];La.forEach(t=>{gr[t]="US"});function Ct(t){var e,n;const r=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:((n=t==null?void 0:t.addressLines)==null?void 0:n[1])||void 0,city:t.locality||void 0,zip:t.postalCode||void 0,province:t.administrativeArea||t.subLocality||void 0,country:Uc(t.countryCode),phone:t.phoneNumber||void 0};return a.country==="HK"&&(a.zip=void 0,a.province=t.postalCode),r&&La.includes(r)&&(a.province=r),a.lastName||(a.lastName=a.firstName),a}function Uc(t){if(!t)return"ZZ";const e=t.toUpperCase();return Object.keys(gr).includes(e)?gr[e]:e}function Fc(t,e){return t.map(n=>{const{title:r,deliveryPromise:a}=zc(n,e);return{title:r,estimatedCost:{amount:$c(n),currencyCode:n[0].estimatedCost.currencyCode},handle:xa(n),deliveryPromise:a}})}function Bc(t,e){return t.map(n=>{const{title:r,description:a}=Hc(n,e);return{title:r,description:a,handle:xa(n)}})}function Oa({deliveryGroups:t}){return t.map(e=>e.deliveryOptions.filter(({deliveryMethodType:n})=>n==="SHIPPING").map(n=>k(w({},n),{groupType:e.groupType}))).reduce((e,n)=>e.flatMap(r=>n.map(a=>[...r,a])),[[]])}function $c(t){return t.reduce((e,n)=>e+Number(n.estimatedCost.amount),0).toFixed(2)}function zc(t,e){const n=t.find(l=>l.groupType===Te.OneTimePurchase),r=t.find(l=>l.groupType===Te.Subscription),a=[...new Set([n==null?void 0:n.title,r==null?void 0:r.title])].filter(Boolean),i=[...new Set([n==null?void 0:n.deliveryPromise,r==null?void 0:r.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 n=t.find(o=>o.groupType===Te.OneTimePurchase),r=t.find(o=>o.groupType===Te.Subscription),a=t.map(Gc).filter(Boolean).join(", ");let i=(n==null?void 0:n.title)||(r==null?void 0:r.title);return n&&r&&(i=e.translate("shipping_methods.connect_shipping_methods",{methodOne:n.title,methodTwo:r.title})),{title:i,description:a}}function Gc(t){const e=Number(t.estimatedCost.amount).toFixed(2),n=t.estimatedCost.currencyCode,r=t.deliveryPromise;return r?"(".concat(r,") ").concat(e," ").concat(n):"".concat(e," ").concat(n)}function xa(t){return t.map(e=>e.handle).join(",")}function Ma({deliveryGroups:t,i18n:e}){const n=t.some(r=>r.groupType===Te.Subscription);return t.map(r=>{var a;let i=e.translate("order_summary.shipping");return n&&(i=r.groupType===Te.Subscription?e.translate("order_summary.shipping_subscription"):e.translate("order_summary.shipping_one_time_purchase")),{label:i,amount:Re(((a=r.selectedDeliveryOption)==null?void 0:a.estimatedCost.amount)||0)}})}function Vc(t,e){return ot({label:t,possibleLines:[e]})[0]}function qc({subtotal:t,deliveryGroups:e,duties:n,taxes:r,discountAllocations:a,i18n:i,formattedRecurringTotals:o}){var s;const l=ot({label:i.translate("order_summary.subtotal"),possibleLines:[t]}),u=Ma({deliveryGroups:e,i18n:i}),d=ot({label:i.translate("order_summary.duties"),possibleLines:[n]}),h=ot({label:i.translate("order_summary.taxes"),possibleLines:[r]}),p=o.map(_=>({label:_,amount:"0.00",type:"pending"})),m=p.length?[{label:i.translate("order_summary.subscriptions.recurring_total_tooltip_line"),amount:"0.00",type:"pending"}]:[],E=(s=a==null?void 0:a.flatMap(_=>{var A;const P=(A=_.title)!=null?A:_.code;return ot({label:P!=null?P:i.translate("order_summary.discount"),possibleLines:[_.discountedAmount],isDiscount:!0})}))!=null?s:[];return[...l,...u,...d,...h,...E,...p,...m]}function ot({label:t,possibleLines:e,isDiscount:n=!1}){return e.filter(r=>(r==null?void 0:r.amount)!==void 0).map(r=>({label:t,amount:n?"-".concat(Re(r.amount)):Re(r.amount)}))}function _n(t,e){if(!t.length)return[];const n=Oa({deliveryGroups:t});return Fc(n,e).map(r=>{var a;return{label:r.title||"",amount:r.estimatedCost.amount,identifier:r.handle,detail:(a=r.deliveryPromise)!=null?a:""}})}const ir=async({paymentSheetAction:t,onProceed:e,terminateSession:n})=>{switch(t.action){case"abort":n();break;case"show_error":await e(t.errors);break;case"update":await e(t.errors);break;default:throw new Error('Missing handler for payment sheet action "'.concat(t.action,'"'))}},Wc=["decelerate","abort","show_error","complete","update"];class Ge extends Xn{constructor(){super(...arguments),c(this,"name","UnhandledActionError")}}class Ua{constructor(){c(this,"generatePrioritizedPaymentSheetAction",(e,n)=>{let r;const a=[],i=[],o=[],s=n.filter(u=>u!==g.UnacceptablePaymentsAmount).some(u=>e[u]!==void 0);for(const u of Object.keys(e))if(!(u===g.UnacceptablePaymentsAmount&&s)){const d=e[u]();d.effects&&i.push(...d.effects),d.action!=="complete"&&d.errors&&o.push(...d.errors),a.push(d)}const l=(u=>Wc.map(d=>u.find(h=>h.action===d)).find(d=>!!d))(a);return l&&(r=l,r.effects=i,r.action!=="complete"&&(r.errors=o)),r})}getMergedPaymentSheetAction({result:e,errorActions:n}){const r={};n.forEach(i=>{i.errors.forEach(o=>{e.errors.includes(o)&&(r[o]=i.generateAction)})});let a;for(const i of e.errors){const o=r[i];if(o){a=o();break}}return{firstPaymentSheetAction:a,prioritizedPaymentSheetAction:this.generatePrioritizedPaymentSheetAction(r,e.errors)}}getUnhandledErrors(e,n){const r=n.flatMap(a=>a.errors);return e.filter(a=>!r.includes(a))}decelerateOrAbort({reason:e,instrumentName:n,errorOrWarning:r,result:a}){var i,o;return((i=a==null?void 0:a.data)==null?void 0:i.__typename)==="SubmitFailed"?{action:"decelerate",redirectUrl:(o=a.data)==null?void 0:o.checkoutUrl,reason:e}:{action:"abort",effects:[()=>{var s;b.notify(new Error("[".concat(n,"] unexpected ").concat(r," received in ").concat((s=a==null?void 0:a.data)==null?void 0:s.__typename," response, aborting")))}]}}}class jc extends Ua{constructor(e){super(),c(this,"completionResult"),this.i18n=e,this.completionResult=null}mapMutationResultToPaymentSheetAction(e,n){var r;const a=this.mapCustomValidationFunctionErrorToAction(e.errors);if(a)return a;const i=this.getErrorActions({shippingCountryCode:n==null?void 0:n.shippingCountryCode}),o=e.errors,s=this.getUnhandledErrors(o,i);if(s.forEach(u=>{b.notify(new Ge("[".concat(f.ApplePay,"] mutation result error not handled: ").concat(u),{groupingHash:"UnhandledActionError:".concat(f.ApplePay,":").concat(u)}))}),((r=e.data)==null?void 0:r.deliveryGroups.length)===0&&n!=null&&n.shippingRequired)return{action:"show_error",errors:[new ApplePayError("addressUnserviceable")]};const{firstPaymentSheetAction:l}=this.getMergedPaymentSheetAction({result:e,errorActions:i});return l||(s.length>0?{action:"abort",effects:[()=>{O(this.i18n.translate("brand.apple_pay"),this.i18n)}]}:{action:"update",errors:[]})}mapCompletionResultToPaymentSheetAction(e,n){if(!e.data)throw new Error("[".concat(f.ApplePay,"] completion returned null result"));switch(this.completionResult=e,e.data.__typename){case"SubmitSuccess":return{action:"complete",redirectUrl:e.data.redirectUrl};case"SubmitAlreadyAccepted":case"SubmitThrottled":case"SubmitFailed":{const r=this.mapCustomValidationFunctionErrorToAction(e.errors);if(r)return r;const a=this.getErrorActions({shippingCountryCode:n==null?void 0:n.shippingCountryCode}),i=e.errors;this.getUnhandledErrors(i,a).forEach(s=>{b.notify(new Ge("[".concat(f.ApplePay,"] completion result error not handled: ").concat(s),{groupingHash:"UnhandledActionError:".concat(f.ApplePay,":").concat(s)}))});const{prioritizedPaymentSheetAction:o}=this.getMergedPaymentSheetAction({result:e,errorActions:a});return o||{action:"abort",effects:[()=>{O(this.i18n.translate("brand.apple_pay"),this.i18n)}]}}default:throw new Error("[".concat(f.ApplePay,"] unknown completion result type: ").concat(e.data.__typename))}}getErrorActions({shippingCountryCode:e}){return[{errors:[g.CaptchaCompletionRequired],generateAction:()=>this.decelerateOrAbort({reason:"captcha_required",instrumentName:f.ApplePay,errorOrWarning:g.CaptchaCompletionRequired,result:this.completionResult})},{errors:[g.InvalidLanguage],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.ApplePay,"] mutation provided invalid language, aborting")))}]})},{errors:[g.InvalidCountry],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.ApplePay,"] mutation provided invalid country, aborting")))}]})},{errors:[g.MissingCartId],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.ApplePay,"] mutation provided invalid cart ID, aborting")))}]})},{errors:ya,generateAction:()=>({action:"abort",effects:[()=>{O(this.i18n.translate("brand.apple_pay"),this.i18n)}]})},{errors:[g.RedirectToCheckoutRequired],generateAction:()=>({action:"abort",effects:[()=>{O(this.i18n.translate("brand.apple_pay"),this.i18n)}]})},{errors:Dr,generateAction:()=>this.decelerateOrAbort({reason:"dynamic_tax",instrumentName:f.ApplePay,errorOrWarning:g.NewTaxMustBeAccepted,result:this.completionResult})},{errors:fa,generateAction:()=>this.decelerateOrAbort({reason:"not_enough_stock",instrumentName:f.ApplePay,errorOrWarning:g.MerchandiseNotEnoughStock,result:this.completionResult})},{errors:[g.MerchandiseOutOfStock],generateAction:()=>({action:"abort",effects:[()=>ge(this.i18n)]})},{errors:ga,generateAction:()=>({action:"abort",effects:[()=>O(this.i18n.translate("brand.apple_pay"),this.i18n)]})},{errors:ma,generateAction:()=>({action:"show_error",errors:[new ApplePayError("addressUnserviceable")]})},{errors:[g.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","emailAddress",this.i18n.translate("errors.missing.email"))]})},{errors:to,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.missing.first_name"))]})},{errors:ro,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.invalid.first_name"))]})},{errors:no,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.missing.last_name"))]})},{errors:ao,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.invalid.last_name"))]})},{errors:io,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.missing.address1"))]})},{errors:[g.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address1"))]})},{errors:oo,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.missing.address2"))]})},{errors:[g.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address2"))]})},{errors:so,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.missing.city"))]})},{errors:[g.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.invalid.city"))]})},{errors:[g.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.missing.zone"),this.i18n.translate("errors.missing.emirate"),"shippingContactInvalid",e)]})},{errors:[g.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.invalid.zone"),this.i18n.translate("errors.invalid.emirate"),"shippingContactInvalid",e)]})},{errors:lo,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.missing.postal_code"))]})},{errors:pa,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.invalid.postal_code"))]})},{errors:[g.DeliveryCountryRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","country",this.i18n.translate("errors.missing.country"))]})},{errors:co,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.missing.phone"))]})},{errors:ho,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.invalid.phone"))]})},{errors:uo,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","country",this.i18n.translate("errors.invalid.country"))]})},{errors:mo,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid")]})},{errors:[g.UnsupportedApplePayPaymentMethod],generateAction:()=>({action:"abort",effects:[()=>{O(this.i18n.translate("brand.apple_pay"),this.i18n)},()=>{b.notify(new Ge("[".concat(f.ApplePay,"] payment method is not supported"),{groupingHash:"UnhandledActionError:".concat(f.ApplePay,":payment_method_not_supported")}))}]})},{errors:[g.PaymentsMethodRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("unknown")]})},{errors:[g.CustomValidation],generateAction:()=>({action:"abort",effects:[()=>{O(this.i18n.translate("brand.apple_pay"),this.i18n)}]})},{errors:[g.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.emojis.last_name"))]})},{errors:[g.DeliveryFirstNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.emojis.first_name"))]})},{errors:[g.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.too_long.address1"))]})},{errors:[g.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.too_long.address2"))]})},{errors:[g.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.too_long.first_name"))]})},{errors:[g.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.too_long.last_name"))]})},{errors:[g.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.too_long.city"))]})},{errors:[g.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.url.first_name"))]})},{errors:[g.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.url.last_name"))]})},{errors:[g.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address1"))]})},{errors:[g.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address2"))]})},{errors:[g.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.html_tags.city"))]})},{errors:[g.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.html_tags.first_name"))]})},{errors:[g.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.html_tags.last_name"))]})},{errors:[g.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.emojis.city"))]})},{errors:[g.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address1"))]})},{errors:[g.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address2"))]})},{errors:[g.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.emojis.postal_code"))]})},{errors:[g.BuyerIdentityEmailInvalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","emailAddress",this.i18n.translate("errors.invalid.email"))]})},{errors:[g.DiscountNotApplicable],generateAction:()=>({action:"show_error",errors:[new ApplePayError("couponCodeInvalid",void 0,this.i18n.translate("errors.invalid.discount"))]})}]}mapCustomValidationFunctionErrorToAction(e){const n=kr(e);return n?{action:"abort",effects:[()=>{const r=this.i18n.translate("brand.apple_pay");Or(this.i18n.translate("error_dialogs.wallet.title",{wallet:r}),n.message)}]}:null}createApplePayZoneError(e,n,r,a){const i=a==="AE"?"subLocality":"administrativeArea";return new ApplePayError(r,i,a==="AE"?n:e)}}const En=["name","postalAddress"];function Yc({shippingRequired:t,walletParams:e,buyerCurrency:n}){const{phoneRequired:r,emailRequired:a}=e,i=[...a?["email"]:[],...r?["phone"]:[]],o=t?[...En,...i]:i;return{countryCode:e.countryCode,currencyCode:n,merchantCapabilities:e.merchantCapabilities,supportedNetworks:e.supportedNetworks,total:{type:"pending",label:e.merchantName,amount:"1.00"},requiredBillingContactFields:En,requiredShippingContactFields:o,shippingType:e.shippingType}}const Kc=t=>{const e=t.lineItems.flatMap(n=>n.discountAllocations);return[...t.discountCodes.filter(n=>n.applicable&&t.discountAllocations.findIndex(r=>r.code===n.code)===-1&&e.findIndex(r=>r.code===n.code)===-1).map(n=>({code:n.code,discountedAmount:{amount:"0",currencyCode:t.totalAmount.currencyCode}})),...t.discountAllocations,...e]},Fa=t=>{const e=t.lineItems.reduce((n,r)=>n+Number(r.subtotalAmount.amount),0);return{amount:String(e),currencyCode:t.totalAmount.currencyCode}};function Qc(t,e){return t.reduce((n,r)=>{if(!r.sellingPlanAllocation)return n;const{sellingPlanAllocation:{sellingPlan:a,priceAdjustments:i},quantity:o}=r;if(!a.recurringDeliveries||!a.billingPolicy)return n;const s=Jc({billingPolicy:a.billingPolicy,i18n:e});if(i.length===0){const l=St({price:Number(r.subtotalAmount.amount)*o,currencyCode:r.subtotalAmount.currencyCode,locale:e.locale});return[...n,e.translate("order_summary.subscriptions.recurring_totals",{fixedPrice:l,interval:s})]}else if(i.length===1){const l=St({price:Number(i[0].price.amount)*o,currencyCode:i[0].price.currencyCode,locale:e.locale});return[...n,e.translate("order_summary.subscriptions.recurring_totals",{fixedPrice:l,interval:s})]}else if(i.length===2){const l=St({price:Number(i[0].price.amount)*o,currencyCode:i[0].price.currencyCode,locale:e.locale}),u=St({price:Number(i[1].price.amount)*o,currencyCode:i[1].price.currencyCode,locale:e.locale}),d=a.priceAdjustments[0].orderCount;return[...n,e.translate("order_summary.subscriptions.recurring_totals_with_policies",{count:d,fixedPrice:l,recurringPrice:u,interval:s})]}return n},[])}function St({price:t,currencyCode:e,locale:n}){return Intl.NumberFormat(n,{style:"currency",currency:e,currencyDisplay:"narrowSymbol"}).format(t)}function Jc({billingPolicy:t,i18n:e}){const{interval:n,intervalCount:r}=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"}[n];if(!a)throw new Error("Unknown selling plan interval provided: ".concat(n));return e.translate(a,{count:r})}async function Ba({cartId:t,cartClient:e,instrumentName:n,selectedDeliveryOptions:r,abortSignal:a}){try{if(!t)throw new Error("[".concat(n,"] provided no cart ID when updating shipping method"));if(!e)throw new Error("[".concat(n,"] provided invalid cart client when updating shipping method"));return await e.updateSelectedDeliveryOptions(t,r,n,a)}catch(i){throw y.updateFailed(n,"updateSelectedDeliveryOptions"),i}}async function $a({cartId:t,token:e,cartClient:n,instrumentName:r}){try{if(!t)throw new Error("[".concat(r,"] provided no cart ID when submitting for completion"));if(!n)throw new Error("[".concat(r,"] provided invalid cart client when submitting for completion"));if(!e)throw new Error("[".concat(r,"] provided no token when submitting for completion"));return await n.submitForCompletion(t,e,r)}catch(a){throw y.updateFailed(r,"submitForCompletion"),a}}function za({selectedDeliveryOptionHandles:t,deliveryGroups:e,instrumentName:n}){return e.map(r=>{const a=r.deliveryOptions.filter(i=>t.includes(i.handle));if(!a.length)return{deliveryGroupId:"",deliveryOptionHandle:""};if(a.length>1)throw new Xn("[".concat(n,"] found multiple delivery options with selectedDeliverOptionHandle in group: ").concat(r.id),{groupingHash:"getSelectedDeliveryOptions::MultipleOptions"});return{deliveryGroupId:r.id,deliveryOptionHandle:a[0].handle}}).filter(r=>!!r.deliveryGroupId)}async function Xc(t){const{cartClient:e,instrumentName:n}=t;try{if(!t.cartId)throw new Error("[".concat(n,"] provided no cart ID when updating billing address"));if(!e)throw new Error("[".concat(n,"] provided invalid cart client when updating billing address"));return await e.updateCartBillingAddress(t)}catch(r){throw y.updateFailed(n,"updateBillingAddress"),r}}function An(t,e){return t.some(n=>e.includes(n))}function ct({result:t,instrument:e}){var n;const r=(n=t.errors)!=null?n:[];An(r,Dr)&&y.dynamicTaxFailed({instrument:e}),An(r,po)&&y.dynamicShippingFailed({instrument:e})}const Cn=["cart_not_ready","cart_throttled","not_enough_stock","payment_method_not_applicable"];class Zc{constructor({accessToken:e,buyerCountry:n,buyerCurrency:r,button:a,i18n:i,merchantName:o,dataSource:s,apiClient:l,walletParams:u}){c(this,"name",f.ApplePay),c(this,"accessToken"),c(this,"button"),c(this,"buyerCountry"),c(this,"cart"),c(this,"apiClient"),c(this,"dataSource"),c(this,"i18n"),c(this,"merchantName"),c(this,"session"),c(this,"paymentSheetActionGenerator"),c(this,"cancelled"),c(this,"buyerCurrency"),c(this,"customerAccountEmail"),c(this,"abortController",null),c(this,"isPersonalDataCleared",!1),c(this,"isSheetLoaded",!1),c(this,"onvalidatemerchant",async d=>{var h,p,m;try{const E=new URL(d.validationURL),_=this.getMerchantSession(E),{cart:A,decelerationReason:P,customValidationError:$,unrecoverableError:M}=await be({element:this.button,instrumentName:this.name,dataSource:this.dataSource});if(M){y.sheetClicked({instrument:this.name,result:"failed"}),this.session.abort(),(h=this.abortController)==null||h.abort("[Apple Pay] Unrecoverable error ".concat(M)),Oe(this.i18n,M);return}if($){this.session.abort(),(p=this.abortController)==null||p.abort("[Apple Pay] Custom validation error"),Le(this.i18n,$.message);return}this.cart=A;const le=await _;if(b.leaveBreadcrumb("ApplePay Session completeMerchantValidation",{session:le},"log"),P&&Cn.includes(P)){await this.terminateSession(),F({checkoutUrl:(m=A==null?void 0:A.checkoutUrl)!=null?m:"",instrumentName:this.name,reason:P});return}if(this.sessionIsCancelled())return;this.session.completeMerchantValidation(le)}catch(E){y.sheetClicked({instrument:f.ApplePay,result:"failed"}),this.terminateSession(E)}}),c(this,"onshippingcontactselected",async d=>{try{const h=Ct(d.shippingContact),p=await He({cartId:this.cart.id,streetAddress:h,cartClient:this.apiClient,instrumentName:this.name});if(!p.data)throw new Error("Missing cart during Apple Pay Session creation");if(await this.decelerateOrAbort(p))return;await this.applyPaymentSheetActions(p,m=>this.completeShippingContactSelection(p.data,m),{shippingRequired:this.isShippingRequired,shippingCountryCode:h.country})}catch(h){this.terminateSession(h)}}),c(this,"onshippingmethodselected",async d=>{var h;try{const p=d.shippingMethod.identifier.split(","),m=za({selectedDeliveryOptionHandles:p,deliveryGroups:this.cart.deliveryGroups,instrumentName:this.name});if(m.length===0){this.handleShippingMethodNotFoundInCart(p);return}const E=await Ba({cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name,selectedDeliveryOptions:m,abortSignal:(h=this.abortController)==null?void 0:h.signal});if(await this.decelerateOrAbort(E))return;await this.applyPaymentSheetActions(E,()=>this.completeShippingMethodSelection(E.data),{shippingRequired:this.isShippingRequired,shippingCountryCode:void 0}),this.onSheetLoaded()}catch(p){this.terminateSession(p)}}),c(this,"onpaymentmethodselected",async d=>{try{const{billingContact:h}=d.paymentMethod;if(!this.isShippingRequired&&h){const E=Ct(h),_=await He({cartId:this.cart.id,countryCode:E.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(_,()=>this.cart=_.data,{shippingRequired:this.isShippingRequired,shippingCountryCode:E.country});const A=await Xc({billingAddress:E,cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name});await this.applyPaymentSheetActions(A,()=>this.cart=A.data,{shippingRequired:this.isShippingRequired,shippingCountryCode:E.country})}const{newTotal:p,newLineItems:m}=this.getNewTotalAndLineItems(this.cart);if(b.leaveBreadcrumb("ApplePay Session completePaymentMethodSelection",{newTotal:p,newLineItems:m},"log"),this.sessionIsCancelled())return;this.session.completePaymentMethodSelection({newTotal:p,newLineItems:m}),this.isShippingRequired||this.onSheetLoaded()}catch(h){this.terminateSession(h)}}),c(this,"oncancel",()=>{var d;this.cancelled=!0,this.removePersonalData(),K(L.SheetLoad,this.name),y.sheetCancelled(this.name),this.button.disabled=!1,(d=this.abortController)==null||d.abort("[Apple Pay] Payment sheet cancelled")}),c(this,"onpaymentauthorized",async d=>{y.authorizationAttempt(this.name),Ze(L.AuthorizationLatency,this.name);const h=T=>{y.authorizationComplete({instrument:this.name,measurement:K(L.AuthorizationLatency,this.name),result:"failed"}),this.terminateSession(T)},p=async T=>{var G,z;switch((G=T.effects)==null||G.forEach(x=>x()),T.action){case"complete":{const x=ApplePaySession.STATUS_SUCCESS;try{await this.completePayment(x),ye(T.redirectUrl)}catch(se){h(se)}break}case"show_error":{const x=(z=T.errors)!=null?z:[];try{await this.completePayment(ApplePaySession.STATUS_FAILURE,x)}catch(se){h(se)}break}case"abort":{try{this.abortPaymentSheetAndShowError(),this.removePersonalData()}catch(x){h(x)}break}case"decelerate":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),await this.removePersonalData(),F({checkoutUrl:T.redirectUrl,instrumentName:this.name,reason:T.reason})}catch(x){h(x)}break}default:h(new Error("[".concat(this.name,"] completion action not handled: ").concat(T.action)))}},{token:m,billingContact:E,shippingContact:_}=d.payment;let A=null,P=null;try{if(!E){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}if(A=Ct(k(w({},E),{phoneNumber:_==null?void 0:_.phoneNumber})),this.isShippingRequired){if(!_){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}P=Ct(_)}}catch(T){h(T);return}const $=async()=>{var T;try{const G=this.isShippingRequired?{validateAddress:!0,streetAddress:P}:{},z=(T=this.customerAccountEmail)!=null?T:_==null?void 0:_.emailAddress,x=await He(w({cartId:this.cart.id,emailAddress:z,cartClient:this.apiClient,instrumentName:this.name},G));if(ct({result:x,instrument:this.name}),await this.decelerateOrAbort(x))return;const se=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(x,{shippingRequired:this.isShippingRequired,shippingCountryCode:P==null?void 0:P.country});await ir({paymentSheetAction:se,onProceed:async ce=>{ce&&ce.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,ce):await M()},terminateSession:h})}catch(G){h(G)}},M=async()=>{var T;try{const G=this.cart.lineItems.some(se=>!!se.sellingPlanAllocation),z=await $r({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{applePayWalletContent:{billingAddress:A,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:A,cartClient:this.apiClient,instrumentName:this.name,hasSellingPlan:G,abortSignal:(T=this.abortController)==null?void 0:T.signal});if(ct({result:z,instrument:this.name}),await this.decelerateOrAbort(z))return;const x=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(z,{shippingRequired:this.isShippingRequired,shippingCountryCode:P==null?void 0:P.country});await ir({paymentSheetAction:x,onProceed:async se=>{se&&se.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,se):await le()},terminateSession:h})}catch(G){h(G)}},le=async()=>{try{const T=await $a({cartId:this.cart.id,token:m.transactionIdentifier,cartClient:this.apiClient,instrumentName:this.name});ct({result:T,instrument:this.name});const G=this.paymentSheetActionGenerator.mapCompletionResultToPaymentSheetAction(T,{shippingRequired:this.isShippingRequired,shippingCountryCode:P==null?void 0:P.country});await p(G)}catch(T){h(T)}};await $()}),c(this,"terminateSession",async d=>{var h;try{this.button.disabled=!1,K(L.SheetLoad,this.name),d&&b.notify(d),y.sheetFailed(this.name,d);try{b.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.session.abort(),(h=this.abortController)==null||h.abort("[Apple Pay] Payment sheet terminated")}catch(p){console.debug("[DEBUG] InvalidAccessError occurred during Apple Pay terminateSession")}if(d){const p=this.i18n.translate("brand.apple_pay");O(p,this.i18n)}}finally{await this.removePersonalData()}}),c(this,"getMostRecentNonNullCart",(d,h)=>d?(this.cart=d,d):h),c(this,"handleNullCart",d=>{if(!d)throw new Error("[".concat(this.name,"] no cart returned on mutation, aborting"))}),c(this,"completeShippingContactSelection",(d,h)=>{try{const p=this.getMostRecentNonNullCart(d,this.cart),{newTotal:m,newLineItems:E}=this.getNewTotalAndLineItems(p),_=_n(p.deliveryGroups,this.i18n);b.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{errors:h,newTotal:m,newLineItems:E,newShippingMethods:_},"log"),this.session.completeShippingContactSelection({errors:h!=null?h:[],newTotal:m,newLineItems:E,newShippingMethods:_})}catch(p){this.terminateSession(p)}}),c(this,"completeShippingMethodSelection",d=>{try{this.handleNullCart(d),this.cart=d;const{newTotal:h,newLineItems:p}=this.getNewTotalAndLineItems(d);b.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{newTotal:h,newLineItems:p},"log"),this.session.completeShippingMethodSelection({newTotal:h,newLineItems:p})}catch(h){this.terminateSession(h)}}),c(this,"sessionIsCancelled",()=>this.cancelled),this.accessToken=e,this.buyerCountry=n,this.button=a,this.cart=null,this.apiClient=l,this.dataSource=s,this.i18n=i,this.merchantName=o,this.cancelled=!1,this.buyerCurrency=r,this.customerAccountEmail=u.customerAccountEmail,this.session=new ApplePaySession(Gn,Yc({shippingRequired:this.isShippingRequired,walletParams:u,buyerCurrency:r})),this.session.onvalidatemerchant=this.onvalidatemerchant,this.session.onshippingcontactselected=this.onshippingcontactselected,this.session.onshippingmethodselected=this.onshippingmethodselected,this.session.onpaymentmethodselected=this.onpaymentmethodselected,this.session.oncancel=this.oncancel,this.session.onpaymentauthorized=this.onpaymentauthorized,this.paymentSheetActionGenerator=new jc(i)}begin(){b.leaveBreadcrumb("ApplePay Session begin",{},"log"),this.abortController=Ne("AbortController"),this.session.begin()}handleShippingMethodNotFoundInCart(e){var n,r;const a=_n((r=(n=this.cart)==null?void 0:n.deliveryGroups)!=null?r:[],this.i18n);b.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(e,n,r){var a;const i=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(e,r);(a=i.effects)==null||a.forEach(o=>o()),!this.sessionIsCancelled()&&await ir({paymentSheetAction:i,onProceed:n,terminateSession:this.terminateSession})}async getMerchantSession(e){const n=await new Ht({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,apiVersion:"unstable"}).applePaySessionCreate(e);return JSON.parse(n)}abortPaymentSheetAndShowError(){b.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.session.abort(),this.button.disabled=!1,this.emitPaymentCompleteTelemetry(ApplePaySession.STATUS_FAILURE)}abortPaymentSheetAndShowOutOfStockModal(){b.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.session.abort(),this.button.disabled=!1,ge(this.i18n),this.emitPaymentCompleteTelemetry(ApplePaySession.STATUS_FAILURE)}emitPaymentCompleteTelemetry(e){y.authorizationComplete({instrument:this.name,measurement:K(L.AuthorizationLatency,this.name),result:e===ApplePaySession.STATUS_SUCCESS?"success":"failed"})}async completePayment(e,n=void 0){b.leaveBreadcrumb("ApplePay Session completePayment",{status:e,errors:n},"log"),this.session.completePayment({status:e,errors:n}),this.emitPaymentCompleteTelemetry(e)}getNewTotalAndLineItems(e){return{newTotal:Vc(this.merchantName,e.totalAmount),newLineItems:qc({subtotal:Fa(e),discountAllocations:Kc(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"?(this.abortPaymentSheetAndShowOutOfStockModal(),!0):this.decelerateIfNeeded(e)}async decelerateIfNeeded(e){if(!e.data)return!1;const{checkoutUrl:n,totalAmount:r}=e.data;let a;if(e.decelerationReason&&Cn.includes(e.decelerationReason)?a=e.decelerationReason:Lr({currentCartTotal:r,initialBuyerCurrency:this.buyerCurrency})&&(a="currency_changed"),a){try{await this.terminateSession()}finally{F({checkoutUrl:n,instrumentName:this.name,reason:a})}return!0}return!1}get isShippingRequired(){return this.button.isShippingRequired}async removePersonalData(){this.isPersonalDataCleared||!this.cart||(await this.apiClient.cartRemovePersonalData({cartId:this.cart.id,instrumentName:this.name}),this.isPersonalDataCleared=!0)}onSheetLoaded(){if(this.isSheetLoaded)return;this.isSheetLoaded=!0;const e=K(L.SheetLoad,this.name);e&&(V({event:B.SheetLoaded,ttl:e}),y.sheetLoaded({instrument:this.name,measurement:e}))}}function zr({translate:t,logoElement:e,setAriaHidden:n}){const r=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,n&&i.setAttribute("aria-hidden","true")),r.appendChild(i)}),r}const fr=new Map;function Je({instrumentName:t,logoType:e="LIGHT",logoContent:n}){const r=fr.get(t)||{};r[e]||(r[e]=n,fr.set(t,r))}function ht({instrumentName:t,logoType:e="LIGHT"}){var n;const r=(n=fr.get(t))==null?void 0:n[e];if(!r)throw new Error("".concat(t," ").concat(e," logo not loaded"));return r}class ed extends we{constructor(){super(...arguments),c(this,"name",f.ApplePay),c(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,n,r){super.attributeChangedCallback(e,n,r,this.button)}async handleClick(e){if(e.preventDefault(),this.disabled||!this.button||this.button.hasAttribute("aria-disabled"))return;this.disabled=!0;const[n,r,a]=await Promise.all([this.i18n,this.dataSource,this.apiClient]);Ze(L.SheetLoad,this.name);let i;try{if(i=new Zc({accessToken:this.accessToken,buyerCountry:this.buyerCountry,buyerCurrency:this.buyerCurrency,button:this,i18n:n,merchantName:this.merchantName,dataSource:r,apiClient:a,walletParams:this.walletParams}),!i)throw new Error("missing ApplePaySession");i.begin(),y.sheetClicked({instrument:this.name,result:"success"})}catch(o){b.notify(o),y.sheetClicked({instrument:this.name,result:"failed"}),i==null||i.terminateSession()}}async render(){var e;const n=this.getOrCreateShadowRoot(),{translate:r}=await this.i18n,a=ht({instrumentName:f.ApplePay}),i=new DOMParser().parseFromString(a,"image/svg+xml").documentElement;if(!this.button){const o=this.isCTA?r("buy_with_button_content",{wallet:r("brand.apple_pay")}):r("brand.apple_pay");if(this.button=Vt({label:o}),this.button.onclick=s=>this.handleClick(s),this.button.classList.add("apple-pay-button",fi[this.buttonTheme],ke.BUTTON),this.isCTA){const s=zr({translate:r,logoElement:i,setAriaHidden:!0});s.classList.add("apple-pay--content"),this.button.appendChild(s)}else this.button.appendChild(i);this.initializeShadowStyles(n,Mc),n.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 Hr(t){return function(e,n,r){const a=r.value;return r.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},r}}var td=Object.defineProperty,rd=Object.getOwnPropertyDescriptor,Ha=(t,e,n,r)=>{for(var a=rd(e,n),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,n,a)||a);return a&&td(e,n,a),a};class Gr extends _e{constructor(e){super(e),c(this,"companyFieldRequired"),this.companyFieldRequired=!!this.walletParams.companyRequired}static walletName(){return"apple_pay"}getWebComponentName(){return"shopify-apple-pay-button"}getWebComponentClass(){return ed}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,n,r,a;if(typeof window>"u"||window.ApplePaySession===void 0)return{eligible:!1,reason:"window or ApplePaySession is undefined"};try{if(!((n=(e=window.ApplePaySession).supportsVersion)!=null&&n.call(e,Gn)))return{eligible:!1,reason:"SDK does not meet minimum version requirement"};if(!((a=(r=window.ApplePaySession).canMakePayments)!=null&&a.call(r)))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(){const e=await import("./apple-pay-logo-BZB6IYWC.js");if(e)Je({instrumentName:f.ApplePay,logoContent:e.default});else throw new Error("Apple Pay logo is empty")}}Ha([Hr("Apple Pay")],Gr.prototype,"getLoadEligibility"),Ha([Hr("Apple Pay")],Gr.prototype,"getPartnerSDKEligibility");const nd=".buy-with-prime-button{width:100%;height:100%;padding:12px 10px 8px;display:flex;align-items:center;justify-content:center;gap:5px;opacity:1;border-width:0px}.buy-with-prime-button:hover:enabled{background-color:#0684eb!important}.buy-with-prime-button:focus{box-shadow:0 0 0 2px #1a98ff,inset 0 0 0 2px rgb(var(--color-background))!important;outline:none!important}.buy-with-prime-button:active,.buy-with-prime-button:hover:enabled:active{background-color:#0066cd!important;box-shadow:none!important}";class kt extends Error{constructor(){super(...arguments),c(this,"name","MissingAccessTokenError")}}class Vr extends Error{constructor(){super(...arguments),c(this,"name","FetchingWalletsPlatformConfigError")}}class qr extends Error{constructor(){super(...arguments),c(this,"name","EmptyLineItemsWalletsPlatformConfigError")}}async function Wr({configOptionsEndpoint:t,checkoutUrl:e,sourceId:n,accessToken:r,instrument:a}){try{const i=JSON.stringify({checkout_url:e,checkout_cancel_url:window.location.href,cart_id:n}),o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":r},body:i});if(o.ok)return o.json();const s=await o.json();throw s.error?new Error(s.error):new Error("Could not fetch wallets platform configs: [".concat(o.status,"] ").concat(o.statusText))}catch(i){const{message:o}=i!=null?i:{};switch(o){case"empty_line_items":throw new qr("[Fetch Pay Config][".concat(a,"] No eligible line items provided in the config request."));default:throw new Vr("[Fetch Pay Config][".concat(a,"] ").concat(o))}}}const ad={[v.Checkout]:"Checkout",[v.CartAjax]:"Cart",[v.CartPage]:"Cart",[v.ProductPage]:"Product",[v.Unknown]:"Product"},Fe=class vu extends we{constructor(){super(...arguments),c(this,"name",f.BuyWithPrime),c(this,"button",null),c(this,"apiClientId","")}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name),this.handleOnSendCheckoutAction=this.handleOnSendCheckoutAction.bind(this)}async triggerCheckout(){this.handleClick({showDisabledStyles:!1})}async createButton(){const{translate:e}=await this.i18n,n=Vt({label:e("brand.buy_with_prime")});return n.type="button",n.className="buy-with-prime-button",this.applyEnabledStyles(n),n}applyEnabledStyles(e){const n=ht({instrumentName:f.BuyWithPrime});e.innerHTML=n,e.disabled=!1,fn(e,{"background-color":"#1A98FF",color:"#FFFFFF",cursor:"pointer"})}applyDisabledStyles(e){const n=ht({instrumentName:f.BuyWithPrime,logoType:"DARK"});e.innerHTML=n,e.disabled=!0,fn(e,{"background-color":"#C0E3FF",color:"#7292AC",cursor:"not-allowed"})}async handleClick(e={showDisabledStyles:!0}){var n,r,a;if(!this.button)return;const[i,o]=await Promise.all([this.i18n,this.dataSource]);let s=[];try{e.showDisabledStyles&&this.applyDisabledStyles(this.button);let l=this.walletParams;if(this.apiClientId=this.apiClientId||l.appId||"",!l.createCheckoutSessionConfig){const{cart:d,decelerationReason:h,customValidationError:p,unrecoverableError:m}=await be({element:this,instrumentName:this.name,dataSource:o});if(m){y.sheetClicked({instrument:this.name,result:"failed",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,pageType:this.pageType}:void 0}),Oe(i,m);return}if(p){Le(i,p.message);return}if(h){F({checkoutUrl:(n=d==null?void 0:d.checkoutUrl)!=null?n:"",instrumentName:this.name,reason:h});return}if(!this.accessToken)throw new kt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");l=w({},await Wr({configOptionsEndpoint:vu.OPTIMUS_CONFIG_REST_API_URL,checkoutUrl:(r=d==null?void 0:d.checkoutUrl)!=null?r:"",sourceId:(a=Nr(d))!=null?a:"",accessToken:this.accessToken,instrument:this.name}))}l.placement=this.getPlacement(),s=this.extractSKUs(l),delete l.checkoutSupportsSplitCart,delete l.appId;const u=l;this.pciEnabled&&(u.onSendCheckoutAction=this.handleOnSendCheckoutAction),window.amazon.buywithprime.initCheckout({amazonPayOptions:u}),y.sheetClicked({instrument:this.name,result:"success",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:s,pageType:this.pageType}:void 0})}catch(l){vu.EXPECTED_ERRORS.some(h=>l instanceof h)||b.notify(l),y.sheetClicked({instrument:this.name,result:"failed",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:s,pageType:this.pageType}:void 0});const{name:u}=l!=null?l:{name:"unknown"},{translate:d}=i;ft(d("error_dialogs.wallet.title",{wallet:d("brand.buy_with_prime")}),this.getModalContent(u,d))}finally{this.applyEnabledStyles(this.button)}}getModalContent(e,n){return e==="EmptyLineItemsWalletsPlatformConfigError"?n("error_dialogs.wallet.eligibility_error",{wallet:n("brand.buy_with_prime")}):n("error_dialogs.wallet.generic_error",{wallet:n("brand.buy_with_prime")})}extractSKUs(e){var n;return(n=e.createCheckoutSessionConfig)!=null&&n.payloadJSON?JSON.parse(e.createCheckoutSessionConfig.payloadJSON).cartDetails.lineItems.map(r=>r&&r.sku).filter(r=>r):[]}getPlacement(){return this.pageType&&ad[this.pageType]||"Other"}async render(){var e;const n=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(ke.BUTTON),await this.initializeShadowStyles(n,nd),n.appendChild(this.button),(e=this.onRendered)==null||e.call(this))}buildBwpEventData(e){const n={};return e.createCheckoutSessionConfig&&(n.skus=this.extractSKUs(e),n.apiClientId=this.apiClientId),n}async handleOnSendCheckoutAction(e){const{eventName:n,redirect:r,redirectUrl:a,requestPayload:i}=e;if(r&&a){this.dispatchWalletEvent({eventName:"wallet-redirect",detail:{redirectUrl:a,requestPayload:i}});return}switch(n){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}}};c(Fe,"OPTIMUS_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/optimus")),c(Fe,"EXPECTED_ERRORS",[Vr,kt,qr]);let Lt=Fe;async function Ga({fn:t,maxRetries:e=3,delay:n=1e3,retryPolicyFn:r=()=>!0,onFinishedFn:a=()=>{}}){const i=()=>new Promise(l=>{setTimeout(l,n)});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 r=document.createElement("script");r.src=t,r.onload=()=>{window.amazon?e():n(new Error("Amazon SDK not present after loading"))},r.onerror=a=>{const i=a instanceof Event?a.type:String(a);n(new ae("Error loading Amazon SDK: ".concat(i)))},document.head.append(r)})}async function Va({sdkUrl:t=Pr,maxRetries:e=3}){return Ga({fn:()=>id(t),maxRetries:e,delay:200,retryPolicyFn:()=>!0,onFinishedFn:n=>{y.amazonPaySDKLoadRetries({retries:n})}})}const Be=class Iu extends _e{static walletName(){return"buy_with_prime"}constructor(e){super(e)}getWebComponentName(){return"shopify-buy-with-prime-button"}getInstrumentName(){return f.BuyWithPrime}getWebComponentClass(){return Lt}async loadWalletSDK(){await Va({sdkUrl:Iu.SDK_URL,maxRetries:Iu.MAX_RETRIES}),await this.loadLogos()}async loadLogos(){await Promise.all([this.loadPrimeLogo(),this.loadPrimeLogoDark()])}async loadPrimeLogo(){const e=await import("./prime-logo-DoVHKBSO.js");if(e)Je({instrumentName:f.BuyWithPrime,logoType:"LIGHT",logoContent:e.default});else throw new Error("Buy with Prime logo is empty")}async loadPrimeLogoDark(){const e=await import("./prime-logo-dark-DJIA6J0w.js");if(e)Je({instrumentName:f.BuyWithPrime,logoType:"DARK",logoContent:e.default});else throw new Error("Buy with Prime logo dark is empty")}};c(Be,"MAX_RETRIES",3),c(Be,"SDK_URL",Pr);let br=Be;const od="shopify-amazon-pay-button div[role=button][slot=amazon-pay-slot][data-testid=amazon-pay-button]{border-radius:0!important}",Sn="amazon-pay-slot";var pt,mt,We,j,te,ve;const $e=class Du extends we{constructor(){super(...arguments),c(this,"name",f.AmazonPay),c(this,"resizeObserver",null),H(this,pt,0),H(this,mt,0),H(this,We,!1),H(this,j,null),H(this,te,null),H(this,ve,null),c(this,"sdkButton",null)}connectedCallback(){this.resizeObserver=Ne("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 triggerCheckout(){if(!this.sdkButton)throw y.log({body:"Attempted to trigger checkout on uninitialized Amazon Pay SDK button",attributes:{pageType:this.pageType,containerID:C(this,te)}}),new Error("Attempted to trigger checkout on uninitialized Amazon Pay SDK button");this.handleClick(this.sdkButton)}async handleClick(e){var n,r;const[a,i]=await Promise.all([this.i18n,this.dataSource]);try{const{cart:o,decelerationReason:s,customValidationError:l,unrecoverableError:u}=await be({element:this,instrumentName:this.name,dataSource:i});if(u){y.sheetClicked({instrument:this.name,result:"failed"}),Oe(a,u);return}if(l){Le(a,l.message);return}if(s){F({checkoutUrl:(n=o==null?void 0:o.checkoutUrl)!=null?n:"",instrumentName:this.name,reason:s});return}const{totalAmount:{amount:d},checkoutUrl:h}=o;let p=this.walletParams;if(!p.createCheckoutSessionConfig){if(!this.accessToken)throw new kt("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");p=k(w({},await Wr({configOptionsEndpoint:Du.CV2_CONFIG_REST_API_URL,checkoutUrl:h,sourceId:(r=Nr(o))!=null?r:"",accessToken:this.accessToken,instrument:this.name})),{placement:this.pageType===v.ProductPage?"Product":"Cart"})}delete p.appId,e.initCheckout(w(w({},p),Number(d)!==0&&{estimatedOrderAmount:{amount:d,currencyCode:this.buyerCurrency}})),y.sheetClicked({instrument:this.name,result:"success"})}catch(o){Du.EXPECTED_ERRORS.some(l=>o instanceof l)||b.notify(o),y.sheetClicked({instrument:this.name,result:"failed"});const s=a.translate("brand.amazon_pay");O(s,a)}}createContainer({containerID:e,height:n}){const r=document.createElement("div");return r.id=e,r.style.display="flex",n!=null&&(r.style.height="".concat(n,"px")),r.slot=Sn,r.setAttribute("data-testid","amazon-pay-button"),r}async onResize(){const e=Tt(C(this,j))||0,n=Nt(C(this,j))||0,r=C(this,pt)!==e||C(this,mt)!==n;!C(this,We)&&r&&(this.teardownAmazonButtonContainer(),await this.cleanupOnFailure(()=>this.renderFromAmazonSDK(),this.name))}async render(){var e;const n=this.getOrCreateShadowRoot();try{const r=document.createElement("slot");r.name=Sn;const a=document.createElement("style");a.textContent=od,this.appendChild(a),await this.initializeShadowStyles(n);const i=await this.containerInstanceNumber;U(this,te,"AcceleratedCheckoutAmazonPayButtonContainer".concat(this.pageType).concat(i)),U(this,j,document.createElement("div")),C(this,j).classList.add(ke.BUTTON),C(this,j).appendChild(r),n.appendChild(C(this,j)),(e=this.resizeObserver)==null||e.observe(C(this,j)),await this.renderFromAmazonSDK()}catch(r){b.notify(r)}}async renderFromAmazonSDK(){var e;U(this,We,!0);const n=Nt(C(this,j))||0;U(this,ve,this.createContainer({containerID:C(this,te),height:n})),this.appendChild(C(this,ve));const r=Tt(C(this,j))||0,a={buttonBorderRadius:"".concat(r,"px")};let i=!1;try{if(this.sdkButton=window.amazon.Pay.renderButton("#".concat(C(this,te)),k(w({},this.walletParams),{style:a,placement:this.pageType===v.ProductPage?"Product":"Cart"})),this.sdkButton){const o=this.sdkButton;this.sdkButton.onClick(()=>this.handleClick(o))}else y.log({body:"Amazon Pay Button rendered null SDK button",attributes:{pageType:this.pageType,containerID:C(this,te)}});U(this,mt,n),U(this,pt,r),y.renderSucceeded(this.name),i=!0}catch(o){y.renderFailed(this.name);const s="Amazon Pay Button not able to render into container #".concat(C(this,te),".");console.error(s),y.log({body:s,attributes:{pageType:this.pageType,containerID:C(this,te),error:o==null?void 0:o.toString()}})}finally{U(this,We,!1)}i&&((e=this.onRendered)==null||e.call(this))}teardownAmazonButtonContainer(){var e;(e=C(this,ve))==null||e.remove(),U(this,ve,null)}};pt=new WeakMap,mt=new WeakMap,We=new WeakMap,j=new WeakMap,te=new WeakMap,ve=new WeakMap,c($e,"CV2_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/amazon_pay")),c($e,"EXPECTED_ERRORS",[Vr,kt,qr]);let Ot=$e;const ze=class Nu extends _e{static walletName(){return"amazon_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-amazon-pay-button"}getInstrumentName(){return f.AmazonPay}getWebComponentClass(){return Ot}async loadWalletSDK(){await Va({sdkUrl:Nu.SDK_URL,maxRetries:Nu.MAX_RETRIES})}getLoadEligibility(e){return e.getRootNode()instanceof ShadowRoot?{eligible:!1,reason:"Cannot load Amazon Pay within Shadow DOM"}:{eligible:!0}}};c(ze,"MAX_RETRIES",3),c(ze,"SDK_URL",Pr);let wr=ze;var or={Purple:{D50:"#4524DB",P40:"#5433EB"},Grayscale:{L0:"#FFFFFF"}},sd={16:16},Pn="gravity-font-faces",ld="\n@font-face {\n font-family: 'SuisseIntl';\n src: url('https://cdn.shopify.com/shop-assets/static_uploads/shoplift/SuisseIntl-Book.otf')\n format('opentype');\n font-style: normal;\n font-weight: 450;\n font-display: fallback;\n}\n\n@font-face {\n font-family: 'SuisseIntl';\n src: url('https://cdn.shopify.com/shop-assets/static_uploads/shoplift/SuisseIntl-Medium.otf')\n format('opentype');\n font-style: normal;\n font-weight: 500;\n font-display: fallback;\n}\n\n@font-face {\n font-family: 'SuisseIntl';\n src: url('https://cdn.shopify.com/shop-assets/static_uploads/shoplift/SuisseIntl-SemiBold.otf')\n format('opentype');\n font-style: normal;\n font-weight: 600;\n font-display: fallback;\n}",cd=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(ld)),document.head.appendChild(t)}_updateButton(){var t;let e=this._getOrCreateShadowRoot();e.innerHTML=ud,this.hasAttribute("disabled")&&((t=e.querySelector("button"))==null||t.setAttribute("disabled",""))}_getOrCreateShadowRoot(){return this.shadowRoot||this.attachShadow({mode:"open"}),this.shadowRoot}};function dd(){window.customElements&&(customElements.get("gravity-button")||customElements.define("gravity-button",cd))}var ud="\n\n\n\n');const hd=".button-content{display:flex;align-items:center;justify-content:center;width:100%;height:100%;gap:3px;white-space:nowrap;container-type:inline-size;container-name:bc}.ShopPromise>.separator{margin:0 8px}@container bc (width <= 338px){.ShopPromise{display:none!important}}gravity-button{display:block}shop-pay-iframe-content{height:100%}.credit-card-iframe-container{position:relative;height:100%;left:-34px;width:0px;transition:width .35s cubic-bezier(.33,0,0,1);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{opacity:1;visibility:visible}.credit-card-iframe-show-digits{width:38px}.credit-card-iframe{position:absolute;top:0;left:0;object-position:left top;object-fit:none;height:100%;width:80px}svg#shop-pay-logo{transform-box:fill-box}.shop-pay-square-removing{overflow:visible}.shop-pay-square-removing #pay-square{transform-origin:81.85% 100%;animation:fadeOutScale .3s cubic-bezier(.33,0,0,1) forwards}.shop-pay-square-removing.animation-complete #pay-square{animation:none;opacity:0;transform:translateY(25%) scale(.55)}@keyframes fadeOutScale{0%{transform:scale(1)}30%{transform:translateY(-15%) scale(1)}95%{opacity:1}to{opacity:0;transform:translateY(25%) scale(.55)}}",pd='.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 qa extends Error{constructor(){const e="DeliveryEstimatesResponseIsNullError";super("deliveryEstimates is null or undefined"),this.name=e}}class sr extends Error{constructor(){const e="DeliveryPromiseAPIClientError";super("window.Shopify.ShopPromise.deliveryPromiseAPIClient is undefined"),this.name=e}}const md=15,yd=200;class gd{constructor(e){c(this,"storefrontAPIToken"),this.storefrontAPIToken=e}async fetchDeliveryPromise({variant:e,postalCode:n,defaultPostalCode:r,sellingPlanId:a}){const i=await Ga({fn:async()=>this.fetchDeliveryOptions(e,n,r,a),maxRetries:md,delay:yd,retryPolicyFn:o=>o instanceof sr}).catch(o=>{if(o instanceof sr)throw o;return null});if(!i)throw new qa;return i}async fetchDeliveryOptions(e,n,r,a){var i,o;const s={variantId:e,sellingPlanId:a,postalCode:n||r,isPostalCodeOverride:!!n},l=(o=(i=window==null?void 0:window.Shopify)==null?void 0:i.ShopPromise)==null?void 0:o.deliveryPromiseAPIClient;if(!l)throw new sr;return l(s,this.storefrontAPIToken)}}function fd(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 bd="delivery_promise_default_address",wd="delivery_promise_postal_code";class _d extends wt{constructor(){super(...arguments),c(this,"lastFetchedProductVariantId"),c(this,"lastFetchSellingPlan"),c(this,"fetching",!1),c(this,"i18n",null),c(this,"daysToDelivery"),c(this,"formObserver",null)}async connectedCallback(){this.formObserver=new Br(this,({variantId:e,sellingPlanId:n})=>{this.fetchDeliveryPromise(e,n)}),this.formObserver.setupMutationObservers()}setTranslations(e){this.i18n=e,this.render()}get postalCode(){try{return JSON.parse(ut(wd)||"null")||null}catch(e){return null}}get defaultDeliveryAddress(){try{return JSON.parse(ut(bd)||"null")}catch(e){return null}}async fetchDeliveryPromise(e,n){var r,a,i,o;if(!(!e||!this.accessToken)&&!(e===this.lastFetchedProductVariantId&&n===this.lastFetchSellingPlan))try{this.lastFetchedProductVariantId=e,this.lastFetchSellingPlan=n;const s=((r=this.defaultDeliveryAddress)==null?void 0:r.zip)||"",l=await new gd(this.accessToken).fetchDeliveryPromise({variant:e,postalCode:this.postalCode||"",defaultPostalCode:s,sellingPlanId:n||""}),u=Fr(this),d=(i=(a=l==null?void 0:l.selectedShippingOption)==null?void 0:a.brandedPromise)==null?void 0:i.handle;if((u==null?void 0:u.sellingPlanId)!==n||(u==null?void 0:u.variantId)!==e||d!=="shop_promise")return;this.daysToDelivery=(o=l==null?void 0:l.selectedShippingOption)==null?void 0:o.maxCalendarDaysToDelivery,this.render()}catch(s){s instanceof qa&&(this.daysToDelivery=null)}}render(){const e=fd(this.daysToDelivery,this.i18n);this.classList.add("ShopPromise"),this.innerHTML=e?'|'.concat(e,""):""}}function Ed({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 Wa(t,e,n){const r=n!=null?n:window.location.origin;if(t.origin!==r||!e)return!1;try{return t.source===e.contentWindow}catch(a){return!1}}class Ad extends wt{constructor(){super(...arguments),c(this,"_userRecognized"),c(this,"iframe",null),c(this,"iframeContainer",null),c(this,"iframeCreationStart",null),c(this,"iframeOrigin",null),c(this,"payLogo",null),c(this,"iframeState","hidden"),c(this,"pendingAnimation",!1),c(this,"handleMessage",e=>{var n;if(Wa(e,this.iframe,e.origin)&&((n=e.data)==null?void 0:n.type)==="loaded"){if(this.iframeOrigin!==e.origin&&(this.iframeOrigin=e.origin),e.data.type==="loaded"&&this.iframeCreationStart){const r=ie()-this.iframeCreationStart,a={instrument:f.ShopPay,pageType:It()};S.histogram({name:I.ShopPayPersonalizedIframeLoadTime,value:r,attributes:a,unit:"ms"}),S.histogram({name:I.ShopPayPersonalizedIframeLoadTimeFromPageLoad,value:window.performance.now(),attributes:a,unit:"ms"})}if(e.data.type==="loaded"){if(this._userRecognized=e.data.recognized===!0,this.iframeCreationStart){const r=ie()-this.iframeCreationStart,a={instrument:f.ShopPay,pageType:It()};S.histogram({name:I.ShopPayPersonalizedIframeLoadTime,value:r,attributes:a,unit:"ms"}),S.histogram({name:I.ShopPayPersonalizedIframeLoadTimeFromPageLoad,value:window.performance.now(),attributes:a,unit:"ms"})}this._userRecognized?this.handleIframeLoaded():(this.cleanup(),this.dispatchEvent(new CustomEvent("user-not-recognized")))}}})}get userRecognized(){return this._userRecognized}async createIframe(){if(this.iframeContainer)return this.iframeContainer;const e=ie();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=Ed({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()}setPayLogo(e){this.payLogo=e}setDisabled(e){this.disabled=e,e&&this.iframeState!=="animation-complete"&&this.hideIframe()}animationCompleted(){return this.iframeState==="animation-complete"}triggerAnimation(){const e=this.style.display!=="none",n=["animating","animation-complete"];this.disabled||n.includes(this.iframeState)||!e||(this.iframeState==="ready"?this.showIframe():this.pendingAnimation=!0)}hideAnimation(){this.pendingAnimation=!1,this.iframeState==="animating"&&this.hideIframe()}setupMessageListener(){window.addEventListener("message",this.handleMessage)}handleIframeLoaded(){this.iframeState==="hidden"&&(this.iframeState="ready");const e=this.style.display!=="none";this.pendingAnimation&&!this.disabled&&this.iframeState==="ready"&&e&&(this.pendingAnimation=!1,this.showIframe())}showIframe(){if(this.payLogo&&!this.disabled&&this.iframeState==="ready"){if(!this.iframeContainer)return;this.iframeState="animating",this.payLogo.classList.add("shop-pay-square-removing"),this.iframeContainer.classList.add("credit-card-iframe-visible"),this.sendMessageToIframe(),this.payLogo.addEventListener("animationend",()=>{var e,n;(e=this.iframeContainer)==null||e.classList.add("credit-card-iframe-show-digits"),this.iframeState="animation-complete",(n=this.payLogo)==null||n.classList.add("animation-complete")},{once:!0})}}hideIframe(){var e,n,r,a;this.iframeState!=="hidden"&&this.iframeState!=="animation-complete"&&(this.iframeState="hidden",(e=this.payLogo)==null||e.classList.remove("shop-pay-square-removing"),(n=this.payLogo)==null||n.classList.remove("animation-complete"),(r=this.iframeContainer)==null||r.classList.remove("credit-card-iframe-visible"),(a=this.iframeContainer)==null||a.classList.remove("credit-card-iframe-show-digits"))}cleanup(){var e;window.removeEventListener("message",this.handleMessage),(e=this.iframeContainer)==null||e.remove(),this.iframeContainer=null,this.iframe=null,this.iframeOrigin=null,this.payLogo=null,this.iframeState="hidden",this.pendingAnimation=!1}sendMessageToIframe(){var e;if(!((e=this.iframe)!=null&&e.contentWindow)||!this.iframeOrigin)return;const n={timestamp:ie(),type:"animate-in"};this.iframe.contentWindow.postMessage(n,this.iframeOrigin)}}function Cd(t){const e=t.querySelector(".button-content span");if(!e)return 0;const n=window.getComputedStyle(e);return parseFloat(n.fontSize)}function Sd({element:t,isCTA:e,onFormStateChange:n,personalized:r,shopPromiseEligible:a,shopPromiseProductPageContent:i}){if(!r)return{cleanup:()=>{},shouldRender:()=>!1};let o={disabled:!1,variantId:void 0};const s=new Br(t,({disabled:l,variantId:u})=>{o={disabled:l,variantId:u},n==null||n()});return s.setupMutationObservers(),{cleanup:()=>{var l;(l=s.addToCartMutationObserver)==null||l.disconnect()},shouldRender:()=>{var l;if(o.disabled&&o.variantId!==void 0||a&&i||((l=t.offsetWidth)!=null?l:0)<170)return!1;if(e){const u=Cd(t);if(u<10||u>18)return!1}return!0}}}class Pd extends we{constructor(){super(...arguments),c(this,"name",f.ShopPay),c(this,"button",null),c(this,"shopPromiseProductPageContent",null),c(this,"shopPromiseEligible",!1),c(this,"payLogo",null),c(this,"iframeContent",null),c(this,"iframeRenderEligibility",null),c(this,"buttonContentDiv",null),c(this,"intersectionObserver",null),c(this,"inView",!1),c(this,"impressionTracked",!1),c(this,"impressionAbortController",null)}static get observedAttributes(){return["disabled"]}connectedCallback(){this.shopPromiseEligible=Ea(),this.setupIntersectionObserver(),this.cleanupOnFailure(async()=>{dd(),await this.render()},this.name)}disconnectedCallback(){var e,n;(e=this.intersectionObserver)==null||e.disconnect(),this.intersectionObserver=null,(n=this.iframeRenderEligibility)==null||n.cleanup(),this.iframeRenderEligibility=null,this.impressionAbortController&&!this.impressionAbortController.signal.aborted&&this.impressionAbortController.abort()}attributeChangedCallback(e,n,r){super.attributeChangedCallback(e,n,r,this.button),e==="disabled"&&this.onDisabledChanged(r)}setupIntersectionObserver(){"IntersectionObserver"in window?(this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(n=>{var r;n.isIntersecting&&!this.inView&&(this.inView=!0,this.onButtonInView(),(r=this.intersectionObserver)==null||r.unobserve(this))})},{threshold:.1,rootMargin:"50px"}),this.intersectionObserver.observe(this)):(this.inView=!0,this.onButtonInView())}onButtonInView(){var e;(e=this.iframeRenderEligibility)!=null&&e.shouldRender()?(this.iframeContent?this.iframeContent.triggerAnimation():this.createAndAttachIframe(),this.waitForIframeAndTrackImpression()):this.trackButtonImpression()}waitForIframeAndTrackImpression(){if(this.iframeContent&&this.iframeContent.userRecognized!==void 0){this.trackButtonImpression();return}this.impressionAbortController&&!this.impressionAbortController.signal.aborted&&this.impressionAbortController.abort();const e=Ne("AbortController");if(this.impressionAbortController=e,!e){this.trackButtonImpression();return}const n=e.signal,r=a=>{var i,o;const s=(i=this.iframeContent)==null?void 0:i.querySelector("iframe");Wa(a,s)&&a.data.type==="loaded"&&(this.trackButtonImpression(),(o=this.impressionAbortController)==null||o.abort(),this.impressionAbortController=null)};window.addEventListener("message",r,{signal:n})}trackButtonImpression(){var e;if(this.impressionTracked)return;const n=!!((e=this.iframeContent)!=null&&e.userRecognized);V({event:B.ShopPayButtonInView,instrumentId:this.name,eventSubtype:n?"personalized":"not_personalized"}),this.impressionTracked=!0}onDisabledChanged(e){var n;(n=this.iframeContent)==null||n.setDisabled(e!==null)}async addButtonContent(){if(!this.button)return;let e;const n=await this.i18n,r=ht({instrumentName:f.ShopPay}),a=new DOMParser().parseFromString(r,"image/svg+xml").documentElement;this.payLogo=a,this.isCTA?e=zr({translate:n.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(n),this.shopPromiseProductPageContent.setAttribute("access-token",this.accessToken||""),e.appendChild(this.shopPromiseProductPageContent));const i=this.getAttribute("is-shop-pay-personalization-eligible")==="true",o=()=>{var s,l;if(!this.iframeContent){(s=this.iframeRenderEligibility)!=null&&s.shouldRender()&&this.createAndAttachIframe();return}const u=((l=this.iframeRenderEligibility)==null?void 0:l.shouldRender())||!1;this.iframeContent.animationCompleted()||(this.iframeContent.style.display=u?"":"none",u?u&&this.inView&&this.iframeContent.triggerAnimation():this.iframeContent.hideAnimation())};this.iframeRenderEligibility=Sd({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.setPayLogo(this.payLogo),this.iframeContent.setDisabled(this.disabled),this.iframeContent.addEventListener("user-not-recognized",()=>{this.iframeContent=null}),this.buttonContentDiv.appendChild(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.hideAnimation())}getShopPayBehavior(){return this.pageType===v.ProductPage?"force_shop_pay_product":this.pageType===v.CartPage?"force_shop_pay_cart":"force_shop_pay"}async handleClick(e){var n,r;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 be({element:this,instrumentName:f.ShopPay,dataSource:i});if(u){y.sheetClicked({instrument:this.name,result:"failed"}),Oe(a,u);return}if(y.sheetClicked({instrument:this.name,result:"success"}),l){Le(a,l.message);return}if(o){F({checkoutUrl:(n=s==null?void 0:s.checkoutUrl)!=null?n:"",instrumentName:this.name,reason:o});return}ye((r=s==null?void 0:s.checkoutUrl)!=null?r:"",this.getShopPayBehavior())}catch(o){b.notify(new Id("An error occurred when attempting to create a cart using the Shop Pay Button. Details: ".concat(o),{cause:o})),y.sheetClicked({instrument:this.name,result:"failed"}),bt(a)}}async render(){const e=this.getOrCreateShadowRoot();if(e.innerHTML)return;this.button||(this.button=document.createElement("gravity-button"));const n=document.createElement("style");n.innerHTML=[pd,hd].join("\n"),e.appendChild(n),await this.addButtonContent(),this.disabled&&this.button.setAttribute("disabled",""),this.button.classList.add(ke.BUTTON),this.button.onclick=r=>this.handleClick(r),e.appendChild(this.button),this.ensureLightDOMIsNotEmpty(),this.handleIframeRenderLogic(),this.onRendered()}}oe("shop-promise-product-page-content",_d),oe("shop-pay-iframe-content",Ad);class Id extends Error{constructor(){super(...arguments),c(this,"name","ShopPayButtonError")}}var vd=Object.defineProperty,Dd=Object.getOwnPropertyDescriptor,Rd=(t,e,n,r)=>{for(var a=Dd(e,n),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,n,a)||a);return a&&vd(e,n,a),a};class ja extends _e{static walletName(){return"shop_pay"}constructor(e){super(e)}getWebComponentName(){return"shop-pay-wallet-button"}getWebComponentClass(){return Pd}getInstrumentName(){return f.ShopPay}async createWebComponent(e){var n;const r=await super.createWebComponent(e),{walletContainer:a}=e,i=a.isShopPayPersonalizationEnabled,o=(n=this.walletParams)==null?void 0:n.personalized;return i&&o&&r.setAttribute("is-shop-pay-personalization-eligible","true"),r}async loadWalletSDK(){await this.loadLogo()}getLoadEligibility(){return{eligible:!0}}async loadLogo(){const e=await import("./shop-pay-logo-nzlo6e3W.js");if(e)Je({instrumentName:f.ShopPay,logoType:"LIGHT",logoContent:e.default});else throw new Error("Shop wordmark logo is empty")}}Rd([Hr("Shop Pay")],ja.prototype,"getLoadEligibility");const Td=".button{display:flex;justify-content:center;align-items:center;width:100%;border:none}.button:hover:not(:disabled){filter:brightness(92%);cursor:pointer}.button:disabled{opacity:.5;cursor:not-allowed}.logo-only>svg{width:50px}.dark{background:#000;color:#fff}.light{background:#fff;color:#000;outline:1px solid #3c4043}@media (forced-colors: active){.light{outline:none}}.content{display:flex;justify-content:center;align-items:center;white-space:pre}";function lr({cart:t,i18n:e}){const n=Fa(t),r={label:e.translate("order_summary.subtotal"),type:"SUBTOTAL",price:Re(n.amount)},a=Ma({deliveryGroups:t.deliveryGroups,i18n:e}).map(s=>Nd({lineItem:s,type:"LINE_ITEM"})),i=kd(t,e),o=[r,...a,...i];if(t.totalDutyAmount){const s={label:e.translate("order_summary.duties"),type:"LINE_ITEM",price:Re(t.totalDutyAmount.amount)};o.push(s)}if(t.totalTaxAmount){const s={label:e.translate("order_summary.taxes"),type:"TAX",price:Re(t.totalTaxAmount.amount)};o.push(s)}return{totalPrice:t.totalAmount.amount,currencyCode:t.totalAmount.currencyCode,totalPriceStatus:"ESTIMATED",totalPriceLabel:e.translate("order_summary.total"),displayItems:o}}function Nd({lineItem:t,type:e,status:n="FINAL"}){return{label:t.label,type:e,price:t.amount,status:n}}function kd(t,e){return[...t.lineItems.flatMap(n=>n.discountAllocations),...t.discountAllocations].flatMap(n=>{var r;const a=(r=n.title)!=null?r:n.code;return{label:a!=null?a:e.translate("order_summary.discount"),type:"LINE_ITEM",price:"-".concat(Re(Number(n.discountedAmount.amount)))}})}const Ya=["PAYMENT_AUTHORIZATION"],Ld=Ya.concat(["SHIPPING_ADDRESS","SHIPPING_OPTION"]),Od=["PAN_ONLY"];function xd({walletParams:t,isShippingRequired:e,hasSellingPlan:n,i18n:r,buyerCurrency:a,authJwt:i}){const o={totalPrice:"0.01",currencyCode:a,totalPriceStatus:"ESTIMATED",totalPriceLabel:r.translate("order_summary.total"),displayItems:[{label:r.translate("order_summary.subtotal"),type:"SUBTOTAL",price:"0.01"}]},s=k(w({},t.paymentData),{shippingAddressRequired:e,shippingOptionRequired:e,transactionInfo:o});return s.merchantInfo.authJwt=i,e||delete s.shippingAddressParameters,s.callbackIntents=e?Ld:Ya,n&&Md(s),s}function Md(t){t.allowedPaymentMethods.forEach(e=>{e.parameters.allowedAuthMethods=e.parameters.allowedAuthMethods.filter(n=>Od.includes(n))})}class Ud extends Ua{constructor(e){super(),c(this,"brandName"),c(this,"completionResult"),this.i18n=e,this.brandName=this.i18n.translate("brand.google_pay"),this.completionResult=void 0}mapMutationResultToPaymentSheetAction(e){const n=this.mapCustomValidationFunctionErrorToAction(e.errors);if(n)return n;const r=this.getErrorActions(),a=e.errors,i=this.getUnhandledErrors(a,r);i.forEach(s=>{b.notify(new Ge("[".concat(f.GooglePay,"] mutation result error not handled: ").concat(s),{groupingHash:"UnhandledActionError:".concat(f.GooglePay,":").concat(s)}))});const{firstPaymentSheetAction:o}=this.getMergedPaymentSheetAction({result:e,errorActions:r});return o||(i.length>0?{action:"abort"}:{action:"update",errors:[]})}mapCompletionResultToPaymentSheetAction(e){if(!e.data)throw new Error("[".concat(f.GooglePay,"] completion returned null result"));switch(this.completionResult=e,e.data.__typename){case"SubmitSuccess":return{action:"complete",redirectUrl:e.data.redirectUrl};case"SubmitAlreadyAccepted":case"SubmitThrottled":case"SubmitFailed":{const n=this.mapCustomValidationFunctionErrorToAction(e.errors);if(n)return n;const r=this.getErrorActions(),a=e.errors;this.getUnhandledErrors(a,r).forEach(o=>{b.notify(new Ge("[".concat(f.GooglePay,"] completion result error not handled: ").concat(o),{groupingHash:"UnhandledActionError:".concat(f.GooglePay,":").concat(o)}))});const{prioritizedPaymentSheetAction:i}=this.getMergedPaymentSheetAction({result:e,errorActions:r});return i||(O(this.brandName,this.i18n),{action:"abort"})}default:throw new Error("[".concat(f.GooglePay,"] unknown completion result type: ").concat(e.data.__typename))}}getErrorActions(){return[{errors:[g.CaptchaCompletionRequired],generateAction:()=>this.decelerateOrAbort({reason:"captcha_required",instrumentName:f.GooglePay,errorOrWarning:g.CaptchaCompletionRequired,result:this.completionResult})},{errors:[g.InvalidLanguage],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.GooglePay,"] mutation provided invalid language, aborting")))},()=>O(this.brandName,this.i18n)]})},{errors:[g.InvalidCountry],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.GooglePay,"] mutation provided invalid country, aborting")))},()=>O(this.brandName,this.i18n)]})},{errors:[g.MissingCartId],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.GooglePay,"] mutation provided invalid cart ID, aborting")))},()=>O(this.brandName,this.i18n)]})},{errors:[g.RedirectToCheckoutRequired],generateAction:()=>({action:"abort",effects:[()=>O(this.brandName,this.i18n)]})},{errors:Dr,generateAction:()=>this.decelerateOrAbort({reason:"dynamic_tax",instrumentName:f.GooglePay,errorOrWarning:g.NewTaxMustBeAccepted,result:this.completionResult})},{errors:[g.MerchandiseExpectedPriceMismatch,g.DeliveryLineChanged,g.DeliveryLocalPickupLineChanged,...ya],generateAction:()=>({action:"abort",effects:[()=>O(this.brandName,this.i18n)]})},{errors:[g.UnsupportedGooglePayPaymentMethod],generateAction:()=>({action:"abort",effects:[()=>O(this.brandName,this.i18n),()=>{b.notify(new Ge("[".concat(f.GooglePay,"] payment method is not supported"),{groupingHash:"UnhandledActionError:".concat(f.GooglePay,":payment_method_not_supported")}))}]})},{errors:[g.PaymentsMethodRequired,g.PaymentsMethodUnavailable],generateAction:()=>({action:"abort",effects:[()=>O(this.brandName,this.i18n)]})},{errors:[g.CustomValidation],generateAction:()=>({action:"abort",effects:[()=>O(this.brandName,this.i18n)]})},{errors:[g.MerchandiseOutOfStock],generateAction:()=>({action:"abort",effects:[()=>ge(this.i18n)]})},{errors:ga,generateAction:()=>({action:"abort",effects:[()=>O(this.brandName,this.i18n)]})},{errors:fa,generateAction:()=>this.decelerateOrAbort({reason:"not_enough_stock",instrumentName:f.GooglePay,errorOrWarning:g.MerchandiseNotEnoughStock,result:this.completionResult})},{errors:ma,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.shipping_address")}]})},{errors:pa,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[g.NoDeliveryGroupSelected],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_OPTION_INVALID",intent:"SHIPPING_OPTION",message:this.i18n.translate("errors.missing.shipping_option")}]})},{errors:[g.BuyerIdentityEmailDomainInvalid,g.BuyerIdentityEmailNotExpectedPattern,g.BuyerIdentityEmailInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.email")}]})},{errors:[g.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.email")}]})},{errors:[g.DeliveryAddress2Required,g.DeliveryAddress2AddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address2")}]})},{errors:[g.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address2")}]})},{errors:[g.DeliveryCityAddressFieldRequired,g.DeliveryCityRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.city")}]})},{errors:[g.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.city")}]})},{errors:[g.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.zone")}]})},{errors:[g.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.zone")}]})},{errors:[g.DeliveryPostalCodeRequired,g.DeliveryPostalCodeAddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:[g.DeliveryPostalCodeInvalid,g.DeliveryInvalidPostalCodeForZone,g.DeliveryInvalidPostalCodeForCountry,g.DeliveryZipInvalidForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[g.DeliveryPhoneNumberRequired],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.phone_number")}]})},{errors:[g.DeliveryPhoneNumberInvalid,g.BuyerIdentityInvalidPhone,g.DeliveryPhoneDoesNotMatchExpectedPattern],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.phone_number")}]})},{errors:[g.BuyerIdentityInvalidCountry,g.DeliveryCountryInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.country")}]})},{errors:[g.DeliveryFirstNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.first_name")}]})},{errors:[g.DeliveryFirstNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.first_name")}]})},{errors:[g.DeliveryLastNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.last_name")}]})},{errors:[g.DeliveryLastNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.last_name")}]})},{errors:[g.DeliveryAddress1Required],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address1")}]})},{errors:[g.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address1")}]})},{errors:[g.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.last_name")}]})},{errors:[g.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.city")}]})},{errors:[g.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address1")}]})},{errors:[g.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address2")}]})},{errors:[g.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.postal_code")}]})},{errors:[g.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address1")}]})},{errors:[g.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address2")}]})},{errors:[g.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.first_name")}]})},{errors:[g.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.last_name")}]})},{errors:[g.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.city")}]})},{errors:[g.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.first_name")}]})},{errors:[g.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.last_name")}]})},{errors:[g.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address1")}]})},{errors:[g.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address2")}]})},{errors:[g.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.city")}]})},{errors:[g.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.first_name")}]})},{errors:[g.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.last_name")}]})},{errors:[g.InvalidPaymentGooglePayBillingAddress],generateAction:()=>({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:this.i18n.translate("errors.invalid.billing_address")}]})}]}mapCustomValidationFunctionErrorToAction(e){const n=kr(e);return n?(b.notify(new Error("[".concat(f.GooglePay,"] custom validation function error: ").concat(JSON.stringify(e)))),Or(this.i18n.translate("error_dialogs.wallet.title",{wallet:this.brandName}),n.message),{action:"abort"}):null}}function Fd({deliveryGroups:t,i18n:e}){var n;const r=Bc(Oa({deliveryGroups:t}),e),a=r.map(({handle:o,title:s,description:l})=>({id:o,label:s!=null?s:"",description:l})),i=(n=r.find(o=>{var s;return o.handle.includes(((s=t[0].selectedDeliveryOption)==null?void 0:s.handle)||"")}))==null?void 0:n.handle;return{shippingOptions:a,defaultSelectedOptionId:i}}function cr(t){let e=t.administrativeArea,n=t.locality;t.countryCode==="AE"&&(n=t.administrativeArea,t.administrativeArea in In&&(e=In[t.administrativeArea])),t.countryCode==="MX"&&e&&(e=Bd(e));let r,a;if(t.name){const[i,...o]=(t.name||"").split(" ");o.length===0?a=i:a=o.join(" "),r=i}return{firstName:r,lastName:a,address1:t.address1,address2:t.address2,city:n,province:e,country:t.countryCode,phone:t.phoneNumber,zip:t.postalCode}}const In={"\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"},Bd=t=>t==="M\xE9x."?"MEX":t==="Q.R."?"Q ROO":t.replace(/\./g,"").toUpperCase();class dr extends Error{constructor(){super(...arguments),c(this,"name","GooglePayError")}}function Ka(t){const e=t.auth;if(!(Array.isArray(e)&&e.length>0))return{result:"error",reason:"invalidAuthParams"};const n=ie();for(const r of e)if(n{var m,E;const{callbackTrigger:_,shippingAddress:A,shippingOptionData:P}=p,{translate:$}=this.i18n;switch(_){case"INITIALIZE":{if(!this.cart)try{const{cart:le,customValidationError:T,decelerationReason:G,unrecoverableError:z}=await be({element:this.button,instrumentName:f.GooglePay,dataSource:this.dataSource});if(T||z)return this.terminalCartCreationError=T?T.message:Gd(this.i18n,z),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:this.terminalCartCreationError,intent:"SHIPPING_ADDRESS"}});if(G)return F({checkoutUrl:(m=le==null?void 0:le.checkoutUrl)!=null?m:"",instrumentName:this.name,reason:G}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:""}});this.cart=le,y.sheetClicked({instrument:this.name,result:"success"})}catch(le){return y.sheetClicked({instrument:this.name,result:"failed"}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}let M=!1;if(A)try{return await this.handleShippingAddressChange(this.cart.id,A)}catch(le){M=!0}return w({newTransactionInfo:lr({cart:this.cart,i18n:this.i18n})},M?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:lr({cart:this.cart,i18n:this.i18n})}:this.showPaymentDataRequestError({intent:_});case"SHIPPING_OPTION":{if(!this.cart)return this.showPaymentDataRequestError({intent:_});if(!P||!P.id)return{error:{reason:"SHIPPING_OPTION_INVALID",message:$("shipping_methods.choose_delivery_strategy"),intent:"SHIPPING_OPTION"}};const M=await this.handleDeliveryOptionChange(P.id.split(","));return M.data?(this.cart=M.data,M.abortReason==="out_of_stock"?this.showPaymentDataRequestError({error:{intent:"SHIPPING_OPTION",reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.product.out_of_stock")}}):M.decelerationReason?(F({checkoutUrl:(E=this.cart.checkoutUrl)!=null?E:"",instrumentName:this.name,reason:M.decelerationReason}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_OPTION",reason:"OTHER_ERROR",message:""}})):this.handlePaymentDataRequestUpdate({result:M,intent:_})):this.showPaymentDataRequestError({intent:_})}default:return this.logException("Payment data changed callback returned unexpected intent: ".concat(_),{severity:"warning"}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}}),c(this,"onPaymentAuthorized",async p=>{var m,E,_;y.authorizationAttempt(this.name),Ze(L.AuthorizationLatency,this.name);const A=(m=p.paymentMethodData.info)==null?void 0:m.billingAddress,P=p.shippingAddress,{signature:$,signedMessage:M,protocolVersion:le}=JSON.parse(p.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&&!P)return this.handlePaymentAuthorizationError({error:{reason:"SHIPPING_ADDRESS_INVALID",intent:"PAYMENT_AUTHORIZATION",message:this.i18n.translate("errors.invalid.shipping_address")}});const T=async()=>{var z,x;const se=(z=C(this,yt))!=null?z:p.email,ce=this.isShippingRequired?{validateAddress:!0,streetAddress:cr(P)}:{};return await He(w({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:this.name,emailAddress:se,abortSignal:(x=C(this,re))==null?void 0:x.signal},ce))},G=async()=>{var z;const x=cr(A);return await $r({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{googlePayWalletContent:{billingAddress:x,signature:$,signedMessage:M,protocolVersion:le}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:x,cartClient:this.cartClient,instrumentName:this.name,hasSellingPlan:this.hasSellingPlan,abortSignal:(z=C(this,re))==null?void 0:z.signal})};try{const z=setTimeout(()=>{var Tu;(Tu=C(this,re))==null||Tu.abort("[Google Pay] Timeout")},$d),x=await T(),se=this.handleIntermediatePaymentAuthorizationResult(x);if(se)return se;const ce=await G(),ku=this.handleIntermediatePaymentAuthorizationResult(ce);if(ku)return ku;if(clearTimeout(z),(_=(E=C(this,re))==null?void 0:E.signal)!=null&&_.aborted)throw new dr("Abort Controller was not aborted");const Ru=await $a({cartId:this.cart.id,token:$,cartClient:this.cartClient,instrumentName:this.name});ct({result:Ru,instrument:this.name});const Uu=this.actionGenerator.mapCompletionResultToPaymentSheetAction(Ru);return this.handlePaymentAuthorizationResult(Uu)}catch(z){const{message:x}=z;return x!=null&&x.includes(zd)?this.handlePaymentAuthorizationError({status:"timeout"}):(this.logException(x),this.handlePaymentAuthorizationError())}}),c(this,"handlePaymentAuthorizationResult",async p=>{var m,E;switch((m=p.effects)==null||m.forEach(_=>_()),p.action){case"complete":return this.emitAuthorizationCompleteMetric("success"),ye(p.redirectUrl),{transactionState:"SUCCESS"};case"show_error":return this.handlePaymentAuthorizationError({error:(E=p.errors)==null?void 0:E[0]});case"decelerate":return F({checkoutUrl:p.redirectUrl,instrumentName:this.name,reason:p.reason}),this.emitAuthorizationCompleteMetric("failed"),{transactionState:"SUCCESS"};case"abort":default:return this.emitAuthorizationCompleteMetric("failed"),{transactionState:"SUCCESS"}}}),this.walletParams=e,this.isShippingRequired=n,this.hasSellingPlan=r,this.dataSource=a,this.button=i,this.i18n=o,this.cartClient=s,this.initialBuyerCurrency=l,U(this,yt,e.customerAccountEmail),U(this,re,u);const d=Ka(this.walletParams);if(d.result==="error")throw b.leaveBreadcrumb("Google Pay Invalid AuthJwt detected on click",{reason:d.reason,walletParams:this.walletParams},"error"),new dr(d.reason);U(this,je,d.jwt);const h={environment:this.walletParams.environment,merchantInfo:k(w({},this.walletParams.paymentData.merchantInfo),{authJwt:C(this,je)}),paymentDataCallbacks:{onPaymentDataChanged:this.isShippingRequired?this.onPaymentDataChanged:void 0,onPaymentAuthorized:this.onPaymentAuthorized}};this.paymentsClient=new window.google.payments.api.PaymentsClient(h),this.actionGenerator=new Ud(this.i18n)}async handleClick(){if(!this.isShippingRequired)throw new ae("Google Pay checkout started for digital cart");const e=xd({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,i18n:this.i18n,buyerCurrency:this.initialBuyerCurrency,authJwt:C(this,je)});await this.paymentsClient.loadPaymentData(e)}showPaymentDataRequestError({error:e,intent:n="SHIPPING_ADDRESS"}={}){return e?{error:e}:{error:{intent:n,reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.wallet.generic_error",{wallet:this.i18n.translate("brand.google_pay")})}}}handlePaymentAuthorizationError({error:e,status:n="failed"}={}){return this.emitAuthorizationCompleteMetric(n),w({transactionState:"ERROR"},this.showPaymentDataRequestError({error:e,intent:"PAYMENT_AUTHORIZATION"}))}handlePaymentDataRequestUpdate({result:e,intent:n}){var r,a;const i=this.actionGenerator.mapMutationResultToPaymentSheetAction(e);switch(i.action){case"update":{const o=i,{data:s,decelerationReason:l}=e;return s?l?(F({checkoutUrl:s.checkoutUrl,instrumentName:this.name,reason:l}),this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:"",intent:"OFFER"}})):this.isShippingRequired&&s.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:lr({cart:s,i18n:this.i18n}),newShippingOptionParameters:this.isShippingRequired?Fd({deliveryGroups:s.deliveryGroups,i18n:this.i18n}):void 0,error:(r=o.errors)==null?void 0:r[0]}:this.showPaymentDataRequestError({intent:n})}case"show_error":return{error:(a=i.errors)==null?void 0:a[0]};case"abort":return this.showPaymentDataRequestError({intent:n});default:return this.logException("Payment sheet update returned unexpected action (see request tab for details)",{metadata:{request:{action:i.action,intent:n}}}),this.showPaymentDataRequestError({intent:n})}}handleIntermediatePaymentAuthorizationResult(e){var n,r,a,i;if(ct({result:e,instrument:this.name}),e.abortReason==="out_of_stock")return ge(this.i18n),{transactionState:"SUCCESS"};if(e.decelerationReason)return F({checkoutUrl:(r=(n=e.data)==null?void 0:n.checkoutUrl)!=null?r:"",instrumentName:this.name,reason:e.decelerationReason}),{transactionState:"SUCCESS"};const o=this.actionGenerator.mapMutationResultToPaymentSheetAction(e);if(((a=e.errors)==null?void 0:a.length)>0){const s=o;if(s.action==="show_error")return this.handlePaymentAuthorizationError({error:(i=s.errors)==null?void 0:i[0]})}}handleCurrencyChange(e,n){Lr({currentCartTotal:n,initialBuyerCurrency:this.initialBuyerCurrency})&&F({checkoutUrl:e,instrumentName:this.name,reason:"currency_changed"})}async handleShippingAddressChange(e,n){var r,a;let i=await He({cartClient:this.cartClient,cartId:e,streetAddress:n?cr(n):{},instrumentName:f.GooglePay,abortSignal:(r=C(this,re))==null?void 0:r.signal});if(!i.data)return this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"});if(this.cart=i.data,i.abortReason==="out_of_stock")return this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:this.i18n.translate("error_dialogs.product.out_of_stock")}});if(i.decelerationReason)return F({checkoutUrl:(a=this.cart.checkoutUrl)!=null?a:"",instrumentName:this.name,reason:i.decelerationReason}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:""}});const o=this.cart.deliveryGroups.map(({selectedDeliveryOption:s,deliveryOptions:l})=>{var u;return s!=null&&s.handle&&s.deliveryMethodType!=="LOCAL"?s.handle:(u=l.filter(({deliveryMethodType:d})=>d==="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"})}async handleDeliveryOptionChange(e){var n;const r=za({deliveryGroups:this.cart.deliveryGroups,instrumentName:f.GooglePay,selectedDeliveryOptionHandles:e});return await Ba({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:f.GooglePay,selectedDeliveryOptions:r,abortSignal:(n=C(this,re))==null?void 0:n.signal})}logException(e,{severity:n,metadata:r}={}){b.notify(new dr(e),{severity:n!=null?n:"error",metadata:r})}emitAuthorizationCompleteMetric(e){y.authorizationComplete({instrument:this.name,measurement:K(L.AuthorizationLatency,this.name),result:e})}}yt=new WeakMap,re=new WeakMap,je=new WeakMap;function Gd(t,e){switch(e){case ne.VariantRequiresSellingPlan:case ne.SellingPlanNotApplicable:case ne.InvalidQuantity:return t.translate("error_dialogs.checkout.generic_error");default:return t.translate("error_dialogs.checkout.generic_error")}}const Vd={LIGHT:"light",DARK:"dark"};class qd extends we{constructor(){super(...arguments),c(this,"name",f.GooglePay),c(this,"paymentsClient",null),c(this,"button",null),c(this,"handleClick",async()=>{if(this.disabled)return;this.disabled=!0;const e=Ne("AbortController");try{await this.createPaymentsClient(e),await this.paymentsClient.handleClick()}catch(n){if(this.disabled=!1,n.statusCode==="CANCELED"){e==null||e.abort("[Google Pay] Payment sheet cancelled"),y.sheetCancelled(f.GooglePay);return}e==null||e.abort("[Google Pay] Payment sheet failure"),b.notify(n),y.sheetClicked({instrument:this.name,result:"failed"});const r=await this.i18n,a=r.translate("brand.google_pay");O(a,r)}})}static get observedAttributes(){return["disabled"]}attributeChangedCallback(e,n,r){super.attributeChangedCallback(e,n,r,this.button)}async connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async createPaymentsClient(e){this.paymentsClient=new Hd({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,Td);const{translate:n}=await this.i18n,r=this.isCTA?n("buy_with_button_content",{wallet:n("brand.google_pay")}):n("brand.google_pay"),a=Vt({label:r});this.disabled&&a.setAttribute("disabled",""),a.classList.add("button",ke.BUTTON,Vd[this.buttonTheme]),a.onclick=this.handleClick,await this.renderButtonContent(a,n),this.button=a,e.appendChild(a),this.ensureLightDOMIsNotEmpty(),this.onRendered()}async renderButtonContent(e,n){const r=ht({instrumentName:f.GooglePay,logoType:this.buttonTheme}),a=new DOMParser().parseFromString(r,"image/svg+xml").documentElement;if(e.style.font=window.getComputedStyle(this).font,this.isCTA){const i=zr({translate:n,logoElement:a,setAriaHidden:!0});i.classList.add("content"),e.appendChild(i)}else e.classList.add("logo-only"),e.appendChild(a)}}const Ie=class jt extends _e{static walletName(){return"google_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-google-pay-button"}getInstrumentName(){return f.GooglePay}getWebComponentClass(){return qd}async loadWalletSDK(){if(jt.googlePaySDKPromise)return jt.googlePaySDKPromise;const e=document.createElement("script");e.setAttribute("src",this.walletParams.sdkUrl);const n=new Promise((r,a)=>{e.onload=()=>r(),e.onerror=i=>{document.body.removeChild(e),a(i)},document.body.appendChild(e)});return jt.googlePaySDKPromise=Promise.all([n,this.loadLogos()]),jt.googlePaySDKPromise}getLoadEligibility(){const e=Ka(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(){const e=await import("./google-pay-logo-BgkSiJGq.js");if(e)Je({instrumentName:f.GooglePay,logoType:"LIGHT",logoContent:e.default});else throw new Error("Google Pay logo is empty")}async loadGooglePayLogoDark(){const e=await import("./google-pay-logo-dark-DmTdfep2.js");if(e)Je({instrumentName:f.GooglePay,logoType:"DARK",logoContent:e.default});else throw new Error("Google Pay logo dark is empty")}};c(Ie,"googlePaySDKPromise");let _r=Ie;const Wd=[Tc,yr,Gr,_r,br,wr,ja],jd=new Map(Wd.map(t=>[t.walletName(),e=>new t(e)]));function dt(t){if(!t)return null;const e=jd.get(t.name);return e?e(t):(console.debug("Can't build wallet with name ".concat(t.name)),null)}function Yd(t){return t.map(e=>dt(e)).filter(e=>e!=null)}const Qa="*{box-sizing:border-box}.wallet-button-fade-in{animation:animation-fade-in .3s cubic-bezier(.1,.79,1,1)}@keyframes animation-fade-in{0%{opacity:0}to{opacity:1}}button[aria-disabled=true]{opacity:.5;cursor:not-allowed}";class Kd{constructor(e,n,r){this.element=e,this.apiClient=n,this.instrumentName=r}async getInitialCart(e){const n=Fr(this.element);if(!n)throw new Error("[".concat(this.instrumentName,"] unable to find product form"));const r=ut(_i),{data:a,errors:i,abortReason:o,decelerationReason:s}=await this.apiClient.createCart(k(w({},n),{discountCodes:r?[r]:[],instrumentName:e}));return{cart:a,errors:i,abortReason:o,decelerationReason:s}}}function Qd({styleId:t,styles:e,cssFileName:n}){var r,a;(a=(r=window.Shopify)==null?void 0:r.PaymentButton)!=null&&a.isStorefrontPortableWallets&&(Jd({styleId:t})||Xd({styleId:t,styles:e}))}function Jd({styleId:t}){return!!document.querySelector("style#".concat(t))}function Xd({styleId:t,styles:e}){const n=document.createElement("style");n.id=t,n.innerHTML=e,document.head.appendChild(n)}const J={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 vn(t){let e=0,n=0,r=0;const a=t.split(/\s+/);for(let i=0;i"&&(o.includes("#")&&(e+=(o.match(/#/g)||[]).length),o.includes(".")&&(n+=(o.match(/\./g)||[]).length),o.includes("[")&&(n+=(o.match(/\[/g)||[]).length),o.includes(":")&&(n+=(o.match(/:[^:]/g)||[]).length),/^[A-Za-z]/.test(o)&&(r+=1))}return[e,n,r]}function Zd(t,e){for(let n=0;n<3;n++)if(t[n]!==e[n])return e[n]-t[n];return 0}function Dn(t){return[...t].sort((e,n)=>{const r=vn(e.selector),a=vn(n.selector);return Zd(r,a)})}const eu=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*(>\s*)?li(?![a-zA-Z0-9_.:#-])/,tu=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*\[role="?button"?\](?![:\w-])/,ru=/\.additional-checkout-buttons\s*(?:div\s*)?\[role="?button"?\](?![:\w-])/,Ja=/\[data-shopify-buttoncontainer\](?![:\w-])/,Xa=/.dynamic-checkout-buttons .shopify-payment-button__button/,nu=/(?!.*\.shopify-cleanslate)\.shopify-payment-button__button(?:--branded)?(?![\w-:.#>])/,au=/\.(shopify-payment-button|shopify-payment-button__button|shopify-payment-button__button--branded)\s*\[role="?button"?\](?![:\w-])/,iu=/(?:only\s+)?(?:screen\s+and\s+)?\((?:min|max)-(?:width|height):\s*\d+px\)/,ou=[tu,Ja,eu,ru,Xa],su=[nu,au,Xa],lu=.001;function Za(t){const e=t.pageType,n=[...document.styleSheets].filter(cu),r=[],a=[];n.forEach(T=>{try{const G=[...T.cssRules].filter(x=>x instanceof CSSMediaRule),z=[...T.cssRules].filter(x=>x instanceof CSSStyleRule);a.push(...G.filter(x=>iu.test(x.conditionText)).flatMap(x=>[...x.cssRules].filter(se=>se instanceof CSSStyleRule).flatMap(se=>se.selectorText.split(",").map(ce=>ce.trim()).map(ce=>w({selector:ce,conditionText:x.conditionText},Ln(se)))))),r.push(...z.flatMap(x=>x.selectorText.split(",").map(se=>se.trim()).map(se=>w({selector:se},Ln(x)))))}catch(G){vt()("shopify-support-debug")&&(console.debug("[shopify-support-debug] stylesheet origin: ".concat(T.href)),console.debug(G))}});const i=e===v.ProductPage?su:ou,o=new Set;function s(T,G){const z=G.selector.match(T);return z?(o.add(z[0]),!0):!1}const l=r.filter(T=>i.some(G=>s(G,T))).reverse(),u=a.filter(T=>i.some(G=>s(G,T))).reverse(),d=vt()("shopify-support-debug");d&&console.table(Array.from(o));const h=Dn(l),p=Dn(u),m={},E=Rn(e)?document.querySelector(".cart__blocks .button"):document.querySelector(".product-form__buttons .button");E&&(m.boxShadow=getComputedStyle(E,":before").boxShadow);for(const T of h){const G=["height","minHeight","borderRadius","marginTop"];Rn(e)&&T.selector.match(Ja)&&G.push("justifyContent");for(const z of G)m[z]=hu({rule:T,property:z,currentPropertyValue:m[z]})}const{height:_,borderRadius:A,minHeight:P,marginTop:$,justifyContent:M,boxShadow:le}=m;return d&&console.table([{property:"height",value:_},{property:"borderRadius",value:A},{property:"minHeight",value:P},{property:"marginTop",value:$},{property:"justifyContent",value:M},{property:"boxShadow",value:le}]),e===v.ProductPage?kn({styles:{height:_,minHeight:P,borderRadius:A,marginTop:$,boxShadow:le},mediaRules:p,element:t}):kn({styles:{borderRadius:A,boxShadow:le,justifyContent:M},mediaRules:p,element:t})}function ei(t,e){if(!e)return;mu(e,t);const n="global-".concat(t.tagName.toLowerCase(),"-styles");if(document.head.querySelector("style#".concat(n))==null){const r=document.createElement("style");r.id=n,r.innerHTML=e,document.head.appendChild(r)}}function cu(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 Rn(t){return t===v.CartPage||t===v.CartAjax}function Tn({height:t,minHeight:e}){let n=t,r=e;return(n!=null&&n.includes("var(".concat(J.buttonBlockSize))||n==="auto")&&(n=null),(r!=null&&r.includes("var(".concat(J.buttonBlockSize))||r==="auto")&&(r=null),n===r?n:r&&n?"max(".concat(n,",").concat(r,")"):n||r}function Nn({existingProperties:t,mediaCondition:e,selector:n,styles:r}){const a=w({},r);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?"":du({mediaCondition:e,selector:n,styles:a})}function du({mediaCondition:t,selector:e,styles:n}){let r="".concat(t?"@media ".concat(t," { "):"").concat(e," {");for(const[a,i]of Object.entries(n))i&&(r+="\n ".concat(a,": ").concat(i,";"));return r+="\n}",t&&(r+="}"),r+="\n",r}function kn({styles:t,element:e,mediaRules:n}){const{height:r,minHeight:a,borderRadius:i,marginTop:o,justifyContent:s,boxShadow:l}=t,u=e.tagName.toLowerCase(),d=getComputedStyle(e),h=new Set;for(const m of Object.values(J))d.getPropertyValue(m)&&h.add(m);let p=Nn({existingProperties:h,selector:u,styles:{[J.buttonBlockSize]:Tn({height:r,minHeight:a}),[J.buttonBorderRadius]:i,[J.buttonBoxShadow]:l,[J.inlineAlignment]:s,"margin-top":o,display:o?"block":void 0}});return n.forEach(m=>{(m.height||m.minHeight||m.borderRadius||m.boxShadow||m.justifyContent||m.marginTop)&&(p+=Nn({existingProperties:h,mediaCondition:m.conditionText,selector:u,styles:{[J.buttonBlockSize]:Tn({height:m.height,minHeight:m.minHeight}),[J.buttonBorderRadius]:m.borderRadius,[J.buttonBoxShadow]:m.boxShadow,[J.inlineAlignment]:m.justifyContent,"margin-top":m.marginTop,display:m.marginTop?"block":void 0}}))}),p.trim()}function Ln(t){return[["height"],["minHeight","min-height"],["borderRadius","border-radius"],["marginTop","margin-top"],["justifyContent","justify-content"]].reduce((e,[n,r])=>(e[n]=uu({rule:t,property:r!=null?r:n}),e),{})}function uu({rule:t,property:e}){const n=t.style.getPropertyValue(e);return t.style.getPropertyPriority(e)?"".concat(n," !important"):n||null}function hu({rule:t,property:e,currentPropertyValue:n}){const r=t[e];return!(n!=null&&n.includes("!important"))&&r!=null&&r.includes("!important")?r:n!=null?n:r}function pu(t){const e=/(--[\w-]+)\s*:/g;let n;const r={};for(;(n=e.exec(t))!==null;){const l=n[1];r[l]=(r[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:r,mediaQueryCount:i,marginTopCount:s}}function mu(t,e){var n,r,a;const i=(a=(r=(n=window.ShopifyAnalytics)==null?void 0:n.lib)==null?void 0:r.trekkie)==null?void 0:a.defaultAttributes,o=i==null?void 0:i.shopId,s=i==null?void 0:i.themeId;if(o&&s&&(y.log({body:"Style backwards compatibility used",attributes:{shopId:"".concat(o),themeId:"".concat(s)}}),Math.random()0&&y.styleBackwardsCompatibilityRules({rule:"@media",count:l.mediaQueryCount,pageType:e.pageType}),l.marginTopCount>0&&y.styleBackwardsCompatibilityRules({rule:"margin-top",count:l.marginTopCount,pageType:e.pageType}),y.log({body:"Style backwards compatibility details",attributes:{shopId:"".concat(o),themeId:"".concat(s),pageType:e.pageType,stylesString:t.length>2e3?t.substring(0,2e3):t}})}}const On=2e3;class xn extends Error{constructor(){super(...arguments),c(this,"name","AcceleratedCheckoutError")}}var Ye;const xt=class Lu extends Mr{constructor(){super(...arguments),c(this,"instanceNumber",++Lu.instanceCount),c(this,"pageType",v.ProductPage),c(this,"formObserver"),c(this,"dataSource"),c(this,"wrapper"),c(this,"shopPromiseEligible",!1),c(this,"didInitiateRender",!1),H(this,Ye)}static get observedAttributes(){return["access-token","disabled","has-selling-plan","requires-shipping"]}async connectedCallback(){var e,n;super.connectedCallback();try{if((n=(e=this.wrapper)==null?void 0:e.children)!=null&&n.length||this.didInitiateRender)return;if(!this.validateRenderingSurface()){this.clearUI();return}this.instanceNumber===1&&(Ur(this),y.initStarted(),Qd({styleId:"shopify-accelerated-checkout",styles:wc,cssFileName:"AcceleratedCheckout.css"}),this.extractStyles()),this.shopPromiseEligible=Ea();const r=Qe(L.ButtonDisplay,"dc:".concat(this.instanceNumber));this.i18n=Gt(),this.setupFormObserver(),this.didInitiateRender=!0;const a=await this.loadWallet(),i=a.getInstrumentName();this.apiClient=new Ht({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,withCarrierRates:!0,cartPrepareMigrationEnabled:this.isFlagEnabled(Ra)}),this.dataSource=new Kd(this,this.apiClient,i);const o=await this.getWebComponentInstance({wallet:a,instrumentName:i,dataSource:this.dataSource,i18n:this.i18n,apiClient:this.apiClient,buttonDisplayBenchmark:r});this.render(o,i),y.initCompleted(),this.instanceNumber===1&&this.triggerLoadedEvent()}catch(r){if(this.clearUI(),y.initCompleted(r),r.name===gt)throw r;b.notify(new xn("An error occurred while attempting to render AcceleratedCheckout: ".concat(r),{cause:r}))}}async attributeChangedCallback(e,n,r){n!==r&&(xr(this,e,r),e==="has-selling-plan"&&r===""?this.showBuyerConsent(this.apiClient,this.i18n):e==="has-selling-plan"&&r===null&&this.hideBuyerConsent())}async getWebComponentInstance({wallet:e,instrumentName:n,dataSource:r,i18n:a,apiClient:i,buttonDisplayBenchmark:o}){if(this.hidePaymentButton){y.log({body:"Payment button hidden for instrument ".concat(n),attributes:{instrument:n,pageType:this.pageType,containerInstanceNumber:this.instanceNumber,hidePaymentButton:this.hidePaymentButton,isRedirectedFromAmazon:this.isRedirectedFromAmazon,isBuyWithPrimeEligible:this.isBuyWithPrimeEligible}}),y.amazonAdExperimentPaymentButtonHidden({instrument:n});return}const s=await e.createWebComponent({walletContainer:this,dataSource:r,i18n:a,apiClient:i,classNames:yu(n),callToAction:"true",pageType:this.pageType,containerInstanceNumber:this.instanceNumber,onRendered:()=>y.instrumentLoaded({instrumentOrComponentName:n,result:"success",measurement:o()})});if(!s)throw new xn("No web component instance found for instrument ".concat(n));return s}async render(e,n){this.clearUI();const r=this.getOrCreateShadowRoot(),a=document.createElement("style");a.innerHTML=Qa,r.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),r==null||r.appendChild(this.wrapper),this.hasSellingPlan?this.showBuyerConsent(this.apiClient,this.i18n):this.hideBuyerConsent();const l=new DocumentFragment;e&&l.appendChild(e);const u=this.getShopPromiseSlot();u&&l.appendChild(u);const d=this.getMorePaymentOptionsLink(n);d&&l.appendChild(d),this.appendChild(l)}getMorePaymentOptionsLink(e){var n,r;if(e===f.BuyItNow)return null;const a=document.createElement("more-payment-options-link");return qt(a,{"buyer-country":(n=this.buyerCountry)!=null?n:"","access-token":(r=this.accessToken)!=null?r:"","recommended-instrument":e,slot:"more-options"}),a.disabled=this.disabled,a.setDataSource(this.dataSource),a.setI18n(this.i18n),a.setClassNames(ur.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.getRecommendedWallet(),n=bc(e,this.fallbackWallet,"AcceleratedCheckout");return await fu(this,k(w({},n),{instanceNumber:this.instanceNumber}))}getRecommendedWallet(){return this.amazonWallet&&this.isRedirectedFromAmazon?(y.log({body:"Recommended wallet overridden to AmazonPay",attributes:{pageType:this.pageType,containerInstanceNumber:this.instanceNumber,isRedirectedFromAmazon:this.isRedirectedFromAmazon,isBuyWithPrimeEligible:this.isBuyWithPrimeEligible,recommendedWallet:this.recommendedWallet,amazonWallet:this.amazonWallet}}),y.amazonAdExperimentRecommendedWalletOverriden({instrument:f.AmazonPay}),this.amazonWallet):this.recommendedWallet}setupFormObserver(){this.formObserver||(this.formObserver=new Br(this,({disabled:e,hasSellingPlan:n})=>{this.disabled=e,this.hasSellingPlan=n,this.isShippingRequired=gu(this,this.variantParams)}),this.formObserver.setupMutationObservers())}getOrCreateShadowRoot(){return C(this,Ye)||U(this,Ye,this.attachShadow({mode:"closed"})),C(this,Ye)}extractStyles(){if(this.styleExtractorDisabled){vt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled"),y.styleBackwardsCompatibility({usedBackwardsCompatibility:!1});return}const e=Qe(L.StyleExtract,"dc:".concat(this.instanceNumber)),n=Za(this);n&&ei(this,n);const r=e();r&&y.styleBackwardsCompatibilityExecutionTime({measurement:r,pageType:this.pageType,stylesWritten:!!n}),y.styleBackwardsCompatibility({usedBackwardsCompatibility:!!n})}};Ye=new WeakMap,c(xt,"instanceCount",0);let Er=xt;function yu(t){return t===f.BuyItNow?ur.UNBRANDED_BUTTON:ur.BRANDED_BUTTON}function gu(t,e){var n;const r=Fr(t);return!!((n=e.find(a=>a.id===Number(r==null?void 0:r.variantId)))!=null&&n.requiresShipping)}async function fu(t,{recommendedWallet:e,fallbackWallet:n,instanceNumber:r}){const a=e?dt(e):null,i=dt(n),o=async s=>{const l=Da({walletInstrument:s,instanceNumber:r}),u="timeout",d=await Promise.race([l,new Promise(h=>setTimeout(()=>h(u),On))]);if(d===u)y.instrumentSDKLoaded({instrument:s.getInstrumentName(),measurement:On,result:"timeout"});else if(d instanceof _e)return d;return null};if(Dt(t,a)){const s=await o(a);if(s)return s}if(Dt(t,i)){const s=await o(i);if(s)return s}return dt(Yn)}oe("shopify-accelerated-checkout",Er),oe("more-payment-options-link",cc,{isChildCustomElement:!0});const bu=t=>{if(typeof PerformanceObserver>"u")return null;const e=new PerformanceObserver(n=>{n.getEntriesByType("resource").some(r=>r.name.includes(at.CartUpdate)||r.name.includes(at.CartChange)||r.name.includes(at.CartAdd)||r.name.includes(at.CartClear))&&t()});return e.observe({entryTypes:["resource"]}),e},wu=".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;justify-content:var(--shopify-accelerated-checkout-inline-alignment, start)}.wallet-cart-button-container{position:relative;width:150px;min-width:150px;margin:0 5px 5px}.wallet-cart-button-container,.wallet-cart-button{width:150px;min-width:150px;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{display:flex;flex-direction:row;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{width:auto;min-width:0;flex:1 1 0px}@container wrapper (width >= 150px) 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 <= 310px){.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 <= 470px){.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 <= 630px){.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 <= 790px){.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{display:flex;flex-direction:row;justify-content:stretch}.wallet-cart-button-container,.wallet-cart-button{width:auto;min-width:0;flex:1 1 0px}}@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}",_u=".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;justify-content:var(--shopify-accelerated-checkout-inline-alignment, start)}.wallet-cart-button-container{position:relative;width:150px;min-width:150px;margin:0 5px 5px}.wallet-cart-button-container,.wallet-cart-button{width:150px;min-width:150px;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{display:flex;flex-direction:row;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{width:auto;min-width:0;flex:1 1 0px}@container wrapper (width >= 150px) 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 <= 310px){.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 <= 470px){.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 <= 630px){.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 <= 790px){.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{display:flex;flex-direction:row;justify-content:stretch}.wallet-cart-button-container,.wallet-cart-button{width:auto;min-width:0;flex:1 1 0px}}@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 Eu(t){const e=Wt({page:"cart",element:t});return Ta({type:"attributes",form:e})}class Au{constructor(e,n,r){this.element=e,this.cartToken=n,this.apiClient=r}async getInitialCart(e){const n="gid://shopify/Cart/".concat(this.cartToken),r=Eu(this.element);let a,i=[];if(r.length){const o=await this.apiClient.updateCartAttributes({cartId:n,attributes:r,instrumentName:e,startingCheckout:!0});a=o.data,i=o.errors}else a=await this.apiClient.fetchCart({id:n,instrumentName:e,startingCheckout:!0});return{cart:a,errors:i}}}var Ke;const Mt=class Ou extends Mr{constructor(){super(),c(this,"instanceNumber",++Ou.instanceCount),c(this,"pageType",v.CartPage),c(this,"cartObserver",null),c(this,"dataSource",null),c(this,"wrapper"),c(this,"didInitiateRender",!1),c(this,"amazonAdExperimentCheckoutButtonListeners",[]),H(this,Ke)}static get observedAttributes(){return["access-token","has-selling-plan","requires-shipping"]}createDataSource(){if(!this.cartToken){y.cartTokenMissing({reason:"createDataSource"});return}this.i18n=Gt(),this.apiClient=new Ht({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,withCarrierRates:!0,cartPrepareMigrationEnabled:this.isFlagEnabled(Ra)}),this.dataSource=new Au(this,this.cartToken,this.apiClient)}async createWebComponents({shouldRefetchCartAttributes:e}){if(!this.walletConfigs)throw new X({code:"invalid-wallet-configs",message:"[AcceleratedCheckoutCart] walletConfigs does not exist"});const n=dc(this.walletConfigs,"AcceleratedCheckoutCart");if(!(n instanceof Array))throw new X({code:"invalid-wallet-configs",message:"[AcceleratedCheckoutCart] invalid walletConfigs found"});const r=L.ButtonDisplay,a=o=>"".concat(o,":").concat(this.instanceNumber),i=await Cu(this,{walletConfigs:n,startButtonDisplayBenchmark:o=>Ze(r,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,y.instrumentLoaded({instrumentOrComponentName:s,result:"success",measurement:K(r,a(s))}))}})()})}))):[]}async cartChangedCallback(){try{if(!this.dataSource&&this.cartToken){await this.render({shouldRefetchCartAttributes:!0}),y.initCompleted();return}else if(!this.cartToken){y.cartTokenMissing({reason:"cartChangedCallback"});return}await this.updateAttributes()}catch(e){this.clearUI(),b.notify(e)}}async updateAttributes(){var e,n;if(!this.cartToken||!this.apiClient)return;const r=await this.apiClient.fetchLimitedCart({id:"gid://shopify/Cart/".concat(this.cartToken),instrumentName:f.Unknown});this.hasSellingPlan=(e=r.sellingPlan)!=null?e:!1,this.isShippingRequired=(n=r.shippingRequired)!=null?n:!1}async connectedCallback(){super.connectedCallback();try{if(this.didInitiateRender)return;if(this.instanceNumber===1&&Ur(this),y.initStarted(),this.cartObserver=bu(()=>this.cartChangedCallback()),!this.cartObserver){y.log({body:"Cart observer unavailable - PerformanceObserver not supported",attributes:{userAgent:navigator.userAgent}}),this.clearUI();return}if(!this.cartToken){y.cartTokenMissing({reason:"connectedCallback"});return}await this.render({shouldRefetchCartAttributes:!1}),y.initCompleted()}catch(e){this.clearUI(),y.initCompleted(e),b.notify(e)}}disconnectedCallback(){var e;(e=this.cartObserver)==null||e.disconnect(),this.isAmazonAdExperimentEnabled()&&this.amazonAdExperimentRemoveCheckoutButtonListeners()}async attributeChangedCallback(e,n,r){n!==r&&(xr(this,e,r),e==="has-selling-plan"&&r===""?this.showBuyerConsent(this.apiClient,this.i18n):e==="has-selling-plan"&&r===null&&this.hideBuyerConsent())}get cartToken(){return ut("cart")}async render({shouldRefetchCartAttributes:e}){var n;if(this.hasLegacyCartCookie()){y.legacyCartCookie(),this.clearUI();return}this.didInitiateRender=!0;const r=Qe(L.ButtonDisplay,"cart:".concat(this.instanceNumber)),a=await this.createWebComponents({shouldRefetchCartAttributes:e});if(this.clearUI(),a.length===0)return;try{if(this.isAmazonAdExperimentEnabled()){const d=a.find(p=>p.name===f.BuyWithPrime),h=a.find(p=>p.name===f.AmazonPay);y.log({body:"available wallets for amazon ad experiment",attributes:this.getTelemetryAttributes({buyWithPrimeCheckoutButton:!!d,amazonPayCheckoutButton:!!h})}),d?this.accelerateCheckoutButtonsForAmazonAdExperiment(d):h?this.accelerateCheckoutButtonsForAmazonAdExperiment(h):y.amazonAdExperimentAcceleratedCheckoutButtonSetup({instrument:f.Unknown,result:"failed"})}}catch(d){y.log({body:"failed to accelerate checkout buttons for amazon ad experiment",attributes:this.getTelemetryAttributes({error:d instanceof Error?d.message:String(d)})}),b.notify(d,{context:"failed to accelerate checkout buttons for amazon ad experiment"})}const i=new DocumentFragment,o=this.getOrCreateShadowRoot(),s=document.createElement("style");s.innerHTML=[Qa,wu].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=((n=this.i18n)==null?void 0:n.translate("express_checkout"))||"",this.wrapper.appendChild(l);const u=document.createElement("div");u.className="wallet-cart-grid ".concat(ke.CONTAINER),Object.entries(Su).forEach(([d,h])=>{document.querySelector(d)&&u.classList.add(h)}),a.forEach(d=>{const h=document.createElement("div"),p=document.createElement("div"),m=document.createElement("slot");m.name="button-".concat(d.name),h.className="wallet-cart-button-container",p.className="wallet-cart-button",h.setAttribute("data-testid","grid-cell"),h.appendChild(p),p.appendChild(m),u.appendChild(h),i.appendChild(d)}),this.wrapper.appendChild(u),this.hasSellingPlan?this.showBuyerConsent(this.apiClient,this.i18n):this.hideBuyerConsent(),o.appendChild(this.wrapper),this.appendChild(i),y.instrumentLoaded({instrumentOrComponentName:"AcceleratedCheckoutCart",result:"success",measurement:r()})}getTelemetryAttributes(e={}){return w({isAmazonAdExperimentFlagEnabled:this.isFlagEnabled(Me),amazonReferralSessionStorageValue:sessionStorage.getItem("shopify_amazon_referral"),cartToken:this.cartToken,cartInstance:this.instanceNumber,hasDataSource:!!this.dataSource},e)}isAmazonAdExperimentEnabled(){return this.isFlagEnabled(Me)&&sessionStorage.getItem("shopify_amazon_referral")==="mShop"}accelerateCheckoutButtonsForAmazonAdExperiment(e){try{const n=document.getElementsByName("checkout");if(n.length<=0)throw y.log({body:"attempted to accelerate checkout buttons, but none were found",attributes:this.getTelemetryAttributes({walletName:e.name})}),new Error("No checkout buttons found");n.forEach(r=>{const a=async i=>{if(i.preventDefault(),!this.dataSource){this.amazonAdExperimentFallbackToDefaultCheckout(r,e.name);return}try{const{cart:o}=await this.dataSource.getInitialCart(e.name),s=Nr(o);if(!o||!this.accessToken||!s){this.amazonAdExperimentFallbackToDefaultCheckout(r,e.name,"checkout button was clicked but was missing required data to validate ".concat(e.name," eligibility:\n cart: ").concat((o==null?void 0:o.id)||"missing",",\n accessToken: ").concat(this.accessToken||"missing",",\n checkoutToken: ").concat(s||"missing"));return}try{await Wr({configOptionsEndpoint:e.name===f.BuyWithPrime?Lt.OPTIMUS_CONFIG_REST_API_URL:Ot.CV2_CONFIG_REST_API_URL,checkoutUrl:o.checkoutUrl,sourceId:s,accessToken:this.accessToken,instrument:e.name});try{e.triggerCheckout(),y.amazonAdExperimentAcceleratedCheckoutButtonClicked({instrument:e.name,result:"success"}),y.log({body:"checkout button was clicked and accelerated",attributes:this.getTelemetryAttributes({walletName:e.name})})}catch(l){this.amazonAdExperimentFallbackToDefaultCheckout(r,e.name,"checkout button was clicked but failed to accelerate",l)}}catch(l){this.amazonAdExperimentFallbackToDefaultCheckout(r,e.name,"checkout button was clicked but failed to fetch wallets platform config, falling back to guest checkout:\n ".concat(l instanceof Error?"".concat(l.name,": ").concat(l.message):String(l)))}}catch(o){this.amazonAdExperimentFallbackToDefaultCheckout(r,e.name,"checkout button was clicked but was missing required data to validate line item eligibility, falling back to guest checkout",o)}};r.addEventListener("click",a,!0),this.amazonAdExperimentCheckoutButtonListeners.push({button:r,listener:a})}),y.amazonAdExperimentAcceleratedCheckoutButtonSetup({instrument:e.name,result:"success"})}catch(n){y.amazonAdExperimentAcceleratedCheckoutButtonSetup({instrument:e.name,result:"failed"})}}amazonAdExperimentFallbackToDefaultCheckout(e,n,r,a){y.amazonAdExperimentAcceleratedCheckoutButtonClicked({instrument:n,result:"failed"}),r&&(y.log({body:r,attributes:this.getTelemetryAttributes({walletName:n})}),a&&b.notify(a,{context:r}));const i=this.amazonAdExperimentCheckoutButtonListeners.find(o=>o.button===e);if(i){e.removeEventListener("click",i.listener,!0),this.amazonAdExperimentCheckoutButtonListeners=this.amazonAdExperimentCheckoutButtonListeners.filter(s=>s.button!==e);const o=new Event("click",{bubbles:!0,cancelable:!0});typeof e.click=="function"?e.click():e.dispatchEvent(o)}y.amazonAdExperimentAcceleratedCheckoutButtonClicked({instrument:f.BuyItNow,result:"success"})}amazonAdExperimentRemoveCheckoutButtonListeners(){try{this.amazonAdExperimentCheckoutButtonListeners.forEach(({button:e,listener:n})=>{e.removeEventListener("click",n,!0)}),this.amazonAdExperimentCheckoutButtonListeners=[]}catch(e){b.notify(e,{context:"failed to remove checkout button event listeners"})}}getOrCreateShadowRoot(){return C(this,Ke)||U(this,Ke,this.attachShadow({mode:"closed"})),C(this,Ke)}hasLegacyCartCookie(){var e;return this.cartToken?(e=this.cartToken)==null?void 0:e.match(/^[a-z0-9]+$/):!1}extractStyles(){if(this.styleExtractorDisabled){vt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled"),y.styleBackwardsCompatibility({usedBackwardsCompatibility:!1});return}const e=Qe(L.StyleExtract,"cart:".concat(this.instanceNumber)),n=Za(this);if(n){ei(this,n);const a=this.getOrCreateShadowRoot(),i=document.createElement("style");i.innerHTML=_u,a.appendChild(i)}const r=e();r&&y.styleBackwardsCompatibilityExecutionTime({measurement:r,pageType:this.pageType,stylesWritten:!!n}),y.styleBackwardsCompatibility({usedBackwardsCompatibility:!!n})}};Ke=new WeakMap,c(Mt,"instanceCount",0);let Ar=Mt;async function Cu(t,{walletConfigs:e,startButtonDisplayBenchmark:n=()=>{}}){const r=hc(t,Yd(e));return(await Promise.all(r.map(a=>(n(a.getInstrumentName()),Da({walletInstrument:a,instanceNumber:t.instanceNumber}))))).filter(a=>a!=null)}const Su={".additional-checkout-buttons--vertical shopify-accelerated-checkout-cart":"wallet-cart-grid--vertical",".additional-checkout-buttons--horizontal shopify-accelerated-checkout-cart":"wallet-cart-grid--horizontal"};oe("shopify-accelerated-checkout-cart",Ar);class Pu{getInitialCart(){throw new Error('[NoOpDataSource] Unexpected call to "getCart"')}}const Ut=class Mu extends Mr{constructor(){super(...arguments),c(this,"instanceNumber",++Mu.instanceCount),c(this,"pageType",v.Checkout)}get walletConfig(){return this.getAttribute("wallet-config")}async connectedCallback(){var e;super.connectedCallback();try{if(this.children.length)return;this.instanceNumber===1&&(Ur(this),y.initStarted());const n=Qe(L.ButtonDisplay,"dc:".concat(this.instanceNumber)),r=uc(this.walletConfig,"WalletButton");if(!r)throw new Ai("[WalletButton] No config provided.");const a=dt(r);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){y.initCompleted(),this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"success"}}));return}const i=a.getInstrumentName();this.i18n=Gt(),this.apiClient=new Ht({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale});const o=await this.createWebComponent(a,this.i18n,this.apiClient,i,n);this.innerHTML="",this.appendChild(o),y.initCompleted(),this.instanceNumber===1&&this.triggerLoadedEvent()}catch(n){this.innerHTML="",this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"failure",message:(e=n.message)!=null?e:"Error loading wallet SDK"}})),y.initCompleted(n),b.notify(n)}}async createWebComponent(e,n,r,a,i){const o=await e.createWebComponent({walletContainer:this,dataSource:new Pu,i18n:n,apiClient:r,containerInstanceNumber:this.instanceNumber,pageType:this.pageType});return o.onRendered=()=>{this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"success"}})),y.instrumentLoaded({instrumentOrComponentName:a,result:"success",measurement:i()})},o}async eligibleToShow(e){return!(!Dt(this,e)||(await e.loadWalletSDK(),!e.getPartnerSDKEligibility().eligible))}};c(Ut,"instanceCount",0);let Cr=Ut;oe("shopify-wallet-button",Cr),yi(b,{metadata:{custom:{"notify-origin":"window-onerror"}}}),gi(b,{metadata:{custom:{"notify-origin":"unhandled-promise-rejection-handler"}}}),y.startExporter();