@primer-io/primer-js 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,7 +33,7 @@ import{a as xa,b as d,c as k}from"./chunks/chunk.DV3REKZU.js";var _a=class{const
33
33
  --apple-pay-button-width: 100%;
34
34
  --apple-pay-button-height: ${a}px;
35
35
  }
36
- `,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),Nt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.APPLE_PAY}),this.applePaySession=new ApplePaySession(Cn,cc(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:a}=await this.onStartPromise;if(a==="abort")return void this.abort(new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new G({message:"Failed to validate merchant",code:q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(a){C.warn("Apple Pay merchant validation failed:",a),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(qr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling payment method selection",{error:a}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let a=[new ApplePayError("unknown",void 0,this.context.translate(la.UNKNOWN_ERROR,da.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Jr(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw a=[new ApplePayError("billingContactInvalid","name",this.context.translate(la.MISSING_FIRST_OR_LAST_NAME,da.MISSING_FIRST_OR_LAST_NAME))],new G({message:"Billing contact must include first and last name",code:It.MISSING_PARAMETER,paymentMethod:O.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Jr(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw a=[new ApplePayError("unknown",void 0,this.context.translate(la.FAILED_TO_TOKENIZE,da.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof G||i instanceof $?i:new G({message:"Error handling payment authorization",code:F.PAYMENT_FAILED,paymentMethod:O.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:a}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:a,error:i}=await this.context.clientSessionApi.setShippingAddress(Jr(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!a||i)throw i??new G({message:"Failed to set shipping address",code:q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeShippingContactSelection(qr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling shipping contact selection",{error:a}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let a=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&a){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new G({message:"Failed to select shipping method",code:q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(qr(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.context.clientSessionApi.unselectPaymentMethod(),this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},Ya=class extends mt{constructor(){super(...arguments);k(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new $({message:"BLIK code must be exactly 6 digits",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:ro()?"MOBILE_WEB":"WEB",browserInfo:bi(),blikCode:this.blikCode}};try{let{error:a,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),a||!i)throw a??new $({message:"Unable to tokenize BLIK payment method",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(a){throw this.clearBlikCode(),a}}async createPayment(e){let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new Oe({message:"No client token provided for BLIK payment",code:An.MISSING_CLIENT_TOKEN,response:{id:a.id,data:a}});let n=Vt(i);if(!this.isValidBlikClientToken(n))throw new Oe({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:An.INVALID_CLIENT_TOKEN,response:{id:a.id,data:a}});let{promise:o,abort:s}=this.pollStatus(n.statusUrl),l=await o;if(s(),"error"in l)throw l.error;let c=l.id;if(!c){let m=await this.context.pciApi.getResumeStatus(n.statusUrl);if(m.error||!m.data?.id)throw m.error??new Error("Unable to get resume token");c=m.data.id}return await this.resumePayment(a.id,c)}pollStatus(e){let a=!0,i=1e3,n=864e5,o=Date.now();return{promise:new Promise(async s=>{for(;a;){if(Date.now()-o>=n)return void s({error:new Error("BLIK payment polling timed out after 24 hours")});let{data:l,error:c}=await this.context.pciApi.getResumeStatus(e);if(c)return void s({error:c instanceof Error?c:new Error(String(c))});if(l?.status==="COMPLETE")return void s({id:l.id});await Ht(i)}}),abort:()=>{a=!1}}}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let a=e;return!(a.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in a)||typeof a.statusUrl!="string"||!a.statusUrl)}},co="https://sdk.primer.io/web/hosted-pages/v0.0.22",li=!1,pc=`${co}/api-controller.html`,mc=`${co}/hosted-input.html`,hc="https://goat-assets.production.core.primer.io";function uo(r,t,e){let a={checkoutSessionId:r,name:t};e!==void 0&&(a.defaultValue=e);try{return btoa(JSON.stringify(a))}catch{let{defaultValue:n,...o}=a;return btoa(JSON.stringify(o))}}gi("../../node_modules/card-validator/dist/index.js");var ce={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},En="cardSecurityCodeRecapture";Object.values(ce);function po(r,t){return{cardNumber:sa(r,ce.cardNumber),cardSecurityCode:sa(r,ce.cardSecurityCode),cardExpiryDate:sa(r,ce.cardExpiryDate),cardholderName:sa(r,ce.cardholderName,t?.cardholderName)}}function sa(r,t,e){let a=document.createElement("iframe"),i=uo(r,t,e);return a.src=`${mc}#${i}`,a.setAttribute("tabindex","0"),a.setAttribute("frameBorder","0"),a.style.border="none",a.style.boxSizing="border-box",a.style.height="20px",a.style.width="100%",a.style.colorScheme="auto",a}var za=class extends mt{constructor(e,a){super(e,a);k(this,"iframes");this.iframes=po(a.checkoutSessionId)}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postCardPaymentInstruments();if(e||!a)throw e??new $({code:F.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:O.PAYMENT_CARD});return a}};function gc(r){if(!r)return{};let t=r.indexOf(" ");return t===-1?{firstName:r}:{firstName:r.substring(0,t),lastName:r.substring(t+1)}}function Qr(r){let{firstName:t,lastName:e}=gc(r.name);return{firstName:t||null,lastName:e||null,addressLine1:r.address1||null,addressLine2:r.address2||null,city:r.locality||null,state:r.administrativeArea||null,postalCode:r.postalCode||null,countryCode:r.countryCode||null}}function Tn(r){return r.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var Pn=2,In=0,yc="https://pay.google.com/gp/p/js/pay.js",fc={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},Nn=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Oa={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Ba={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},vc="buy",Sc="black",bc="fill",$a=class extends mt{constructor(){super(...arguments);k(this,"disabled",!1);k(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,a){return this.context.translate?.(e,a)??a}async tokenize(){throw new $({code:F.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:O.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await io(yc),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:a}=this.context.configuration.clientSession.order;if(!e)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:O.GOOGLE_PAY});if(!a)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:O.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:Pn,apiVersionMinor:In,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let a=this.client.createButton({buttonType:this.clientOptions?.buttonType??vc,buttonColor:this.clientOptions?.buttonColor??Sc,buttonSizeMode:this.clientOptions?.buttonSizeMode??bc,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(a)}async handleClick(e){if(!this.client)return void C.error("Google Pay client not available");let a=this.callbacks.onStart();this.context.clientSessionApi.selectPaymentMethod(O.GOOGLE_PAY),Nt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await a;if(n==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:a,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Fa.encode(e.paymentMethodData.tokenizationData.token)});if(i||!a)throw this.callbacks.onFinish(void 0,i),i??new $({code:F.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:O.GOOGLE_PAY});this.callbacks.onFinish(a)}async updateBillingAddress(e){let a=e.paymentMethodData.info?.billingAddress;if(a){let i=Qr(a);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let a=e.shippingAddress,i=e.email,n=a?.phoneNumber;if(a||n||i){let o=a?Qr(a):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let a=e.callbackTrigger;try{if(a==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(a==="SHIPPING_ADDRESS"||a==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Qr(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:Tn(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:a==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:a,totalOrderAmount:i}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:a,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:na(i,a),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:a,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Oa.SUBTOTAL,Ba.SUBTOTAL),type:"SUBTOTAL",price:na(i,a)}),c):(n&&n.length>0&&n.forEach(m=>{c.push({label:m.description||this.translate(Oa.ITEM,Ba.ITEM),type:"LINE_ITEM",price:na(m.amount,a)})}),o&&o.length>0&&o.filter(m=>m.amount!==0).forEach(m=>{c.push({label:m.type||m.description||this.translate(Oa.FEE,Ba.FEE),type:"LINE_ITEM",price:na(m.amount,a)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Oa.SHIPPING,Ba.SHIPPING),type:"LINE_ITEM",price:na(s.amount,a)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return Nn;let a=e.map(i=>fc[i]).filter(i=>!!i);return a.length>0?a:Nn}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,a=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:Pn,apiVersionMinor:In,...a&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:Tn(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}};function Ac(r,t){var e={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,a=Object.getOwnPropertySymbols(r);i<a.length;i++)t.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(r,a[i])&&(e[a[i]]=r[a[i]]);return e}function Cc(r,t){var e=document.querySelector('script[src="'.concat(r,'"]'));if(e===null)return null;var a=mo(r,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(a.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==a.dataset[o]&&(n=!1)}),n?e:null}function Mc(r){var t=r.url,e=r.attributes,a=r.onSuccess,i=r.onError,n=mo(t,e);n.onerror=i,n.onload=a,document.head.insertBefore(n,document.head.firstElementChild)}function Ec(r){var t=r.sdkBaseUrl,e=r.environment,a=Ac(r,["sdkBaseUrl","environment"]),i=t||Ic(e),n=a,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,m){var g=n[m].toString();return m=Tc(m),m.substring(0,4)==="data"||m==="crossorigin"?c.attributes[m]=g:c.queryParams[m]=g,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Pc(s)),attributes:l}}function Tc(r){var t=function(e,a){return(a?"-":"")+e.toLowerCase()};return r.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Pc(r){var t="";return Object.keys(r).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+r[e]}),t}function Ic(r){return r==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function mo(r,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=r,Object.keys(t).forEach(function(a){e.setAttribute(a,t[a]),a==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Nc(r,t){if(t===void 0&&(t=Promise),ho(r,t),typeof document>"u")return t.resolve(null);var e=Ec(r),a=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=kn(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),Cc(a,i)&&o?t.resolve(o):kc({url:a,attributes:i},t).then(function(){var s=kn(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function kc(r,t){t===void 0&&(t=Promise),ho(r,t);var e=r.url,a=r.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(a!==void 0&&typeof a!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();Mc({url:e,attributes:a,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function kn(r){return window[r]}function ho(r,t){if(typeof r!="object"||r===null)throw new Error("Expected an options object.");var e=r.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Ga=new Map,Ln={getOrCreateNamespace(r){let t=Ga.get(r);return t?t.namespace:Te()},getInstance(r){return Ga.get(r)?.instance??null},storeInstance(r,t,e){Ga.set(r,{instance:t,namespace:e})},hasInstance(r){return Ga.has(r)}};async function Lc({context:r,configId:t,paymentMethodType:e,callbacks:a}){try{let{action:i}=await a.onStart();if(i==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e});await r.clientSessionApi.selectPaymentMethod(e);let{data:n,error:o}=await r.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),a.onFinish(void 0,i),i instanceof G||i instanceof $?i:new G({message:"Failed to create billing agreement",code:F.PAYMENT_FAILED,paymentMethod:e})}}async function Rc({context:r,configId:t,paymentMethodType:e,callbacks:a,data:i}){try{let n=i.billingToken;if(!n)throw new $({message:"Billing token not provided",code:F.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await r.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let h=s?.message??"Failed to confirm billing agreement";throw new $({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:m,data:g}=await r.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(m||!g){let h=m?.message??"Unable to vault PayPal payment method";throw new $({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}a.onFinish(g)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),a.onFinish(void 0,n),n instanceof $||n instanceof G?n:new $({message:"Failed to approve billing agreement",code:F.TOKENIZATION_ERROR,paymentMethod:e})}}var xc="gold",_c="black",wc="rect",Dc="paypal",Oc="vertical",go="horizontal",Rn=2,xn=["paypal","paylater"],yo={default:{color:xc},card:{validColors:["black","white"],defaultColor:_c}};function Bc(r){if(!r)return;let t=yo[r];if(t&&"validColors"in t)return t}function Gc(r,t){let e=Bc(t);if(!e)return r??yo.default.color;let a=r??e.defaultColor;return e.validColors.includes(a)?a:(C.warn(`PayPal: Invalid color "${a}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var Kc=25,Fc=55;function Uc(r){return parseFloat(r)||0}function Vc(r){let t=Uc(r);return Math.max(Kc,Math.min(Fc,t))}function Hc(r,t,e){let a=t?r?.[t]:void 0,i=a?.tagline??r?.tagline??!1,n=i?go:Oc,o,s=a?.height??r?.height;s!=null?o=s:e!=null&&(o=Vc(String(e)));let l=a?.borderRadius??r?.borderRadius,c=a?.disableMaxWidth??r?.disableMaxWidth,m=a?.color??r?.color;return{color:Gc(m,t),shape:a?.shape??r?.shape??wc,label:a?.label??r?.label??Dc,layout:a?.layout??r?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function Yc(r,t,e,a){let i={style:r,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&a?(i.createBillingAgreement=a.createBillingAgreement,i.onApprove=a.onApprove):i.onApprove=e.onApprove,i}function zc(r){if(!r)return;let t={first_name:r.firstName,last_name:r.lastName,address_line_1:r.addressLine1??"",address_line_2:r.addressLine2,city:r.city??"",state:r.state,postal_code:r.postalCode??"",country_code:r.countryCode??""},{address_line_1:e,city:a,postal_code:i,country_code:n}=t;if(!(!e||!a||!i||!n))return t}function $c(r){if(!r)return null;let t=r.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,a=t.name;return{firstName:a?.given_name,lastName:a?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function jc(r,t,e){let{order:{currencyCode:a,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=r;if(!a)throw new G({message:"Currency code is not provided",code:It.MISSING_PARAMETER,paymentMethod:e});let m={amount:i??n,currencyCode:a,paymentMethodConfigId:t,amountBreakdown:{}},g=c?.shippingAddress,h=zc(g);h&&(m.shipping_address=h);let T=!s.some(M=>!M.name&&!M.description);if(T&&(m.items=s.map(M=>{let{name:_,description:x,taxAmount:E,amount:L,quantity:K}=M,j=E?Math.floor(E/K):0;return{name:x||_||"",unit_amount:{value:L,currency_code:a},quantity:K.toString(),tax:{value:j,currency_code:a}}})),T&&s.length){let M=s.reduce((de,{amount:H,quantity:De})=>de+H*De,0),_=l?.reduce?.((de,{amount:H})=>de+(H??0),0),x=s?.reduce((de,{discountAmount:H})=>de+(H??0),0),E=s?.reduce((de,{taxAmount:H})=>de+(H??0),0),L=o?.amount??0,K=_??0,j=M+E+L+K-x;m.amountBreakdown={item_total:{value:M,currency_code:a},tax_total:{value:E,currency_code:a},handling:{value:K,currency_code:a},shipping:{value:L,currency_code:a},discount:{value:x,currency_code:a}},m.amount=j}return m}async function Wc({context:r,configId:t,paymentMethodType:e,callbacks:a,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await a.onStart();if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e})}await r.clientSessionApi.selectPaymentMethod(e);let{data:n,error:o}=await r.coreApi.createPaypalOrder(jc(r.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw a.onFinish(void 0,n),n}}async function Zc({context:r,paymentMethodType:t,callbacks:e,data:a,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:g}=await e.onStart();if(g==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(g){C.warn("Failed to get PayPal order details",g)}let s=$c(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:a.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:a.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:m}=await r.pciApi.postPaypalPaymentInstruments(l);if(c||!m){let g=c?.message??"Unable to create payment instrument";throw new $({message:g,code:F.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(m)}var Jc=["buttons","funding-eligibility"],_n=[],wn="paypal";function fo(r){if(!r?.length)return;r.includes(wn)&&C.warn("PayPal: Cannot disable paypal funding source");let t=r.filter(e=>e!==wn);return t.length>0?t:void 0}var qc="authorize";function Qc(r,t,e){return(r??t==="PREFER_VAULT")&&e}function Dn({isVaultFlow:r,configIntent:t}){return r?"tokenize":t??qc}function Xc(r,t,e,a){let{clientId:i,intent:n}=t.options,o=r.configuration.clientSession.order.currencyCode,s=r.clientOptions.paypal?.disableFunding??(_n.length>0?_n:void 0),l=fo(s),c=r.clientOptions?.paypal?.enableFunding,m={dataNamespace:e,clientId:i,currency:o,components:Jc,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:r.clientOptions.paypal?.integrationDate,debug:r.clientOptions.paypal?.debug};return(li||r.decodedClientToken.env==="SANDBOX"||r.decodedClientToken.env==="STAGING")&&(m.buyerCountry=r.clientOptions?.paypal?.buyerCountry),a?(m.vault="true",m.intent=Dn({isVaultFlow:!0,configIntent:n})):(m.vault="false",m.intent=Dn({isVaultFlow:!1,configIntent:n})),m}var ja=class extends mt{constructor(e,a){super(e,a);k(this,"paypalInstance");k(this,"dataNamespace");k(this,"isVaultFlow",!1);k(this,"isSetupComplete",!1);k(this,"setupPromise");k(this,"eligibleFundingSources",[]);k(this,"currentFundingSource",null);k(this,"onStartDeferred",!1);k(this,"disabled",!1);this.dataNamespace=Ln.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new $({message:"PayPal does not support direct tokenization",code:F.TOKENIZATION_ERROR,paymentMethod:O.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let a=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=Qc(a,i,n);let o=Xc(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Nc(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,Ln.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=fo(this.context.clientOptions.paypal?.disableFunding),g=(s.getFundingSources?.()??[]).filter(h=>s?.isFundingEligible?.(h));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",g),this.eligibleFundingSources=this.filterFundingSources(g,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(a){return C.warn("PayPal setup failed:",{error:a}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,a){let{Buttons:i}=this.paypalInstance;if(!i)throw new G({message:"PayPal Buttons component not available",code:It.INVALID_USAGE,paymentMethod:O.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=a?.style?.buttonHeight,s=n?.layout===go,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>Lc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>Rc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,m=this.eligibleFundingSources,g=[];for(let M of m){let _=Hc(n,M,o),x=Yc(_,this.isVaultFlow,l,c);this.isVaultFlow||(x.createOrder=this.handleCreateOrder.bind(this));let E=i({...x,fundingSource:M});E.isEligible()?g.push({button:E,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(g.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new G({message:"No PayPal buttons eligible to render",code:It.INVALID_USAGE,paymentMethod:O.PAYPAL});let h=s&&g.length>Rn?this.selectButtonsForHorizontalLayout(g):g;s&&this.applyHorizontalLayoutStyles(e,h.length);let T=h.map(({button:M})=>M.render(e));await Promise.all(T)}selectButtonsForHorizontalLayout(e){let a=new Set(xn),i=xn.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!a.has(o.fundingSource));return[...i,...n].slice(0,Rn)}applyHorizontalLayoutStyles(e,a){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${a}, 1fr)`,e.style.gap="10px"}handleInit(e,a){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),a.disable();return}a.enable()}handleClick(e,a){return this.currentFundingSource=e.fundingSource??null,Nt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),a.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,Wc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,a){let i=this.onStartDeferred;return this.onStartDeferred=!1,Zc({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:a,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new G({message:"The PayPal payment was cancelled by the user.",paymentMethod:O.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,a,i){return e.filter(n=>!(a?.length&&!a.includes(n)||i?.includes(n)))}};function On(r,t,e){if(!r)return null;let a={id:r.id,orderId:r.orderId};return t?.paymentInstrumentData&&e&&(a.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),a}var vo=(r,t,e,a,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void r.onCheckoutComplete?.({payment:On(t,a,i)});r.onCheckoutFail?.(n||new G({code:F.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:On(t,a,i)??void 0})},eu=async(r,t)=>{let e=t.config.type;if(!r.onBeforePaymentCreate)return{action:"continue"};let a=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);return new Promise(i=>{r.onBeforePaymentCreate({paymentMethodType:e},{continuePaymentCreation:n=>{clearTimeout(a),C.log(`Continuing payment creation for ${e}`),n?.idempotencyKey&&t.setIdempotencyKey(n.idempotencyKey),r.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(a),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})})};async function pa(r,t,e){if(t.setCallbacks({onStart:()=>(Nt({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:t.config.type}),eu(r,t)),onFinish:(a,i)=>{Bn(r,t,a,i)}}),!e)return t.start();{let a,i;try{i=await t.tokenizeVaulted(e.id)}catch(n){a=n}return Bn(r,t,i,a)}}async function Bn(r,t,e,a){let i;if(e&&!a)try{i=await t.createPayment(e),i=await t.handleRequiredAction(i)}catch(n){a=n}vo(r,i,a,e,t.config.type)}var Gn=Symbol("PROXY_MARKER");function Ai({namespace:r,onMessage:t,sendMessage:e}){function a(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[Gn])return Reflect.get(o,s,l);let c=()=>{};return c[Gn]=!0,a(c,[...n,s])},apply(o,s,l){return new Promise(async(c,m)=>{try{let g=[],h=l.map(x=>{if(typeof x!="function")return x;{let E=Te();return g.push(E),t(L=>{L.namespace===r&&L.sender===ei.PROVIDER&&L.type===Xr.CALLBACK&&L.id===E&&x(...L.data)}),E}}),T=Te(),M=t(x=>{x.namespace===r&&x.sender===ei.PROVIDER&&x.type===Xr.APPLY&&x.id===T&&(x.error?m(new Error(x.error)):c(x.data),M?.())}),_={type:Xr.APPLY,sender:ei.INJECTOR,id:T,path:n,args:h,callbackIds:g,timeStamp:Date.now(),namespace:r};e(_)}catch(g){m(g)}})}})}return a({},[])}var Xr={APPLY:"apply",CALLBACK:"callback"},ei={PROVIDER:"provider",INJECTOR:"injector"};function di(r,t){let e=t?.input?.base?.height;e&&(r.style.height=typeof e=="number"?`${e}px`:e)}function tu(r,t,e,a={}){let i=r.cardholderName?.defaultValue??r.card?.cardholderName?.defaultValue,n=po(t.checkoutSessionId,{cardholderName:i});e.iframes=n;let o=[],s="LOCAL",l={[ce.cardNumber]:void 0,[ce.cardExpiryDate]:void 0,[ce.cardSecurityCode]:void 0,[ce.cardholderName]:void 0},c=!1;t.subscribeToTeardown(()=>{c=!0});let m={createHostedInputs:()=>{let g=h=>{let T=new Map;return{getOptions:()=>{},setOptions:M=>{di(e.iframes[h],M.style),e.iframes[h].setAttribute("title",M.ariaLabel||""),l[h]?.setOptions(M)},render:(M,_)=>{let x=e.iframes[h];if(!x)return C.errorWithDatadog(`No iframe found for ${h}`),Promise.resolve();let E;return E=typeof M=="string"?document.getElementById(M):M,E?(di(x,_.style),E.appendChild(x),new Promise(L=>{x.onload=()=>{if(c){C.warn(`Teardown was already called, aborting render for ${h}`),x.remove(),L();return}l[h]=Ai({namespace:`${t.checkoutSessionId}-${h}`,onMessage:H=>{let De=Wr=>H(Wr.data);return window.addEventListener("message",De),()=>window.removeEventListener("message",De)},sendMessage:H=>{x.contentWindow.postMessage(H,"*")}}),e.iframes[h].setAttribute("title",_.ariaLabel||"");let K=r.cardholderName??r.card?.cardholderName,{defaultValue:j,...de}=K??{};l[h].setOptions({..._,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:de}),l[h].setOnBlur(()=>{try{T.get("blur")?.()}catch(H){C.errorWithDatadog(`Blur listener error for ${h}`,{error:H})}}),l[h].setOnFocus(()=>{try{T.get("focus")?.()}catch(H){C.errorWithDatadog(`Focus listener error for ${h}`,{error:H})}}),l[h].setOnInput(H=>{let De={...H,errorCode:H.error,active:H.focused};try{T.get("input")?.(De),T.get("change")?.(De)}catch(Wr){C.errorWithDatadog(`Input listener error for ${h}`,{error:Wr})}}),l[h].setOnEnter(()=>{try{T.get("enter")?.()}catch(H){C.errorWithDatadog(`Enter listener error for ${h}`,{error:H})}}),h===ce.cardNumber&&(l[h].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),l[h].setOnCardNetworksChange((H,De)=>{(De!==s||au(o,H))&&(o=H,s=De,a.onCardNetworksChange?.(ru({networks:o,source:s},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks)))}))},L()})):(C.error(`Container not found for ${h}:`,M),Promise.resolve())},addEventListener:(M,_)=>{T.set(M,_)},focus:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.focus()}catch(_){C.errorWithDatadog(`Focus send error for ${h}`,{error:_})}else C.warn(`Focus failed for ${h} - iframe not available`)},blur:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.blur()}catch(_){C.errorWithDatadog(`Blur send error for ${h}`,{error:_})}},setDisabled:M=>{l[h]?.setDisabled(M)}}};return{cardNumberInput:g(ce.cardNumber),cardholderNameInput:g(ce.cardholderName),expiryInput:g(ce.cardExpiryDate),cvvInput:g(ce.cardSecurityCode)}},removeHostedInputs:()=>{c=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()},submit:async g=>{if((await m.validate()).valid)return await t.apiController.setPreferredNetwork(g?.cardNetwork),pa(r,e)},validate:async()=>{let g=(await Promise.all(Object.entries(l).map(([T,M])=>M?.getFieldState().then(_=>[T,_]).catch(()=>{})))).filter(T=>T!==void 0),h=[];for(let[T,M]of g)!M.valid&&M.error&&h.push({field:T,name:T,error:M.error,message:M.error});return{valid:h.length===0,validationErrors:h}},reset:()=>{Object.values(l).forEach(g=>{g?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:g=>{try{l[ce.cardholderName]?.setCardholderName(g)}catch(h){C.errorWithDatadog("SetCardholderName error",{error:h})}}};return m}function au(r,t){if(r.length!==t.length)return!0;let e=t.map(({network:a})=>a);return!r.every(({network:a})=>e.includes(a))}function ru({networks:r,source:t},e){let a=e,i=new Set(a.map(l=>Wa(l).backend)),n=r.map(l=>({...l,allowed:i.has(l.network)})).sort((l,c)=>l.allowed?a.indexOf(l.network)-a.indexOf(c.network):1),o=n.filter(l=>l.allowed),s=t==="REMOTE"&&o.length>1;return{detectedCardNetworks:{items:n,preferred:o[0]},...s&&{selectableCardNetworks:{items:o,preferred:o[0]}},source:t}}function iu(r,t,e){return{createButton:()=>({render:async(a,i)=>{await pa(r,e);let n=typeof a=="string"?document.getElementById(a):a;if(!n)throw new G({code:Jd.CONTAINER_NOT_FOUND,message:`Container with id "${a}" not found in the DOM.`});await e.render(n,i)},setDisabled:a=>e.setDisabled(a)})}}function nu(r,t,e){return{start:()=>pa(r,e)}}function ou(r,t,e){return{start:async a=>(a?.blikCode&&e.setBlikCode(a.blikCode),pa(r,e))}}function su(r,t){return{"Content-Type":"application/json","primer-client-token":r,"primer-sdk-client":"WEB","primer-sdk-version":"0.0.0-local","primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}function lu(r,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(r instanceof Error){let a=r.message.toLowerCase();return a.includes("network")||a.includes("timeout")||a.includes("connection")}return!1}function du(r){let n=1e3*Math.pow(1.1,r),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var cu={attempts:3,retryCondition:lu,delayCalculator:du,totalTimeout:3e5};async function uu(r,t,e){let a={...cu,...t.retry},i=[],n=Date.now();for(let s=0;s<=a.attempts;s++)try{let l=await r();if(!l.error)return{...l,retryHistory:i.length>0?i:void 0};if(s===a.attempts||!a.retryCondition(l.error,s,l))return{...l,retryHistory:i};let c=a.delayCalculator(s);if(i.push({attempt:s+1,delay:c,error:l.error,timestamp:Date.now()}),Date.now()-n+c>a.totalTimeout)return{...l,error:new Oe({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:ua({status:408}),response:l}),retryHistory:i};await Ht(c)}catch(l){i.push({attempt:s+1,delay:0,error:new Oe({message:`Request failed for ${t.method} ${e}`,code:q.UNEXPECTED,error:l,response:{id:t.id}}),timestamp:Date.now()})}let o=i[i.length-1]?.error;return{id:t.id,error:o,retryHistory:i}}var zt=class{constructor(t,e="",a={}){k(this,"fetch");k(this,"baseUrl");k(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...a})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let a={...e,headers:{...this.defaultHeaders,...e?.headers},id:Te()};return e?.retry?uu(()=>this.fetch(t,{...a,retry:void 0}),a,t):this.fetch(t,a)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,a){return this.executeFetch(t,{...a,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}};async function pu(r,t){let e=t.id??Te(),a={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(r,t);if(a.data=await i.json(),a.status=i.status,a.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new Oe({message:`Request failed for ${t.method} ${r}`,code:ua({backendErrorId:a.data?.error?.errorId,status:a.status}),response:{...a}});a.error=n}}catch(i){let n=new Oe({message:`Request failed for ${t.method} ${r}`,code:ua({status:a.status}),response:{...a},error:i});a.error=n}return a}var ci=class extends zt{constructor(){super(...arguments);k(this,"configurationSubscribers",new Set);k(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this._configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=e,this.configurationSubscribers.forEach(a=>a(this._configuration))}},ui=class extends zt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}};async function mu(r){return new Promise((t,e)=>{let a=uo(r,"api"),i=`${pc}#${a}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${o}`))},n.src=i,document.body.appendChild(n))})}var ca=class ca extends zt{constructor(){super(...arguments);k(this,"onClientSessionUpdate");k(this,"onPaymentMethodAction");k(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return ca.noActionsResponse;let a=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=a;return i&&this.onClientSessionUpdate?.(i),a}async selectPaymentMethod(e,a={}){return this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...a,paymentMethodType:e}}])}async unselectPaymentMethod(){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(O.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let a=this.removeEmptyStringFromObject(e);return Object.values(a).length===0?ca.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:a}}])}async setShippingAddress(e,a,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),a&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:a}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:a,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),a&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:a}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:a}=Wa(e);return{network:a,issuer_name:null,product_code:a,product_name:a,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let a={...e};for(let i in a)a[i]===""?delete a[i]:typeof a[i]=="object"&&a[i]!==null&&!Array.isArray(a[i])&&(a[i]=this.removeEmptyStringFromObject(a[i]));return a}};k(ca,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var pi=ca,mi=class extends zt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}};async function hu(r,{locale:t,dialogProvider:e,translate:a,clientOptions:i}){let n=Te(),o=Vt(r),s=await mu(n),l=Ai({namespace:`api-controller-${n}`,onMessage:E=>{let L=K=>{if(K.data?.data?.error?.name==="RequestError"){let j=Object.assign(new Oe({...K.data.data.error}),K.data.data.error);typeof j.error=="object"&&"message"in j.error&&(j.error=Object.assign(new Error(j.error.message),{stack:j.error.stack})),K.data.data.error=j}return E(K.data)};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},sendMessage:E=>{s.contentWindow.postMessage(E,"*")}}),c=su(o.accessToken,n),m=new ci(pu,o.configurationUrl,c),g=Date.now(),{error:h}=await m.getConfiguration();if(h||!m.configuration)throw new Error(`Failed to fetch configuration: ${h}`);let T=new ui(l.fetch,m.configuration.pciUrl,c),M=new mi(l.fetch,m.configuration.coreUrl,c),_=new pi(l.fetch,m.configuration.pciUrl,c);_.setOnClientSessionUpdate(E=>{m.configuration=E});let x=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(E){return m.subscribe(E)},checkoutSessionId:n,apiController:l,configurationApi:m,pciApi:T,coreApi:M,clientSessionApi:_,dialogProvider:e,decodedClientToken:o,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:a??((E,L)=>L),clientOptions:i,updateClientToken(E){try{let L=Vt(E);m.setDefaultHeader("primer-client-token",L.accessToken),T.setDefaultHeader("primer-client-token",L.accessToken),M.setDefaultHeader("primer-client-token",L.accessToken),_.setDefaultHeader("primer-client-token",L.accessToken)}catch{}},async refreshClientConfiguration(){let{data:E,error:L}=await m.getConfiguration();return L||!E?(C.warn("Failed to refresh client configuration:",L),!1):(m.configuration=E,!0)},subscribeToTeardown(E){return x.add(E),()=>{x.delete(E)}},teardown(){s.remove(),x.forEach(E=>E())}}}var gu=100;function yu({height:r,name:t,url:e="",width:a}){let i=new Set,n=window.open(e,t,vu({height:r,width:a}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),fu(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var fu=r=>new Promise(t=>{let e=setInterval(()=>{r.closed&&(clearInterval(e),t())},gu)});function vu(r){let t=Su({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:r});return bu(t)}var Su=({parent:r,popup:t})=>({left:r.left+(r.width-t.width)/2,top:r.top+(r.height-t.height)/2,height:t.height,width:t.width}),bu=r=>Object.entries(r).map(t=>t.join("=")).join(","),Au=({name:r,background:t,logoSrc:e,logoAlt:a,message:i})=>`<html>
36
+ `,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),Nt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.APPLE_PAY}),this.applePaySession=new ApplePaySession(Cn,cc(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:a}=await this.onStartPromise;if(a==="abort")return void this.abort(new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new G({message:"Failed to validate merchant",code:q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(a){C.warn("Apple Pay merchant validation failed:",a),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(qr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling payment method selection",{error:a}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let a=[new ApplePayError("unknown",void 0,this.context.translate(la.UNKNOWN_ERROR,da.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Jr(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw a=[new ApplePayError("billingContactInvalid","name",this.context.translate(la.MISSING_FIRST_OR_LAST_NAME,da.MISSING_FIRST_OR_LAST_NAME))],new G({message:"Billing contact must include first and last name",code:It.MISSING_PARAMETER,paymentMethod:O.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Jr(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw a=[new ApplePayError("unknown",void 0,this.context.translate(la.FAILED_TO_TOKENIZE,da.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof G||i instanceof $?i:new G({message:"Error handling payment authorization",code:F.PAYMENT_FAILED,paymentMethod:O.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:a}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:a,error:i}=await this.context.clientSessionApi.setShippingAddress(Jr(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!a||i)throw i??new G({message:"Failed to set shipping address",code:q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY});this.applePaySession.completeShippingContactSelection(qr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling shipping contact selection",{error:a}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let a=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&a){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new G({message:"Failed to select shipping method",code:q.REQUEST_ERROR,paymentMethod:O.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(qr(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.context.clientSessionApi.unselectPaymentMethod(),this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},Ya=class extends mt{constructor(){super(...arguments);k(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new $({message:"BLIK code must be exactly 6 digits",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:ro()?"MOBILE_WEB":"WEB",browserInfo:bi(),blikCode:this.blikCode}};try{let{error:a,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),a||!i)throw a??new $({message:"Unable to tokenize BLIK payment method",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(a){throw this.clearBlikCode(),a}}async createPayment(e){let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new Oe({message:"No client token provided for BLIK payment",code:An.MISSING_CLIENT_TOKEN,response:{id:a.id,data:a}});let n=Vt(i);if(!this.isValidBlikClientToken(n))throw new Oe({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:An.INVALID_CLIENT_TOKEN,response:{id:a.id,data:a}});let{promise:o,abort:s}=this.pollStatus(n.statusUrl),l=await o;if(s(),"error"in l)throw l.error;let c=l.id;if(!c){let m=await this.context.pciApi.getResumeStatus(n.statusUrl);if(m.error||!m.data?.id)throw m.error??new Error("Unable to get resume token");c=m.data.id}return await this.resumePayment(a.id,c)}pollStatus(e){let a=!0,i=1e3,n=864e5,o=Date.now();return{promise:new Promise(async s=>{for(;a;){if(Date.now()-o>=n)return void s({error:new Error("BLIK payment polling timed out after 24 hours")});let{data:l,error:c}=await this.context.pciApi.getResumeStatus(e);if(c)return void s({error:c instanceof Error?c:new Error(String(c))});if(l?.status==="COMPLETE")return void s({id:l.id});await Ht(i)}}),abort:()=>{a=!1}}}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let a=e;return!(a.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in a)||typeof a.statusUrl!="string"||!a.statusUrl)}},co="https://sdk.primer.io/web/hosted-pages/v0.0.22",li=!1,pc=`${co}/api-controller.html`,mc=`${co}/hosted-input.html`,hc="https://goat-assets.production.core.primer.io";function uo(r,t,e){let a={checkoutSessionId:r,name:t};e!==void 0&&(a.defaultValue=e);try{return btoa(JSON.stringify(a))}catch{let{defaultValue:n,...o}=a;return btoa(JSON.stringify(o))}}gi("../../node_modules/card-validator/dist/index.js");var ce={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},En="cardSecurityCodeRecapture";Object.values(ce);function po(r,t){return{cardNumber:sa(r,ce.cardNumber),cardSecurityCode:sa(r,ce.cardSecurityCode),cardExpiryDate:sa(r,ce.cardExpiryDate),cardholderName:sa(r,ce.cardholderName,t?.cardholderName)}}function sa(r,t,e){let a=document.createElement("iframe"),i=uo(r,t,e);return a.src=`${mc}#${i}`,a.setAttribute("tabindex","0"),a.setAttribute("frameBorder","0"),a.style.border="none",a.style.boxSizing="border-box",a.style.height="20px",a.style.width="100%",a.style.colorScheme="auto",a}var za=class extends mt{constructor(e,a){super(e,a);k(this,"iframes");this.iframes=po(a.checkoutSessionId)}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postCardPaymentInstruments();if(e||!a)throw e??new $({code:F.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:O.PAYMENT_CARD});return a}};function gc(r){if(!r)return{};let t=r.indexOf(" ");return t===-1?{firstName:r}:{firstName:r.substring(0,t),lastName:r.substring(t+1)}}function Qr(r){let{firstName:t,lastName:e}=gc(r.name);return{firstName:t||null,lastName:e||null,addressLine1:r.address1||null,addressLine2:r.address2||null,city:r.locality||null,state:r.administrativeArea||null,postalCode:r.postalCode||null,countryCode:r.countryCode||null}}function Tn(r){return r.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var Pn=2,In=0,yc="https://pay.google.com/gp/p/js/pay.js",fc={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},Nn=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Oa={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Ba={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},vc="buy",Sc="black",bc="fill",$a=class extends mt{constructor(){super(...arguments);k(this,"disabled",!1);k(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,a){return this.context.translate?.(e,a)??a}async tokenize(){throw new $({code:F.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:O.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await io(yc),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:a}=this.context.configuration.clientSession.order;if(!e)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:O.GOOGLE_PAY});if(!a)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:O.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:Pn,apiVersionMinor:In,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let a=this.client.createButton({buttonType:this.clientOptions?.buttonType??vc,buttonColor:this.clientOptions?.buttonColor??Sc,buttonSizeMode:this.clientOptions?.buttonSizeMode??bc,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(a)}async handleClick(e){if(!this.client)return void C.error("Google Pay client not available");let a=this.callbacks.onStart();this.context.clientSessionApi.selectPaymentMethod(O.GOOGLE_PAY),Nt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:O.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await a;if(n==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:a,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Fa.encode(e.paymentMethodData.tokenizationData.token)});if(i||!a)throw this.callbacks.onFinish(void 0,i),i??new $({code:F.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:O.GOOGLE_PAY});this.callbacks.onFinish(a)}async updateBillingAddress(e){let a=e.paymentMethodData.info?.billingAddress;if(a){let i=Qr(a);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let a=e.shippingAddress,i=e.email,n=a?.phoneNumber;if(a||n||i){let o=a?Qr(a):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let a=e.callbackTrigger;try{if(a==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(a==="SHIPPING_ADDRESS"||a==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Qr(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:Tn(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:a==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:a,totalOrderAmount:i}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:a,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:na(i,a),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:a,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Oa.SUBTOTAL,Ba.SUBTOTAL),type:"SUBTOTAL",price:na(i,a)}),c):(n&&n.length>0&&n.forEach(m=>{c.push({label:m.description||this.translate(Oa.ITEM,Ba.ITEM),type:"LINE_ITEM",price:na(m.amount,a)})}),o&&o.length>0&&o.filter(m=>m.amount!==0).forEach(m=>{c.push({label:m.type||m.description||this.translate(Oa.FEE,Ba.FEE),type:"LINE_ITEM",price:na(m.amount,a)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Oa.SHIPPING,Ba.SHIPPING),type:"LINE_ITEM",price:na(s.amount,a)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return Nn;let a=e.map(i=>fc[i]).filter(i=>!!i);return a.length>0?a:Nn}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,a=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:Pn,apiVersionMinor:In,...a&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:Tn(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}};function Ac(r,t){var e={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,a=Object.getOwnPropertySymbols(r);i<a.length;i++)t.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(r,a[i])&&(e[a[i]]=r[a[i]]);return e}function Cc(r,t){var e=document.querySelector('script[src="'.concat(r,'"]'));if(e===null)return null;var a=mo(r,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(a.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==a.dataset[o]&&(n=!1)}),n?e:null}function Mc(r){var t=r.url,e=r.attributes,a=r.onSuccess,i=r.onError,n=mo(t,e);n.onerror=i,n.onload=a,document.head.insertBefore(n,document.head.firstElementChild)}function Ec(r){var t=r.sdkBaseUrl,e=r.environment,a=Ac(r,["sdkBaseUrl","environment"]),i=t||Ic(e),n=a,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,m){var g=n[m].toString();return m=Tc(m),m.substring(0,4)==="data"||m==="crossorigin"?c.attributes[m]=g:c.queryParams[m]=g,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Pc(s)),attributes:l}}function Tc(r){var t=function(e,a){return(a?"-":"")+e.toLowerCase()};return r.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Pc(r){var t="";return Object.keys(r).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+r[e]}),t}function Ic(r){return r==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function mo(r,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=r,Object.keys(t).forEach(function(a){e.setAttribute(a,t[a]),a==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Nc(r,t){if(t===void 0&&(t=Promise),ho(r,t),typeof document>"u")return t.resolve(null);var e=Ec(r),a=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=kn(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),Cc(a,i)&&o?t.resolve(o):kc({url:a,attributes:i},t).then(function(){var s=kn(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function kc(r,t){t===void 0&&(t=Promise),ho(r,t);var e=r.url,a=r.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(a!==void 0&&typeof a!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();Mc({url:e,attributes:a,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function kn(r){return window[r]}function ho(r,t){if(typeof r!="object"||r===null)throw new Error("Expected an options object.");var e=r.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Ga=new Map,Ln={getOrCreateNamespace(r){let t=Ga.get(r);return t?t.namespace:Te()},getInstance(r){return Ga.get(r)?.instance??null},storeInstance(r,t,e){Ga.set(r,{instance:t,namespace:e})},hasInstance(r){return Ga.has(r)}};async function Lc({context:r,configId:t,paymentMethodType:e,callbacks:a}){try{let{action:i}=await a.onStart();if(i==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e});await r.clientSessionApi.selectPaymentMethod(e);let{data:n,error:o}=await r.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),a.onFinish(void 0,i),i instanceof G||i instanceof $?i:new G({message:"Failed to create billing agreement",code:F.PAYMENT_FAILED,paymentMethod:e})}}async function Rc({context:r,configId:t,paymentMethodType:e,callbacks:a,data:i}){try{let n=i.billingToken;if(!n)throw new $({message:"Billing token not provided",code:F.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await r.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let h=s?.message??"Failed to confirm billing agreement";throw new $({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:m,data:g}=await r.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(m||!g){let h=m?.message??"Unable to vault PayPal payment method";throw new $({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}a.onFinish(g)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),a.onFinish(void 0,n),n instanceof $||n instanceof G?n:new $({message:"Failed to approve billing agreement",code:F.TOKENIZATION_ERROR,paymentMethod:e})}}var xc="gold",_c="black",wc="rect",Dc="paypal",Oc="vertical",go="horizontal",Rn=2,xn=["paypal","paylater"],yo={default:{color:xc},card:{validColors:["black","white"],defaultColor:_c}};function Bc(r){if(!r)return;let t=yo[r];if(t&&"validColors"in t)return t}function Gc(r,t){let e=Bc(t);if(!e)return r??yo.default.color;let a=r??e.defaultColor;return e.validColors.includes(a)?a:(C.warn(`PayPal: Invalid color "${a}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var Kc=25,Fc=55;function Uc(r){return parseFloat(r)||0}function Vc(r){let t=Uc(r);return Math.max(Kc,Math.min(Fc,t))}function Hc(r,t,e){let a=t?r?.[t]:void 0,i=a?.tagline??r?.tagline??!1,n=i?go:Oc,o,s=a?.height??r?.height;s!=null?o=s:e!=null&&(o=Vc(String(e)));let l=a?.borderRadius??r?.borderRadius,c=a?.disableMaxWidth??r?.disableMaxWidth,m=a?.color??r?.color;return{color:Gc(m,t),shape:a?.shape??r?.shape??wc,label:a?.label??r?.label??Dc,layout:a?.layout??r?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function Yc(r,t,e,a){let i={style:r,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&a?(i.createBillingAgreement=a.createBillingAgreement,i.onApprove=a.onApprove):i.onApprove=e.onApprove,i}function zc(r){if(!r)return;let t={first_name:r.firstName,last_name:r.lastName,address_line_1:r.addressLine1??"",address_line_2:r.addressLine2,city:r.city??"",state:r.state,postal_code:r.postalCode??"",country_code:r.countryCode??""},{address_line_1:e,city:a,postal_code:i,country_code:n}=t;if(!(!e||!a||!i||!n))return t}function $c(r){if(!r)return null;let t=r.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,a=t.name;return{firstName:a?.given_name,lastName:a?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function jc(r,t,e){let{order:{currencyCode:a,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=r;if(!a)throw new G({message:"Currency code is not provided",code:It.MISSING_PARAMETER,paymentMethod:e});let m={amount:i??n,currencyCode:a,paymentMethodConfigId:t,amountBreakdown:{}},g=c?.shippingAddress,h=zc(g);h&&(m.shipping_address=h);let T=!s.some(M=>!M.name&&!M.description);if(T&&(m.items=s.map(M=>{let{name:_,description:x,taxAmount:E,amount:L,quantity:K}=M,j=E?Math.floor(E/K):0;return{name:x||_||"",unit_amount:{value:L,currency_code:a},quantity:K.toString(),tax:{value:j,currency_code:a}}})),T&&s.length){let M=s.reduce((de,{amount:H,quantity:De})=>de+H*De,0),_=l?.reduce?.((de,{amount:H})=>de+(H??0),0),x=s?.reduce((de,{discountAmount:H})=>de+(H??0),0),E=s?.reduce((de,{taxAmount:H})=>de+(H??0),0),L=o?.amount??0,K=_??0,j=M+E+L+K-x;m.amountBreakdown={item_total:{value:M,currency_code:a},tax_total:{value:E,currency_code:a},handling:{value:K,currency_code:a},shipping:{value:L,currency_code:a},discount:{value:x,currency_code:a}},m.amount=j}return m}async function Wc({context:r,configId:t,paymentMethodType:e,callbacks:a,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await a.onStart();if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e})}await r.clientSessionApi.selectPaymentMethod(e);let{data:n,error:o}=await r.coreApi.createPaypalOrder(jc(r.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw a.onFinish(void 0,n),n}}async function Zc({context:r,paymentMethodType:t,callbacks:e,data:a,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:g}=await e.onStart();if(g==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(g){C.warn("Failed to get PayPal order details",g)}let s=$c(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:a.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:a.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:m}=await r.pciApi.postPaypalPaymentInstruments(l);if(c||!m){let g=c?.message??"Unable to create payment instrument";throw new $({message:g,code:F.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(m)}var Jc=["buttons","funding-eligibility"],_n=[],wn="paypal";function fo(r){if(!r?.length)return;r.includes(wn)&&C.warn("PayPal: Cannot disable paypal funding source");let t=r.filter(e=>e!==wn);return t.length>0?t:void 0}var qc="authorize";function Qc(r,t,e){return(r??t==="PREFER_VAULT")&&e}function Dn({isVaultFlow:r,configIntent:t}){return r?"tokenize":t??qc}function Xc(r,t,e,a){let{clientId:i,intent:n}=t.options,o=r.configuration.clientSession.order.currencyCode,s=r.clientOptions.paypal?.disableFunding??(_n.length>0?_n:void 0),l=fo(s),c=r.clientOptions?.paypal?.enableFunding,m={dataNamespace:e,clientId:i,currency:o,components:Jc,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:r.clientOptions.paypal?.integrationDate,debug:r.clientOptions.paypal?.debug};return(li||r.decodedClientToken.env==="SANDBOX"||r.decodedClientToken.env==="STAGING")&&(m.buyerCountry=r.clientOptions?.paypal?.buyerCountry),a?(m.vault="true",m.intent=Dn({isVaultFlow:!0,configIntent:n})):(m.vault="false",m.intent=Dn({isVaultFlow:!1,configIntent:n})),m}var ja=class extends mt{constructor(e,a){super(e,a);k(this,"paypalInstance");k(this,"dataNamespace");k(this,"isVaultFlow",!1);k(this,"isSetupComplete",!1);k(this,"setupPromise");k(this,"eligibleFundingSources",[]);k(this,"currentFundingSource",null);k(this,"onStartDeferred",!1);k(this,"disabled",!1);this.dataNamespace=Ln.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new $({message:"PayPal does not support direct tokenization",code:F.TOKENIZATION_ERROR,paymentMethod:O.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let a=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=Qc(a,i,n);let o=Xc(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Nc(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,Ln.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=fo(this.context.clientOptions.paypal?.disableFunding),g=(s.getFundingSources?.()??[]).filter(h=>s?.isFundingEligible?.(h));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",g),this.eligibleFundingSources=this.filterFundingSources(g,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(a){return C.warn("PayPal setup failed:",{error:a}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,a){let{Buttons:i}=this.paypalInstance;if(!i)throw new G({message:"PayPal Buttons component not available",code:It.INVALID_USAGE,paymentMethod:O.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=a?.style?.buttonHeight,s=n?.layout===go,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>Lc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>Rc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,m=this.eligibleFundingSources,g=[];for(let M of m){let _=Hc(n,M,o),x=Yc(_,this.isVaultFlow,l,c);this.isVaultFlow||(x.createOrder=this.handleCreateOrder.bind(this));let E=i({...x,fundingSource:M});E.isEligible()?g.push({button:E,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(g.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new G({message:"No PayPal buttons eligible to render",code:It.INVALID_USAGE,paymentMethod:O.PAYPAL});let h=s&&g.length>Rn?this.selectButtonsForHorizontalLayout(g):g;s&&this.applyHorizontalLayoutStyles(e,h.length);let T=h.map(({button:M})=>M.render(e));await Promise.all(T)}selectButtonsForHorizontalLayout(e){let a=new Set(xn),i=xn.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!a.has(o.fundingSource));return[...i,...n].slice(0,Rn)}applyHorizontalLayoutStyles(e,a){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${a}, 1fr)`,e.style.gap="10px"}handleInit(e,a){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),a.disable();return}a.enable()}handleClick(e,a){return this.currentFundingSource=e.fundingSource??null,Nt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),a.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,Wc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,a){let i=this.onStartDeferred;return this.onStartDeferred=!1,Zc({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:a,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new G({message:"The PayPal payment was cancelled by the user.",paymentMethod:O.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,a,i){return e.filter(n=>!(a?.length&&!a.includes(n)||i?.includes(n)))}};function On(r,t,e){if(!r)return null;let a={id:r.id,orderId:r.orderId};return t?.paymentInstrumentData&&e&&(a.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),a}var vo=(r,t,e,a,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void r.onCheckoutComplete?.({payment:On(t,a,i)});r.onCheckoutFail?.(n||new G({code:F.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:On(t,a,i)??void 0})},eu=async(r,t)=>{let e=t.config.type;if(!r.onBeforePaymentCreate)return{action:"continue"};let a=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);return new Promise(i=>{r.onBeforePaymentCreate({paymentMethodType:e},{continuePaymentCreation:n=>{clearTimeout(a),C.log(`Continuing payment creation for ${e}`),n?.idempotencyKey&&t.setIdempotencyKey(n.idempotencyKey),r.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(a),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})})};async function pa(r,t,e){if(t.setCallbacks({onStart:()=>(Nt({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:t.config.type}),eu(r,t)),onFinish:(a,i)=>{Bn(r,t,a,i)}}),!e)return t.start();{let a,i;try{i=await t.tokenizeVaulted(e.id)}catch(n){a=n}return Bn(r,t,i,a)}}async function Bn(r,t,e,a){let i;if(e&&!a)try{i=await t.createPayment(e),i.status!=="FAILED"&&(i=await t.handleRequiredAction(i))}catch(n){a=n}vo(r,i,a,e,t.config.type)}var Gn=Symbol("PROXY_MARKER");function Ai({namespace:r,onMessage:t,sendMessage:e}){function a(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[Gn])return Reflect.get(o,s,l);let c=()=>{};return c[Gn]=!0,a(c,[...n,s])},apply(o,s,l){return new Promise(async(c,m)=>{try{let g=[],h=l.map(x=>{if(typeof x!="function")return x;{let E=Te();return g.push(E),t(L=>{L.namespace===r&&L.sender===ei.PROVIDER&&L.type===Xr.CALLBACK&&L.id===E&&x(...L.data)}),E}}),T=Te(),M=t(x=>{x.namespace===r&&x.sender===ei.PROVIDER&&x.type===Xr.APPLY&&x.id===T&&(x.error?m(new Error(x.error)):c(x.data),M?.())}),_={type:Xr.APPLY,sender:ei.INJECTOR,id:T,path:n,args:h,callbackIds:g,timeStamp:Date.now(),namespace:r};e(_)}catch(g){m(g)}})}})}return a({},[])}var Xr={APPLY:"apply",CALLBACK:"callback"},ei={PROVIDER:"provider",INJECTOR:"injector"};function di(r,t){let e=t?.input?.base?.height;e&&(r.style.height=typeof e=="number"?`${e}px`:e)}function tu(r,t,e,a={}){let i=r.cardholderName?.defaultValue??r.card?.cardholderName?.defaultValue,n=po(t.checkoutSessionId,{cardholderName:i});e.iframes=n;let o=[],s="LOCAL",l={[ce.cardNumber]:void 0,[ce.cardExpiryDate]:void 0,[ce.cardSecurityCode]:void 0,[ce.cardholderName]:void 0},c=!1;t.subscribeToTeardown(()=>{c=!0});let m={createHostedInputs:()=>{let g=h=>{let T=new Map;return{getOptions:()=>{},setOptions:M=>{di(e.iframes[h],M.style),e.iframes[h].setAttribute("title",M.ariaLabel||""),l[h]?.setOptions(M)},render:(M,_)=>{let x=e.iframes[h];if(!x)return C.errorWithDatadog(`No iframe found for ${h}`),Promise.resolve();let E;return E=typeof M=="string"?document.getElementById(M):M,E?(di(x,_.style),E.appendChild(x),new Promise(L=>{x.onload=()=>{if(c){C.warn(`Teardown was already called, aborting render for ${h}`),x.remove(),L();return}l[h]=Ai({namespace:`${t.checkoutSessionId}-${h}`,onMessage:H=>{let De=Wr=>H(Wr.data);return window.addEventListener("message",De),()=>window.removeEventListener("message",De)},sendMessage:H=>{x.contentWindow.postMessage(H,"*")}}),e.iframes[h].setAttribute("title",_.ariaLabel||"");let K=r.cardholderName??r.card?.cardholderName,{defaultValue:j,...de}=K??{};l[h].setOptions({..._,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:de}),l[h].setOnBlur(()=>{try{T.get("blur")?.()}catch(H){C.errorWithDatadog(`Blur listener error for ${h}`,{error:H})}}),l[h].setOnFocus(()=>{try{T.get("focus")?.()}catch(H){C.errorWithDatadog(`Focus listener error for ${h}`,{error:H})}}),l[h].setOnInput(H=>{let De={...H,errorCode:H.error,active:H.focused};try{T.get("input")?.(De),T.get("change")?.(De)}catch(Wr){C.errorWithDatadog(`Input listener error for ${h}`,{error:Wr})}}),l[h].setOnEnter(()=>{try{T.get("enter")?.()}catch(H){C.errorWithDatadog(`Enter listener error for ${h}`,{error:H})}}),h===ce.cardNumber&&(l[h].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),l[h].setOnCardNetworksChange((H,De)=>{(De!==s||au(o,H))&&(o=H,s=De,a.onCardNetworksChange?.(ru({networks:o,source:s},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks)))}))},L()})):(C.error(`Container not found for ${h}:`,M),Promise.resolve())},addEventListener:(M,_)=>{T.set(M,_)},focus:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.focus()}catch(_){C.errorWithDatadog(`Focus send error for ${h}`,{error:_})}else C.warn(`Focus failed for ${h} - iframe not available`)},blur:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.blur()}catch(_){C.errorWithDatadog(`Blur send error for ${h}`,{error:_})}},setDisabled:M=>{l[h]?.setDisabled(M)}}};return{cardNumberInput:g(ce.cardNumber),cardholderNameInput:g(ce.cardholderName),expiryInput:g(ce.cardExpiryDate),cvvInput:g(ce.cardSecurityCode)}},removeHostedInputs:()=>{c=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()},submit:async g=>{if((await m.validate()).valid)return await t.apiController.setPreferredNetwork(g?.cardNetwork),pa(r,e)},validate:async()=>{let g=(await Promise.all(Object.entries(l).map(([T,M])=>M?.getFieldState().then(_=>[T,_]).catch(()=>{})))).filter(T=>T!==void 0),h=[];for(let[T,M]of g)!M.valid&&M.error&&h.push({field:T,name:T,error:M.error,message:M.error});return{valid:h.length===0,validationErrors:h}},reset:()=>{Object.values(l).forEach(g=>{g?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:g=>{try{l[ce.cardholderName]?.setCardholderName(g)}catch(h){C.errorWithDatadog("SetCardholderName error",{error:h})}}};return m}function au(r,t){if(r.length!==t.length)return!0;let e=t.map(({network:a})=>a);return!r.every(({network:a})=>e.includes(a))}function ru({networks:r,source:t},e){let a=e,i=new Set(a.map(l=>Wa(l).backend)),n=r.map(l=>({...l,allowed:i.has(l.network)})).sort((l,c)=>l.allowed?a.indexOf(l.network)-a.indexOf(c.network):1),o=n.filter(l=>l.allowed),s=t==="REMOTE"&&o.length>1;return{detectedCardNetworks:{items:n,preferred:o[0]},...s&&{selectableCardNetworks:{items:o,preferred:o[0]}},source:t}}function iu(r,t,e){return{createButton:()=>({render:async(a,i)=>{await pa(r,e);let n=typeof a=="string"?document.getElementById(a):a;if(!n)throw new G({code:Jd.CONTAINER_NOT_FOUND,message:`Container with id "${a}" not found in the DOM.`});await e.render(n,i)},setDisabled:a=>e.setDisabled(a)})}}function nu(r,t,e){return{start:()=>pa(r,e)}}function ou(r,t,e){return{start:async a=>(a?.blikCode&&e.setBlikCode(a.blikCode),pa(r,e))}}function su(r,t){return{"Content-Type":"application/json","primer-client-token":r,"primer-sdk-client":"WEB","primer-sdk-version":"0.0.0-local","primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}function lu(r,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(r instanceof Error){let a=r.message.toLowerCase();return a.includes("network")||a.includes("timeout")||a.includes("connection")}return!1}function du(r){let n=1e3*Math.pow(1.1,r),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var cu={attempts:3,retryCondition:lu,delayCalculator:du,totalTimeout:3e5};async function uu(r,t,e){let a={...cu,...t.retry},i=[],n=Date.now();for(let s=0;s<=a.attempts;s++)try{let l=await r();if(!l.error)return{...l,retryHistory:i.length>0?i:void 0};if(s===a.attempts||!a.retryCondition(l.error,s,l))return{...l,retryHistory:i};let c=a.delayCalculator(s);if(i.push({attempt:s+1,delay:c,error:l.error,timestamp:Date.now()}),Date.now()-n+c>a.totalTimeout)return{...l,error:new Oe({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:ua({status:408}),response:l}),retryHistory:i};await Ht(c)}catch(l){i.push({attempt:s+1,delay:0,error:new Oe({message:`Request failed for ${t.method} ${e}`,code:q.UNEXPECTED,error:l,response:{id:t.id}}),timestamp:Date.now()})}let o=i[i.length-1]?.error;return{id:t.id,error:o,retryHistory:i}}var zt=class{constructor(t,e="",a={}){k(this,"fetch");k(this,"baseUrl");k(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...a})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let a={...e,headers:{...this.defaultHeaders,...e?.headers},id:Te()};return e?.retry?uu(()=>this.fetch(t,{...a,retry:void 0}),a,t):this.fetch(t,a)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,a){return this.executeFetch(t,{...a,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}};async function pu(r,t){let e=t.id??Te(),a={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(r,t);if(a.data=await i.json(),a.status=i.status,a.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new Oe({message:`Request failed for ${t.method} ${r}`,code:ua({backendErrorId:a.data?.error?.errorId,status:a.status}),response:{...a}});a.error=n}}catch(i){let n=new Oe({message:`Request failed for ${t.method} ${r}`,code:ua({status:a.status}),response:{...a},error:i});a.error=n}return a}var ci=class extends zt{constructor(){super(...arguments);k(this,"configurationSubscribers",new Set);k(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this._configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=e,this.configurationSubscribers.forEach(a=>a(this._configuration))}},ui=class extends zt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}};async function mu(r){return new Promise((t,e)=>{let a=uo(r,"api"),i=`${pc}#${a}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${o}`))},n.src=i,document.body.appendChild(n))})}var ca=class ca extends zt{constructor(){super(...arguments);k(this,"onClientSessionUpdate");k(this,"onPaymentMethodAction");k(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return ca.noActionsResponse;let a=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=a;return i&&this.onClientSessionUpdate?.(i),a}async selectPaymentMethod(e,a={}){return this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...a,paymentMethodType:e}}])}async unselectPaymentMethod(){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(O.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let a=this.removeEmptyStringFromObject(e);return Object.values(a).length===0?ca.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:a}}])}async setShippingAddress(e,a,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),a&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:a}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:a,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),a&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:a}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:a}=Wa(e);return{network:a,issuer_name:null,product_code:a,product_name:a,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let a={...e};for(let i in a)a[i]===""?delete a[i]:typeof a[i]=="object"&&a[i]!==null&&!Array.isArray(a[i])&&(a[i]=this.removeEmptyStringFromObject(a[i]));return a}};k(ca,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var pi=ca,mi=class extends zt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}};async function hu(r,{locale:t,dialogProvider:e,translate:a,clientOptions:i}){let n=Te(),o=Vt(r),s=await mu(n),l=Ai({namespace:`api-controller-${n}`,onMessage:E=>{let L=K=>{if(K.data?.data?.error?.name==="RequestError"){let j=Object.assign(new Oe({...K.data.data.error}),K.data.data.error);typeof j.error=="object"&&"message"in j.error&&(j.error=Object.assign(new Error(j.error.message),{stack:j.error.stack})),K.data.data.error=j}return E(K.data)};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},sendMessage:E=>{s.contentWindow.postMessage(E,"*")}}),c=su(o.accessToken,n),m=new ci(pu,o.configurationUrl,c),g=Date.now(),{error:h}=await m.getConfiguration();if(h||!m.configuration)throw new Error(`Failed to fetch configuration: ${h}`);let T=new ui(l.fetch,m.configuration.pciUrl,c),M=new mi(l.fetch,m.configuration.coreUrl,c),_=new pi(l.fetch,m.configuration.pciUrl,c);_.setOnClientSessionUpdate(E=>{m.configuration=E});let x=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(E){return m.subscribe(E)},checkoutSessionId:n,apiController:l,configurationApi:m,pciApi:T,coreApi:M,clientSessionApi:_,dialogProvider:e,decodedClientToken:o,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:a??((E,L)=>L),clientOptions:i,updateClientToken(E){try{let L=Vt(E);m.setDefaultHeader("primer-client-token",L.accessToken),T.setDefaultHeader("primer-client-token",L.accessToken),M.setDefaultHeader("primer-client-token",L.accessToken),_.setDefaultHeader("primer-client-token",L.accessToken)}catch{}},async refreshClientConfiguration(){let{data:E,error:L}=await m.getConfiguration();return L||!E?(C.warn("Failed to refresh client configuration:",L),!1):(m.configuration=E,!0)},subscribeToTeardown(E){return x.add(E),()=>{x.delete(E)}},teardown(){s.remove(),x.forEach(E=>E())}}}var gu=100;function yu({height:r,name:t,url:e="",width:a}){let i=new Set,n=window.open(e,t,vu({height:r,width:a}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),fu(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var fu=r=>new Promise(t=>{let e=setInterval(()=>{r.closed&&(clearInterval(e),t())},gu)});function vu(r){let t=Su({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:r});return bu(t)}var Su=({parent:r,popup:t})=>({left:r.left+(r.width-t.width)/2,top:r.top+(r.height-t.height)/2,height:t.height,width:t.width}),bu=r=>Object.entries(r).map(t=>t.join("=")).join(","),Au=({name:r,background:t,logoSrc:e,logoAlt:a,message:i})=>`<html>
37
37
  <head>
