import.meta;var Ea=Object.defineProperty,Aa=Object.defineProperties,Ca=Object.getOwnPropertyDescriptors,ct=Object.getOwnPropertySymbols,Ir=Object.prototype.hasOwnProperty,Pr=Object.prototype.propertyIsEnumerable,Mt=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),vr=t=>{throw TypeError(t)},Ft=(t,e,n)=>e in t?Ea(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_=(t,e)=>{for(var n in e||(e={}))Ir.call(e,n)&&Ft(t,n,e[n]);if(ct)for(var n of ct(e))Pr.call(e,n)&&Ft(t,n,e[n]);return t},T=(t,e)=>Aa(t,Ca(e)),Dr=(t,e)=>{var n={};for(var r in t)Ir.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&ct)for(var r of ct(t))e.indexOf(r)<0&&Pr.call(t,r)&&(n[r]=t[r]);return n},d=(t,e,n)=>Ft(t,typeof e!="symbol"?e+"":e,n),Rr=(t,e,n)=>e.has(t)||vr("Cannot "+n),C=(t,e,n)=>(Rr(t,e,"read from private field"),n?n.call(t):e.get(t)),O=(t,e,n)=>e.has(t)?vr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),L=(t,e,n,r)=>(Rr(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),J=function(t,e){this[0]=t,this[1]=e},ve=(t,e,n)=>{var r=(o,s,l,c)=>{try{var u=n[o](s),h=(s=u.value)instanceof J,p=u.done;Promise.resolve(h?s[0]:s).then(y=>h?r(o==="return"?o:"next",s[1]?{done:y.done,value:y.value}:y,l,c):l({value:y,done:p})).catch(y=>r("throw",y,l,c))}catch(y){c(y)}},a=o=>i[o]=s=>new Promise((l,c)=>r(o,s,l,c)),i={};return n=n.apply(t,e),i[Mt("asyncIterator")]=()=>i,a("next"),a("throw"),a("return"),i},X=(t,e,n)=>(e=t[Mt("asyncIterator")])?e.call(t):(t=t[Mt("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(c=>o({value:c,done:l}),s)))),n("next"),n("return"),e);const Sa=":host{display:flex;align-items:center;justify-content:center}";class Ia extends HTMLElement{constructor(){var e,n;super(),d(this,"size"),d(this,"color"),this.size=(e=this.getAttribute("size"))!=null?e:"18px",this.color=(n=this.getAttribute("color"))!=null?n:"gray",this.attachShadow({mode:"open"})}connectedCallback(){this.render();const e=document.createElement("style");e.textContent=Sa,this.shadowRoot.appendChild(e)}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 Pa="#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 va(t){return dn(t).map(e=>e instanceof Error?e:new un("[".concat(typeof e,"] ").concat(Da(e).slice(0,10240))))}function dn(t,e=0){return e>=20?[t,"Truncated cause stack"]:t instanceof Error&&"cause"in t?[t,...dn(t.cause,e+1)]:[t]}function Da(t){var e;if(typeof t!="string")try{return(e=JSON.stringify(t))!=null?e:typeof t}catch(n){}return"".concat(t)}var un=class extends Error{constructor(){super(...arguments),d(this,"name","BugsnagInvalidError")}},hn=/^\s*at .*(\S+:\d+|\(native\))/m,Ra=/^(eval@)?(\[native code])?$/;function Na(t){return t.stack?t.stack.match(hn)?Ta(t):ka(t):[]}function pn(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 Ta(t){return t.stack.split("\n").filter(e=>!!e.match(hn)).map(e=>{let n=e.replace(/^\s+/,"").replace(/^.*?\s+/,""),r=n.match(/ (\(.+\)$)/);n=r?n.replace(r[0],""):n;let a=pn(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 ka(t){return t.stack.split("\n").filter(e=>!e.match(Ra)).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=pn(e.replace(n,""));return{method:a,file:i[0],lineNumber:i[1],columnNumber:i[2]}})}var Nr="5",La=class{constructor(t){d(this,"breadcrumbs",[]),d(this,"apiKey"),d(this,"plugins"),d(this,"appId"),d(this,"appType"),d(this,"appVersion"),d(this,"releaseStage"),d(this,"locale"),d(this,"userAgent"),d(this,"metadata"),d(this,"persistedMetadata"),d(this,"onError"),d(this,"onPostErrorListeners",[]),d(this,"endpoints");var e,n;this.apiKey=t.apiKey,this.appType=t.appType,this.appId=t.appId,this.appVersion=t.appVersion,this.releaseStage=t.releaseStage,this.locale=t.locale,this.userAgent=t.userAgent,this.metadata=t.metadata,this.onError=t.onError,this.persistedMetadata={},this.endpoints=(e=t.endpoints)!=null?e:{notify:"https://notify.bugsnag.com/",sessions:"https://sessions.bugsnag.com"},this.plugins=(n=t.plugins)!=null?n:[],this.plugins.forEach(r=>r.load(this)),this.leaveBreadcrumb("Bugsnag started",void 0,"state")}addMetadata(t){for(let e of Object.keys(t))this.persistedMetadata[e]=t[e]}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,c;let u=va(t),h=_(_(_({},this.metadata),this.persistedMetadata),i),p=this.buildBugsnagEvent(u,{errorClass:e,severityType:r,handled:a,severity:n,metadata:h,context:o,groupingHash:s});if(((c=(l=this.onError)==null?void 0:l.call(this,p,t))==null||c)&&this.releaseStage!=="development"){let y=this.sendToBugsnag(p);return this.onPostErrorListeners.forEach(E=>E(p)),y}return Promise.resolve()}addOnPostError(t){this.onPostErrorListeners.push(t)}buildBugsnagEvent(t,{errorClass:e,severity:n="error",severityType:r="handledException",handled:a,metadata:i={},context:o,groupingHash:s}){let l=new Date().toISOString(),{breadcrumbs:c,appId:u,appType:h,appVersion:p,releaseStage:y,locale:E,userAgent:w}=this,A=t.map((I,k)=>({errorClass:k===0&&e!=null?e:I.name,stacktrace:mn(u,I),message:I.message}));return{payloadVersion:Nr,exceptions:A,severity:n,severityReason:{type:r},unhandled:!a,app:{id:u,type:h,version:p,releaseStage:y},device:{time:l,locale:E,userAgent:w},breadcrumbs:c,context:o,metaData:i,groupingHash:s}}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":Nr,"Bugsnag-Sent-At":t.device.time},body:JSON.stringify(n)})}catch(r){console.warn("[bugsnag-light] failed to send an event"),console.warn(r)}}};function mn(t,e){let n=Na(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 un){let r=n.findIndex(a=>a.method.endsWith("notify"));r>-1&&(n=n.slice(r+1))}return n}var xa=class Ic extends Error{constructor(e){super(e),d(this,"reason"),this.name="BreadcrumbsPluginFetchError",Object.setPrototypeOf(this,Ic.prototype)}};function Oa(t){let e=window.onerror;window.onerror=(n,r,a,i,o)=>{o&&t.notify(o,{severityType:"unhandledException",handled:!1}),typeof e=="function"&&e.apply(window.onerror,[n,r,a,i,o])}}function Ma(t){window.addEventListener("unhandledrejection",e=>{e.reason&&!(e.reason instanceof xa)&&t.notify(e.reason,{severityType:"unhandledPromiseRejection",handled:!1})})}function Ze(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 Yt={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",HIDDEN:"shopify-payment-button__button--hidden"},Fa={DARK:"apple-pay--dark",LIGHT:"apple-pay--light"},Ua=44,Ba="_shopify_y",gn=6,$a="discount_code",ir="https://static-na.payments-amazon.com/checkout.js",Ge={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"},yt="VALIDATION_CUSTOM",fn="portable-wallets",Ce={BUTTON:"accelerated-checkout-button",BUTTON_ON_CART:"accelerated-checkout-button-cart",CONTAINER:"accelerated-checkout-button-container"},bn="unknown";function wn(t){try{return!t.toString().includes("[native code]")}catch(e){return!0}}const Ut=new Map,Ha={checkDuplicate({errorClass:t,message:e}){if(Ut.has(t)){const n=Ut.get(t);if(n.has(e))return!0;n.add(e)}else Ut.set(t,new Set([e]));return!1},reset(){}};function P(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var Ga=0;function se(t){return"__private_"+Ga+++"_"+t}function It(t){return Object.entries(t).map(([e,n])=>({key:e,value:{stringValue:String(n)}}))}function Va(t){return Object.entries(t).map(([e,n])=>({key:e,value:_n(n)}))}function _n(t){if(Array.isArray(t))return{arrayValue:{values:t.map(e=>_n(e))}};switch(typeof t){case"boolean":return{boolValue:!!t};case"number":return{doubleValue:Number(t)};case"string":default:return{stringValue:String(t)}}}const or=1,za=qa(5,2,12);function qa(t,e,n){const r=[0];for(let a=0;a{switch(r.attributes=_(_({},P(this,W)[W]),r.attributes),r.type){case"histogram":Ya(e,r);break;case"exponential_histogram":Wa(e,r);break;case"counter":Ka(e,r);break;case"gauge":Qa(e,r);break}});const n=Object.values(e);n.length!==0&&(P(this,z)[z]=[],await P(this,ue)[ue].exportMetrics(n))}async exportLogs(){const e=P(this,he)[he].map(n=>{const r={timeUnixNano:n.timeUnixNano,observedTimeUnixNano:n.timeUnixNano,attributes:Va(_(_({},P(this,W)[W]),n.attributes))};return n.body&&(r.body={stringValue:n.body}),r});e.length!==0&&(P(this,he)[he]=[],await P(this,ue)[ue].exportLogs(e))}}function Ya(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:za,c=new Array(l.length+1).fill(0);t[r]||(t[r]={name:r,unit:i||"1",histogram:{aggregationTemporality:or,dataPoints:[]}});for(let u=0;u0?h:0,bucketCounts:r>0?[1]:[]};t[n].exponentialHistogram.dataPoints.push({attributes:It(o!=null?o:{}),startTimeUnixNano:i,timeUnixNano:i,count:1,sum:l,scale:c,zeroCount:p,positive:E,negative:y,min:l,max:l,zeroThreshold:0})}function Ka(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:or,isMonotonic:!0,dataPoints:[]}}),t[n].sum.dataPoints.push({startTimeUnixNano:i,timeUnixNano:i,asDouble:r,attributes:It(o!=null?o:{})})}function Qa(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:It(o!=null?o:{})})}var Ve=se("url"),pe=se("serviceName"),ze=se("logger"),qe=se("fetchFn");class Ja{constructor(e,n,r){Object.defineProperty(this,Ve,{writable:!0,value:void 0}),Object.defineProperty(this,pe,{writable:!0,value:void 0}),Object.defineProperty(this,ze,{writable:!0,value:void 0}),Object.defineProperty(this,qe,{writable:!0,value:void 0}),P(this,Ve)[Ve]=e.replace(/\/v1\/(logs|metrics|traces)\/?$/,""),P(this,pe)[pe]=n,P(this,ze)[ze]=r==null?void 0:r.logger,P(this,qe)[qe]=r==null?void 0:r.fetchFn}async exportMetrics(e){const n={resourceMetrics:[{resource:{attributes:[{key:"service.name",value:{stringValue:P(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:P(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(P(this,Ve)[Ve]).concat(n),{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if((r=P(this,ze)[ze])===null||r===void 0||r.log({status:a.status}),!a.ok){if(a.status===400){const i=await a.text();throw new Je("Invalid OpenTelemetry Data: ".concat(i))}if(a.status===429||a.status===503){const i=await a.json(),o=a.headers.get("Retry-After"),s=o?{seconds:Number(o)}:void 0;throw new Je("Server did not accept data",{errorData:i,retryAfter:s,body:e})}throw new Je("Server responded with ".concat(a.status))}}exporterFetch(){return P(this,qe)[qe]||fetch}}class Je extends Error{constructor(e,n){super(e),this.metadata=void 0,this.name="OpenTelemetryClientError",this.metadata=n}}const Xa="https://otlp-http-production.shopifysvc.com",Za="portable_wallets";var Le;class ei{constructor(e){O(this,Le),L(this,Le,e)}async exportMetrics(e){var n;try{await C(this,Le).exportMetrics(e)}catch(r){if(r instanceof Je){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 Tr("Unable to export metrics",{cause:r})}}async exportLogs(e){var n;try{await C(this,Le).exportLogs(e)}catch(r){if(r instanceof Je){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 Tr("Unable to export logs",{cause:r})}}}Le=new WeakMap;const ti=new Ja(Xa,Za),ri=new ei(ti),v=new ja({exporter:ri}),En="TelemetryExportError";class Tr extends Error{constructor(){super(...arguments),d(this,"name",En)}}var x=(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.AuthorizationAttempt="portable_wallets_authorization_attempt",t.AuthorizationComplete="portable_wallets_authorization_complete",t.CartTokenMissing="portable_wallets_cart_token_missing",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.ErrorTriggered="portable_wallets_error_triggered",t))(x||{}),_e=(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))(_e||{});let sr=ni();function ni(){return{shopId:bn,debug:!1}}function ai(t){Object.assign(sr,t)}function lr(){const t=sr,{debug:e}=t;return Dr(t,["debug"])}function ii(){return sr.debug}const ot="DeveloperError";class cr extends Error{constructor({code:e,message:n}){const r="An unexpected error happened likely because of customizations made to HTML/JavaScript on this site ".concat(n);super("[".concat(e,"]: ").concat(r)),d(this,"name",ot),d(this,"code","unknown"),this.code=e}}const dr="SilencedError";class Pt extends Error{constructor(){super(...arguments),d(this,"name",dr)}}class oi extends Error{constructor(){super(...arguments),d(this,"name","MissingConfigError")}}const An="https://www.paypal.com",si=["Load failed","Failed to fetch","when attempting to fetch resource","GraphQL mutation failed with status 404","Component closed",ot,dr],kr=new Map([["TypeError","Illegal constructor"],["BugsnagInvalidError",'"isTrusted":true']]),li=[dr,En,"OpenTelemetryClientError"],ci=["Chrome-Lighthouse"];function di(t){const e=t.exceptions[0];if(!e||!e.message||Ha.checkDuplicate(e))return!1;ui(t);let n=!0;try{n=pi(t)}catch(r){const a=r;console.error(a);const i={errorClass:"UnfilterableError",message:"Could not properly filter error with message: ".concat(a.message),stacktrace:mn(fn,a)};t.exceptions.unshift(i)}return vi(n),ii()&&Di({errorClass:e.errorClass,message:e.message,stacktrace:JSON.stringify(e.stacktrace),filterResult:n}),n}function ui(t){var e,n;t.context=window.location.pathname,t.request||(t.request={}),t.request.url=window.location.href,t.device.orientation=(n=(e=window.screen)==null?void 0:e.orientation)==null?void 0:n.type,hi(t),t.metaData=T(_({},t.metaData),{shop:_(_({},lr()),t.metaData.shop),custom:T(_({},t.metaData.custom),{customFetch:wn(fetch)})})}function hi(t){for(const e of t.exceptions)for(const n of e.stacktrace)n.file.startsWith(An)&&(n.inProject=!0)}function pi(t){const e=t.exceptions[0];return!(mi()||yi(t)||gi(e)||fi()||bi(t)||_i(t)||Ei(t)||Ai(e.message)||Ci(t)||Si(t)||Ii(e)||Pi(t))}function mi(){return ci.some(t=>navigator.userAgent.includes(t))}function yi(t){return t.exceptions[0].stacktrace.length===0}function gi(t){return t.stacktrace.some(e=>{var n;return(n=e.file)==null?void 0:n.includes("spin.dev")})}function fi(){return[HTMLElement,Event,document.createElement].some(wn)}function bi(t){const e=t.exceptions.map(n=>n.stacktrace.filter(r=>!wi(r)));return e.some(n=>{var r;return!((r=n[0])!=null&&r.inProject)})?!0:e.some(n=>n.every(r=>r.file.startsWith(An)))}function wi(t){return t.file.includes("native code")||t.file.includes("/cdn/wpm/")}function _i(t){const e=t.exceptions[0],n=e.stacktrace.some(a=>a.inProject),r=t.unhandled&&!e.stacktrace[0].inProject;return!n||r}function Ei(t){var e;return(e=t.metaData.custom)!=null&&e.customFetch?t.exceptions.some(n=>{var r;return(r=n.message)==null?void 0:r.includes("GraphQL Client: API multipart response did not return an iterable body")}):!1}function Ai(t){return si.some(e=>t==null?void 0:t.includes(e))}function Ci(t){const e=t.exceptions.some(n=>n.errorClass===ot);return e&&console.error(t.exceptions[0]),e}function Si(t){return t.exceptions.some(e=>li.includes(e.errorClass))}function Ii(t){const e=t.errorClass,n=t.message;return kr.has(e)&&(n==null?void 0:n.includes(kr.get(e)))}function Pi(t){return t.exceptions[0].errorClass==="BugsnagInvalidError"&&t.unhandled}function vi(t){v.counter({name:x.ErrorTriggered,value:1,attributes:{filterResult:t}})}function Di(t){v.log({body:"Bugsnag Error",attributes:_(_({},lr()),t)})}var cn;const Ri={apiKey:"cb577dc231be1c7494db8a63441ef66b",appId:fn,appVersion:"0.0.0-53152cfa7861a5eb87b05c2fba9d199523469c27",releaseStage:"production",locale:"en",userAgent:navigator.userAgent,metadata:{user:{id:(cn=Ze(Ba))!=null?cn:"unknown"}},onError:di},b=new La(Ri);b.addOnPostError(t=>{b.leaveBreadcrumb("Bugsnag Error Notified",{errorClass:t.exceptions[0].errorClass,message:t.exceptions[0].message},"error")});var Ni={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."}}}};let Bt;class Lr extends Error{constructor(e,n){const r="i18n: Missing or invalid translation '".concat(e,"' in '").concat(n,"'");super(r)}}class Ti extends Error{constructor(e,n,r){const a="i18n: Missing translation template key '".concat(e,"' for '").concat(n,"' in '").concat(r,"'");super(a)}}class ki extends Error{constructor(e,n,r){const a="i18n: Invalid pluralization for '".concat(e,"':'").concat(n,"' in '").concat(r,"'");super(a)}}function vt(){return Bt==null&&(Bt=Li(Ni)),Bt}function Li(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,c)=>{const u=c.replace(/%\{(.*)\}/,"$1");return o[u]?l.replace(c,o[u]):(b.notify(new Ti(u,i,a)),l)},i):i},a=xi();return{locale:a,translate(i,o={}){var s;const l=i.split(".");let c=t[a];try{for(const u of l)switch(typeof c){case"object":c=c[u];break;case"string":case"undefined":throw new Lr(i,a)}if(e(c,o)){if(typeof c=="string")throw new ki(i,c,a);c=c[n(c,o.count)]}if(typeof c!="string")throw new Lr(i,a);return r(c,o)}catch(u){return b.notify(u),(s=o.defaultValue)!=null?s:i}}}}function xi(){return"en"}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||{}),S=(t=>(t.CartPage="cart_page",t.CartAjax="cart_ajax",t.ProductPage="product",t.Checkout="checkout",t.Unknown="unknown",t))(S||{}),Ye=(t=>(t.CartChange="/cart/change",t.CartUpdate="/cart/update",t.CartAdd="/cart/add",t.CartClear="/cart/clear",t))(Ye||{}),Ae=(t=>(t.OneTimePurchase="ONE_TIME_PURCHASE",t.Subscription="SUBSCRIPTION",t))(Ae||{});function Oi(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 Bi(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||Ui()).toString()};return t&&t.userAgent&&(e["User-Agent"]=t.userAgent),t&&t.remoteIp&&(e["X-Forwarded-For"]=t.remoteIp),e}async function $i({endpoint:t,event:e,keepalive:n}){return fetch(t!=null?t:Mi+Fi,{method:"post",headers:Bi(e.metadata),body:JSON.stringify({schema_id:e.schemaId,payload:e.payload}),keepalive:n})}const Hi=["Chrome-Lighthouse"];function Gi(){const t=navigator.userAgent;return Hi.some(e=>t.includes(e))}async function Vi(t){if(Gi())return;b.leaveBreadcrumb("monorail event produced to ".concat(t.schemaId),t);let e;try{e=await $i({event:t})}catch(n){}if(!(e!=null&&e.ok))try{v.counter({name:x.MonorailProduceError,value:1,attributes:{schemaId:t.schemaId}})}catch(n){}}const xr="shopify_wallet_checkout_track/6.2";async function V(t){var e,n,r,a,i,o,s;let l=null;try{const c=await zi();if(l={schemaId:xr,payload:{app_name:"storefront",page_type:go(),checkout_one:!0,event:t.event,event_subtype:t.eventSubtype,checkout_token:t.checkoutToken,instrument_id:t.instrumentId,ttl:t.ttl,error_reason:t.errorReason,uniq_token:(e=c==null?void 0:c.uniqToken)!=null?e:"",visit_token:(n=c==null?void 0:c.visitToken)!=null?n:"",micro_session_id:(r=c==null?void 0:c.microSessionId)!=null?r:"",micro_session_count:(a=c==null?void 0:c.microSessionCount)!=null?a:0,shop_id:(i=c==null?void 0:c.shopId)!=null?i:0,theme_id:c==null?void 0:c.themeId,theme_city_hash:(o=c==null?void 0:c.themeCityHash)!=null?o:"",content_language:(s=c==null?void 0:c.contentLanguage)!=null?s:"",referer:c==null?void 0:c.referer}},!(t!=null&&t.event)){b.notify(new Error("Event is required"),{metadata:{request:{monorail:{schemaId:xr,payload:JSON.stringify(l)}}}});return}await Vi(l)}catch(c){b.notify(new qi("Failed to send monorail event: ".concat(c),{cause:c}),{metadata:{request:{monorail:{payload:JSON.stringify(l!=null?l:t)}}}})}}async function zi(){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,c;(c=(l=window==null?void 0:window.ShopifyAnalytics)==null?void 0:l.lib)!=null&&c.trekkie&&(clearInterval(o),i())},100),s=setTimeout(()=>{clearInterval(o),clearTimeout(s),i()},7e3)}),(a=(r=(n=window.ShopifyAnalytics)==null?void 0:n.lib)==null?void 0:r.trekkie)==null?void 0:a.defaultAttributes}class qi extends Error{constructor(){super(...arguments),d(this,"name","MonorailError")}}var B=(t=>(t.CartInitCalled="portable_wallets_cart_init_called",t.ClickSheetCancelled="portable_wallets_instrument_click_sheet_cancelled",t.ClickSheetFailed="portable_wallets_instrument_click_sheet_failure",t.ClickSheetSuccess="portable_wallets_instrument_click_sheet_success",t.SheetFailed="portable_wallets_instrument_sheet_failed",t.AuthorizationAttempt="portable_wallets_authorization_attempt",t.AuthorizationComplete="portable_wallets_authorization_complete",t.InitCalled="portable_wallets_init_called",t.InitFailed="portable_wallets_init_failed",t.InitSuccess="portable_wallets_init_success",t.UpdateFailed="portable_wallets_instrument_update_failed",t.InstrumentLoaded="portable_wallets_instrument_loaded",t.InstrumentLoadFailed="portable_wallets_instrument_load_failed",t.FirstVisible="portable_wallets_first_visible",t.FirstVisibleNotAvailable="portable_wallets_first_visible_not_available",t))(B||{});const Or={[S.Checkout]:"bwp_checkout_widget_click",[S.CartAjax]:"bwp_cart_widget_click",[S.CartPage]:"bwp_cart_widget_click",[S.ProductPage]:"bwp_widget_click",[S.Unknown]:"bwp_widget_click"};function ji({apiClientId:t,skus:e,pageType:n}){var r;if(!((r=window.Shopify)!=null&&r.analytics))return;const a=n&&Or[n]||"bwp_widget_click";a===Or[S.Checkout]&&window.Shopify.analytics.publish("shopify:app:pixels:load:".concat(t),{},{sendTo:"PIXEL-LOADER"}),window.Shopify.analytics.publish(a,{skus:e},{sendTo:t})}function Yi(){V({event:B.InitCalled})}function Wi(t){var e,n;const r="error"in t?"failed":t.result,a="error"in t&&po(t.error)?"[".concat(t.error.name,"]: ").concat(t.error.code):"eventType"in t&&t.eventType||void 0;V({event:r==="success"?B.InitSuccess:B.InitFailed,eventSubtype:a}),v.counter({name:x.InitCompleted,value:1,attributes:{result:r,eventType:a,recoveredFailure:!!((n=(e=window.Shopify)==null?void 0:e.PaymentButton)!=null&&n.failedToLoad)}})}function Ki({instrumentOrComponentName:t,result:e,measurement:n}){V({event:e==="success"?B.InstrumentLoaded:B.InstrumentLoadFailed,instrumentId:t,ttl:n}),n!=null&&(v.histogram({name:x.InstrumentLoadTime,value:n,attributes:{instrument:t},unit:"ms"}),v.histogram({name:x.InstrumentLoadTimeFromPageLoad,value:window.performance.now(),attributes:{instrument:t},unit:"ms"}))}function Qi({instrument:t,measurement:e,result:n}){const r=n==="success"?_e.InstrumentSdkLoaded:_e.InstrumentSdkFailed;V({event:r,instrumentId:t,ttl:e,errorReason:n==="success"?void 0:n}),e!=null&&v.histogram({name:_e.InstrumentSdkLoaded,value:e,attributes:{instrument:t,result:n},unit:"ms"})}function Ji({instrument:t,result:e,reason:n}){const r=e==="success"?_e.InstrumentSdkEligible:_e.InstrumentSdkNotEligible;V({event:r,instrumentId:t}),v.counter({name:_e.InstrumentSdkEligible,value:1,attributes:{instrument:t,reason:n,result:e}})}function Xi({instrument:t,result:e,reason:n}){v.counter({name:x.InstrumentLoadEligibility,value:1,attributes:{instrument:t,result:e,reason:n}})}function Zi(t){v.counter({name:x.ButtonRender,value:1,attributes:{result:"success",instrument:t}})}function eo(t){v.counter({name:x.ButtonRender,value:1,attributes:{result:"failed",instrument:t}})}function to({instrument:t,result:e,webPixelMetaData:n}){V({event:e==="success"?B.ClickSheetSuccess:B.ClickSheetFailed,instrumentId:t}),v.counter({name:x.SheetClicked,value:1,attributes:{instrument:t,result:e}}),t===f.BuyWithPrime&&n&&ji(n)}function ro(t,e){V({event:"".concat(B.UpdateFailed,"-").concat(e),instrumentId:t})}function no(t){V({event:B.ClickSheetCancelled,instrumentId:t}),v.counter({name:x.SheetCancelled,value:1,attributes:{instrument:t}})}function ao(t,e){V({event:B.SheetFailed,instrumentId:t,errorReason:e==null?void 0:e.message}),v.counter({name:x.SheetFailed,value:1,attributes:{instrument:t}})}function io(t){V({event:B.AuthorizationAttempt,instrumentId:t}),v.counter({name:x.AuthorizationAttempt,value:1,attributes:{instrument:t}})}function oo({instrument:t,measurement:e,result:n}){V({event:B.AuthorizationComplete,eventSubtype:n,ttl:e,instrumentId:t}),e!=null&&v.histogram({name:x.AuthorizationComplete,value:e,attributes:{instrument:t,result:n},unit:"ms"})}function so({instrument:t,reason:e}){v.counter({name:x.Decelerated,value:1,attributes:{instrument:t,reason:e}}),g.flushTelemetry()}function lo({reason:t}){v.counter({name:x.CartTokenMissing,value:1,attributes:{reason:t}})}function co(){v.counter({name:x.WalletConfigDeveloperError,value:1})}function uo(){v.counter({name:x.LegacyCartCookie,value:1})}function ho(){window.setInterval(()=>{Sn()},1e3)}function po(t){return(t==null?void 0:t.name)===ot}function Sn(){v.exportMetrics(),v.exportLogs()}function mo(t){const{body:e,attributes:n}=t;v.log({body:e,attributes:_(_({},lr()),n)})}function yo(){v.counter({name:x.StyleBackwardsCompatibility,value:1})}const g={initStarted:R(Yi),initCompleted:R(Wi),instrumentLoaded:R(Ki),instrumentLoadEligibility:R(Xi),instrumentSDKLoaded:R(Qi),instrumentSDKEligible:R(Ji),renderSucceeded:R(Zi),renderFailed:R(eo),sheetClicked:R(to),sheetCancelled:R(no),sheetFailed:R(ao),updateFailed:R(ro),authorizationAttempt:R(io),authorizationComplete:R(oo),startExporter:R(ho),decelerated:R(so),cartTokenMissing:R(lo),walletConfigDeveloperError:R(co),legacyCartCookie:R(uo),flushTelemetry:R(Sn),styleBackwardsCompatibility:R(yo),log:R(mo,{logErrors:!1})};function R(t,{logErrors:e=!0}={}){return(...n)=>{try{t(...n)}catch(r){e&&g.log({body:"Error calling telemetry function",attributes:{error:"".concat(r)}})}}}const We=[];function le(t,e,n){if(window.customElements!=null)try{const r=e;window.customElements.get(t)||(window.customElements.define(t,r),n!=null&&n.isChildCustomElement&&We.push(t))}catch(r){b.notify(r),Oi()}}function gt(){const t=new URLSearchParams(window.location.search);return function(e){return!!t.get(e)}}function go(){var t,e,n,r;const a=(t=window.Shopify)==null?void 0:t.CartType;if(a===S.CartAjax)return S.CartAjax;if(a===S.CartPage)return S.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 S.ProductPage;case"cart":return S.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 S.ProductPage;case"cart":return S.CartPage}}catch(s){console.error("Error parsing JSON script tag:",s)}return S.Unknown}function Ee(t){return Number(t).toFixed(2)}function In(t){if(!(!t||!t.id||!t.id.includes("gid://shopify/Cart/")))return t.id.replace("gid://shopify/Cart/","").split("?")[0]}function te(){let t;return[new Promise(e=>t=e),t]}const fo={force_shop_pay_product:"direct_checkout_product",force_shop_pay_cart:"direct_checkout_cart"};function ie(t,e="no_redirect_for_checkout"){g.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=fo[e];r&&n.searchParams.set("redirect_source",r);break}}window.location.assign(n.toString())}function Pn(){return!!document.querySelector('[data-source-attribution="shopify.shop-promise-pdp"]')}function Ke(){return new Date().getTime()}function ur(t){return t.find(e=>typeof e=="object"&&(e==null?void 0:e.code)===yt)}class bo extends HTMLElement{constructor(){super(),d(this,"overflow"),d(this,"formerFocus"),this.attachShadow({mode:"open"}),this.overflow="",this.formerFocus=document.activeElement}connectedCallback(){const e=vt();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=Pa,n.appendChild(i),this.overflow=document.body.style.overflow,document.body.style.overflow="hidden",this.trapFocus(r,n),le("svg-icon",Ia)}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 wo="@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 Dt({type:t="button",label:e=void 0}={}){const n=document.createElement("button");return n.type=t,e&&n.setAttribute("aria-label",e),n}function Rt(t,e){for(const[n,r]of Object.entries(e))t.setAttribute(n,r)}function Mr(t,e){for(const[n,r]of Object.entries(e))t.style.setProperty(n,r)}function Se(t,e){const n=document.createElement("top-level-modal");n.textContent=e,Rt(n,{"data-testid":"top-level-modal","has-close-button":"true",title:t}),document.body.appendChild(n)}function hr(t,e,n){const r=document.createElement("top-level-modal");Rt(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 Q(t,e){Se(e.translate("error_dialogs.wallet.title",{wallet:t}),e.translate("error_dialogs.wallet.generic_error",{wallet:t}))}function Ie(t,e){Se(t.translate("error_dialogs.checkout.title"),e)}le("top-level-modal",bo);class Nt 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 cartPrepareMigrationEnabled(){return this.hasAttribute("cart-prepare")}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 _o="#more-payment-options-link{cursor:pointer}";function Eo(t){const e=n=>{n.persisted&&(t(),window.removeEventListener("pageshow",e))};window.addEventListener("pageshow",e)}var m=(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(yt),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.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))(m||{});const Ao=["DELIVERY_FIRST_NAME_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName"],Co=["DELIVERY_FIRST_NAME_INVALID","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.firstName"],So=["DELIVERY_LAST_NAME_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName"],Io=["DELIVERY_LAST_NAME_INVALID","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.lastName"],Po=["DELIVERY_ADDRESS1_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address1"],vo=["DELIVERY_ADDRESS2_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.address2"],Do=["DELIVERY_CITY_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.city"],Ro=["DELIVERY_POSTAL_CODE_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.zip"],vn=["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"],No=["DELIVERY_PHONE_NUMBER_REQUIRED","ADDRESS_FIELD_IS_REQUIRED: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],To=["INVALID: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.country","Variable $buyerIdentity of type CartBuyerIdentityInput! was provided invalid value for countryCode"],ko=["DELIVERY_PHONE_NUMBER_INVALID","INVALID: buyerIdentity.phone","ADDRESS_FIELD_DOES_NOT_MATCH_EXPECTED_PATTERN: buyerIdentity.deliveryAddressPreferences.0.deliveryAddress.phone"],Dn=["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"],Rn=["INVALID_PAYMENT: amount","INVALID_PAYMENT: payment.amount"],Nn=["TAX_NEW_TAX_MUST_BE_ACCEPTED","PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"],Lo=["INVALID_PAYMENT: payment.freePaymentMethod.billingAddress","INVALID_PAYMENT: payment.walletPaymentMethod.applePayWalletContent.billingAddress"],Tn=["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_OUT_OF_STOCK","MERCHANDISE_PRODUCT_VARIANT_NOT_FOUND","MERCHANDISE_NOT_FOUND","MERCHANDISE_PRODUCT_NOT_PUBLISHED","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","MERCHANDISE_NOT_APPLICABLE"],xo={currency_changed:Ge.CURRENCY_CHANGE,captcha_required:Ge.CAPTCHA_REQUIRED,not_enough_stock:Ge.NOT_ENOUGH_STOCK,cart_not_ready:Ge.CART_NOT_READY,dynamic_tax:Ge.DYNAMIC_TAX,cart_throttled:null,out_of_stock:null};function pt({warnings:t,cartStatus:e}){if(e==="CartStatusNotReady")return"cart_not_ready";if(e==="CartThrottled")return"cart_throttled";if(!(!t||t.length===0)){if(t.includes("MERCHANDISE_OUT_OF_STOCK"))return"out_of_stock";if(t.includes("MERCHANDISE_NOT_ENOUGH_STOCK"))return"not_enough_stock"}}function pr({currentCartTotal:t,initialBuyerCurrency:e}){const n=t.amount;return!(!n||Number(n)===0||e.toUpperCase()===t.currencyCode.toUpperCase())}function M({checkoutUrl:t,instrumentName:e,reason:n}){if(!t)throw new Error("Invalid Checkout URL");const r=new URL(t),a=xo[n];a&&r.searchParams.set(a,"true"),g.decelerated({instrument:e,reason:n}),ie(r.toString())}class Oo extends Error{constructor(e){super("[".concat(e.name,"] ").concat(e.message)),this.stack=e.stack,this.name="HandleCreateCartError"}}async function ce({element:t,instrumentName:e,dataSource:n}){try{const r=await n.getInitialCart(e),{cart:a,errors:i,warnings:o}=r;Eo(()=>{t&&(t.disabled=!1)});const s=ur(i);if(!a&&!s)throw new Error("[".concat(e,"] Failed to create cart"));if(a&&!a.id)throw new Error("[".concat(e,"] received invalid cart"));if(a&&!a.checkoutUrl)throw new Error("[".concat(e,"] Created cart with no checkout URL"));const l=i.length===1&&i[0]===m.InvalidQuantity;if(i.length>0&&!(l||s))throw new Error("Failed to create cart: ".concat(JSON.stringify(i)));return{cart:a,warnings:o,customValidationError:s,decelerationReason:pt({warnings:o})}}catch(r){throw new Oo(r)}finally{t.disabled=!1}}class Mo extends Nt{constructor(){super(),d(this,"name",f.MoreOptions),d(this,"anchor"),d(this,"i18n"),d(this,"dataSource"),d(this,"classNames"),d(this,"setI18n"),d(this,"setDataSource"),d(this,"setClassNames"),[this.i18n,this.setI18n]=te(),[this.dataSource,this.setDataSource]=te(),[this.classNames,this.setClassNames]=te()}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}=await ce({element:this,instrumentName:f.MoreOptions,dataSource:i});if(l){Ie(a,l.message);return}if(o){M({checkoutUrl:(n=s==null?void 0:s.checkoutUrl)!=null?n:"",instrumentName:f.MoreOptions,reason:o});return}const c=this.recommendedInstrument===f.ShopPay?"skip_shop_pay":"allow_redirect";g.sheetClicked({instrument:f.MoreOptions,result:"success"}),ie((r=s==null?void 0:s.checkoutUrl)!=null?r:"",c)}catch(o){g.sheetClicked({instrument:f.MoreOptions,result:"failed"}),b.notify(o),Se(a.translate("error_dialogs.checkout.title"),a.translate("error_dialogs.checkout.generic_error"))}}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=_o,this.appendChild(r)}setAccessibilityAttributes(){this.anchor&&(this.disabled?(this.anchor.removeAttribute("href"),this.anchor.role="link"):(this.anchor.removeAttribute("role"),this.anchor.href="#"))}}var $=(t=>(t.ButtonDisplay="buttonDisplay",t.LoadInstrument="loadInstrument",t.LoadSdk="loadSDK",t.AuthorizationLatency="authorizationLatency",t))($||{});function kn(){var t,e;return!!((t=window.performance)!=null&&t.mark)&&!!((e=window.performance)!=null&&e.measure)}function Tt(t,e){return st(t,e),()=>oe(t,e)}function st(t,e){kn()&&window.performance.mark("".concat(t,"-").concat(e,"-start"))}function oe(t,e){var n,r;if(kn())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;if(l==null){b.notify(new Fr("Could not measure performance of ".concat(t," ").concat(e)),{severity:"warning"});return}return l}catch(a){a instanceof SyntaxError||b.notify(new Fr("An error occurred when attempting to measure benchmark duration ".concat(t," with context ").concat(e,": ").concat(a),{cause:a}));return}}class Fr extends Error{constructor(){super(...arguments),d(this,"name","BenchmarkError")}}function mr(t,e,n){if(We!=null&&We.length){const r=We.join(",");t.querySelectorAll(r).forEach(a=>{n===null?a.removeAttribute(e):a.setAttribute(e,n)})}}function Fo(t,e){try{const n=JSON.parse(t!=null?t:"[]");if(!(n instanceof Array))throw new Error("[".concat(e,"] invalid walletConfigs found"));return n}catch(n){throw new Error("[".concat(e,"] Error while parsing walletConfigs JSON: ").concat(n))}}function Uo(t,e){try{return t?JSON.parse(t):null}catch(n){throw new Error("[".concat(e,"] Error while parsing walletConfig JSON: ").concat(n))}}function yr(t,e){var n;const r=e==null?void 0:e.getLoadEligibility(t);return g.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 Bo(t,e){return e.filter(n=>yr(t,n))}async function Wt({walletInstrument:t,instanceNumber:e}){const n=t.getInstrumentName(),r=Tt($.LoadSdk,"".concat(n,":").concat(e));try{await t.loadWalletSDK(),g.instrumentSDKLoaded({instrument:n,measurement:r(),result:"success"})}catch(i){return b.notify(i),g.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?(g.instrumentSDKEligible({instrument:n,result:"success"}),t):(g.instrumentSDKEligible({instrument:n,reason:a.reason,result:"failed"}),null)}function Be(t,...e){try{const n=window[t];if(typeof n=="function")return new n(...e)}catch(n){}return null}class gr extends Nt{constructor(){super(),d(this,"name",null),d(this,"apiClient"),d(this,"i18n"),d(this,"policy"),d(this,"isFetchingPolicy",!1),d(this,"intersectionObserver",null),this.mountIntersectionObserver()}get shopId(){return this.getAttribute("shop-id")}get cartId(){return this.getAttribute("cart-id")}get walletConfigs(){return this.getAttribute("wallet-configs")}get recommendedWallet(){return this.getAttribute("recommended")}get fallbackWallet(){return this.getAttribute("fallback")}get variantParams(){var e;try{return JSON.parse((e=this.getAttribute("variant-params"))!=null?e:"[]")}catch(n){throw new cr({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")}triggerLoadedEvent(){document.dispatchEvent(new Event("shopify:payment_button:loaded",{bubbles:!0,cancelable:!0}))}async attributeChangedCallback(e,n,r){n!==r&&mr(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=""}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){hr(n.translate("subscriptions.cancellation_policy"),e,n.translate("subscriptions.policy_not_found"))}mountIntersectionObserver(){this.intersectionObserver=Be("IntersectionObserver",this.handleIntersection),this.intersectionObserver?this.intersectionObserver.observe(this):V({event:B.FirstVisibleNotAvailable})}handleIntersection(e,n){e.some(r=>r.isIntersecting)&&(n.disconnect(),V({event:B.FirstVisible}))}}function fr(t){var e,n;ai({shopId:(e=t.shopId)!=null?e:bn,cartId:(n=t.cartId)!=null?n:void 0,debug:t.debug})}function Ln({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=$o(o),l=Ho(o);s&&typeof l<"u"&&l.trim()!==""&&(i[s]=l)}),Object.entries(i!=null?i:{}).map(([o,s])=>({key:o,value:s}))}function kt({page:t,element:e}){const n=t==="product"?'[data-shopify="payment-button"]':'[data-shopify="dynamic-checkout-cart"]',r=Ur(e,n)||document.querySelector(n);return Ur(r,"form")}const je=Element.prototype;function Ur(t,e){if(je.matches=je.matches||je.webkitMatchesSelector||je.msMatchesSelector||je.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 $o(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 Ho(t){if(!(["radio","checkbox"].includes(t.type)&&!t.checked)&&!(t.value===""||typeof t.value>"u"))return t.value}function br(t){const e=kt({page:"product",element:t});return xn(e)}function xn(t){var e;const n=t==null?void 0:t.elements;if(!n)return null;const r=mt(n,"id");if(!r||isNaN(Number(r)))return null;const a=Number((e=mt(n,"quantity"))!=null?e:"1"),i="gid://shopify/ProductVariant/".concat(r),o=mt(n,"selling_plan"),s=o?"gid://shopify/SellingPlan/".concat(o):void 0,l=Ln({type:"properties",form:t});return{variantId:r,quantity:a,merchandiseId:i,sellingPlanId:s,lineItemProperties:l}}function Go(t){const e=t==null?void 0:t.elements;return e?!!mt(e,"selling_plan"):!1}function mt(t,e){var n;const r=t.namedItem(e);return r&&"value"in r&&(n=r.value)!=null?n:null}class On{constructor(e,n){d(this,"addToCartMutationObserver"),d(this,"addToCartForm"),d(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=xn(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:Go(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(){this.addToCartForm=kt({page:"product",element:this.element}),this.addToCartForm&&(this.addToCartButtons=[...this.addToCartForm.querySelectorAll("[type=submit]")])}}function Vo(t,e,n){try{const r=JSON.parse(t!=null?t:"{}"),a=JSON.parse(e!=null?e:JSON.stringify({name:"buy_it_now",wallet_params:{}}));if(r===null||Object.keys(r).length===0){if(!(a instanceof Object))throw new Error("[".concat(n,"] Invalid fallback wallet configs JSON"));return{recommendedWallet:null,fallbackWallet:a}}return{recommendedWallet:r,fallbackWallet:a}}catch(r){throw r instanceof SyntaxError?(g.walletConfigDeveloperError(),new cr({code:"invalid-recommended-fallback-json",message:"recommended / fallback must be valid JSON"})):new Error("[".concat(n,"] Error while parsing recommended/fallback JSON: ").concat(r))}}const zo=".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-payment-button__button{border-radius:0}#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 )}",qo='.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);min-width:150px}: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)}@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}}',jo=70;class Xe{constructor(e,n,r,a){d(this,"red"),d(this,"green"),d(this,"blue"),d(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 Xe(0,0,0,0),r.blendWith(a,n)):a.opacity>0?r=a:r=n,n=r,a=e.shift();return r}const Kt=new Xe(255,255,255,1);function Wo(t){const e=[];let n=t;for(;n.parentElement;){n=n.parentElement;const r=window.getComputedStyle(n).backgroundColor,a=Ko(r);if(r&&e.push(a),a.opacity===1)break}try{return Yo(e.reverse())}catch(r){return b.notify(new Mn("[BackgroundDetection] Failed to blend colors for element ".concat(t.outerHTML),{cause:r})),Kt}}function Ko(t){if(!t)return Kt;try{const e=t.split("(")[1].split(")")[0].replace(" ","").split(",");return new Xe(Number(e[0]),Number(e[1]),Number(e[2]),typeof e[3]>"u"?1:Number(e[3]))}catch(e){b.notify(new Mn("[BackgroundDetection] Failed to convert rgbString to array ".concat(t),{cause:e}))}return Kt}class Mn extends Error{constructor(){super(...arguments),d(this,"name","ColorProcessingError")}}class Pe extends Nt{constructor(){super(),d(this,"name",null),d(this,"i18n"),d(this,"dataSource"),d(this,"apiClient"),d(this,"classNames"),d(this,"containerInstanceNumber"),d(this,"onRendered"),d(this,"setI18n"),d(this,"setDataSource"),d(this,"setApiClient"),d(this,"setClassNames"),d(this,"setContainerInstanceNumber"),d(this,"parsedWalletParams"),this.onRendered=()=>{},[this.i18n,this.setI18n]=te(),[this.dataSource,this.setDataSource]=te(),[this.apiClient,this.setApiClient]=te(),[this.classNames,this.setClassNames]=te(),[this.containerInstanceNumber,this.setContainerInstanceNumber]=te()}async cleanupOnFailure(e,n){var r;try{await e()}catch(a){b.notify(new Qo("An error occurred requiring cleanup when attempting to render the ".concat(n," instrument: ").concat(a),{cause:a}));const i=await this.containerInstanceNumber;g.instrumentLoaded({instrumentOrComponentName:n,result:"failed",measurement:oe($.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")||S.Unknown}get buttonTheme(){return Wo(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 Error("Error while parsing wallet-params JSON: ".concat(n))}return this.parsedWalletParams}async initializeShadowStyles(e,n=""){const r=document.createElement("style");r.innerHTML=[qo,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}))}}class Qo extends Error{constructor(){super(...arguments),d(this,"name","CleanupOnFailureError")}}class Jo extends Pe{constructor(){super(...arguments),d(this,"name",f.BuyItNow),d(this,"button",null)}static get observedAttributes(){return["disabled"]}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}attributeChangedCallback(e,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}=await ce({element:this,instrumentName:this.name,dataSource:a});if(g.sheetClicked({instrument:this.name,result:"success"}),s){Ie(r,s.message);return}if(i){M({checkoutUrl:(e=o==null?void 0:o.checkoutUrl)!=null?e:"",instrumentName:this.name,reason:i});return}ie((n=o==null?void 0:o.checkoutUrl)!=null?n:"","allow_redirect")}catch(i){b.notify(i),g.sheetClicked({instrument:this.name,result:"failed"}),Se(r.translate("error_dialogs.checkout.title"),r.translate("error_dialogs.checkout.generic_error"))}}async render(){var e;this.button||(this.button=Dt());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)}}function Xo(){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}class de{constructor(e){d(this,"walletParams"),this.walletParams=e.wallet_params}static walletName(){throw new Error("Must define walletName for WalletInstrument subclass")}createWebComponent({walletContainer:e,dataSource:n,i18n:r,apiClient:a,containerInstanceNumber:i,classNames:o="",callToAction:s,pageType:l=S.ProductPage,slot:c="button",onRendered:u=()=>{}}){var h,p,y;const E=this.getWebComponentName();le(E,this.getWebComponentClass(),{isChildCustomElement:!0});const w=document.createElement(E),A={"access-token":(h=e.accessToken)!=null?h:"","buyer-country":(p=e.buyerCountry)!=null?p:"","buyer-currency":e.buyerCurrency,"wallet-params":JSON.stringify((y=this.walletParams)!=null?y:{}),"page-type":l,slot:c};try{e.disabled&&w.setAttribute("disabled",""),Rt(w,A),e.isShippingRequired&&w.setAttribute("requires-shipping",""),e.hasSellingPlan&&w.setAttribute("has-selling-plan",""),e.pciEnabled&&w.setAttribute("pci-enabled","")}catch(I){const k=I;throw k.message.includes("setAttribute is not a function")&&Xo()?new Pt(k.message):k}return s&&w.setAttribute("call-to-action",""),w.setDataSource(n),w.setApiClient(a),w.setI18n(r),w.setClassNames(o),w.setContainerInstanceNumber(i),w.onRendered=u,w}loadWalletSDK(){return Promise.resolve()}getLoadEligibility(e){return{eligible:!0}}getPartnerSDKEligibility(){return{eligible:!0}}}class Zo extends de{static walletName(){return"buy_it_now"}getWebComponentName(){return"shopify-buy-it-now-button"}getInstrumentName(){return f.BuyItNow}getWebComponentClass(){return Jo}}const es="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}",ts="::slotted(div){height:100%}";async function ke(t){const{cartClient:e,instrumentName:n}=t;try{if(!t.cartId)throw new Error("[".concat(n,"] provided no cart ID when updating buyer identity"));if(!e)throw new Error("[".concat(n,"] provided invalid cart client when updating buyer identity"));return await e.updateCartBuyerIdentity(t)}catch(r){throw g.updateFailed(n,"updateBuyerIdentity"),r}}async function wr({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 c={freePaymentMethod:{billingAddress:r}};return await a.updateCartPayment(t,_({amount:{amount:e.amount,currencyCode:e.currencyCode}},Number(e.amount)<=0&&!l&&!s?c:n),i,o)}catch(c){throw g.updateFailed(i,"updatePayment"),c}}function Fn(t){return window[Un(t)]}function Un(t){return"paypal-".concat(t.replace(/[^a-zA-Z0-9]/g,""))}function ft(t){if(!t)return null;const e=getComputedStyle(t).borderRadius;return e.includes("px")?parseInt(e,10):null}function bt(t){if(!t)return null;const e=getComputedStyle(t).height;return e.includes("px")?parseInt(e,10):null}const $t=25,Br=55,rs=["cart_not_ready","cart_throttled"];var ye;class ns extends Pe{constructor(){super(),d(this,"name",f.PayPal),d(this,"abortController"),d(this,"cartId"),d(this,"sdkButtonsComponent"),d(this,"container",null),d(this,"resizeObserver",null),d(this,"buttonHeight"),d(this,"rendering",!1),d(this,"prevBorderRadius",0),d(this,"prevHeight",0),O(this,ye),L(this,ye,this.attachShadow({mode:"closed"})),this.abortController=Be("AbortController"),this.resizeObserver=Be("ResizeObserver",()=>this.onResize())}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async disconnectedCallback(){this.innerHTML="",C(this,ye).innerHTML="",await this.teardownPayPalButton(),this.resizeObserver&&this.resizeObserver.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=ft(this.container),n=bt(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=document.createElement("div");n.className=Ce.BUTTON;const r=document.createElement("style");r.innerHTML=es,this.appendChild(r),await this.initializeShadowStyles(C(this,ye),ts),C(this,ye).appendChild(n),this.container=n,this.renderFromPayPalSDK(),(e=this.resizeObserver)==null||e.observe(this.container)}getHeight(){const e=bt(this.container);return e?e>=$t&&e<=Br?e:e<$t?(console.debug("[PayPalButton] Container height is less than the minimum height of the PayPal button. Using the minimum height of 25px."),$t):(console.debug("[PayPalButton] Container height is greater than the maximum height of the PayPal button. Using the maximum height of 55px."),Br):Ua}async renderFromPayPalSDK(){var e,n,r;if(!this.container)throw new Error("button container not set when attempting to render");this.rendering=!0;const a=()=>this.createToken(this.apiClient);let i,o;this.requiresBillingAgreement()?o=a:i=a;const s=ft(this.container),l=this.getHeight();this.prevHeight=l;const c={color:"gold",label:this.isCTA?"pay":"paypal",disableMaxWidth:!0,height:l,shape:"sharp"};s&&s>0&&(c.borderRadius=s,this.prevBorderRadius=s),this.sdkButtonsComponent=(n=(e=Fn(this.walletParams.sdkUrl))==null?void 0:e.Buttons)==null?void 0:n.call(e,{fundingSource:"paypal",style:c,createOrder:i,createBillingAgreement:o,onApprove:async u=>{await this.onApprove(u)},onCancel:()=>{var u;g.sheetCancelled(this.name),(u=this.abortController)==null||u.abort()},onClick:this.onClick.bind(this),onError:this.onError.bind(this)}),await((r=this.sdkButtonsComponent)==null?void 0:r.render(this.container)),this.rendering=!1,this.onRendered()}async onClick(e,n){var r,a;if(this.disabled)return n.reject();const i=this.getBoundingClientRect(),o=i.left+i.width/2,s=i.top+i.height/2,l=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1,clientX:o,clientY:s,screenX:window.screenX+o,screenY:window.screenY+s});this.dispatchEvent(l);const[c,u]=await Promise.all([this.dataSource,this.i18n]);try{const{decelerationReason:h,cart:p,customValidationError:y}=await ce({element:this,instrumentName:this.name,dataSource:c});if(y)return Ie(u,y.message),n.reject();const{hasManagedSellingPlanState:E}=this.walletParams;return E!=null&&E!==this.hasSellingPlan?(ie((r=p==null?void 0:p.checkoutUrl)!=null?r:""),n.reject()):h?(M({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 g.sheetClicked({instrument:this.name,result:"failed"}),b.notify(h),Se(u.translate("error_dialogs.checkout.title"),u.translate("error_dialogs.checkout.generic_error")),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 g.sheetClicked({instrument:this.name,result:"success"}),r}catch(r){throw g.sheetClicked({instrument:this.name,result:"failed"}),r}}async onApprove({orderID:e,payerID:n,billingToken:r}){var a;try{if(g.authorizationAttempt(this.name),st($.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:c,email:u,remoteOrderId:h}=await i.paypalBuyerDetailsFetch(o,this.cartId),{data:p,decelerationReason:y}=await ke({cartId:this.cartId,cartClient:i,instrumentName:this.name,emailAddress:u,streetAddress:l});if(!p)throw new Error("Cart not found");const{id:E,checkoutUrl:w,totalAmount:A}=p;if(this.shouldDecelerate(y)){M({checkoutUrl:w,instrumentName:this.name,reason:y});return}const{decelerationReason:I}=await wr({abortSignal:(a=this.abortController)==null?void 0:a.signal,cartClient:i,cartId:E,instrumentName:f.PayPal,billingAddress:s!=null?s:l,paymentMethod:{walletPaymentMethod:{paypalWalletContent:{billingAddress:s!=null?s:l,email:u,expiresAt:c,payerId:n,token:h!=null?h:e,acceptedSubscriptionTerms:!1,vaultingAgreement:!1,merchantId:this.walletParams.merchantId}}},canUsePaymentMethodForFreeOrder:!0,totalAmount:A});if(this.shouldDecelerate(I)){M({checkoutUrl:w,instrumentName:this.name,reason:I});return}if(pr({currentCartTotal:A,initialBuyerCurrency:this.buyerCurrency})){M({checkoutUrl:w,instrumentName:this.name,reason:"currency_changed"});return}g.authorizationComplete({instrument:this.name,result:"success",measurement:oe($.AuthorizationLatency,this.name)}),ie(w)}catch(i){throw g.authorizationComplete({instrument:this.name,result:"failure",measurement:oe($.AuthorizationLatency,this.name)}),i}}async onError(e){var n;if(e.message==="Window is closed, can not determine type"){g.sheetCancelled(this.name),(n=this.abortController)==null||n.abort();return}e.message==="RESTRICTED_WALLET_ACCOUNT"?g.log({body:"PayPal modal closed due to error: ".concat(e)}):b.notify(e);const r=await this.i18n,a=r.translate("brand.paypal");Q(a,r)}requiresBillingAgreement(){return this.walletParams.hasManagedSellingPlanState||this.walletParams.requiresBillingAgreement}shouldDecelerate(e){return!!(e&&rs.includes(e))}}ye=new WeakMap;const De=class wc extends de{static walletName(){return"paypal"}constructor(e){super(e)}getWebComponentName(){return"shopify-paypal-button"}getInstrumentName(){return f.PayPal}getWebComponentClass(){return ns}loadWalletSDK(){let e=wc.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",Un(this.walletParams.sdkUrl)),n.onload=()=>r(),n.onerror=i=>{wc.paypalSDKPromiseByUrl.delete(this.walletParams.sdkUrl),n&&document.body.contains(n)&&document.body.removeChild(n),a(i)},document.body.appendChild(n)}),wc.paypalSDKPromiseByUrl.set(this.walletParams.sdkUrl,e),e}getLoadEligibility(){return{eligible:!0}}getPartnerSDKEligibility(){var e,n;try{return(n=(e=Fn(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 cr({code:"paypal-sdk-eligibility-check-failed",message:"PayPal SDK 'isEligible' method failed unexpectedly: ".concat(r)})}}};d(De,"paypalSDKPromiseByUrl",new Map);let Qt=De;const as=".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}",Jt={UK:"GB",JA:"JP"},Bn=["AS","GU","MP","PR","VI"];Bn.forEach(t=>{Jt[t]="US"});function dt(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:is(t.countryCode),phone:t.phoneNumber||void 0};return a.country==="HK"&&(a.zip=void 0,a.province=t.postalCode),r&&Bn.includes(r)&&(a.province=r),a.lastName||(a.lastName=a.firstName),a}function is(t){if(!t)return"ZZ";const e=t.toUpperCase();return Object.keys(Jt).includes(e)?Jt[e]:e}function os(t,e){return t.map(n=>{const{title:r,deliveryPromise:a}=cs(n,e);return{title:r,estimatedCost:{amount:ls(n),currencyCode:n[0].estimatedCost.currencyCode},handle:Hn(n),deliveryPromise:a}})}function ss(t,e){return t.map(n=>{const{title:r,description:a}=ds(n,e);return{title:r,description:a,handle:Hn(n)}})}function $n({deliveryGroups:t}){return t.map(e=>e.deliveryOptions.filter(({deliveryMethodType:n})=>n==="SHIPPING").map(n=>T(_({},n),{groupType:e.groupType}))).reduce((e,n)=>e.flatMap(r=>n.map(a=>[...r,a])),[[]])}function ls(t){return t.reduce((e,n)=>e+Number(n.estimatedCost.amount),0).toFixed(2)}function cs(t,e){const n=t.find(l=>l.groupType===Ae.OneTimePurchase),r=t.find(l=>l.groupType===Ae.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 ds(t,e){const n=t.find(o=>o.groupType===Ae.OneTimePurchase),r=t.find(o=>o.groupType===Ae.Subscription),a=t.map(us).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 us(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 Hn(t){return t.map(e=>e.handle).join(",")}function Gn({deliveryGroups:t,i18n:e}){const n=t.some(r=>r.groupType===Ae.Subscription);return t.map(r=>{var a;let i=e.translate("order_summary.shipping");return n&&(i=r.groupType===Ae.Subscription?e.translate("order_summary.shipping_subscription"):e.translate("order_summary.shipping_one_time_purchase")),{label:i,amount:Ee(((a=r.selectedDeliveryOption)==null?void 0:a.estimatedCost.amount)||0)}})}function hs(t,e){return Qe({label:t,possibleLines:[e]})[0]}function ps({subtotal:t,deliveryGroups:e,duties:n,taxes:r,discountAllocations:a,i18n:i,formattedRecurringTotals:o}){var s;const l=Qe({label:i.translate("order_summary.subtotal"),possibleLines:[t]}),c=Gn({deliveryGroups:e,i18n:i}),u=Qe({label:i.translate("order_summary.duties"),possibleLines:[n]}),h=Qe({label:i.translate("order_summary.taxes"),possibleLines:[r]}),p=o.map(w=>({label:w,amount:"0.00",type:"pending"})),y=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(w=>{var A;const I=(A=w.title)!=null?A:w.code;return Qe({label:I!=null?I:i.translate("order_summary.discount"),possibleLines:[w.discountedAmount],isDiscount:!0})}))!=null?s:[];return[...l,...c,...u,...h,...E,...p,...y]}function Qe({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(Ee(r.amount)):Ee(r.amount)}))}function ms(t,e){if(!t.length)return[];const n=$n({deliveryGroups:t});return os(n,e).map(r=>{var a;return{label:r.title||"",amount:r.estimatedCost.amount,identifier:r.handle,detail:(a=r.deliveryPromise)!=null?a:""}})}const Ht=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,'"'))}},ys=["decelerate","abort","show_error","complete","update"];class wt extends Error{constructor(){super(...arguments),d(this,"name","UnhandledActionError")}}class Vn{constructor(){d(this,"generatePrioritizedPaymentSheetAction",(e,n)=>{let r;const a=[],i=[],o=[],s=n.filter(c=>c!==m.UnacceptablePaymentsAmount).some(c=>e[c]!==void 0);for(const c of Object.keys(e))if(!(c===m.UnacceptablePaymentsAmount&&s)){const u=e[c]();u.effects&&i.push(...u.effects),u.action!=="complete"&&u.errors&&o.push(...u.errors),a.push(u)}const l=(c=>ys.map(u=>c.find(h=>h.action===u)).find(u=>!!u))(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 a?((i=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.data)==null?void 0:s.__typename," response, aborting")))}]}:{action:"abort"}}}class gs extends Vn{constructor(e){super(),d(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(c=>{b.notify(new wt("[".concat(f.ApplePay,"] mutation result error not handled: ").concat(c)))}),((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"}:{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 Error("[".concat(f.ApplePay,"] completion result error not handled: ").concat(s)))});const{prioritizedPaymentSheetAction:o}=this.getMergedPaymentSheetAction({result:e,errorActions:a});return o||{action:"abort"}}default:throw new Error("[".concat(f.ApplePay,"] unknown completion result type: ").concat(e.data.__typename))}}getErrorActions({shippingCountryCode:e}){return[{errors:[m.CaptchaCompletionRequired],generateAction:()=>this.decelerateOrAbort({reason:"captcha_required",instrumentName:f.ApplePay,errorOrWarning:m.CaptchaCompletionRequired,result:this.completionResult})},{errors:[m.InvalidLanguage],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.ApplePay,"] mutation provided invalid language, aborting")))}]})},{errors:[m.InvalidCountry],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.ApplePay,"] mutation provided invalid country, aborting")))}]})},{errors:[m.MissingCartId],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.ApplePay,"] mutation provided invalid cart ID, aborting")))}]})},{errors:Nn,generateAction:()=>this.decelerateOrAbort({reason:"dynamic_tax",instrumentName:f.ApplePay,errorOrWarning:m.NewTaxMustBeAccepted,result:this.completionResult})},{errors:Rn,generateAction:()=>({action:"abort"})},{errors:[m.MerchandiseNotEnoughStock],generateAction:()=>this.decelerateOrAbort({reason:"not_enough_stock",instrumentName:f.ApplePay,errorOrWarning:m.MerchandiseNotEnoughStock,result:this.completionResult})},{errors:Tn,generateAction:()=>this.decelerateOrAbort({reason:"out_of_stock",instrumentName:f.ApplePay,errorOrWarning:m.MerchandiseOutOfStock,result:this.completionResult})},{errors:Dn,generateAction:()=>({action:"show_error",errors:[new ApplePayError("addressUnserviceable")]})},{errors:[m.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","emailAddress",this.i18n.translate("errors.missing.email"))]})},{errors:Ao,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.missing.first_name"))]})},{errors:Co,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.invalid.first_name"))]})},{errors:So,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.missing.last_name"))]})},{errors:Io,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.invalid.last_name"))]})},{errors:Po,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.missing.address1"))]})},{errors:[m.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address1"))]})},{errors:vo,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.missing.address2"))]})},{errors:[m.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.invalid.address2"))]})},{errors:Do,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.missing.city"))]})},{errors:[m.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.invalid.city"))]})},{errors:[m.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.missing.zone"),this.i18n.translate("errors.missing.emirate"),"shippingContactInvalid",e)]})},{errors:[m.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.i18n.translate("errors.invalid.zone"),this.i18n.translate("errors.invalid.emirate"),"shippingContactInvalid",e)]})},{errors:Ro,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.missing.postal_code"))]})},{errors:vn,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.invalid.postal_code"))]})},{errors:[m.DeliveryCountryRequired],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","country",this.i18n.translate("errors.missing.country"))]})},{errors:No,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.missing.phone"))]})},{errors:ko,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","phoneNumber",this.i18n.translate("errors.invalid.phone"))]})},{errors:To,generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","country",this.i18n.translate("errors.invalid.country"))]})},{errors:Lo,generateAction:()=>({action:"show_error",errors:[new ApplePayError("billingContactInvalid")]})},{errors:[m.UnsupportedApplePayPaymentMethod],generateAction:()=>({action:"abort",effects:[()=>{Q(this.i18n.translate("brand.apple_pay"),this.i18n)},()=>{b.notify(new wt("[".concat(f.ApplePay,"] payment method is not supported")))}]})},{errors:[m.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.emojis.last_name"))]})},{errors:[m.DeliveryFirstNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.emojis.first_name"))]})},{errors:[m.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.too_long.address1"))]})},{errors:[m.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.too_long.address2"))]})},{errors:[m.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.too_long.first_name"))]})},{errors:[m.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.too_long.last_name"))]})},{errors:[m.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.too_long.city"))]})},{errors:[m.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.url.first_name"))]})},{errors:[m.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.url.last_name"))]})},{errors:[m.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address1"))]})},{errors:[m.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.html_tags.address2"))]})},{errors:[m.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.html_tags.city"))]})},{errors:[m.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.html_tags.first_name"))]})},{errors:[m.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","name",this.i18n.translate("errors.html_tags.last_name"))]})},{errors:[m.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","locality",this.i18n.translate("errors.emojis.city"))]})},{errors:[m.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address1"))]})},{errors:[m.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","addressLines",this.i18n.translate("errors.emojis.address2"))]})},{errors:[m.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.i18n.translate("errors.emojis.postal_code"))]})},{errors:[m.BuyerIdentityEmailInvalid],generateAction:()=>({action:"show_error",errors:[new ApplePayError("shippingContactInvalid","emailAddress",this.i18n.translate("errors.invalid.email"))]})},{errors:[m.DiscountNotApplicable],generateAction:()=>({action:"show_error",errors:[new ApplePayError("couponCodeInvalid",void 0,this.i18n.translate("errors.invalid.discount"))]})}]}mapCustomValidationFunctionErrorToAction(e){const n=ur(e);return n?{action:"abort",effects:[()=>{const r=this.i18n.translate("brand.apple_pay");hr(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 $r=["name","postalAddress"];function fs({shippingRequired:t,walletParams:e,buyerCurrency:n}){const{phoneRequired:r,emailRequired:a}=e,i=[...a?["email"]:[],...r?["phone"]:[]],o=t?[...$r,...i]:i;return{countryCode:e.countryCode,currencyCode:n,merchantCapabilities:e.merchantCapabilities,supportedNetworks:e.supportedNetworks,total:{type:"pending",label:e.merchantName,amount:"1.00"},requiredBillingContactFields:$r,requiredShippingContactFields:o,shippingType:e.shippingType}}const bs=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]},zn=t=>{const e=t.lineItems.reduce((n,r)=>n+Number(r.subtotalAmount.amount),0);return{amount:String(e),currencyCode:t.totalAmount.currencyCode}};function ws(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=_s({billingPolicy:a.billingPolicy,i18n:e});if(i.length===0){const l=ut({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=ut({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=ut({price:Number(i[0].price.amount)*o,currencyCode:i[0].price.currencyCode,locale:e.locale}),c=ut({price:Number(i[1].price.amount)*o,currencyCode:i[1].price.currencyCode,locale:e.locale}),u=a.priceAdjustments[0].orderCount;return[...n,e.translate("order_summary.subscriptions.recurring_totals_with_policies",{count:u,fixedPrice:l,recurringPrice:c,interval:s})]}return n},[])}function ut({price:t,currencyCode:e,locale:n}){return Intl.NumberFormat(n,{style:"currency",currency:e,currencyDisplay:"narrowSymbol"}).format(t)}function _s({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})}const Lt="GraphQL Client",Hr=0,Gr=3,qn="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",jn="Response returned unexpected Content-Type:",Yn="An unknown error has occurred. The API did not return a data object or any errors in its response.",Xt={json:"application/json",multipart:"multipart/mixed"},Vr="X-SDK-Variant",zr="X-SDK-Version",Es="shopify-graphql-client",As="1.2.2",Wn=1e3,Cs=[429,503],Kn=/@(defer)\b/i,qr="\r\n",Ss=/boundary="?([^=";]+)"?/i,jr=qr+qr;function ae(t,e=Lt){return t.startsWith("".concat(e))?t:"".concat(e,": ").concat(t)}function $e(t){return t instanceof Error?t.message:JSON.stringify(t)}function Qn(t){return t instanceof Error&&t.cause?t.cause:void 0}function Jn(t){return t.flatMap(({errors:e})=>e!=null?e:[])}function Xn({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||eGr))throw new Error("".concat(t,': The provided "retries" value (').concat(e,") is invalid - it cannot be less than ").concat(Hr," or greater than ").concat(Gr))}function G(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}function Zn(t,e){if(t.length===0)return e;const n={[t.pop()]:e};return t.length===0?n:Zn(t,n)}function ea(t,e){return Object.keys(e||{}).reduce((n,r)=>(typeof e[r]=="object"||Array.isArray(e[r]))&&t[r]?(n[r]=ea(t[r],e[r]),n):(n[r]=e[r],n),Array.isArray(t)?[...t]:_({},t))}function ta([t,...e]){return e.reduce(ea,_({},t))}function Is({clientLogger:t,customFetchApi:e=fetch,client:n=Lt,defaultRetryWaitTime:r=Wn,retriableCodes:a=Cs}){const i=async(o,s,l)=>{const c=s+1,u=l+1;let h;try{if(h=await e(...o),t({type:"HTTP-Response",content:{requestParams:o,response:h}}),!h.ok&&a.includes(h.status)&&c<=u)throw new Error;return h}catch(p){if(c<=u){const y=h==null?void 0:h.headers.get("Retry-After");return await Ps(y?parseInt(y,10):r),t({type:"HTTP-Retry",content:{requestParams:o,lastResponse:h,retryAttempt:s,maxRetries:l}}),i(o,c,l)}throw new Error(ae("".concat(l>0?"Attempted maximum number of ".concat(l," network retries. Last message - "):"").concat($e(p)),n))}};return i}async function Ps(t){return new Promise(e=>setTimeout(e,t))}function vs({headers:t,url:e,customFetchApi:n=fetch,retries:r=0,logger:a}){Xn({client:Lt,retries:r});const i={headers:t,url:e,retries:r},o=Ds(a),s=Is({customFetchApi:n,clientLogger:o,defaultRetryWaitTime:Wn}),l=Rs(s,i),c=Ns(l),u=Fs(l);return{config:i,fetch:l,request:c,requestStream:u}}function Ds(t){return e=>{t&&t(e)}}async function ra(t){const{errors:e,data:n,extensions:r}=await t.json();return _(T(_(_({},G("data",n)),G("extensions",r)),{headers:t.headers}),e||!n?{errors:T(_({networkStatusCode:t.status,message:ae(e?qn:Yn)},G("graphQLErrors",e)),{response:t})}:{})}function Rs(t,{url:e,headers:n,retries:r}){return async(a,i={})=>{const{variables:o,headers:s,url:l,retries:c,signal:u}=i,h=JSON.stringify({query:a,variables:o});Xn({client:Lt,retries:c});const p=Object.entries(_(_({},n),s)).reduce((E,[w,A])=>(E[w]=Array.isArray(A)?A.join(", "):A.toString(),E),{});!p[Vr]&&!p[zr]&&(p[Vr]=Es,p[zr]=As);const y=[l!=null?l:e,{method:"POST",headers:p,body:h,signal:u}];return t(y,1,c!=null?c:r)}}function Ns(t){return async(...e)=>{if(Kn.test(e[0]))throw new Error(ae("This operation will result in a streamable response - use requestStream() instead."));try{const n=await t(...e),{status:r,statusText:a}=n,i=n.headers.get("content-type")||"";return n.ok?i.includes(Xt.json)?ra(n):{errors:{networkStatusCode:r,message:ae("".concat(jn," ").concat(i)),response:n}}:{errors:{networkStatusCode:r,message:ae(a),response:n}}}catch(n){return{errors:{message:$e(n)}}}}}function Ts(t){return ve(this,null,function*(){const e=new TextDecoder;if(t.body[Symbol.asyncIterator])try{for(var n=X(t.body),r,a,i;r=!(a=yield new J(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 J(a.call(n)))}finally{if(i)throw i[0]}}else{const o=t.body.getReader();let s;try{for(;!(s=yield new J(o.read())).done;)yield e.decode(s.value)}finally{o.cancel()}}})}function ks(t,e){return{[Symbol.asyncIterator](){return ve(this,null,function*(){try{let o="";try{for(var n=X(t),r,a,i;r=!(a=yield new J(n.next())).done;r=!1){const s=a.value;if(o+=s,o.indexOf(e)>-1){const l=o.lastIndexOf(e),c=o.slice(0,l).split(e).filter(u=>u.trim().length>0).map(u=>u.slice(u.indexOf(jr)+jr.length).trim());c.length>0&&(yield c),o=o.slice(l+e.length),o.trim()==="--"&&(o="")}}}catch(s){i=[s]}finally{try{r&&(a=n.return)&&(yield new J(a.call(n)))}finally{if(i)throw i[0]}}}catch(o){throw new Error("Error occured while processing stream payload - ".concat($e(o)))}})}}}function Ls(t){return{[Symbol.asyncIterator](){return ve(this,null,function*(){const e=yield new J(ra(t));yield T(_({},e),{hasNext:!1})})}}}function xs(t){return t.map(e=>{try{return JSON.parse(e)}catch(n){throw new Error("Error in parsing multipart response - ".concat($e(n)))}}).map(e=>{const{data:n,incremental:r,hasNext:a,extensions:i,errors:o}=e;if(!r)return T(_(_({data:n||{}},G("errors",o)),G("extensions",i)),{hasNext:a});const s=r.map(({data:l,path:c,errors:u})=>_({data:l&&c?Zn(c,l):{}},G("errors",u)));return T(_({data:s.length===1?s[0].data:ta([...s.map(({data:l})=>l)])},G("errors",Jn(s))),{hasNext:a})})}function Os(t,e){if(t.length>0)throw new Error(qn,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(Yn)}function Ms(t,e){var n,r;const a=(e!=null?e:"").match(Ss),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=Ts(t);let s={},l;return{[Symbol.asyncIterator](){return ve(this,null,function*(){var c,u;try{let w=!0;try{for(var h=X(ks(o,i)),p,y,E;p=!(y=yield new J(h.next())).done;p=!1){const A=y.value,I=xs(A);l=(u=(c=I.find(U=>U.extensions))==null?void 0:c.extensions)!=null?u:l;const k=Jn(I);s=ta([s,...I.map(({data:U})=>U)]),w=I.slice(-1)[0].hasNext,Os(k,s),yield T(_(_({},G("data",s)),G("extensions",l)),{hasNext:w})}}catch(A){E=[A]}finally{try{p&&(y=h.return)&&(yield new J(y.call(h)))}finally{if(E)throw E[0]}}if(w)throw new Error("Response stream terminated unexpectedly")}catch(w){const A=Qn(w);yield T(_(_({},G("data",s)),G("extensions",l)),{errors:T(_({message:ae($e(w)),networkStatusCode:t.status},G("graphQLErrors",A==null?void 0:A.graphQLErrors)),{response:t}),hasNext:!1})}})}}}function Fs(t){return async(...e)=>{if(!Kn.test(e[0]))throw new Error(ae("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(Xt.json):return Ls(n);case a.includes(Xt.multipart):return Ms(n,a);default:throw new Error("".concat(jn," ").concat(a),{cause:n})}}catch(n){return{[Symbol.asyncIterator](){return ve(this,null,function*(){const r=Qn(n);yield{errors:_(_({message:ae($e(n))},G("networkStatusCode",r==null?void 0:r.status)),G("response",r)),hasNext:!1}})}}}}}const Us="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}}}}}",Bs="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}",$s="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}",Hs="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}",Gs="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}",Vs="mutation applePaySessionCreate($validationUrl:URL!){applePaySessionCreate(validationUrl:$validationUrl){...@defer{applePaySession{body}}}}",zs="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}}}}}}",qs="mutation PayPalTokenCreate($cartId:ID!){paypalTokenCreate(cartId:$cartId){...@defer{paypalToken{token}}}}",js="query cartQuery($id:ID!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false)@inContext(country:$country language:$language){cart(id:$id){...@defer(if:$withCarrierRates){...CartParts}}}",Ys="query subscriptionPolicyQuery($country:CountryCode$language:LanguageCode)@inContext(country:$country language:$language){shop{subscriptionPolicy(sanitized:true){body}}}",Ws="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}",ht="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}}}}}}",Yr="fragment CartErrorParts on CartUserError{message field code}",Wr="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}}}}",Ks="mutation prepareCart($cartId:ID!$country:CountryCode$language:LanguageCode$withCarrierRates:Boolean=false$prepareCart:Boolean=true)@inContext(country:$country language:$language){...PreparedCartFragment}",Qs="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}}}}",Js="unstable",Kr="RESTRICTED_WALLET_ACCOUNT";class me extends Error{constructor(e="No response"){super(e),this.name="NoResponseError"}}class xt{constructor({accessToken:e,country:n,locale:r,apiVersion:a=Js,withCarrierRates:i=!1,cartPrepareMigrationEnabled:o=!1}){if(d(this,"OPERATION_NAME_REGEX",/[^ ]+ (\w+)/),d(this,"client"),d(this,"country"),d(this,"url"),d(this,"locale"),d(this,"withCarrierRates"),d(this,"lastValidCart"),d(this,"cartPrepareMigrationEnabled"),!e)throw new Error("StorefrontApiClient constructed with no access token");if(!n)throw new Error("StorefrontApiClient constructed with no buyer country");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=vs({headers:{"Content-Type":"application/json",Accept:"application/json","X-Shopify-Storefront-Access-Token":e,"X-SDK-Variant":"portable-wallets"},url:this.url,retries:0,logger:s=>{if(s.type==="HTTP-Response"){const[l,c]=s.content.requestParams;b.leaveBreadcrumb("POST: ".concat(l),{statusCode:s.content.response.status,statusText:s.content.response.statusText,url:l,method:c==null?void 0:c.method,headers:c==null?void 0:c.headers,body:c==null?void 0:c.body},"request")}}})}async createCart(e){var n,r,a;const i=await this.requestStream([Us,ht],{input:{lines:[{merchandiseId:e.merchandiseId,quantity:e.quantity,sellingPlanId:e.sellingPlanId,attributes:e.lineItemProperties}],discountCodes:e.discountCodes,buyerIdentity:e.buyerIdentity},country:this.country,language:this.formatLanguage(this.locale)},{instrumentName:e.instrumentName,startingCheckout:!0});try{for(var o=X(i),s,l,c;s=!(l=await o.next()).done;s=!1){const u=l.value;u.errors&&this.onError(u.errors);const h=(n=u.data)==null?void 0:n.result;if(h&&!u.hasNext){h.errors&&this.onResultError(h.errors);const p=this.parseMutationWarnings((a=(r=u.data)==null?void 0:r.result)==null?void 0:a.warnings);return{data:h.cart?this.parseCartResponse(h.cart):null,errors:this.parseMutationErrors(u,"result"),warnings:p,decelerationReason:pt({warnings:p})}}}}catch(u){c=[u]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(c)throw c[0]}}throw new me("Cart create operation returned no response")}async updateCartBillingAddress(e){const{cartId:n,billingAddress:r,instrumentName:a}=e;return this.requestDeferredCart($s,{cartId:n,billingAddress:r},{instrumentName:a})}async updateCartBuyerIdentity(e,n){const{cartId:r,instrumentName:a}=e;return this.requestDeferredCart(Hs,{cartId:r,buyerIdentity:Zs(e)},{instrumentName:a,abortSignal:n})}async updateSelectedDeliveryOptions(e,n,r,a){let i=n;const o=Ke()+2e4;for(;Ke()typeof c=="string"&&c.startsWith(m.PendingDeliveryGroups))))return s;const l=s.data.deliveryGroups.flatMap(c=>c.deliveryOptions.map(u=>({deliveryOptionHandle:u.handle,deliveryGroupId:c.id})));i=i.map(c=>{var u;return(u=l.find(h=>h.deliveryOptionHandle===c.deliveryOptionHandle))!=null?u:c})}throw new Error("Selected delivery options update operation timed out")}async applePaySessionCreate(e){var n,r,a;const i=await this.requestStream([Vs],{validationUrl:e.toString()},{instrumentName:f.ApplePay});try{for(var o=X(i),s,l,c;s=!(l=await o.next()).done;s=!1){const u=l.value;u.errors&&this.onError(u.errors);const h=(a=(r=(n=u.data)==null?void 0:n.applePaySessionCreate)==null?void 0:r.applePaySession)==null?void 0:a.body;if(h)return h}}catch(u){c=[u]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(c)throw c[0]}}throw new me("Apple Pay session create operation returned no response")}async paypalBuyerDetailsFetch(e,n){var r,a;const i=await this.requestStream([zs],{token:e,cartId:n},{instrumentName:f.PayPal});try{for(var o=X(i),s,l,c;s=!(l=await o.next()).done;s=!1){const u=l.value;if(u.hasNext)continue;u.errors&&this.onError(u.errors);const h=(a=(r=u.data)==null?void 0:r.paypalBuyerDetailsFetch)==null?void 0:a.paypalDetails;if(h)return h}}catch(u){c=[u]}finally{try{s&&(l=o.return)&&await l.call(o)}finally{if(c)throw c[0]}}throw new me("PayPal buyer details fetch operation returned no response")}async paypalTokenCreate(e){var n,r,a,i;const o=await this.requestStream([qs],{cartId:e},{instrumentName:f.PayPal});try{for(var s=X(o),l,c,u;l=!(c=await s.next()).done;l=!1){const h=c.value;if(h.errors){if((n=h.errors.graphQLErrors)!=null&&n.find(y=>{var E;return((E=y.extensions)==null?void 0:E.code)===Kr}))throw new Pt(Kr);this.onError(h.errors)}const p=(i=(a=(r=h.data)==null?void 0:r.paypalTokenCreate)==null?void 0:a.paypalToken)==null?void 0:i.token;if(p)return p}}catch(h){u=[h]}finally{try{l&&(c=s.return)&&await c.call(s)}finally{if(u)throw u[0]}}throw new me("PayPal token create operation returned no response")}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?Ks:js,l=this.cartPrepareMigrationEnabled?[ht,Yr,Wr]:[ht],c=this.cartPrepareMigrationEnabled?{cartId:e,country:this.country,language:i,withCarrierRates:this.withCarrierRates,prepareCart:!0}:{id:e,country:this.country,language:i,withCarrierRates:this.withCarrierRates},u=await this.requestStream([s,...l],c,{instrumentName:r,startingCheckout:n});try{for(var h=X(u),p,y,E;p=!(y=await h.next()).done;p=!1){const w=y.value;w.errors&&this.onError(w.errors);let A=null,I;if(!w.data)throw new me("".concat(o," operation returned no data in response"));if(Xs(w.data)){const k=w.data.preparedCart;A=(a=k==null?void 0:k.result)==null?void 0:a.cart,I=this.parsePreparedCartMutationErrors(w.errors,this.extractPreparedCartMutationErrors(k))}else A=w.data.cart;if(b.leaveBreadcrumb("".concat(o," response"),{body:A,errors:I,hasNext:w.hasNext},"log"),A&&!w.hasNext){const k=this.parseCartResponse(A);return this.lastValidCart=k,k}}}catch(w){E=[w]}finally{try{p&&(y=h.return)&&await y.call(h)}finally{if(E)throw E[0]}}throw new me("".concat(o," operation returned no response"))}async updateCartPayment(e,n,r,a){var i,o;const s={cartId:e,input:n},{amount:l,currencyCode:c}=n.amount;let u;const h=Ke()+1e4;for(;Ke()setTimeout(y,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===c?p:u}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(Bs,i,{instrumentName:r,startingCheckout:a})}async submitForCompletion(e,n,r){var a,i;const o=this.formatLanguage(this.locale),s=await this.request([Qs],{cartId:e,attemptToken:n,country:this.country,language:o,withCarrierRates:this.withCarrierRates},{instrumentName:r});return{data:(i=(a=s.data)==null?void 0:a.cartSubmitForCompletion)==null?void 0:i.result,errors:this.parseCompletionErrors(s)}}async fetchSubscriptionPolicy(){var e,n;const{data:r}=await this.request([Ys],{country:this.country,language:this.formatLanguage(this.locale)},{});return(n=(e=r==null?void 0:r.shop)==null?void 0:e.subscriptionPolicy)==null?void 0:n.body}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:Qr(r),url:this.generateURLWithOperationName(e[0])})}async requestStream(e,n,r){return this.client.requestStream(e.join(""),{variables:n,headers:Qr(r),url:this.generateURLWithOperationName(e[0]),signal:r.abortSignal})}async requestDeferredCart(e,n,r){var a,i,o,s,l,c,u,h,p;const y=this.formatLanguage(this.locale),E=await this.requestStream([e,ht,Yr,Wr],T(_({},n),{country:this.country,language:y,withCarrierRates:this.withCarrierRates,prepareCart:this.cartPrepareMigrationEnabled}),r);try{for(var w=X(E),A,I,k;A=!(I=await w.next()).done;A=!1){const U=I.value;U.errors&&this.onError(U.errors);const He=this.extractMutationErrors(U),D=(i=(a=U.data)==null?void 0:a.preparedCart)==null?void 0:i.result,H=(l=(s=(o=U.data)==null?void 0:o.result)==null?void 0:s.cart)!=null?l:D==null?void 0:D.cart;if(H&&!U.hasNext){let F;this.cartPrepareMigrationEnabled||(F=await this.fetchCart({id:H.id,instrumentName:r.instrumentName,startingCheckout:!1}));const N=this.parseMutationWarnings((u=(c=U.data)==null?void 0:c.result)==null?void 0:u.warnings);return{data:F!=null?F:this.parseCartResponse(H),errors:this.parsePreparedCartMutationErrors(U.errors,He),warnings:N,decelerationReason:pt({warnings:N,cartStatus:D==null?void 0:D.__typename})}}if(this.lastValidCart&&He.length>0){this.onResultError(He);const F=this.parseMutationWarnings((p=(h=U.data)==null?void 0:h.result)==null?void 0:p.warnings);return{data:this.lastValidCart,errors:this.parsePreparedCartMutationErrors(U.errors,He),warnings:F,decelerationReason:pt({warnings:F})}}}}catch(U){k=[U]}finally{try{A&&(I=w.return)&&await I.call(w)}finally{if(k)throw k[0]}}throw new me("Deferred cart operation returned no response")}onError(e){var n,r;if(!e)return;b.leaveBreadcrumb("GraphQL response error",e,"error");const a=(r=(n=e.graphQLErrors)==null?void 0:n.map(s=>s.message).join(", "))!=null?r:"",i="".concat(e.message).concat(a.length>0?" - ".concat(a):""),o=e!=null&&e.networkStatusCode?"with status ".concat(e.networkStatusCode," => ").concat(i):"=> ".concat(i);throw new Error("GraphQL mutation failed ".concat(o))}onResultError(e){b.leaveBreadcrumb("GraphQL result error",e,"error")}formatLanguage(e){return e.includes("-")?e.split("-")[0].toUpperCase():e.toUpperCase()}parseCartResponse(e){var n,r,a;const i=e.lines.edges.map(s=>{var l,c;const u=s.node;return{quantity:u.quantity,totalAmount:{amount:u.cost.totalAmount.amount,currencyCode:u.cost.totalAmount.currencyCode},subtotalAmount:{amount:(l=u.cost.subtotalAmount)==null?void 0:l.amount,currencyCode:(c=u.cost.subtotalAmount)==null?void 0:c.currencyCode},merchandise:{requiresShipping:u.merchandise.requiresShipping},discountAllocations:u.discountAllocations,sellingPlanAllocation:u.sellingPlanAllocation}}),o=e.deliveryGroups.edges.map(s=>s.node);return{id:e.id,totalAmount:e.cost.totalAmount,subtotalAmount:(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===yt?{code:yt,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(c=>c))||[],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)}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(c=>c.code))!=null?i:[]);const l=[...o,...s];return b.leaveBreadcrumb("GraphQL errors on completion",l,"error"),l}}function Xs(t){return!("cart"in t)}function Zs({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 Qr({instrumentName:t,startingCheckout:e}){const n={};return t&&(n["X-Wallet-Name"]="".concat(t)),e&&(n["X-Start-Wallet-Checkout"]="".concat(e)),n}async function na({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 g.updateFailed(n,"updateSelectedDeliveryOptions"),i}}async function aa({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 g.updateFailed(r,"submitForCompletion"),a}}function ia({selectedDeliveryOptionHandles:t,deliveryGroups:e,instrumentName:n}){return e.map(r=>{const a=r.deliveryOptions.filter(i=>t.includes(i.handle));if(!a.length)throw new Error("[".concat(n,"] could not find delivery option for group: ").concat(r.id));if(a.length>1)throw new Error("[".concat(n,"] found multiple delivery options with selectedDeliverOptionHandle in group: ").concat(r.id));return{deliveryGroupId:r.id,deliveryOptionHandle:a[0].handle}})}async function el(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 g.updateFailed(n,"updateBillingAddress"),r}}const tl=["cart_not_ready","cart_throttled"];class rl{constructor({accessToken:e,buyerCountry:n,buyerCurrency:r,button:a,i18n:i,merchantName:o,dataSource:s,apiClient:l,walletParams:c}){d(this,"name",f.ApplePay),d(this,"accessToken"),d(this,"button"),d(this,"buyerCountry"),d(this,"cart"),d(this,"apiClient"),d(this,"dataSource"),d(this,"i18n"),d(this,"merchantName"),d(this,"session"),d(this,"paymentSheetActionGenerator"),d(this,"cancelled"),d(this,"buyerCurrency"),d(this,"customerAccountEmail"),d(this,"abortController",null),d(this,"onvalidatemerchant",async u=>{var h,p,y;try{const E=new URL(u.validationURL),w=this.getMerchantSession(E),{cart:A,decelerationReason:I,customValidationError:k}=await ce({element:this.button,instrumentName:this.name,dataSource:this.dataSource});if(k){this.session.abort(),(h=this.abortController)==null||h.abort(),Ie(this.i18n,k.message);return}this.cart=A;const U=await w;if(b.leaveBreadcrumb("ApplePay Session completeMerchantValidation",{session:U},"log"),I){this.session.abort(),(p=this.abortController)==null||p.abort(),M({checkoutUrl:(y=A==null?void 0:A.checkoutUrl)!=null?y:"",instrumentName:this.name,reason:I});return}if(this.sessionIsCancelled())return;this.session.completeMerchantValidation(U)}catch(E){g.sheetClicked({instrument:f.ApplePay,result:"failed"}),this.terminateSession(E)}}),d(this,"onshippingcontactselected",async u=>{try{const h=dt(u.shippingContact),p=await ke({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(this.shouldDecelerate(p))return;await this.applyPaymentSheetActions(p,y=>this.completeShippingContactSelection(p.data,y),{shippingRequired:this.isShippingRequired,shippingCountryCode:h.country})}catch(h){this.terminateSession(h)}}),d(this,"onshippingmethodselected",async u=>{var h;try{const p=u.shippingMethod.identifier.split(","),y=ia({selectedDeliveryOptionHandles:p,deliveryGroups:this.cart.deliveryGroups,instrumentName:this.name}),E=await na({cartId:this.cart.id,cartClient:this.apiClient,instrumentName:this.name,selectedDeliveryOptions:y,abortSignal:(h=this.abortController)==null?void 0:h.signal});await this.applyPaymentSheetActions(E,()=>this.completeShippingMethodSelection(E.data),{shippingRequired:this.isShippingRequired,shippingCountryCode:void 0})}catch(p){this.terminateSession(p)}}),d(this,"onpaymentmethodselected",async u=>{try{const{billingContact:h}=u.paymentMethod;if(!this.isShippingRequired&&h){const E=dt(h),w=await ke({cartId:this.cart.id,countryCode:E.country,cartClient:this.apiClient,instrumentName:this.name});if(!w.data)throw new Error("Missing cart during Apple Pay Session creation");if(this.shouldDecelerate(w))return;await this.applyPaymentSheetActions(w,()=>this.cart=w.data,{shippingRequired:this.isShippingRequired,shippingCountryCode:E.country});const A=await el({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:y}=this.getNewTotalAndLineItems(this.cart);if(b.leaveBreadcrumb("ApplePay Session completePaymentMethodSelection",{newTotal:p,newLineItems:y},"log"),this.sessionIsCancelled())return;this.session.completePaymentMethodSelection({newTotal:p,newLineItems:y})}catch(h){this.terminateSession(h)}}),d(this,"oncancel",()=>{var u;this.cancelled=!0,g.sheetCancelled(this.name),this.button.disabled=!1,(u=this.abortController)==null||u.abort()}),d(this,"onpaymentauthorized",async u=>{g.authorizationAttempt(this.name),st($.AuthorizationLatency,this.name);const h=D=>{g.authorizationComplete({instrument:this.name,measurement:oe($.AuthorizationLatency,this.name),result:"failure"}),this.terminateSession(D)},p=async D=>{var H,F;switch((H=D.effects)==null||H.forEach(N=>N()),D.action){case"complete":{const N=ApplePaySession.STATUS_SUCCESS;try{await this.completePayment(N),ie(D.redirectUrl)}catch(ee){h(ee)}break}case"show_error":{const N=(F=D.errors)!=null?F:[];try{await this.completePayment(ApplePaySession.STATUS_FAILURE,N)}catch(ee){h(ee)}break}case"abort":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),this.button.disabled=!1}catch(N){h(N)}break}case"decelerate":{try{await this.completePayment(ApplePaySession.STATUS_FAILURE),M({checkoutUrl:D.redirectUrl,instrumentName:this.name,reason:D.reason})}catch(N){h(N)}break}default:h(new Error("[".concat(this.name,"] completion action not handled: ").concat(D.action)))}},{token:y,billingContact:E,shippingContact:w}=u.payment;let A=null,I=null;try{if(!E){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}if(A=dt(T(_({},E),{phoneNumber:w==null?void 0:w.phoneNumber})),this.isShippingRequired){if(!w){await this.completePayment(ApplePaySession.STATUS_FAILURE);return}I=dt(w)}}catch(D){h(D);return}const k=async()=>{var D;try{const H=this.isShippingRequired?{validateAddress:!0,streetAddress:I}:{},F=(D=this.customerAccountEmail)!=null?D:w==null?void 0:w.emailAddress,N=await ke(_({cartId:this.cart.id,emailAddress:F,cartClient:this.apiClient,instrumentName:this.name},H));if(this.shouldDecelerate(N))return;const ee=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(N,{shippingRequired:this.isShippingRequired,shippingCountryCode:I==null?void 0:I.country});await Ht({paymentSheetAction:ee,onProceed:async lt=>{lt&<.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,lt):await U()},terminateSession:h})}catch(H){h(H)}},U=async()=>{var D;try{const H=this.cart.lineItems.some(ee=>!!ee.sellingPlanAllocation),F=await wr({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{applePayWalletContent:{billingAddress:A,data:y.paymentData.data,header:y.paymentData.header,lastDigits:y.paymentMethod.displayName.split(" ")[1],signature:y.paymentData.signature,version:y.paymentData.version}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:A,cartClient:this.apiClient,instrumentName:this.name,hasSellingPlan:H,abortSignal:(D=this.abortController)==null?void 0:D.signal});if(this.shouldDecelerate(F))return;const N=this.paymentSheetActionGenerator.mapMutationResultToPaymentSheetAction(F,{shippingRequired:this.isShippingRequired,shippingCountryCode:I==null?void 0:I.country});await Ht({paymentSheetAction:N,onProceed:async ee=>{ee&&ee.length>0?await this.completePayment(ApplePaySession.STATUS_FAILURE,ee):await He()},terminateSession:h})}catch(H){h(H)}},He=async()=>{try{const D=await aa({cartId:this.cart.id,token:y.transactionIdentifier,cartClient:this.apiClient,instrumentName:this.name}),H=this.paymentSheetActionGenerator.mapCompletionResultToPaymentSheetAction(D,{shippingRequired:this.isShippingRequired,shippingCountryCode:I==null?void 0:I.country});await p(H)}catch(D){h(D)}};await k()}),d(this,"terminateSession",u=>{var h;this.button.disabled=!1,u&&b.notify(u),g.sheetFailed(this.name,u);try{b.leaveBreadcrumb("ApplePay Session abort",{},"log"),this.session.abort(),(h=this.abortController)==null||h.abort()}catch(p){console.debug("[DEBUG] InvalidAccessError occurred during Apple Pay terminateSession")}if(u){const p=this.i18n.translate("brand.apple_pay");Q(p,this.i18n)}}),d(this,"getMostRecentNonNullCart",(u,h)=>u?(this.cart=u,u):h),d(this,"handleNullCart",u=>{if(!u)throw new Error("[".concat(this.name,"] no cart returned on mutation, aborting"))}),d(this,"completeShippingContactSelection",(u,h)=>{try{const p=this.getMostRecentNonNullCart(u,this.cart),{newTotal:y,newLineItems:E}=this.getNewTotalAndLineItems(p),w=ms(p.deliveryGroups,this.i18n);b.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{errors:h,newTotal:y,newLineItems:E,newShippingMethods:w},"log"),this.session.completeShippingContactSelection({errors:h!=null?h:[],newTotal:y,newLineItems:E,newShippingMethods:w})}catch(p){this.terminateSession(p)}}),d(this,"completeShippingMethodSelection",u=>{try{this.handleNullCart(u),this.cart=u;const{newTotal:h,newLineItems:p}=this.getNewTotalAndLineItems(u);b.leaveBreadcrumb("ApplePay Session completeShippingContactSelection",{newTotal:h,newLineItems:p},"log"),this.session.completeShippingMethodSelection({newTotal:h,newLineItems:p})}catch(h){this.terminateSession(h)}}),d(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=c.customerAccountEmail,this.session=new ApplePaySession(gn,fs({shippingRequired:this.isShippingRequired,walletParams:c,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 gs(i)}begin(){b.leaveBreadcrumb("ApplePay Session begin",{},"log"),this.abortController=Be("AbortController"),this.session.begin()}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 Ht({paymentSheetAction:i,onProceed:n,terminateSession:this.terminateSession})}async getMerchantSession(e){const n=await new xt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,apiVersion:"unstable"}).applePaySessionCreate(e);return JSON.parse(n)}async completePayment(e,n=void 0){b.leaveBreadcrumb("ApplePay Session completePayment",{status:e,errors:n},"log"),this.session.completePayment({status:e,errors:n}),g.authorizationComplete({instrument:this.name,measurement:oe($.AuthorizationLatency,this.name),result:e===ApplePaySession.STATUS_SUCCESS?"success":"failure"})}getNewTotalAndLineItems(e){return{newTotal:hs(this.merchantName,e.totalAmount),newLineItems:ps({subtotal:zn(e),discountAllocations:bs(e),deliveryGroups:e.deliveryGroups,duties:e.totalDutyAmount,taxes:e.totalTaxAmount,i18n:this.i18n,formattedRecurringTotals:ws(this.cart.lineItems,this.i18n)})}}shouldDecelerate(e){if(!e.data)return!1;const{checkoutUrl:n,totalAmount:r}=e.data;let a;return e.decelerationReason&&tl.includes(e.decelerationReason)?a=e.decelerationReason:pr({currentCartTotal:r,initialBuyerCurrency:this.buyerCurrency})&&(a="currency_changed"),a?(M({checkoutUrl:n,instrumentName:this.name,reason:a}),this.terminateSession(),!0):!1}get isShippingRequired(){return this.button.isShippingRequired}}function _r({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}var xe;class nl extends Pe{constructor(){super(),d(this,"name",f.ApplePay),d(this,"button",null),O(this,xe),L(this,xe,this.attachShadow({mode:"closed"}))}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]);let i;try{if(i=new rl({accessToken:this.accessToken,buyerCountry:this.buyerCountry,buyerCurrency:this.buyerCurrency,button:this,i18n:n,merchantName:this.merchantName,dataSource:r,apiClient:a,walletParams:this.walletParams}),!i)throw new Error("missing ApplePaySession");i.begin(),g.sheetClicked({instrument:this.name,result:"success"})}catch(o){b.notify(o),g.sheetClicked({instrument:this.name,result:"failed"}),i==null||i.terminateSession()}}async render(){var e;const{translate:n}=await this.i18n,r=new DOMParser().parseFromString(sa.applePayLogo,"image/svg+xml").documentElement;if(!this.button){const a=this.isCTA?n("buy_with_button_content",{wallet:n("brand.apple_pay")}):n("brand.apple_pay");if(this.button=Dt({label:a}),this.button.onclick=i=>this.handleClick(i),this.button.classList.add("apple-pay-button",Fa[this.buttonTheme],Ce.BUTTON),this.isCTA){const i=_r({translate:n,logoElement:r,setAriaHidden:!0});i.classList.add("apple-pay--content"),this.button.appendChild(i)}else this.button.appendChild(r);this.initializeShadowStyles(C(this,xe),as),C(this,xe).appendChild(this.button),this.ensureLightDOMIsNotEmpty(),(e=this.onRendered)==null||e.call(this)}this.disabled&&(this.button.setAttribute("disabled",""),this.button.setAttribute("aria-disabled","true"))}}xe=new WeakMap;function Er(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 al=Object.defineProperty,il=Object.getOwnPropertyDescriptor,oa=(t,e,n,r)=>{for(var a=il(e,n),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,n,a)||a);return a&&al(e,n,a),a},ne;const Ar=(ne=class extends de{constructor(t){super(t),d(this,"companyFieldRequired"),this.companyFieldRequired=!!this.walletParams.companyRequired}static walletName(){return"apple_pay"}getWebComponentName(){return"shopify-apple-pay-button"}getWebComponentClass(){return nl}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 t,e,n,r;return typeof window>"u"||window.ApplePaySession===void 0?{eligible:!1,reason:"window or ApplePaySession is undefined"}:(e=(t=window.ApplePaySession).supportsVersion)!=null&&e.call(t,gn)?(r=(n=window.ApplePaySession).canMakePayments)!=null&&r.call(n)?{eligible:!0}:{eligible:!1,reason:"failed SDK eligibility check"}:{eligible:!1,reason:"SDK does not meet minimum version requirement"}}async loadWalletSDK(){await this.loadAppleLogo()}async loadAppleLogo(){if(ne.applePayLogo=(await import("./apple-pay-logo-BZB6IYWC.js")).default,!ne.applePayLogo)throw new Error("Apple Pay logo is empty")}},d(ne,"applePayLogo",""),ne);oa([Er("Apple Pay")],Ar.prototype,"getLoadEligibility"),oa([Er("Apple Pay")],Ar.prototype,"getPartnerSDKEligibility");let sa=Ar;const ol=".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 _t extends Error{constructor(){super(...arguments),d(this,"name","MissingAccessTokenError")}}class Cr extends Error{constructor(){super(...arguments),d(this,"name","FetchingWalletsPlatformConfigError")}}class Sr extends Error{constructor(){super(...arguments),d(this,"name","EmptyLineItemsWalletsPlatformConfigError")}}async function la({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 Sr("[Fetch Pay Config][".concat(a,"] No eligible line items provided in the config request."));default:throw new Cr("[Fetch Pay Config][".concat(a,"] ").concat(o))}}}const sl={[S.Checkout]:"Checkout",[S.CartAjax]:"Cart",[S.CartPage]:"Cart",[S.ProductPage]:"Product",[S.Unknown]:"Product"};var rt;const Re=class vc extends Pe{constructor(){super(...arguments),d(this,"name",f.BuyWithPrime),d(this,"button",null),d(this,"apiClientId",""),O(this,rt,this.attachShadow({mode:"closed"}))}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name),this.handleOnSendCheckoutAction=this.handleOnSendCheckoutAction.bind(this)}async createButton(){const{translate:e}=await this.i18n,n=Dt({label:e("brand.buy_with_prime")});return n.type="button",n.className="buy-with-prime-button",this.applyEnabledStyles(n),n}applyEnabledStyles(e){e.innerHTML=et.primeLogo,e.disabled=!1,Mr(e,{"background-color":"#1A98FF",color:"#FFFFFF",cursor:"pointer"})}applyDisabledStyles(e){e.innerHTML=et.primeLogoDark,e.disabled=!0,Mr(e,{"background-color":"#C0E3FF",color:"#7292AC",cursor:"not-allowed"})}async handleClick(){var e,n,r;if(!this.button)return;const[a,i]=await Promise.all([this.i18n,this.dataSource]);let o=[];try{this.applyDisabledStyles(this.button);let s=this.walletParams;if(this.apiClientId=this.apiClientId||s.appId||"",!s.createCheckoutSessionConfig){const{cart:c,decelerationReason:u,customValidationError:h}=await ce({element:this,instrumentName:this.name,dataSource:i});if(h){Ie(a,h.message);return}if(u){M({checkoutUrl:(e=c==null?void 0:c.checkoutUrl)!=null?e:"",instrumentName:this.name,reason:u});return}if(!this.accessToken)throw new _t("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");s=_({},await la({configOptionsEndpoint:vc.OPTIMUS_CONFIG_REST_API_URL,checkoutUrl:(n=c==null?void 0:c.checkoutUrl)!=null?n:"",sourceId:(r=In(c))!=null?r:"",accessToken:this.accessToken,instrument:this.name}))}s.placement=this.getPlacement(),o=this.extractSKUs(s),delete s.checkoutSupportsSplitCart,delete s.appId;const l=s;this.pciEnabled&&(l.onSendCheckoutAction=this.handleOnSendCheckoutAction),window.amazon.buywithprime.initCheckout({amazonPayOptions:l}),g.sheetClicked({instrument:this.name,result:"success",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:o,pageType:this.pageType}:void 0})}catch(s){vc.EXPECTED_ERRORS.some(u=>s instanceof u)||b.notify(s),g.sheetClicked({instrument:this.name,result:"failed",webPixelMetaData:this.apiClientId?{apiClientId:this.apiClientId,skus:o,pageType:this.pageType}:void 0});const{name:l}=s!=null?s:{name:"unknown"},{translate:c}=a;Se(c("error_dialogs.wallet.title",{wallet:c("brand.buy_with_prime")}),this.getModalContent(l,c))}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&&sl[this.pageType]||"Other"}async render(){var e;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(Ce.BUTTON),await this.initializeShadowStyles(C(this,rt),ol),C(this,rt).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}}};rt=new WeakMap,d(Re,"OPTIMUS_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/optimus")),d(Re,"EXPECTED_ERRORS",[Cr,_t,Sr]);let Zt=Re;function ca(t,e=3,n=1e3,r=()=>!0){const a=()=>new Promise(o=>{setTimeout(o,n)}),i=async o=>{try{return await t()}catch(s){if(o>0&&r(s))return await a(),i(o-1);throw s}};return i(e-1)}async function ll(t){return new Promise((e,n)=>{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=()=>{n(new Pt("Error loading Amazon SDK"))},document.head.append(r)})}async function da({sdkUrl:t=ir,maxRetries:e=3}){return ca(()=>ll(t),e,200)}const j=class yn extends de{static walletName(){return"buy_with_prime"}constructor(e){super(e)}getWebComponentName(){return"shopify-buy-with-prime-button"}getInstrumentName(){return f.BuyWithPrime}getWebComponentClass(){return Zt}async loadWalletSDK(){await da({sdkUrl:yn.SDK_URL,maxRetries:yn.MAX_RETRIES}),await this.loadLogos()}async loadLogos(){await Promise.all([this.loadPrimeLogo(),this.loadPrimeLogoDark()])}async loadPrimeLogo(){if(yn.primeLogo=(await import("./prime-logo-DoVHKBSO.js")).default,!yn.primeLogo)throw new Error("Buy with Prime logo is empty")}async loadPrimeLogoDark(){if(yn.primeLogoDark=(await import("./prime-logo-dark-DJIA6J0w.js")).default,!yn.primeLogoDark)throw new Error("Buy with Prime logo dark is empty")}};d(j,"MAX_RETRIES",3),d(j,"SDK_URL",ir),d(j,"primeLogo",""),d(j,"primeLogoDark","");let et=j;const cl="shopify-amazon-pay-button div[role=button][slot=amazon-pay-slot][data-testid=amazon-pay-button]{border-radius:0!important}",Jr="amazon-pay-slot";var nt,at,Oe,Y,re,ge,fe;const Ne=class Cc extends Pe{constructor(){super(),d(this,"name",f.AmazonPay),d(this,"resizeObserver",null),O(this,nt,0),O(this,at,0),O(this,Oe,!1),O(this,Y,null),O(this,re,null),O(this,ge,null),O(this,fe),L(this,fe,this.attachShadow({mode:"closed"})),this.resizeObserver=Be("ResizeObserver",()=>this.onResize())}connectedCallback(){this.cleanupOnFailure(this.render.bind(this),this.name)}async disconnectedCallback(){var e;this.innerHTML="",C(this,fe).innerHTML="",this.teardownAmazonButtonContainer(),(e=this.resizeObserver)==null||e.disconnect()}async handleClick(e){var n,r;const[a,i]=await Promise.all([this.i18n,this.dataSource]);try{const{cart:o,decelerationReason:s,customValidationError:l}=await ce({element:this,instrumentName:this.name,dataSource:i});if(l){Ie(a,l.message);return}if(s){M({checkoutUrl:(n=o==null?void 0:o.checkoutUrl)!=null?n:"",instrumentName:this.name,reason:s});return}const{totalAmount:{amount:c},checkoutUrl:u}=o;let h=this.walletParams;if(!h.createCheckoutSessionConfig){if(!this.accessToken)throw new _t("[Fetch Pay Config] could not fetch pay configs since required accessToken is missing.");h=T(_({},await la({configOptionsEndpoint:Cc.CV2_CONFIG_REST_API_URL,checkoutUrl:u,sourceId:(r=In(o))!=null?r:"",accessToken:this.accessToken,instrument:this.name})),{placement:this.pageType===S.ProductPage?"Product":"Cart"})}delete h.appId,e.initCheckout(_(_({},h),Number(c)!==0&&{estimatedOrderAmount:{amount:c,currencyCode:this.buyerCurrency}})),g.sheetClicked({instrument:this.name,result:"success"})}catch(o){Cc.EXPECTED_ERRORS.some(l=>o instanceof l)||b.notify(o),g.sheetClicked({instrument:this.name,result:"failed"});const s=a.translate("brand.amazon_pay");Q(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=Jr,r.setAttribute("data-testid","amazon-pay-button"),r}async onResize(){const e=ft(C(this,Y))||0,n=bt(C(this,Y))||0,r=C(this,nt)!==e||C(this,at)!==n;!C(this,Oe)&&r&&(this.teardownAmazonButtonContainer(),await this.cleanupOnFailure(()=>this.renderFromAmazonSDK(),this.name))}async render(){var e;try{const n=document.createElement("slot");n.name=Jr;const r=document.createElement("style");r.textContent=cl,this.appendChild(r),await this.initializeShadowStyles(C(this,fe));const a=await this.containerInstanceNumber;L(this,re,"AcceleratedCheckoutAmazonPayButtonContainer".concat(this.pageType).concat(a)),L(this,Y,document.createElement("div")),C(this,Y).classList.add(Ce.BUTTON),C(this,Y).appendChild(n),C(this,fe).appendChild(C(this,Y)),(e=this.resizeObserver)==null||e.observe(C(this,Y)),await this.renderFromAmazonSDK()}catch(n){b.notify(n)}}async renderFromAmazonSDK(){var e;try{L(this,Oe,!0);const n=bt(C(this,Y))||0;L(this,ge,this.createContainer({containerID:C(this,re),height:n})),this.appendChild(C(this,ge));const r=ft(C(this,Y))||0,a={buttonBorderRadius:"".concat(r,"px")},i=window.amazon.Pay.renderButton("#".concat(C(this,re)),T(_({},this.walletParams),{style:a,placement:this.pageType===S.ProductPage?"Product":"Cart"}));i==null||i.onClick(()=>this.handleClick(i)),L(this,at,n),L(this,nt,r),g.renderSucceeded(this.name),(e=this.onRendered)==null||e.call(this)}catch(n){g.renderFailed(this.name);const r="Amazon Pay Button not able to render into container #".concat(C(this,re),".");console.error(r),g.log({body:r,attributes:{pageType:this.pageType,containerID:C(this,re),error:n==null?void 0:n.toString()}})}finally{L(this,Oe,!1)}}teardownAmazonButtonContainer(){var e;(e=C(this,ge))==null||e.remove(),L(this,ge,null)}};nt=new WeakMap,at=new WeakMap,Oe=new WeakMap,Y=new WeakMap,re=new WeakMap,ge=new WeakMap,fe=new WeakMap,d(Ne,"CV2_CONFIG_REST_API_URL","".concat(window.location.origin,"/wallets/config/amazon_pay")),d(Ne,"EXPECTED_ERRORS",[Cr,_t,Sr]);let er=Ne;const Te=class _c extends de{static walletName(){return"amazon_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-amazon-pay-button"}getInstrumentName(){return f.AmazonPay}getWebComponentClass(){return er}async loadWalletSDK(){await da({sdkUrl:_c.SDK_URL,maxRetries:_c.MAX_RETRIES})}getLoadEligibility(e){return e.getRootNode()instanceof ShadowRoot?{eligible:!1,reason:"Cannot load Amazon Pay within Shadow DOM"}:{eligible:!0}}};d(Te,"MAX_RETRIES",3),d(Te,"SDK_URL",ir);let tr=Te;var Gt={Purple:{D0:"#4524DB",D1:"#30368D",D2:"#1C234C",L0:"#6445ED",L1:"#9C83F8",L2:"#EEEAFF",L3:"#F7F5FF",Primary:"#5433EB",PrimaryLight:"#DBD1FF"},Grayscale:{Black:"#000000",D0:"#666666",D1:"#404040",D2:"#121212",D3:"#0B0B0C",D2D:"#2A2A2A",PrimaryLight:"#707070",L1:"#A8A8A7",L2:"#CBCBCA",L2L:"#E3E3E3",L3:"#F0F0F0",L4:"#F2F4F5",White:"#FFFFFF"},Green:{D1:"#008552",D2:"#004839",L1:"#BAEBCB",L2:"#D2F2DE",L3:"#E4F6EB",Primary:"#92D08D"},Poppy:{D0:"#F05D38",D1:"#D92A0F",D2:"#832711",L1:"#FFD2C2",L2:"#FFECE9",Primary:"#FF967D"},Ochre:{D0:"#F8DB67",D1:"#E3BE2B",D2:"#C29D05",D4:"#443600",L1:"#FFF4CB",L2:"#FFF9E2",Primary:"#FFEC9F"},Brand:{Aqua:"#8DC0C6",Lime:"#C7DE00",Magenta:"#D354FF",Olive:"#8B8F01",Sage:"#D8E59D",Sand:"#F4F4ED",Violet:"#A327C2"}},dl={0:0,none:0,xxxs:2,xxs:4,xs:8,"xs-s":12,s:16,gutter:20,m:24,l:32,section:36,xl:40,xxl:48,xxxl:64,auto:"auto"},ul=class extends HTMLElement{static get observedAttributes(){return["disabled"]}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this._updateButton()}attributeChangedCallback(){this._updateButton()}_updateButton(){var t;let e=this.shadowRoot;e&&(e.innerHTML=pl,this.hasAttribute("disabled")&&((t=this.shadowRoot.querySelector("button"))==null||t.setAttribute("disabled","")))}};function hl(){window.customElements&&(customElements.get("gravity-button")||customElements.define("gravity-button",ul))}var pl="\n\n\n\n');const ml=".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}",yl='.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);min-width:150px}: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)}@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 ua extends Error{constructor(){const e="DeliveryEstimatesResponseIsNullError";super("deliveryEstimates is null or undefined"),this.name=e}}class Vt extends Error{constructor(){const e="DeliveryPromiseAPIClientError";super("window.Shopify.ShopPromise.deliveryPromiseAPIClient is undefined"),this.name=e}}const gl=15,fl=200;class bl{constructor(e){d(this,"storefrontAPIToken"),this.storefrontAPIToken=e}async fetchDeliveryPromise({variant:e,postalCode:n,defaultPostalCode:r,sellingPlanId:a}){const i=await ca(async()=>this.fetchDeliveryOptions(e,n,r,a),gl,fl,o=>o instanceof Vt).catch(o=>{if(o instanceof Vt)throw o;return null});if(!i)throw new ua;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 Vt;return l(s,this.storefrontAPIToken)}}function wl(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 _l="delivery_promise_default_address",El="delivery_promise_postal_code";class Al extends Nt{constructor(){super(...arguments),d(this,"lastFetchedProductVariantId"),d(this,"lastFetchSellingPlan"),d(this,"fetching",!1),d(this,"i18n",null),d(this,"daysToDelivery"),d(this,"formObserver",null)}async connectedCallback(){this.formObserver=new On(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(Ze(El)||"null")||null}catch(e){return null}}get defaultDeliveryAddress(){try{return JSON.parse(Ze(_l)||"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 bl(this.accessToken).fetchDeliveryPromise({variant:e,postalCode:this.postalCode||"",defaultPostalCode:s,sellingPlanId:n||""}),c=br(this),u=(i=(a=l==null?void 0:l.selectedShippingOption)==null?void 0:a.brandedPromise)==null?void 0:i.handle;if((c==null?void 0:c.sellingPlanId)!==n||(c==null?void 0:c.variantId)!==e||u!=="shop_promise")return;this.daysToDelivery=(o=l==null?void 0:l.selectedShippingOption)==null?void 0:o.maxCalendarDaysToDelivery,this.render()}catch(s){s instanceof ua&&(this.daysToDelivery=null)}}render(){const e=wl(this.daysToDelivery,this.i18n);this.classList.add("ShopPromise"),this.innerHTML=e?'|'.concat(e,""):""}}var be;class Cl extends Pe{constructor(){super(),d(this,"name",f.ShopPay),d(this,"button",null),d(this,"shopPromiseProductPageContent",null),d(this,"shopPromiseEligible",!1),O(this,be),L(this,be,this.attachShadow({mode:"closed"}))}static get observedAttributes(){return["disabled"]}connectedCallback(){this.shopPromiseEligible=Pn(),this.cleanupOnFailure(async()=>{hl(),await this.render()},this.name)}attributeChangedCallback(e,n,r){super.attributeChangedCallback(e,n,r,this.button)}async addButtonContent(){if(!this.button)return;let e;const n=await this.i18n,r=new DOMParser().parseFromString(pa.shopPayLogoElement,"image/svg+xml").documentElement;this.isCTA?e=_r({translate:n.translate,logoElement:r,setAriaHidden:!1}):(e=document.createElement("div"),e.appendChild(r)),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)),this.button.appendChild(e)}getShopPayBehavior(){return this.pageType===S.ProductPage?"force_shop_pay_product":this.pageType===S.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}=await ce({element:this,instrumentName:f.ShopPay,dataSource:i});if(g.sheetClicked({instrument:this.name,result:"success"}),l){Ie(a,l.message);return}if(o){M({checkoutUrl:(n=s==null?void 0:s.checkoutUrl)!=null?n:"",instrumentName:this.name,reason:o});return}ie((r=s==null?void 0:s.checkoutUrl)!=null?r:"",this.getShopPayBehavior())}catch(o){b.notify(new Sl("An error occurred when attempting to create a cart using the Shop Pay Button. Details: ".concat(o),{cause:o})),g.sheetClicked({instrument:this.name,result:"failed"}),Se(a.translate("error_dialogs.checkout.title"),a.translate("error_dialogs.checkout.generic_error"))}}async render(){if(C(this,be).innerHTML)return;this.button||(this.button=document.createElement("gravity-button"));const e=document.createElement("style");e.innerHTML=[yl,ml].join("\n"),C(this,be).appendChild(e),await this.addButtonContent(),this.disabled&&this.button.setAttribute("disabled",""),this.button.classList.add(Ce.BUTTON),this.button.onclick=n=>this.handleClick(n),C(this,be).appendChild(this.button),this.ensureLightDOMIsNotEmpty(),this.onRendered()}}be=new WeakMap,le("shop-promise-product-page-content",Al);class Sl extends Error{constructor(){super(...arguments),d(this,"name","ShopPayButtonError")}}var Il=Object.defineProperty,Pl=Object.getOwnPropertyDescriptor,vl=(t,e,n,r)=>{for(var a=Pl(e,n),i=t.length-1,o;i>=0;i--)(o=t[i])&&(a=o(e,n,a)||a);return a&&Il(e,n,a),a},we;const ha=(we=class extends de{static walletName(){return"shop_pay"}constructor(t){super(t)}getWebComponentName(){return"shop-pay-wallet-button"}getWebComponentClass(){return Cl}getInstrumentName(){return f.ShopPay}async loadWalletSDK(){await this.loadLogo()}getLoadEligibility(){return{eligible:!0}}async loadLogo(){we.shopPayLogoElement=(await import("./shop-pay-logo-CYhOC7ye.js")).default}},d(we,"shopPayLogoElement"),we);vl([Er("Shop Pay")],ha.prototype,"getLoadEligibility");let pa=ha;const Dl=".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 zt({cart:t,i18n:e}){const n=zn(t),r={label:e.translate("order_summary.subtotal"),type:"SUBTOTAL",price:Ee(n.amount)},a=Gn({deliveryGroups:t.deliveryGroups,i18n:e}).map(s=>Rl({lineItem:s,type:"LINE_ITEM"})),i=Nl(t,e),o=[r,...a,...i];if(t.totalDutyAmount){const s={label:e.translate("order_summary.duties"),type:"LINE_ITEM",price:Ee(t.totalDutyAmount.amount)};o.push(s)}if(t.totalTaxAmount){const s={label:e.translate("order_summary.taxes"),type:"TAX",price:Ee(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 Rl({lineItem:t,type:e,status:n="FINAL"}){return{label:t.label,type:e,price:t.amount,status:n}}function Nl(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(Ee(Number(n.discountedAmount.amount)))}})}const ma=["PAYMENT_AUTHORIZATION"],Tl=ma.concat(["SHIPPING_ADDRESS","SHIPPING_OPTION"]),kl=["PAN_ONLY"];function Ll({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=T(_({},t.paymentData),{shippingAddressRequired:e,shippingOptionRequired:e,transactionInfo:o});return s.merchantInfo.authJwt=i,e||delete s.shippingAddressParameters,s.callbackIntents=e?Tl:ma,n&&xl(s),s}function xl(t){t.allowedPaymentMethods.forEach(e=>{e.parameters.allowedAuthMethods=e.parameters.allowedAuthMethods.filter(n=>kl.includes(n))})}class Ol extends Vn{constructor(e){super(),d(this,"brandName"),d(this,"completionResult"),this.i18n=e,this.brandName=this.i18n.translate("brand.google_pay"),this.completionResult=void 0}mapMutationResultToPaymentSheetAction(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 wt("[".concat(f.GooglePay,"] mutation result error not handled: ").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 Error("[".concat(f.GooglePay,"] completion result error not handled: ").concat(o)))});const{prioritizedPaymentSheetAction:i}=this.getMergedPaymentSheetAction({result:e,errorActions:r});return i||(Q(this.brandName,this.i18n),{action:"abort"})}default:throw new Error("[".concat(f.GooglePay,"] unknown completion result type: ").concat(e.data.__typename))}}getErrorActions(){return[{errors:[m.CaptchaCompletionRequired],generateAction:()=>this.decelerateOrAbort({reason:"captcha_required",instrumentName:f.GooglePay,errorOrWarning:m.CaptchaCompletionRequired,result:this.completionResult})},{errors:[m.InvalidLanguage],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.GooglePay,"] mutation provided invalid language, aborting")))},()=>Q(this.brandName,this.i18n)]})},{errors:[m.InvalidCountry],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.GooglePay,"] mutation provided invalid country, aborting")))},()=>Q(this.brandName,this.i18n)]})},{errors:[m.MissingCartId],generateAction:()=>({action:"abort",effects:[()=>{b.notify(new Error("[".concat(f.GooglePay,"] mutation provided invalid cart ID, aborting")))},()=>Q(this.brandName,this.i18n)]})},{errors:Nn,generateAction:()=>this.decelerateOrAbort({reason:"dynamic_tax",instrumentName:f.GooglePay,errorOrWarning:m.NewTaxMustBeAccepted,result:this.completionResult})},{errors:[m.MerchandiseExpectedPriceMismatch,m.DeliveryLineChanged,m.DeliveryLocalPickupLineChanged,...Rn],generateAction:()=>({action:"abort",effects:[()=>Q(this.brandName,this.i18n)]})},{errors:[m.UnsupportedGooglePayPaymentMethod],generateAction:()=>({action:"abort",effects:[()=>Q(this.brandName,this.i18n),()=>{b.notify(new wt("[".concat(f.GooglePay,"] payment method is not supported")))}]})},{errors:[m.MerchandiseNotEnoughStock],generateAction:()=>this.decelerateOrAbort({reason:"not_enough_stock",instrumentName:f.GooglePay,errorOrWarning:m.MerchandiseNotEnoughStock,result:this.completionResult})},{errors:Tn,generateAction:()=>this.decelerateOrAbort({reason:"out_of_stock",instrumentName:f.GooglePay,errorOrWarning:m.MerchandiseOutOfStock,result:this.completionResult})},{errors:Dn,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.shipping_address")}]})},{errors:vn,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[m.NoDeliveryGroupSelected],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_OPTION_INVALID",intent:"SHIPPING_OPTION",message:this.i18n.translate("errors.missing.shipping_option")}]})},{errors:[m.BuyerIdentityEmailDomainInvalid,m.BuyerIdentityEmailNotExpectedPattern,m.BuyerIdentityEmailInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.email")}]})},{errors:[m.BuyerIdentityEmailRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.email")}]})},{errors:[m.DeliveryAddress2Required,m.DeliveryAddress2AddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address2")}]})},{errors:[m.DeliveryAddress2Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address2")}]})},{errors:[m.DeliveryCityAddressFieldRequired,m.DeliveryCityRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.city")}]})},{errors:[m.DeliveryCityInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.city")}]})},{errors:[m.DeliveryZoneRequiredForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.zone")}]})},{errors:[m.DeliveryZoneNotFound],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.zone")}]})},{errors:[m.DeliveryPostalCodeRequired,m.DeliveryPostalCodeAddressFieldRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.postal_code")}]})},{errors:[m.DeliveryPostalCodeInvalid,m.DeliveryInvalidPostalCodeForZone,m.DeliveryInvalidPostalCodeForCountry,m.DeliveryZipInvalidForCountry],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.postal_code")}]})},{errors:[m.DeliveryPhoneNumberRequired],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.phone_number")}]})},{errors:[m.DeliveryPhoneNumberInvalid,m.BuyerIdentityInvalidPhone,m.DeliveryPhoneDoesNotMatchExpectedPattern],generateAction:()=>({action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.phone_number")}]})},{errors:[m.BuyerIdentityInvalidCountry,m.DeliveryCountryInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.country")}]})},{errors:[m.DeliveryFirstNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.first_name")}]})},{errors:[m.DeliveryFirstNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.first_name")}]})},{errors:[m.DeliveryLastNameRequired],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.last_name")}]})},{errors:[m.DeliveryLastNameInvalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.last_name")}]})},{errors:[m.DeliveryAddress1Required],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.missing.address1")}]})},{errors:[m.DeliveryAddress1Invalid],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.invalid.address1")}]})},{errors:[m.DeliveryLastNameContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.last_name")}]})},{errors:[m.DeliveryCityContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.city")}]})},{errors:[m.DeliveryAddress1ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address1")}]})},{errors:[m.DeliveryAddress2ContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.address2")}]})},{errors:[m.DeliveryPostalCodeContainsEmojis],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.emojis.postal_code")}]})},{errors:[m.DeliveryAddress1TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address1")}]})},{errors:[m.DeliveryAddress2TooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.address2")}]})},{errors:[m.DeliveryFirstNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.first_name")}]})},{errors:[m.DeliveryLastNameTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.last_name")}]})},{errors:[m.DeliveryCityTooLong],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.too_long.city")}]})},{errors:[m.DeliveryFirstNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.first_name")}]})},{errors:[m.DeliveryLastNameContainsUrl],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.url.last_name")}]})},{errors:[m.DeliveryAddress1ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address1")}]})},{errors:[m.DeliveryAddress2ContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.address2")}]})},{errors:[m.DeliveryCityContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.city")}]})},{errors:[m.DeliveryFirstNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.first_name")}]})},{errors:[m.DeliveryLastNameContainsHtmlTags],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.i18n.translate("errors.html_tags.last_name")}]})},{errors:[m.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=ur(e);return n?(b.notify(new Error("[".concat(f.GooglePay,"] custom validation function error: ").concat(JSON.stringify(e)))),hr(this.i18n.translate("error_dialogs.wallet.title",{wallet:this.brandName}),n.message),{action:"abort"}):null}}function Ml({deliveryGroups:t,i18n:e}){var n;const r=ss($n({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 qt(t){let e=t.administrativeArea,n=t.locality;t.countryCode==="AE"&&(n=t.administrativeArea,t.administrativeArea in Xr&&(e=Xr[t.administrativeArea])),t.countryCode==="MX"&&e&&(e=Fl(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 Xr={"\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"},Fl=t=>t==="M\xE9x."?"MEX":t==="Q.R."?"Q ROO":t.replace(/\./g,"").toUpperCase();class jt extends Error{constructor(){super(...arguments),d(this,"name","GooglePayError")}}function ya(t){const e=t.auth;if(!(Array.isArray(e)&&e.length>0))return{result:"error",reason:"invalidAuthParams"};const n=Ke();for(const r of e)if(n{var y;const{callbackTrigger:E,shippingAddress:w,shippingOptionData:A}=p,{translate:I}=this.i18n;switch(E){case"INITIALIZE":{if(!this.cart)try{const{cart:U,customValidationError:He,decelerationReason:D}=await ce({element:this.button,instrumentName:f.GooglePay,dataSource:this.dataSource});if(He)return this.customValidationError=He,this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:this.customValidationError.message,intent:"SHIPPING_ADDRESS"}});if(D)return M({checkoutUrl:(y=U==null?void 0:U.checkoutUrl)!=null?y:"",instrumentName:this.name,reason:D}),this.showPaymentDataRequestError({error:{intent:"SHIPPING_ADDRESS",reason:"OTHER_ERROR",message:""}});this.cart=U,g.sheetClicked({instrument:this.name,result:"success"})}catch(U){return g.sheetClicked({instrument:this.name,result:"failed"}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}let k=!1;if(w)try{return await this.handleShippingAddressChange(this.cart.id,w)}catch(U){k=!0}return _({newTransactionInfo:zt({cart:this.cart,i18n:this.i18n})},k?this.showPaymentDataRequestError():{})}case"SHIPPING_ADDRESS":return this.customValidationError?this.showPaymentDataRequestError({error:{reason:"OTHER_ERROR",message:this.customValidationError.message,intent:"SHIPPING_ADDRESS"}}):this.cart?w?this.handleShippingAddressChange(this.cart.id,w):{newTransactionInfo:zt({cart:this.cart,i18n:this.i18n})}:this.showPaymentDataRequestError({intent:E});case"SHIPPING_OPTION":{if(!this.cart)return this.showPaymentDataRequestError({intent:E});if(!A||!A.id)return{error:{reason:"SHIPPING_OPTION_INVALID",message:I("shipping_methods.choose_delivery_strategy"),intent:"SHIPPING_OPTION"}};const k=await this.handleDeliveryOptionChange(A.id.split(","));return k.data?(this.cart=k.data,this.handlePaymentDataRequestUpdate({result:k,intent:E})):this.showPaymentDataRequestError({intent:E})}default:return this.logException("Payment data changed callback returned unexpected intent: ".concat(E),{severity:"warning"}),this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"})}}),d(this,"onPaymentAuthorized",async p=>{var y,E,w;g.authorizationAttempt(this.name),st($.AuthorizationLatency,this.name);const A=(y=p.paymentMethodData.info)==null?void 0:y.billingAddress,I=p.shippingAddress,{signature:k,signedMessage:U,protocolVersion:He}=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&&!I)return this.handlePaymentAuthorizationError({error:{reason:"SHIPPING_ADDRESS_INVALID",intent:"PAYMENT_AUTHORIZATION",message:this.i18n.translate("errors.invalid.shipping_address")}});const D=async()=>{var F,N;const ee=(F=C(this,it))!=null?F:p.email,lt=this.isShippingRequired?{validateAddress:!0,streetAddress:qt(I)}:{};return await ke(_({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:this.name,emailAddress:ee,abortSignal:(N=C(this,Z))==null?void 0:N.signal},lt))},H=async()=>{var F;const N=qt(A);return await wr({cartId:this.cart.id,totalAmount:this.cart.totalAmount,paymentMethod:{walletPaymentMethod:{googlePayWalletContent:{billingAddress:N,signature:k,signedMessage:U,protocolVersion:He}}},canUsePaymentMethodForFreeOrder:!1,billingAddress:N,cartClient:this.cartClient,instrumentName:this.name,hasSellingPlan:this.hasSellingPlan,abortSignal:(F=C(this,Z))==null?void 0:F.signal})};try{const F=setTimeout(()=>{var Ac;(Ac=C(this,Z))==null||Ac.abort("Google Pay Timeout")},Ul),N=await D(),ee=this.handleIntermediatePaymentAuthorizationResult(N);if(ee)return ee;const lt=await H(),Ec=this.handleIntermediatePaymentAuthorizationResult(lt);if(Ec)return Ec;if(clearTimeout(F),(w=(E=C(this,Z))==null?void 0:E.signal)!=null&&w.aborted)throw new jt("Abort Controller was not aborted");const Nc=await aa({cartId:this.cart.id,token:k,cartClient:this.cartClient,instrumentName:this.name}),kc=this.actionGenerator.mapCompletionResultToPaymentSheetAction(Nc);return this.handlePaymentAuthorizationResult(kc)}catch(F){const{message:N}=F;return this.logException(N),this.handlePaymentAuthorizationError()}}),d(this,"handlePaymentAuthorizationResult",async p=>{var y,E;switch((y=p.effects)==null||y.forEach(w=>w()),p.action){case"complete":return this.emitAuthorizationCompleteMetric("success"),ie(p.redirectUrl),{transactionState:"SUCCESS"};case"show_error":return this.handlePaymentAuthorizationError({error:(E=p.errors)==null?void 0:E[0]});case"decelerate":return M({checkoutUrl:p.redirectUrl,instrumentName:this.name,reason:p.reason}),this.emitAuthorizationCompleteMetric("failure"),{transactionState:"SUCCESS"};case"abort":default:return this.emitAuthorizationCompleteMetric("failure"),{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,L(this,it,e.customerAccountEmail),L(this,Z,c);const u=ya(this.walletParams);if(u.result==="error")throw b.leaveBreadcrumb("Google Pay Invalid AuthJwt detected on click",{reason:u.reason,walletParams:this.walletParams},"error"),new jt(u.reason);L(this,Me,u.jwt);const h={environment:this.walletParams.environment,merchantInfo:T(_({},this.walletParams.paymentData.merchantInfo),{authJwt:C(this,Me)}),paymentDataCallbacks:{onPaymentDataChanged:this.isShippingRequired?this.onPaymentDataChanged:void 0,onPaymentAuthorized:this.onPaymentAuthorized}};this.paymentsClient=new window.google.payments.api.PaymentsClient(h),this.actionGenerator=new Ol(this.i18n)}async handleClick(){if(!this.isShippingRequired)throw new Pt("Google Pay checkout started for digital cart");const e=Ll({walletParams:this.walletParams,isShippingRequired:this.isShippingRequired,hasSellingPlan:this.hasSellingPlan,i18n:this.i18n,buyerCurrency:this.initialBuyerCurrency,authJwt:C(this,Me)});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}={}){return this.emitAuthorizationCompleteMetric("failure"),_({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?(M({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:zt({cart:s,i18n:this.i18n}),newShippingOptionParameters:this.isShippingRequired?Ml({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(e.decelerationReason)return M({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){pr({currentCartTotal:n,initialBuyerCurrency:this.initialBuyerCurrency})&&M({checkoutUrl:e,instrumentName:this.name,reason:"currency_changed"})}async handleShippingAddressChange(e,n){var r;let a=await ke({cartClient:this.cartClient,cartId:e,streetAddress:n?qt(n):{},instrumentName:f.GooglePay,abortSignal:(r=C(this,Z))==null?void 0:r.signal});if(!a.data)return this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"});if(this.cart=a.data,this.cart.deliveryGroups.length>0&&(this.cart.deliveryGroups.some(i=>{var o;return((o=i.selectedDeliveryOption)==null?void 0:o.deliveryMethodType)==="LOCAL"})||this.cart.deliveryGroups.every(i=>i.selectedDeliveryOption==null))){const i=this.cart.deliveryGroups.map(o=>o.deliveryOptions.filter(({deliveryMethodType:s})=>s==="SHIPPING")).map(o=>o[0].handle);if(a=await this.handleDeliveryOptionChange(i),!a.data)return this.showPaymentDataRequestError({intent:"SHIPPING_ADDRESS"});this.cart=a.data}return this.handleCurrencyChange(this.cart.checkoutUrl,this.cart.totalAmount),this.handlePaymentDataRequestUpdate({result:a,intent:"SHIPPING_ADDRESS"})}async handleDeliveryOptionChange(e){var n;const r=ia({deliveryGroups:this.cart.deliveryGroups,instrumentName:f.GooglePay,selectedDeliveryOptionHandles:e});return await na({cartClient:this.cartClient,cartId:this.cart.id,instrumentName:f.GooglePay,selectedDeliveryOptions:r,abortSignal:(n=C(this,Z))==null?void 0:n.signal})}logException(e,{severity:n,metadata:r}={}){b.notify(new jt(e),{severity:n!=null?n:"error",metadata:r})}emitAuthorizationCompleteMetric(e){g.authorizationComplete({instrument:this.name,measurement:oe($.AuthorizationLatency,this.name),result:e})}}it=new WeakMap,Z=new WeakMap,Me=new WeakMap;const $l={LIGHT:"light",DARK:"dark"};var Fe;class Hl extends Pe{constructor(){super(),d(this,"name",f.GooglePay),d(this,"paymentsClient",null),d(this,"button",null),O(this,Fe),d(this,"handleClick",async()=>{if(this.disabled)return;this.disabled=!0;const e=Be("AbortController");try{await this.createPaymentsClient(e),await this.paymentsClient.handleClick()}catch(n){if(this.disabled=!1,n.statusCode==="CANCELED"){e==null||e.abort("Payment sheet cancelled"),g.sheetCancelled(f.GooglePay);return}e==null||e.abort("Payment sheet failure"),b.notify(n),g.sheetClicked({instrument:this.name,result:"failed"});const r=await this.i18n,a=r.translate("brand.google_pay");Q(a,r)}}),L(this,Fe,this.attachShadow({mode:"closed"}))}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 Bl({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(){if(this.button)return;await this.initializeShadowStyles(C(this,Fe),Dl);const{translate:e}=await this.i18n,n=this.isCTA?e("buy_with_button_content",{wallet:e("brand.google_pay")}):e("brand.google_pay"),r=Dt({label:n});this.disabled&&r.setAttribute("disabled",""),r.classList.add("button",Ce.BUTTON,$l[this.buttonTheme]),r.onclick=this.handleClick,await this.renderButtonContent(r,e),this.button=r,C(this,Fe).appendChild(r),this.ensureLightDOMIsNotEmpty(),this.onRendered()}async renderButtonContent(e,n){const r=this.buttonTheme==="DARK"?tt.googlePayLogoDark:tt.googlePayLogo,a=new DOMParser().parseFromString(r,"image/svg+xml").documentElement;if(e.style.font=window.getComputedStyle(this).font,this.isCTA){const i=_r({translate:n,logoElement:a,setAriaHidden:!0});i.classList.add("content"),e.appendChild(i)}else e.classList.add("logo-only"),e.appendChild(a)}}Fe=new WeakMap;const q=class Ot extends de{static walletName(){return"google_pay"}constructor(e){super(e)}getWebComponentName(){return"shopify-google-pay-button"}getInstrumentName(){return f.GooglePay}getWebComponentClass(){return Hl}async loadWalletSDK(){if(Ot.googlePaySDKPromise)return Ot.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 Ot.googlePaySDKPromise=Promise.all([n,this.loadLogos()]),Ot.googlePaySDKPromise}getLoadEligibility(){const e=ya(this.walletParams);switch(e.result){case"success":return{eligible:!0};case"error":return{eligible:!1,reason:e.reason}}}getPartnerSDKEligibility(){return{eligible:!0}}async loadLogos(){return Promise.all([this.loadGooglePayLogo(),this.loadGooglePayLogoDark()])}async loadGooglePayLogo(){if(Ot.googlePayLogo=(await import("./google-pay-logo-BgkSiJGq.js")).default,!Ot.googlePayLogo)throw new Error("Google Pay logo is empty")}async loadGooglePayLogoDark(){if(Ot.googlePayLogoDark=(await import("./google-pay-logo-dark-DmTdfep2.js")).default,!Ot.googlePayLogoDark)throw new Error("Google Pay logo dark is empty")}};d(q,"googlePaySDKPromise"),d(q,"googlePayLogo",""),d(q,"googlePayLogoDark","");let tt=q;const Gl=[Zo,Qt,sa,tt,et,tr,pa],Vl=new Map(Gl.map(t=>[t.walletName(),e=>new t(e)]));function Et(t){const e=Vl.get(t.name);return e?e(t):(console.debug("Can't build wallet with name ".concat(t.name)),null)}function zl(t){return t.map(e=>Et(e)).filter(e=>e!=null)}const ga="*{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 ql{constructor(e,n,r){this.element=e,this.apiClient=n,this.instrumentName=r}async getInitialCart(e){const n=br(this.element);if(!n)throw new Error("[".concat(this.instrumentName,"] unable to find product form"));const r=Ze($a),{data:a,errors:i,warnings:o}=await this.apiClient.createCart(T(_({},n),{discountCodes:r?[r]:[],instrumentName:e}));return{cart:a,errors:i,warnings:o}}}function jl({instanceNumber:t,styleId:e,styles:n,cssFileName:r}){var a,i;t===1&&(i=(a=window.Shopify)==null?void 0:a.PaymentButton)!=null&&i.isStorefrontPortableWallets&&(Yl({styleId:e,styles:n,cssFileName:r})||Wl({styleId:e,styles:n}))}function Yl({styleId:t}){return!!document.querySelector("style#".concat(t))}function Wl({styleId:t,styles:e}){const n=document.createElement("style");n.id=t,n.innerHTML=e,document.head.appendChild(n)}const K={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 Zr(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 Kl(t,e){for(let n=0;n<3;n++)if(t[n]!==e[n])return e[n]-t[n];return 0}function en(t){return[...t].sort((e,n)=>{const r=Zr(e.selector),a=Zr(n.selector);return Kl(r,a)})}const Ql=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*(>\s*)?li(?![a-zA-Z0-9_.:#-])/,Jl=/\.cart__dynamic-checkout-buttons|\.dynamic-checkout-buttons\s*\[role="?button"?\](?![:\w-])/,Xl=/\.additional-checkout-buttons\s*(?:div\s*)?\[role="?button"?\](?![:\w-])/,fa=/\[data-shopify-buttoncontainer\](?![:\w-])/,ba=/.dynamic-checkout-buttons .shopify-payment-button__button/,Zl=/(?!.*\.shopify-cleanslate)\.shopify-payment-button__button(?:--branded)?(?![\w-:.#>])/,ec=/\.(shopify-payment-button|shopify-payment-button__button|shopify-payment-button__button--branded)\s*\[role="?button"?\](?![:\w-])/,tc=/(?:only\s+)?(?:screen\s+and\s+)?\((?:min|max)-(?:width|height):\s*\d+px\)/,rc=[Jl,fa,Ql,Xl,ba],nc=[Zl,ec,ba];function wa(t){const e=t.pageType,n=[...document.styleSheets].filter(ac),r=[],a=[];n.forEach(D=>{try{const H=[...D.cssRules].filter(N=>N instanceof CSSMediaRule),F=[...D.cssRules].filter(N=>N instanceof CSSStyleRule);a.push(...H.filter(N=>tc.test(N.conditionText)).flatMap(N=>[...N.cssRules].filter(ee=>ee instanceof CSSStyleRule).flatMap(ee=>ee.selectorText.split(",").map(lt=>lt.trim()).map(lt=>_({selector:lt,conditionText:N.conditionText},on(ee)))))),r.push(...F.flatMap(N=>N.selectorText.split(",").map(ee=>ee.trim()).map(ee=>_({selector:ee},on(N)))))}catch(H){gt()("shopify-support-debug")&&(console.debug("[shopify-support-debug] stylesheet origin: ".concat(D.href)),console.debug(H))}});const i=e===S.ProductPage?nc:rc,o=new Set;function s(D,H){const F=H.selector.match(D);return F?(o.add(F[0]),!0):!1}const l=r.filter(D=>i.some(H=>s(H,D))).reverse(),c=a.filter(D=>i.some(H=>s(H,D))).reverse(),u=gt()("shopify-support-debug");u&&console.table(Array.from(o));const h=en(l),p=en(c),y={},E=tn(e)?document.querySelector(".cart__blocks .button"):document.querySelector(".product-form__buttons .button");E&&(y.boxShadow=getComputedStyle(E,":before").boxShadow);for(const D of h){const H=["height","minHeight","borderRadius","marginTop"];tn(e)&&D.selector.match(fa)&&H.push("justifyContent");for(const F of H)y[F]=sc({rule:D,property:F,currentPropertyValue:y[F]})}const{height:w,borderRadius:A,minHeight:I,marginTop:k,justifyContent:U,boxShadow:He}=y;return u&&console.table([{property:"height",value:w},{property:"borderRadius",value:A},{property:"minHeight",value:I},{property:"marginTop",value:k},{property:"justifyContent",value:U},{property:"boxShadow",value:He}]),e===S.ProductPage?an({styles:{height:w,minHeight:I,borderRadius:A,marginTop:k,boxShadow:He},mediaRules:p,element:t}):an({styles:{borderRadius:A,boxShadow:He,justifyContent:U},mediaRules:p,element:t})}function _a(t,e){var n,r,a;if(!e)return;g.styleBackwardsCompatibility();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;o&&s&&g.log({body:"Style backwards compatibility used",attributes:{shopId:"".concat(o),themeId:"".concat(s)}});const l="global-".concat(t.tagName.toLowerCase(),"-styles");if(document.head.querySelector("style#".concat(l))==null){const c=document.createElement("style");c.id=l,c.innerHTML=e,document.head.appendChild(c)}}function ac(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 tn(t){return t===S.CartPage||t===S.CartAjax}function rn({height:t,minHeight:e}){let n=t,r=e;return(n!=null&&n.includes("var(".concat(K.buttonBlockSize))||n==="auto")&&(n=null),(r!=null&&r.includes("var(".concat(K.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=_({},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];return Object.keys(a).length===0?"":ic({mediaCondition:e,selector:n,styles:a})}function ic({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 an({styles:t,element:e,mediaRules:n}){const{height:r,minHeight:a,borderRadius:i,marginTop:o,justifyContent:s,boxShadow:l}=t,c=e.tagName.toLowerCase(),u=getComputedStyle(e),h=new Set;for(const y of Object.values(K))u.getPropertyValue(y)&&h.add(y);let p=nn({existingProperties:h,selector:c,styles:{[K.buttonBlockSize]:rn({height:r,minHeight:a}),[K.buttonBorderRadius]:i,[K.buttonBoxShadow]:l,[K.inlineAlignment]:s,"margin-top":o,display:o?"block":void 0}});return n.forEach(y=>{(y.height||y.minHeight||y.borderRadius||y.boxShadow||y.justifyContent||y.marginTop)&&(p+=nn({existingProperties:h,mediaCondition:y.conditionText,selector:c,styles:{[K.buttonBlockSize]:rn({height:y.height,minHeight:y.minHeight}),[K.buttonBorderRadius]:y.borderRadius,[K.buttonBoxShadow]:y.boxShadow,[K.inlineAlignment]:y.justifyContent,"margin-top":y.marginTop,display:y.marginTop?"block":void 0}}))}),p.trim()}function on(t){return[["height"],["minHeight","min-height"],["borderRadius","border-radius"],["marginTop","margin-top"],["justifyContent","justify-content"]].reduce((e,[n,r])=>(e[n]=oc({rule:t,property:r!=null?r:n}),e),{})}function oc({rule:t,property:e}){const n=t.style.getPropertyValue(e);return t.style.getPropertyPriority(e)?"".concat(n," !important"):n||null}function sc({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}const sn=2e3;class ln extends Error{constructor(){super(...arguments),d(this,"name","AcceleratedCheckoutError")}}const At=class Sc extends gr{constructor(){super(),d(this,"instanceNumber",++Sc.instanceCount),d(this,"pageType",S.ProductPage),d(this,"formObserver"),d(this,"dataSource"),d(this,"wrapper"),d(this,"shopPromiseEligible"),d(this,"didInitiateRender",!1),this.wrapper=document.createElement("div"),jl({instanceNumber:this.instanceNumber,styleId:"shopify-accelerated-checkout",styles:zo,cssFileName:"AcceleratedCheckout.css"}),this.shopPromiseEligible=Pn()}static get observedAttributes(){return["access-token","disabled","has-selling-plan","requires-shipping"]}async connectedCallback(){var e,n,r;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&&(fr(this),g.initStarted(),this.extractStyles());const a=Tt($.ButtonDisplay,"dc:".concat(this.instanceNumber));this.i18n=vt(),this.setupFormObserver(),this.didInitiateRender=!0;const i=await this.loadWallet(),o=(r=i==null?void 0:i.getInstrumentName())!=null?r:f.BuyItNow,s=o===f.ApplePay||o===f.GooglePay;this.apiClient=new xt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale,withCarrierRates:s,cartPrepareMigrationEnabled:this.cartPrepareMigrationEnabled}),this.dataSource=new ql(this,this.apiClient,o);const l=i==null?void 0:i.createWebComponent({walletContainer:this,dataSource:this.dataSource,i18n:this.i18n,apiClient:this.apiClient,classNames:lc(o),callToAction:"true",pageType:this.pageType,containerInstanceNumber:this.instanceNumber,onRendered:()=>g.instrumentLoaded({instrumentOrComponentName:o,result:"success",measurement:a()})});if(!l)throw new ln("No web component found");this.render(l,o),g.initCompleted({result:"success"}),this.instanceNumber===1&&this.triggerLoadedEvent()}catch(a){if(this.clearUI(),g.initCompleted({error:a}),a.name===ot)throw a;b.notify(new ln("An error occurred while attempting to render the AcceleratedCheckout: ".concat(a),{cause:a}))}}async attributeChangedCallback(e,n,r){n!==r&&(mr(this,e,r),e==="has-selling-plan"&&r===""?this.showBuyerConsent(this.apiClient,this.i18n):e==="has-selling-plan"&&r===null&&this.hideBuyerConsent())}async render(e,n){this.clearUI();const r=this.attachShadow({mode:"closed"}),a=document.createElement("style");a.innerHTML=ga,r.appendChild(a),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;l.appendChild(e);const c=this.getShopPromiseSlot();c&&l.appendChild(c);const u=this.getMorePaymentOptionsLink(n);u&&l.appendChild(u),this.appendChild(l)}getMorePaymentOptionsLink(e){var n,r;if(e===f.BuyItNow)return null;const a=document.createElement("more-payment-options-link");return Rt(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(Yt.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 kt({page:"product",element:this})!=null}async loadWallet(){const e=Vo(this.recommendedWallet,this.fallbackWallet,"AcceleratedCheckout");return await dc(this,T(_({},e),{instanceNumber:this.instanceNumber}))}setupFormObserver(){this.formObserver||(this.formObserver=new On(this,({disabled:e,hasSellingPlan:n})=>{this.disabled=e,this.hasSellingPlan=n,this.isShippingRequired=cc(this,this.variantParams)}),this.formObserver.setupMutationObservers())}extractStyles(){if(this.styleExtractorDisabled){gt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled");return}const e=wa(this);e&&_a(this,e)}};d(At,"instanceCount",0);let rr=At;function lc(t){return t===f.BuyItNow?Yt.UNBRANDED_BUTTON:Yt.BRANDED_BUTTON}function cc(t,e){var n;const r=br(t);return!!((n=e.find(a=>a.id===Number(r==null?void 0:r.variantId)))!=null&&n.requiresShipping)}async function dc(t,{recommendedWallet:e,fallbackWallet:n,instanceNumber:r}){const a=e?Et(e):null,i=Et(n);if(yr(t,a)){const o=Wt({walletInstrument:a,instanceNumber:r}),s="timeout",l=await Promise.race([o,new Promise(c=>setTimeout(()=>c(s),sn))]);if(l===s)g.instrumentSDKLoaded({instrument:a.getInstrumentName(),measurement:sn,result:"timeout"});else if(l instanceof de)return l}return i&&Wt({walletInstrument:i,instanceNumber:r})}le("shopify-accelerated-checkout",rr),le("more-payment-options-link",Mo,{isChildCustomElement:!0});const uc=t=>{const e=new PerformanceObserver(n=>{n.getEntriesByType("resource").some(r=>r.name.includes(Ye.CartUpdate)||r.name.includes(Ye.CartChange)||r.name.includes(Ye.CartAdd)||r.name.includes(Ye.CartClear))&&t()});return e.observe({entryTypes:["resource"]}),e},hc=".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;margin:0 5px 5px}.wallet-cart-button-container,.wallet-cart-button{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;flex-shrink:0;flex-grow:0}.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:8px 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)}@container wrapper (width >= 150px) and (width <= 500px){.wallet-cart-grid: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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:has(>.wallet-cart-button-container:nth-of-type(6)){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid: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:8px 0 0}.wallet-cart-grid:has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button-container:first-child{margin:0}.wallet-cart-grid:has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}@media screen and (max-width: 750px){.wallet-cart-grid{justify-content:flex-start;flex-direction:column;margin:0;max-width:none}.wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:8px 0 0;max-width:none}.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)}}@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:8px 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}",pc=".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;margin:0 5px 5px}.wallet-cart-button-container,.wallet-cart-button{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;flex-shrink:0;flex-grow:0}.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:8px 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)}@container wrapper (width >= 150px) and (width <= 500px){.wallet-cart-grid: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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: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: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:8px 0 0}.wallet-cart-grid: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: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:has(>.wallet-cart-button-container:nth-of-type(6)){justify-content:flex-start;flex-direction:column;margin:0}.wallet-cart-grid: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:8px 0 0}.wallet-cart-grid:has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button-container:first-child{margin:8px 0 0}.wallet-cart-grid:has(>.wallet-cart-button-container:nth-of-type(6)) .wallet-cart-button{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px)}@media screen and (max-width: 750px){.wallet-cart-grid{justify-content:flex-start;flex-direction:column;margin:0;max-width:none}.wallet-cart-button-container{width:100%;height:clamp(25px,var(--shopify-accelerated-checkout-button-block-size, 54px),55px);margin:8px 0 0;max-width:none}.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)}}@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:8px 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 mc(t){const e=kt({page:"cart",element:t});return Ln({type:"attributes",form:e})}class yc{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=mc(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 Ue;const Ct=class Pc extends gr{constructor(){super(),d(this,"instanceNumber",++Pc.instanceCount),d(this,"pageType",S.CartPage),d(this,"cartObserver",null),d(this,"dataSource",null),d(this,"wrapper"),d(this,"didInitiateRender",!1),O(this,Ue),this.wrapper=document.createElement("div")}static get observedAttributes(){return["access-token","has-selling-plan","requires-shipping"]}createDataSource(e){if(!this.cartToken)throw new Error("[AcceleratedCheckoutCart] cart cookie does not exist");const n=vt(),r=new xt({accessToken:this.accessToken,country:this.buyerCountry,locale:n.locale,withCarrierRates:e,cartPrepareMigrationEnabled:this.cartPrepareMigrationEnabled}),a=new yc(this,this.cartToken,r);this.dataSource=a,this.apiClient=r,this.i18n=n}async createWebComponents({shouldRefetchCartAttributes:e}){if(!this.walletConfigs)throw new Error("[AcceleratedCheckoutCart] walletConfigs does not exist");const n=Fo(this.walletConfigs,"AcceleratedCheckoutCart");if(!(n instanceof Array))throw new Error("[AcceleratedCheckoutCart] invalid walletConfigs found");const r=$.ButtonDisplay,a=l=>"".concat(l,":").concat(this.instanceNumber),i=await gc(this,{walletConfigs:n,startButtonDisplayBenchmark:l=>st(r,a(l))}),o=new Set([f.ApplePay,f.GooglePay]),s=i.some(l=>o.has(l.getInstrumentName()));return this.createDataSource(s),e&&await this.updateAttributes(),i.map(l=>{const c=l.getInstrumentName();return l.createWebComponent({walletContainer:this,dataSource:this.dataSource,i18n:this.i18n,apiClient:this.apiClient,pageType:this.pageType,containerInstanceNumber:this.instanceNumber,slot:"button-".concat(l.getInstrumentName()),onRendered:()=>g.instrumentLoaded({instrumentOrComponentName:c,result:"success",measurement:oe(r,a(c))})})})}async cartChangedCallback(){try{if(!this.dataSource&&this.cartToken){await this.render({shouldRefetchCartAttributes:!0});return}else if(!this.cartToken){g.cartTokenMissing({reason:"cartChangedCallback"});return}await this.updateAttributes()}catch(e){this.clearUI(),b.notify(e)}}async updateAttributes(){var e;if(!this.cartToken)return;const n=await((e=this.apiClient)==null?void 0:e.fetchCart({id:"gid://shopify/Cart/".concat(this.cartToken),instrumentName:f.Unknown}));if(!(n!=null&&n.id))throw new Error("[".concat(this.updateAttributes,"] received invalid cart"));this.hasSellingPlan=n.lineItems.some(r=>r.sellingPlanAllocation!=null),this.isShippingRequired=n.lineItems.some(r=>r.merchandise.requiresShipping)}async connectedCallback(){try{if(this.didInitiateRender)return;if(this.instanceNumber===1&&fr(this),V({event:B.CartInitCalled}),this.cartObserver=uc(()=>this.cartChangedCallback()),!this.cartToken){g.cartTokenMissing({reason:"connectedCallback"});return}await this.render({shouldRefetchCartAttributes:!1})}catch(e){this.clearUI(),b.notify(e)}}disconnectedCallback(){var e;(e=this.cartObserver)==null||e.disconnect()}async attributeChangedCallback(e,n,r){n!==r&&(mr(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 Ze("cart")}async render({shouldRefetchCartAttributes:e}){var n;if(this.hasLegacyCartCookie()){g.legacyCartCookie(),this.clearUI();return}this.didInitiateRender=!0;const r=Tt($.ButtonDisplay,"cart:".concat(this.instanceNumber)),a=await this.createWebComponents({shouldRefetchCartAttributes:e});if(this.clearUI(),a.length===0)return;const i=new DocumentFragment,o=this.getOrCreateShadowRoot(),s=document.createElement("style");s.innerHTML=[ga,hc].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 c=document.createElement("div");c.className="wallet-cart-grid ".concat(Ce.CONTAINER),fc()&&c.classList.add("wallet-cart-grid--vertical"),a.forEach(u=>{const h=document.createElement("div"),p=document.createElement("div"),y=document.createElement("slot");y.name="button-".concat(u.name),h.className="wallet-cart-button-container",p.className="wallet-cart-button",h.setAttribute("data-testid","grid-cell"),h.appendChild(p),p.appendChild(y),c.appendChild(h),i.appendChild(u)}),this.wrapper.appendChild(c),this.hasSellingPlan?this.showBuyerConsent(this.apiClient,this.i18n):this.hideBuyerConsent(),o.appendChild(this.wrapper),this.appendChild(i),g.instrumentLoaded({instrumentOrComponentName:"AcceleratedCheckoutCart",result:"success",measurement:r()})}getOrCreateShadowRoot(){return C(this,Ue)||L(this,Ue,this.attachShadow({mode:"closed"})),C(this,Ue)}hasLegacyCartCookie(){var e;return this.cartToken?(e=this.cartToken)==null?void 0:e.match(/^[a-z0-9]+$/):!1}extractStyles(){if(this.styleExtractorDisabled){gt()("shopify-support-debug")&&console.debug("[shopify-support-debug] styling backward compatibility disabled");return}const e=wa(this);if(e){_a(this,e);const n=this.getOrCreateShadowRoot(),r=document.createElement("style");r.innerHTML=pc,n.appendChild(r)}}};Ue=new WeakMap,d(Ct,"instanceCount",0);let nr=Ct;async function gc(t,{walletConfigs:e,startButtonDisplayBenchmark:n=()=>{}}){const r=Bo(t,zl(e));return(await Promise.all(r.map(a=>(n(a.getInstrumentName()),Wt({walletInstrument:a,instanceNumber:t.instanceNumber}))))).filter(a=>a!=null)}function fc(){return!!document.querySelector(".additional-checkout-buttons--vertical shopify-accelerated-checkout-cart")}le("shopify-accelerated-checkout-cart",nr);class bc{getInitialCart(){throw new Error('[NoOpDataSource] Unexpected call to "getCart"')}}const St=class Dc extends gr{constructor(){super(...arguments),d(this,"instanceNumber",++Dc.instanceCount)}get walletConfig(){return this.getAttribute("wallet-config")}get pageType(){return this.getAttribute("page-type")||S.Unknown}async connectedCallback(){var e;try{if(this.children.length)return;this.instanceNumber===1&&(fr(this),g.initStarted());const n=Tt($.ButtonDisplay,"dc:".concat(this.instanceNumber)),r=Uo(this.walletConfig,"WalletButton");if(!r)throw new oi("[WalletButton] No config provided.");const a=Et(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){g.initCompleted({result:"success"}),this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"success"}}));return}const i=a.getInstrumentName();this.i18n=vt(),this.apiClient=new xt({accessToken:this.accessToken,country:this.buyerCountry,locale:this.i18n.locale});const o=this.createWebComponent(a,this.i18n,this.apiClient,i,n);this.innerHTML="",this.appendChild(o),g.initCompleted({result:"success"}),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"}})),g.initCompleted({error:n}),b.notify(n)}}createWebComponent(e,n,r,a,i){const o=e.createWebComponent({walletContainer:this,dataSource:new bc,i18n:n,apiClient:r,containerInstanceNumber:this.instanceNumber,pageType:this.pageType});return o.onRendered=()=>{this.pciEnabled&&this.dispatchEvent(new CustomEvent("wallet-rendered",{detail:{status:"success"}})),g.instrumentLoaded({instrumentOrComponentName:a,result:"success",measurement:i()})},o}async eligibleToShow(e){return!(!yr(this,e)||(await e.loadWalletSDK(),!e.getPartnerSDKEligibility().eligible))}};d(St,"instanceCount",0);let ar=St;le("shopify-wallet-button",ar),Oa(b),Ma(b),g.startExporter();