@primer-io/primer-js 1.4.1 → 1.4.2
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.
- package/CHANGELOG.md +6 -0
- package/dist/custom-elements.json +58 -58
- package/dist/primer-loader.d.ts +1 -1
- package/dist/primer-loader.js +9 -5
- package/dist/web-types.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
{
|
|
52
52
|
"kind": "variable",
|
|
53
53
|
"name": "ye",
|
|
54
|
-
"default": "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._classObserver=null;this.locale=rr(La());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ya(this),this.primerEventsController=new er(this),this.styleProcessingController=new fa(this),this.vaultManagerController=new Mr(this),this.headlessSdkController=new Ya(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}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:[\"class\"]})}attributeChangedCallback(e,r,i){e===Qm.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has(\"options\")&&(this.options?.locale&&(Cn(this.options?.locale)?this.locale=rr(this.options?.locale):P.warn(\"\\u{1F30E}\\u2757 Unsupported locale provided:\",this.options?.locale,\"- Falling back to system locale\")),vn(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.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:\"CHECKOUT_FLOW_STARTED\"});let r=De.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Qn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn(\"Loading timeout in component, forcing completion\"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return u` ${k(
|
|
54
|
+
"default": "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._classObserver=null;this.locale=rr(La());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ya(this),this.primerEventsController=new er(this),this.styleProcessingController=new fa(this),this.vaultManagerController=new Mr(this),this.headlessSdkController=new Ya(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}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:[\"class\"]})}attributeChangedCallback(e,r,i){e===Qm.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has(\"options\")&&(this.options?.locale&&(Cn(this.options?.locale)?this.locale=rr(this.options?.locale):P.warn(\"\\u{1F30E}\\u2757 Unsupported locale provided:\",this.options?.locale,\"- Falling back to system locale\")),vn(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.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:\"CHECKOUT_FLOW_STARTED\"});let r=De.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Qn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn(\"Loading timeout in component, forcing completion\"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return u` ${k(i,()=>u`<primer-checkout-error></primer-checkout-error>`)}<slot name=\"main\" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent||!n,()=>y,()=>u`<primer-main></primer-main>`)} `}addEventListener(e,r,i){super.addEventListener(e,r,i)}removeEventListener(e,r,i){super.removeEventListener(e,r,i)}}"
|
|
55
55
|
},
|
|
56
56
|
{
|
|
57
57
|
"kind": "function",
|
|
@@ -302,7 +302,7 @@
|
|
|
302
302
|
{
|
|
303
303
|
"kind": "variable",
|
|
304
304
|
"name": "kt",
|
|
305
|
-
"default": "class extends v{constructor(){super(...arguments);this.hasAssignedContent=!1;this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()}}render(){return this.primerContext?.sdkState?.isSuccessful?u`<slot name=\"checkout-complete\"><primer-checkout-complete></primer-checkout-complete></slot>`:u`<slot name=\"payments\" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent,()=>y,()=>u`<div class=${X({\"primer-is-processing\":!!this.primerContext?.sdkState?.isProcessing})} ><primer-vault-manager></primer-vault-manager><primer-show-other-payments><div slot=\"other-payments\" class=\"primer-main-list\">${this.primerContext?.paymentMethods?.map(e=>u`<primer-payment-method type=${e.type} ?disabled=${this.primerContext?.clientOptions?.disabledPayments===!0} ></primer-payment-method>`)}</div></primer-show-other-payments><primer-error-message-container></primer-error-message-container></div>`)} `}}"
|
|
305
|
+
"default": "class extends v{constructor(){super(...arguments);this.hasAssignedContent=!1;this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()}}render(){return this.primerContext?.sdkState?.isLoading?y:this.primerContext?.sdkState?.isSuccessful?u`<slot name=\"checkout-complete\"><primer-checkout-complete></primer-checkout-complete></slot>`:u`<slot name=\"payments\" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent,()=>y,()=>u`<div class=${X({\"primer-is-processing\":!!this.primerContext?.sdkState?.isProcessing})} ><primer-vault-manager></primer-vault-manager><primer-show-other-payments><div slot=\"other-payments\" class=\"primer-main-list\">${this.primerContext?.paymentMethods?.map(e=>u`<primer-payment-method type=${e.type} ?disabled=${this.primerContext?.clientOptions?.disabledPayments===!0} ></primer-payment-method>`)}</div></primer-show-other-payments><primer-error-message-container></primer-error-message-container></div>`)} `}}"
|
|
306
306
|
},
|
|
307
307
|
{
|
|
308
308
|
"kind": "function",
|
|
@@ -1664,61 +1664,6 @@
|
|
|
1664
1664
|
}
|
|
1665
1665
|
]
|
|
1666
1666
|
},
|
|
1667
|
-
{
|
|
1668
|
-
"kind": "javascript-module",
|
|
1669
|
-
"path": "e2e/mocks/shared.ts",
|
|
1670
|
-
"declarations": [
|
|
1671
|
-
{
|
|
1672
|
-
"kind": "function",
|
|
1673
|
-
"name": "mockConfigurationCall",
|
|
1674
|
-
"parameters": [
|
|
1675
|
-
{
|
|
1676
|
-
"name": "page",
|
|
1677
|
-
"type": {
|
|
1678
|
-
"text": "Page"
|
|
1679
|
-
}
|
|
1680
|
-
},
|
|
1681
|
-
{
|
|
1682
|
-
"name": "config",
|
|
1683
|
-
"type": {
|
|
1684
|
-
"text": "unknown"
|
|
1685
|
-
}
|
|
1686
|
-
}
|
|
1687
|
-
]
|
|
1688
|
-
},
|
|
1689
|
-
{
|
|
1690
|
-
"kind": "function",
|
|
1691
|
-
"name": "mockDemoUrl",
|
|
1692
|
-
"parameters": [
|
|
1693
|
-
{
|
|
1694
|
-
"name": "primerCheckoutOptions",
|
|
1695
|
-
"optional": true,
|
|
1696
|
-
"type": {
|
|
1697
|
-
"text": "PrimerCheckoutOptions"
|
|
1698
|
-
}
|
|
1699
|
-
}
|
|
1700
|
-
]
|
|
1701
|
-
}
|
|
1702
|
-
],
|
|
1703
|
-
"exports": [
|
|
1704
|
-
{
|
|
1705
|
-
"kind": "js",
|
|
1706
|
-
"name": "mockConfigurationCall",
|
|
1707
|
-
"declaration": {
|
|
1708
|
-
"name": "mockConfigurationCall",
|
|
1709
|
-
"module": "e2e/mocks/shared.ts"
|
|
1710
|
-
}
|
|
1711
|
-
},
|
|
1712
|
-
{
|
|
1713
|
-
"kind": "js",
|
|
1714
|
-
"name": "mockDemoUrl",
|
|
1715
|
-
"declaration": {
|
|
1716
|
-
"name": "mockDemoUrl",
|
|
1717
|
-
"module": "e2e/mocks/shared.ts"
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
]
|
|
1721
|
-
},
|
|
1722
1667
|
{
|
|
1723
1668
|
"kind": "javascript-module",
|
|
1724
1669
|
"path": "dist/chunks/ar.4ZFBST5B.js",
|
|
@@ -2852,6 +2797,61 @@
|
|
|
2852
2797
|
}
|
|
2853
2798
|
]
|
|
2854
2799
|
},
|
|
2800
|
+
{
|
|
2801
|
+
"kind": "javascript-module",
|
|
2802
|
+
"path": "e2e/mocks/shared.ts",
|
|
2803
|
+
"declarations": [
|
|
2804
|
+
{
|
|
2805
|
+
"kind": "function",
|
|
2806
|
+
"name": "mockConfigurationCall",
|
|
2807
|
+
"parameters": [
|
|
2808
|
+
{
|
|
2809
|
+
"name": "page",
|
|
2810
|
+
"type": {
|
|
2811
|
+
"text": "Page"
|
|
2812
|
+
}
|
|
2813
|
+
},
|
|
2814
|
+
{
|
|
2815
|
+
"name": "config",
|
|
2816
|
+
"type": {
|
|
2817
|
+
"text": "unknown"
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
]
|
|
2821
|
+
},
|
|
2822
|
+
{
|
|
2823
|
+
"kind": "function",
|
|
2824
|
+
"name": "mockDemoUrl",
|
|
2825
|
+
"parameters": [
|
|
2826
|
+
{
|
|
2827
|
+
"name": "primerCheckoutOptions",
|
|
2828
|
+
"optional": true,
|
|
2829
|
+
"type": {
|
|
2830
|
+
"text": "PrimerCheckoutOptions"
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
]
|
|
2834
|
+
}
|
|
2835
|
+
],
|
|
2836
|
+
"exports": [
|
|
2837
|
+
{
|
|
2838
|
+
"kind": "js",
|
|
2839
|
+
"name": "mockConfigurationCall",
|
|
2840
|
+
"declaration": {
|
|
2841
|
+
"name": "mockConfigurationCall",
|
|
2842
|
+
"module": "e2e/mocks/shared.ts"
|
|
2843
|
+
}
|
|
2844
|
+
},
|
|
2845
|
+
{
|
|
2846
|
+
"kind": "js",
|
|
2847
|
+
"name": "mockDemoUrl",
|
|
2848
|
+
"declaration": {
|
|
2849
|
+
"name": "mockDemoUrl",
|
|
2850
|
+
"module": "e2e/mocks/shared.ts"
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
]
|
|
2854
|
+
},
|
|
2855
2855
|
{
|
|
2856
2856
|
"kind": "javascript-module",
|
|
2857
2857
|
"path": "src/__tests__/setup.ts",
|
|
@@ -4822,7 +4822,7 @@
|
|
|
4822
4822
|
{
|
|
4823
4823
|
"kind": "variable",
|
|
4824
4824
|
"name": "cssLoaderStyles",
|
|
4825
|
-
"default": "` @keyframes primer-css-spinner-rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* Hide primer-main
|
|
4825
|
+
"default": "` @keyframes primer-css-spinner-rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* Hide primer-main and primer-checkout-error while they are loading to prevent FOUC Only check for undefined primer-* elements, ignoring browser extensions */ primer-main:not(:defined), primer-checkout-error:not(:defined) { visibility: hidden; } primer-checkout:not([js-initialized]) [slot=\"main\"] { display: none; } primer-checkout:not([js-initialized]) { display: block; position: relative; width: 100%; min-height: 64px; } primer-checkout:not([js-initialized]):not([loader-disabled])::after { content: \"\"; display: block; box-sizing: border-box; position: absolute; inset: 0; margin: auto; width: var(--primer-size-xlarge); height: var(--primer-size-xlarge); border-radius: 50%; border: 3px solid #f5f5f5; border-top-color: var(--primer-color-loader); animation: primer-css-spinner-rotate 1.2s linear infinite; z-index: 9999; } `",
|
|
4826
4826
|
"description": "This module exports the CSS loader styles as a string for inline injection.\nThese styles are injected into the page before any JavaScript loads,\nensuring the loading indicator appears immediately."
|
|
4827
4827
|
}
|
|
4828
4828
|
],
|
package/dist/primer-loader.d.ts
CHANGED
|
@@ -5266,7 +5266,7 @@ declare class PrimerMainComponent extends LitElement {
|
|
|
5266
5266
|
*/
|
|
5267
5267
|
private onSlotChange;
|
|
5268
5268
|
primerContext?: ContextType;
|
|
5269
|
-
render(): import("lit-html").TemplateResult<1
|
|
5269
|
+
render(): import("lit-html").TemplateResult<1> | typeof nothing;
|
|
5270
5270
|
}
|
|
5271
5271
|
declare global {
|
|
5272
5272
|
interface HTMLElementTagNameMap {
|
package/dist/primer-loader.js
CHANGED
|
@@ -33,7 +33,7 @@ import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q
|
|
|
33
33
|
--apple-pay-button-width: 100%;
|
|
34
34
|
--apple-pay-button-height: ${r}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(),Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.APPLE_PAY}),this.applePaySession=new ApplePaySession(co,Pu(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:r}=await this.onStartPromise;if(r==="abort")return void this.abort(new R({message:"Payment creation aborted",code:x.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 R({message:"Failed to validate merchant",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(r){C.warn("Apple Pay merchant validation failed:",r),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling payment method selection",{error:r}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let r=[new ApplePayError("unknown",void 0,this.context.translate(fr.UNKNOWN_ERROR,vr.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Si(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw r=[new ApplePayError("billingContactInvalid","name",this.context.translate(fr.MISSING_FIRST_OR_LAST_NAME,vr.MISSING_FIRST_OR_LAST_NAME))],new R({message:"Billing contact must include first and last name",code:wt.MISSING_PARAMETER,paymentMethod:B.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=Si(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 r=[new ApplePayError("unknown",void 0,this.context.translate(fr.FAILED_TO_TOKENIZE,vr.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 R||i instanceof F?i:new R({message:"Error handling payment authorization",code:x.PAYMENT_FAILED,paymentMethod:B.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:r}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:r,error:i}=await this.context.clientSessionApi.setShippingAddress(Si(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!r||i)throw i??new R({message:"Failed to set shipping address",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeShippingContactSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling shipping contact selection",{error:r}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let r=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&r){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new R({message:"Failed to select shipping method",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(Ai(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.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},na=class extends Ee{constructor(){super(...arguments);S(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 R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new F({message:"BLIK code must be exactly 6 digits",code:x.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:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),blikCode:this.blikCode}};try{let{error:r,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),r||!i)throw r??new F({message:"Unable to tokenize BLIK payment method",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearBlikCode(),r}}async createPayment(e){let r=await super.createPayment(e),i=r.requiredAction?.clientToken;if(!i)throw new le({message:"No client token provided for BLIK payment",code:aa.MISSING_CLIENT_TOKEN,response:{id:r.id,data:r}});let n=ht(i);if(!this.isValidBlikClientToken(n))throw new le({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:aa.INVALID_CLIENT_TOKEN,response:{id:r.id,data:r}});let o=await this.context.pciApi.pollResumeStatus(n.statusUrl,{timeout:864e5,isComplete:l=>!!l.error||l.data?.status==="COMPLETE"});if(o.error)throw o.error;let s=o.data?.id;if(!s){let l=await this.context.pciApi.getResumeStatus(n.statusUrl);if(l.error||!l.data?.id)throw l.error??new Error("Unable to get resume token");s=l.data.id}return await this.resumePayment(r.id,s)}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}},Xo="https://sdk.primer.io/web/hosted-pages/v0.0.30",_i=!1,Nu=`${Xo}/api-controller.html`,Iu=`${Xo}/hosted-input.html`,es="https://goat-assets.production.core.primer.io",ku="primer-js-1.4.1_sdk-core-0.12.1";function ts(a,t,e){let r={checkoutSessionId:a,name:t};e!==void 0&&(r.defaultValue=e);try{return btoa(JSON.stringify(r))}catch{let{defaultValue:n,...o}=r;return btoa(JSON.stringify(o))}}Wi("../../node_modules/card-validator/dist/index.js");var ie={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},po="cardSecurityCodeRecapture";Object.values(ie);function Lu({networks:a,source:t},e){let r=e,i=new Set(r.map(p=>Zt(p).backend)),n=a.map(p=>({...p,allowed:i.has(p.network)})).sort((p,m)=>p.allowed?r.indexOf(p.network)-r.indexOf(m.network):1),o=n.filter(p=>p.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Jr),preferred:o.length?Jr(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Jr),preferred:o.length?Jr(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Jr({network:a,displayName:t,allowed:e}){return{network:a,displayName:t,allowed:e}}function Ru(a,t){return{cardNumber:yr(a,ie.cardNumber),cardSecurityCode:yr(a,ie.cardSecurityCode),cardExpiryDate:yr(a,ie.cardExpiryDate),cardholderName:yr(a,ie.cardholderName,t?.cardholderName)}}function yr(a,t,e){let r=document.createElement("iframe"),i=ts(a,t,e);return r.src=`${Iu}#${i}`,r.setAttribute("tabindex","0"),r.setAttribute("frameBorder","0"),r.style.border="none",r.style.boxSizing="border-box",r.style.height="20px",r.style.width="100%",r.style.colorScheme="auto",r}var oa=class extends Ee{constructor(e,r){super(e,r);S(this,"iframes");this.iframes=Ru(r.checkoutSessionId,{cardholderName:r.clientOptions.card?.cardholderName?.defaultValue})}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postCardPaymentInstruments();if(e||!r)throw e??new F({code:x.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:B.PAYMENT_CARD});return r}};function wu(a){if(!a)return{};let t=a.indexOf(" ");return t===-1?{firstName:a}:{firstName:a.substring(0,t),lastName:a.substring(t+1)}}function Ei(a){let{firstName:t,lastName:e}=wu(a.name);return{firstName:t||null,lastName:e||null,addressLine1:a.address1||null,addressLine2:a.address2||null,city:a.locality||null,state:a.administrativeArea||null,postalCode:a.postalCode||null,countryCode:a.countryCode||null}}function mo(a){return a.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var ho=2,go=0,xu="https://pay.google.com/gp/p/js/pay.js",_u={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},yo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],qr={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Qr={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},Ou="buy",Du="black",Bu="fill",sa=class extends Ee{constructor(){super(...arguments);S(this,"disabled",!1);S(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,r){return this.context.translate?.(e,r)??r}async tokenize(){throw new F({code:x.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:B.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await Xi(xu),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;if(!e)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:B.GOOGLE_PAY});if(!r)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:B.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:ho,apiVersionMinor:go,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 r=this.client.createButton({buttonType:this.clientOptions?.buttonType??Ou,buttonColor:this.clientOptions?.buttonColor??Du,buttonSizeMode:this.clientOptions?.buttonSizeMode??Bu,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(r)}async handleClick(e){if(this.disabled)return;if(!this.client)return void C.error("Google Pay client not available");let r=this.callbacks.onStart();Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await r;if(n==="abort")throw new R({message:"Payment creation aborted",code:x.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.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:r,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Cr.encode(e.paymentMethodData.tokenizationData.token)});if(i||!r)throw this.callbacks.onFinish(void 0,i),i??new F({code:x.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:B.GOOGLE_PAY});this.callbacks.onFinish(r)}async updateBillingAddress(e){let r=e.paymentMethodData.info?.billingAddress;if(r){let i=Ei(r);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let r=e.shippingAddress,i=e.email,n=r?.phoneNumber;if(r||n||i){let o=r?Ei(r):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 r=e.callbackTrigger;try{if(r==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(r==="SHIPPING_ADDRESS"||r==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Ei(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:mo(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:r==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:r,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:hr(i??n,r),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:r,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(qr.SUBTOTAL,Qr.SUBTOTAL),type:"SUBTOTAL",price:hr(i,r)}),c):(n&&n.length>0&&n.forEach(p=>{c.push({label:p.description||this.translate(qr.ITEM,Qr.ITEM),type:"LINE_ITEM",price:hr(p.amount,r)})}),o&&o.length>0&&o.filter(p=>p.amount!==0).forEach(p=>{c.push({label:p.type||p.description||this.translate(qr.FEE,Qr.FEE),type:"LINE_ITEM",price:hr(p.amount,r)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(qr.SHIPPING,Qr.SHIPPING),type:"LINE_ITEM",price:hr(s.amount,r)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return yo;let r=e.map(i=>_u[i]).filter(i=>!!i);return r.length>0?r:yo}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,r=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:ho,apiVersionMinor:go,...r&&{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:mo(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}}}]}}},Gu="https://x.klarnacdn.net/kp/lib/v1/api.js",la=class extends Error{constructor(){super("Klarna authorization cancelled by user"),this.name="KlarnaUserCancelledError"}},da=class extends Ee{constructor(){super(...arguments);S(this,"session",null);S(this,"selectedCategoryId",null)}getCategories(){let e=this.session?.categories??[],r=this.context.clientOptions.klarna?.allowedPaymentCategories;return r?r.map(i=>e.find(n=>n.identifier===i)).filter(i=>i!=null):e}setSelectedCategory(e){this.selectedCategoryId=e}async setup(){try{return await Xi(Gu,{crossorigin:""}),window.Klarna?.Payments?(this.session=await this.createSession(),this.session?this.getCategories().length===0?(C.warn("No Klarna payment categories available"),!1):(window.Klarna.Payments.init({client_token:this.session.clientToken}),!0):!1):(C.error("Klarna SDK failed to load"),!1)}catch(e){return C.error("Klarna setup failed",e),!1}}get isRecurring(){return this.context.clientOptions.klarna?.paymentFlow==="PREFER_VAULT"}async createSession(){let{clientSession:e}=this.context.configuration,r=e.order,i={localeCode:this.context.locale,countryCode:r?.countryCode??"",currencyCode:r?.currencyCode??""},n;if(this.isRecurring)n={sessionType:"RECURRING_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,description:this.context.clientOptions.klarna?.recurringPaymentDescription};else{if(!r?.lineItems||r.lineItems.length===0)return C.error("Klarna requires order.lineItems to be provided"),null;let l=r.lineItems.map(p=>({name:p.name||p.description||"",unitAmount:p.amount,reference:p.itemId,quantity:p.quantity,discountAmount:p.discountAmount,taxCode:p.taxCode,taxAmount:p.taxAmount,productType:p.productType})),c=r.merchantAmount??r.totalOrderAmount??0;n={sessionType:"ONE_OFF_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,totalAmount:c,orderItems:l}}let{data:o,error:s}=await this.context.coreApi.createKlarnaSession(n);return s||!o?(C.error("Failed to create Klarna session",s),null):o}async renderCategory(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna,i=(typeof e.containerId=="string",e.containerId);return e.onHeightChange&&r.on("heightChanged",e.onHeightChange),new Promise((n,o)=>{r.load({container:i,payment_method_category:e.paymentMethodCategoryId},s=>{s.error?o(new F({message:`Klarna load failed: ${s.error.invalid_fields?.join(", ")}`,code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type})):(this.selectedCategoryId=e.paymentMethodCategoryId,n())})})}async authorize(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna;return new Promise(i=>{r.authorize({payment_method_category:e},void 0,i)})}async finalizeSession(){if(!this.session)return null;let{data:e,error:r}=await this.context.coreApi.finalizeKlarnaSession({sessionId:this.session.sessionId,paymentMethodConfigId:this.config.id});return r||!e?(C.error("Failed to finalize Klarna session",r),null):e}async createCustomerToken(e){if(!this.session)return null;let r=this.context.clientOptions.klarna?.recurringPaymentDescription;if(!r)return C.error("klarna.recurringPaymentDescription must be provided for PREFER_VAULT flow"),null;let{clientSession:i}=this.context.configuration,n=i.order,{data:o,error:s}=await this.context.coreApi.createKlarnaCustomerToken({paymentMethodConfigId:this.config.id,sessionId:this.session.sessionId,authorizationToken:e,description:r,localeData:{localeCode:this.context.locale,countryCode:n?.countryCode??"",currencyCode:n?.currencyCode??""}});return s||!o?(C.error("Failed to create Klarna customer token",s),null):o}async tokenize(){if(!this.selectedCategoryId)throw new F({message:"No Klarna payment category selected",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e=await this.authorize(this.selectedCategoryId);if(!e.approved&&!e.error)throw C.debug("Klarna authorization cancelled by user"),new la;if(!e.approved||!e.authorization_token){let r=e.error?.invalid_fields?.join(", ")||"Authorization failed";throw new F({message:`Klarna authorization failed: ${r}`,code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type})}return this.isRecurring?this.tokenizeWithCustomerToken(e.authorization_token):this.tokenizeWithAuthToken(e.authorization_token)}async tokenizeWithAuthToken(e){let r=await this.finalizeSession();if(!r)throw new F({message:"Failed to finalize Klarna session",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaPaymentInstruments({klarnaAuthorizationToken:e,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async tokenizeWithCustomerToken(e){let r=await this.createCustomerToken(e);if(!r)throw new F({message:"Failed to create Klarna customer token",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaCustomerTokenInstruments({klarnaCustomerToken:r.customerTokenId,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new Error("Payment aborted"));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){if(e instanceof la)return void this.context.clientSessionApi.unselectPaymentMethod();this.callbacks.onFinish(void 0,e)}}async startWithCategory(e){return this.selectedCategoryId=e,this.start()}},Ku=100;function en({height:a,name:t,url:e="",width:r}){let i=new Set,n=window.open(e,t,Uu({height:a,width:r}));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=a=>new Promise(t=>{let e=setInterval(()=>{a.closed&&(clearInterval(e),t())},Ku)});function Uu(a){let t=Vu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:a});return Hu(t)}var Vu=({parent:a,popup:t})=>({left:a.left+(a.width-t.width)/2,top:a.top+(a.height-t.height)/2,height:t.height,width:t.width}),Hu=a=>Object.entries(a).map(t=>t.join("=")).join(",");function xt(a){return a?new Promise(t=>{setTimeout(t,a)}):Promise.resolve()}function tn(a,t){return a?.redirect?.returnUrl?!0:(C.warn(`[Primer SDK] ${t} is enabled in your client session but \`options.redirect.returnUrl\` is missing. This payment method may redirect the customer to an external page; without a return URL the customer cannot be brought back. The payment method will not be available in this checkout. Set \`options.redirect.returnUrl\` to a page that re-initializes the SDK with the \`?clientToken=...\` query parameter Primer appends on return.`),!1)}function Yu(a,t){if(a?.redirect?.returnUrl)return;let e=typeof window<"u"&&window.location?window.location.href:"";C.warn(`[Primer SDK] Initiating ${t} which may redirect the customer to an external page, but no \`options.redirect.returnUrl\` is configured. The customer will be returned to the current page (${e}). Set \`options.redirect.returnUrl\` to control the return destination.`),Le({eventName:"REDIRECT_RETURN_URL_NOT_CONFIGURED",paymentMethod:t})}function rn(a,t,e){let r="";try{r=new URL(a).origin}catch{r=""}C.info(`[Primer SDK] Redirecting to ${t} payment page at ${r} (${e})`),Le({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:t,redirectDestinationUrl:r,redirectReason:e})}function fo(a,t={}){C.info(`[Primer SDK] Returned from third-party payment page (${a})`),Le({eventName:"PAYMENT_RETURNED_FROM_THIRD_PARTY",intent:a,...t})}var Mi="Adyen Klarna",ca=class extends Ee{constructor(){super(...arguments);S(this,"paymentTypes",[]);S(this,"popup");S(this,"shouldRedirect",!1);S(this,"redirectReason","force_redirect");S(this,"dialogPromise");S(this,"selectedOptionId",null)}get assets(){let{displayMetadata:e,name:r}=this.config;return{icon:e?.button?.iconUrl??{},logo:e?.overlay?.logo??e?.button?.iconUrl??{},backgroundColor:e?.button?.backgroundColor??e?.overlay?.backgroundColor??{},name:r}}get logoSrc(){return this.assets.logo.colored||this.assets.logo.light||this.assets.icon.colored||this.assets.icon.light||""}async setup(){if(!tn(this.context.clientOptions,this.config.type))return!1;try{let{data:e,error:r}=await this.context.coreApi.getPaymentMethodOptions(this.config.id);return r?(C.error("Failed to fetch Adyen Klarna payment types",r),!1):e?.result?.length?(this.paymentTypes=e.result,this.paymentTypes.length===1&&(this.selectedOptionId=this.paymentTypes[0].name),!0):(C.warn("No Adyen Klarna payment types available for this currency/country combination"),!1)}catch(e){return C.error("Adyen Klarna setup failed",e),!1}}getOptions(){return this.paymentTypes.map(e=>({id:e.name,label:e.id}))}selectOption(e){this.selectedOptionId=e}async tokenize(){if(!this.selectedOptionId)throw new F({message:"No Adyen Klarna payment type selected",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{error:e,data:r}=await this.context.pciApi.postAdyenKlarnaPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),paymentMethodType:this.selectedOptionId,merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!r)throw e??new F({message:"Unable to tokenize Adyen Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return r}async createPayment(e){try{let r=await super.createPayment(e),i=this.validateAndDecodeClientToken(r);if(this.shouldRedirect&&(rn(i.redirectUrl,this.config.type,this.redirectReason),window.location.assign(i.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.cancelPayment(r);this.popup.setUrl(i.redirectUrl);let n=await this.waitForPaymentCompletion(i.statusUrl);if(this.cleanup(),"error"in n)throw n.error;if(this.wasPopupClosedWithoutCompletion(n))return this.cancelPayment(r);let o=await this.getResumeToken(n,i.statusUrl);return await this.resumePayment(r.id,o)}catch(r){throw this.cleanup(),r}}async start(){try{this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect?(this.shouldRedirect=!0,this.redirectReason="force_redirect"):Qi()&&(this.shouldRedirect=!0,this.redirectReason="in_app_browser"),this.showOverlayDialog(),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:r}=await this.callbacks.onStart();if(r==="abort")throw this.cleanup(),new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let i=await this.tokenize();this.callbacks.onFinish(i)}catch(e){this.cleanup(),this.callbacks.onFinish(void 0,e)}}cleanup(){this.popup?.close(),this.context.dialogProvider.close()}cancelPayment(e){return this.context.clientSessionApi.unselectPaymentMethod(e),this.cleanup(),{...e,cancelled:!0}}validateAndDecodeClientToken(e){let r=e.requiredAction?.clientToken;if(!r)throw new F({message:"No client token provided for Adyen Klarna redirect"});let i=ht(r);if(!jo(i,this.config.type))throw new F({message:"Invalid Adyen Klarna client token"});return i}async waitForPaymentCompletion(e){let r=this.dialogPromise?.then(()=>({id:"",popupClosed:!0}))??Promise.resolve({id:"",popupClosed:!0}),i=new Promise(l=>{this.popup?.onClose(()=>l({id:"",popupClosed:!0}))}),{promise:n,abort:o}=this.pollStatus(e),s=await Promise.race([r,i,n]);return o(),s}wasPopupClosedWithoutCompletion(e){return"popupClosed"in e&&!!e.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure}async getResumeToken(e,r){if(e.id)return e.id;let{data:i,error:n}=await this.context.pciApi.getResumeStatus(r);if(n||!i?.id)throw n??new Error("Unable to get resume token");return i.id}showOverlayDialog(){let e=this.assets.backgroundColor.colored||this.assets.backgroundColor.light||"#FFB3C7",r=document.createElement("div");r.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");if(i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${e};border-radius:var(--primer-radius-small);`),this.logoSrc){let o=document.createElement("img");o.src=this.logoSrc,o.setAttribute("style","height:100%;"),i.appendChild(o)}r.appendChild(i);let n=document.createElement("p");n.setAttribute("style","max-width: 300px;text-align: center;"),n.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.assets.name),r.appendChild(n),this.dialogPromise=this.context.dialogProvider.show({htmlContent:r,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>this.popup?.focus()}}).then(()=>{})}openPopup(){let{name:e,displayMetadata:{popup:r}}=this.config;this.popup=en({name:e,height:r?.height??1e3,width:r?.width??1200}),this.popup?.setContent(this.createPopupLoadingContent())}createPopupLoadingContent(){let e=this.context.translate("paymentMethodPopupLoadingScreenText","Hold on! {paymentMethodName} is loading.").replace("{paymentMethodName}",Mi);return`
|
|
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(),Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.APPLE_PAY}),this.applePaySession=new ApplePaySession(co,Pu(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:r}=await this.onStartPromise;if(r==="abort")return void this.abort(new R({message:"Payment creation aborted",code:x.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 R({message:"Failed to validate merchant",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(r){C.warn("Apple Pay merchant validation failed:",r),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling payment method selection",{error:r}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let r=[new ApplePayError("unknown",void 0,this.context.translate(fr.UNKNOWN_ERROR,vr.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Si(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw r=[new ApplePayError("billingContactInvalid","name",this.context.translate(fr.MISSING_FIRST_OR_LAST_NAME,vr.MISSING_FIRST_OR_LAST_NAME))],new R({message:"Billing contact must include first and last name",code:wt.MISSING_PARAMETER,paymentMethod:B.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=Si(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 r=[new ApplePayError("unknown",void 0,this.context.translate(fr.FAILED_TO_TOKENIZE,vr.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 R||i instanceof F?i:new R({message:"Error handling payment authorization",code:x.PAYMENT_FAILED,paymentMethod:B.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:r}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:r,error:i}=await this.context.clientSessionApi.setShippingAddress(Si(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!r||i)throw i??new R({message:"Failed to set shipping address",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeShippingContactSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling shipping contact selection",{error:r}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let r=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&r){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new R({message:"Failed to select shipping method",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(Ai(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.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},na=class extends Ee{constructor(){super(...arguments);S(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 R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new F({message:"BLIK code must be exactly 6 digits",code:x.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:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),blikCode:this.blikCode}};try{let{error:r,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),r||!i)throw r??new F({message:"Unable to tokenize BLIK payment method",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearBlikCode(),r}}async createPayment(e){let r=await super.createPayment(e),i=r.requiredAction?.clientToken;if(!i)throw new le({message:"No client token provided for BLIK payment",code:aa.MISSING_CLIENT_TOKEN,response:{id:r.id,data:r}});let n=ht(i);if(!this.isValidBlikClientToken(n))throw new le({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:aa.INVALID_CLIENT_TOKEN,response:{id:r.id,data:r}});let o=await this.context.pciApi.pollResumeStatus(n.statusUrl,{timeout:864e5,isComplete:l=>!!l.error||l.data?.status==="COMPLETE"});if(o.error)throw o.error;let s=o.data?.id;if(!s){let l=await this.context.pciApi.getResumeStatus(n.statusUrl);if(l.error||!l.data?.id)throw l.error??new Error("Unable to get resume token");s=l.data.id}return await this.resumePayment(r.id,s)}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}},Xo="https://sdk.primer.io/web/hosted-pages/v0.0.32",_i=!1,Nu=`${Xo}/api-controller.html`,Iu=`${Xo}/hosted-input.html`,es="https://goat-assets.production.core.primer.io",ku="primer-js-1.4.2_sdk-core-0.12.1";function ts(a,t,e){let r={checkoutSessionId:a,name:t};e!==void 0&&(r.defaultValue=e);try{return btoa(JSON.stringify(r))}catch{let{defaultValue:n,...o}=r;return btoa(JSON.stringify(o))}}Wi("../../node_modules/card-validator/dist/index.js");var ie={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},po="cardSecurityCodeRecapture";Object.values(ie);function Lu({networks:a,source:t},e){let r=e,i=new Set(r.map(p=>Zt(p).backend)),n=a.map(p=>({...p,allowed:i.has(p.network)})).sort((p,m)=>p.allowed?r.indexOf(p.network)-r.indexOf(m.network):1),o=n.filter(p=>p.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Jr),preferred:o.length?Jr(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Jr),preferred:o.length?Jr(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Jr({network:a,displayName:t,allowed:e}){return{network:a,displayName:t,allowed:e}}function Ru(a,t){return{cardNumber:yr(a,ie.cardNumber),cardSecurityCode:yr(a,ie.cardSecurityCode),cardExpiryDate:yr(a,ie.cardExpiryDate),cardholderName:yr(a,ie.cardholderName,t?.cardholderName)}}function yr(a,t,e){let r=document.createElement("iframe"),i=ts(a,t,e);return r.src=`${Iu}#${i}`,r.setAttribute("tabindex","0"),r.setAttribute("frameBorder","0"),r.style.border="none",r.style.boxSizing="border-box",r.style.height="20px",r.style.width="100%",r.style.colorScheme="auto",r}var oa=class extends Ee{constructor(e,r){super(e,r);S(this,"iframes");this.iframes=Ru(r.checkoutSessionId,{cardholderName:r.clientOptions.card?.cardholderName?.defaultValue})}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postCardPaymentInstruments();if(e||!r)throw e??new F({code:x.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:B.PAYMENT_CARD});return r}};function wu(a){if(!a)return{};let t=a.indexOf(" ");return t===-1?{firstName:a}:{firstName:a.substring(0,t),lastName:a.substring(t+1)}}function Ei(a){let{firstName:t,lastName:e}=wu(a.name);return{firstName:t||null,lastName:e||null,addressLine1:a.address1||null,addressLine2:a.address2||null,city:a.locality||null,state:a.administrativeArea||null,postalCode:a.postalCode||null,countryCode:a.countryCode||null}}function mo(a){return a.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var ho=2,go=0,xu="https://pay.google.com/gp/p/js/pay.js",_u={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},yo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],qr={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Qr={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},Ou="buy",Du="black",Bu="fill",sa=class extends Ee{constructor(){super(...arguments);S(this,"disabled",!1);S(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,r){return this.context.translate?.(e,r)??r}async tokenize(){throw new F({code:x.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:B.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await Xi(xu),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;if(!e)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:B.GOOGLE_PAY});if(!r)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:B.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:ho,apiVersionMinor:go,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 r=this.client.createButton({buttonType:this.clientOptions?.buttonType??Ou,buttonColor:this.clientOptions?.buttonColor??Du,buttonSizeMode:this.clientOptions?.buttonSizeMode??Bu,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(r)}async handleClick(e){if(this.disabled)return;if(!this.client)return void C.error("Google Pay client not available");let r=this.callbacks.onStart();Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await r;if(n==="abort")throw new R({message:"Payment creation aborted",code:x.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.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:r,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Cr.encode(e.paymentMethodData.tokenizationData.token)});if(i||!r)throw this.callbacks.onFinish(void 0,i),i??new F({code:x.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:B.GOOGLE_PAY});this.callbacks.onFinish(r)}async updateBillingAddress(e){let r=e.paymentMethodData.info?.billingAddress;if(r){let i=Ei(r);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let r=e.shippingAddress,i=e.email,n=r?.phoneNumber;if(r||n||i){let o=r?Ei(r):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 r=e.callbackTrigger;try{if(r==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(r==="SHIPPING_ADDRESS"||r==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Ei(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:mo(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:r==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:r,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:hr(i??n,r),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:r,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(qr.SUBTOTAL,Qr.SUBTOTAL),type:"SUBTOTAL",price:hr(i,r)}),c):(n&&n.length>0&&n.forEach(p=>{c.push({label:p.description||this.translate(qr.ITEM,Qr.ITEM),type:"LINE_ITEM",price:hr(p.amount,r)})}),o&&o.length>0&&o.filter(p=>p.amount!==0).forEach(p=>{c.push({label:p.type||p.description||this.translate(qr.FEE,Qr.FEE),type:"LINE_ITEM",price:hr(p.amount,r)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(qr.SHIPPING,Qr.SHIPPING),type:"LINE_ITEM",price:hr(s.amount,r)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return yo;let r=e.map(i=>_u[i]).filter(i=>!!i);return r.length>0?r:yo}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,r=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:ho,apiVersionMinor:go,...r&&{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:mo(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}}}]}}},Gu="https://x.klarnacdn.net/kp/lib/v1/api.js",la=class extends Error{constructor(){super("Klarna authorization cancelled by user"),this.name="KlarnaUserCancelledError"}},da=class extends Ee{constructor(){super(...arguments);S(this,"session",null);S(this,"selectedCategoryId",null)}getCategories(){let e=this.session?.categories??[],r=this.context.clientOptions.klarna?.allowedPaymentCategories;return r?r.map(i=>e.find(n=>n.identifier===i)).filter(i=>i!=null):e}setSelectedCategory(e){this.selectedCategoryId=e}async setup(){try{return await Xi(Gu,{crossorigin:""}),window.Klarna?.Payments?(this.session=await this.createSession(),this.session?this.getCategories().length===0?(C.warn("No Klarna payment categories available"),!1):(window.Klarna.Payments.init({client_token:this.session.clientToken}),!0):!1):(C.error("Klarna SDK failed to load"),!1)}catch(e){return C.error("Klarna setup failed",e),!1}}get isRecurring(){return this.context.clientOptions.klarna?.paymentFlow==="PREFER_VAULT"}async createSession(){let{clientSession:e}=this.context.configuration,r=e.order,i={localeCode:this.context.locale,countryCode:r?.countryCode??"",currencyCode:r?.currencyCode??""},n;if(this.isRecurring)n={sessionType:"RECURRING_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,description:this.context.clientOptions.klarna?.recurringPaymentDescription};else{if(!r?.lineItems||r.lineItems.length===0)return C.error("Klarna requires order.lineItems to be provided"),null;let l=r.lineItems.map(p=>({name:p.name||p.description||"",unitAmount:p.amount,reference:p.itemId,quantity:p.quantity,discountAmount:p.discountAmount,taxCode:p.taxCode,taxAmount:p.taxAmount,productType:p.productType})),c=r.merchantAmount??r.totalOrderAmount??0;n={sessionType:"ONE_OFF_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,totalAmount:c,orderItems:l}}let{data:o,error:s}=await this.context.coreApi.createKlarnaSession(n);return s||!o?(C.error("Failed to create Klarna session",s),null):o}async renderCategory(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna,i=(typeof e.containerId=="string",e.containerId);return e.onHeightChange&&r.on("heightChanged",e.onHeightChange),new Promise((n,o)=>{r.load({container:i,payment_method_category:e.paymentMethodCategoryId},s=>{s.error?o(new F({message:`Klarna load failed: ${s.error.invalid_fields?.join(", ")}`,code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type})):(this.selectedCategoryId=e.paymentMethodCategoryId,n())})})}async authorize(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna;return new Promise(i=>{r.authorize({payment_method_category:e},void 0,i)})}async finalizeSession(){if(!this.session)return null;let{data:e,error:r}=await this.context.coreApi.finalizeKlarnaSession({sessionId:this.session.sessionId,paymentMethodConfigId:this.config.id});return r||!e?(C.error("Failed to finalize Klarna session",r),null):e}async createCustomerToken(e){if(!this.session)return null;let r=this.context.clientOptions.klarna?.recurringPaymentDescription;if(!r)return C.error("klarna.recurringPaymentDescription must be provided for PREFER_VAULT flow"),null;let{clientSession:i}=this.context.configuration,n=i.order,{data:o,error:s}=await this.context.coreApi.createKlarnaCustomerToken({paymentMethodConfigId:this.config.id,sessionId:this.session.sessionId,authorizationToken:e,description:r,localeData:{localeCode:this.context.locale,countryCode:n?.countryCode??"",currencyCode:n?.currencyCode??""}});return s||!o?(C.error("Failed to create Klarna customer token",s),null):o}async tokenize(){if(!this.selectedCategoryId)throw new F({message:"No Klarna payment category selected",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e=await this.authorize(this.selectedCategoryId);if(!e.approved&&!e.error)throw C.debug("Klarna authorization cancelled by user"),new la;if(!e.approved||!e.authorization_token){let r=e.error?.invalid_fields?.join(", ")||"Authorization failed";throw new F({message:`Klarna authorization failed: ${r}`,code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type})}return this.isRecurring?this.tokenizeWithCustomerToken(e.authorization_token):this.tokenizeWithAuthToken(e.authorization_token)}async tokenizeWithAuthToken(e){let r=await this.finalizeSession();if(!r)throw new F({message:"Failed to finalize Klarna session",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaPaymentInstruments({klarnaAuthorizationToken:e,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async tokenizeWithCustomerToken(e){let r=await this.createCustomerToken(e);if(!r)throw new F({message:"Failed to create Klarna customer token",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaCustomerTokenInstruments({klarnaCustomerToken:r.customerTokenId,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new Error("Payment aborted"));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){if(e instanceof la)return void this.context.clientSessionApi.unselectPaymentMethod();this.callbacks.onFinish(void 0,e)}}async startWithCategory(e){return this.selectedCategoryId=e,this.start()}},Ku=100;function en({height:a,name:t,url:e="",width:r}){let i=new Set,n=window.open(e,t,Uu({height:a,width:r}));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=a=>new Promise(t=>{let e=setInterval(()=>{a.closed&&(clearInterval(e),t())},Ku)});function Uu(a){let t=Vu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:a});return Hu(t)}var Vu=({parent:a,popup:t})=>({left:a.left+(a.width-t.width)/2,top:a.top+(a.height-t.height)/2,height:t.height,width:t.width}),Hu=a=>Object.entries(a).map(t=>t.join("=")).join(",");function xt(a){return a?new Promise(t=>{setTimeout(t,a)}):Promise.resolve()}function tn(a,t){return a?.redirect?.returnUrl?!0:(C.warn(`[Primer SDK] ${t} is enabled in your client session but \`options.redirect.returnUrl\` is missing. This payment method may redirect the customer to an external page; without a return URL the customer cannot be brought back. The payment method will not be available in this checkout. Set \`options.redirect.returnUrl\` to a page that re-initializes the SDK with the \`?clientToken=...\` query parameter Primer appends on return.`),!1)}function Yu(a,t){if(a?.redirect?.returnUrl)return;let e=typeof window<"u"&&window.location?window.location.href:"";C.warn(`[Primer SDK] Initiating ${t} which may redirect the customer to an external page, but no \`options.redirect.returnUrl\` is configured. The customer will be returned to the current page (${e}). Set \`options.redirect.returnUrl\` to control the return destination.`),Le({eventName:"REDIRECT_RETURN_URL_NOT_CONFIGURED",paymentMethod:t})}function rn(a,t,e){let r="";try{r=new URL(a).origin}catch{r=""}C.info(`[Primer SDK] Redirecting to ${t} payment page at ${r} (${e})`),Le({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:t,redirectDestinationUrl:r,redirectReason:e})}function fo(a,t={}){C.info(`[Primer SDK] Returned from third-party payment page (${a})`),Le({eventName:"PAYMENT_RETURNED_FROM_THIRD_PARTY",intent:a,...t})}var Mi="Adyen Klarna",ca=class extends Ee{constructor(){super(...arguments);S(this,"paymentTypes",[]);S(this,"popup");S(this,"shouldRedirect",!1);S(this,"redirectReason","force_redirect");S(this,"dialogPromise");S(this,"selectedOptionId",null)}get assets(){let{displayMetadata:e,name:r}=this.config;return{icon:e?.button?.iconUrl??{},logo:e?.overlay?.logo??e?.button?.iconUrl??{},backgroundColor:e?.button?.backgroundColor??e?.overlay?.backgroundColor??{},name:r}}get logoSrc(){return this.assets.logo.colored||this.assets.logo.light||this.assets.icon.colored||this.assets.icon.light||""}async setup(){if(!tn(this.context.clientOptions,this.config.type))return!1;try{let{data:e,error:r}=await this.context.coreApi.getPaymentMethodOptions(this.config.id);return r?(C.error("Failed to fetch Adyen Klarna payment types",r),!1):e?.result?.length?(this.paymentTypes=e.result,this.paymentTypes.length===1&&(this.selectedOptionId=this.paymentTypes[0].name),!0):(C.warn("No Adyen Klarna payment types available for this currency/country combination"),!1)}catch(e){return C.error("Adyen Klarna setup failed",e),!1}}getOptions(){return this.paymentTypes.map(e=>({id:e.name,label:e.id}))}selectOption(e){this.selectedOptionId=e}async tokenize(){if(!this.selectedOptionId)throw new F({message:"No Adyen Klarna payment type selected",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{error:e,data:r}=await this.context.pciApi.postAdyenKlarnaPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),paymentMethodType:this.selectedOptionId,merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!r)throw e??new F({message:"Unable to tokenize Adyen Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return r}async createPayment(e){try{let r=await super.createPayment(e),i=this.validateAndDecodeClientToken(r);if(this.shouldRedirect&&(rn(i.redirectUrl,this.config.type,this.redirectReason),window.location.assign(i.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.cancelPayment(r);this.popup.setUrl(i.redirectUrl);let n=await this.waitForPaymentCompletion(i.statusUrl);if(this.cleanup(),"error"in n)throw n.error;if(this.wasPopupClosedWithoutCompletion(n))return this.cancelPayment(r);let o=await this.getResumeToken(n,i.statusUrl);return await this.resumePayment(r.id,o)}catch(r){throw this.cleanup(),r}}async start(){try{this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect?(this.shouldRedirect=!0,this.redirectReason="force_redirect"):Qi()&&(this.shouldRedirect=!0,this.redirectReason="in_app_browser"),this.showOverlayDialog(),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:r}=await this.callbacks.onStart();if(r==="abort")throw this.cleanup(),new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let i=await this.tokenize();this.callbacks.onFinish(i)}catch(e){this.cleanup(),this.callbacks.onFinish(void 0,e)}}cleanup(){this.popup?.close(),this.context.dialogProvider.close()}cancelPayment(e){return this.context.clientSessionApi.unselectPaymentMethod(e),this.cleanup(),{...e,cancelled:!0}}validateAndDecodeClientToken(e){let r=e.requiredAction?.clientToken;if(!r)throw new F({message:"No client token provided for Adyen Klarna redirect"});let i=ht(r);if(!jo(i,this.config.type))throw new F({message:"Invalid Adyen Klarna client token"});return i}async waitForPaymentCompletion(e){let r=this.dialogPromise?.then(()=>({id:"",popupClosed:!0}))??Promise.resolve({id:"",popupClosed:!0}),i=new Promise(l=>{this.popup?.onClose(()=>l({id:"",popupClosed:!0}))}),{promise:n,abort:o}=this.pollStatus(e),s=await Promise.race([r,i,n]);return o(),s}wasPopupClosedWithoutCompletion(e){return"popupClosed"in e&&!!e.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure}async getResumeToken(e,r){if(e.id)return e.id;let{data:i,error:n}=await this.context.pciApi.getResumeStatus(r);if(n||!i?.id)throw n??new Error("Unable to get resume token");return i.id}showOverlayDialog(){let e=this.assets.backgroundColor.colored||this.assets.backgroundColor.light||"#FFB3C7",r=document.createElement("div");r.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");if(i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${e};border-radius:var(--primer-radius-small);`),this.logoSrc){let o=document.createElement("img");o.src=this.logoSrc,o.setAttribute("style","height:100%;"),i.appendChild(o)}r.appendChild(i);let n=document.createElement("p");n.setAttribute("style","max-width: 300px;text-align: center;"),n.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.assets.name),r.appendChild(n),this.dialogPromise=this.context.dialogProvider.show({htmlContent:r,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>this.popup?.focus()}}).then(()=>{})}openPopup(){let{name:e,displayMetadata:{popup:r}}=this.config;this.popup=en({name:e,height:r?.height??1e3,width:r?.width??1200}),this.popup?.setContent(this.createPopupLoadingContent())}createPopupLoadingContent(){let e=this.context.translate("paymentMethodPopupLoadingScreenText","Hold on! {paymentMethodName} is loading.").replace("{paymentMethodName}",Mi);return`
|
|
37
37
|
<!DOCTYPE html>
|
|
38
38
|
<html>
|
|
39
39
|
<head>
|
|
@@ -177,7 +177,7 @@ import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q
|
|
|
177
177
|
</html>
|
|
178
178
|
`,Vi=class extends Ee{constructor(){super(...arguments);S(this,"popup");S(this,"shouldRedirect",!1);S(this,"redirectReason","force_redirect");S(this,"dialogPromise")}async setup(){return tn(this.context.clientOptions,this.config.type)}async start(){try{let e=this.callbacks.onStart(),r=this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect;(r||Qi())&&(this.shouldRedirect=!0,this.redirectReason=r?"force_redirect":"in_app_browser");let i=document.createElement("div");i.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let n=document.createElement("div");n.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 o=document.createElement("img");o.src=this.logoSrc,n.appendChild(o),o.setAttribute("style","height:100%;"),i.appendChild(n);let s=document.createElement("p");s.setAttribute("style","max-width: 300px;text-align: center;"),s.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),i.appendChild(s),this.dialogPromise=this.context.dialogProvider.show({htmlContent:i,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 xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:l}=await e;if(l==="abort")throw new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let c=await this.tokenize();this.callbacks.onFinish(c)}catch(e){this.context.dialogProvider.close(),this.popup?.close(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!r)throw e??new F({message:"Unable to tokenize payment method",code:x.TOKENIZATION_ERROR});return r}async createPayment(e){try{let r=await super.createPayment(e),i=r.requiredAction?.clientToken;if(!i)throw new F({message:"No client token provided"});let n=ht(i);if(!jo(n,this.config.type))throw new F({message:"Invalid client token"});if(this.shouldRedirect&&(rn(n.redirectUrl,this.config.type,this.redirectReason),window.location.assign(n.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.unselect(r),this.context.dialogProvider.close(),{...r,cancelled:!0};this.popup?.setUrl(n.redirectUrl);let o=(this.dialogPromise??Promise.resolve()).then(()=>({id:"",popupClosed:!0})),s=new Promise(g=>{this.popup?.onClose(()=>{C.debug("Popup closed"),g({id:"",popupClosed:!0})})}),l=new AbortController,c=this.context.pciApi.pollResumeStatus(n.statusUrl,{signal:l.signal,isComplete:g=>!!g.error||g.data?.status==="COMPLETE"}),p=await Promise.race([o,s,c.then(g=>g.error?{error:g.error,id:"",popupClosed:!1}:{id:g.data?.id??"",popupClosed:!1})]);if(l.abort(),this.popup?.close(),this.context.dialogProvider.close(),"error"in p)throw p.error;if("popupClosed"in p&&p.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(r),{...r,cancelled:!0};let m=p.id;if(!m){let g=await this.context.pciApi.getResumeStatus(n.statusUrl);if(g.error||!g.data?.id)throw g.error??new Error("Unable to get resume token");m=g.data.id}return await this.resumePayment(r.id,m)}catch(r){throw this.context.dialogProvider.close(),this.popup?.close(),r}}unselect(e){this.context.clientSessionApi.unselectPaymentMethod(e)}openPopup(){let{name:e,displayMetadata:{popup:r}}=this.config;this.popup=en({name:e,height:r?.height??500,width:r?.width??1e3}),this.popup?.setContent(ss({name:e,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:e,message:`Loading ${e}...`}))}get backgroundColor(){let{displayMetadata:{button:e,overlay:r}}=this.config;return r?.backgroundColor.colored||e?.backgroundColor.colored||r?.backgroundColor.light||e?.backgroundColor.light||r?.backgroundColor.dark||e?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:e,overlay:r}}=this.config;return r?.logo.colored||e?.iconUrl.colored||r?.logo.light||e?.iconUrl.light||r?.logo.dark||e?.iconUrl.dark}},Hi=class{constructor(t,e){S(this,"currentState");S(this,"stateProcessor");S(this,"handlerRegistry");this.stateProcessor=t,this.handlerRegistry=e}async run(t){let e=await this.stateProcessor.initialize(t??{});return this.handle(e)}async resume(t){let e=await this.stateProcessor.resume(t);return this.handle(e)}async handleEvent(t){if(!this.currentState)throw new Error("handleEvent() called before run()");C.debug("Orchestrator handling event",t);let e=await this.stateProcessor.applyEvent(this.currentState,t);return this.handle(e)}async handle(t){if(this.currentState=t.newState,t.error)throw new Error(t.error.message);if(t.terminal)return C.debug("Orchestrator reached terminal",t.terminal),t.terminal;if(!t.action)return C.debug("Orchestrator waiting for external event"),null;let e=t.action;C.debug(`Executing ${e.type}`,e.params);let r,i;try{let o=await this.handlerRegistry.execute(e.type,e);r=o.outcome,i=o.data??{}}catch(o){C.warn(`Handler failed for ${e.type}`,o),r="error",i={error:o instanceof Error?o.message:"Unknown error"}}let n=await this.stateProcessor.applyResult(this.currentState,e.id,r,i);return this.handle(n)}},Yi=class{constructor(){S(this,"handlers",new Map)}register(t,e){this.handlers.set(t,e)}get(t){return this.handlers.get(t)}async execute(t,e){let r=this.handlers.get(t);return r?r.execute(e):{outcome:"unsupported"}}finishAll(){this.handlers.forEach(t=>t.onFinish?.())}},Zp=["https://sdk.primer.io/web/","https://sdk.dev.primer.io/web/","https://sdk.sandbox.primer.io/web/","https://sdk.production.primer.io/web/","https://sdk.primer.io/state-processor/","https://sdk.dev.primer.io/state-processor/","https://sdk.primer.io/cel-wrapper/","https://sdk.dev.primer.io/cel-wrapper/","https://assets.primer.io/","https://x.klarnacdn.net/kp/lib/v","https://www.paypal.com/sdk/js","https://www.paypalobjects.com/","https://js.stripe.com/","https://pay.google.com/gp/p/js/"];function Jp(a){return Zp.some(t=>a.startsWith(t))}async function Io(a,t){if(!Jp(a))throw new Error(`Script source not authorized per PCI DSS 6.4.3: ${a}`);await new Promise((e,r)=>{let i=document.createElement("script");i.src=a,i.integrity=`sha256-${t}`,i.crossOrigin="anonymous",i.onload=()=>{i.remove(),e()},i.onerror=()=>{i.remove(),r(new Error(`SRI check or load failed for script: ${a}`))},document.head.appendChild(i)})}async function qp(a,t){let e=await fetch(a).then(n=>n.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",e);if(btoa(String.fromCharCode(...new Uint8Array(r)))!==t)throw new Error(`Integrity check failed for ${a}`);return e}var ls=["MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUM5exrePPsIdkWFL6IjKdYmEDoEHBZkoBvrApQpmDEhQ7IisLTCiP0byqN+5B5V60QjAj4I/Bw292h8gPGZyOg==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAERA0j68aAYtwMDagEx2FY+CBbm2+MAYviARSMxWHt1Qt8wGyVvLJ2FqIvg4m2pKfb7GqUwzuJRD/gaOrO2ZJulQ==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEp7v1KpNTWcI9yJSoZYGvRxsPtciT99P2YDpISVLyD6BDD8xqJ11A8v2/elOEPaSxx5hConszht1cOlPp9YdTsA=="];function Qp(a){let t=2;a[1]===129&&(t=3),t++;let e=a[t++],r=a.slice(t,t+e);t+=e,t++;let i=a[t++],n=a.slice(t,t+i),o=new Uint8Array(new ArrayBuffer(64));return o.set(r.slice(-32),32-Math.min(r.length,32)),o.set(n.slice(-32),64-Math.min(n.length,32)),o}async function Xp(a){let t=Uint8Array.from(atob(a),e=>e.charCodeAt(0));return crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}async function em(a,t){let e=Qp(Uint8Array.from(atob(t),i=>i.charCodeAt(0))),r=new TextEncoder().encode(a);for(let i of ls)try{let n=await Xp(i);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,e,r))return!0}catch{}return!1}async function tm(a){let e;for(let r=0;r<3;r++){r>0&&await xt(300*r);try{let i=await fetch(a.manifestUrl);if(!i.ok)throw new Error(`Failed to fetch state processor manifest: ${i.status}`);let n=await i.json(),{signature:o,manifest:s}=n;if(typeof o!="string"||typeof s!="string")throw new Error("Invalid manifest response format");let l=Cr.decode(s);if(!await em(l,o))throw new Error("Manifest signature verification failed");return JSON.parse(l)}catch(i){e=i}}throw e}async function rm(){return Promise.all(ls.map(async a=>{let t=Uint8Array.from(atob(a),r=>r.charCodeAt(0)),e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("")}))}async function am(a,t,e){let r=await tm(a),i=r.cel.noModules,n=await qp(i.wasm.br,i.wasm.sha256);typeof window.primer_wasm_bindgen!="function"&&await Io(i.js.url,i.js.sha256);let o=window.primer_wasm_bindgen;if(typeof o!="function")throw new Error("Invalid CEL wrapper: window.primer_wasm_bindgen not set after script load");await o(n),window.StateProcessor?.createStateProcessor||await Io(r.stateProcessor.umd.url,r.stateProcessor.umd.sha256);let s=window.StateProcessor;if(!s?.createStateProcessor)throw new Error("createStateProcessor not found after loading state processor module");return s.createStateProcessor(t,e)}function im(a,t){return new Promise((e,r)=>{if(t.aborted)return void r(new DOMException("Aborted","AbortError"));let i=setTimeout(e,a);t.addEventListener("abort",()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))},{once:!0})})}var $i=class{constructor(t,e,r){S(this,"popup");S(this,"shouldRedirect",!1);S(this,"resolveOutcome");S(this,"context");S(this,"config");S(this,"onBeforeRedirect");this.context=t,this.config=e,this.onBeforeRedirect=r}async execute(t){let{url:e}=t.params,r=!!this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect,i=null;return r?(this.shouldRedirect=!0,i="force_redirect"):Qi()&&(this.shouldRedirect=!0,i="in_app_browser"),this.showDialogOverlay(),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,i="popup_blocked")),this.shouldRedirect&&i?(rn(e,this.config.type,i),this.onBeforeRedirect(),window.location.assign(e),new Promise(()=>{})):(this.popup?.setUrl(e),new Promise(n=>{this.resolveOutcome=n,this.popup?.onClose(()=>{this.context.dialogProvider.close(),n({outcome:"cancelled"})})}))}onFinish(){this.resolveOutcome?.({outcome:"success"}),this.context.dialogProvider.close(),this.popup?.close()}get isOpen(){return this.popup?.isOpen??!1}focus(){this.popup?.focus()}openPopup(){let{popup:t}=this.config.displayMetadata;this.popup=en({name:this.config.name,height:t.height,width:t.width}),this.popup?.setContent(ss({name:this.config.name,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:this.config.name,message:`Loading ${this.config.name}...`}))}showDialogOverlay(){let t=document.createElement("div");t.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let e=document.createElement("div");e.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 r=document.createElement("img");r.src=this.logoSrc,e.appendChild(r),t.appendChild(e);let i=document.createElement("p");i.setAttribute("style","max-width: 300px;text-align: center;"),i.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),t.appendChild(i),this.context.dialogProvider.show({htmlContent:t,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}).then(()=>{this.popup?.isOpen&&this.popup.close()})}get backgroundColor(){let{displayMetadata:{button:t,overlay:e}}=this.config;return e?.backgroundColor.colored||t?.backgroundColor.colored||e?.backgroundColor.light||t?.backgroundColor.light||e?.backgroundColor.dark||t?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:t,overlay:e}}=this.config;return e?.logo.colored||t?.iconUrl.colored||e?.logo.light||t?.iconUrl.light||e?.logo.dark||t?.iconUrl.dark||""}},zi=class{async execute(t){let{message:e,severity:r,context:i}=t.params.properties;return Ro(e,{status:r,metadata:i}),{outcome:"success"}}},ji=class{async execute(t){return Le({...t.params,eventName:t.params.eventName}),{outcome:"success"}}},Sr=class extends Ee{constructor(e,r){super(e,r);S(this,"onFinishCallback");S(this,"stepHandlerRegistry");S(this,"abortController");S(this,"stateProcessorConfig");this.stepHandlerRegistry=new Yi;let i=r.decodedClientToken.env,n=null;i!=="PRODUCTION"&&(n=new URLSearchParams(window.location.search).get("manifestUrl")),this.stateProcessorConfig={manifestUrl:n??`https://sdk.primer.io/state-processor/v0/manifests/${i.toLowerCase()}.json`},r.subscribeToTeardown(()=>{this.abortController?.abort(),this.stepHandlerRegistry?.finishAll()})}async setup(){return tn(this.context.clientOptions,this.config.type)?super.setup():!1}setOnFinishCallback(e){this.onFinishCallback=e}async tokenize(){throw new R({message:"Tokenize is not supported for backend-driven payment methods"})}async start(){let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));this.abortController=new AbortController;let r=this.abortController.signal;try{let i=this.context.configuration.clientSession.clientSessionId,n=await this.initiatePayment(i),o=await this.runInstructionLoop(n,i,r);if(r.aborted)return this.finishCancel();if(o.type!=="END")throw new R({message:"Unexpected final instruction type"});this.handleEndInstruction(o)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async resume(e){this.abortController=new AbortController;let r=this.abortController.signal;try{let i=await this.fetchNextInstruction(e),n=await this.runInstructionLoop(i,e,r);if(r.aborted)return this.finishCancel();if(n.type!=="END")throw new R({message:"Unexpected final instruction type"});this.handleEndInstruction(n)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async runInstructionLoop(e,r,i){let n=e,o=null;for(;!i.aborted&&n.type!=="END";){n.type==="EXECUTE"&&!o&&(o=this.processExecute(n)),await im(n.pollDelayMilliseconds,i);let s=this.fetchNextInstruction(r);if(o){let l=await Promise.race([s.then(c=>({kind:"poll",value:c})),o.then(c=>({kind:"orch",value:c}))]);if(l.kind==="orch"){if(l.value?.outcome==="cancelled"){this.abortController?.abort();break}if(l.value?.outcome==="error")throw s.catch(()=>{}),new Error("Step handler failed");n=await s,o=null;continue}n=l.value;continue}n=await s}return n}async initiatePayment(e){Yu(this.context.clientOptions,this.config.type);let{data:r,error:i}=await this.context.pciApi.postClientSessionPay(e,{paymentMethodConfigId:this.config.id,processorMerchantAccountId:this.config.options?.merchantAccountId??null,paymentMethodType:this.config.type,clientInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),returnUri:this.context.clientOptions.redirect?.returnUrl}});if(i||!r)throw i??new R({message:"Failed to initiate backend-driven payment"});return r.clientInstruction}async fetchNextInstruction(e){let{data:r,error:i}=await this.context.pciApi.getClientSessionInstruction(e);if(i||!r)throw i??new R({message:"Failed to fetch payment instruction"});return r.clientInstruction}async processExecute(e){let{schema:r,parameters:i}=e.payload;rm().then(s=>{Le({eventName:"BDC_FLOW_START",trustedKeyFingerprints:s})}).catch(()=>{});let n=await am(this.stateProcessorConfig,JSON.stringify(r),this.buildSdkContext()),o=new Hi(n,this.stepHandlerRegistry);return this.stepHandlerRegistry.register("url.open",new $i(this.context,this.config,()=>this.abortController?.abort())),this.stepHandlerRegistry.register("platform.log",new zi),this.stepHandlerRegistry.register("analytics.event",new ji),o.run(i)}buildSdkContext(){let e=Rt();return{sdk:{type:"WEB",version:ma.getContext()?.sdkVersion??"",integrationType:this.context.integrationType},device:{locale:e.language,userAgent:e.userAgent},session:{checkoutSessionId:this.context.checkoutSessionId,clientSessionId:this.context.configuration.clientSession.clientSessionId,customerId:this.context.configuration.clientSession.customer?.customerId},merchant:{primerAccountId:this.context.configuration.primerAccountId},payment:{paymentMethodType:this.config.type}}}handleEndInstruction(e){this.stepHandlerRegistry?.finishAll();let{checkoutOutcome:r,payment:i}=e.payload;if(i){let{paymentInstrumentToken:n,...o}=i;this.onFinishCallback?.({result:"complete",payment:{...o,checkoutOutcome:r},token:n})}else this.onFinishCallback?.({result:"complete"})}finishCancel(){this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"cancel"})}normalizeError(e){return e instanceof R?e:e instanceof Error?new R({message:e.message}):new R({message:String(e)})}},nm=[B.ADYEN_AFFIRM,B.ADYEN_BANCONTACT_CARD,B.ADYEN_BANCONTACT_PAYCONIQ,B.ADYEN_EPS,B.ADYEN_MULTIBANCO,B.GO_CARDLESS,B.OMISE_PROMPTPAY,B.RAPYD_FAST,B.RAPYD_PROMPTPAY,B.STRIPE_ACH,B.XFERS_PAYNOW,B.NETS];async function om(a,t){let r=a.configuration.paymentMethods.filter(({type:n})=>!t||t.includes(n)).map(n=>{if(nm.includes(n.type))return C.warn(`Payment method ${n.type} is not supported in sdk core.`),null;if(C.debug("Initializing payment method:",n.type),n.implementationType==="BACKEND_DRIVEN"||n.implementationType==="WEB_REDIRECT"&&n.capabilities?.includes("BACKEND_DRIVEN"))return new Sr(n,a);if(n.implementationType==="WEB_REDIRECT")return new Vi(n,a);if(n.type===B.PAYMENT_CARD)return new oa(n,a);if(n.type===B.PAYPAL)return new pa(n,a);if(n.type===B.APPLE_PAY)return new ia(n,a);if(n.type===B.GOOGLE_PAY)return new sa(n,a);if(n.type===B.ADYEN_BLIK)return new na(n,a);if(n.type===B.KLARNA)return new da(n,a);if(n.type===B.ADYEN_KLARNA)return new ca(n,a);if(n.type===B.ADYEN_MBWAY)return new ua(n,a)}).map(async n=>{if(!n)return null;try{return await n.setup()?n:null}catch(o){return C.warn(`Failed to initialize payment method ${n.config.type}:`,o),null}});return(await Promise.all(r)).filter(n=>!!n)}function sm(a,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new R({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let r=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new R({code:Zr.VAULT_ERROR,message:"Missing vaulted payment methods data"});return r=lm(i.data,t.configuration?.clientSession?.paymentMethod?.orderedAllowedCardNetworks),r},async deleteVaultedPaymentMethod(i){if(!r.find(s=>s.id===i))throw new R({code:Zr.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;r=r.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=r.find(s=>s.id===i);if(!n)throw new R({code:Zr.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 F({code:Zr.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await We(a,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=yr(t.checkoutSessionId,po);await new Promise(g=>{s.onload=()=>{g()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),Di(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=an({namespace:`${t.checkoutSessionId}-${po}`,onMessage:g=>{let A=M=>g(M.data);return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},sendMessage:g=>{s.contentWindow?.postMessage(g,"*")}});function c(g,A){g!=="metadata"&&n[g].add(A)}l.setOnFocus(()=>{n.focus.forEach(g=>g())}),l.setOnBlur(()=>{n.blur.forEach(g=>g())}),l.setOnInput(g=>{o=g,n.change.forEach(A=>A())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function p(){s.parentNode&&s.remove()}let m=t.subscribeToTeardown(p);return{frame:s,remove:()=>{m(),p()},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(g,A){g!=="metadata"&&n[g].delete(A)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(g=>{o=g,n.change.forEach(A=>A(o))})}}}}}function lm(a,t){if(!t||t.length===0)return a;let e=new Set(t.map(r=>Zt(r).backend));return a.filter(r=>{if(r.paymentInstrumentType!==Jc.CARD)return!0;let i=r.paymentInstrumentData?.network;return typeof i!="string"||!i?!0:e.has(Zt(i).backend)})}function dm(a,t,e){return e.setOnFinishCallback(r=>{r.result==="cancel"?t.clientSessionApi.unselectPaymentMethod():br(a,r.payment,r.error,r.token,e.config.type)}),{start:()=>We(a,e)}}async function ds(a,t){C.debug("createHeadless",t);let e=await Wp(a,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,integrationType:t.integrationType,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,klarna:t.klarna,merchantDomain:t.merchantDomain,redirect:t.redirect,card:t.card}}),r=await om(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction((n,o)=>t.onPaymentMethodAction?.(n,{...o,payment:Oi(o.payment,o.token)??void 0}));let i={environment:_i?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:a,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return zc({environment:_i?"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?.(r.map(n=>({type:n.config.type,managerType:cm(n)}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){fo(e.decodedClientToken.intent,{paymentId:e.decodedClientToken.paymentId});let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);br(t,n,o);return}if(e.decodedClientToken.intent==="AWAIT_CLIENT_INSTRUCTION"){let{clientSessionId:n,paymentMethodType:o,intent:s}=e.decodedClientToken;fo(s,{paymentMethod:o});let l=r.find(c=>c instanceof Sr&&c.config.type===o);if(!l)return void br(t,void 0,new R({message:"No backend-driven payment method found for resume"}));l.setOnFinishCallback(({result:c,payment:p,error:m,token:g})=>{c!=="cancel"&&br(t,p,m,g,l.config.type)}),await l.resume(n);return}},createPaymentMethodManager:async(n,o)=>{let s=r.find(({config:l})=>l.type===n);return s?s instanceof oa?Mp(t,e,s,o):s instanceof pa||s instanceof ia||s instanceof sa?Tp(t,e,s):s instanceof na?Ip(t,e,s):s instanceof Sr?dm(t,e,s):s instanceof da?kp(t,e,s,o):s instanceof ca?Lp(t,e,s,o):s instanceof ua?Rp(t,e,s):Np(t,e,s):(C.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:ko,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return Zo(e.locale,n??o,s)},getCDNAssets:async n=>{let o=r.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s}=o.config.displayMetadata?.button||{};return{assets:{icon:n?`brand/icon/${n.toLowerCase().replace(/_/g,"-")}.svg`:""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:es}},getPaymentMethodConfiguration:n=>r.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 R({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return sm(t,e,r)},getAssetsManager:()=>({getCardNetworkAsset:ko,getPaymentMethodAsset:async n=>{let o=r.find(({config:p})=>p.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()}}function cm(a){switch(a.config.type){case B.PAYMENT_CARD:return jt.CARD;case B.KLARNA:return jt.KLARNA;case B.ADYEN_KLARNA:return jt.ADYEN_KLARNA;case B.ADYEN_MBWAY:return jt.MBWAY;default:return a.config.implementationType==="NATIVE_SDK"?jt.NATIVE:jt.REDIRECT}}var ko=a=>{let{asset:t,display:e}=Zt(a);return{cardUrl:`${es}/brand/card/${t}.svg`,displayName:e}},um=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Xt(a){let{id:t,orderId:e,paymentMethodData:r}=a,i={id:t,orderId:e};if(!r||typeof r!="object")return i;let n={};for(let[o,s]of Object.entries(r))um.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var pm={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 mm(a,t){let e=a;for(let r of t.split(".")){if(!e||typeof e!="object")return;e=e[r]}return e&&typeof e=="object"?e:void 0}function hm(a,t){if(!a)return;let e={};for(let r of t)a[r]!==void 0&&(e[r]=a[r]);return Object.keys(e).length>0?e:void 0}function cs(a){let{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=a,s=pm[i],l;if(s&&n&&typeof n=="object"){let c=s.path?mm(n,s.path):n;l=hm(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var er=class{constructor(t){this.host=t}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)}dispatchBinDataAvailable(t){this.dispatchEvent("primer:bin-data-available",t)}dispatchBinDataLoadingChange(t){this.dispatchEvent("primer:bin-data-loading-change",{loading: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})}dispatchPaymentCancel(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-cancel",{...t,timestamp:e})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(t,e){let r=Math.floor(Date.now()/1e3),i=!1,n=new CustomEvent("primer:payment-start",{detail:{paymentMethodType:t,abortPaymentCreation:()=>{i=!0,e.abortPaymentCreation()},continuePaymentCreation:o=>{i=!0,e.continuePaymentCreation(o)},timestamp:r},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(n),n.defaultPrevented?!0:i}dispatchPaymentSuccess(t,e){let r=Xt(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{payment:r,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,r){let i=Math.floor(Date.now()/1e3),n=r?Xt(r):void 0;this.dispatchEvent("primer:payment-failure",{error:t,payment:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t,e){let r=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-methods-update",{vaultedPayments:t,cvvRecapture:e,timestamp:r})}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 gt=class extends Event{constructor(t,e,r,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=r,this.subscribe=i??!1}};var tr=class{constructor(t,e,r,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=r,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 gt(this.context,this.host,this.t,this.subscribe))}};var ga=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let r=e||!Object.is(t,this.o);this.o=t,r&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:r}]of this.subscriptions)e(this.o,r)},t!==void 0&&(this.value=t)}addCallback(t,e,r){if(!r)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 nn=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},yt=class extends ga{constructor(t,e,r){super(e.context!==void 0?e.initialValue:r),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 gt(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 nn(this.context,this.host))}};function G({context:a,subscribe:t}){return(e,r)=>{typeof r=="object"?r.addInitializer((function(){new tr(this,{context:a,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new tr(i,{context:a,callback:n=>{i[r]=n},subscribe:t})}))}}var K=Symbol("primer-context");function ft(a,t,e=0,r=10){if(e>r)return a===t;if(a===t)return!0;if(a==null||t==null||typeof a!="object"||typeof t!="object")return!1;let i=Object.keys(a);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=a[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!ft(o,s,e+1,r))return!1}else if(o!==s)return!1}return!0}var ps={klarnaCategories:{categories:[],isLoading:!0},sdkState:{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},paymentMethods:[]},ya=class{constructor(t){(this.host=t).addController(this),this.contextProvider=new yt(t,{context:K,initialValue:structuredClone(ps)})}hostConnected(){}setContext(t){this.contextProvider?.setValue({...this.contextProvider.value,...t})}setSdkState(t){let e=this.contextProvider.value.sdkState,r={...e,...t};ft(e,r)||(this.host.primerEventsController.dispatchSdkState(r),this.setContext({sdkState:r}))}resetSdkState(){this.setContext(structuredClone(ps))}setCardNetworks(t){this.setContext({cardNetworks:t})}setCardNetworksLoadingFalse(){this.setContext({cardNetworks:{detectedCardNetwork:this.contextProvider.value.cardNetworks?.detectedCardNetwork??null,selectableCardNetworks:this.contextProvider.value.cardNetworks?.selectableCardNetworks??[],isLoading:!1}})}setVaultManager(t){this.setContext({vaultManager:t})}setKlarnaCategories(t){this.setContext({klarnaCategories:t})}setAdyenKlarnaOptions(t){this.setContext({adyenKlarnaOptions:t})}setComputedStyles(t){this.setContext({computedStyles:t})}setVaultManagerCvv(t){this.setContext({vaultItem:t})}setEventsController(t){this.setContext({events:t})}};var _t=class _t{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 r=/^[\w\s#.,%()\-+/!]+$/.test(t);return r||P.warn(`Rejected potentially unsafe CSS value: ${t}`),r}getCssVarName(t){let e=_t.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(r,i)=>`-${i.toLowerCase()}`)}`,_t.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let r of Object.keys(t)){let i=t[r];if(!i)continue;if(!this.isValidCssProperty(r)){P.warn(`Skipping invalid CSS property name: ${r}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(r);e.push([n,i])}if(e.length>0)for(let[r,i]of e)this.host.style.setProperty(r,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of _t.cssVarCache.keys()){let e=_t.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};_t.cssVarCache=new Map;var fa=_t;var va=globalThis,Ca=va.ShadowRoot&&(va.ShadyCSS===void 0||va.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,hs=Symbol(),ms=new WeakMap,ba=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==hs)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(Ca&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=ms.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&ms.set(e,t))}return t}toString(){return this.cssText}},gs=a=>new ba(typeof a=="string"?a:a+"",void 0,hs);var on=(a,t)=>{if(Ca)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=va.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},Sa=Ca?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return gs(e)})(a):a;var{is:gm,defineProperty:ym,getOwnPropertyDescriptor:fm,getOwnPropertyNames:vm,getOwnPropertySymbols:bm,getPrototypeOf:Cm}=Object,vt=globalThis,ys=vt.trustedTypes,Sm=ys?ys.emptyScript:"",Am=vt.reactiveElementPolyfillSupport,Er=(a,t)=>a,sn={toAttribute(a,t){switch(t){case Boolean:a=a?Sm:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},Aa=(a,t)=>!gm(a,t),fs={attribute:!0,type:String,converter:sn,reflect:!1,hasChanged:Aa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),vt.litPropertyMetadata??(vt.litPropertyMetadata=new WeakMap);var Ot=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=fs){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&ym(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=fm(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,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??fs}static _$Ei(){if(this.hasOwnProperty(Er("elementProperties")))return;let t=Cm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Er("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Er("properties"))){let e=this.properties,r=[...vm(e),...bm(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(Sa(i))}else t!==void 0&&e.push(Sa(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r: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 r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return on(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,r){this._$AK(t,r)}_$EC(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:sn).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:sn;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){if(r??(r=this.constructor.getPropertyOptions(t)),!(r.hasChanged??Aa)(this[t],e))return;this.P(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,r){this._$AL.has(t)||this._$AL.set(t,e),r.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 r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r)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((r=>r.hostUpdate?.())),this.update(e)):this._$EU()}catch(r){throw t=!1,this._$EU(),r}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){}};Ot.elementStyles=[],Ot.shadowRootOptions={mode:"open"},Ot[Er("elementProperties")]=new Map,Ot[Er("finalized")]=new Map,Am?.({ReactiveElement:Ot}),(vt.reactiveElementVersions??(vt.reactiveElementVersions=[])).push("2.0.4");var bt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},Y=Symbol(),$=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,r){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:r};this.v=i.task,this.j=i.args,this.m=i.argsEqual??vs,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,r;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,r=o}if(this.p===i){if(e===Y)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(r)}catch{}this.i=3,this.h?.(r)}this.u=e,this.l=r}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)}}},vs=(a,t)=>a===t||a.length===t.length&&a.every(((e,r)=>!Aa(e,t[r])));var Ea={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},bs={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Mr=class{constructor(t){this.host=t;this._coreState={...Ea};this._itemState={...bs};this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(t)};this.deleteVaultedPaymentMethod=async t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.updateCoreState({vaultedPaymentMethods:this._coreState.vaultedPaymentMethods}),await this._vaultManager.deleteVaultedPaymentMethod(t),await this.fetchVaultedPaymentMethods()}catch(e){let r=e instanceof Error?e:new Error("Failed to delete payment method");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}};this.setCvvInput=t=>{this.updateItemState({cvvInput:t})};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let t=this._itemState.selectedVaultedPaymentMethod,e=this._coreState.cvvRecapture,r=this._itemState.cvvInput;if(!t||e&&(!r||r.metadata.error)){this.updateItemState({formIsDirty:!0});return}this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t.id,e?{cvv:r?.valueToken}:void 0)}catch(i){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n})}};this.setSelectedVaultedPaymentMethod=t=>{this.updateItemState({selectedVaultedPaymentMethod:t,formIsDirty:!1}),this.host.primerEventsController.dispatchVaultSelectionChange(t?.id??null)};this.startVaultPaymentById=async(t,e)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let r=this._coreState.vaultedPaymentMethods.find(i=>i.id===t);if(!r)throw new Error(`Payment method not found: ${t}`);this.setSelectedVaultedPaymentMethod(r),this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t,e?.cvv?{cvv:e.cvv}:void 0)}catch(i){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n}),i}};this.host.addController(this),this._coreState={...this._coreState,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput},this._itemState={...this._itemState,setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)},new $(this.host,{task:async([e,r])=>{if(!e||!r?.vaultEnabled)return this.updateCoreState({...Ea,enabled:!1}),Y;this.updateCoreState({isLoading:!0});try{let i=e();this._vaultManager=i,this.updateCoreState({enabled:r.vaultEnabled,cvvRecapture:!!r.captureVaultedCardCvv,showEmptyState:r.showEmptyState??!1,headless:r.headless??!1,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.host.sdkContextController.setVaultManagerCvv(this._itemState),await this.fetchVaultedPaymentMethods(!0),P.log("VaultManagerController: Vault initialized successfully",{coreState:this.vaultManagerState,cvvState:this.vaultItemState})}catch(i){P.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:i});let n=i instanceof Error?i:new Error("Unknown error");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:n})}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}updateCoreState(t){let e={...this._coreState,...t};ft(this._coreState,e)?this._coreState=e:(this._coreState=e,this.host.sdkContextController.setVaultManager(e))}updateItemState(t){let e={...this._itemState,...t};ft(this._itemState,e)?this._itemState=e:(this._itemState=e,this.host.sdkContextController.setVaultManagerCvv(e))}initializeVaultManager(t,e){this.createVaultManagerFn=t,this.options=e??null}get vaultManager(){return this._vaultManager}set vaultManager(t){this._vaultManager=t,this.host.requestUpdate()}get options(){return this._options}set options(t){this._options=t,this.host.requestUpdate()}get vaultManagerState(){return Object.freeze({...this._coreState})}get vaultItemState(){return Object.freeze({...this._itemState})}hostConnected(){}hostDisconnected(){this.vaultManager=null,this.updateCoreState({...Ea})}createVaultedPaymentsArray(t){return t.map(e=>cs(e))}updatePaymentMethodsWithEvents(t){this.updateCoreState({vaultedPaymentMethods:t,isLoading:!1,isUpdating:!1});let e=this.createVaultedPaymentsArray(t);this.host.primerEventsController.dispatchVaultMethodsUpdate(e,this.vaultManagerState.cvvRecapture),this.host.primerJS?.handleVaultedMethodsUpdate(e,this.vaultManagerState.cvvRecapture),P.log("VaultManagerController: Dispatched vault methods update",{methodCount:t.length,filteredMethodCount:e.length})}async fetchVaultedPaymentMethods(t){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{t||this.updateCoreState({isUpdating:!0});let e=await this._vaultManager.fetchVaultedPaymentMethods();return P.log("VaultManagerController: Fetched payment methods",e),this.updatePaymentMethodsWithEvents(e),e}catch(e){let r=e instanceof Error?e:new Error("Failed to fetch payment methods");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}}};var Cs=()=>Ss.randomUUID?.()||Em(),Em=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,a=>(a^Mm()>>a/4).toString(16)),Mm=()=>(Ss.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,Ss=typeof crypto<"u"?crypto:{};var Pm={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"},ln=class{sendEvent(t){let e=De.getContext();if(!e)return;let r={...t,id:Cs(),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};Nm(r,e)}},Tm=new ln;function As(a){let t={...a,userAgent:a.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};De.initialize(t)}function Q(a){Tm.sendEvent(a)}function Es(){De.clear()}async function Nm(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){P.debug(`Analytics event ${a.eventName}:`,a);return}let r=Pm[t];return fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{P.error("Failed to send analytics event:",i)})}var Pr="lit-localize-status";var Ms=a=>typeof a!="string"&&"strTag"in a,Ma=(a,t,e)=>{let r=a[0];for(let i=1;i<a.length;i++)r+=t[e?e[i-1]:i-1],r+=a[i];return r};var Tr=(a=>Ms(a)?Ma(a.strings,a.values):a);var E=Tr,Ps=!1;function dn(a){if(Ps)throw new Error("lit-localize can only be configured once");E=a,Ps=!0}var cn=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(Pr,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(Pr,this.__litLocalizeEventHandler)}},Im=a=>a.addController(new cn(a)),Ts=Im;var D=()=>(a,t)=>(a.addInitializer(Ts),a);var Nr=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 Ze=[];for(let a=0;a<256;a++)Ze[a]=(a>>4&15).toString(16)+(a&15).toString(16);function Ns(a){let t=0,e=8997,r=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<a.length;c++)e^=a.charCodeAt(c),t=e*435,r=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,r+=t>>>16,e=t&65535,n+=r>>>16,i=r&65535,l=s+(n>>>16)&65535,o=n&65535;return Ze[l>>8]+Ze[l&255]+Ze[o>>8]+Ze[o&255]+Ze[i>>8]+Ze[i&255]+Ze[e>>8]+Ze[e&255]}var km="",Lm="h",Rm="s";function Is(a,t){return(t?Lm:Rm)+Ns(typeof a=="string"?a:a.join(km))}var ks=new WeakMap,Ls=new Map;function Rs(a,t,e){if(a){let r=e?.id??wm(t),i=a[r];if(i){if(typeof i=="string")return i;if("strTag"in i)return Ma(i.strings,t.values,i.values);{let n=ks.get(i);return n===void 0&&(n=i.values,ks.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return Tr(t)}function wm(a){let t=typeof a=="string"?a:a.strings,e=Ls.get(t);return e===void 0&&(e=Is(t,typeof a!="string"&&!("strTag"in a)),Ls.set(t,e)),e}function un(a){window.dispatchEvent(new CustomEvent(Pr,{detail:a}))}var Ta="",pn,ws,Na,mn,xs,Dt=new Nr;Dt.resolve();var Pa=0,_s=a=>(dn(((t,e)=>Rs(xs,t,e))),Ta=ws=a.sourceLocale,Na=new Set(a.targetLocales),Na.add(a.sourceLocale),mn=a.loadLocale,{getLocale:xm,setLocale:_m}),xm=()=>Ta,_m=a=>{if(a===(pn??Ta))return Dt.promise;if(!Na||!mn)throw new Error("Internal error");if(!Na.has(a))throw new Error("Invalid locale code");Pa++;let t=Pa;return pn=a,Dt.settled&&(Dt=new Nr),un({status:"loading",loadingLocale:a}),(a===ws?Promise.resolve({templates:void 0}):mn(a)).then(r=>{Pa===t&&(Ta=a,pn=void 0,xs=r.templates,un({status:"ready",readyLocale:a}),Dt.resolve())},r=>{Pa===t&&(un({status:"error",errorLocale:a,errorMessage:r.toString()}),Dt.reject(r))}),Dt.promise};var hn="en",gn=["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"],yn="You must call `loadLocale` first to set up the localized template.",Ia,ka,Os=a=>{let t=_s({sourceLocale:hn,targetLocales:gn,loadLocale:a});Ia=t.getLocale,ka=t.setLocale};var fn=a=>{Os(a)},vn=a=>{if(!ka)throw new Error(yn);return ka(a)},bn=()=>{if(!Ia)throw new Error(yn);return Ia()};var Ir=new Set(gn);Ir.add(hn);var Cn=a=>{if(typeof a!="string")return!1;if(a==="en")return!0;let t=a.replace("_","-");if(Ir.has(t))return!0;let e=t.split("-")[0];return!!Ir.has(e)},La=()=>navigator.language||navigator.languages[0]||"en",rr=a=>{let t=a.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":Ir.has(t)?t:Ir.has(e)?e:"en-GB"};var Ra=globalThis,wa=Ra.ShadowRoot&&(Ra.ShadyCSS===void 0||Ra.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Sn=Symbol(),Ds=new WeakMap,kr=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==Sn)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(wa&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=Ds.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&Ds.set(e,t))}return t}toString(){return this.cssText}},Je=a=>new kr(typeof a=="string"?a:a+"",void 0,Sn),f=(a,...t)=>{let e=a.length===1?a[0]:t.reduce(((r,i,n)=>r+(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)+a[n+1]),a[0]);return new kr(e,a,Sn)},Bs=(a,t)=>{if(wa)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=Ra.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},An=wa?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return Je(e)})(a):a;var{is:Om,defineProperty:Dm,getOwnPropertyDescriptor:Bm,getOwnPropertyNames:Gm,getOwnPropertySymbols:Km,getPrototypeOf:Fm}=Object,Ct=globalThis,Gs=Ct.trustedTypes,Um=Gs?Gs.emptyScript:"",Vm=Ct.reactiveElementPolyfillSupport,Lr=(a,t)=>a,Rr={toAttribute(a,t){switch(t){case Boolean:a=a?Um:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},xa=(a,t)=>!Om(a,t),Ks={attribute:!0,type:String,converter:Rr,reflect:!1,useDefault:!1,hasChanged:xa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ct.litPropertyMetadata??(Ct.litPropertyMetadata=new WeakMap);var qe=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=Ks){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 r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&Dm(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=Bm(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,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ks}static _$Ei(){if(this.hasOwnProperty(Lr("elementProperties")))return;let t=Fm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Lr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Lr("properties"))){let e=this.properties,r=[...Gm(e),...Km(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(An(i))}else t!==void 0&&e.push(An(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r: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 r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Bs(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,r){this._$AK(t,r)}_$ET(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:Rr).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Rr;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){let i=this.constructor,n=this[t];if(r??(r=i.getPropertyOptions(t)),!((r.hasChanged??xa)(n,e)||r.useDefault&&r.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,r))))return;this.C(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:r,reflect:i,wrapped:n},o){r&&!(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||r||(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 r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r){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((r=>r.hostUpdate?.())),this.update(e)):this._$EM()}catch(r){throw t=!1,this._$EM(),r}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){}};qe.elementStyles=[],qe.shadowRootOptions={mode:"open"},qe[Lr("elementProperties")]=new Map,qe[Lr("finalized")]=new Map,Vm?.({ReactiveElement:qe}),(Ct.reactiveElementVersions??(Ct.reactiveElementVersions=[])).push("2.1.0");var xr=globalThis,_a=xr.trustedTypes,Fs=_a?_a.createPolicy("lit-html",{createHTML:a=>a}):void 0,Mn="$lit$",Qe=`lit$${Math.random().toFixed(9).slice(2)}$`,Pn="?"+Qe,Hm=`<${Pn}>`,Kt=document,_r=()=>Kt.createComment(""),Or=a=>a===null||typeof a!="object"&&typeof a!="function",Tn=Array.isArray,zs=a=>Tn(a)||typeof a?.[Symbol.iterator]=="function",En=`[
|
|
179
179
|
\f\r]`,wr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Us=/-->/g,Vs=/>/g,Bt=RegExp(`>|${En}(?:([^\\s"'>=/]+)(${En}*=${En}*(?:[^
|
|
180
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Hs=/'/g,Ys=/"/g,js=/^(?:script|style|textarea|title)$/i,Nn=a=>(t,...e)=>({_$litType$:a,strings:t,values:e}),u=Nn(1),ge=Nn(2),wv=Nn(3),Xe=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),$s=new WeakMap,Gt=Kt.createTreeWalker(Kt,129);function Ws(a,t){if(!Tn(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return Fs!==void 0?Fs.createHTML(t):t}var Zs=(a,t)=>{let e=a.length-1,r=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=wr;for(let s=0;s<e;s++){let l=a[s],c,p,m=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===wr?p[1]==="!--"?o=Us:p[1]!==void 0?o=Vs:p[2]!==void 0?(js.test(p[2])&&(i=RegExp("</"+p[2],"g")),o=Bt):p[3]!==void 0&&(o=Bt):o===Bt?p[0]===">"?(o=i??wr,m=-1):p[1]===void 0?m=-2:(m=o.lastIndex-p[2].length,c=p[1],o=p[3]===void 0?Bt:p[3]==='"'?Ys:Hs):o===Ys||o===Hs?o=Bt:o===Us||o===Vs?o=wr:(o=Bt,i=void 0);let A=o===Bt&&a[s+1].startsWith("/>")?" ":"";n+=o===wr?l+Hm:m>=0?(r.push(c),l.slice(0,m)+Mn+l.slice(m)+Qe+A):l+Qe+(m===-2?s:A)}return[Ws(a,n+(a[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},Dr=class a{constructor({strings:t,_$litType$:e},r){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,p]=Zs(t,e);if(this.el=a.createElement(c,r),Gt.currentNode=this.el.content,e===2||e===3){let m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(i=Gt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let m of i.getAttributeNames())if(m.endsWith(Mn)){let g=p[o++],A=i.getAttribute(m).split(Qe),M=/([.?@])?(.*)/.exec(g);l.push({type:1,index:n,name:M[2],strings:A,ctor:M[1]==="."?Da:M[1]==="?"?Ba:M[1]==="@"?Ga:Ut}),i.removeAttribute(m)}else m.startsWith(Qe)&&(l.push({type:6,index:n}),i.removeAttribute(m));if(js.test(i.tagName)){let m=i.textContent.split(Qe),g=m.length-1;if(g>0){i.textContent=_a?_a.emptyScript:"";for(let A=0;A<g;A++)i.append(m[A],_r()),Gt.nextNode(),l.push({type:2,index:++n});i.append(m[g],_r())}}}else if(i.nodeType===8)if(i.data===Pn)l.push({type:2,index:n});else{let m=-1;for(;(m=i.data.indexOf(Qe,m+1))!==-1;)l.push({type:7,index:n}),m+=Qe.length-1}n++}}static createElement(t,e){let r=Kt.createElement("template");return r.innerHTML=t,r}};function Ft(a,t,e=a,r){if(t===Xe)return t;let i=r!==void 0?e._$Co?.[r]:e._$Cl,n=Or(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(a),i._$AT(a,e,r)),r!==void 0?(e._$Co??(e._$Co=[]))[r]=i:e._$Cl=i),i!==void 0&&(t=Ft(a,i._$AS(a,t.values),i,r)),t}var Oa=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:r}=this._$AD,i=(t?.creationScope??Kt).importNode(e,!0);Gt.currentNode=i;let n=Gt.nextNode(),o=0,s=0,l=r[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new ar(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ka(n,this,t)),this._$AV.push(c),l=r[++s]}o!==l?.index&&(n=Gt.nextNode(),o++)}return Gt.currentNode=Kt,i}p(t){let e=0;for(let r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,e),e+=r.strings.length-2):r._$AI(t[e])),e++}},ar=class a{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,r,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=r,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=Ft(this,t,e),Or(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==Xe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):zs(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&&Or(this._$AH)?this._$AA.nextSibling.data=t:this.T(Kt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:r}=t,i=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=Dr.createElement(Ws(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Oa(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=$s.get(t.strings);return e===void 0&&$s.set(t.strings,e=new Dr(t)),e}k(t){Tn(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,r,i=0;for(let n of t)i===e.length?e.push(r=new a(this.O(_r()),this.O(_r()),this,this.options)):r=e[i],r._$AI(n),i++;i<e.length&&(this._$AR(r&&r._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let r=t.nextSibling;t.remove(),t=r}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,r,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=y}_$AI(t,e=this,r,i){let n=this.strings,o=!1;if(n===void 0)t=Ft(this,t,e,0),o=!Or(t)||t!==this._$AH&&t!==Xe,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ft(this,s[r+l],e,l),c===Xe&&(c=this._$AH[l]),o||(o=!Or(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??"")}},Da=class extends Ut{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Ba=class extends Ut{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Ga=class extends Ut{constructor(t,e,r,i,n){super(t,e,r,i,n),this.type=5}_$AI(t,e=this){if((t=Ft(this,t,e,0)??y)===Xe)return;let r=this._$AH,i=t===y&&r!==y||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,n=t!==y&&(r===y||i);i&&this.element.removeEventListener(this.name,this,r),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)}},Ka=class{constructor(t,e,r){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(t){Ft(this,t)}},Js={M:Mn,P:Qe,A:Pn,C:1,L:Zs,R:Oa,D:zs,V:Ft,I:ar,H:Ut,N:Ba,U:Ga,B:Da,F:Ka},Ym=xr.litHtmlPolyfillSupport;Ym?.(Dr,ar),(xr.litHtmlVersions??(xr.litHtmlVersions=[])).push("3.3.0");var qs=(a,t,e)=>{let r=e?.renderBefore??t,i=r._$litPart$;if(i===void 0){let n=e?.renderBefore??null;r._$litPart$=i=new ar(t.insertBefore(_r(),n),n,void 0,e??{})}return i._$AI(a),i};var Br=globalThis,v=class extends qe{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=qs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};v._$litElement$=!0,v.finalized=!0,Br.litElementHydrateSupport?.({LitElement:v});var $m=Br.litElementPolyfillSupport;$m?.({LitElement:v});(Br.litElementVersions??(Br.litElementVersions=[])).push("4.2.0");var b=a=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(a,t)})):customElements.define(a,t)};var zm={attribute:!0,type:String,converter:Rr,reflect:!1,hasChanged:xa},jm=(a=zm,t,e)=>{let{kind:r,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),r==="setter"&&((a=Object.create(a)).wrapped=!0),n.set(e.name,a),r==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,a)},init(s){return s!==void 0&&this.C(o,void 0,a,s),s}}}if(r==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,a)}}throw Error("Unsupported decorator location: "+r)};function h(a){return(t,e)=>typeof e=="object"?jm(a,t,e):((r,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,r),o?Object.getOwnPropertyDescriptor(i,n):void 0})(a,t,e)}function N(a){return h({...a,state:!0,attribute:!1})}var Vt=(a,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(a,t,e),e);function de(a,t){return(e,r,i)=>{let n=o=>o.renderRoot?.querySelector(a)??null;if(t){let{get:o,set:s}=typeof r=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Vt(e,r,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Vt(e,r,{get(){return n(this)}})}}function k(a,t,e){return a?t(a):e?.(a)}var T=f` * { box-sizing: border-box; } `,Qs=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 Xs="https://sdk.primer.io/web/v2-latest/Primer.min.js";var et="20px";var tt={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"},W={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 Fa=class{constructor(t){this.paymentMethods=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,r)=>this.startVaultPaymentInternal(e,r),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=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:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let r=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:r})}}setCardholderName(t){let e=this.paymentMethods?.find(r=>r.type===W.PAYMENT_CARD)?.manager;if(!e){P.warn("PrimerJS: Card payment manager not available - setCardholderName cannot be called yet");return}try{e.setCardholderName(t)}catch(r){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:r})}}};var Ua=typeof window<"u"&&typeof window.document<"u";function Wm(a){return document.querySelector(`script[src^="${a}"]`)}function Zm(a,t){let e=document.createElement("script");return e.setAttribute("src",a),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function el(a,t=!1){if(!Ua)throw new Error("Cannot load script in server environment");let e=Wm(a)??Zm(a,t);return new Promise((r,i)=>{e.onload=()=>{r()},e.onerror=()=>{i(new Error(`Failed to load script: ${a}`))},e.parentNode||document.head.appendChild(e)})}var tl=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var te=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.darkMode=!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.darkMode&&this.classList.add("primer-dark-theme"),this.open||this.openDialog()}updated(e){super.updated(e),e.has("darkMode")&&(this.darkMode?this.classList.add("primer-dark-theme"):this.classList.remove("primer-dark-theme")),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?u`<primer-dialog class="${this.darkMode?"primer-dark-theme":""}" .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?u`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?u`<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}};te.styles=[T,tl],d([h({type:String})],te.prototype,"size",2),d([h({type:Boolean})],te.prototype,"showCloseButton",2),d([h({type:Boolean})],te.prototype,"darkMode",2),d([h({type:Object})],te.prototype,"onOpen",2),d([h({type:Object})],te.prototype,"onContentRendered",2),d([h({type:Object})],te.prototype,"cta",2),d([N()],te.prototype,"open",2),d([de("primer-dialog")],te.prototype,"dialog",2),te=d([b("primer-portal-dialog"),D()],te);var Va=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let r=new te;r.size=t.size??"large",r.showCloseButton=t.showCloseButton??!1;let i=document.querySelector("primer-checkout");r.darkMode=i?.classList.contains("primer-dark-theme")??!1,r.onContentRendered=t.onContentReady,r.cta=t.cta;let n=()=>{r.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};r.addEventListener("primer:dialog-close",n),this.currentDialog=r,this.currentResolver=e,document.body.appendChild(r),r.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 Jm=jr({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});var ir=null,In=null;async function rl(a){if(In===a&&ir)return ir;try{return ir=(await Jm(`../../../localization/lit-localize/locales/${a}.ts`)).templates,In=a,ir}catch{return a!=="en-GB"?rl("en-GB"):(ir={},In=a,ir)}}async function al(a){let t=await rl(a);return(e,r)=>t[e]??r}var Ha=class a 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 a(t,e)}};function il(a,t,e){return a.isDisconnected?!1:(a.host.sdkContextController.contextProvider.value.sdkState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),a.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),a.host.primerEventsController.dispatchPaymentStart(t,e))}function nl(a,t,e){if(!a.isDisconnected&&(P.info("Payment completed:",t),a.host.sdkContextController.setSdkState({isProcessing:!1,isSuccessful:!0}),a.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),a.primerJS?.onPaymentSuccess)){let r=Math.floor(Date.now()/1e3);a.primerJS.onPaymentSuccess({payment:Xt(t),paymentMethodType:e,timestamp:r})}}function ol(a,t,e,r){if(a.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 Ha?{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(a.host.sdkContextController.setSdkState({isProcessing:!1,paymentFailure:o}),a.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,r),Q({eventName:"PAYMENT_FAILURE",paymentId:r?.id,paymentMethod:e}),a.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);a.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:r?Xt(r):void 0,paymentMethodType:e,timestamp:s})}}var sl="1.4.1",Ya=class{constructor(t){this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,new $(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()})}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkContextController.setSdkState({isLoading:!0}),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.contextProvider?.value?.analytics){let e=this.host.sdkContextController.contextProvider.value.sdkState;(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 r={...e.card.cardholderName};r.visible===!1&&(r.required=!1),e.card={...e.card,cardholderName:r}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkContextController.setSdkState({isLoading:!1}))},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.host.sdkContextController.resetSdkState(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Es(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=Xs){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 el(t),await e.Primer?.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),Y;if(!t||!e)return Y;this.cleanupResources();let r;try{let i;if(e.sdkCore!==!1){let m=new Va,g=rr(e.locale||La()),A=await al(g);i={createHeadless:(w,L)=>ds(w,{...L,dialogProvider:m,translate:A,sdkVersion:sl,locale:g})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Fa(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=[],s=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:m=>{this.isDisconnected||(P.info("Configuration payment methods:",m),o=m)},onCheckoutComplete:({payment:m})=>{let g=m?.paymentMethodData?.paymentMethodType;nl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,g)},onCheckoutFail:(m,g)=>{let A=g.payment?.paymentMethodData?.paymentMethodType;ol({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,A,g.payment)},onBeforePaymentCreate:(m,g)=>{if(!m.paymentMethodType){P.error("Payment creation started without payment method type"),g?.abortPaymentCreation();return}if(!(il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m.paymentMethodType,g)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:m.paymentMethodType},g);return}g?.continuePaymentCreation()}},onPaymentMethodAction:(m,g)=>{this.isDisconnected||m==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(g),this.host.sdkContextController.setSdkState({isProcessing:!1}))},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.currentSdkInstance=s,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:s,writable:!1}),await s.start(),this.isDisconnected)return this.cleanupResources(),Y;let l=s.getSDKUtilities();r=s.getAnalyticsUtils?.(),r&&(As({environment:r.environment,checkoutSessionId:r.checkoutSessionId,clientSessionId:r.clientSessionId||"",primerAccountId:r.primerAccountId||"",sdkVersion:sl,clientSessionToken:r.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),r.configurationFetchStartTime&&De.setSdkInitStartTime(r.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.vaultManagerController.initializeVaultManager(s.createVaultManager.bind(s),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!l.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1});let c=(await Promise.all(o.map(async m=>{let g=await this.createManager(m,s);return g?{...m,manager:g}:null}))).filter(m=>!!m),p={clientOptions:e,analytics:r,headlessUtils:l,configuration:e.sdkCore!==!1?s.getConfiguration?.():void 0,paymentMethods:c};return this.host.sdkContextController.setContext(p),this.primerJS&&(this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS),this.primerJS.setPaymentMethods(c)),this.host.primerEventsController.dispatchPaymentMethods(c),P.info("Initialized payment methods:",c),this.host.sdkContextController.setSdkState({isLoading:!1}),Q({eventName:"SDK_INIT_END"}),s}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkContextController.setSdkState({primerJsError:i})),this.cleanupResources(),i}}}async createManager(t,e){try{if(t.managerType==="KLARNA")return await e.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:r=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:r,isLoading:!1})}});if(t.managerType==="ADYEN_KLARNA"){let r=await e.createPaymentMethodManager("ADYEN_KLARNA",{onPaymentOptionsChange:i=>{this.isDisconnected||this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}});if(r&&"getPaymentOptions"in r){let i=r.getPaymentOptions();i.length>0&&this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}return r}return t.managerType==="CARD"?await e.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:r=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataAvailable(r)},onCardNetworksChange:r=>{if(this.isDisconnected)return;let{detectedCardNetworks:i,selectableCardNetworks:n}=r;this.updateCardNetworksState({detectedCardNetwork:i.preferred??i.items[0],selectableCardNetworks:n?.items??[],isLoading:!1})},onBinDataLoadingChange:r=>{this.isDisconnected||(r?this.updateCardNetworksState({detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0}):this.host.sdkContextController.setCardNetworksLoadingFalse(),this.host.primerEventsController.dispatchBinDataLoadingChange(r))}}):await e.createPaymentMethodManager(t.type)}catch(r){P.errorWithDatadog(`Failed to initialize manager for ${t.type}`,{error:r})}}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}};var qm=jr({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});fn(a=>qm(`../../localization/lit-localize/locales/${a}.ts`));var Qm={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},ye=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._classObserver=null;this.locale=rr(La());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ya(this),this.primerEventsController=new er(this),this.styleProcessingController=new fa(this),this.vaultManagerController=new Mr(this),this.headlessSdkController=new Ya(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}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:["class"]})}attributeChangedCallback(e,r,i){e===Qm.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Cn(this.options?.locale)?this.locale=rr(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),vn(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.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let r=De.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Qn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return u` ${k(r,()=>y)} ${k(i,()=>u`<primer-checkout-error></primer-checkout-error>`)} ${k(n,()=>u`<slot name="main" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent,()=>y,()=>u`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,r,i){super.addEventListener(e,r,i)}removeEventListener(e,r,i){super.removeEventListener(e,r,i)}};ye.styles=[T,Qs],d([h({type:String,attribute:"custom-styles"})],ye.prototype,"customStyles",2),d([h({type:String,attribute:"client-token"})],ye.prototype,"clientToken",2),d([h({type:Object,attribute:!1,hasChanged:(e,r)=>!ft(e,r)})],ye.prototype,"options",2),d([h({type:Boolean,attribute:"loader-disabled"})],ye.prototype,"disableLoader",2),d([h({type:Boolean,reflect:!0,attribute:"js-initialized"})],ye.prototype,"_jsInitialized",2),d([de("slot")],ye.prototype,"defaultSlot",2),d([N()],ye.prototype,"previousLoadingState",2),ye=d([D(),b("primer-checkout")],ye);function Xm(a){return document.querySelector(`#${a}`)}function eh(a,t){let e=document.createElement("style");return e.textContent=a,e.id=t,e}function Gr(a,t,e=!0){if(!Ua||Xm(t))return;let i=eh(a,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var ll=`
|
|
180
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Hs=/'/g,Ys=/"/g,js=/^(?:script|style|textarea|title)$/i,Nn=a=>(t,...e)=>({_$litType$:a,strings:t,values:e}),u=Nn(1),ge=Nn(2),wv=Nn(3),Xe=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),$s=new WeakMap,Gt=Kt.createTreeWalker(Kt,129);function Ws(a,t){if(!Tn(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return Fs!==void 0?Fs.createHTML(t):t}var Zs=(a,t)=>{let e=a.length-1,r=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=wr;for(let s=0;s<e;s++){let l=a[s],c,p,m=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===wr?p[1]==="!--"?o=Us:p[1]!==void 0?o=Vs:p[2]!==void 0?(js.test(p[2])&&(i=RegExp("</"+p[2],"g")),o=Bt):p[3]!==void 0&&(o=Bt):o===Bt?p[0]===">"?(o=i??wr,m=-1):p[1]===void 0?m=-2:(m=o.lastIndex-p[2].length,c=p[1],o=p[3]===void 0?Bt:p[3]==='"'?Ys:Hs):o===Ys||o===Hs?o=Bt:o===Us||o===Vs?o=wr:(o=Bt,i=void 0);let A=o===Bt&&a[s+1].startsWith("/>")?" ":"";n+=o===wr?l+Hm:m>=0?(r.push(c),l.slice(0,m)+Mn+l.slice(m)+Qe+A):l+Qe+(m===-2?s:A)}return[Ws(a,n+(a[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},Dr=class a{constructor({strings:t,_$litType$:e},r){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,p]=Zs(t,e);if(this.el=a.createElement(c,r),Gt.currentNode=this.el.content,e===2||e===3){let m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(i=Gt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let m of i.getAttributeNames())if(m.endsWith(Mn)){let g=p[o++],A=i.getAttribute(m).split(Qe),M=/([.?@])?(.*)/.exec(g);l.push({type:1,index:n,name:M[2],strings:A,ctor:M[1]==="."?Da:M[1]==="?"?Ba:M[1]==="@"?Ga:Ut}),i.removeAttribute(m)}else m.startsWith(Qe)&&(l.push({type:6,index:n}),i.removeAttribute(m));if(js.test(i.tagName)){let m=i.textContent.split(Qe),g=m.length-1;if(g>0){i.textContent=_a?_a.emptyScript:"";for(let A=0;A<g;A++)i.append(m[A],_r()),Gt.nextNode(),l.push({type:2,index:++n});i.append(m[g],_r())}}}else if(i.nodeType===8)if(i.data===Pn)l.push({type:2,index:n});else{let m=-1;for(;(m=i.data.indexOf(Qe,m+1))!==-1;)l.push({type:7,index:n}),m+=Qe.length-1}n++}}static createElement(t,e){let r=Kt.createElement("template");return r.innerHTML=t,r}};function Ft(a,t,e=a,r){if(t===Xe)return t;let i=r!==void 0?e._$Co?.[r]:e._$Cl,n=Or(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(a),i._$AT(a,e,r)),r!==void 0?(e._$Co??(e._$Co=[]))[r]=i:e._$Cl=i),i!==void 0&&(t=Ft(a,i._$AS(a,t.values),i,r)),t}var Oa=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:r}=this._$AD,i=(t?.creationScope??Kt).importNode(e,!0);Gt.currentNode=i;let n=Gt.nextNode(),o=0,s=0,l=r[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new ar(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ka(n,this,t)),this._$AV.push(c),l=r[++s]}o!==l?.index&&(n=Gt.nextNode(),o++)}return Gt.currentNode=Kt,i}p(t){let e=0;for(let r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,e),e+=r.strings.length-2):r._$AI(t[e])),e++}},ar=class a{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,r,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=r,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=Ft(this,t,e),Or(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==Xe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):zs(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&&Or(this._$AH)?this._$AA.nextSibling.data=t:this.T(Kt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:r}=t,i=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=Dr.createElement(Ws(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Oa(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=$s.get(t.strings);return e===void 0&&$s.set(t.strings,e=new Dr(t)),e}k(t){Tn(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,r,i=0;for(let n of t)i===e.length?e.push(r=new a(this.O(_r()),this.O(_r()),this,this.options)):r=e[i],r._$AI(n),i++;i<e.length&&(this._$AR(r&&r._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let r=t.nextSibling;t.remove(),t=r}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,r,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=y}_$AI(t,e=this,r,i){let n=this.strings,o=!1;if(n===void 0)t=Ft(this,t,e,0),o=!Or(t)||t!==this._$AH&&t!==Xe,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ft(this,s[r+l],e,l),c===Xe&&(c=this._$AH[l]),o||(o=!Or(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??"")}},Da=class extends Ut{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Ba=class extends Ut{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Ga=class extends Ut{constructor(t,e,r,i,n){super(t,e,r,i,n),this.type=5}_$AI(t,e=this){if((t=Ft(this,t,e,0)??y)===Xe)return;let r=this._$AH,i=t===y&&r!==y||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,n=t!==y&&(r===y||i);i&&this.element.removeEventListener(this.name,this,r),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)}},Ka=class{constructor(t,e,r){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(t){Ft(this,t)}},Js={M:Mn,P:Qe,A:Pn,C:1,L:Zs,R:Oa,D:zs,V:Ft,I:ar,H:Ut,N:Ba,U:Ga,B:Da,F:Ka},Ym=xr.litHtmlPolyfillSupport;Ym?.(Dr,ar),(xr.litHtmlVersions??(xr.litHtmlVersions=[])).push("3.3.0");var qs=(a,t,e)=>{let r=e?.renderBefore??t,i=r._$litPart$;if(i===void 0){let n=e?.renderBefore??null;r._$litPart$=i=new ar(t.insertBefore(_r(),n),n,void 0,e??{})}return i._$AI(a),i};var Br=globalThis,v=class extends qe{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=qs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};v._$litElement$=!0,v.finalized=!0,Br.litElementHydrateSupport?.({LitElement:v});var $m=Br.litElementPolyfillSupport;$m?.({LitElement:v});(Br.litElementVersions??(Br.litElementVersions=[])).push("4.2.0");var b=a=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(a,t)})):customElements.define(a,t)};var zm={attribute:!0,type:String,converter:Rr,reflect:!1,hasChanged:xa},jm=(a=zm,t,e)=>{let{kind:r,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),r==="setter"&&((a=Object.create(a)).wrapped=!0),n.set(e.name,a),r==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,a)},init(s){return s!==void 0&&this.C(o,void 0,a,s),s}}}if(r==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,a)}}throw Error("Unsupported decorator location: "+r)};function h(a){return(t,e)=>typeof e=="object"?jm(a,t,e):((r,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,r),o?Object.getOwnPropertyDescriptor(i,n):void 0})(a,t,e)}function N(a){return h({...a,state:!0,attribute:!1})}var Vt=(a,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(a,t,e),e);function de(a,t){return(e,r,i)=>{let n=o=>o.renderRoot?.querySelector(a)??null;if(t){let{get:o,set:s}=typeof r=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Vt(e,r,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Vt(e,r,{get(){return n(this)}})}}function k(a,t,e){return a?t(a):e?.(a)}var T=f` * { box-sizing: border-box; } `,Qs=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 Xs="https://sdk.primer.io/web/v2-latest/Primer.min.js";var et="20px";var tt={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"},W={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 Fa=class{constructor(t){this.paymentMethods=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,r)=>this.startVaultPaymentInternal(e,r),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=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:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let r=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:r})}}setCardholderName(t){let e=this.paymentMethods?.find(r=>r.type===W.PAYMENT_CARD)?.manager;if(!e){P.warn("PrimerJS: Card payment manager not available - setCardholderName cannot be called yet");return}try{e.setCardholderName(t)}catch(r){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:r})}}};var Ua=typeof window<"u"&&typeof window.document<"u";function Wm(a){return document.querySelector(`script[src^="${a}"]`)}function Zm(a,t){let e=document.createElement("script");return e.setAttribute("src",a),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function el(a,t=!1){if(!Ua)throw new Error("Cannot load script in server environment");let e=Wm(a)??Zm(a,t);return new Promise((r,i)=>{e.onload=()=>{r()},e.onerror=()=>{i(new Error(`Failed to load script: ${a}`))},e.parentNode||document.head.appendChild(e)})}var tl=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var te=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.darkMode=!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.darkMode&&this.classList.add("primer-dark-theme"),this.open||this.openDialog()}updated(e){super.updated(e),e.has("darkMode")&&(this.darkMode?this.classList.add("primer-dark-theme"):this.classList.remove("primer-dark-theme")),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?u`<primer-dialog class="${this.darkMode?"primer-dark-theme":""}" .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?u`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?u`<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}};te.styles=[T,tl],d([h({type:String})],te.prototype,"size",2),d([h({type:Boolean})],te.prototype,"showCloseButton",2),d([h({type:Boolean})],te.prototype,"darkMode",2),d([h({type:Object})],te.prototype,"onOpen",2),d([h({type:Object})],te.prototype,"onContentRendered",2),d([h({type:Object})],te.prototype,"cta",2),d([N()],te.prototype,"open",2),d([de("primer-dialog")],te.prototype,"dialog",2),te=d([b("primer-portal-dialog"),D()],te);var Va=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let r=new te;r.size=t.size??"large",r.showCloseButton=t.showCloseButton??!1;let i=document.querySelector("primer-checkout");r.darkMode=i?.classList.contains("primer-dark-theme")??!1,r.onContentRendered=t.onContentReady,r.cta=t.cta;let n=()=>{r.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};r.addEventListener("primer:dialog-close",n),this.currentDialog=r,this.currentResolver=e,document.body.appendChild(r),r.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 Jm=jr({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});var ir=null,In=null;async function rl(a){if(In===a&&ir)return ir;try{return ir=(await Jm(`../../../localization/lit-localize/locales/${a}.ts`)).templates,In=a,ir}catch{return a!=="en-GB"?rl("en-GB"):(ir={},In=a,ir)}}async function al(a){let t=await rl(a);return(e,r)=>t[e]??r}var Ha=class a 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 a(t,e)}};function il(a,t,e){return a.isDisconnected?!1:(a.host.sdkContextController.contextProvider.value.sdkState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),a.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),a.host.primerEventsController.dispatchPaymentStart(t,e))}function nl(a,t,e){if(!a.isDisconnected&&(P.info("Payment completed:",t),a.host.sdkContextController.setSdkState({isProcessing:!1,isSuccessful:!0}),a.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),a.primerJS?.onPaymentSuccess)){let r=Math.floor(Date.now()/1e3);a.primerJS.onPaymentSuccess({payment:Xt(t),paymentMethodType:e,timestamp:r})}}function ol(a,t,e,r){if(a.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 Ha?{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(a.host.sdkContextController.setSdkState({isProcessing:!1,paymentFailure:o}),a.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,r),Q({eventName:"PAYMENT_FAILURE",paymentId:r?.id,paymentMethod:e}),a.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);a.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:r?Xt(r):void 0,paymentMethodType:e,timestamp:s})}}var sl="1.4.2",Ya=class{constructor(t){this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,new $(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()})}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkContextController.setSdkState({isLoading:!0}),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.contextProvider?.value?.analytics){let e=this.host.sdkContextController.contextProvider.value.sdkState;(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 r={...e.card.cardholderName};r.visible===!1&&(r.required=!1),e.card={...e.card,cardholderName:r}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkContextController.setSdkState({isLoading:!1}))},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.host.sdkContextController.resetSdkState(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Es(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=Xs){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 el(t),await e.Primer?.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),Y;if(!t||!e)return Y;this.cleanupResources();let r;try{let i;if(e.sdkCore!==!1){let m=new Va,g=rr(e.locale||La()),A=await al(g);i={createHeadless:(w,L)=>ds(w,{...L,dialogProvider:m,translate:A,sdkVersion:sl,locale:g})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Fa(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=[],s=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:m=>{this.isDisconnected||(P.info("Configuration payment methods:",m),o=m)},onCheckoutComplete:({payment:m})=>{let g=m?.paymentMethodData?.paymentMethodType;nl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,g)},onCheckoutFail:(m,g)=>{let A=g.payment?.paymentMethodData?.paymentMethodType;ol({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,A,g.payment)},onBeforePaymentCreate:(m,g)=>{if(!m.paymentMethodType){P.error("Payment creation started without payment method type"),g?.abortPaymentCreation();return}if(!(il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m.paymentMethodType,g)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:m.paymentMethodType},g);return}g?.continuePaymentCreation()}},onPaymentMethodAction:(m,g)=>{this.isDisconnected||m==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(g),this.host.sdkContextController.setSdkState({isProcessing:!1}))},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.currentSdkInstance=s,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:s,writable:!1}),await s.start(),this.isDisconnected)return this.cleanupResources(),Y;let l=s.getSDKUtilities();r=s.getAnalyticsUtils?.(),r&&(As({environment:r.environment,checkoutSessionId:r.checkoutSessionId,clientSessionId:r.clientSessionId||"",primerAccountId:r.primerAccountId||"",sdkVersion:sl,clientSessionToken:r.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),r.configurationFetchStartTime&&De.setSdkInitStartTime(r.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.vaultManagerController.initializeVaultManager(s.createVaultManager.bind(s),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!l.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1});let c=(await Promise.all(o.map(async m=>{let g=await this.createManager(m,s);return g?{...m,manager:g}:null}))).filter(m=>!!m),p={clientOptions:e,analytics:r,headlessUtils:l,configuration:e.sdkCore!==!1?s.getConfiguration?.():void 0,paymentMethods:c};return this.host.sdkContextController.setContext(p),this.primerJS&&(this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS),this.primerJS.setPaymentMethods(c)),this.host.primerEventsController.dispatchPaymentMethods(c),P.info("Initialized payment methods:",c),this.host.sdkContextController.setSdkState({isLoading:!1}),Q({eventName:"SDK_INIT_END"}),s}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkContextController.setSdkState({primerJsError:i})),this.cleanupResources(),i}}}async createManager(t,e){try{if(t.managerType==="KLARNA")return await e.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:r=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:r,isLoading:!1})}});if(t.managerType==="ADYEN_KLARNA"){let r=await e.createPaymentMethodManager("ADYEN_KLARNA",{onPaymentOptionsChange:i=>{this.isDisconnected||this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}});if(r&&"getPaymentOptions"in r){let i=r.getPaymentOptions();i.length>0&&this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}return r}return t.managerType==="CARD"?await e.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:r=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataAvailable(r)},onCardNetworksChange:r=>{if(this.isDisconnected)return;let{detectedCardNetworks:i,selectableCardNetworks:n}=r;this.updateCardNetworksState({detectedCardNetwork:i.preferred??i.items[0],selectableCardNetworks:n?.items??[],isLoading:!1})},onBinDataLoadingChange:r=>{this.isDisconnected||(r?this.updateCardNetworksState({detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0}):this.host.sdkContextController.setCardNetworksLoadingFalse(),this.host.primerEventsController.dispatchBinDataLoadingChange(r))}}):await e.createPaymentMethodManager(t.type)}catch(r){P.errorWithDatadog(`Failed to initialize manager for ${t.type}`,{error:r})}}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}};var qm=jr({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});fn(a=>qm(`../../localization/lit-localize/locales/${a}.ts`));var Qm={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},ye=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._classObserver=null;this.locale=rr(La());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ya(this),this.primerEventsController=new er(this),this.styleProcessingController=new fa(this),this.vaultManagerController=new Mr(this),this.headlessSdkController=new Ya(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}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:["class"]})}attributeChangedCallback(e,r,i){e===Qm.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Cn(this.options?.locale)?this.locale=rr(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),vn(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.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let r=De.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Qn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return u` ${k(i,()=>u`<primer-checkout-error></primer-checkout-error>`)}<slot name="main" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent||!n,()=>y,()=>u`<primer-main></primer-main>`)} `}addEventListener(e,r,i){super.addEventListener(e,r,i)}removeEventListener(e,r,i){super.removeEventListener(e,r,i)}};ye.styles=[T,Qs],d([h({type:String,attribute:"custom-styles"})],ye.prototype,"customStyles",2),d([h({type:String,attribute:"client-token"})],ye.prototype,"clientToken",2),d([h({type:Object,attribute:!1,hasChanged:(e,r)=>!ft(e,r)})],ye.prototype,"options",2),d([h({type:Boolean,attribute:"loader-disabled"})],ye.prototype,"disableLoader",2),d([h({type:Boolean,reflect:!0,attribute:"js-initialized"})],ye.prototype,"_jsInitialized",2),d([de("slot")],ye.prototype,"defaultSlot",2),d([N()],ye.prototype,"previousLoadingState",2),ye=d([D(),b("primer-checkout")],ye);function Xm(a){return document.querySelector(`#${a}`)}function eh(a,t){let e=document.createElement("style");return e.textContent=a,e.id=t,e}function Gr(a,t,e=!0){if(!Ua||Xm(t))return;let i=eh(a,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var ll=`
|
|
181
181
|
@keyframes primer-css-spinner-rotate {
|
|
182
182
|
0% {
|
|
183
183
|
transform: rotate(0deg);
|
|
@@ -187,12 +187,16 @@ import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q
|
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
189
|
|
|
190
|
-
/* Hide primer-main
|
|
190
|
+
/* Hide primer-main and primer-checkout-error while they are loading to prevent FOUC
|
|
191
191
|
Only check for undefined primer-* elements, ignoring browser extensions */
|
|
192
|
-
primer-
|
|
192
|
+
primer-main:not(:defined), primer-checkout-error:not(:defined) {
|
|
193
193
|
visibility: hidden;
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
+
primer-checkout:not([js-initialized]) [slot="main"] {
|
|
197
|
+
display: none;
|
|
198
|
+
}
|
|
199
|
+
|
|
196
200
|
primer-checkout:not([js-initialized]) {
|
|
197
201
|
display: block;
|
|
198
202
|
position: relative;
|
|
@@ -236,4 +240,4 @@ primer-checkout:not([js-initialized]):not([loader-disabled])::after {
|
|
|
236
240
|
input[data-custom-input]:focus {
|
|
237
241
|
outline: none;
|
|
238
242
|
}
|
|
239
|
-
`,t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}function Zd(a,t){return a.active!==t.active||a.dirty!==t.dirty||a.error!==t.error||a.errorCode!==t.errorCode||a.submitted!==t.submitted||a.touched!==t.touched||a.valid!==t.valid}var ti=class{constructor(t,e){this._meta={active:!1,dirty:!1,error:null,errorCode:null,submitted:!1,touched:!1,valid:!1};this._hostedInput=null;this._standardInput=null;this.host=t,this.config=e,this.host.addController(this),this.setupTask=new $(this.host,{args:()=>[this.getHostedInput()],task:this.setupHostedInput.bind(this)}),this.host.addEventListener("wrapper-click",()=>{this.focusInput()})}focusInput(){this._hostedInput?this._hostedInput.focus():this._standardInput&&this._standardInput.focus()}notifyUserInteraction(){let t=this.host.cardFormContext;t?.onUserInteraction&&t.onUserInteraction()}getHostedInput(){let{type:t}=this.config,e=this.host.cardFormContext;return e?{cardNumber:e.cardNumberInput,cvv:e.cvvInput,expire:e.expiryInput,cardholderName:e.cardholderNameInput??"cardholderName"}[t]:void 0}async setupHostedInput([t]){if(!t)return Y;await this.host.updateComplete;let e=this.getTargetContainer();return e?t==="cardholderName"?this.setupStandardInput(e):this.setupHostedIframeInput(t,e):Y}getTargetContainer(){return this.host.renderRoot.querySelector(this.config.containerSelector)}setupStandardInput(t){let e=document.createElement("input");return e.type="text",e.placeholder=this.host.placeholder,Hn(e,this.host),(this.host.ariaLabel||this.host.label)&&e.setAttribute("aria-label",this.host.ariaLabel??this.host.label),this.setupInputEventListeners(e),t.innerHTML="",t.appendChild(e),this._standardInput=e,!0}setupInputEventListeners(t){t.addEventListener("input",e=>{let r=e.target,n=!!r.value.trim();this.notifyUserInteraction(),this._meta={...this._meta,dirty:n},this.config.onInput?.(r.value),this.host.requestUpdate()}),t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this._meta.touched=!1,this.host.requestUpdate()}),t.addEventListener("keydown",e=>{if(e.key==="Enter"){e.preventDefault();let r=this.host.closest("form");r&&r.requestSubmit()}})}async setupHostedIframeInput(t,e){await new Promise(n=>requestAnimationFrame(()=>n())),this._hostedInput=t;let r=Fr(this.host.primerContext?.computedStyles??null),i=r?{style:{input:{base:r}}}:void 0;return t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this.host.requestUpdate()}),t.addEventListener("change",n=>{let o=n;this.notifyUserInteraction(),Zd(this._meta,o)&&(this._meta={...this._meta,...o},this.host.requestUpdate())}),t.addEventListener("enter",()=>{let n=this.host.closest("form");n&&n.requestSubmit()}),this.host.isConnected?(await t.render(e,{placeholder:this.host.placeholder,ariaLabel:this.host.ariaLabel,...i}),!0):!1}get meta(){return this._meta}updateMetaFromValidation(t){this._meta={...this._meta,valid:!!t.valid,error:t.error||null,errorCode:t.errorCode||null},this.host.requestUpdate()}setSubmitted(t){this._meta={...this._meta,submitted:t,...t&&{touched:!0}},this.host.requestUpdate()}hostConnected(){this.registerWithContext()}hostDisconnected(){this.unregisterFromContext(),this._hostedInput=null,this._standardInput=null}hostUpdate(){if(this._hostedInput?.setOptions){let t=Fr(this.host.primerContext?.computedStyles??null);this._hostedInput.setOptions({placeholder:this.host.placeholder,ariaLabel:this.host.ariaLabel,...t&&{style:{input:{base:t}}}})}else this._standardInput&&this.host.primerContext?.computedStyles&&Hn(this._standardInput,this.host)}registerWithContext(){let t=this.host.cardFormContext;t?.registerInputController&&t.registerInputController(this.config.type,this)}unregisterFromContext(){let t=this.host.cardFormContext;t?.unregisterInputController&&t.unregisterInputController(this.config.type)}};var Jd=f` :host { display: contents; } form { display: flex; flex-direction: column; gap: var(--primer-space-medium); width: 100%; } .card-form { display: flex; flex-direction: column; gap: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .card-form-row { display: flex; gap: var(--primer-space-small); } `;var qd={cardholderName:"cardholderName",cardNumber:"cardNumber",cardExpiryDate:"expire",expiryDate:"expire",cardSecurityCode:"cvv",cvv:"cvv"},Se=class extends v{constructor(){super(...arguments);this.hideLabels=!1;this.disabled=!1;this.hasAssignedContent=!1;this.selectedCardNetwork=null;this.formErrorMessage=null;this.paymentMethodSelectionSent=!1;this.cardFormProvider=new yt(this,{context:dr,initialValue:null});this.eventsController=new er(this);this._contextCardSubmitListener=null;this._isHandlingContextEvent=!1;this.inputControllers=new Map;this.setupCardFormTask=new $(this,{task:([e])=>{let r=e?.find(l=>l.type===W.PAYMENT_CARD)?.manager;if(!r)return Y;let i=r.createHostedInputs(),{cardNumberInput:n,expiryInput:o,cvvInput:s}=i;return this.cardFormProvider.setValue({cardholderNameInput:i.cardholderNameInput,cardNumberInput:n,expiryInput:o,cvvInput:s,setCardholderName:l=>{r.setCardholderName(l),this.shouldRequireCardholderName&&r.validate?.().then(c=>{let m=c?.validationErrors?.find(A=>A.name===qd.cardholderName),g=this.inputControllers.get("cardholderName");g&&g.updateMetaFromValidation({valid:!1,error:m?.message||m?.error||null,errorCode:m?.message||m?.error||null})})},setCardNetwork:l=>{this.selectedCardNetwork=l},validate:()=>r.validate(),submit:l=>r.submit(l),hideLabels:this.hideLabels,disabled:this.disabled,setSubmissionState:l=>{this.inputControllers.forEach(c=>{c.setSubmitted(l)})},propagateValidationErrors:l=>{l&&l.forEach(c=>{let p=c.field||c.name,m=c.message||c.error,g=qd[p];if(g){let A=this.inputControllers.get(g);if(A){let M={valid:!1,error:m,errorCode:m};A.updateMetaFromValidation(M)}}})},registerInputController:(l,c)=>{this.inputControllers.set(l,c)},unregisterInputController:l=>{this.inputControllers.delete(l)},onUserInteraction:()=>{this.sendPaymentMethodSelectionEvent(),this.checkAndSendPaymentDetailsEnteredEvent()}}),!0},args:()=>[this.primerContext?.paymentMethods]});this.paymentDetailsEnteredSent=!1;this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isSubmitButton(n)&&(e.preventDefault(),this.submitCardPayment())};this.handleDirectSubmit=e=>{e.stopPropagation(),this.submitCardPayment()};this.handleContextCardSubmit=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{e.target!==this&&(e.stopPropagation(),this.submitCardPayment())}finally{this._isHandlingContextEvent=!1}}};this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0};this.handleFormSubmit=e=>{e.preventDefault(),e.stopPropagation(),this.submitCardPayment()}}updated(e){if(super.updated(e),(e.has("hideLabels")||e.has("disabled"))&&this.cardFormProvider.value&&this.cardFormProvider.setValue({...this.cardFormProvider.value,hideLabels:this.hideLabels,disabled:this.disabled}),e.has("context")){let i=e.get("context")?.events??null;i?.host&&this._contextCardSubmitListener&&i.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener),this.setupContextEventListeners()}}get shouldShowCardholderName(){let e=this.primerContext?.clientOptions?.card?.cardholderName;return typeof e?.visible=="boolean"?e.visible:!0}get shouldRequireCardholderName(){if(!this.shouldShowCardholderName)return!1;let e=this.primerContext?.clientOptions?.card?.cardholderName;return typeof e?.required=="boolean"?e.required:!0}sendPaymentMethodSelectionEvent(){this.paymentMethodSelectionSent||(this.paymentMethodSelectionSent=!0,Q({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYMENT_CARD"}))}checkAndSendPaymentDetailsEnteredEvent(){if(this.paymentDetailsEnteredSent)return;let e=this.inputControllers.get("cardNumber"),r=this.inputControllers.get("expire"),i=this.inputControllers.get("cvv"),n=e?.meta?.dirty===!0,o=r?.meta?.dirty===!0,s=i?.meta?.dirty===!0,l=!0;this.shouldRequireCardholderName&&(l=this.inputControllers.get("cardholderName")?.meta?.dirty===!0),n&&o&&s&&l&&(this.sendPaymentDetailsEnteredEvent(),this.paymentDetailsEnteredSent=!0)}sendPaymentDetailsEnteredEvent(){Q({eventName:"PAYMENT_DETAILS_ENTERED",paymentMethod:"PAYMENT_CARD"})}connectedCallback(){super.connectedCallback(),this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:card-submit",this.handleDirectSubmit),this._contextCardSubmitListener=e=>{this.handleContextCardSubmit(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:card-submit",this.handleDirectSubmit),this.cleanupContextEventListeners(),super.disconnectedCallback()}setupContextEventListeners(){this.primerContext?.events?.host&&this._contextCardSubmitListener&&this.primerContext?.events.host.addEventListener("primer:card-submit",this._contextCardSubmitListener)}cleanupContextEventListeners(){this.primerContext?.events?.host&&this._contextCardSubmitListener&&this.primerContext?.events.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener)}isSubmitButton(e){let r=e.tagName.toLowerCase(),i=r==="button",n=r==="primer-button";return i&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))||n&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))}async submitCardPayment(){let e=this.cardFormProvider.value;if(!e||this.disabled)return;this.formErrorMessage=null,e.setSubmissionState?.(!0);let r=this.querySelector("primer-billing-address")||this.renderRoot.querySelector("primer-billing-address"),i=!0;r&&(i=await r.validateForSubmission());let n=await e.validate?.();if(n?.valid&&i){if(r&&!await r.submitToSDK()){let c=E("tokenizationError",{id:"tokenizationError"});this.formErrorMessage=c,this.eventsController.dispatchFormSubmitErrors([{field:"billingAddress",name:"billingAddress",error:"BILLING_ADDRESS_SUBMISSION_FAILED",message:c}]);return}let o={success:!0};this.eventsController.dispatchFormSubmitSuccess(o);let s=this.selectedCardNetwork?{cardNetwork:this.selectedCardNetwork}:void 0;await e.submit?.(s)}else{let o=n?.validationErrors;e.propagateValidationErrors?.(o||[]),this.cardFormProvider.setValue({...e,errors:o}),this.eventsController.dispatchFormSubmitErrors(o)}}render(){return this.setupCardFormTask.status===bt.ERROR||this.setupCardFormTask.status===bt.INITIAL?y:u`<form @submit=${this.handleFormSubmit}><slot name="card-form-content" @slotchange=${this.onSlotChange}></slot>${this.setupCardFormTask.render({complete:()=>k(this.hasAssignedContent,()=>y,()=>u`<div class="card-form"><primer-input-card-number></primer-input-card-number><div class="card-form-row"><primer-input-card-expiry></primer-input-card-expiry><primer-input-cvv></primer-input-cvv></div>${k(this.shouldShowCardholderName,()=>u`<primer-input-card-holder-name></primer-input-card-holder-name>`,()=>y)} ${k(this.primerContext?.clientOptions?.sdkCore!==!1,()=>u`<primer-billing-address></primer-billing-address>`,()=>y)}</div><primer-card-form-submit></primer-card-form-submit><primer-error-message message="${this.formErrorMessage||""}" ?visible="${!!this.formErrorMessage}" ></primer-error-message>`)})}</form>`}};Se.styles=[T,Jd],d([h({type:Boolean,attribute:"hide-labels",reflect:!0})],Se.prototype,"hideLabels",2),d([h({type:Boolean,attribute:"disabled"})],Se.prototype,"disabled",2),d([N()],Se.prototype,"hasAssignedContent",2),d([N()],Se.prototype,"selectedCardNetwork",2),d([N()],Se.prototype,"formErrorMessage",2),d([G({context:K,subscribe:!0}),h({attribute:!1})],Se.prototype,"primerContext",2),Se=d([b("primer-card-form"),D()],Se);var se=class extends v{constructor(){super();this._cardFormContext=null;this._userAssignedProps=new Set;this._internalLabel="";this._internalPlaceholder="";this._internalAriaLabel="";this.handleWrapperClick=()=>{this.hostedInputController.focusInput()};this.hostedInputController={}}get cardFormContext(){return this._cardFormContext}set cardFormContext(e){let r=this._cardFormContext;this._cardFormContext=e,!r&&e&&this.updateComplete.then(()=>{this.hostedInputController?.registerWithContext?.()}),this.requestUpdate("cardFormContext",r)}getTranslatedValue(e){return e?typeof e=="string"?e:E(e.id,{id:e.id}):""}get label(){return this._userAssignedProps.has("label")?this._internalLabel:this.getTranslatedValue(this.config.translations.label)}set label(e){let r=this.label;e!==""?(this._userAssignedProps.add("label"),this._internalLabel=e):(this._userAssignedProps.delete("label"),this._internalLabel=""),this.requestUpdate("label",r)}get placeholder(){return this._userAssignedProps.has("placeholder")?this._internalPlaceholder:this.getTranslatedValue(this.config.translations.placeholder)}set placeholder(e){let r=this.placeholder;this._userAssignedProps.add("placeholder"),this._internalPlaceholder=e,this.requestUpdate("placeholder",r)}get ariaLabel(){return this._userAssignedProps.has("ariaLabel")?this._internalAriaLabel:this.getTranslatedValue(this.config.translations.ariaLabel)||this.getTranslatedValue(this.config.translations.label)}set ariaLabel(e){let r=this.ariaLabel;e!==""?(this._userAssignedProps.add("ariaLabel"),this._internalAriaLabel=e):(this._userAssignedProps.delete("ariaLabel"),this._internalAriaLabel=""),this.requestUpdate("ariaLabel",r)}childUpdated(){Object.defineProperty(this,"hostedInputController",{value:new ti(this,{type:this.config.inputType,containerSelector:this.config.containerSelector,onInput:this.config.onInput}),writable:!1,configurable:!1})}getError(){let e=this.hostedInputController.meta;return e.submitted||e.dirty&&e.touched?e.errorCode:null}renderInput(){if(this.hostedInputController.setupTask.status===bt.ERROR)return y;let e=this.getError();return u`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} @wrapper-click="${this.handleWrapperClick}" >${k(!this.cardFormContext?.hideLabels,()=>u`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>y)}<div slot="input" class="card-input-slot" id="${this.config.containerSelector.substring(1)}" aria-label="${this.ariaLabel}" ></div>${k(e,()=>u`<primer-input-error slot="error">${E(e,{id:e})}</primer-input-error>`,()=>y)}</primer-input-wrapper>`}};d([G({context:dr,subscribe:!0})],se.prototype,"cardFormContext",1),d([G({context:K,subscribe:!0}),h({attribute:!1})],se.prototype,"primerContext",2),d([h({type:String})],se.prototype,"label",1),d([h({type:String})],se.prototype,"placeholder",1),d([h({type:String,attribute:"aria-label"})],se.prototype,"ariaLabel",1);var Qd=f` :host { display: contents; } .card-number-container { display: flex; align-items: center; width: 100%; position: relative; gap: var(--primer-space-small); } #cardNumber { flex: 1; display: flex; width: 100%; } .network-selector-container { display: flex; align-items: center; z-index: 2; } `;var Pt=f` .card-input-slot { display: flex; } `;var lt=class extends se{constructor(){super();this.config={inputType:"cardNumber",containerSelector:"#cardNumber",errorName:"cardNumber-card",translations:{label:{id:"cardNumber",defaultMessage:"Card Number"},placeholder:"4111 1111 1111 1111",ariaLabel:{id:"cardNumber",defaultMessage:"Card Number"}}};this.handleNetworkSelected=e=>{let{network:r}=e.detail;this.cardFormContext&&this.cardFormContext.setCardNetwork(r)};this.childUpdated()}renderInput(){if(this.hostedInputController.setupTask.status===bt.ERROR)return y;let e=this.getError();return u`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} >${k(!this.cardFormContext?.hideLabels,()=>u`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>y)}<div slot="input" class="card-number-container" aria-label="${this.ariaLabel}" ><div id="${this.config.containerSelector.substring(1)}"></div><div class="network-selector-container"><primer-card-network-selector @network-selected=${this.handleNetworkSelected} ></primer-card-network-selector></div></div>${k(e,r=>u`<primer-input-error slot="error">${E(r,{id:r})}</primer-input-error>`,()=>y)}</primer-input-wrapper>`}render(){return this.renderInput()}};lt.styles=[T,Pt,Qd],lt=d([b("primer-input-card-number"),D()],lt);var Xd=f` :host { display: contents; } `;var dt=class extends se{constructor(){super();this.config={inputType:"cvv",containerSelector:"#cvv",errorName:"cvv-card",translations:{label:"CVV",placeholder:"123"}};this.childUpdated()}render(){return this.renderInput()}};dt.styles=[T,Pt,Xd],dt=d([b("primer-input-cvv"),D()],dt);var ec=f` :host { display: contents; } `;var ct=class extends se{constructor(){super();this.config={inputType:"expire",containerSelector:"#expiry",errorName:"expiryDate-card",translations:{label:{id:"cardExpiry",defaultMessage:"Expiry Date"},placeholder:{id:"cardExpiryPlaceholder",defaultMessage:"MM/YY"},ariaLabel:{id:"cardExpiry",defaultMessage:"Expiry Date"}}};this.childUpdated()}render(){return this.renderInput()}};ct.styles=[T,Pt,ec],ct=d([b("primer-input-card-expiry"),D()],ct);var tc=f` :host { display: contents; } `;var ut=class extends se{constructor(){super();this.config={inputType:"cardholderName",containerSelector:"#cardFormName",errorName:"cardholderName",translations:{label:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"},placeholder:{id:"cardholderNamePlaceholder",defaultMessage:"Name on card"},ariaLabel:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"}},onInput:e=>this.handleInput(e)};this.childUpdated()}handleInput(e){this.cardFormContext?.setCardholderName?.(e)}render(){return this.renderInput()}};ut.styles=[T,Pt,tc],ut=d([b("primer-input-card-holder-name"),D()],ut);var rc=f` :host { display: contents; } `;var pe=class extends v{constructor(){super(...arguments);this._userAssignedProps=new Set;this._internalButtonText="";this.cardFormContext=null;this.variant="primary";this.disabled=!1;this.handleClick=e=>{if(e.preventDefault(),this.disabled)return;Q({eventName:"PAYMENT_SUBMITTED",paymentMethod:"PAYMENT_CARD"});let r=new CustomEvent("primer:card-submit",{bubbles:!0,composed:!0,detail:{source:"primer-card-form-submit"}});this.dispatchEvent(r)}}get buttonText(){return this._userAssignedProps.has("buttonText")?this._internalButtonText:E("pay",{id:"pay"})}set buttonText(e){let r=this.buttonText;e!==""?(this._userAssignedProps.add("buttonText"),this._internalButtonText=e):(this._userAssignedProps.delete("buttonText"),this._internalButtonText=""),this.requestUpdate("buttonText",r)}get submitButtonConfig(){return this.primerContext?.clientOptions?.submitButton??null}get shouldShowBuiltInButton(){return this.submitButtonConfig?.useBuiltInButton??!0}render(){if(!this.shouldShowBuiltInButton)return y;let e=this.submitButtonConfig?.amountVisible?this.primerContext?.headlessUtils?.getUIOrderAmount():null,r=e?` ${e}`:y,i=this.disabled||this.cardFormContext?.disabled||!1;return u`<primer-button type="submit" variant=${this.variant} ?disabled=${i} @click=${this.handleClick} .loading=${!!this.primerContext?.sdkState?.isProcessing} data-submit >${this.buttonText}${r}</primer-button>`}};pe.styles=[T,rc],d([h({type:String})],pe.prototype,"buttonText",1),d([G({context:dr,subscribe:!0}),h()],pe.prototype,"cardFormContext",2),d([G({context:K,subscribe:!0}),h({attribute:!1})],pe.prototype,"primerContext",2),d([h({type:String})],pe.prototype,"variant",2),d([h({type:Boolean})],pe.prototype,"disabled",2),pe=d([b("primer-card-form-submit"),D()],pe);var ac=f` :host { display: flex; align-items: center; position: relative; height: var(--primer-typography-body-large-line-height); } .network-selector { display: flex; align-items: center; cursor: pointer; background: none; padding: unset; border: none; transition: opacity var(--primer-animation-duration) var(--primer-animation-easing); outline: none; gap: var(--primer-space-xsmall); } .network-selector:hover { opacity: 0.8; } .network-selector.static { cursor: default; } .network-selector.static:hover { opacity: 1; } .network-selector:focus-visible { outline: 2px solid var(--primer-color-focus); border-radius: var(--primer-radius-xsmall); } .network-selector-inline { display: flex; border: 1px solid var(--primer-color-border-outlined-default); border-radius: var(--primer-radius-small); padding: 1px; .network-icon-container { padding: var(--primer-space-xsmall); } .network-icon-container + .network-icon-container { border-left: 1px solid var(--primer-color-border-outlined-default); } } .network-icon { display: block; width: calc(var(--primer-size-medium) * 1.4); height: var(--primer-size-medium); object-fit: contain; margin: 0; svg { width: auto; height: 100%; } } .caret { margin-left: var(--primer-space-xsmall); transition: transform var(--primer-animation-duration) var(--primer-animation-easing); color: var(--primer-color-icon-primary); } .caret.open { transform: rotate(180deg); } .dropdown { position: absolute; top: 100%; right: 0; width: max-content; min-width: calc(var(--primer-size-xxxlarge) * 3); background: var(--primer-color-gray-000); border-radius: var(--primer-radius-small); box-shadow: 0 var(--primer-space-xxsmall) var(--primer-space-large) rgba(0, 0, 0, 0.15); z-index: 10; overflow: hidden; border: 1px solid var(--primer-color-border-outlined-default); } .dropdown:not(.open) { display: none; } .dropdown.open { display: block; max-height: calc(var(--primer-size-xxxlarge) * 4); overflow-y: auto; } .network-option { display: flex; align-items: center; padding: var(--primer-space-small) var(--primer-space-medium); cursor: pointer; transition: background-color var(--primer-animation-duration) var(--primer-animation-easing); position: relative; outline: none; background-color: transparent; } /* Only apply hover effect when not in keyboard navigation mode */ .network-option:hover { background-color: var(--primer-color-gray-100); } /* Apply focused style only when the focused class is present (keyboard navigation) */ .network-option.focused { background-color: var(--primer-color-gray-100); } .network-option:focus-visible { outline: 2px solid var(--primer-color-focus); outline-offset: -2px; } .network-option-icon { width: var(--primer-size-medium); height: var(--primer-size-small); margin-right: var(--primer-space-small); object-fit: contain; } .network-name { font-size: var(--primer-typography-body-medium-size); font-family: var(--primer-typography-body-medium-font); line-height: var(--primer-typography-body-medium-line-height); letter-spacing: var(--primer-typography-body-medium-letter-spacing); white-space: nowrap; color: var(--primer-color-text-primary); flex: 1; } .checkmark { margin-left: var(--primer-space-small); color: var(--primer-color-brand); width: var(--primer-size-small); height: var(--primer-size-small); } `;var cy=bi(Pc()),uy=bi(Hr());var ly=bi(Hr());var Nc=[["AMEX","american-express"],["CARTES_BANCAIRES"],["DANKORT"],["DINERS_CLUB","diners-club"],["DISCOVER","discover"],["ENROUTE"],["ELO","elo"],["EFTPOS"],["HIPER","hiper","hiper-pay"],["HIPERCARD","hipercard"],["INTERAC"],["JCB","jcb"],["MAESTRO","maestro"],["MASTERCARD","mastercard"],["MIR","mir","mir-pay"],["OTHER",void 0,"payment-card"],["UNIONPAY","unionpay"],["VISA","visa"]],px=new Map(Nc.map(a=>[a[0],a])),mx=new Map(Nc.filter(a=>a[1]).map(a=>[a[1],a]));var py={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"};var Px=Object.values(py);var my=["EFTPOS"];function Ic(a){return!a.some(t=>my.includes(t))}var me=class extends v{constructor(){super(...arguments);this.selectedCardNetwork=null;this.isDropdownOpen=!1;this.focusedNetworkIndex=0;this.isKeyboardNavigation=!1;this.buttonRef=Ht();this.dropdownRef=Ht();this.networkOptionRefs=[];this.toggleDropdown=e=>{this.isKeyboardNavigation=!1,e.stopPropagation(),this.getSelectableNetworks().length>1&&(this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))};this.handleClickOutside=e=>{this.isDropdownOpen&&(this.contains(e.target)||(this.isDropdownOpen=!1,this.isKeyboardNavigation=!1))};this.handleMouseMove=()=>{this.isKeyboardNavigation&&(this.isKeyboardNavigation=!1)};this.handleKeyDown=e=>{if(!(!(this.getSelectableNetworks().length>1)||!(this.contains(e.target)||this===e.target||this.isDropdownOpen&&e.target===document.body)))switch(this.isKeyboardNavigation=!0,e.key){case"ArrowDown":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex+1)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"ArrowUp":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex-1+this.getSelectableNetworks().length)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Enter":case" ":this.isDropdownOpen&&this.focusedNetworkIndex>=0?(e.preventDefault(),this.selectNetwork(e,this.getSelectableNetworks()[this.focusedNetworkIndex])):!this.isDropdownOpen&&this.buttonRef.value===document.activeElement&&(e.preventDefault(),this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Escape":this.isDropdownOpen&&(e.preventDefault(),this.isDropdownOpen=!1,this.buttonRef.value?.focus());break;case"Tab":this.isDropdownOpen&&(this.isDropdownOpen=!1);break}};this.handleDocumentKeyDown=e=>{this.isDropdownOpen&&this.handleKeyDown(e)}}getNetworkIconUrl(e){return this.primerContext?.headlessUtils?.getCardNetworkAsset(e.network)?.cardUrl}renderDefaultCardIcon(){return u`<div class="network-icon">${$a["payment-card"]}</div>`}getSelectableNetworks(){return this.primerContext?.cardNetworks?.selectableCardNetworks||[]}getDetectedNetwork(){return this.selectedCardNetwork??(this.primerContext?.cardNetworks?.detectedCardNetwork||null)}getSelectedNetworkIndex(){let e=this.getDetectedNetwork();if(!e)return 0;let r=this.getSelectableNetworks().findIndex(i=>i.network===e.network);return r>=0?r:0}selectNetwork(e,r){e.stopPropagation(),this.selectedCardNetwork=r,this.isDropdownOpen=!1,this.buttonRef.value?.focus(),this.primerContext?.cardNetworks&&this.dispatchEvent(new CustomEvent("network-selected",{detail:{network:r.network},bubbles:!0,composed:!0}))}focusNetworkOption(){requestAnimationFrame(()=>{this.networkOptionRefs[this.focusedNetworkIndex]&&this.networkOptionRefs[this.focusedNetworkIndex].focus()})}setNetworkOptionRef(e,r){this.networkOptionRefs[r]=e}connectedCallback(){super.connectedCallback(),setTimeout(()=>{document.addEventListener("click",this.handleClickOutside),document.addEventListener("mousemove",this.handleMouseMove),this.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keydown",this.handleDocumentKeyDown)},0)}disconnectedCallback(){document.removeEventListener("click",this.handleClickOutside),document.removeEventListener("keydown",this.handleDocumentKeyDown),document.removeEventListener("mousemove",this.handleMouseMove),this.removeEventListener("keydown",this.handleKeyDown),super.disconnectedCallback()}render(){if(this.primerContext?.cardNetworks?.isLoading)return u`<primer-spinner size="small" compact></primer-spinner>`;let e=this.getSelectableNetworks();if(!this.getDetectedNetwork()&&e.length===0)return this.renderDefaultCardIcon();let r=this.getDetectedNetwork()||(e.length>0?e[0]:null);if(!r)return this.renderDefaultCardIcon();let i=e.length>1;return i&&!Ic(e.map(o=>o.network))?u`<div class="network-selector-inline">${e.map(o=>u`<div class="network-icon-container"><img class="network-icon" src=${this.getNetworkIconUrl(o)??""} alt=${o.displayName} /></div>`)}</div>`:u`<button ${Et(this.buttonRef)} class="network-selector ${i?"":"static"}" tabindex=${i?"0":"-1"} @click=${this.toggleDropdown} @keydown=${o=>{(o.key===" "||o.key==="Enter")&&i&&(o.preventDefault(),this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))}} aria-label=${i?`Selected card network: ${r.displayName}. Click to change.`:`Card network: ${r.displayName}`} aria-expanded=${i?this.isDropdownOpen:y} aria-haspopup=${i?"true":y} aria-controls=${i?"network-dropdown":y} ><img class="network-icon" src=${this.getNetworkIconUrl(r)} alt=${r.displayName} />${k(i,()=>u`<primer-icon class="caret ${this.isDropdownOpen?"open":""}" size="sm" name="chevron-down" ></primer-icon>`,()=>y)}</button>${k(this.isDropdownOpen,()=>u`<div ${Et(this.dropdownRef)} id="network-dropdown" class="dropdown open" role="listbox" aria-label="Select card network" >${e.map((o,s)=>u`<div ${Et(l=>this.setNetworkOptionRef(l,s))} class="network-option ${this.isKeyboardNavigation&&s===this.focusedNetworkIndex?"focused":""}" @click=${l=>this.selectNetwork(l,o)} @keydown=${l=>{(l.key==="Enter"||l.key===" ")&&this.selectNetwork(l,o)}} role="option" aria-selected=${o.network===r.network} tabindex="${s===this.focusedNetworkIndex?"0":"-1"}" ><img class="network-option-icon" src=${this.getNetworkIconUrl(o)} alt=${o.displayName} /><span class="network-name">${o.displayName}</span>${k(o.network===r.network,()=>u`<primer-icon class="checkmark" name="checkmark" size="sm" ></primer-icon>`,()=>y)}</div>`)}</div>`,()=>y)} `}};me.styles=[T,ac],d([G({context:K,subscribe:!0}),h({attribute:!1})],me.prototype,"primerContext",2),d([N()],me.prototype,"selectedCardNetwork",2),d([N()],me.prototype,"isDropdownOpen",2),d([N()],me.prototype,"focusedNetworkIndex",2),d([N()],me.prototype,"isKeyboardNavigation",2),me=d([b("primer-card-network-selector")],me);var kc=f` :host { display: block; margin-top: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .other-payment-methods-container { width: 100%; } .other-payment-methods-content { padding: var(--primer-space-medium) 0; } .primer-loader { display: flex; justify-content: center; align-items: center; } /* Collapsable animation for slotted toggle button */ .collapsable-wrapper { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--primer-animation-duration) var(--primer-animation-easing); overflow: hidden; } .collapsable-wrapper.expanded { grid-template-rows: 1fr; } .collapsable-content { min-height: 0; } `;var _e=class extends v{constructor(){super(...arguments);this.hasSlottedToggle=!1;this.isExpanded=!1;this._isHandlingContextEvent=!1;this._contextToggleListener=null;this.handleToggleSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasSlottedToggle=i.length>0};this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isToggleButton(n)&&(e.preventDefault(),this.toggleAccordion())};this.handleDirectToggle=e=>{let r=e.detail?.action;r==="expand"?this.expand():r==="collapse"?this.collapse():this.toggleAccordion()};this.handleContextToggle=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{if(e.target!==this){e.stopPropagation();let r=e.detail?.action;r==="expand"?this.expand():r==="collapse"?this.collapse():this.toggleAccordion()}}finally{this._isHandlingContextEvent=!1}}}}isToggleButton(e){let r=this.shadowRoot?.querySelector('slot[name="show-other-payments-toggle-button"]');return r?r.assignedElements({flatten:!0}).some(n=>n===e||n.contains(e)):!1}toggleAccordion(){this.hasSlottedToggle?(this.isExpanded=!this.isExpanded,this.dispatchExpandedEvent(this.isExpanded)):this.collapsableElement&&(this.collapsableElement.isExpanded?this.collapsableElement.collapse():this.collapsableElement.expand())}dispatchExpandedEvent(e){this.dispatchEvent(new CustomEvent("primer:show-other-payments-toggled",{bubbles:!0,composed:!0,detail:{expanded:e}}))}expand(){this.hasSlottedToggle?this.isExpanded||(this.isExpanded=!0,this.dispatchExpandedEvent(!0)):this.collapsableElement?.expand()}collapse(){this.hasSlottedToggle?this.isExpanded&&(this.isExpanded=!1,this.dispatchExpandedEvent(!1)):this.collapsableElement?.collapse()}setupContextEventListeners(){this.primerContext?.events?.host&&this._contextToggleListener&&this.primerContext?.events.host.addEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}cleanupContextEventListeners(){this.primerContext?.events?.host&&this._contextToggleListener&&this.primerContext?.events.host.removeEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}connectedCallback(){super.connectedCallback(),this.isExpanded=this.primerContext?.vaultManager?.vaultedPaymentMethods.length===0,this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this._contextToggleListener=e=>{this.handleContextToggle(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this.cleanupContextEventListeners(),super.disconnectedCallback()}render(){if(this.primerContext?.vaultManager?.isLoading)return y;let e=this.primerContext?.vaultManager?.showEmptyState||this.primerContext?.vaultManager?.vaultedPaymentMethods.length;return!this.primerContext?.vaultManager||!this.primerContext?.vaultManager.enabled||this.primerContext?.vaultManager.headless||!e?u`<slot name="other-payments"></slot>`:u`<div class="other-payment-methods-container"><slot name="show-other-payments-toggle-button" @slotchange=${this.handleToggleSlotChange} ></slot>${k(!this.hasSlottedToggle,()=>u`<primer-collapsable buttonVariant="secondary" .expanded="${this.primerContext?.vaultManager?.vaultedPaymentMethods.length===0}" .header="${E("navigateToPaymentMethods",{id:"navigateToPaymentMethods"})}" ><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></primer-collapsable>`,()=>u`<div class="collapsable-wrapper ${this.isExpanded?"expanded":""}" role="region" aria-labelledby="custom-toggle-button" ><div class="collapsable-content"><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></div></div>`)}</div>`}};_e.styles=[kc],d([G({context:K,subscribe:!0}),h({attribute:!1})],_e.prototype,"primerContext",2),d([de("primer-collapsable")],_e.prototype,"collapsableElement",2),d([N()],_e.prototype,"hasSlottedToggle",2),d([N()],_e.prototype,"isExpanded",2),_e=d([b("primer-show-other-payments")],_e);var Lc=f` :host { display: flex; width: 100%; } .container { width: 100%; display: flex; flex-direction: column; transition: all var(--primer-animation-duration) var(--primer-animation-easing); } .container.expanded { border-radius: var(--primer-radius-medium); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); background-color: var(--primer-color-background-outlined-default); border: 1px solid var(--primer-color-border-outlined-default); padding: var(--primer-space-large); } .expanded-content { width: 100%; display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--primer-animation-duration) var(--primer-animation-easing); overflow: hidden; } .container.expanded .expanded-content { grid-template-rows: 1fr; } .content-wrapper { overflow: hidden; } :host([disabled]) { opacity: 0.6; cursor: not-allowed; } `;var Oe=class extends v{constructor(){super(...arguments);this.disabled=!1;this.expanded=!1;this.suppressBlurCollapse=!1;this._handleDocumentClick=e=>{this.expanded&&(this.suppressBlurCollapse||e.composedPath().includes(this)||this._collapseFromOutsideInteraction())};this._handleWindowBlur=()=>{!this.expanded||this.suppressBlurCollapse||setTimeout(()=>{document.hasFocus()&&this._collapseFromOutsideInteraction()},100)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this._handleDocumentClick),window.addEventListener("blur",this._handleWindowBlur)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("click",this._handleDocumentClick),window.removeEventListener("blur",this._handleWindowBlur)}_collapseFromOutsideInteraction(){this.expanded&&(this.expanded=!1,this.dispatchEvent(new CustomEvent("expanded-change",{detail:{expanded:!1},bubbles:!0,composed:!0})))}_handleButtonClick(){this.disabled||(this.expanded=!this.expanded,this.dispatchEvent(new CustomEvent("expanded-change",{detail:{expanded:this.expanded},bubbles:!0,composed:!0})))}render(){return u`<div class="container ${this.expanded?"expanded":""}"><primer-payment-method-button .type=${this.type} ?disabled=${this.disabled} @payment-method-click=${()=>this._handleButtonClick()} ></primer-payment-method-button><div class="expanded-content"><div class="content-wrapper"><slot></slot></div></div></div>`}};Oe.styles=[T,Lc],d([h({type:String})],Oe.prototype,"type",2),d([h({type:Boolean,attribute:"disabled"})],Oe.prototype,"disabled",2),d([h({type:Boolean,reflect:!0})],Oe.prototype,"expanded",2),d([h({type:Boolean,attribute:"suppress-blur-collapse"})],Oe.prototype,"suppressBlurCollapse",2),Oe=d([b("primer-payment-method-accordion")],Oe);var Rc=f` :host { display: block; width: 100%; } button { padding: var(--primer-space-medium) var(--primer-space-large); display: flex; align-items: center; justify-content: center; border-radius: var(--primer-radius-small); background-color: var(--primer-color-brand); color: var(--primer-color-background-outlined-default); border: none; font-family: var(--primer-typography-body-medium-font); font-size: var(--primer-typography-body-medium-size); font-weight: var(--primer-typography-body-medium-weight); width: 100%; cursor: pointer; transition: all var(--primer-animation-duration) var(--primer-animation-easing); } button:hover:not(:disabled) { filter: brightness(105%); } button:disabled { background-color: var(--primer-color-background-outlined-disabled); border-color: var(--primer-color-border-outlined-disabled); color: var(--primer-color-text-disabled); cursor: not-allowed; } button.loading { opacity: 0.7; pointer-events: none; } `;var pt=class extends v{constructor(){super(...arguments);this.disabled=!1;this.loading=!1}render(){return u`<button class=${X({loading:this.loading})} ?disabled=${this.disabled||this.loading} @click=${()=>this.dispatchEvent(new Event("confirm",{bubbles:!0,composed:!0}))} >${this.loading?u`<primer-spinner size="small" compact></primer-spinner>`:E("confirm",{id:"confirm"})}</button>`}};pt.styles=[T,Rc],d([h({type:Boolean})],pt.prototype,"disabled",2),d([h({type:Boolean})],pt.prototype,"loading",2),pt=d([b("primer-payment-method-accordion-confirm-button"),D()],pt);var pr=class extends v{render(){return u`<primer-checkout-state type="complete"></primer-checkout-state>`}};pr=d([b("primer-checkout-complete")],pr);var zt=class extends v{render(){return u`<primer-checkout-state type="failure" description=${this.primerContext?.sdkState?.primerJsError?.message||""} ></primer-checkout-state>`}};d([G({context:K,subscribe:!0}),h({attribute:!1})],zt.prototype,"primerContext",2),zt=d([b("primer-checkout-error")],zt);var wc=f` :host { display: block; width: 100%; } `;var mt=class extends v{constructor(){super(...arguments);this.showProcessingErrors=!0}get shouldShowError(){return!this.primerContext?.sdkState||this.primerContext.sdkState.isProcessing?!1:!!(this.primerContext.sdkState.paymentFailure&&this.showProcessingErrors)}render(){return this.primerContext?.sdkState?u`<primer-error-message message="${E(this.primerContext.sdkState.paymentFailure?.message??"",{id:"tokenizationError"})}" ?visible="${this.shouldShowError}" ></primer-error-message>`:y}};mt.styles=[wc],d([G({context:K,subscribe:!0}),h({attribute:!1})],mt.prototype,"primerContext",2),d([h({type:Boolean,attribute:"show-processing-errors"})],mt.prototype,"showProcessingErrors",2),mt=d([b("primer-error-message-container")],mt);var xc=f` :host { display: contents; } .primer-main-list { display: flex; flex-direction: column; gap: var(--primer-space-small); } .primer-is-processing { opacity: 0.5; pointer-events: none; } primer-vault-manager { margin-bottom: var(--primer-space-xlarge); } `;var kt=class extends v{constructor(){super(...arguments);this.hasAssignedContent=!1;this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()}}render(){return this.primerContext?.sdkState?.isSuccessful?u`<slot name="checkout-complete"><primer-checkout-complete></primer-checkout-complete></slot>`:u`<slot name="payments" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent,()=>y,()=>u`<div class=${X({"primer-is-processing":!!this.primerContext?.sdkState?.isProcessing})} ><primer-vault-manager></primer-vault-manager><primer-show-other-payments><div slot="other-payments" class="primer-main-list">${this.primerContext?.paymentMethods?.map(e=>u`<primer-payment-method type=${e.type} ?disabled=${this.primerContext?.clientOptions?.disabledPayments===!0} ></primer-payment-method>`)}</div></primer-show-other-payments><primer-error-message-container></primer-error-message-container></div>`)} `}};kt.styles=[T,xc],d([G({context:K,subscribe:!0}),h({attribute:!1})],kt.prototype,"primerContext",2),kt=d([b("primer-main")],kt);!1;function QO(){pl(),ml()}export{Te as AdyenMbway,Ve as ApplePay,ne as BillingAddress,be as Blik,ce as Button,Se as CardForm,dt as CardFormCVV,me as CardFormCardNetworkSelector,lt as CardFormCardNumber,it as CardFormError,ct as CardFormExpiry,ut as CardFormName,pe as CardFormSubmit,ue as Collapsable,Re as Dialog,Fe as ErrorMessage,mt as ErrorMessageContainer,Ue as GooglePay,j as Input,at as InputLabel,Ge as InputWrapper,He as PayPal,Ye as PaymentMethod,Oe as PaymentMethodAccordion,pt as PaymentMethodAccordionConfirmButton,$e as PaymentMethodButton,we as PaymentMethodContainer,je as PaymentMethodContentComponent,te as PortalDialog,pr as PrimerCheckoutComplete,ye as PrimerCheckoutComponent,zt as PrimerCheckoutFailure,nt as PrimerCheckoutState,Ke as PrimerIcon,ve as PrimerKlarna,kt as PrimerMain,re as PtPhoneNumberInput,ot as RedirectPayment,fe as Select,_e as ShowOtherPayments,Be as Spinner,ae as VaultCvvInput,Ie as VaultDeleteConfirmation,st as VaultEmptyState,ze as VaultErrorMessage,oe as VaultManager,xe as VaultManagerHeader,Ne as VaultPaymentMethodItem,Ce as VaultPaymentSubmit,ih as injectDarkTheme,ah as injectLightTheme,pl as injectLoaderStyles,ml as injectThemeStyles,QO as loadPrimer};
|
|
243
|
+
`,t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}function Zd(a,t){return a.active!==t.active||a.dirty!==t.dirty||a.error!==t.error||a.errorCode!==t.errorCode||a.submitted!==t.submitted||a.touched!==t.touched||a.valid!==t.valid}var ti=class{constructor(t,e){this._meta={active:!1,dirty:!1,error:null,errorCode:null,submitted:!1,touched:!1,valid:!1};this._hostedInput=null;this._standardInput=null;this.host=t,this.config=e,this.host.addController(this),this.setupTask=new $(this.host,{args:()=>[this.getHostedInput()],task:this.setupHostedInput.bind(this)}),this.host.addEventListener("wrapper-click",()=>{this.focusInput()})}focusInput(){this._hostedInput?this._hostedInput.focus():this._standardInput&&this._standardInput.focus()}notifyUserInteraction(){let t=this.host.cardFormContext;t?.onUserInteraction&&t.onUserInteraction()}getHostedInput(){let{type:t}=this.config,e=this.host.cardFormContext;return e?{cardNumber:e.cardNumberInput,cvv:e.cvvInput,expire:e.expiryInput,cardholderName:e.cardholderNameInput??"cardholderName"}[t]:void 0}async setupHostedInput([t]){if(!t)return Y;await this.host.updateComplete;let e=this.getTargetContainer();return e?t==="cardholderName"?this.setupStandardInput(e):this.setupHostedIframeInput(t,e):Y}getTargetContainer(){return this.host.renderRoot.querySelector(this.config.containerSelector)}setupStandardInput(t){let e=document.createElement("input");return e.type="text",e.placeholder=this.host.placeholder,Hn(e,this.host),(this.host.ariaLabel||this.host.label)&&e.setAttribute("aria-label",this.host.ariaLabel??this.host.label),this.setupInputEventListeners(e),t.innerHTML="",t.appendChild(e),this._standardInput=e,!0}setupInputEventListeners(t){t.addEventListener("input",e=>{let r=e.target,n=!!r.value.trim();this.notifyUserInteraction(),this._meta={...this._meta,dirty:n},this.config.onInput?.(r.value),this.host.requestUpdate()}),t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this._meta.touched=!1,this.host.requestUpdate()}),t.addEventListener("keydown",e=>{if(e.key==="Enter"){e.preventDefault();let r=this.host.closest("form");r&&r.requestSubmit()}})}async setupHostedIframeInput(t,e){await new Promise(n=>requestAnimationFrame(()=>n())),this._hostedInput=t;let r=Fr(this.host.primerContext?.computedStyles??null),i=r?{style:{input:{base:r}}}:void 0;return t.addEventListener("focus",()=>{this.notifyUserInteraction(),this._meta.active=!0,this.host.requestUpdate()}),t.addEventListener("blur",()=>{this._meta.active=!1,this.host.requestUpdate()}),t.addEventListener("change",n=>{let o=n;this.notifyUserInteraction(),Zd(this._meta,o)&&(this._meta={...this._meta,...o},this.host.requestUpdate())}),t.addEventListener("enter",()=>{let n=this.host.closest("form");n&&n.requestSubmit()}),this.host.isConnected?(await t.render(e,{placeholder:this.host.placeholder,ariaLabel:this.host.ariaLabel,...i}),!0):!1}get meta(){return this._meta}updateMetaFromValidation(t){this._meta={...this._meta,valid:!!t.valid,error:t.error||null,errorCode:t.errorCode||null},this.host.requestUpdate()}setSubmitted(t){this._meta={...this._meta,submitted:t,...t&&{touched:!0}},this.host.requestUpdate()}hostConnected(){this.registerWithContext()}hostDisconnected(){this.unregisterFromContext(),this._hostedInput=null,this._standardInput=null}hostUpdate(){if(this._hostedInput?.setOptions){let t=Fr(this.host.primerContext?.computedStyles??null);this._hostedInput.setOptions({placeholder:this.host.placeholder,ariaLabel:this.host.ariaLabel,...t&&{style:{input:{base:t}}}})}else this._standardInput&&this.host.primerContext?.computedStyles&&Hn(this._standardInput,this.host)}registerWithContext(){let t=this.host.cardFormContext;t?.registerInputController&&t.registerInputController(this.config.type,this)}unregisterFromContext(){let t=this.host.cardFormContext;t?.unregisterInputController&&t.unregisterInputController(this.config.type)}};var Jd=f` :host { display: contents; } form { display: flex; flex-direction: column; gap: var(--primer-space-medium); width: 100%; } .card-form { display: flex; flex-direction: column; gap: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .card-form-row { display: flex; gap: var(--primer-space-small); } `;var qd={cardholderName:"cardholderName",cardNumber:"cardNumber",cardExpiryDate:"expire",expiryDate:"expire",cardSecurityCode:"cvv",cvv:"cvv"},Se=class extends v{constructor(){super(...arguments);this.hideLabels=!1;this.disabled=!1;this.hasAssignedContent=!1;this.selectedCardNetwork=null;this.formErrorMessage=null;this.paymentMethodSelectionSent=!1;this.cardFormProvider=new yt(this,{context:dr,initialValue:null});this.eventsController=new er(this);this._contextCardSubmitListener=null;this._isHandlingContextEvent=!1;this.inputControllers=new Map;this.setupCardFormTask=new $(this,{task:([e])=>{let r=e?.find(l=>l.type===W.PAYMENT_CARD)?.manager;if(!r)return Y;let i=r.createHostedInputs(),{cardNumberInput:n,expiryInput:o,cvvInput:s}=i;return this.cardFormProvider.setValue({cardholderNameInput:i.cardholderNameInput,cardNumberInput:n,expiryInput:o,cvvInput:s,setCardholderName:l=>{r.setCardholderName(l),this.shouldRequireCardholderName&&r.validate?.().then(c=>{let m=c?.validationErrors?.find(A=>A.name===qd.cardholderName),g=this.inputControllers.get("cardholderName");g&&g.updateMetaFromValidation({valid:!1,error:m?.message||m?.error||null,errorCode:m?.message||m?.error||null})})},setCardNetwork:l=>{this.selectedCardNetwork=l},validate:()=>r.validate(),submit:l=>r.submit(l),hideLabels:this.hideLabels,disabled:this.disabled,setSubmissionState:l=>{this.inputControllers.forEach(c=>{c.setSubmitted(l)})},propagateValidationErrors:l=>{l&&l.forEach(c=>{let p=c.field||c.name,m=c.message||c.error,g=qd[p];if(g){let A=this.inputControllers.get(g);if(A){let M={valid:!1,error:m,errorCode:m};A.updateMetaFromValidation(M)}}})},registerInputController:(l,c)=>{this.inputControllers.set(l,c)},unregisterInputController:l=>{this.inputControllers.delete(l)},onUserInteraction:()=>{this.sendPaymentMethodSelectionEvent(),this.checkAndSendPaymentDetailsEnteredEvent()}}),!0},args:()=>[this.primerContext?.paymentMethods]});this.paymentDetailsEnteredSent=!1;this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isSubmitButton(n)&&(e.preventDefault(),this.submitCardPayment())};this.handleDirectSubmit=e=>{e.stopPropagation(),this.submitCardPayment()};this.handleContextCardSubmit=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{e.target!==this&&(e.stopPropagation(),this.submitCardPayment())}finally{this._isHandlingContextEvent=!1}}};this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0};this.handleFormSubmit=e=>{e.preventDefault(),e.stopPropagation(),this.submitCardPayment()}}updated(e){if(super.updated(e),(e.has("hideLabels")||e.has("disabled"))&&this.cardFormProvider.value&&this.cardFormProvider.setValue({...this.cardFormProvider.value,hideLabels:this.hideLabels,disabled:this.disabled}),e.has("context")){let i=e.get("context")?.events??null;i?.host&&this._contextCardSubmitListener&&i.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener),this.setupContextEventListeners()}}get shouldShowCardholderName(){let e=this.primerContext?.clientOptions?.card?.cardholderName;return typeof e?.visible=="boolean"?e.visible:!0}get shouldRequireCardholderName(){if(!this.shouldShowCardholderName)return!1;let e=this.primerContext?.clientOptions?.card?.cardholderName;return typeof e?.required=="boolean"?e.required:!0}sendPaymentMethodSelectionEvent(){this.paymentMethodSelectionSent||(this.paymentMethodSelectionSent=!0,Q({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYMENT_CARD"}))}checkAndSendPaymentDetailsEnteredEvent(){if(this.paymentDetailsEnteredSent)return;let e=this.inputControllers.get("cardNumber"),r=this.inputControllers.get("expire"),i=this.inputControllers.get("cvv"),n=e?.meta?.dirty===!0,o=r?.meta?.dirty===!0,s=i?.meta?.dirty===!0,l=!0;this.shouldRequireCardholderName&&(l=this.inputControllers.get("cardholderName")?.meta?.dirty===!0),n&&o&&s&&l&&(this.sendPaymentDetailsEnteredEvent(),this.paymentDetailsEnteredSent=!0)}sendPaymentDetailsEnteredEvent(){Q({eventName:"PAYMENT_DETAILS_ENTERED",paymentMethod:"PAYMENT_CARD"})}connectedCallback(){super.connectedCallback(),this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:card-submit",this.handleDirectSubmit),this._contextCardSubmitListener=e=>{this.handleContextCardSubmit(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:card-submit",this.handleDirectSubmit),this.cleanupContextEventListeners(),super.disconnectedCallback()}setupContextEventListeners(){this.primerContext?.events?.host&&this._contextCardSubmitListener&&this.primerContext?.events.host.addEventListener("primer:card-submit",this._contextCardSubmitListener)}cleanupContextEventListeners(){this.primerContext?.events?.host&&this._contextCardSubmitListener&&this.primerContext?.events.host.removeEventListener("primer:card-submit",this._contextCardSubmitListener)}isSubmitButton(e){let r=e.tagName.toLowerCase(),i=r==="button",n=r==="primer-button";return i&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))||n&&(e.getAttribute("type")==="submit"||e.hasAttribute("data-submit"))}async submitCardPayment(){let e=this.cardFormProvider.value;if(!e||this.disabled)return;this.formErrorMessage=null,e.setSubmissionState?.(!0);let r=this.querySelector("primer-billing-address")||this.renderRoot.querySelector("primer-billing-address"),i=!0;r&&(i=await r.validateForSubmission());let n=await e.validate?.();if(n?.valid&&i){if(r&&!await r.submitToSDK()){let c=E("tokenizationError",{id:"tokenizationError"});this.formErrorMessage=c,this.eventsController.dispatchFormSubmitErrors([{field:"billingAddress",name:"billingAddress",error:"BILLING_ADDRESS_SUBMISSION_FAILED",message:c}]);return}let o={success:!0};this.eventsController.dispatchFormSubmitSuccess(o);let s=this.selectedCardNetwork?{cardNetwork:this.selectedCardNetwork}:void 0;await e.submit?.(s)}else{let o=n?.validationErrors;e.propagateValidationErrors?.(o||[]),this.cardFormProvider.setValue({...e,errors:o}),this.eventsController.dispatchFormSubmitErrors(o)}}render(){return this.setupCardFormTask.status===bt.ERROR||this.setupCardFormTask.status===bt.INITIAL?y:u`<form @submit=${this.handleFormSubmit}><slot name="card-form-content" @slotchange=${this.onSlotChange}></slot>${this.setupCardFormTask.render({complete:()=>k(this.hasAssignedContent,()=>y,()=>u`<div class="card-form"><primer-input-card-number></primer-input-card-number><div class="card-form-row"><primer-input-card-expiry></primer-input-card-expiry><primer-input-cvv></primer-input-cvv></div>${k(this.shouldShowCardholderName,()=>u`<primer-input-card-holder-name></primer-input-card-holder-name>`,()=>y)} ${k(this.primerContext?.clientOptions?.sdkCore!==!1,()=>u`<primer-billing-address></primer-billing-address>`,()=>y)}</div><primer-card-form-submit></primer-card-form-submit><primer-error-message message="${this.formErrorMessage||""}" ?visible="${!!this.formErrorMessage}" ></primer-error-message>`)})}</form>`}};Se.styles=[T,Jd],d([h({type:Boolean,attribute:"hide-labels",reflect:!0})],Se.prototype,"hideLabels",2),d([h({type:Boolean,attribute:"disabled"})],Se.prototype,"disabled",2),d([N()],Se.prototype,"hasAssignedContent",2),d([N()],Se.prototype,"selectedCardNetwork",2),d([N()],Se.prototype,"formErrorMessage",2),d([G({context:K,subscribe:!0}),h({attribute:!1})],Se.prototype,"primerContext",2),Se=d([b("primer-card-form"),D()],Se);var se=class extends v{constructor(){super();this._cardFormContext=null;this._userAssignedProps=new Set;this._internalLabel="";this._internalPlaceholder="";this._internalAriaLabel="";this.handleWrapperClick=()=>{this.hostedInputController.focusInput()};this.hostedInputController={}}get cardFormContext(){return this._cardFormContext}set cardFormContext(e){let r=this._cardFormContext;this._cardFormContext=e,!r&&e&&this.updateComplete.then(()=>{this.hostedInputController?.registerWithContext?.()}),this.requestUpdate("cardFormContext",r)}getTranslatedValue(e){return e?typeof e=="string"?e:E(e.id,{id:e.id}):""}get label(){return this._userAssignedProps.has("label")?this._internalLabel:this.getTranslatedValue(this.config.translations.label)}set label(e){let r=this.label;e!==""?(this._userAssignedProps.add("label"),this._internalLabel=e):(this._userAssignedProps.delete("label"),this._internalLabel=""),this.requestUpdate("label",r)}get placeholder(){return this._userAssignedProps.has("placeholder")?this._internalPlaceholder:this.getTranslatedValue(this.config.translations.placeholder)}set placeholder(e){let r=this.placeholder;this._userAssignedProps.add("placeholder"),this._internalPlaceholder=e,this.requestUpdate("placeholder",r)}get ariaLabel(){return this._userAssignedProps.has("ariaLabel")?this._internalAriaLabel:this.getTranslatedValue(this.config.translations.ariaLabel)||this.getTranslatedValue(this.config.translations.label)}set ariaLabel(e){let r=this.ariaLabel;e!==""?(this._userAssignedProps.add("ariaLabel"),this._internalAriaLabel=e):(this._userAssignedProps.delete("ariaLabel"),this._internalAriaLabel=""),this.requestUpdate("ariaLabel",r)}childUpdated(){Object.defineProperty(this,"hostedInputController",{value:new ti(this,{type:this.config.inputType,containerSelector:this.config.containerSelector,onInput:this.config.onInput}),writable:!1,configurable:!1})}getError(){let e=this.hostedInputController.meta;return e.submitted||e.dirty&&e.touched?e.errorCode:null}renderInput(){if(this.hostedInputController.setupTask.status===bt.ERROR)return y;let e=this.getError();return u`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} @wrapper-click="${this.handleWrapperClick}" >${k(!this.cardFormContext?.hideLabels,()=>u`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>y)}<div slot="input" class="card-input-slot" id="${this.config.containerSelector.substring(1)}" aria-label="${this.ariaLabel}" ></div>${k(e,()=>u`<primer-input-error slot="error">${E(e,{id:e})}</primer-input-error>`,()=>y)}</primer-input-wrapper>`}};d([G({context:dr,subscribe:!0})],se.prototype,"cardFormContext",1),d([G({context:K,subscribe:!0}),h({attribute:!1})],se.prototype,"primerContext",2),d([h({type:String})],se.prototype,"label",1),d([h({type:String})],se.prototype,"placeholder",1),d([h({type:String,attribute:"aria-label"})],se.prototype,"ariaLabel",1);var Qd=f` :host { display: contents; } .card-number-container { display: flex; align-items: center; width: 100%; position: relative; gap: var(--primer-space-small); } #cardNumber { flex: 1; display: flex; width: 100%; } .network-selector-container { display: flex; align-items: center; z-index: 2; } `;var Pt=f` .card-input-slot { display: flex; } `;var lt=class extends se{constructor(){super();this.config={inputType:"cardNumber",containerSelector:"#cardNumber",errorName:"cardNumber-card",translations:{label:{id:"cardNumber",defaultMessage:"Card Number"},placeholder:"4111 1111 1111 1111",ariaLabel:{id:"cardNumber",defaultMessage:"Card Number"}}};this.handleNetworkSelected=e=>{let{network:r}=e.detail;this.cardFormContext&&this.cardFormContext.setCardNetwork(r)};this.childUpdated()}renderInput(){if(this.hostedInputController.setupTask.status===bt.ERROR)return y;let e=this.getError();return u`<primer-input-wrapper .focusWithin="${this.hostedInputController.meta.active}" .hasError=${!!e} >${k(!this.cardFormContext?.hideLabels,()=>u`<primer-input-label slot="label" >${this.label}</primer-input-label >`,()=>y)}<div slot="input" class="card-number-container" aria-label="${this.ariaLabel}" ><div id="${this.config.containerSelector.substring(1)}"></div><div class="network-selector-container"><primer-card-network-selector @network-selected=${this.handleNetworkSelected} ></primer-card-network-selector></div></div>${k(e,r=>u`<primer-input-error slot="error">${E(r,{id:r})}</primer-input-error>`,()=>y)}</primer-input-wrapper>`}render(){return this.renderInput()}};lt.styles=[T,Pt,Qd],lt=d([b("primer-input-card-number"),D()],lt);var Xd=f` :host { display: contents; } `;var dt=class extends se{constructor(){super();this.config={inputType:"cvv",containerSelector:"#cvv",errorName:"cvv-card",translations:{label:"CVV",placeholder:"123"}};this.childUpdated()}render(){return this.renderInput()}};dt.styles=[T,Pt,Xd],dt=d([b("primer-input-cvv"),D()],dt);var ec=f` :host { display: contents; } `;var ct=class extends se{constructor(){super();this.config={inputType:"expire",containerSelector:"#expiry",errorName:"expiryDate-card",translations:{label:{id:"cardExpiry",defaultMessage:"Expiry Date"},placeholder:{id:"cardExpiryPlaceholder",defaultMessage:"MM/YY"},ariaLabel:{id:"cardExpiry",defaultMessage:"Expiry Date"}}};this.childUpdated()}render(){return this.renderInput()}};ct.styles=[T,Pt,ec],ct=d([b("primer-input-card-expiry"),D()],ct);var tc=f` :host { display: contents; } `;var ut=class extends se{constructor(){super();this.config={inputType:"cardholderName",containerSelector:"#cardFormName",errorName:"cardholderName",translations:{label:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"},placeholder:{id:"cardholderNamePlaceholder",defaultMessage:"Name on card"},ariaLabel:{id:"cardholderNameLabel",defaultMessage:"Cardholder Name"}},onInput:e=>this.handleInput(e)};this.childUpdated()}handleInput(e){this.cardFormContext?.setCardholderName?.(e)}render(){return this.renderInput()}};ut.styles=[T,Pt,tc],ut=d([b("primer-input-card-holder-name"),D()],ut);var rc=f` :host { display: contents; } `;var pe=class extends v{constructor(){super(...arguments);this._userAssignedProps=new Set;this._internalButtonText="";this.cardFormContext=null;this.variant="primary";this.disabled=!1;this.handleClick=e=>{if(e.preventDefault(),this.disabled)return;Q({eventName:"PAYMENT_SUBMITTED",paymentMethod:"PAYMENT_CARD"});let r=new CustomEvent("primer:card-submit",{bubbles:!0,composed:!0,detail:{source:"primer-card-form-submit"}});this.dispatchEvent(r)}}get buttonText(){return this._userAssignedProps.has("buttonText")?this._internalButtonText:E("pay",{id:"pay"})}set buttonText(e){let r=this.buttonText;e!==""?(this._userAssignedProps.add("buttonText"),this._internalButtonText=e):(this._userAssignedProps.delete("buttonText"),this._internalButtonText=""),this.requestUpdate("buttonText",r)}get submitButtonConfig(){return this.primerContext?.clientOptions?.submitButton??null}get shouldShowBuiltInButton(){return this.submitButtonConfig?.useBuiltInButton??!0}render(){if(!this.shouldShowBuiltInButton)return y;let e=this.submitButtonConfig?.amountVisible?this.primerContext?.headlessUtils?.getUIOrderAmount():null,r=e?` ${e}`:y,i=this.disabled||this.cardFormContext?.disabled||!1;return u`<primer-button type="submit" variant=${this.variant} ?disabled=${i} @click=${this.handleClick} .loading=${!!this.primerContext?.sdkState?.isProcessing} data-submit >${this.buttonText}${r}</primer-button>`}};pe.styles=[T,rc],d([h({type:String})],pe.prototype,"buttonText",1),d([G({context:dr,subscribe:!0}),h()],pe.prototype,"cardFormContext",2),d([G({context:K,subscribe:!0}),h({attribute:!1})],pe.prototype,"primerContext",2),d([h({type:String})],pe.prototype,"variant",2),d([h({type:Boolean})],pe.prototype,"disabled",2),pe=d([b("primer-card-form-submit"),D()],pe);var ac=f` :host { display: flex; align-items: center; position: relative; height: var(--primer-typography-body-large-line-height); } .network-selector { display: flex; align-items: center; cursor: pointer; background: none; padding: unset; border: none; transition: opacity var(--primer-animation-duration) var(--primer-animation-easing); outline: none; gap: var(--primer-space-xsmall); } .network-selector:hover { opacity: 0.8; } .network-selector.static { cursor: default; } .network-selector.static:hover { opacity: 1; } .network-selector:focus-visible { outline: 2px solid var(--primer-color-focus); border-radius: var(--primer-radius-xsmall); } .network-selector-inline { display: flex; border: 1px solid var(--primer-color-border-outlined-default); border-radius: var(--primer-radius-small); padding: 1px; .network-icon-container { padding: var(--primer-space-xsmall); } .network-icon-container + .network-icon-container { border-left: 1px solid var(--primer-color-border-outlined-default); } } .network-icon { display: block; width: calc(var(--primer-size-medium) * 1.4); height: var(--primer-size-medium); object-fit: contain; margin: 0; svg { width: auto; height: 100%; } } .caret { margin-left: var(--primer-space-xsmall); transition: transform var(--primer-animation-duration) var(--primer-animation-easing); color: var(--primer-color-icon-primary); } .caret.open { transform: rotate(180deg); } .dropdown { position: absolute; top: 100%; right: 0; width: max-content; min-width: calc(var(--primer-size-xxxlarge) * 3); background: var(--primer-color-gray-000); border-radius: var(--primer-radius-small); box-shadow: 0 var(--primer-space-xxsmall) var(--primer-space-large) rgba(0, 0, 0, 0.15); z-index: 10; overflow: hidden; border: 1px solid var(--primer-color-border-outlined-default); } .dropdown:not(.open) { display: none; } .dropdown.open { display: block; max-height: calc(var(--primer-size-xxxlarge) * 4); overflow-y: auto; } .network-option { display: flex; align-items: center; padding: var(--primer-space-small) var(--primer-space-medium); cursor: pointer; transition: background-color var(--primer-animation-duration) var(--primer-animation-easing); position: relative; outline: none; background-color: transparent; } /* Only apply hover effect when not in keyboard navigation mode */ .network-option:hover { background-color: var(--primer-color-gray-100); } /* Apply focused style only when the focused class is present (keyboard navigation) */ .network-option.focused { background-color: var(--primer-color-gray-100); } .network-option:focus-visible { outline: 2px solid var(--primer-color-focus); outline-offset: -2px; } .network-option-icon { width: var(--primer-size-medium); height: var(--primer-size-small); margin-right: var(--primer-space-small); object-fit: contain; } .network-name { font-size: var(--primer-typography-body-medium-size); font-family: var(--primer-typography-body-medium-font); line-height: var(--primer-typography-body-medium-line-height); letter-spacing: var(--primer-typography-body-medium-letter-spacing); white-space: nowrap; color: var(--primer-color-text-primary); flex: 1; } .checkmark { margin-left: var(--primer-space-small); color: var(--primer-color-brand); width: var(--primer-size-small); height: var(--primer-size-small); } `;var cy=bi(Pc()),uy=bi(Hr());var ly=bi(Hr());var Nc=[["AMEX","american-express"],["CARTES_BANCAIRES"],["DANKORT"],["DINERS_CLUB","diners-club"],["DISCOVER","discover"],["ENROUTE"],["ELO","elo"],["EFTPOS"],["HIPER","hiper","hiper-pay"],["HIPERCARD","hipercard"],["INTERAC"],["JCB","jcb"],["MAESTRO","maestro"],["MASTERCARD","mastercard"],["MIR","mir","mir-pay"],["OTHER",void 0,"payment-card"],["UNIONPAY","unionpay"],["VISA","visa"]],px=new Map(Nc.map(a=>[a[0],a])),mx=new Map(Nc.filter(a=>a[1]).map(a=>[a[1],a]));var py={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"};var Px=Object.values(py);var my=["EFTPOS"];function Ic(a){return!a.some(t=>my.includes(t))}var me=class extends v{constructor(){super(...arguments);this.selectedCardNetwork=null;this.isDropdownOpen=!1;this.focusedNetworkIndex=0;this.isKeyboardNavigation=!1;this.buttonRef=Ht();this.dropdownRef=Ht();this.networkOptionRefs=[];this.toggleDropdown=e=>{this.isKeyboardNavigation=!1,e.stopPropagation(),this.getSelectableNetworks().length>1&&(this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))};this.handleClickOutside=e=>{this.isDropdownOpen&&(this.contains(e.target)||(this.isDropdownOpen=!1,this.isKeyboardNavigation=!1))};this.handleMouseMove=()=>{this.isKeyboardNavigation&&(this.isKeyboardNavigation=!1)};this.handleKeyDown=e=>{if(!(!(this.getSelectableNetworks().length>1)||!(this.contains(e.target)||this===e.target||this.isDropdownOpen&&e.target===document.body)))switch(this.isKeyboardNavigation=!0,e.key){case"ArrowDown":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex+1)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"ArrowUp":e.preventDefault(),this.isDropdownOpen?(this.focusedNetworkIndex=(this.focusedNetworkIndex-1+this.getSelectableNetworks().length)%this.getSelectableNetworks().length,this.focusNetworkOption()):(this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Enter":case" ":this.isDropdownOpen&&this.focusedNetworkIndex>=0?(e.preventDefault(),this.selectNetwork(e,this.getSelectableNetworks()[this.focusedNetworkIndex])):!this.isDropdownOpen&&this.buttonRef.value===document.activeElement&&(e.preventDefault(),this.isDropdownOpen=!0,this.focusedNetworkIndex=this.getSelectedNetworkIndex());break;case"Escape":this.isDropdownOpen&&(e.preventDefault(),this.isDropdownOpen=!1,this.buttonRef.value?.focus());break;case"Tab":this.isDropdownOpen&&(this.isDropdownOpen=!1);break}};this.handleDocumentKeyDown=e=>{this.isDropdownOpen&&this.handleKeyDown(e)}}getNetworkIconUrl(e){return this.primerContext?.headlessUtils?.getCardNetworkAsset(e.network)?.cardUrl}renderDefaultCardIcon(){return u`<div class="network-icon">${$a["payment-card"]}</div>`}getSelectableNetworks(){return this.primerContext?.cardNetworks?.selectableCardNetworks||[]}getDetectedNetwork(){return this.selectedCardNetwork??(this.primerContext?.cardNetworks?.detectedCardNetwork||null)}getSelectedNetworkIndex(){let e=this.getDetectedNetwork();if(!e)return 0;let r=this.getSelectableNetworks().findIndex(i=>i.network===e.network);return r>=0?r:0}selectNetwork(e,r){e.stopPropagation(),this.selectedCardNetwork=r,this.isDropdownOpen=!1,this.buttonRef.value?.focus(),this.primerContext?.cardNetworks&&this.dispatchEvent(new CustomEvent("network-selected",{detail:{network:r.network},bubbles:!0,composed:!0}))}focusNetworkOption(){requestAnimationFrame(()=>{this.networkOptionRefs[this.focusedNetworkIndex]&&this.networkOptionRefs[this.focusedNetworkIndex].focus()})}setNetworkOptionRef(e,r){this.networkOptionRefs[r]=e}connectedCallback(){super.connectedCallback(),setTimeout(()=>{document.addEventListener("click",this.handleClickOutside),document.addEventListener("mousemove",this.handleMouseMove),this.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keydown",this.handleDocumentKeyDown)},0)}disconnectedCallback(){document.removeEventListener("click",this.handleClickOutside),document.removeEventListener("keydown",this.handleDocumentKeyDown),document.removeEventListener("mousemove",this.handleMouseMove),this.removeEventListener("keydown",this.handleKeyDown),super.disconnectedCallback()}render(){if(this.primerContext?.cardNetworks?.isLoading)return u`<primer-spinner size="small" compact></primer-spinner>`;let e=this.getSelectableNetworks();if(!this.getDetectedNetwork()&&e.length===0)return this.renderDefaultCardIcon();let r=this.getDetectedNetwork()||(e.length>0?e[0]:null);if(!r)return this.renderDefaultCardIcon();let i=e.length>1;return i&&!Ic(e.map(o=>o.network))?u`<div class="network-selector-inline">${e.map(o=>u`<div class="network-icon-container"><img class="network-icon" src=${this.getNetworkIconUrl(o)??""} alt=${o.displayName} /></div>`)}</div>`:u`<button ${Et(this.buttonRef)} class="network-selector ${i?"":"static"}" tabindex=${i?"0":"-1"} @click=${this.toggleDropdown} @keydown=${o=>{(o.key===" "||o.key==="Enter")&&i&&(o.preventDefault(),this.isDropdownOpen=!this.isDropdownOpen,this.isDropdownOpen&&(this.focusedNetworkIndex=this.getSelectedNetworkIndex()))}} aria-label=${i?`Selected card network: ${r.displayName}. Click to change.`:`Card network: ${r.displayName}`} aria-expanded=${i?this.isDropdownOpen:y} aria-haspopup=${i?"true":y} aria-controls=${i?"network-dropdown":y} ><img class="network-icon" src=${this.getNetworkIconUrl(r)} alt=${r.displayName} />${k(i,()=>u`<primer-icon class="caret ${this.isDropdownOpen?"open":""}" size="sm" name="chevron-down" ></primer-icon>`,()=>y)}</button>${k(this.isDropdownOpen,()=>u`<div ${Et(this.dropdownRef)} id="network-dropdown" class="dropdown open" role="listbox" aria-label="Select card network" >${e.map((o,s)=>u`<div ${Et(l=>this.setNetworkOptionRef(l,s))} class="network-option ${this.isKeyboardNavigation&&s===this.focusedNetworkIndex?"focused":""}" @click=${l=>this.selectNetwork(l,o)} @keydown=${l=>{(l.key==="Enter"||l.key===" ")&&this.selectNetwork(l,o)}} role="option" aria-selected=${o.network===r.network} tabindex="${s===this.focusedNetworkIndex?"0":"-1"}" ><img class="network-option-icon" src=${this.getNetworkIconUrl(o)} alt=${o.displayName} /><span class="network-name">${o.displayName}</span>${k(o.network===r.network,()=>u`<primer-icon class="checkmark" name="checkmark" size="sm" ></primer-icon>`,()=>y)}</div>`)}</div>`,()=>y)} `}};me.styles=[T,ac],d([G({context:K,subscribe:!0}),h({attribute:!1})],me.prototype,"primerContext",2),d([N()],me.prototype,"selectedCardNetwork",2),d([N()],me.prototype,"isDropdownOpen",2),d([N()],me.prototype,"focusedNetworkIndex",2),d([N()],me.prototype,"isKeyboardNavigation",2),me=d([b("primer-card-network-selector")],me);var kc=f` :host { display: block; margin-top: var(--primer-space-medium); margin-bottom: var(--primer-space-medium); } .other-payment-methods-container { width: 100%; } .other-payment-methods-content { padding: var(--primer-space-medium) 0; } .primer-loader { display: flex; justify-content: center; align-items: center; } /* Collapsable animation for slotted toggle button */ .collapsable-wrapper { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--primer-animation-duration) var(--primer-animation-easing); overflow: hidden; } .collapsable-wrapper.expanded { grid-template-rows: 1fr; } .collapsable-content { min-height: 0; } `;var _e=class extends v{constructor(){super(...arguments);this.hasSlottedToggle=!1;this.isExpanded=!1;this._isHandlingContextEvent=!1;this._contextToggleListener=null;this.handleToggleSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasSlottedToggle=i.length>0};this.handleSlotButtonClick=e=>{let i=e.target.closest("button, primer-button");if(!i)return;let n=i;this.isToggleButton(n)&&(e.preventDefault(),this.toggleAccordion())};this.handleDirectToggle=e=>{let r=e.detail?.action;r==="expand"?this.expand():r==="collapse"?this.collapse():this.toggleAccordion()};this.handleContextToggle=e=>{if(!this._isHandlingContextEvent){this._isHandlingContextEvent=!0;try{if(e.target!==this){e.stopPropagation();let r=e.detail?.action;r==="expand"?this.expand():r==="collapse"?this.collapse():this.toggleAccordion()}}finally{this._isHandlingContextEvent=!1}}}}isToggleButton(e){let r=this.shadowRoot?.querySelector('slot[name="show-other-payments-toggle-button"]');return r?r.assignedElements({flatten:!0}).some(n=>n===e||n.contains(e)):!1}toggleAccordion(){this.hasSlottedToggle?(this.isExpanded=!this.isExpanded,this.dispatchExpandedEvent(this.isExpanded)):this.collapsableElement&&(this.collapsableElement.isExpanded?this.collapsableElement.collapse():this.collapsableElement.expand())}dispatchExpandedEvent(e){this.dispatchEvent(new CustomEvent("primer:show-other-payments-toggled",{bubbles:!0,composed:!0,detail:{expanded:e}}))}expand(){this.hasSlottedToggle?this.isExpanded||(this.isExpanded=!0,this.dispatchExpandedEvent(!0)):this.collapsableElement?.expand()}collapse(){this.hasSlottedToggle?this.isExpanded&&(this.isExpanded=!1,this.dispatchExpandedEvent(!1)):this.collapsableElement?.collapse()}setupContextEventListeners(){this.primerContext?.events?.host&&this._contextToggleListener&&this.primerContext?.events.host.addEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}cleanupContextEventListeners(){this.primerContext?.events?.host&&this._contextToggleListener&&this.primerContext?.events.host.removeEventListener("primer:show-other-payments-toggle",this._contextToggleListener)}connectedCallback(){super.connectedCallback(),this.isExpanded=this.primerContext?.vaultManager?.vaultedPaymentMethods.length===0,this.addEventListener("click",this.handleSlotButtonClick),this.addEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this._contextToggleListener=e=>{this.handleContextToggle(e)},this.setupContextEventListeners()}disconnectedCallback(){this.removeEventListener("click",this.handleSlotButtonClick),this.removeEventListener("primer:show-other-payments-toggle",this.handleDirectToggle),this.cleanupContextEventListeners(),super.disconnectedCallback()}render(){if(this.primerContext?.vaultManager?.isLoading)return y;let e=this.primerContext?.vaultManager?.showEmptyState||this.primerContext?.vaultManager?.vaultedPaymentMethods.length;return!this.primerContext?.vaultManager||!this.primerContext?.vaultManager.enabled||this.primerContext?.vaultManager.headless||!e?u`<slot name="other-payments"></slot>`:u`<div class="other-payment-methods-container"><slot name="show-other-payments-toggle-button" @slotchange=${this.handleToggleSlotChange} ></slot>${k(!this.hasSlottedToggle,()=>u`<primer-collapsable buttonVariant="secondary" .expanded="${this.primerContext?.vaultManager?.vaultedPaymentMethods.length===0}" .header="${E("navigateToPaymentMethods",{id:"navigateToPaymentMethods"})}" ><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></primer-collapsable>`,()=>u`<div class="collapsable-wrapper ${this.isExpanded?"expanded":""}" role="region" aria-labelledby="custom-toggle-button" ><div class="collapsable-content"><div class="other-payment-methods-content"><slot name="other-payments"></slot></div></div></div>`)}</div>`}};_e.styles=[kc],d([G({context:K,subscribe:!0}),h({attribute:!1})],_e.prototype,"primerContext",2),d([de("primer-collapsable")],_e.prototype,"collapsableElement",2),d([N()],_e.prototype,"hasSlottedToggle",2),d([N()],_e.prototype,"isExpanded",2),_e=d([b("primer-show-other-payments")],_e);var Lc=f` :host { display: flex; width: 100%; } .container { width: 100%; display: flex; flex-direction: column; transition: all var(--primer-animation-duration) var(--primer-animation-easing); } .container.expanded { border-radius: var(--primer-radius-medium); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); background-color: var(--primer-color-background-outlined-default); border: 1px solid var(--primer-color-border-outlined-default); padding: var(--primer-space-large); } .expanded-content { width: 100%; display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--primer-animation-duration) var(--primer-animation-easing); overflow: hidden; } .container.expanded .expanded-content { grid-template-rows: 1fr; } .content-wrapper { overflow: hidden; } :host([disabled]) { opacity: 0.6; cursor: not-allowed; } `;var Oe=class extends v{constructor(){super(...arguments);this.disabled=!1;this.expanded=!1;this.suppressBlurCollapse=!1;this._handleDocumentClick=e=>{this.expanded&&(this.suppressBlurCollapse||e.composedPath().includes(this)||this._collapseFromOutsideInteraction())};this._handleWindowBlur=()=>{!this.expanded||this.suppressBlurCollapse||setTimeout(()=>{document.hasFocus()&&this._collapseFromOutsideInteraction()},100)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this._handleDocumentClick),window.addEventListener("blur",this._handleWindowBlur)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("click",this._handleDocumentClick),window.removeEventListener("blur",this._handleWindowBlur)}_collapseFromOutsideInteraction(){this.expanded&&(this.expanded=!1,this.dispatchEvent(new CustomEvent("expanded-change",{detail:{expanded:!1},bubbles:!0,composed:!0})))}_handleButtonClick(){this.disabled||(this.expanded=!this.expanded,this.dispatchEvent(new CustomEvent("expanded-change",{detail:{expanded:this.expanded},bubbles:!0,composed:!0})))}render(){return u`<div class="container ${this.expanded?"expanded":""}"><primer-payment-method-button .type=${this.type} ?disabled=${this.disabled} @payment-method-click=${()=>this._handleButtonClick()} ></primer-payment-method-button><div class="expanded-content"><div class="content-wrapper"><slot></slot></div></div></div>`}};Oe.styles=[T,Lc],d([h({type:String})],Oe.prototype,"type",2),d([h({type:Boolean,attribute:"disabled"})],Oe.prototype,"disabled",2),d([h({type:Boolean,reflect:!0})],Oe.prototype,"expanded",2),d([h({type:Boolean,attribute:"suppress-blur-collapse"})],Oe.prototype,"suppressBlurCollapse",2),Oe=d([b("primer-payment-method-accordion")],Oe);var Rc=f` :host { display: block; width: 100%; } button { padding: var(--primer-space-medium) var(--primer-space-large); display: flex; align-items: center; justify-content: center; border-radius: var(--primer-radius-small); background-color: var(--primer-color-brand); color: var(--primer-color-background-outlined-default); border: none; font-family: var(--primer-typography-body-medium-font); font-size: var(--primer-typography-body-medium-size); font-weight: var(--primer-typography-body-medium-weight); width: 100%; cursor: pointer; transition: all var(--primer-animation-duration) var(--primer-animation-easing); } button:hover:not(:disabled) { filter: brightness(105%); } button:disabled { background-color: var(--primer-color-background-outlined-disabled); border-color: var(--primer-color-border-outlined-disabled); color: var(--primer-color-text-disabled); cursor: not-allowed; } button.loading { opacity: 0.7; pointer-events: none; } `;var pt=class extends v{constructor(){super(...arguments);this.disabled=!1;this.loading=!1}render(){return u`<button class=${X({loading:this.loading})} ?disabled=${this.disabled||this.loading} @click=${()=>this.dispatchEvent(new Event("confirm",{bubbles:!0,composed:!0}))} >${this.loading?u`<primer-spinner size="small" compact></primer-spinner>`:E("confirm",{id:"confirm"})}</button>`}};pt.styles=[T,Rc],d([h({type:Boolean})],pt.prototype,"disabled",2),d([h({type:Boolean})],pt.prototype,"loading",2),pt=d([b("primer-payment-method-accordion-confirm-button"),D()],pt);var pr=class extends v{render(){return u`<primer-checkout-state type="complete"></primer-checkout-state>`}};pr=d([b("primer-checkout-complete")],pr);var zt=class extends v{render(){return u`<primer-checkout-state type="failure" description=${this.primerContext?.sdkState?.primerJsError?.message||""} ></primer-checkout-state>`}};d([G({context:K,subscribe:!0}),h({attribute:!1})],zt.prototype,"primerContext",2),zt=d([b("primer-checkout-error")],zt);var wc=f` :host { display: block; width: 100%; } `;var mt=class extends v{constructor(){super(...arguments);this.showProcessingErrors=!0}get shouldShowError(){return!this.primerContext?.sdkState||this.primerContext.sdkState.isProcessing?!1:!!(this.primerContext.sdkState.paymentFailure&&this.showProcessingErrors)}render(){return this.primerContext?.sdkState?u`<primer-error-message message="${E(this.primerContext.sdkState.paymentFailure?.message??"",{id:"tokenizationError"})}" ?visible="${this.shouldShowError}" ></primer-error-message>`:y}};mt.styles=[wc],d([G({context:K,subscribe:!0}),h({attribute:!1})],mt.prototype,"primerContext",2),d([h({type:Boolean,attribute:"show-processing-errors"})],mt.prototype,"showProcessingErrors",2),mt=d([b("primer-error-message-container")],mt);var xc=f` :host { display: contents; } .primer-main-list { display: flex; flex-direction: column; gap: var(--primer-space-small); } .primer-is-processing { opacity: 0.5; pointer-events: none; } primer-vault-manager { margin-bottom: var(--primer-space-xlarge); } `;var kt=class extends v{constructor(){super(...arguments);this.hasAssignedContent=!1;this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()}}render(){return this.primerContext?.sdkState?.isLoading?y:this.primerContext?.sdkState?.isSuccessful?u`<slot name="checkout-complete"><primer-checkout-complete></primer-checkout-complete></slot>`:u`<slot name="payments" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent,()=>y,()=>u`<div class=${X({"primer-is-processing":!!this.primerContext?.sdkState?.isProcessing})} ><primer-vault-manager></primer-vault-manager><primer-show-other-payments><div slot="other-payments" class="primer-main-list">${this.primerContext?.paymentMethods?.map(e=>u`<primer-payment-method type=${e.type} ?disabled=${this.primerContext?.clientOptions?.disabledPayments===!0} ></primer-payment-method>`)}</div></primer-show-other-payments><primer-error-message-container></primer-error-message-container></div>`)} `}};kt.styles=[T,xc],d([G({context:K,subscribe:!0}),h({attribute:!1})],kt.prototype,"primerContext",2),kt=d([b("primer-main")],kt);!1;function QO(){pl(),ml()}export{Te as AdyenMbway,Ve as ApplePay,ne as BillingAddress,be as Blik,ce as Button,Se as CardForm,dt as CardFormCVV,me as CardFormCardNetworkSelector,lt as CardFormCardNumber,it as CardFormError,ct as CardFormExpiry,ut as CardFormName,pe as CardFormSubmit,ue as Collapsable,Re as Dialog,Fe as ErrorMessage,mt as ErrorMessageContainer,Ue as GooglePay,j as Input,at as InputLabel,Ge as InputWrapper,He as PayPal,Ye as PaymentMethod,Oe as PaymentMethodAccordion,pt as PaymentMethodAccordionConfirmButton,$e as PaymentMethodButton,we as PaymentMethodContainer,je as PaymentMethodContentComponent,te as PortalDialog,pr as PrimerCheckoutComplete,ye as PrimerCheckoutComponent,zt as PrimerCheckoutFailure,nt as PrimerCheckoutState,Ke as PrimerIcon,ve as PrimerKlarna,kt as PrimerMain,re as PtPhoneNumberInput,ot as RedirectPayment,fe as Select,_e as ShowOtherPayments,Be as Spinner,ae as VaultCvvInput,Ie as VaultDeleteConfirmation,st as VaultEmptyState,ze as VaultErrorMessage,oe as VaultManager,xe as VaultManagerHeader,Ne as VaultPaymentMethodItem,Ce as VaultPaymentSubmit,ih as injectDarkTheme,ah as injectLightTheme,pl as injectLoaderStyles,ml as injectThemeStyles,QO as loadPrimer};
|
package/dist/web-types.json
CHANGED
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@primer-io/primer-js",
|
|
3
3
|
"description": "Primer Checkout is a web component-based SDK for building secure, customizable, and PCI-compliant checkout experiences. Designed with a modular architecture, it integrates seamlessly with any JavaScript framework and supports multiple payment methods.",
|
|
4
4
|
"license": "BSD-3-Clause",
|
|
5
|
-
"version": "1.4.
|
|
5
|
+
"version": "1.4.2",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./dist/primer-loader.js",
|
|
8
8
|
"types": "./dist/primer-loader.d.ts",
|