var Ir=Object.create;var pt=Object.defineProperty;var Lr=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var Or=Object.getPrototypeOf,Dr=Object.prototype.hasOwnProperty;var Te=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var kr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pr(e))!Dr.call(t,o)&&o!==r&&pt(t,o,{get:()=>e[o],enumerable:!(n=Lr(e,o))||n.enumerable});return t};var Ie=(t,e,r)=>(r=t!=null?Ir(Or(t)):{},kr(e||!t||!t.__esModule?pt(r,"default",{value:t,enumerable:!0}):r,t));var tt=Te(et=>{"use strict";et.parse=En;et.serialize=Sn;var fn=Object.prototype.toString,pn=Object.prototype.hasOwnProperty,gn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,yn=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,wn=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,bn=/^[\u0020-\u003A\u003D-\u007E]*$/;function En(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},n=t.length;if(n<2)return r;var o=e&&e.decode||xn,s=0,i=0,a=0;do{if(i=t.indexOf("=",s),i===-1)break;if(a=t.indexOf(";",s),a===-1)a=n;else if(i>a){s=t.lastIndexOf(";",i-1)+1;continue}var c=Vt(t,s,i),m=Bt(t,i,c),d=t.slice(c,m);if(!pn.call(r,d)){var u=Vt(t,i+1,a),l=Bt(t,a,u);t.charCodeAt(u)===34&&t.charCodeAt(l-1)===34&&(u++,l--);var f=t.slice(u,l);r[d]=Cn(f,o)}s=a+1}while(sr;){var n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}function Sn(t,e,r){var n=r&&r.encode||encodeURIComponent;if(typeof n!="function")throw new TypeError("option encode is invalid");if(!gn.test(t))throw new TypeError("argument name is invalid");var o=n(e);if(!yn.test(o))throw new TypeError("argument val is invalid");var s=t+"="+o;if(!r)return s;if(r.maxAge!=null){var i=Math.floor(r.maxAge);if(!isFinite(i))throw new TypeError("option maxAge is invalid");s+="; Max-Age="+i}if(r.domain){if(!wn.test(r.domain))throw new TypeError("option domain is invalid");s+="; Domain="+r.domain}if(r.path){if(!bn.test(r.path))throw new TypeError("option path is invalid");s+="; Path="+r.path}if(r.expires){var a=r.expires;if(!vn(a)||isNaN(a.valueOf()))throw new TypeError("option expires is invalid");s+="; Expires="+a.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority){var c=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(c){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(r.sameSite){var m=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(m){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return s}function xn(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function vn(t){return fn.call(t)==="[object Date]"}function Cn(t,e){try{return e(t)}catch{return t}}});var Er=Te((_a,br)=>{"use strict";var C=function(t){if(t=t||{},this.Promise=t.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=t.domainReentrant||!1,this.domainReentrant){if(typeof process>"u"||typeof process.domain>"u")throw new Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=t.timeout||C.DEFAULT_TIMEOUT,this.maxOccupationTime=t.maxOccupationTime||C.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=t.maxExecutionTime||C.DEFAULT_MAX_EXECUTION_TIME,t.maxPending===1/0||Number.isInteger(t.maxPending)&&t.maxPending>=0?this.maxPending=t.maxPending:this.maxPending=C.DEFAULT_MAX_PENDING};C.DEFAULT_TIMEOUT=0;C.DEFAULT_MAX_OCCUPATION_TIME=0;C.DEFAULT_MAX_EXECUTION_TIME=0;C.DEFAULT_MAX_PENDING=1e3;C.prototype.acquire=function(t,e,r,n){if(Array.isArray(t))return this._acquireBatch(t,e,r,n);if(typeof e!="function")throw new Error("You must pass a function to execute");var o=null,s=null,i=null;typeof r!="function"&&(n=r,r=null,i=new this.Promise(function(p,S){o=p,s=S})),n=n||{};var a=!1,c=null,m=null,d=null,u=this,l=function(p,S,w){m&&(clearTimeout(m),m=null),d&&(clearTimeout(d),d=null),p&&(u.queues[t]&&u.queues[t].length===0&&delete u.queues[t],u.domainReentrant&&delete u.domains[t]),a||(i?S?s(S):o(w):typeof r=="function"&&r(S,w),a=!0),p&&u.queues[t]&&u.queues[t].length>0&&u.queues[t].shift()()},f=function(p){if(a)return l(p);c&&(clearTimeout(c),c=null),u.domainReentrant&&p&&(u.domains[t]=process.domain);var S=n.maxExecutionTime||u.maxExecutionTime;if(S&&(d=setTimeout(function(){u.queues[t]&&l(p,new Error("Maximum execution time is exceeded "+t))},S)),e.length===1){var w=!1;try{e(function(E,T){w||(w=!0,l(p,E,T))})}catch(E){w||(w=!0,l(p,E))}}else u._promiseTry(function(){return e()}).then(function(E){l(p,void 0,E)},function(E){l(p,E)})};u.domainReentrant&&process.domain&&(f=process.domain.bind(f));var A=n.maxPending||u.maxPending;if(!u.queues[t])u.queues[t]=[],f(!0);else if(u.domainReentrant&&process.domain&&process.domain===u.domains[t])f(!1);else if(u.queues[t].length>=A)l(!1,new Error("Too many pending tasks in queue "+t));else{var h=function(){f(!0)};n.skipQueue?u.queues[t].unshift(h):u.queues[t].push(h);var g=n.timeout||u.timeout;g&&(c=setTimeout(function(){c=null,l(!1,new Error("async-lock timed out in queue "+t))},g))}var y=n.maxOccupationTime||u.maxOccupationTime;if(y&&(m=setTimeout(function(){u.queues[t]&&l(!1,new Error("Maximum occupation time is exceeded in queue "+t))},y)),i)return i};C.prototype._acquireBatch=function(t,e,r,n){typeof r!="function"&&(n=r,r=null);var o=this,s=function(a,c){return function(m){o.acquire(a,c,m,n)}},i=t.reduceRight(function(a,c){return s(c,a)},e);if(typeof r=="function")i(r);else return new this.Promise(function(a,c){i.length===1?i(function(m,d){m?c(m):a(d)}):a(i())})};C.prototype.isBusy=function(t){return t?!!this.queues[t]:Object.keys(this.queues).length>0};C.prototype._promiseTry=function(t){try{return this.Promise.resolve(t())}catch(e){return this.Promise.reject(e)}};br.exports=C});var xr=Te((Ma,Sr)=>{"use strict";Sr.exports=Er()});var z=class extends Error{response;constructor(e,r){super(e),this.response=r}};var Le="",H="";function Y(t){function e(){return t.filter(n=>n.options.attributes).map(n=>n.options.attributes.mapTo(n.value)).flat().map(n=>[n.name,n.value])}function r(){return Object.fromEntries(t.filter(n=>!n.options.attributes&&n.value!==null&&n.value!==void 0&&n.value!==n.options.config.default).map(n=>[{name:n.name,value:n.value}]).flat().map(n=>[n.name,n.value]))}return{queryStringMap:e(),objectSettings:r()}}var Mr=1,Nr=(t,e,r)=>e?.status!==429;async function gt(t,e){let r=0,n=null,o=null,{maxRetries:s=Mr,retryDelay:i=500,shouldRetry:a=Nr,onBeforeRetry:c,onAfterRetry:m,shouldAbortRetry:d}=e,u=async()=>{try{return await t().then(l=>(n=null,o=null,l)).finally(()=>{r>0&&m(o,n,r)})}catch(l){let f=l;if(n="response"in f?f.response:null,o=n?null:f,r+=1,f.name==="AbortError"||!a(o,n,r)||r>s)throw f;let A=typeof i=="number"?i:i(r);if(await new Promise(h=>setTimeout(h,A)),d())throw new DOMException("Retry aborted","AbortError");return c(f,n,r),u()}finally{}};return u()}var Ur=(t,e,r)=>typeof t=="string"?t:e.decode(t,r);async function*yt({response:t,transformChunk:e,maxIterationsPerRead:r=1e4}){let n=t.body?.getReader();if(!n)throw new Error("Response body is null");let o=new TextDecoder,s="",i=0,a=c=>e({chunk:c,response:t,chunkIndex:i});try{for(;;){let{done:c,value:m}=await n.read();if(m&&(s+=Ur(m,o,{stream:!c})),c){/^\s*$/.test(s)||(yield a(s));break}let d=0;for(;;){let u=s.indexOf(Le);if(u===-1)break;let l=s.indexOf(H,u);if(l===-1)break;let f=s.slice(u,l+H.length);if(s=s.slice(l+H.length),yield a(f),i+=1,d+=1,d>=r)break}}}finally{n.releaseLock()}}var Fr=t=>{if(t.src){let e=document.createElement("script");e.src=t.src,document.head.appendChild(e)}},wt=(t,e)=>{let r=[];return t.forEach(n=>{if(n.src){if(n.getAttribute("type")=="module"){import(n.src).then(o=>{o.mount&&r.push(o.mount(e))});return}Fr(n)}}),r};var Q="v1.0";if(!import.meta)throw new Error("This script must be executed as an ESM module");var Pe="elements:refreshing",Z="elements:fetchError",Oe="elements:fetchRetrying",De="elements:fetchRetried",ke="elements:fetchComplete",$r="elements:connected",zr="elements:disconnected",_e="elements:rendered",Me="elements:attribute-changed",Ne="elements:setting-changed",q=class t extends HTMLElement{fetcher;$shadowRoot;abortController;domScripts=[];template;isInitialized=!1;refreshScheduled=!1;latestFetchId=0;options;settingsValues={};_logger;pluginDisconnectHandlers=[];elementInstanceIndex=0;static instanceCount={};constructor(e,r){super(),this.fetcher=r,this.$shadowRoot=this.attachShadow({mode:e.shadowMode||"closed"}),this._logger=e.logger||console,this.options=Object.freeze(e),this.template=document.createElement("template"),t.instanceCount[this.options.tagName]??=0}set logger(e){this._logger=e}getSettings(){return Object.entries(this.options.schema||{}).map(([r,n])=>({name:r,value:this.getSetting(r),options:n}))}getModifiedSettings(){return this.getSettings().filter(e=>e.name in this.settingsValues&&!this.isEventHandlerAttribute(e.name))}get eventMappings(){return{onError:e=>this.onFetchError(e)}}isEventHandlerAttribute(e){return e in this.eventMappings}getSetting(e){if(!this.options.schema||!this.options.schema[e])return;let r=this.options.schema[e];return this.settingsValues[e]??r.config.default}setSetting(e,r){if(!this.options.schema||!this.options.schema[e])return;let n=this.settingsValues[e],o=r,s=new CustomEvent(Ne,{composed:!1,bubbles:!0,detail:{name:e,oldValue:n,newValue:o}});this.$shadowRoot.dispatchEvent(s),this.settingsValues[e]=r,this.isInitialized&&this.refresh()}get tagName(){return this.options.tagName}get version(){return this.options.version??Q}connectedCallback(){if(this.options.singleton&&t.instanceCount[this.options.tagName]>0)return;t.instanceCount[this.options.tagName]++,this.elementInstanceIndex=t.instanceCount[this.options.tagName],this.pluginDisconnectHandlers=(this.options.plugins||[]).map(r=>r.onConnected?.(this)).filter(r=>r!=null),this.bindAttributeEventHandlers();let{initialHTML:e}=this.options;e&&(this.$shadowRoot.innerHTML=typeof e=="string"?e:e(this)),this.isInitialized=!0,this.$shadowRoot.dispatchEvent(new CustomEvent($r,{composed:!1,bubbles:!0})),this.refresh()}disconnectedCallback(){this.options.singleton&&this.elementInstanceIndex!==1||(t.instanceCount[this.options.tagName]--,this.pluginDisconnectHandlers.map(e=>{e()}),this.$shadowRoot.dispatchEvent(new CustomEvent(zr,{composed:!1,bubbles:!0})))}attributeChangedCallback(e,r,n){if(this.options.singleton&&this.elementInstanceIndex!==1)return;let o=new CustomEvent(Me,{composed:!1,bubbles:!0,detail:{name:e,oldValue:r,newValue:n}});this.$shadowRoot.dispatchEvent(o);let s=Object.entries(this.options.schema).find(([i,a])=>a.attributes&&a.attributes.names.indexOf(e)>=0);if(s&&s[1].attributes?.mapFrom){let i=s[1].attributes.mapFrom(e,n,this.settingsValues[s[0]]);this.setSetting(s[0],i)}}refresh(){this.refreshScheduled||(this.refreshScheduled=!0,queueMicrotask(()=>{this.refreshScheduled=!1,this.latestFetchId++,this.startFetch()}))}startFetch(){let e=this.latestFetchId;gt(()=>this.fetchHtml(),{...this.options.fetchOptions,shouldAbortRetry:()=>this.latestFetchId!==e,onBeforeRetry:(r,n,o)=>{let s=new CustomEvent(Oe,{composed:!1,bubbles:!0,detail:{error:r,response:n,attempt:o}});this.$shadowRoot.dispatchEvent(s)},onAfterRetry:(r,n,o)=>{let s=new CustomEvent(De,{composed:!1,bubbles:!0,detail:{error:r,response:n,attempt:o}});this.$shadowRoot.dispatchEvent(s)}}).catch(r=>{if(r.name==="AbortError")return;let n="";console.error("Error rendering component:",r),this.render(n)})}async fetchHtml(){this.abortController&&this.abortController.abort();let{abortController:e,generator:r}=this.fetcher.fetch(this.instrumentedFetch,this.getModifiedSettings());this.abortController=e;try{for await(let n of await r)this.render(n)}catch(n){if(n.name==="BulkElementError"&&n.elementError===!0){let o=new CustomEvent(Z,{composed:!1,bubbles:!0,detail:{url:n.fetchUrl,fetchOptions:n.fetchOptions,error:n,status:n.originalResult?.statusCode||n.originalResult?.status||n.originalResult?.data&&n.originalResult.data.statusCode||n.originalResult?.data&&n.originalResult.data.status,responseHeaders:n.responseHeaders}});this.$shadowRoot.dispatchEvent(o)}throw n}}instrumentedFetch=async(e,r)=>{let n=new CustomEvent(Pe,{composed:!1,bubbles:!0,detail:{url:e,fetchOptions:r}});this.$shadowRoot.dispatchEvent(n);let o,s=Date.now(),i;try{i=await fetch(e.toString(),r);let a=Date.now();o=i.status;let c=new CustomEvent(ke,{composed:!1,bubbles:!0,detail:{duration:a-s,endTime:a,responseHeaders:i.headers}});if(this.$shadowRoot.dispatchEvent(c),!i.ok)throw new z(`Fetch error. Status: ${i.status}`,i);return i}catch(a){if(a.name==="AbortError")throw a;let c;if(a instanceof z)try{a.response.headers.get("content-type")?.includes("application/json")&&(c=await a.response.json())}catch(A){this._logger?.warn("Failed to parse error response as JSON:",A)}this._logger?.error(`[ElementsWebComponent.fetch]: Error fetching, options: ${JSON.stringify(r)}, error:`,a);let m=a.name==="BulkElementError"&&a.elementError===!0,d=e,u=r,l=o;m&&(d=a.fetchUrl||e,u=a.fetchOptions||r,l=a.originalResult?.statusCode||a.originalResult?.status||o);let f=new CustomEvent(Z,{composed:!1,bubbles:!0,detail:{url:d,fetchOptions:u,error:c||a,status:l,responseHeaders:i?.headers}});throw this.$shadowRoot.dispatchEvent(f),a}};render(e){let r=this.$shadowRoot,n=Date.now(),s=typeof e=="string"?{template:e,data:void 0}:{template:e.html,data:e.data};this.template.innerHTML=s.template,this.domScripts.forEach(l=>{l&&l()}),this.domScripts=[];let i=this.template.content.cloneNode(!0);r.innerHTML="";let a=this.options.hostDefaultStyle??"inline-block";if(a!=="disabled"){let l=document.createElement("style");l.innerHTML=`:host { display: ${a}; all: initial;}`,r.appendChild(l)}r.appendChild(i);let c=r.querySelectorAll("script"),m=wt(c,r);this.domScripts.push(...m);let d=Date.now(),u=new CustomEvent(_e,{composed:!1,bubbles:!0,detail:{duration:d-n,endTime:d,shadowRoot:r,data:s.data}});setTimeout(()=>{this.$shadowRoot.dispatchEvent(u)},1)}onFetching(e){return this.$shadowRoot.addEventListener(Pe,e),()=>this.$shadowRoot.removeEventListener(Pe,e)}onFetched(e){return this.$shadowRoot.addEventListener(ke,e),()=>this.$shadowRoot.removeEventListener(ke,e)}onRendered(e){return this.$shadowRoot.addEventListener(_e,e),()=>this.$shadowRoot.removeEventListener(_e,e)}onFetchError(e){return this.$shadowRoot.addEventListener(Z,e),()=>this.$shadowRoot.removeEventListener(Z,e)}onFetchRetrying(e){return this.$shadowRoot.addEventListener(Oe,e),()=>this.$shadowRoot.removeEventListener(Oe,e)}onFetchRetried(e){return this.$shadowRoot.addEventListener(De,e),()=>this.$shadowRoot.removeEventListener(De,e)}onAttributeChanged(e){return this.$shadowRoot.addEventListener(Me,e),()=>this.$shadowRoot.removeEventListener(Me,e)}onSettingChanged(e){return this.$shadowRoot.addEventListener(Ne,e),()=>this.$shadowRoot.removeEventListener(Ne,e)}bindAttributeEventHandlers(){Object.entries(this.eventMappings).forEach(([e,r])=>{let n=this.getAttribute(e);n&&typeof window[n]=="function"&&r(window[n])})}};var bt="https://order.buywithprime.amazon.com/static/storefront-host/clickstream.browser.js",Et="clickstream:error";var Ue=class{withPublisher(){}event(){return this}with(){return this}track(){}setPersistence(){return this}setPersistentProperty(){return this}on(){return this}},St=async()=>typeof window>"u"||typeof process<"u"?{createClickstream:async()=>new Ue}:import(bt);function xt(t){return document.cookie.split("; ").find(r=>r.startsWith(t+"="))?.split("=")[1]}function vt(t,e,r){let n=new Date;n.setTime(n.getTime()+r*24*60*60*1e3);let o="expires="+n.toUTCString();document.cookie=t+"="+e+"; "+o+"; path=/"}var b=[];for(ee=0;ee<256;++ee)b.push((ee+256).toString(16).slice(1));var ee;function Ct(t,e=0){return(b[t[e+0]]+b[t[e+1]]+b[t[e+2]]+b[t[e+3]]+"-"+b[t[e+4]]+b[t[e+5]]+"-"+b[t[e+6]]+b[t[e+7]]+"-"+b[t[e+8]]+b[t[e+9]]+"-"+b[t[e+10]]+b[t[e+11]]+b[t[e+12]]+b[t[e+13]]+b[t[e+14]]+b[t[e+15]]).toLowerCase()}var te,Hr=new Uint8Array(16);function Fe(){if(!te&&(te=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!te))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return te(Hr)}var qr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),$e={randomUUID:qr};function jr(t,e,r){if($e.randomUUID&&!e&&!t)return $e.randomUUID();t=t||{};var n=t.random||(t.rng||Fe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var o=0;o<16;++o)e[r+o]=n[o];return e}return Ct(n)}var ze=jr;function At(t){let e=xt("ubid_ovr");e||(e=ze()),e&&(t.setPersistence(!0),t.setPersistentProperty("ubid",e),vt("ubid_ovr",e,365))}var Vr=(t,e)=>{let r={errorName:e.error_metric_name,errorValue:e.error_metric_value,pathname:window.location.pathname,userAgent:navigator.userAgent||""};t.error(`${Et} ${JSON.stringify(r)}`)},Rt=new Map,Tt=async({logger:t,clickstreamTenantArn:e,clickStreamTenantArn:r,applicationId:n,schemaName:o="store-front-schema",setUbid:s=!1,disableCaching:i})=>{let a=r??e,{createClickstream:c}=await St(),m=async()=>{let l=await c(a,n,o);return l.on("error",f=>{Vr(t,f)}),s&&At(l),l};if(i)return m();let d=JSON.stringify({tenantArn:a,applicationId:n,schemaName:o,setUbid:s}),u=Rt.get(d);return u||(u=m(),Rt.set(d,u)),u};function Br(t){let e=t.getElementById("context");if(!e?.textContent)return;let r=JSON.parse(e.textContent);return r.ClickstreamTenant||r.clickStreamTenantArn}var It=t=>new He(t),He=class{options;name="ClickstreamPlugin";elementOptions;constructor(e){this.options=e}configure(e){return this.elementOptions=e,e}getSkuOrIdFromTarget(e){return e.getAttribute("product-sku")||e.getAttribute("product-id")||e.getAttribute("product-external-id")||e.getAttribute("product-amazon-sku")}getTrackerDimensions(e,r){let{schemaName:n,project_id:o}=this.options,s={project_id:o,...e&&{product_sku:e}};if(n==="exs-elements-schema"){let{elementTagName:a,elementVersion:c,elementId:m}=this.options,d=m||e;return{...s,...d&&{element_id:d},...c&&{element_version:c},...a&&{element_tag_name:a}}}let i=this.options.widget_version??r;return{...s,...i&&{widget_version:i},...e&&{widget_id:e}}}onConnected(e){let r=this.elementOptions?.logger||console,n=[],o=s=>{let i=this.getSkuOrIdFromTarget(e),a=this.options.onRenderedEventName||"widget-load",c=this.getTrackerDimensions(i,e.tagName),d=(this.options.resolveClickStreamTenantArn||Br)(s.detail.shadowRoot);if(!d){r.error("ClickstreamTenantArn is could not be resolved from shadow root DOM");return}Tt({schemaName:this.options.schemaName,applicationId:this.options.applicationId,clickStreamTenantArn:d,logger:r,setUbid:!0}).then(u=>{u?.event(a).with(c).track()})};return n.push(e.onRendered(o)),()=>{n.forEach(s=>s())}}};var re=class t{name="GroupRefreshElementPlugin";static elements=[];shouldIncludeElement;constructor(e){this.shouldIncludeElement=e||(()=>!0)}onConnected(e){return this.shouldIncludeElement(e.getSettings())&&(t.elements.push(e),t.elements.forEach(r=>{r!=e&&r.refresh()}),e.onSettingChanged(()=>{t.elements.forEach(r=>{r!=e&&r.refresh()})})),()=>{t.elements=t.elements.filter(r=>r!=e),t.elements.forEach(r=>{r!=e&&r.refresh()})}}};var j;(function(t){t[t.stub=0]="stub"})(j||(j={}));var ne=()=>{},qe=class t{static createMetricsLogger(){return new t}async flush(){}setProperty(){}putDimensions(){}setDimensions(){}putMetric(){}setTimestamp(){}new(){}},je=class t{create(e,r){return{...console,child:(n,o)=>new t().create(n,o)}}},Ve={CTI:j,Unit:j,StandardMetricTypes:j,createExsLogger:()=>new je,createLogger:()=>({log:ne,warn:ne,error:ne}),createMetricsLogger:()=>new qe,enableLocalHostLogging:ne,safeStringify:JSON.stringify};var oe=async()=>typeof window>"u"||typeof process<"u"?(console.warn("@amzn/exs-client-logging is for client side logging, do not use it in node env."),console.log({LoggerModuleStub:Ve}),Ve):import("https://order.buywithprime.amazon.com/static/storefront-host/logger.browser.js");var k=class t{flusher;record={properties:{},dimensions:[]};constructor(e,r={}){this.flusher=e,this.record.properties=r}async flush(){return this.flusher(this.record)}setNamespace(){throw new Error("Cannot set Namespace, namespace is configure via the CTI in the constructor")}setProperty(e,r){return this.record.properties[e]=r,this}putDimensions(e){return this.record.dimensions.push(e),this}setDimensions(...e){return this.record.dimensions=e,this}putMetric(e,r,n){return this.record.metric={key:e,value:r,unit:n},this}setTimestamp(e){return this.record.timestamp=e,this}new(e){return new t(this.flusher,e)}};var se=class t extends k{constructor(e){super(t.flushImplementation(e))}static flushImplementation(e){return async r=>{let n=await e.then(o=>o.new());return Object.entries(r.properties).forEach(([o,s])=>n.setProperty(o,s)),n.setDimensions(...r.dimensions),r.metric&&n.putMetric(r.metric.key,r.metric.value,r.metric.unit),r.timestamp&&n.setTimestamp(r.timestamp),n.flush()}}};var ie=class t extends k{constructor(e={}){super(t.flushImplementation,e)}static async flushImplementation(e){console.log(e.metric,e.properties,e.dimensions,e.timestamp)}};var ae=class{logger;constructor(e){this.logger=e}create(e,r){return new Be(this.logger.then(n=>n.create(e,r)))}},Be=class t{logger;constructor(e){this.logger=e}info(e,...r){this.logger.then(n=>n.info(e,...r))}warn(e,...r){this.logger.then(n=>n.warn(e,...r))}error(e,...r){this.logger.then(n=>n.error(e,...r))}debug(e,...r){this.logger.then(n=>n.debug(e,...r))}child(e,r){return new t(this.logger.then(n=>n.child(e,r)))}};var ce=class{create(e,r){return new Ke({...r,name:e})}},Ke=class t{context;constructor(e){this.context=e}info(e,...r){console.info(e,r,this.context)}warn(e,...r){console.warn(e,r,this.context)}error(e,...r){console.error(e,r,this.context)}debug(e,...r){console.debug(e,r,this.context)}child(e,r){return new t({...r,name:e})}};var v;(function(t){t.CumulativeLayoutShift="CumulativeLayoutShift",t.LargestContentfulPaint="LargestContentfulPaint",t.FirstInputDelay="FirstInputDelay",t.InteractionToNextPaint="InteractionToNextPaint",t.FirstContentfulPaint="FirstContentfulPaint",t.TimeToFirstByte="TimeToFirstByte",t.RequestCount="RequestCount",t.RequestStatus="RequestStatus",t.RequestLatency="RequestLatency",t.RequestError="RequestError",t.TemplateRequestCount="TemplateRequestCount",t.TemplateRequestStatus="TemplateRequestStatus",t.TemplateRequestLatency="TemplateRequestLatency",t.TemplateRequestError="TemplateRequestError",t.LoadCount="LoadCount",t.LoadError="LoadError",t.LoadLatency="LoadLatency",t.RenderCount="RenderCount",t.RenderError="RenderError",t.RenderLatency="RenderLatency",t.UserPerceivedLatency="UserPerceivedLatency",t.InteractionCount="InteractionCount",t.InteractionError="InteractionError",t.InteractionLatency="InteractionLatency",t.ImpressionCount="ImpressionCount",t.ImpressionError="ImpressionError",t.ImpressionLatency="ImpressionLatency",t.JSCallCount="JSCallCount",t.JSCallError="JSCallError"})(v||(v={}));var x;(function(t){t.Seconds="Seconds",t.Microseconds="Microseconds",t.Milliseconds="Milliseconds",t.Bytes="Bytes",t.Kilobytes="Kilobytes",t.Megabytes="Megabytes",t.Gigabytes="Gigabytes",t.Terabytes="Terabytes",t.Bits="Bits",t.Kilobits="Kilobits",t.Megabits="Megabits",t.Gigabits="Gigabits",t.Terabits="Terabits",t.Percent="Percent",t.Count="Count",t.BytesPerSecond="Bytes/Second",t.KilobytesPerSecond="Kilobytes/Second",t.MegabytesPerSecond="Megabytes/Second",t.GigabytesPerSecond="Gigabytes/Second",t.TerabytesPerSecond="Terabytes/Second",t.BitsPerSecond="Bits/Second",t.KilobitsPerSecond="Kilobits/Second",t.MegabitsPerSecond="Megabits/Second",t.GigabitsPerSecond="Gigabits/Second",t.TerabitsPerSecond="Terabits/Second",t.CountPerSecond="Count/Second",t.None="None"})(x||(x={}));var Ge=!1;function Lt(){Ge=!0}function le(t,e){if(Ge)return new ce;let r=oe().then(n=>n.createExsLogger(n.CTI[t],e));return new ae(r)}function ue(t){let e=oe().then(r=>r.createMetricsLogger(r.CTI[t]));return Ge?new ie:new se(e)}function Pt(){oe().then(t=>t.enableLocalHostLogging())}var _=()=>import.meta.url;var Wr=t=>{try{return performance.getEntriesByType("resource").find(n=>n.name===t)?.serverTiming}catch{return null}},Ot=(t=_())=>{let e=Wr(t),r=null,n=null;if(e){let o=s=>{let i=e.find(a=>a.name===s);return i?i.description:null};r=o("cdn-rid"),n=o("tux-rid")}return{"cdn-rid":r,"tux-rid":n}},de=t=>t?{"cdn-rid":t.get("x-amz-cf-id"),"tux-rid":t.get("x-tuxedo-id")}:null;var Dt=(t,e={})=>new We(t,e),We=class{cti;name="LumberjackPlugin";logFactory;logger;metrics;properties;dimensions;constructor(e,{consoleOnlyLogging:r,localHostLogging:n,properties:o,dimensions:s}={}){this.cti=e,r&&Lt(),n&&Pt(),this.logFactory=le(this.cti),this.metrics=ue(this.cti),this.properties=o||{},this.dimensions=s||[]}configure(e){return this.logger=this.logFactory.create(e.tagName),{...e,logger:this.logger}}onConnected(e){let r=Date.now(),n=Ot(),o=typeof this.properties=="function"?this.properties(e):this.properties;this.logger&&(e.logger=this.logger.child(e.tagName,o));let s=(h,g)=>{let y=this.dimensions.length?this.dimensions:[{}];return h.setDimensions(...y,...y.map(p=>({...p,...g}))),h},i=()=>{let h=this.metrics.new();return h.setProperty("WebComponentTraceIds",n),Object.entries(o).forEach(([g,y])=>{h.setProperty(g,y)}),this.dimensions.length>0&&h.setDimensions(...this.dimensions),h.setTimestamp(Date.now()),h};i().putMetric(v.RequestCount,1,x.Count).flush().catch(console.error);let a=performance.getEntriesByName(import.meta.url,"resource");if(a.length>0){let h=a[0];i().putMetric(v.LoadLatency,h.responseEnd-h.fetchStart,x.Milliseconds).flush().catch(console.error)}let c=[];function m(h){r=Date.now()}c.push(e.onSettingChanged(m));function d(h){i().putMetric(v.TemplateRequestCount,1,x.Count).flush().catch(console.error)}c.push(e.onFetching(d));function u(h){let g=h?.detail?.endTime,y=g||Date.now(),p=Math.max(0,y-r),S=de(h.detail.responseHeaders);i().setProperty("TraceIds",S).putMetric(v.RequestLatency,p,x.Milliseconds).flush().catch(console.error),i().setProperty("TraceIds",S).putMetric(v.TemplateRequestLatency,h.detail.duration,x.Milliseconds).flush().catch(console.error),s(i(),{code:"2XX"}).setProperty("TraceIds",S).putMetric(v.TemplateRequestStatus,1,x.Count).flush().catch(console.error)}c.push(e.onFetched(u));function l(h){let g=h.detail.status?`${h.detail.status.toString().substring(0,1)}XX`:"000",y=de(h.detail.responseHeaders);s(i(),{code:g}).setProperty("TraceIds",y).putMetric(v.TemplateRequestStatus,1,x.Count).flush().catch(console.error),i().setProperty("Error",h.detail.error).setProperty("TraceIds",y).putMetric(v.TemplateRequestError,1,x.Count).flush().catch(console.error)}c.push(e.onFetchError(l));function f(h){let g=h.detail.response?.status,y=de(h.detail.response?.headers);i().setProperty("Status",g).setProperty("TraceIds",y).putMetric("TemplateRequestRetryCount",1,x.Count).flush().catch(console.error)}c.push(e.onFetchRetrying(f));function A(h){let g=h?.detail?.endTime,y=g||Date.now(),p=Math.max(0,y-r);i().putMetric(v.RenderLatency,p,x.Milliseconds).flush().catch(console.error)}return c.push(e.onRendered(A)),()=>{c.forEach(h=>h())}}};var kt=()=>new Je,Je=class{name="TargetIdPlugin";constructor(){}configure(e){let r={type:"text",label:"Target Id",config:{default:null}},n=e.bulk?.enabled&&(!e.bulk.splitOnSettings||e.bulk.splitOnSettings.indexOf("targetId")<0);return{...e,bulk:n?{...e.bulk,splitOnSettings:[...e.bulk.splitOnSettings||[],"targetId"]}:e.bulk,schema:{...e.schema,targetId:r}}}onConnected(e){let r=document.querySelector(`script[src='${import.meta.url}']`),n=e.getAttribute("targetId")||r?.getAttribute("data-target-id")||window?.amazonElements?.targetId;return n?(e.setSetting("targetId",n),()=>{}):(console.error("WARNING: Target Id could not be resolved from script tag or global config"),()=>{})}};function M(t){return t.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase()}function I(t){return t!=null}function Jr(t,e){if(!I(e))return;let r=t;if(!r?.config?.options)return;let n=r.config.options.map(o=>o.value).find(o=>o.toString()==e);return I(n)?n:void 0}function Xr(t,e){let r=t;if(!I(e))return;let n=parseFloat(e);if(!isNaN(n)&&!(I(r.config.max)&&n>r.config.max)&&!(I(r.config.min)&&n{let n=N(e,r?.toString());return I(n)?[{name:t,value:n.toString()}]:[]}}function rn(t){return(e,r)=>N(t,r)}function _t(t,e){if(!en.has(e.type))return e;let r=M(t);return{...e,attributes:{names:[r],mapTo:tn(r,e),mapFrom:rn(e)}}}function Mt(t,e){return e.type!=="font"?e:{...e,attributes:nn(t,e)}}function nn(t,e){let n=e.config.capture||["size","weight"],o=n.indexOf("size")>=0,s=n.indexOf("weight")>=0,i=M(t);return{names:n.concat(["vendor","family"]).map(a=>`${i}-${a}`),mapTo:a=>{let c=a,m=[];return c.vendor&&m.push({name:`${i}-vendor`,value:c.vendor.toString()}),c.family&&m.push({name:`${i}-family`,value:c.family.toString()}),o&&c.size!==null&&c.size!==void 0&&m.push({name:`${i}-size`,value:c.size.toString()}),s&&c.weight!==null&&c.weight!==void 0&&m.push({name:`${i}-weight`,value:c.weight.toString()}),m},mapFrom:(a,c,m)=>{let d=typeof m=="object"?{...m}:{};return a===`${i}-vendor`&&(d.vendor=c),a===`${i}-family`&&(d.family=c),o&&a===`${i}-size`&&(d.size=parseInt(c,10)),s&&a===`${i}-weight`&&(d.weight=parseInt(c,10)),d}}}var on=new Map([["checkbox-group",!0],["product",!0],["toggle-group",!0],["reference",!0]]);function sn(t,e){return r=>{let n=r&&r.toString().split(",").map(o=>N(e,o)).filter(o=>o&&o!=e.config.default);return n&&n!==e.config?.default?[{name:t,value:n.toString()}]:[]}}function an(t){return(e,r)=>{let n=r?.split(",").map(o=>N(t,o)).filter(o=>o);return n&&n.length>0&&n||void 0}}function Nt(t,e){if(!on.has(e.type))return e;let r=M(t);return{...e,attributes:{names:[r],mapTo:sn(r,e),mapFrom:an(e)}}}var cn=()=>new Xe,Xe=class{name="ExsSchemaPlugin";constructor(){}configure(e){let r=Object.fromEntries(Object.entries(e.schema).map(([n,o])=>{let s=_t(n,o);return s=Mt(n,s),s=Nt(n,s),[n,s]}));return{...e,schema:r}}},Ut=cn;function Ft(t){let e=un(t),r=[];return t.pluginOptions?.targetId!==!1&&r.push(kt()),t.pluginOptions?.exsSchema!==!1&&r.push(Ut()),e.plugins&&r.push(...e.plugins),e.plugins=r,r.reduce((o,s)=>s.configure&&s.configure(o)||o,e)}function ln(t){let e=t.pathname.split("/");return e.length==5&&e[1].toLowerCase()==="elements"&&e[4].toLowerCase()==="web-component.js"&&e[3]||void 0}function un(t){let e=dn(t.schema||{}),r=new URL(_()),n=t.version??ln(r)??Q,o=t.alias??n;return{...t,schema:e,version:n,renderPath:`/elements/${t.tagName}/${o}`}}function dn(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>typeof e=="object"))}var me=class{fetchUrl;constructor(e){this.fetchUrl=e}fetch(e,r){let{queryStringMap:n,objectSettings:o}=Y(r),s=Object.keys(o).length>0,i=Object.keys(n).length>0,a=`${this.fetchUrl}${i?"?":""}${new URLSearchParams(n).toString()}`,c=new AbortController,{url:m,options:d}={url:new URL(a),options:{method:s?"POST":void 0,body:s?JSON.stringify(o):void 0,signal:c.signal}};return{abortController:c,generator:e(m,d).then(u=>yt({response:u,transformChunk:({chunk:l,response:f})=>f.headers.get("content-type")!=="text/json"?l:JSON.parse(l)[0]}))}}};function $t(t){async function*e(){yield t}return e()}var he=class extends Error{elementError=!0;originalResult;fetchUrl;fetchOptions;responseHeaders;constructor(e,r,n,o,s){super(e),this.name="BulkElementError",this.originalResult=r,this.fetchUrl=n,this.fetchOptions=o,this.responseHeaders=s}};var mn=["bp-1e719710-061b-48d0-8f8e-75da204127f4","bp-acb8dc3f-72ea-4008-8b67-dbf3c6250832","bp-2d340a5a-9ff2-4a5c-a9dd-3abc2dcf8297"],Ye=class{fetchUrl;splitOnSettings;maxBatchSize;fetchers=new Map;constructor(e,r=[],n=50){this.fetchUrl=e,this.splitOnSettings=r,this.maxBatchSize=n}fetch(e,r){let n=[];for(let s of this.splitOnSettings){let i=r.find(a=>a.name===s)?.value;i!=null&&n.push([s,i.toString()])}let o=JSON.stringify(n);if(!this.fetchers.get(o)){let s=`${this.fetchUrl.pathname}?${new URLSearchParams(n).toString()}`;this.fetchers.set(o,new Qe(new URL(s,this.fetchUrl),this.maxBatchSize))}return this.fetchers.get(o).fetch(e,r)}},Qe=class{fetchUrl;maxBatchSize;fetchTimeout;parameterList=[];constructor(e,r){this.fetchUrl=e,this.maxBatchSize=r}isErrorResult(e){return!e||typeof e!="object"?!1:e.error||e.status==="error"||e.success===!1||e.statusCode&&e.statusCode>=400||e.status&&typeof e.status=="number"&&e.status>=400||e.message&&e.type==="error"||e.data&&e.data.error&&e.data.statusCode}fetch(e,r){let n=r.find(a=>a.name==="targetId");n?.value&&mn.includes(n.value.toString())&&(this.maxBatchSize=5);let s=new AbortController,i=new Promise((a,c)=>{let{queryStringMap:m,objectSettings:d}=Y(r),u={attributes:Object.fromEntries(m),settings:d};this.parameterList.push({payload:u,abortController:s,resolve:a,reject:c}),s.signal.addEventListener("abort",()=>{let l=new Error("Aborted");l.name="AbortError",c(l)}),this.fetchTimeout&&clearTimeout(this.fetchTimeout),this.fetchTimeout=setTimeout(async()=>{let l=this.parameterList;this.parameterList=[];let f=l.length,A=Math.ceil(f/this.maxBatchSize);for(let h=0;hw));e(new URL(`${this.fetchUrl}`),{method:"POST",body:S}).then(w=>{let E=w.headers;return w.text().then(T=>({results:JSON.parse(T),headers:E}))}).then(({results:w,headers:E})=>{for(let T=0;T{for(let E=0;E$t(typeof a=="string"?{html:a,settings:{}}:a))}}},zt=Ye;function Ht(t,e,r){let n=new URL(t);return n.pathname=n.pathname.replace(e,r),n}var qt=t=>{let e=Ft(t),r=new URL(_()),n=new URL(r);n.pathname=n.pathname.replace(/(\/elements\/)([^\/]+)/,`$1${t.tagName}`),n.search="",n.hash="";let o=Ht(n,/\/web-component\.js$/,"/render-bulk"),s=Ht(n,/\/web-component\.js$/,"/render"),i=e.bulk?.enabled?new zt(o,e.bulk.splitOnSettings,e.bulk.max):new me(s);return class extends q{constructor(){super({...e,renderPath:e.renderPath},i)}static get schema(){return e.schema}static get observedAttributes(){return Object.entries(e.schema).map(([m,d])=>d.attributes?.names||[]).flat()}}},Ze=t=>{let e=qt(t);if(!customElements.get(t.tagName))try{customElements.define(t.tagName,e)}catch{customElements.define(t.tagName,class extends e{})}return e};var jt={$schema:"https://cdn.us-east-1.prod.moon.dubai.aws.dev/wPjwkduJWkX3/PP8ofMnZY5LC/latest/schemas/settings-schema.json/index.json",display:{type:"text",label:"Delivery Message",config:{default:null}},productSku:{label:"Product selection placeholder",type:"text",config:{default:null,labelStyle:"floating",placeholder:"placeholder"}},productId:{label:"Product selection placeholder",type:"text",config:{default:null,labelStyle:"floating",placeholder:"placeholder"}},productExternalId:{label:"Product selection placeholder",type:"text",config:{default:null,labelStyle:"floating",placeholder:"placeholder"}},productAmazonSku:{label:"Product selection placeholder",type:"text",config:{default:null,labelStyle:"floating",placeholder:"placeholder"}},productMarketplaceId:{label:"Product selection placeholder",type:"text",config:{default:null,labelStyle:"floating",placeholder:"placeholder"}},orderId:{type:"text",label:"Display a delivery promise from an order",config:{default:null,labelStyle:"floating",placeholder:"placeholder"}},messageType:{label:"Delivery Message Display Type",type:"radio",config:{default:"delivery-estimate",options:[{label:"None",value:"none"},{label:"Options Available",value:"options-available"},{label:"Delivery Estimate",value:"delivery-estimate"},{label:"Delivery Estimate with Returns",value:"delivery-estimate-with-returns"}]}},font:{type:"font",label:"Delivery Message font settings",config:{default:{size:16,weight:400,vendor:"system",family:"Amazon Ember, sans-serif"}}},colorMode:{label:"Delivery Message background",type:"radio",config:{default:"light",options:[{label:"Light",value:"light"},{label:"Dark",value:"dark"}]}},fontSizeBase:{type:"number",label:"Delivery Message font base size",config:{default:14,min:12,max:18,help:{body:"The font base size sets the element rem size."}}},textColor:{label:"Delivery Message text color",type:"color",config:{default:""}},contentAlignment:{label:"Delivery Message content alignment",type:"radio",config:{default:"left",options:[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}]}},context:{label:"Delivery message element for Product in cart or checkout",type:"text",config:{default:null}},showPopup:{config:{type:"checkbox",label:"Provider for user sign in",default:!1}},quantity:{type:"number",label:"Defines the quantity selected in cart",config:{default:1}}};var cr=Ie(tt(),1);var An="https://cdn.us-east-1.prod.moon.dubai.aws.dev/6YXKZgpfGuV9/WPsvsMISe4Bu/1/KZRLatEHlh/scripts/shared-state.js",fe=class{sharedState;state;constructor(e,r){this.state=r,!(typeof window>"u")&&(this.sharedState=import(`${An}?name=${e}`).then(n=>n.default),this.sharedState.then(n=>{this.state=n.getState(),n.subscribe(o=>{this.state=o})}).catch(n=>console.log(n)))}getState(){return this.state}setState(e){if(e===void 0)throw new Error("dont set undefined state!");this.state={...this.state,...e},this.sharedState?.then(r=>(r.setState({...this.state,...e}),r))?.then(r=>{this.state=r.getState(),r.subscribe(n=>{this.state=n})}).catch(r=>console.log(r))}subscribe(e){if(!this.sharedState)return()=>{};let r=this.sharedState.then(n=>n.subscribe(e));return()=>r.then(n=>n()).catch(n=>console.log(n))}};var U=class t{cacheName;ttlInMinutes;static getExpireTime(e){return Date.now()+e*60*1e3}constructor(e,r){this.cacheName=e,this.ttlInMinutes=r}get(e){let r=window.localStorage.getItem(this.getCacheKey(e));if(!r)return;let n=JSON.parse(r);if(this.isExpired(n)){this.evict(e);return}return n.value}put(e,r){window.localStorage.setItem(this.getCacheKey(e),JSON.stringify({value:r,expireTime:t.getExpireTime(this.ttlInMinutes)}))}evict(e){window.localStorage.removeItem(this.getCacheKey(e))}getCacheKey(e){return`${e}-${this.cacheName}`}isExpired(e){return e.expireTime<=Date.now()}};var or=Ie(tt(),1);var Kt=["3001","3002"],rt="https://ident-gamma.tuxedo.prod.barossa.dubai.aws.dev",nt="https://ident.tuxedo.prod.barossa.dubai.aws.dev",Gt="https://cdn.elements.amazon/elements/amazon-sign-in/v1.0",ot="amazon_Login_pkce_params";var Wt=["ident-gamma.tuxedo.prod.barossa.dubai.aws.dev","localhost"],Jt="SignInElement",Rn="SignInElementGamma",Xt=()=>{try{let t=new URL(import.meta.url);return Wt.includes(t.hostname)||Wt.includes(window.location.hostname)?Rn:Jt}catch(t){return console.warn("Failed to determine CTI from script URL, defaulting to production CTI:",t),Jt}},Tn=["tuxedo.prod.barossa.dubai.aws.dev","localhost"],pe=()=>Tn.some(t=>window.location.hostname.includes(t)),Yt=()=>{let t=window.location.origin,{hostname:e,port:r}=window.location;return e==="localhost"&&Kt.includes(r)?t:t===rt?rt:t===nt?Gt:nt};var Qt=Xt(),In=le(Qt),Ln=In.create("UserAuthLibrary"),Pn=ue(Qt);function R(t,e){Ln.error({label:`Error: ${t}`,error:e,userAgent:navigator.userAgent,href:window.location.href})}async function st(t,e,r,n){let o=Pn.new();return o.setTimestamp(Date.now()),o.putDimensions({Operation:r,IsTestStore:String(pe())}),o.putMetric(t,e,n),o.flush()}async function F(t,e){await st("Count",1,t,"Count"),await st("Latency",Date.now()-e,t,"Milliseconds")}async function P(t){return st("Error",1,t,"Count")}var ge="Code exchange failed",Zt="LwA initialization failed",it="LwA initialization failed",er="Invalid URL parameters on static page",tr="Invalid state",rr="Failed to parse PKCE cookie",at="Failed to fetch User Profile through API",nr="Error handling auth code exchange";var On="profile:default_shipping_address profile profile:mobile_number buywithprime::merchant_orders",ct="amazon-root",lt="amazon-login-sdk",Dn="https://assets.loginwithamazon.com/sdk/na/login1.js",kn="https://api.amazon.com/user/profile";function _n(){let t=document.getElementById(ct);return t||(t=document.createElement("div"),t.id=ct,document.body.appendChild(t)),t}function Mn(t){let e=document.getElementById(lt);e||(e=document.createElement("script"),e.type="text/javascript",e.async=!0,e.id=lt,e.src=Dn,t.appendChild(e))}function Nn(){return document.getElementById(ct)!==null&&document.getElementById(lt)!==null}async function V(t){return new Promise(e=>{if(Nn()){e("Success");return}window.onAmazonLoginReady=()=>{amazon.Login.setClientId(t),e("Success")};let r=_n();Mn(r)})}async function sr(){let t=new Uint8Array(96);crypto.getRandomValues(t);let e=btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"").substring(0,128),n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n),s=btoa(String.fromCharCode(...new Uint8Array(o))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return{codeVerifier:e,codeChallenge:s}}function ye(t,e,r){let n={path:"/",maxAge:600},o={client_id:e,code_verifier:t};r&&(o.redirect_uri=r),document.cookie=(0,or.serialize)("amazon_Login_pkce_params",JSON.stringify(o),n)}function we(t,e){amazon.Login.authorize({...t,response_type:"code",scope:On,pkce:!0,code_challenge_method:"S256"},e)}function ir(t){return new Promise((e,r)=>{amazon.Login.retrieveToken(t,n=>{n.error&&r(n.error),e(n.access_token)})})}async function ar(t){let e=new URL(kn);e.searchParams.append("access_token",t);let r=await fetch(e,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){let n=new Error(`${at}: ${r.status} ${r.statusText}`);throw R(at,n),n}return r.json()}var be=class t{static idPAssociationsCache=new U("idPAssociations",60);async loadIdPAssociations(e){let r=Yt(),n=await fetch(`${r}/idp-associations?targetId=${encodeURIComponent(e)}`,{method:"GET"});if(!n.ok)throw new Error(`Error fetching IdP associations: ${JSON.stringify(n)}`);return n.json()}async getIdPAssociations(e){let r=t.idPAssociationsCache.get(e);if(r)return r;let n=await this.loadIdPAssociations(e);return t.idPAssociationsCache.put(e,n),n}};var Ee=class extends be{getLwaAssociationByClientId(e,r){if(e)return e.filter(n=>n.clientId!==null&&r===n.clientId).pop()}getDefaultLwaAssociation(e){if(e)return e.filter(r=>r.clientId!==null).shift()}async getLwaAssociation(e,r){let n=Date.now(),s=(await this.getIdPAssociations(e)).lwaAssociations,i=r?this.getLwaAssociationByClientId(s,r):this.getDefaultLwaAssociation(s);if(!i||!i.clientId||!i.redirectEndpoint)throw new Error(`No valid LwA association is found for ${e}`);return await F("GetLwaAssociation",n),i}};var $=class t extends fe{targetId;static userDetailsCache=new U("amazonUser",59);static lwaAssociationAccessor=new Ee;static getUserAuthState(e){let r=t.userDetailsCache.get(e);return{targetId:e,isAuthenticated:r!==void 0,user:r}}getCodeVerifierAndDeleteCookie(){let r=(0,cr.parse)(document.cookie)[ot];r&&(document.cookie=`${ot}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`);try{return JSON.parse(decodeURIComponent(r||"{}")).code_verifier||null}catch(n){return R(rr,n),null}}async getAccessToken(e,r){if(window.elementsAmazon?.elements?.signIn?.lwaConfig?.getAccessToken){let n;return e&&(n=this.getCodeVerifierAndDeleteCookie(),!n)?Promise.reject("Code verifier missing"):window.elementsAmazon.elements.signIn.lwaConfig.getAccessToken(e,r,n)}return e?ir(e):Promise.reject("Auth code undefined")}async handleAuthCodeExchange(e,r,n){try{let o=await this.getAccessToken(e,r),s=await this.getUserDetails(o);t.userDetailsCache.put(this.targetId,s),n&&await F("SignIn",n),this.setState({isAuthenticated:!0,user:s})}catch(o){throw o!=="Auth code undefined"&&(await P("HandleAuthCodeExchange"),R(ge,o)),o}}async handleAuthCodeExchangeAndRedirect(e,r,n,o){await this.handleAuthCodeExchange(e,r,o),n&&window.location.assign(n)}async signInViaAccountLinking(){if(t.getUserAuthState(this.targetId).isAuthenticated)return Promise.resolve(!0);try{let e=Date.now();return await this.handleAuthCodeExchange(),await F("AccountLinkSignIn",e),Promise.resolve(!0)}catch(e){return R(nr,e),Promise.resolve(!1)}}resolveLwaAssociation(e){return t.lwaAssociationAccessor.getLwaAssociation(e,window.elementsAmazon?.elements?.signIn?.lwaConfig?.clientId)}constructor({targetId:e}){super(`UserAuth_${e}`,t.getUserAuthState(e)),this.targetId=e,this.signInViaAccountLinking()}getState(){return this.setState(t.getUserAuthState(this.targetId)),this.state}async signOut(e){let r=Date.now();if(typeof amazon>"u")try{let n=await this.resolveLwaAssociation(this.targetId);await V(n.clientId)}catch(n){await P("ResolveLwaAssociation"),R(it,n);return}amazon.Login.logout(),t.userDetailsCache.evict(this.targetId),this.setState({isAuthenticated:!1,user:void 0}),await F("SignOut",r),e&&window.location.assign(e)}async signIn(e){if(await this.signInViaAccountLinking()){e&&window.location.assign(e);return}let r=Date.now(),n;try{n=await this.resolveLwaAssociation(this.targetId),await V(n.clientId)}catch(i){await P("ResolveLwaAssociation"),R(it,i);return}let{codeVerifier:o,codeChallenge:s}=await sr();this.storeCodeVerifierCookie(o,n),this.signInWithLwa(n,s,e,r)}async getUserDetails(e){let r=await ar(e),n=r.shipping_address?.postal_code,o=r.user_id,s=n&&pe()?{postalCode:n}:void 0;return{name:r.name,lwaAccessToken:e,shippingAddress:s,userId:o}}};var Se=class extends ${signInWithLwa(e,r,n,o){we({popup:!0,code_challenge:r},async i=>{if(i.error){await P("LwaAuth"),R(Zt,i.error);return}await this.handleAuthCodeExchangeAndRedirect(i.code,void 0,n,o)})}storeCodeVerifierCookie(e,r){ye(e,r.clientId)}constructor({targetId:e}){super({targetId:e})}};var xe=class extends ${encodeStateParam(e){return btoa(JSON.stringify(e))}decodeStateParam(e){let r=JSON.parse(atob(e));if(r.redirectUrl&&r.lwaClientId)return r;throw tr}extractAuthCodeAndStateFromQueryParam(){let e=new URL(window.location.href),r=new URLSearchParams(e.search),n=r.get("code"),o=r.get("state");if(n===null||o===null)throw er;return{code:n,state:o}}onStaticPage(e){let r=new URL(window.location.href),n=new URL(e);return r.origin+r.pathname===n.origin+n.pathname}async startCodeExchange(){try{let e=await this.resolveLwaAssociation(this.targetId),{redirectEndpoint:r}=e;if(!this.onStaticPage(r)||window.location.search==="")return;let{code:n,state:o}=this.extractAuthCodeAndStateFromQueryParam(),{lwaClientId:s,redirectUrl:i,signInStartTime:a}=this.decodeStateParam(o);await V(s),await this.handleAuthCodeExchangeAndRedirect(n,r,i,a)}catch(e){await P("StartCodeExchange"),R(ge,e)}}signInWithLwa(e,r,n,o){we({popup:!1,state:this.encodeStateParam({redirectUrl:n||window.location.href,lwaClientId:e.clientId,signInStartTime:o}),code_challenge:r},e.redirectEndpoint)}storeCodeVerifierCookie(e,r){ye(e,r.clientId,r.redirectEndpoint)}constructor({targetId:e}){super({targetId:e}),this.startCodeExchange()}};var Fn=t=>{window.__globalAuthProvider=t},$n=()=>window.__globalAuthProvider,lr=(t,e=!1)=>{let r=$n();return r||(r=e?new Se({targetId:t}):new xe({targetId:t}),Fn(r)),r};var ut=class{pluginOptions;constructor(e){this.pluginOptions=e}configure(e){return{...e,schema:{...e.schema,authStatus:{config:{default:{}}}}}}onConnected(e){let r=e.getSetting("targetId");if(!r)throw new Error(`Target Id missing from element, element: ${e.tagName}`);let n=e.getSetting("showPopup"),o=lr(`${r}`,n);e.setSetting("authStatus",o.getState());let s=this.pluginOptions.triggerRefresh?o.subscribe(i=>e.setSetting("authStatus",i)):void 0;return()=>s&&s()}},ur=t=>new ut(t);var dr={label:"Badge",key:"bwp-badge",path:"elements/bwp-badge/render",icon:"prime-badge",singleton:!1};var ve={label:"Delivery Message",key:"amazon-delivery-message",path:"elements/amazon-delivery-message/render",icon:"delivery-message",singleton:!1};var mr={$schema:"https://cdn.us-east-1.prod.moon.dubai.aws.dev/wPjwkduJWkX3/PP8ofMnZY5LC/latest/schemas/metadata.json/index.json",label:"Delivery Card",key:"amazon-delivery-card",path:"elements/amazon-delivery-card/render",icon:"delivery-card",singleton:!1,enablePersistence:!0};var hr={label:"Offer Card",key:"amazon-offer-card",path:"elements/amazon-offer-card/render",icon:"offer-card",singleton:!1};var Ce={applicationId:"STORE_FRONT_WEBSITE",project_id:"bwp-discovery-elements",schemaName:"exs-elements-schema"},pa={...Ce,elementTagName:dr.key},fr={...Ce,elementTagName:ve.key},ga={...Ce,elementTagName:mr.key},ya={...Ce,elementTagName:hr.key};function pr(){return new URL(import.meta.url)}var gr=[],yr=({renderContext:t,target:e=document.head,selector:r='[data-element-asset="font"]'})=>{let n=t.querySelectorAll(r);n&&n.forEach(o=>{let s=o.getAttribute("href");if(s&&!gr.includes(s)){gr.push(s);let a=s.substring(s.lastIndexOf("/")+1).split(".")?.[0];a&&o.setAttribute("data-font-family",a),e.appendChild(o)}})};var B={VariantChanged:"elements:variant-changed",FetchingVariantAttributes:"elements:fetching-variant-attributes",QuantityChanged:"elements:quantity-changed",SubscriptionsChanged:"elements:subscriptions-changed"};var Ae=async t=>import(t);var wr=()=>window?.ShopifyAnalytics?.meta?L.SHOPIFY:window?.stencilUtils?L.BIGCOMMERCE:document.body.classList.contains("woocommerce")?L.WOOCOMMERCE:"";var dt="https://cdn.elements.amazon",mt={SHOPIFY:new URL("/sdk/esp-adapters/shopify.js",dt).href,BIGCOMMERCE:new URL("/sdk/esp-adapters/bigcommerce.js",dt).href,WOOCOMMERCE:new URL("/sdk/esp-adapters/woocommerce.js",dt).href},L;(function(t){t.SHOPIFY="shopify",t.BIGCOMMERCE="bigcommerce",t.WOOCOMMERCE="woocommerce"})(L||(L={}));var Vn=async t=>t===L.SHOPIFY?Ae(mt.SHOPIFY):t===L.BIGCOMMERCE?Ae(mt.BIGCOMMERCE):t===L.WOOCOMMERCE?Ae(mt.WOOCOMMERCE):Promise.resolve(),ht=t=>({configure(e){let r={type:"radio",label:"Provider",config:{default:"none",options:[{label:"Shopify",value:"shopify"},{label:"None",value:"none"}]}},n={type:"toggle",label:"Enable variant helper",config:{default:!1}};return{...e,schema:{...e.schema,provider:r,variantHelper:n}}},onConnected(e){let r=e.getAttribute("provider")||e.getSetting("provider");if(Object.values(L).includes(r)||(r=wr()),!(e.getAttribute("variant-helper")==="true"||e.getSetting("variantHelper")||t?.enableHelperByDefault))return()=>{};let o=l=>{l.detail?.subscriptionsEnabled?(e.style.visibility="hidden",e.style.opacity="0",e.style.transition="opacity 0.2s ease, visibility 0.2s ease"):(e.style.visibility="visible",e.style.opacity="1")},s=l=>{l.detail?.quantity&&e.setAttribute("quantity",l.detail?.quantity?.toString())},i=l=>{e.hasAttribute("product-sku")&&e.setAttribute("product-sku",l.detail.productSku),e.hasAttribute("product-external-id")&&e.setAttribute("product-external-id",l.detail.productExternalId)};Vn(r).catch(l=>{console.error(`Unable to import adapter for ${r}`,l)});let a=l=>{o(l,e)},c=l=>{(t?.onQuantityChanged??s)(l,e)},m=l=>{(t?.onVariantChanged??i)(l,e)},d=[{type:B.VariantChanged,listener:m}];t?.quantityChangeEnabled&&d.push({type:B.QuantityChanged,listener:c}),t?.subscribeAndSaveEnabled&&d.push({type:B.SubscriptionsChanged,listener:a});let u=t?.onFetchingVariantAttributes;if(u){let l=f=>{u(f,e)};d.push({type:B.FetchingVariantAttributes,listener:l})}return d.forEach(({type:l,listener:f})=>{window.addEventListener(l,f)}),()=>{d.forEach(({type:l,listener:f})=>{window.removeEventListener(l,f)})}}});var Bn=Ie(xr(),1);var K=class extends Error{constructor(e){super(e),this.name="StateProviderLoadError"}};var D=class{stateProviderUrl;constructor(e){let r=new URL(e);this.stateProviderUrl=r.toString()}async getStateProviderModule(){try{let e=(await import(this.stateProviderUrl)).default??{};return this.validateStateProvider(e),e}catch{throw new K(`Failed to load state provider from ${this.stateProviderUrl}`)}}validateStateProvider(e){if(!["setState","getState","subscribe"].every(o=>{let s=typeof e[o]=="function";return s||!1}))throw new K("State provider module does not implement the required interface correctly.")}async getState(){return(await this.getStateProviderModule()).getState()}async setState(e){return(await this.getStateProviderModule()).setState(e)}async subscribe(e){return(await this.getStateProviderModule()).subscribe(e)}};var G=class{keysToSubscribe;stateClient;settingsKey;constructor(e,r,n){this.keysToSubscribe=e,this.stateClient=r,this.settingsKey=n}onConnected(e){let r=this.attachStateObserver(e);return async()=>{(await r)()}}containsAnyKey(e,r){return r.some(n=>n in e)}async attachStateObserver(e){let r=await this.stateClient.getState();if(r&&this.containsAnyKey(r,this.keysToSubscribe)){let n={};this.keysToSubscribe.forEach(o=>{n[o]=r[o]}),Object.keys(n).length>0&&e.setSetting(this.settingsKey,n)}return await this.stateClient.subscribe(n=>{this.containsAnyKey(n,this.keysToSubscribe)&&e.setSetting(this.settingsKey,n)})}};var Cr="https://cdn.elements.amazon/sdk/state-modules/3p.js";var W=class extends D{constructor(){super(Cr)}async setShopperAddress(e){let r=await this.getState();return this.setState({...r,shopperAddress:e})}};var J=class extends G{configure(e){return{...e,schema:{...e.schema,thirdPartyState:{config:{default:{}}}}}}constructor(e){super(e,new W,"thirdPartyState")}};var X=class extends D{removeListener;constructor(e){super(e)}listenDeliveryOffer(e){return this.removeListener&&this.removeListener(),this.removeListener=e.onRendered(r=>{let n=this.filterDeliveryOffer(r.detail.data);!n||Object.keys(n).length===0||this.setState(n)}),this.removeListener}filterDeliveryOffer=e=>!e||typeof e!="object"||!("deliveryOffer"in e)||!e.deliveryOffer||typeof e.deliveryOffer!="object"?void 0:Object.entries(e.deliveryOffer).filter(([n,o])=>typeof o=="object"&&o!==null&&"deliveryPreviewId"in o&&"id"in o&&"deliveryFor"in o&&"deliveryProvider"in o&&"deliveryTerms"in o).reduce((n,[o,s])=>(n[o]=s,n),{});removeRenderListener(){this.removeListener&&this.removeListener()}};var Re=class{name="SetDeliveryPlugin";stateClient;constructor(e){this.stateClient=new X(e?.stateScriptUrl||"https://cdn.elements.amazon/elements/amazon-delivery-message/assets/scripts/delivery-offer-state.js")}onConnected(e){return this.stateClient.listenDeliveryOffer(e)}};var Wn=pr().hostname==="cdn.elements.amazon",ft=ve.key,Ar={tagName:ft,bulk:{enabled:!0,max:25,splitOnSettings:["context"]},version:"v1.0",plugins:[{onConnected:t=>t.onRendered(async e=>{let r=e.detail.shadowRoot;yr({renderContext:r})})},Dt(Wn?"Solo":"SoloGamma",{properties:t=>{let e=new URL(window.location.href);return{appId:`${ft}:targetId=${t.getSetting("targetId")}:${e.host}${e.pathname}`,navigator}},dimensions:[{elementName:ft},{}],consoleOnlyLogging:!1,localHostLogging:!1}),It(fr),ht(),new re(t=>{let e=t.filter(Boolean).find(r=>r.name==="context");return(e&&(e.value==="in-order"||e.value==="in-cart"))??!1}),ur({triggerRefresh:!0}),new J(["shopperAddress"]),new Re],schema:jt,fetchOptions:{maxRetries:0}};Ze(Ar); /*! Bundled license information: cookie/index.js: (*! * cookie * Copyright(c) 2012-2014 Roman Shtylman * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed *) */ //# sourceMappingURL=web-component.js.map