38
38
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
39
39
  <style>
@@ -143,7 +143,7 @@ import{a as xa,b as d,c as k}from"./chunks/chunk.DV3REKZU.js";var _a=class{const
143
143
  </html>
144
144
  `,hi=class extends mt{constructor(){super(...arguments);k(this,"popup");k(this,"shouldRedirect",!1);k(this,"dialogPromise")}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));(this.config.forceRedirect||this.context.clientOptions.redirect?.forceRedirect||Zd())&&(this.shouldRedirect=!0);let a=document.createElement("div");a.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let n=document.createElement("img");n.src=this.logoSrc,i.appendChild(n),a.appendChild(i);let o=document.createElement("p");o.setAttribute("style","max-width: 300px;text-align: center;"),o.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),a.appendChild(o),this.dialogPromise=this.context.dialogProvider.show({htmlContent:a,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}),this.shouldRedirect||(this.openPopup(),this.popup&&await Ht(300),this.popup?.isOpen||(this.shouldRedirect=!0));let s=await this.tokenize();this.callbacks.onFinish(s)}catch(e){this.context.dialogProvider.close(),this.popup?.close(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:ro()?"MOBILE_WEB":"WEB",browserInfo:bi(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!a)throw e??new $({message:"Unable to tokenize payment method",code:F.TOKENIZATION_ERROR});return a}async createPayment(e){try{let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new $({message:"No client token provided"});let n=Vt(i);if(!zd(n,this.config.type))throw new $({message:"Invalid client token"});if(this.shouldRedirect)return Nt({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:this.config.type,redirectDestinationUrl:n.redirectUrl}),window.location.assign(n.redirectUrl),Promise.resolve(a);if(!this.popup?.isOpen)return this.unselect(),this.context.dialogProvider.close(),a;this.popup?.setUrl(n.redirectUrl);let o=(this.dialogPromise??Promise.resolve()).then(()=>({id:"",popupClosed:!0})),s=new Promise(h=>{this.popup?.onClose(()=>{C.debug("Popup closed"),h({id:"",popupClosed:!0})})}),{promise:l,abort:c}=this.pollStatus(n.statusUrl),m=await Promise.race([o,s,l]);if(c(),this.popup?.close(),this.context.dialogProvider.close(),"error"in m)throw m.error;if("popupClosed"in m&&m.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(),a;let g=m.id;if(!g){let h=await this.context.pciApi.getResumeStatus(n.statusUrl);if(h.error||!h.data?.id)throw h.error??new Error("Unable to get resume token");g=h.data.id}return await this.resumePayment(a.id,g)}catch(a){throw this.context.dialogProvider.close(),this.popup?.close(),a}}unselect(){this.context.clientSessionApi.unselectPaymentMethod()}pollStatus(e){let a=!0;return{promise:new Promise(async i=>{for(;a;){let{data:n,error:o}=await this.context.pciApi.getResumeStatus(e);if(o)return void i({error:o});if(await Ht(1e3),n?.status==="COMPLETE")return void i({id:n.id})}}),abort:()=>{C.debug("Polling aborted"),a=!1}}}openPopup(){let{name:e,displayMetadata:{popup:a}}=this.config;this.popup=yu({name:e,height:a?.height??500,width:a?.width??1e3}),this.popup?.setContent(Au({name:e,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:e,message:`Loading ${e}...`}))}get backgroundColor(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.backgroundColor.colored||e?.backgroundColor.colored||a?.backgroundColor.light||e?.backgroundColor.light||a?.backgroundColor.dark||e?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.logo.colored||e?.iconUrl.colored||a?.logo.light||e?.iconUrl.light||a?.logo.dark||e?.iconUrl.dark}},Cu=[O.ADYEN_AFFIRM,O.ADYEN_BANCONTACT_CARD,O.ADYEN_BANCONTACT_PAYCONIQ,O.ADYEN_EPS,O.ADYEN_KLARNA,O.ADYEN_MBWAY,O.ADYEN_MULTIBANCO,O.GO_CARDLESS,O.KLARNA,O.MOLLIE_GIFT_CARD,O.NETS,O.OMISE_PROMPTPAY,O.PAY_NL_KAARTDIRECT,O.PAY_NL_PAYPAL,O.RAPYD_FAST,O.RAPYD_PROMPTPAY,O.STRIPE_ACH,O.XFERS_PAYNOW];async function Mu(r,t){let e=r.configuration.paymentMethods.filter(({type:i})=>!t||t.includes(i)).map(i=>{if(Cu.includes(i.type))return C.warn(`Payment method ${i.type} is not supported in sdk core.`),null;if(C.debug("Initializing payment method:",i.type),i.implementationType==="WEB_REDIRECT")return new hi(i,r);if(i.type===O.PAYMENT_CARD)return new za(i,r);if(i.type===O.PAYPAL)return new ja(i,r);if(i.type===O.APPLE_PAY)return new Ha(i,r);if(i.type===O.GOOGLE_PAY)return new $a(i,r);if(i.type===O.ADYEN_BLIK)return new Ya(i,r)}).map(async i=>{if(!i)return null;try{return await i.setup()?i:null}catch(n){return C.warn(`Failed to initialize payment method ${i.config.type}:`,n),null}});return(await Promise.all(e)).filter(i=>!!i)}function Eu(r,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new G({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let a=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new G({code:Da.VAULT_ERROR,message:"Missing vaulted payment methods data"});return a=i.data,a},async deleteVaultedPaymentMethod(i){if(!a.find(s=>s.id===i))throw new G({code:Da.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;a=a.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=a.find(s=>s.id===i);if(!n)throw new G({code:Da.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new $({code:Da.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await pa(r,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=sa(t.checkoutSessionId,En);await new Promise(h=>{s.onload=()=>{h()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),di(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=Ai({namespace:`${t.checkoutSessionId}-${En}`,onMessage:h=>{let T=M=>h(M.data);return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},sendMessage:h=>{s.contentWindow.postMessage(h,"*")}});function c(h,T){h!=="metadata"&&n[h].add(T)}l.setOnFocus(()=>{n.focus.forEach(h=>h())}),l.setOnBlur(()=>{n.blur.forEach(h=>h())}),l.setOnInput(h=>{o=h,n.change.forEach(T=>T())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function m(){s.parentNode&&s.remove()}let g=t.subscribeToTeardown(m);return{frame:s,remove:()=>{g(),m()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(h,T){h!=="metadata"&&n[h].delete(T)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(h=>{o=h,n.change.forEach(T=>T(o))})}}}}}async function So(r,t){C.debug("createHeadless",t);let e=await hu(r,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,merchantDomain:t.merchantDomain,redirect:t.redirect}}),a=await Mu(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction(t.onPaymentMethodAction);let i={environment:li?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:r,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return Ld({environment:li?"LOCAL":e.decodedClientToken.env,primerAccountId:i.primerAccountId||"",checkoutSessionId:i.checkoutSessionId,clientSessionId:i.clientSessionId||"",clientSessionToken:i.clientSessionToken,sdkVersion:i.sdkVersion||"",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"}),t.onAvailablePaymentMethodsLoad?.(a.map(n=>({type:n.config.type,managerType:n.config.type===O.PAYMENT_CARD?Zr.CARD:n.config.implementationType==="NATIVE_SDK"?Zr.NATIVE:Zr.REDIRECT}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);vo(t,n,o)}},createPaymentMethodManager:async(n,o)=>{let s=a.find(({config:l})=>l.type===n);return s?s instanceof za?tu(t,e,s,o):s instanceof ja||s instanceof Ha||s instanceof $a?iu(t,e,s):s instanceof Ya?ou(t,e,s):nu(t,e,s):(C.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:Kn,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return no(e.locale,n??o,s)},getCDNAssets:async n=>{let o=a.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s,iconUrl:l}=o.config.displayMetadata?.button||{};return{assets:{icon:l?.colored||""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:""}},getPaymentMethodConfiguration:n=>a.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new G({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return Eu(t,e,a)},getAssetsManager:()=>({getCardNetworkAsset:Kn,getPaymentMethodAsset:async n=>{let o=a.find(({config:m})=>m.type===n);if(!o)return null;let{backgroundColor:s,iconUrl:l,text:c}=o.config.displayMetadata?.button||{};return{backgroundColor:s,iconUrl:l,paymentMethodName:c,buttonText:c,displayName:o.config.name}}}),refreshClientSession:e.refreshClientConfiguration,getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}var Kn=r=>{let{asset:t,display:e}=Wa(r);return{cardUrl:`${hc}/brand/card/${t}.svg`,displayName:e}},Tu=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function jt(r){let{id:t,orderId:e,paymentMethodData:a}=r,i={id:t,orderId:e};if(!a||typeof a!="object")return i;let n={};for(let[o,s]of Object.entries(a))Tu.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var Pu={PAYMENT_CARD:{fields:["last4Digits","network","cardholderName","expirationMonth","expirationYear"]},PAYPAL_BILLING_AGREEMENT:{path:"externalPayerInfo",fields:["externalPayerId","email","firstName","lastName"]},KLARNA_CUSTOMER_TOKEN:{path:"sessionData.billingAddress",fields:["email","firstName","lastName","phoneNumber"]},AUTOMATED_CLEARING_HOUSE:{fields:["accountNumberLastFourDigits","bankName","accountType"]}};function Iu(r,t){let e=r;for(let a of t.split(".")){if(!e||typeof e!="object")return;e=e[a]}return e&&typeof e=="object"?e:void 0}function Nu(r,t){if(!r)return;let e={};for(let a of t)r[a]!==void 0&&(e[a]=r[a]);return Object.keys(e).length>0?e:void 0}function bo(r){let{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=r,s=Pu[i],l;if(s&&n&&typeof n=="object"){let c=s.path?Iu(n,s.path):n;l=Nu(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var Wt=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}dispatchCardSubmit(t){this.dispatchEvent("primer:card-submit",{source:t})}dispatchFormSubmitSuccess(t){this.dispatchEvent("primer:card-success",{result:t})}dispatchFormSubmitErrors(t){this.dispatchEvent("primer:card-error",{errors:t})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(){this.dispatchEvent("primer:payment-start",void 0)}dispatchPaymentSuccess(t,e){let a=jt(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{paymentSummary:a,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,a){let i=Math.floor(Date.now()/1e3),n=a?jt(a):void 0;this.dispatchEvent("primer:payment-failure",{error:t,paymentSummary:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault:methods-update",{vaultedPayments:t,timestamp:e})}dispatchVaultSelectionChange(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault:selection-change",{paymentMethodId:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}dispatchShowOtherPaymentsToggled(t){this.dispatchEvent("primer:show-other-payments-toggled",{expanded:t})}};var ht=class extends Event{constructor(t,e,a,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=a,this.subscribe=i??!1}};var Zt=class{constructor(t,e,a,i){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,e.context!==void 0){let n=e;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=e,this.callback=a,this.subscribe=i??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new ht(this.context,this.host,this.t,this.subscribe))}};var Ja=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let a=e||!Object.is(t,this.o);this.o=t,a&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:a}]of this.subscriptions)e(this.o,a)},t!==void 0&&(this.value=t)}addCallback(t,e,a){if(!a)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:e});let{disposer:i}=this.subscriptions.get(t);t(this.value,i)}clearCallbacks(){this.subscriptions.clear()}};var Ci=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},W=class extends Ja{constructor(t,e,a){super(e.context!==void 0?e.initialValue:a),this.onContextRequest=i=>{if(i.context!==this.context)return;let n=i.contextTarget??i.composedPath()[0];n!==this.host&&(i.stopPropagation(),this.addCallback(i.callback,n,i.subscribe))},this.onProviderRequest=i=>{if(i.context!==this.context||(i.contextTarget??i.composedPath()[0])===this.host)return;let n=new Set;for(let[o,{consumerHost:s}]of this.subscriptions)n.has(o)||(n.add(o),s.dispatchEvent(new ht(this.context,s,o,!0)));i.stopPropagation()},this.host=t,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new Ci(this.context,this.host))}};function A({context:r,subscribe:t}){return(e,a)=>{typeof a=="object"?a.addInitializer((function(){new Zt(this,{context:r,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new Zt(i,{context:r,callback:n=>{i[a]=n},subscribe:t})}))}}var gt=Symbol("analytics-context");var Ve=Symbol("events-context");var qa="cardNetworksContext";var ge="clientOptionsContext";var Jt="computedStylesContext";var z="headlessInstanceContext";var Qa="configuration";var Xa="klarnaCategoriesContext";var Z="managerContext";var yt="paymentMethodsContext";var J="sdkStateContext";var ye="vaultManagerContext";var He="vaultManagerCvvContext";function ku(r,t,e,a){let i=r,n=e;return{dispatch:o=>{let s=i,l=t(i,o,n);tr(s,l)?i=l:(i=l,a(l))},getState:()=>Object.freeze({...i}),setCallbacks:o=>{n={...n,...o}}}}function tr(r,t,e=0,a=10){if(e>a)return r===t;if(r===t)return!0;if(r==null||t==null||typeof r!="object"||typeof t!="object")return!1;let i=Object.keys(r);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=r[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!tr(o,s,e+1,a))return!1}else if(o!==s)return!1}return!0}function Mi(r){return(t,e,a)=>{let i=r[e.type];if(!i)throw new Error(`No handler for action type: ${e.type}`);return i(t,e,a)}}var kt=class{constructor(t,e,a,i,n=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=n;this.host.addController(this),this._dispatcher=ku(e,a,i,o=>{this.stateHandler(o)})}get currentState(){return this._dispatcher.getState()}dispatch(t){this._dispatcher.dispatch(t)}setCallbacks(t){this._dispatcher.setCallbacks(t)}hostConnected(){}hostDisconnected(){}},er=class{constructor(t){this.host=t;this._controllers=[];"addController"in this.host&&this.host.addController(this)}addController(t){this._controllers.push(t)}hostConnected(){this._controllers.forEach(t=>{t.hostConnected&&t.hostConnected()})}hostDisconnected(){this._controllers.forEach(t=>{t.hostDisconnected&&t.hostDisconnected()})}};var Ao={isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},Co=Ao;function Lu(r,t){switch(t.type){case"SET_LOADING":return{...r,isLoading:t.payload};case"SET_PROCESSING":return{...r,isProcessing:t.payload,...t.payload&&{primerJsError:null,paymentFailure:null}};case"SET_SUCCESS":return{...r,isSuccessful:t.payload};case"SET_PRIMER_JS_ERROR":return{...r,primerJsError:t.payload};case"SET_PAYMENT_FAILURE":return{...r,isProcessing:!1,paymentFailure:t.payload};case"COMPLETE_PROCESSING":return{...r,isProcessing:!1,isSuccessful:!0};case"RESET":return{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null};default:return r}}var ar=class extends kt{constructor(t){super(t,Ao,Lu,null,e=>{t.sdkContextController.setSdkState(e),t.primerEventsController.dispatchSdkState(e)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setProcessing(t){this.dispatch({type:"SET_PROCESSING",payload:t})}setSuccess(t){this.dispatch({type:"SET_SUCCESS",payload:t})}setPrimerJsError(t){this.dispatch({type:"SET_PRIMER_JS_ERROR",payload:t})}setPaymentFailure(t){this.dispatch({type:"SET_PAYMENT_FAILURE",payload:t})}completeProcessing(){this.dispatch({type:"COMPLETE_PROCESSING"})}reset(){this.dispatch({type:"RESET"})}startLoading(){this.setLoading(!0)}completeLoading(){this.setLoading(!1)}startProcessing(){this.setProcessing(!0)}stopProcessing(){this.setProcessing(!1)}resetError(){this.setPrimerJsError(null),this.setPaymentFailure(null)}forceCompleteLoading(){this.setLoading(!1)}};var rr=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.configurationProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;this.analyticsProvider=null;this.eventsProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new W(t,{context:J,initialValue:Co}),this.paymentMethodsProvider=new W(t,{context:yt,initialValue:null}),this.paymentManagerProvider=new W(t,{context:Z,initialValue:new Map}),this.cardNetworksContext=new W(t,{context:qa,initialValue:null}),this.vaultManagerProvider=new W(t,{context:ye,initialValue:null}),this.vaultManagerCvvProvider=new W(t,{context:He,initialValue:null}),this.clientOptionsContext=new W(t,{context:ge,initialValue:null}),this.klarnaCategoriesProvider=new W(t,{context:Xa,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new W(t,{context:z,initialValue:null}),this.configurationProvider=new W(t,{context:Qa,initialValue:null}),this.computedStylesProvider=new W(t,{context:Jt,initialValue:null}),this.analyticsProvider=new W(t,{context:gt,initialValue:null}),this.eventsProvider=new W(t,{context:Ve,initialValue:null})}hostConnected(){}setSdkState(t){this.sdkStateProvider?.setValue(t)}setPaymentMethods(t){this.paymentMethodsProvider?.setValue(t)}setPaymentManagers(t){this.paymentManagerProvider?.setValue(t)}setCardNetworks(t){this.cardNetworksContext?.setValue(t)}setVaultManager(t){this.vaultManagerProvider?.setValue(t)}setKlarnaCategories(t){this.klarnaCategoriesProvider?.setValue(t)}setClientOptions(t){this.clientOptionsContext?.setValue(t)}setHeadlessUtils(t){this.headlessUtilsProvider?.setValue(t)}setConfiguration(t){this.configurationProvider?.setValue(t)}setAnalyticsUtils(t){this.analyticsProvider?.setValue(t)}getAnalyticsUtils(){return this.analyticsProvider?.value}setComputedStyles(t){this.computedStylesProvider?.setValue(t)}setVaultManagerCvv(t){this.vaultManagerCvvProvider?.setValue(t)}setEventsController(t){this.eventsProvider?.setValue(t)}};var Ei=class{constructor(){k(this,"context",null)}initialize(t){this.context=t,P.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){P.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},Ye=new Ei;var Ru={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Mo(r,t={}){let e=Ye.getContext();if(!e&&!t?.environment)return;let i={message:r instanceof Error?r.message:typeof r=="string"?r:JSON.stringify(r)};r instanceof Error&&r.stack&&(i.stack=r.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};xu(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var Eo=(r,t={})=>Mo(r,{...t,status:"error"});function To(r){let t={event:"CHECKOUT_INITIALIZED"};r!==void 0&&(t.init_duration_ms=r),Mo("Checkout initialized",{status:"info",metadata:t})}function xu(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||r.hostname==="localhost"){P.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",r);return}let a=Ru[t||"LOCAL"];if(!a){P.warn("No logging endpoint configured for current environment");return}fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send log event:",i)})}var V=class V{static _log(t,e,...a){V.enabled&&a.forEach(i=>{i instanceof Error&&i.toJSON})}static log(t,...e){V._log("log",t,...e)}static info(t,...e){V._log("info",t,...e)}static warn(t,...e){V._log("warn",t,...e)}static error(t,...e){V._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:a,status:i="error"}=e||{};if(V.enabled){a instanceof Error&&a.toJSON;try{let n={status:i,metadata:{sdkOptions:V.sdkOptions,clientToken:V.clientToken,error:a}};Eo(t,n)}catch{V.enabled}}}static setSdkOptions(t){V.sdkOptions=t}static setClientToken(t){V.clientToken=t}};k(V,"enabled",!0),k(V,"sdkOptions"),k(V,"clientToken"),k(V,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),k(V,"brandTag","[PRIMER]"),k(V,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${V.defaultFont}`),k(V,"styles",{log:`color: #4CAF50; ${V.defaultFont}`,info:`color: #2196F3; ${V.defaultFont}`,warn:`color: #FF9800; ${V.defaultFont}`,error:`color: #F44336; ${V.defaultFont}`,debug:`color: #9C27B0; ${V.defaultFont}`});var P=V;var Lt=class Lt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){P.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let a=/^[\w\s#.,%()\-+/!]+$/.test(t);return a||P.warn(`Rejected potentially unsafe CSS value: ${t}`),a}getCssVarName(t){let e=Lt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(a,i)=>`-${i.toLowerCase()}`)}`,Lt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let a of Object.keys(t)){let i=t[a];if(!i)continue;if(!this.isValidCssProperty(a)){P.warn(`Skipping invalid CSS property name: ${a}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(a);e.push([n,i])}if(e.length>0)for(let[a,i]of e)this.host.style.setProperty(a,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of Lt.cssVarCache.keys()){let e=Lt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};Lt.cssVarCache=new Map;var ir=Lt;var nr=globalThis,sr=nr.ShadowRoot&&(nr.ShadyCSS===void 0||nr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Io=Symbol(),Po=new WeakMap,or=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Io)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(sr&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Po.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Po.set(e,t))}return t}toString(){return this.cssText}},No=r=>new or(typeof r=="string"?r:r+"",void 0,Io);var Ti=(r,t)=>{if(sr)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=nr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},lr=sr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return No(e)})(r):r;var{is:_u,defineProperty:wu,getOwnPropertyDescriptor:Du,getOwnPropertyNames:Ou,getOwnPropertySymbols:Bu,getPrototypeOf:Gu}=Object,ft=globalThis,ko=ft.trustedTypes,Ku=ko?ko.emptyScript:"",Fu=ft.reactiveElementPolyfillSupport,ma=(r,t)=>r,Pi={toAttribute(r,t){switch(t){case Boolean:r=r?Ku:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},dr=(r,t)=>!_u(r,t),Lo={attribute:!0,type:String,converter:Pi,reflect:!1,hasChanged:dr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ft.litPropertyMetadata??(ft.litPropertyMetadata=new WeakMap);var Rt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Lo){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&wu(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=Du(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get(){return i?.call(this)},set(o){let s=i?.call(this);n.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Lo}static _$Ei(){if(this.hasOwnProperty(ma("elementProperties")))return;let t=Gu(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ma("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ma("properties"))){let e=this.properties,a=[...Ou(e),...Bu(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(lr(i))}else t!==void 0&&e.push(lr(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ti(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$EC(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:Pi).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Pi;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){if(a??(a=this.constructor.getPropertyOptions(t)),!(a.hasChanged??dr)(this[t],e))return;this.P(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,a){this._$AL.has(t)||this._$AL.set(t,e),a.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a)n.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],n)}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EU()}catch(a){throw t=!1,this._$EU(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(t){}firstUpdated(t){}};Rt.elementStyles=[],Rt.shadowRootOptions={mode:"open"},Rt[ma("elementProperties")]=new Map,Rt[ma("finalized")]=new Map,Fu?.({ReactiveElement:Rt}),(ft.reactiveElementVersions??(ft.reactiveElementVersions=[])).push("2.0.4");var vt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},w=Symbol(),B=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((t,e)=>{this.o=t,this.h=e})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(t,e,a){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:a};this.v=i.task,this.j=i.args,this.m=i.argsEqual??Ro,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,a;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,a=o}if(this.p===i){if(e===w)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(a)}catch{}this.i=3,this.h?.(a)}this.u=e,this.l=a}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},Ro=(r,t)=>r===t||r.length===t.length&&r.every(((e,a)=>!dr(e,t[a])));var cr=class{constructor(t){this._methods=t}get(t){return this._methods.get(t)}toArray(){return Array.from(this._methods.values())}size(){return this._methods.size}},ur=class{constructor(t){this._methods=t}get(t){return this._methods.get(t)}toArray(){return Array.from(this._methods.values())}size(){return this._methods.size}};var Uu={SET_LOADING:(r,t)=>({...r,isLoading:t.payload}),SET_UPDATING:(r,t)=>({...r,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(r,t,e)=>({...r,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,headless:t.headless,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(r,t)=>({...r,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:r=>({...r,isLoading:!1,isUpdating:!1}),DISABLE:r=>({...r,enabled:!1}),RESET:()=>xo},Vu={INITIALIZE_CVV:(r,t,e)=>({...r,setCvvInput:e.setCvvInput,setSelectedVaultedPaymentMethod:e.setSelectedVaultedPaymentMethod}),SET_FORM_DIRTY:(r,t)=>({...r,formIsDirty:t.payload}),SET_CVV_INPUT:(r,t)=>({...r,cvvInput:t.payload}),SET_SELECTED_VAULTED_PAYMENT_METHOD:(r,t)=>({...r,selectedVaultedPaymentMethod:t.payload}),RESET_CVV:()=>_o},Hu=Mi(Uu),Yu=Mi(Vu),xo={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},_o={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Ii=class extends kt{constructor(t,e){super(t,xo,Hu,e,a=>{t.sdkContextController.setVaultManager(a)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,a,i,n){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:a,showEmptyState:i,headless:n})}updatePaymentMethods(t){this.dispatch({type:"UPDATE_PAYMENT_METHODS",payload:t})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}disable(){this.dispatch({type:"DISABLE"})}reset(){this.dispatch({type:"RESET"})}},Ni=class extends kt{constructor(t,e){super(t,_o,Yu,e,a=>{t.sdkContextController.setVaultManagerCvv(a)})}initializeCvv(t){this.dispatch({type:"INITIALIZE_CVV",createCvvInput:t})}setFormDirty(t){this.dispatch({type:"SET_FORM_DIRTY",payload:t})}setCvvInputState(t){this.dispatch({type:"SET_CVV_INPUT",payload:t})}setSelectedPaymentMethod(t){this.dispatch({type:"SET_SELECTED_VAULTED_PAYMENT_METHOD",payload:t})}resetCvv(){this.dispatch({type:"RESET_CVV"})}},ha=class extends er{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(a){let i=a instanceof Error?a:new Error("Failed to delete payment method");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,a=this.vaultManagerState.cvvRecapture,i=this.vaultItemState.cvvInput;if(!e||a&&(!i||i.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,a?{cvv:i.valueToken}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1),this.host.primerEventsController.dispatchVaultSelectionChange(e?.id??null)};this.startVaultPaymentById=async(e,a)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let i=this.vaultManagerState.vaultedPaymentMethods.find(n=>n.id===e);if(!i)throw new Error(`Payment method not found: ${e}`);this.setSelectedVaultedPaymentMethod(i),this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e,a?.cvv?{cvv:a.cvv}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");throw this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing(),n}};this.coreController=new Ii(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new Ni(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new B(this.host,{task:async([a,i])=>{if(!a||!i?.vaultEnabled)return this.coreController.disable(),w;this.coreController.setLoading(!0);try{let n=a();this._vaultManager=n,this.coreController.initializeVaultManager(n,i.vaultEnabled,!!i.captureVaultedCardCvv,i.showEmptyState??!1,i.headless??!1),this.itemController.initializeCvv(n.createCvvInput),await this.fetchVaultedPaymentMethods(!0),P.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(n){P.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:n});let o=n instanceof Error?n:new Error("Unknown error");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o)}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}initializeVaultManager(e,a){this.createVaultManagerFn=e,this.options=a??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}createVaultedPaymentsWrapper(e){let a=new Map;for(let i of e){let n=bo(i);a.set(n.id,n)}return new ur(a)}updatePaymentMethodsWithEvents(e){this.coreController.updatePaymentMethods(e);let a=this.createVaultedPaymentsWrapper(e);this.host.primerEventsController.dispatchVaultMethodsUpdate(a),this.host.primerJS?.handleVaultedMethodsUpdate(a,this.vaultManagerState.cvvRecapture),P.log("VaultManagerController: Dispatched vault methods update",{methodCount:e.length,filteredMethodCount:a.size()})}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let a=await this._vaultManager.fetchVaultedPaymentMethods();return P.log("VaultManagerController: Fetched payment methods",a),this.updatePaymentMethodsWithEvents(a),a}catch(a){let i=a instanceof Error?a:new Error("Failed to fetch payment methods");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}}};var wo=()=>Do.randomUUID?.()||zu(),zu=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r=>(r^$u()>>r/4).toString(16)),$u=()=>(Do.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,Do=typeof crypto<"u"?crypto:{};var ju={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},ki=class{sendEvent(t){let e=Ye.getContext();if(!e)return;let a={id:wo(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};Zu(a,e)}},Wu=new ki;function Oo(r){let t={...r,userAgent:r.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};Ye.initialize(t)}function Q(r){Wu.sendEvent(r)}function Bo(){Ye.clear()}async function Zu(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){P.debug(`Analytics event ${r.eventName}:`,r);return}let a=ju[t];return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send analytics event:",i)})}var ga="lit-localize-status";var Go=r=>typeof r!="string"&&"strTag"in r,pr=(r,t,e)=>{let a=r[0];for(let i=1;i<r.length;i++)a+=t[e?e[i-1]:i-1],a+=r[i];return a};var ya=(r=>Go(r)?pr(r.strings,r.values):r);var b=ya,Ko=!1;function Li(r){if(Ko)throw new Error("lit-localize can only be configured once");b=r,Ko=!0}var Ri=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(ga,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(ga,this.__litLocalizeEventHandler)}},Ju=r=>r.addController(new Ri(r)),Fo=Ju;var D=()=>(r,t)=>(r.addInitializer(Fo),r);var fa=class{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}};var tt=[];for(let r=0;r<256;r++)tt[r]=(r>>4&15).toString(16)+(r&15).toString(16);function Uo(r){let t=0,e=8997,a=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<r.length;c++)e^=r.charCodeAt(c),t=e*435,a=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,a+=t>>>16,e=t&65535,n+=a>>>16,i=a&65535,l=s+(n>>>16)&65535,o=n&65535;return tt[l>>8]+tt[l&255]+tt[o>>8]+tt[o&255]+tt[i>>8]+tt[i&255]+tt[e>>8]+tt[e&255]}var qu="",Qu="h",Xu="s";function Vo(r,t){return(t?Qu:Xu)+Uo(typeof r=="string"?r:r.join(qu))}var Ho=new WeakMap,Yo=new Map;function zo(r,t,e){if(r){let a=e?.id??ep(t),i=r[a];if(i){if(typeof i=="string")return i;if("strTag"in i)return pr(i.strings,t.values,i.values);{let n=Ho.get(i);return n===void 0&&(n=i.values,Ho.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return ya(t)}function ep(r){let t=typeof r=="string"?r:r.strings,e=Yo.get(t);return e===void 0&&(e=Vo(t,typeof r!="string"&&!("strTag"in r)),Yo.set(t,e)),e}function xi(r){window.dispatchEvent(new CustomEvent(ga,{detail:r}))}var hr="",_i,$o,gr,wi,jo,xt=new fa;xt.resolve();var mr=0,Wo=r=>(Li(((t,e)=>zo(jo,t,e))),hr=$o=r.sourceLocale,gr=new Set(r.targetLocales),gr.add(r.sourceLocale),wi=r.loadLocale,{getLocale:tp,setLocale:ap}),tp=()=>hr,ap=r=>{if(r===(_i??hr))return xt.promise;if(!gr||!wi)throw new Error("Internal error");if(!gr.has(r))throw new Error("Invalid locale code");mr++;let t=mr;return _i=r,xt.settled&&(xt=new fa),xi({status:"loading",loadingLocale:r}),(r===$o?Promise.resolve({templates:void 0}):wi(r)).then(a=>{mr===t&&(hr=r,_i=void 0,jo=a.templates,xi({status:"ready",readyLocale:r}),xt.resolve())},a=>{mr===t&&(xi({status:"error",errorLocale:r,errorMessage:a.toString()}),xt.reject(a))}),xt.promise};var Di="en",Oi=["ar","bg","ca","cs","da","de","el","en-GB","es","es-AR","es-MX","et-EE","fi-FI","fr","he","hr","hu","id","it","ja","ko","lt","lt-LT","lv","lv-LV","ms","nb","nl","nl_NL","pl","pt","pt-BR","ro","ru","sk","sl","sr-RS","sv","th","tr","uk-UA","vi","zf","zh-CN","zh-HK","zh-TW"],Bi="You must call `loadLocale` first to set up the localized template.",yr,fr,Zo=r=>{let t=Wo({sourceLocale:Di,targetLocales:Oi,loadLocale:r});yr=t.getLocale,fr=t.setLocale};var Gi=r=>{Zo(r)},Ki=r=>{if(!fr)throw new Error(Bi);return fr(r)},Fi=()=>{if(!yr)throw new Error(Bi);return yr()};var va=new Set(Oi);va.add(Di);var Ui=r=>{if(typeof r!="string")return!1;if(r==="en")return!0;let t=r.replace("_","-");if(va.has(t))return!0;let e=t.split("-")[0];return!!va.has(e)},vr=()=>navigator.language||navigator.languages[0]||"en",qt=r=>{let t=r.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":va.has(t)?t:va.has(e)?e:"en-GB"};var Sr=globalThis,br=Sr.ShadowRoot&&(Sr.ShadyCSS===void 0||Sr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Vi=Symbol(),Jo=new WeakMap,Sa=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Vi)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(br&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Jo.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Jo.set(e,t))}return t}toString(){return this.cssText}},fe=r=>new Sa(typeof r=="string"?r:r+"",void 0,Vi),f=(r,...t)=>{let e=r.length===1?r[0]:t.reduce(((a,i,n)=>a+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[n+1]),r[0]);return new Sa(e,r,Vi)},qo=(r,t)=>{if(br)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=Sr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Hi=br?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return fe(e)})(r):r;var{is:rp,defineProperty:ip,getOwnPropertyDescriptor:np,getOwnPropertyNames:op,getOwnPropertySymbols:sp,getPrototypeOf:lp}=Object,St=globalThis,Qo=St.trustedTypes,dp=Qo?Qo.emptyScript:"",cp=St.reactiveElementPolyfillSupport,ba=(r,t)=>r,Aa={toAttribute(r,t){switch(t){case Boolean:r=r?dp:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},Ar=(r,t)=>!rp(r,t),Xo={attribute:!0,type:String,converter:Aa,reflect:!1,useDefault:!1,hasChanged:Ar};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),St.litPropertyMetadata??(St.litPropertyMetadata=new WeakMap);var at=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Xo){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&ip(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=np(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:i,set(o){let s=i?.call(this);n?.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Xo}static _$Ei(){if(this.hasOwnProperty(ba("elementProperties")))return;let t=lp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ba("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ba("properties"))){let e=this.properties,a=[...op(e),...sp(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(Hi(i))}else t!==void 0&&e.push(Hi(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return qo(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$ET(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:Aa).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Aa;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){let i=this.constructor,n=this[t];if(a??(a=i.getPropertyOptions(t)),!((a.hasChanged??Ar)(n,e)||a.useDefault&&a.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,a))))return;this.C(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:a,reflect:i,wrapped:n},o){a&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||a||(e=void 0),this._$AL.set(t,e)),i===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a){let{wrapped:o}=n,s=this[i];o!==!0||this._$AL.has(i)||s===void 0||this.C(i,void 0,n,s)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EM()}catch(a){throw t=!1,this._$EM(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(t){}firstUpdated(t){}};at.elementStyles=[],at.shadowRootOptions={mode:"open"},at[ba("elementProperties")]=new Map,at[ba("finalized")]=new Map,cp?.({ReactiveElement:at}),(St.reactiveElementVersions??(St.reactiveElementVersions=[])).push("2.1.0");var Ma=globalThis,Cr=Ma.trustedTypes,es=Cr?Cr.createPolicy("lit-html",{createHTML:r=>r}):void 0,zi="$lit$",rt=`lit$${Math.random().toFixed(9).slice(2)}$`,$i="?"+rt,up=`<${$i}>`,Dt=document,Ea=()=>Dt.createComment(""),Ta=r=>r===null||typeof r!="object"&&typeof r!="function",ji=Array.isArray,os=r=>ji(r)||typeof r?.[Symbol.iterator]=="function",Yi=`[
145
145
  \f\r]`,Ca=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ts=/-->/g,as=/>/g,_t=RegExp(`>|${Yi}(?:([^\\s"'>=/]+)(${Yi}*=${Yi}*(?:[^
146
- \f\r"'\`<>=]|("|')|))|$)`,"g"),rs=/'/g,is=/"/g,ss=/^(?:script|style|textarea|title)$/i,Wi=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=Wi(1),Be=Wi(2),Gy=Wi(3),ve=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),ns=new WeakMap,wt=Dt.createTreeWalker(Dt,129);function ls(r,t){if(!ji(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return es!==void 0?es.createHTML(t):t}var ds=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=Ca;for(let s=0;s<e;s++){let l=r[s],c,m,g=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===Ca?m[1]==="!--"?o=ts:m[1]!==void 0?o=as:m[2]!==void 0?(ss.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=_t):m[3]!==void 0&&(o=_t):o===_t?m[0]===">"?(o=i??Ca,g=-1):m[1]===void 0?g=-2:(g=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?_t:m[3]==='"'?is:rs):o===is||o===rs?o=_t:o===ts||o===as?o=Ca:(o=_t,i=void 0);let T=o===_t&&r[s+1].startsWith("/>")?" ":"";n+=o===Ca?l+up:g>=0?(a.push(c),l.slice(0,g)+zi+l.slice(g)+rt+T):l+rt+(g===-2?s:T)}return[ls(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},Pa=class r{constructor({strings:t,_$litType$:e},a){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,m]=ds(t,e);if(this.el=r.createElement(c,a),wt.currentNode=this.el.content,e===2||e===3){let g=this.el.content.firstChild;g.replaceWith(...g.childNodes)}for(;(i=wt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let g of i.getAttributeNames())if(g.endsWith(zi)){let h=m[o++],T=i.getAttribute(g).split(rt),M=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:M[2],strings:T,ctor:M[1]==="."?Er:M[1]==="?"?Tr:M[1]==="@"?Pr:Bt}),i.removeAttribute(g)}else g.startsWith(rt)&&(l.push({type:6,index:n}),i.removeAttribute(g));if(ss.test(i.tagName)){let g=i.textContent.split(rt),h=g.length-1;if(h>0){i.textContent=Cr?Cr.emptyScript:"";for(let T=0;T<h;T++)i.append(g[T],Ea()),wt.nextNode(),l.push({type:2,index:++n});i.append(g[h],Ea())}}}else if(i.nodeType===8)if(i.data===$i)l.push({type:2,index:n});else{let g=-1;for(;(g=i.data.indexOf(rt,g+1))!==-1;)l.push({type:7,index:n}),g+=rt.length-1}n++}}static createElement(t,e){let a=Dt.createElement("template");return a.innerHTML=t,a}};function Ot(r,t,e=r,a){if(t===ve)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=Ta(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(r),i._$AT(r,e,a)),a!==void 0?(e._$Co??(e._$Co=[]))[a]=i:e._$Cl=i),i!==void 0&&(t=Ot(r,i._$AS(r,t.values),i,a)),t}var Mr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Dt).importNode(e,!0);wt.currentNode=i;let n=wt.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new Qt(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ir(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=wt.nextNode(),o++)}return wt.currentNode=Dt,i}p(t){let e=0;for(let a of this._$AV)a!==void 0&&(a.strings!==void 0?(a._$AI(t,a,e),e+=a.strings.length-2):a._$AI(t[e])),e++}},Qt=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ot(this,t,e),Ta(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==ve&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):os(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Ta(this._$AH)?this._$AA.nextSibling.data=t:this.T(Dt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:a}=t,i=typeof a=="number"?this._$AC(t):(a.el===void 0&&(a.el=Pa.createElement(ls(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Mr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=ns.get(t.strings);return e===void 0&&ns.set(t.strings,e=new Pa(t)),e}k(t){ji(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,a,i=0;for(let n of t)i===e.length?e.push(a=new r(this.O(Ea()),this.O(Ea()),this,this.options)):a=e[i],a._$AI(n),i++;i<e.length&&(this._$AR(a&&a._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let a=t.nextSibling;t.remove(),t=a}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Bt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=y}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Ot(this,t,e,0),o=!Ta(t)||t!==this._$AH&&t!==ve,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ot(this,s[a+l],e,l),c===ve&&(c=this._$AH[l]),o||(o=!Ta(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Er=class extends Bt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Tr=class extends Bt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Pr=class extends Bt{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Ot(this,t,e,0)??y)===ve)return;let a=this._$AH,i=t===y&&a!==y||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==y&&(a===y||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ir=class{constructor(t,e,a){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=a}get _$AU(){return this._$AM._$AU}_$AI(t){Ot(this,t)}},cs={M:zi,P:rt,A:$i,C:1,L:ds,R:Mr,D:os,V:Ot,I:Qt,H:Bt,N:Tr,U:Pr,B:Er,F:Ir},pp=Ma.litHtmlPolyfillSupport;pp?.(Pa,Qt),(Ma.litHtmlVersions??(Ma.litHtmlVersions=[])).push("3.3.0");var us=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new Qt(t.insertBefore(Ea(),n),n,void 0,e??{})}return i._$AI(r),i};var Ia=globalThis,v=class extends at{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;let t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=us(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ve}};v._$litElement$=!0,v.finalized=!0,Ia.litElementHydrateSupport?.({LitElement:v});var mp=Ia.litElementPolyfillSupport;mp?.({LitElement:v});(Ia.litElementVersions??(Ia.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var hp={attribute:!0,type:String,converter:Aa,reflect:!1,hasChanged:Ar},gp=(r=hp,t,e)=>{let{kind:a,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),a==="setter"&&((r=Object.create(r)).wrapped=!0),n.set(e.name,r),a==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,r)},init(s){return s!==void 0&&this.C(o,void 0,r,s),s}}}if(a==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,r)}}throw Error("Unsupported decorator location: "+a)};function u(r){return(t,e)=>typeof e=="object"?gp(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function I(r){return u({...r,state:!0,attribute:!1})}var Gt=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function Le(r,t){return(e,a,i)=>{let n=o=>o.renderRoot?.querySelector(r)??null;if(t){let{get:o,set:s}=typeof a=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Gt(e,a,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Gt(e,a,{get(){return n(this)}})}}function R(r,t,e){return r?t(r):e?.(r)}var N=f` * { box-sizing: border-box; } `,ps=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var ms="https://sdk.primer.io/web/v2-latest/Primer.min.js",Se="20px";var Nr=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,a)=>this.startVaultPaymentInternal(e,a),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods.toArray():(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleBeforePaymentCreate(t,e){if(this.onPaymentPrepare){let a={continuePaymentCreation:(...i)=>{P.info("PrimerJS: Payment creation continuing"),e.continuePaymentCreation(...i)},abortPaymentCreation:(...i)=>{P.info("PrimerJS: Payment creation aborted"),e.abortPaymentCreation(...i)}};this.onPaymentPrepare(t,a)}else P.info("PrimerJS: No payment prepare handler, continuing by default"),e.continuePaymentCreation()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let a=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:a})}}setCardholderName(t){if(!this.paymentManagers){P.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){P.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var kr=typeof window<"u"&&typeof window.document<"u";function yp(r){return document.querySelector(`script[src^="${r}"]`)}function fp(r,t){let e=document.createElement("script");return e.setAttribute("src",r),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function hs(r,t=!1){if(!kr)throw new Error("Cannot load script in server environment");let e=yp(r)??fp(r,t);return new Promise((a,i)=>{e.onload=()=>{a()},e.onerror=()=>{i(new Error(`Failed to load script: ${r}`))},e.parentNode||document.head.appendChild(e)})}var gs=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var ne=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){super.updated(e),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?p`<primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?p`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?p`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};ne.styles=[N,gs],d([u({type:String})],ne.prototype,"size",2),d([u({type:Boolean})],ne.prototype,"showCloseButton",2),d([u({type:Object})],ne.prototype,"onOpen",2),d([u({type:Object})],ne.prototype,"onContentRendered",2),d([u({type:Object})],ne.prototype,"cta",2),d([I()],ne.prototype,"open",2),d([Le("primer-dialog")],ne.prototype,"dialog",2),ne=d([S("primer-portal-dialog"),D()],ne);var Lr=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=new ne;a.size=t.size??"large",a.showCloseButton=t.showCloseButton??!1,a.onContentRendered=t.onContentReady,a.cta=t.cta;let i=()=>{a.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};a.addEventListener("primer:dialog-close",i),this.currentDialog=a,this.currentResolver=e,document.body.appendChild(a),a.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var vp=xa({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});var Xt=null,Zi=null;async function ys(r){if(Zi===r&&Xt)return Xt;try{return Xt=(await vp(`../../../localization/lit-localize/locales/${r}.ts`)).templates,Zi=r,Xt}catch{return r!=="en-GB"?ys("en-GB"):(Xt={},Zi=r,Xt)}}async function fs(r){let t=await ys(r);return(e,a)=>t[e]??a}var bt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},Na={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var Rr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};function vs(r,t){if(r.isDisconnected)return;r.host.sdkStateController.currentState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),r.host.sdkStateController.startProcessing(),r.host.primerEventsController.dispatchPaymentStart()}function Ss(r,t,e){if(!r.isDisconnected&&(P.info("Payment completed:",t),r.host.sdkStateController.completeProcessing(),r.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),r.primerJS?.onPaymentSuccess)){let a=Math.floor(Date.now()/1e3);r.primerJS.onPaymentSuccess({payment:jt(t),paymentMethodType:e,timestamp:a})}}function bs(r,t,e,a){if(r.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof Rr?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(r.host.sdkStateController.setPaymentFailure(o),r.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,a),Q({eventName:"PAYMENT_FAILURE",paymentId:a?.id,paymentMethod:e}),r.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);r.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:a?jt(a):void 0,paymentMethodType:e,timestamp:s})}}var Ji="0.14.0",xr=class{constructor(t){this.createPaymentMethodManager=null;this._paymentsList=[];this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,this.sdkInstanceTask=new B(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new B(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.getAnalyticsUtils()){let e=this.host.sdkStateController.currentState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Bo(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=ms){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await hs(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),w;if(!t||!e)return w;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new Lr,c=qt(e.locale||vr()),m=await fs(c);i={createHeadless:(h,T)=>So(h,{...T,dialogProvider:l,translate:m,sdkVersion:Ji,locale:c})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Nr(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(P.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{let c=l?.paymentMethodData?.paymentMethodType;Ss({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,c)},onCheckoutFail:(l,c)=>{let m=c.payment?.paymentMethodData?.paymentMethodType;bs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,m,c.payment)},onBeforePaymentCreate:(l,c)=>{if(!l.paymentMethodType){P.error("Payment creation started without payment method type"),c?.abortPaymentCreation();return}vs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l.paymentMethodType),this.primerJS&&!this.isDisconnected?this.primerJS.handleBeforePaymentCreate(l,c):this.isDisconnected||c?.continuePaymentCreation()},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&this.host.sdkStateController.stopProcessing()},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),w;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:Ji}),Oo({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:Ji,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),a.configurationFetchStartTime&&Ye.setSdkInitStartTime(a.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1}),o}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return w;if(!t||!e.length)return w;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return w;let n=new cr(a);return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),P.info("Initialized payment methods:",n.toArray()),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),Q({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return P.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var _r=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:e.message})}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:"Mandate declined"})}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var Sp=xa({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});Gi(r=>Sp(`../../localization/lit-localize/locales/${r}.ts`));var bp={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Pe=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this.locale=qt(vr());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new rr(this),this.sdkStateController=new ar(this),this.primerEventsController=new Wt(this),this.styleProcessingController=new ir(this),this.vaultManagerController=new ha(this),this.cardNetworkController=new _a(this),this.achPaymentEventsController=new _r(this),this.headlessSdkController=new xr(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal})}attributeChangedCallback(e,a,i){e===bp.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,a,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Ui(this.options?.locale)?this.locale=qt(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),Ki(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let a=Ye.getSdkInitStartTime(),i=a?Date.now()-a:void 0;To(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${R(a,()=>y)} ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${R(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent,()=>y,()=>p`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Pe.styles=[N,ps],d([u({type:String,attribute:"custom-styles"})],Pe.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Pe.prototype,"clientToken",2),d([u({type:Object,attribute:!1,hasChanged:(e,a)=>!tr(e,a)})],Pe.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Pe.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Pe.prototype,"_jsInitialized",2),d([Le("slot")],Pe.prototype,"defaultSlot",2),d([I()],Pe.prototype,"previousLoadingState",2),Pe=d([D(),S("primer-checkout")],Pe);function Ap(r){return document.querySelector(`#${r}`)}function Cp(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function ka(r,t,e=!0){if(!kr||Ap(t))return;let i=Cp(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var As=`
146
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),rs=/'/g,is=/"/g,ss=/^(?:script|style|textarea|title)$/i,Wi=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=Wi(1),Be=Wi(2),Gy=Wi(3),ve=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),ns=new WeakMap,wt=Dt.createTreeWalker(Dt,129);function ls(r,t){if(!ji(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return es!==void 0?es.createHTML(t):t}var ds=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=Ca;for(let s=0;s<e;s++){let l=r[s],c,m,g=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===Ca?m[1]==="!--"?o=ts:m[1]!==void 0?o=as:m[2]!==void 0?(ss.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=_t):m[3]!==void 0&&(o=_t):o===_t?m[0]===">"?(o=i??Ca,g=-1):m[1]===void 0?g=-2:(g=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?_t:m[3]==='"'?is:rs):o===is||o===rs?o=_t:o===ts||o===as?o=Ca:(o=_t,i=void 0);let T=o===_t&&r[s+1].startsWith("/>")?" ":"";n+=o===Ca?l+up:g>=0?(a.push(c),l.slice(0,g)+zi+l.slice(g)+rt+T):l+rt+(g===-2?s:T)}return[ls(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},Pa=class r{constructor({strings:t,_$litType$:e},a){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,m]=ds(t,e);if(this.el=r.createElement(c,a),wt.currentNode=this.el.content,e===2||e===3){let g=this.el.content.firstChild;g.replaceWith(...g.childNodes)}for(;(i=wt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let g of i.getAttributeNames())if(g.endsWith(zi)){let h=m[o++],T=i.getAttribute(g).split(rt),M=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:M[2],strings:T,ctor:M[1]==="."?Er:M[1]==="?"?Tr:M[1]==="@"?Pr:Bt}),i.removeAttribute(g)}else g.startsWith(rt)&&(l.push({type:6,index:n}),i.removeAttribute(g));if(ss.test(i.tagName)){let g=i.textContent.split(rt),h=g.length-1;if(h>0){i.textContent=Cr?Cr.emptyScript:"";for(let T=0;T<h;T++)i.append(g[T],Ea()),wt.nextNode(),l.push({type:2,index:++n});i.append(g[h],Ea())}}}else if(i.nodeType===8)if(i.data===$i)l.push({type:2,index:n});else{let g=-1;for(;(g=i.data.indexOf(rt,g+1))!==-1;)l.push({type:7,index:n}),g+=rt.length-1}n++}}static createElement(t,e){let a=Dt.createElement("template");return a.innerHTML=t,a}};function Ot(r,t,e=r,a){if(t===ve)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=Ta(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(r),i._$AT(r,e,a)),a!==void 0?(e._$Co??(e._$Co=[]))[a]=i:e._$Cl=i),i!==void 0&&(t=Ot(r,i._$AS(r,t.values),i,a)),t}var Mr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Dt).importNode(e,!0);wt.currentNode=i;let n=wt.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new Qt(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ir(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=wt.nextNode(),o++)}return wt.currentNode=Dt,i}p(t){let e=0;for(let a of this._$AV)a!==void 0&&(a.strings!==void 0?(a._$AI(t,a,e),e+=a.strings.length-2):a._$AI(t[e])),e++}},Qt=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ot(this,t,e),Ta(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==ve&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):os(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Ta(this._$AH)?this._$AA.nextSibling.data=t:this.T(Dt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:a}=t,i=typeof a=="number"?this._$AC(t):(a.el===void 0&&(a.el=Pa.createElement(ls(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Mr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=ns.get(t.strings);return e===void 0&&ns.set(t.strings,e=new Pa(t)),e}k(t){ji(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,a,i=0;for(let n of t)i===e.length?e.push(a=new r(this.O(Ea()),this.O(Ea()),this,this.options)):a=e[i],a._$AI(n),i++;i<e.length&&(this._$AR(a&&a._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let a=t.nextSibling;t.remove(),t=a}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Bt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=y}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Ot(this,t,e,0),o=!Ta(t)||t!==this._$AH&&t!==ve,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ot(this,s[a+l],e,l),c===ve&&(c=this._$AH[l]),o||(o=!Ta(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Er=class extends Bt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Tr=class extends Bt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Pr=class extends Bt{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Ot(this,t,e,0)??y)===ve)return;let a=this._$AH,i=t===y&&a!==y||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==y&&(a===y||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ir=class{constructor(t,e,a){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=a}get _$AU(){return this._$AM._$AU}_$AI(t){Ot(this,t)}},cs={M:zi,P:rt,A:$i,C:1,L:ds,R:Mr,D:os,V:Ot,I:Qt,H:Bt,N:Tr,U:Pr,B:Er,F:Ir},pp=Ma.litHtmlPolyfillSupport;pp?.(Pa,Qt),(Ma.litHtmlVersions??(Ma.litHtmlVersions=[])).push("3.3.0");var us=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new Qt(t.insertBefore(Ea(),n),n,void 0,e??{})}return i._$AI(r),i};var Ia=globalThis,v=class extends at{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;let t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=us(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ve}};v._$litElement$=!0,v.finalized=!0,Ia.litElementHydrateSupport?.({LitElement:v});var mp=Ia.litElementPolyfillSupport;mp?.({LitElement:v});(Ia.litElementVersions??(Ia.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var hp={attribute:!0,type:String,converter:Aa,reflect:!1,hasChanged:Ar},gp=(r=hp,t,e)=>{let{kind:a,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),a==="setter"&&((r=Object.create(r)).wrapped=!0),n.set(e.name,r),a==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,r)},init(s){return s!==void 0&&this.C(o,void 0,r,s),s}}}if(a==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,r)}}throw Error("Unsupported decorator location: "+a)};function u(r){return(t,e)=>typeof e=="object"?gp(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function I(r){return u({...r,state:!0,attribute:!1})}var Gt=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function Le(r,t){return(e,a,i)=>{let n=o=>o.renderRoot?.querySelector(r)??null;if(t){let{get:o,set:s}=typeof a=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Gt(e,a,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Gt(e,a,{get(){return n(this)}})}}function R(r,t,e){return r?t(r):e?.(r)}var N=f` * { box-sizing: border-box; } `,ps=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var ms="https://sdk.primer.io/web/v2-latest/Primer.min.js",Se="20px";var Nr=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,a)=>this.startVaultPaymentInternal(e,a),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods.toArray():(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleBeforePaymentCreate(t,e){if(this.onPaymentPrepare){let a={continuePaymentCreation:(...i)=>{P.info("PrimerJS: Payment creation continuing"),e.continuePaymentCreation(...i)},abortPaymentCreation:(...i)=>{P.info("PrimerJS: Payment creation aborted"),e.abortPaymentCreation(...i)}};this.onPaymentPrepare(t,a)}else P.info("PrimerJS: No payment prepare handler, continuing by default"),e.continuePaymentCreation()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let a=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:a})}}setCardholderName(t){if(!this.paymentManagers){P.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){P.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var kr=typeof window<"u"&&typeof window.document<"u";function yp(r){return document.querySelector(`script[src^="${r}"]`)}function fp(r,t){let e=document.createElement("script");return e.setAttribute("src",r),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function hs(r,t=!1){if(!kr)throw new Error("Cannot load script in server environment");let e=yp(r)??fp(r,t);return new Promise((a,i)=>{e.onload=()=>{a()},e.onerror=()=>{i(new Error(`Failed to load script: ${r}`))},e.parentNode||document.head.appendChild(e)})}var gs=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var ne=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){super.updated(e),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?p`<primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?p`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?p`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};ne.styles=[N,gs],d([u({type:String})],ne.prototype,"size",2),d([u({type:Boolean})],ne.prototype,"showCloseButton",2),d([u({type:Object})],ne.prototype,"onOpen",2),d([u({type:Object})],ne.prototype,"onContentRendered",2),d([u({type:Object})],ne.prototype,"cta",2),d([I()],ne.prototype,"open",2),d([Le("primer-dialog")],ne.prototype,"dialog",2),ne=d([S("primer-portal-dialog"),D()],ne);var Lr=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=new ne;a.size=t.size??"large",a.showCloseButton=t.showCloseButton??!1,a.onContentRendered=t.onContentReady,a.cta=t.cta;let i=()=>{a.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};a.addEventListener("primer:dialog-close",i),this.currentDialog=a,this.currentResolver=e,document.body.appendChild(a),a.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var vp=xa({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});var Xt=null,Zi=null;async function ys(r){if(Zi===r&&Xt)return Xt;try{return Xt=(await vp(`../../../localization/lit-localize/locales/${r}.ts`)).templates,Zi=r,Xt}catch{return r!=="en-GB"?ys("en-GB"):(Xt={},Zi=r,Xt)}}async function fs(r){let t=await ys(r);return(e,a)=>t[e]??a}var bt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},Na={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var Rr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};function vs(r,t){if(r.isDisconnected)return;r.host.sdkStateController.currentState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),r.host.sdkStateController.startProcessing(),r.host.primerEventsController.dispatchPaymentStart()}function Ss(r,t,e){if(!r.isDisconnected&&(P.info("Payment completed:",t),r.host.sdkStateController.completeProcessing(),r.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),r.primerJS?.onPaymentSuccess)){let a=Math.floor(Date.now()/1e3);r.primerJS.onPaymentSuccess({payment:jt(t),paymentMethodType:e,timestamp:a})}}function bs(r,t,e,a){if(r.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof Rr?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(r.host.sdkStateController.setPaymentFailure(o),r.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,a),Q({eventName:"PAYMENT_FAILURE",paymentId:a?.id,paymentMethod:e}),r.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);r.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:a?jt(a):void 0,paymentMethodType:e,timestamp:s})}}var Ji="0.14.1",xr=class{constructor(t){this.createPaymentMethodManager=null;this._paymentsList=[];this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,this.sdkInstanceTask=new B(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new B(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.getAnalyticsUtils()){let e=this.host.sdkStateController.currentState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Bo(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=ms){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await hs(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),w;if(!t||!e)return w;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new Lr,c=qt(e.locale||vr()),m=await fs(c);i={createHeadless:(h,T)=>So(h,{...T,dialogProvider:l,translate:m,sdkVersion:Ji,locale:c})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Nr(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(P.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{let c=l?.paymentMethodData?.paymentMethodType;Ss({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,c)},onCheckoutFail:(l,c)=>{let m=c.payment?.paymentMethodData?.paymentMethodType;bs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,m,c.payment)},onBeforePaymentCreate:(l,c)=>{if(!l.paymentMethodType){P.error("Payment creation started without payment method type"),c?.abortPaymentCreation();return}vs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l.paymentMethodType),this.primerJS&&!this.isDisconnected?this.primerJS.handleBeforePaymentCreate(l,c):this.isDisconnected||c?.continuePaymentCreation()},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&this.host.sdkStateController.stopProcessing()},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),w;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:Ji}),Oo({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:Ji,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),a.configurationFetchStartTime&&Ye.setSdkInitStartTime(a.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1}),o}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return w;if(!t||!e.length)return w;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return w;let n=new cr(a);return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),P.info("Initialized payment methods:",n.toArray()),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),Q({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return P.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var _r=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:e.message})}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:"Mandate declined"})}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var Sp=xa({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});Gi(r=>Sp(`../../localization/lit-localize/locales/${r}.ts`));var bp={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Pe=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this.locale=qt(vr());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new rr(this),this.sdkStateController=new ar(this),this.primerEventsController=new Wt(this),this.styleProcessingController=new ir(this),this.vaultManagerController=new ha(this),this.cardNetworkController=new _a(this),this.achPaymentEventsController=new _r(this),this.headlessSdkController=new xr(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal})}attributeChangedCallback(e,a,i){e===bp.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,a,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Ui(this.options?.locale)?this.locale=qt(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),Ki(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let a=Ye.getSdkInitStartTime(),i=a?Date.now()-a:void 0;To(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${R(a,()=>y)} ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${R(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent,()=>y,()=>p`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Pe.styles=[N,ps],d([u({type:String,attribute:"custom-styles"})],Pe.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Pe.prototype,"clientToken",2),d([u({type:Object,attribute:!1,hasChanged:(e,a)=>!tr(e,a)})],Pe.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Pe.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Pe.prototype,"_jsInitialized",2),d([Le("slot")],Pe.prototype,"defaultSlot",2),d([I()],Pe.prototype,"previousLoadingState",2),Pe=d([D(),S("primer-checkout")],Pe);function Ap(r){return document.querySelector(`#${r}`)}function Cp(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function ka(r,t,e=!0){if(!kr||Ap(t))return;let i=Cp(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var As=`
147
147
  @keyframes primer-css-spinner-rotate {
148
148
  0% {
149
149
  transform: rotate(0deg);