@getopenpay/openpay-js 0.5.23 → 0.5.24

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/dist/index.umd.js CHANGED
@@ -210,9 +210,9 @@ ${S.message}`),S.message)}else return getHumanFriendlyMessage(S.message);if(type
210
210
  </div>
211
211
  </div>
212
212
  `;const C=document.createElement("div"),L=C.attachShadow({mode:"open"});L.appendChild(D.content.cloneNode(!0));const y=L.querySelector(".cancel-button"),_=L.querySelectorAll(".bank-item"),N=()=>{document.body.removeChild(C)};y.addEventListener("click",()=>{N(),M(new Error("Bank selection cancelled"))}),_.forEach((I,x)=>{I.addEventListener("click",()=>{N(),R(S[x])})}),document.body.appendChild(C)})},createAndOpenMicroDepositForm=(S,T)=>{const{width:A,height:P,baseUrl:O}=T??{},R=new URL(`app/direct_debit/micro_deposit/?type=${S}`,O).toString();return new Promise((M,D)=>{const U=createAndOpenFrame(R,{width:A,height:P,title:"Micro Deposit Form"}),C=()=>{U.host.remove()},L=()=>{C(),D(new Error("Micro deposit form cancelled"))},y=V=>{C(),V.status==="success"&&V.payload?"error"in V.payload?D(new Error(V.payload.error)):M(V.payload):D(new Error("Micro deposit form failed"))};U.cancelButton.addEventListener("click",L);const _=startPolling(U.iframe,y,new URL(O).origin,"micro-deposit-status",MicroDepositStatusResponse),N=()=>{U.cancelButton.removeEventListener("click",L),clearInterval(_)},I=L,x=()=>{N(),I()};U.cancelButton.removeEventListener("click",L),U.cancelButton.addEventListener("click",x)})};function startPolling(S,T,A,P,O){const R=async()=>{try{const D=await pingCdeForStatus(S,A,P,O);D&&(clearInterval(M),T(D))}catch{}};R();const M=setInterval(R,CDE_POLLING_INTERVAL);return M}function handleEvents({elements:S,pollingInterval:T,resolve:A}){const P=()=>{clearInterval(T),S.host.remove(),A({status:ThreeDSStatus.CANCELLED})};return S.cancelButton.addEventListener("click",P),()=>{S.cancelButton.removeEventListener("click",P)}}async function start3dsVerification(S){const{url:T,baseUrl:A,frameWidth:P,frameHeight:O,frameTitle:R}=S,M=createAndOpenFrame(T,{width:P,height:O,title:R});return new Promise(D=>{const U=y=>{setTimeout(()=>{M.host.remove()},1e3),D(y),L?.()},C=startPolling(M.iframe,U,new URL(A).origin,"ping-3ds-status",Ping3DSStatusResponse),L=handleEvents({elements:M,pollingInterval:C,resolve:D})})}const start3dsVerificationStrict=async S=>{const T=await start3dsVerification(S);if(T.status===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(T.status===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed");return T.status!==ThreeDSStatus.SUCCESS&&assertNever(T.status),{href:T.href}},openPopupWindow=(S,T)=>{const A=window.open(T,"_blank");if(!A)throw new Error(`${S} popup window blocked. Please allow popups for this site.`);return A},startPopupWindowVerificationStrict=async(S,T,A,P)=>{const{err__:O}=createOjsFlowLoggers("popup-verify");return new Promise((R,M)=>{const D=openPopupWindow(S,P),U=setInterval(async()=>{try{const C=await checkIfPopupWindowVerified(T,A);if(C.present)clearInterval(U),D.close(),R({href:C.href});else if(D.closed)throw new Error(`${S} payment cancelled`)}catch(C){O(getErrorMessage(C)),clearInterval(U),M(getErrorMessage(C))}},1e3)})},detectLanguage=()=>{let T=(navigator.languages&&navigator.languages.length?navigator.languages:[navigator.language])?.[0];return T&&(T=T.split("-")[0]),T},{log__:log__$w,err__:err__$w}=createOjsFlowLoggers("common-cc"),createDynamicValidationSchema=({require_zip_code:S,require_full_billing_address:T,require_full_shipping_address:A,payment_method:P,isBusinessPurchase:O},R)=>{const M={};return P==="ach"&&(M[FieldName.FIRST_NAME]=stringType().min(2,{message:"Minimum length is 2"}),M[FieldName.LAST_NAME]=stringType().min(2,{message:"Minimum length is 2"})),S&&(M[FieldName.ZIP_CODE]=RequiredString),T&&(M[FieldName.LINE1]=RequiredString,M[FieldName.CITY]=RequiredString,M[FieldName.STATE]=RequiredString,M[FieldName.COUNTRY]=RequiredString,M[FieldName.ZIP_CODE]=RequiredString),A&&(M[FieldName.SHIPPING_LINE1]=RequiredString,M[FieldName.SHIPPING_CITY]=RequiredString,M[FieldName.SHIPPING_STATE]=RequiredString,M[FieldName.SHIPPING_COUNTRY]=RequiredString,M[FieldName.SHIPPING_ZIP_CODE]=RequiredString),(R[FieldName.IS_BUSINESS_PURCHASE]??O)&&(M[FieldName.BUSINESS_NAME]=RequiredString),Object.keys(M).length===0?RequiredFormFields:RequiredFormFields.extend(M)},validateNonCdeFormFields=(S,T,A={})=>{if(A){log__$w(`Received default field values: ${JSON.stringify(A)}`);const R=Object.keys(A);for(let M=0;M<R.length;M++){const D=R[M],U=A[D];S[D]||(S[D]=U)}}S[FieldName.IS_SHIPPING_SAME_AS_BILLING]=!!S[FieldName.IS_SHIPPING_SAME_AS_BILLING],S[FieldName.IS_SHIPPING_SAME_AS_BILLING]&&(S[FieldName.SHIPPING_LINE1]=S[FieldName.LINE1],S[FieldName.SHIPPING_LINE2]=S[FieldName.LINE2],S[FieldName.SHIPPING_LINE3]=S[FieldName.LINE3],S[FieldName.SHIPPING_CITY]=S[FieldName.CITY],S[FieldName.SHIPPING_STATE]=S[FieldName.STATE],S[FieldName.SHIPPING_COUNTRY]=S[FieldName.COUNTRY],S[FieldName.SHIPPING_ZIP_CODE]=S[FieldName.ZIP_CODE]);const O=createDynamicValidationSchema(A,S).safeParse(S);if(!O.success){const R=O.error.format(),M=extractIssuesPerField(R),D=Object.keys(M);for(let U=0;U<D.length;U++){const C=D[U],L=M[C];T(C,L,C)}throw err__$w("Got validation errors in non-CDE form fields",M),new Error("Almost there! Just a few things highlighted above to fix before you can submit.")}return O.data},{log__:log__$v,err__:err__$v}=createOjsFlowLoggers("common-cc"),validateNonCdeFormFieldsForCC=validateNonCdeFormFields,validateTokenizeCardResults=(S,T)=>{for(const A of S)if(A.success===!1)throw A.errors.forEach(P=>{const O=AllFieldNames.safeParse(P.elementType);if(!O.success)err__$v(`Unknown field name in onValidationError: ${P.elementType}. Error object:`,P);else{const R=O.data;T(R,P.errors)}}),log__$v(`Error tokenizing card: got validation errors: ${JSON.stringify(A.errors)}`),new Error("Got validation errors while tokenizing card")},{err__:err__$u}=createOjsFlowLoggers("common"),parseConfirmPaymentFlowResponse=S=>{if(S.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${S.payment_methods.length}`);return{payment_method_id:S.payment_methods[0].id}},findCpmMatchingType=(S,T)=>{const A=S.find(P=>T.safeParse(P).success);if(!A)throw err__$u("No CPMs found for model. All models:",S),new Error("No CPMs found for model");return T.parse(A)},createCustomerFieldsFromForm=(S,T)=>({new_customer_email:S.email,new_customer_last_name:S.lastName,new_customer_first_name:S.firstName,customer_business_name:S.businessName,customer_tax_id:S.taxId,customer_tax_id_type:S.taxIdType,new_customer_address:generateBillingAddressFromFields(S),new_customer_shipping_address:generateShippingAddressFromFields(S,T),customer_language:detectLanguage(),new_customer_phone:S.phone}),performSimpleCheckoutOrSetup=async S=>{const{log__:T}=createOjsFlowLoggers(S.logPrefix),A=await getPrefill(S.anyCdeConnection),P=parseConfirmPaymentFlowResponse(S.confirmResult);if(A.mode==="setup")return T("Setting up payment method..."),{mode:"setup",result:await finalizeSetupPaymentMethod(S.anyCdeConnection,{secure_token:A.token,pm_id:P.payment_method_id})};{if(S.usePayFirstFlow){if(T("Using pay-first flow..."),!S.confirmResult.pay_first_success_response)throw err__$u("Checkout failed, no pay-first success response:",S.confirmResult),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:S.confirmResult.pay_first_success_response}}const O={secure_token:A.token,payment_input:{provider_type:S.checkoutPaymentMethod.provider},customer_email:S.requiredFormFields[FieldName.EMAIL],customer_address:generateBillingAddressFromFields(S.requiredFormFields),customer_shipping_address:generateShippingAddressFromFields(S.requiredFormFields,A.checkout_settings),promotion_code:S.requiredFormFields[FieldName.PROMOTION_CODE],line_items:A.line_items,total_amount_atom:A.amount_total_atom,cancel_at_end:!1,use_confirmed_pm_id:P.payment_method_id,checkout_payment_method:S.checkoutPaymentMethod};return T("Doing checkout...",O),{mode:"checkout",result:await performCheckout(S.anyCdeConnection,O)}}},PaymentProcessor=enumType(["stripe","airwallex","authorize_net","adyen","paypal","pockyt","loop"]);PaymentProcessor.Enum.stripe;const loadScript=({scriptId:S,src:T,checkLoadedFn:A})=>{const P=new AbortController;return new Promise((O,R)=>{let M=document.createElement("script");M.src=T,M.id=S,M.async=!0;const D=document.getElementById(S);A()?O():D?M=D:document.body.appendChild(M),M.addEventListener("load",()=>{P.abort(),O()},{signal:P.signal}),M.addEventListener("error",()=>{P.abort(),R("Failed to load the script")},{signal:P.signal})})},getPaymentDataRequest=({gateway:S,gatewayMerchantId:T,merchantName:A,merchantId:P,initialPreview:O,overridePaymentRequest:R,prefill:M})=>{const D=R?.amount?.amountAtom??O?.amountAtom??0,U=Math.max(D/100,0),C=(R?.amount?.currency??M?.currency??O.currency).toUpperCase(),L={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:S,gatewayMerchantId:T}}}],emailRequired:!0,shippingAddressRequired:M.checkout_settings.require_full_shipping_address,merchantInfo:{merchantId:P??"",merchantName:A},transactionInfo:{countryCode:"US",currencyCode:C,totalPriceStatus:R?.pending?"ESTIMATED":"FINAL",totalPrice:U.toFixed(2)}};return R?.googlePayPaymentRequest?typeof R.googlePayPaymentRequest=="function"?{...L,...R.googlePayPaymentRequest(L)}:{...L,...R.googlePayPaymentRequest}:L},loadGooglePayScript=()=>loadScript({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>!!window.google?.payments?.api});let paymentsClient=null;const getGooglePayEnvironment=async S=>await getCurrentEnv(S)==="prod"?"PRODUCTION":"TEST",getGooglePaymentsClient=async(S,T)=>{const A=await getGooglePayEnvironment(S);return paymentsClient===null&&(paymentsClient=new window.google.payments.api.PaymentsClient({environment:A,merchantInfo:T.merchantInfo})),paymentsClient},parseAirwallexStartPaymentFlowResponse=S=>{const T=S.required_user_actions.find(A=>A.type==="airwallex_payment_consent");return T?CommonNextActionMetadata.parse(T):null},fillEmptyFormInputsWithGooglePay=(S,T)=>{const A={...S},P=T.paymentMethodData?.info?.billingAddress,O=T.shippingAddress;if(P){const[R,...M]=P.name?.trim()?.split(/\s+/)??[],D=M.join(" ")||void 0;A[FieldName.EMAIL]=A[FieldName.EMAIL]||T.email||"op_unfilled@getopenpay.com",A[FieldName.LINE1]=A[FieldName.LINE1]||P.address1||"",A[FieldName.LINE2]=A[FieldName.LINE2]||P.address2||"",A[FieldName.LINE3]=A[FieldName.LINE3]||P.address3||"",A[FieldName.CITY]=A[FieldName.CITY]||P.locality||"",A[FieldName.STATE]=A[FieldName.STATE]||P.administrativeArea||"",A[FieldName.COUNTRY]=A[FieldName.COUNTRY]||P.countryCode||"US",A[FieldName.ZIP_CODE]=A[FieldName.ZIP_CODE]||P.postalCode||"00000";const U=A[FieldName.FIRST_NAME]||R||"",C=A[FieldName.LAST_NAME]||D||"";U||C?(A[FieldName.FIRST_NAME]=U,A[FieldName.LAST_NAME]=C):(A[FieldName.FIRST_NAME]="_OP_UNKNOWN",A[FieldName.LAST_NAME]="")}return O&&(A[FieldName.SHIPPING_LINE1]=A[FieldName.SHIPPING_LINE1]||O.address1||"",A[FieldName.SHIPPING_LINE2]=A[FieldName.SHIPPING_LINE2]||O.address2||"",A[FieldName.SHIPPING_LINE3]=A[FieldName.SHIPPING_LINE3]||O.address3||"",A[FieldName.SHIPPING_CITY]=A[FieldName.SHIPPING_CITY]||O.locality||"",A[FieldName.SHIPPING_ZIP_CODE]=A[FieldName.SHIPPING_ZIP_CODE]||O.postalCode||"00000",A[FieldName.SHIPPING_STATE]=A[FieldName.SHIPPING_STATE]||O.administrativeArea||"",A[FieldName.SHIPPING_COUNTRY]=A[FieldName.SHIPPING_COUNTRY]||O.countryCode||"US"),A},{log__:log__$u,err__:err__$t}=createOjsFlowLoggers("awx-bacs"),runAirwallexBACSFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{const R=validateNonCdeFormFieldsForCC(A,P.get.onValidationError),M=S.anyCdeConnection,D=await getPrefill(M),U=O.verificationMethod??"truelayer";let C=null;if(U==="micro_deposit"){log__$u("Micro deposit verification selected, showing form...");try{C=await createAndOpenMicroDepositForm("bacs_direct_debit",{width:"450px",height:"350px",baseUrl:S.baseUrl}),log__$u("Micro deposit data collected")}catch{throw log__$u("Micro deposit form cancelled"),new Error("Micro deposit form cancelled")}}const L=await startPaymentFlow(M,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(R,D.checkout_settings),customer_language:detectLanguage()}),y=parseAirwallexStartPaymentFlowResponse(L),_=y?.consent_id,N=y?.available_banks;let I;if(U==="truelayer"&&N&&N.length>=1){log__$u("Multiple banks available, showing bank selector...");try{I=await createAndOpenBankSelector(N,{width:"450px",height:"500px",title:"Select bank"}),log__$u(`Bank selected: ${I.display_name}`)}catch{throw log__$u("Bank selection cancelled"),new Error("Bank selection cancelled")}}const x=generateBillingAddressFromFields(R),V={type:"bacs_direct_debit",bacs_direct_debit:{bank_name:I?.bank_name,owner_name:getFullName(R[FieldName.FIRST_NAME],R[FieldName.LAST_NAME]),owner_email:R[FieldName.EMAIL],country_code:R[FieldName.COUNTRY],account_number:C?.account_number,sort_code:C?.sort_code,address:{...x,town:x.city,postcode:x.zip_code}}},F=(await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_,verification_method:U,direct_debit_data:V}})).required_user_actions?.find(ee=>ee.type==="airwallex_payment_consent")?.redirect_url;if(F){log__$u("BACS verification required, starting verification...");const{status:ee}=await start3dsVerification({url:F,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"BACS verification"});if(log__$u(`╰ BACS verification completed [Status: ${ee}]`),ee===ThreeDSStatus.CANCELLED)throw new Error("BACS verification cancelled");if(ee===ThreeDSStatus.FAILURE)throw new Error("BACS verification failed")}const W=await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_}});try{return performSimpleCheckoutOrSetup({logPrefix:"awx-bacs",anyCdeConnection:M,checkoutPaymentMethod:T,requiredFormFields:R,confirmResult:W,usePayFirstFlow:!1})}catch(ee){throw err__$t("BACS payment error",ee),track("checkout_error",{error:ee}),new Error(ee?.message??"Unknown error")}}),{log__:log__$t,err__:err__$s}=createOjsFlowLoggers("awx-eft"),runAirwallexEFTFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{const R=validateNonCdeFormFieldsForCC(A,P.get.onValidationError),M=S.anyCdeConnection,D=await getPrefill(M),U=O.verificationMethod??"plaid";let C=null;if(U==="micro_deposit"){log__$t("Micro deposit verification selected, showing form...");try{C=await createAndOpenMicroDepositForm("eft_direct_debit",{width:"450px",height:"450px",baseUrl:S.baseUrl}),log__$t("Micro deposit data collected")}catch{throw log__$t("Micro deposit form cancelled"),new Error("Micro deposit form cancelled")}}const L=await startPaymentFlow(M,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(R,D.checkout_settings),customer_language:detectLanguage()}),_=parseAirwallexStartPaymentFlowResponse(L)?.consent_id,N={type:"eft_direct_debit",eft_direct_debit:{business_account:O.isBusinessAccount??!1,owner_name:getFullName(R[FieldName.FIRST_NAME],R[FieldName.LAST_NAME]),owner_email:R[FieldName.EMAIL],institution_number:C?.institution_number,transit_number:C?.transit_number,account_number:C?.account_number}},x=(await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_,verification_method:U,direct_debit_data:N}})).required_user_actions?.find(k=>k.type==="airwallex_payment_consent")?.redirect_url;if(x){log__$t("EFT verification required, starting verification...");const{status:k}=await start3dsVerification({url:x,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"EFT verification"});if(log__$t(`╰ EFT verification completed [Status: ${k}]`),k===ThreeDSStatus.CANCELLED)throw new Error("EFT verification cancelled");if(k===ThreeDSStatus.FAILURE)throw new Error("EFT verification failed")}const V=await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_}});try{return performSimpleCheckoutOrSetup({logPrefix:"awx-eft",anyCdeConnection:M,checkoutPaymentMethod:T,requiredFormFields:R,confirmResult:V,usePayFirstFlow:!1})}catch(k){throw err__$s("EFT payment error",k),track("checkout_error",{error:k}),new Error(k?.message??"Unknown error")}}),{log__:log__$s,err__:err__$r}=createOjsFlowLoggers("awx-sepa"),runAirwallexSEPAFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{const R=validateNonCdeFormFieldsForCC(A,P.get.onValidationError),M=S.anyCdeConnection,D=await getPrefill(M),U=O.verificationMethod??"truelayer";let C=null;if(U==="micro_deposit"){log__$s("Micro deposit verification selected, showing form...");try{C=await createAndOpenMicroDepositForm("sepa_direct_debit",{width:"450px",height:"300px",baseUrl:S.baseUrl}),log__$s("Micro deposit data collected")}catch{throw log__$s("Micro deposit form cancelled"),new Error("Micro deposit form cancelled")}}const L=await startPaymentFlow(M,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(R,D.checkout_settings),customer_language:detectLanguage()}),y=parseAirwallexStartPaymentFlowResponse(L),_=y?.consent_id,N=y?.available_banks;let I;if(U==="truelayer"&&N&&N.length>=1){log__$s("Multiple banks available, showing bank selector...");try{I=await createAndOpenBankSelector(N,{width:"450px",height:"500px",title:"Select bank"}),log__$s(`Bank selected: ${I.display_name}`)}catch{throw log__$s("Bank selection cancelled"),new Error("Bank selection cancelled")}}const V=(await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_,verification_method:U,direct_debit_data:{type:"sepa_direct_debit",sepa_direct_debit:{bank_name:I?.bank_name,country_code:R[FieldName.COUNTRY],owner_name:getFullName(R[FieldName.FIRST_NAME],R[FieldName.LAST_NAME]),owner_email:R[FieldName.EMAIL],iban:C?.iban}}}})).required_user_actions?.find(F=>F.type==="airwallex_payment_consent")?.redirect_url;if(V){log__$s("SEPA verification required, starting verification...");const{status:F}=await start3dsVerification({url:V,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"SEPA verification"});if(log__$s(`╰ SEPA verification completed [Status: ${F}]`),F===ThreeDSStatus.CANCELLED)throw new Error("SEPA verification cancelled");if(F===ThreeDSStatus.FAILURE)throw new Error("SEPA verification failed")}const k=await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_}});try{return performSimpleCheckoutOrSetup({logPrefix:"awx-sepa",anyCdeConnection:M,checkoutPaymentMethod:T,requiredFormFields:R,confirmResult:k,usePayFirstFlow:!1})}catch(F){throw err__$r("SEPA payment error",F),track("checkout_error",{error:F}),new Error(F?.message??"Unknown error")}}),{log__:log__$r,err__:err__$q}=createOjsFlowLoggers("airwallex-cc"),Airwallex3dsErrorResponseHeaders=objectType({"op-airwallex-3ds-url":stringType(),"op-airwallex-initial-intent-id":stringType(),"op-airwallex-consent-id":stringType()}),parseResponseHeaders$3=S=>{const T=Airwallex3dsErrorResponseHeaders.safeParse(S);if(!T.success){const A="Unable to process your credit card. Please contact support for assistance.",P=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(S)}`;throw err__$q(P),new Error(A)}return T.data},checkIfRequiresAirwallex3ds=S=>S?.["op-airwallex-3ds-url"]!==void 0,parseIntentIdFrom3dsHref=S=>{try{const T=new URL(S??"").searchParams.get("payment_intent_id");if(!T)throw new Error("No intent ID found in Airwallex 3DS verification result");return log__$r(`Airwallex 3DS verification success. [Intent ID: ${T}]`),T}catch(T){const A="Error verifying Airwallex 3DS verification result.";throw err__$q(A,`Resulting URL: ${S}.
213
- Error: ${getErrorMessage(T)}`),new Error(A)}},runAirwallex3dsFlow=async(S,T)=>{const A=parseResponseHeaders$3(T),P=await start3dsVerificationStrict({url:A["op-airwallex-3ds-url"],baseUrl:S}),O=parseIntentIdFrom3dsHref(P.href??""),R=A["op-airwallex-initial-intent-id"];if(R!==O){const D="Unable to process your credit card. Please contact support for assistance.",U=`Intent ID from callback (${O}) does not match the initial intent ID (${R}).`;throw err__$q(U),new Error(D)}return{existing_cc:{initial_intent_id:O,consent_id:A["op-airwallex-consent-id"]}}},ApplePayCpm$2=objectType({provider:literalType("apple_pay"),processor_name:literalType("airwallex"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType()})}),GooglePayCpm$2=objectType({provider:literalType("google_pay"),processor_name:literalType("airwallex"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType(),google_pay_merchant_id:stringType().nullish()})}),loadApplePayScript=()=>loadScript({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession}),fillEmptyFormInputsWithApplePay=(S,T)=>{const A=T.token.paymentMethod.billingContact,P=T.billingContact,O=T.shippingContact,R={...S};if(A||P||O){R[FieldName.EMAIL]=R[FieldName.EMAIL]||A?.emailAddress||P?.emailAddress||O?.emailAddress||"op_unfilled@email.com",R[FieldName.COUNTRY]=R[FieldName.COUNTRY]||A?.countryCode||P?.countryCode||O?.countryCode||"US",R[FieldName.ZIP_CODE]=R[FieldName.ZIP_CODE]||A?.postalCode||P?.postalCode||O?.postalCode||"00000";const M=R[FieldName.FIRST_NAME]||A?.givenName||P?.givenName||O?.givenName||"",D=R[FieldName.LAST_NAME]||A?.familyName||P?.familyName||O?.familyName||"";M||D?(R[FieldName.FIRST_NAME]=M,R[FieldName.LAST_NAME]=D):(R[FieldName.FIRST_NAME]="_OP_UNKNOWN",R[FieldName.LAST_NAME]="")}return R};objectType({data:objectType({messageHeaders:recordType(stringType(),anyType()),errors:arrayType(anyType()),messageType:stringType(),messageBody:recordType(stringType(),anyType())}),origin:literalType("https://applepay.cdn-apple.com")});const createRecurringPaymentRequest=({total:S,prefill:T})=>{if(T.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:S.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${T.token}`,FRAME_BASE_URL).toString()};const A=T.line_items?.[0];if(A)return{paymentDescription:A?.description??"",regularBilling:{amount:S.amount,label:A?.description??"",recurringPaymentIntervalUnit:A?.billing_interval,recurringPaymentIntervalCount:A?.billing_interval_count??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${T.token}`}},createApplePayTotal=({overridePaymentRequest:S,initialPreview:T,prefill:A,defaultLabel:P="Total"})=>{const O=(S?.amount?.currency??A?.currency??T.currency).toUpperCase(),M=((S?.amount?.amountAtom??T?.amountAtom??0)/100).toFixed(2);return{currencyCode:O,total:{label:S?.label??P??"Total",type:S?.pending?"pending":"final",amount:M}}},getApplePayPaymentRequest=({overridePaymentRequest:S,initialPreview:T,prefill:A,defaultLabel:P})=>{const{currencyCode:O,total:R}=createApplePayTotal({overridePaymentRequest:S,initialPreview:T,prefill:A,defaultLabel:P});let M={countryCode:"US",currencyCode:O,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email",...A.checkout_settings.require_full_shipping_address?["postalAddress"]:[]],supportedNetworks:["visa","masterCard","amex","discover","jcb"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],total:R};return A.line_items.every(U=>U.billing_interval&&U.billing_interval_count)&&(M.recurringPaymentRequest=createRecurringPaymentRequest({total:R,prefill:A})),S?.applePayPaymentRequest&&(typeof S.applePayPaymentRequest=="function"?M={...M,...S.applePayPaymentRequest(M)}:M={...M,...S.applePayPaymentRequest}),M},AdyenEnvironment=enumType(["test","live","live-us","live-in","live-apse","live-au"]),AdyenLocale=enumType(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:log__$q,err__:err__$p}=createOjsFlowLoggers("adyen-cc"),Adyen3dsResponseHeaders=objectType({"op-account-id":stringType(),"op-adyen-client-key":stringType(),"op-adyen-environment":AdyenEnvironment,"op-adyen-action":stringType()}),friendlyErr="Unable to process your credit card. Please contact support for assistance.",parseResponseHeaders$2=S=>{const T=Adyen3dsResponseHeaders.safeParse(S);if(!T.success)throw err__$p(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(S)}`),new Error(friendlyErr);return T.data},decodeAdyenAction=S=>JSON.parse(S),isAdyenAvailable=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,getAdyenCheckout=async()=>{log__$q("Waiting for Adyen SDK to load...");for(let S=0;S<10;S++)isAdyenAvailable()||await sleep(500);if(!isAdyenAvailable())throw err__$p("Adyen SDK not loaded properly"),new Error(friendlyErr);return log__$q("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},handleAdyen3ds=S=>{const{headers:T,locale:A,countryCode:P,component:O,host:R,cancelButton:M}=S,D=decodeAdyenAction(T["op-adyen-action"]);return log__$q(`Running Adyen 3DS flow for action type: ${D.type}`),new Promise(U=>{const C=()=>{log__$q("Cleaning up Adyen 3DS flow"),M.removeEventListener("click",_),R.remove()},L=I=>{err__$p("Authentication failed. Result:",I),U({status:ThreeDSStatus.FAILURE,cleanup:C})},y=I=>{err__$p("Adyen error:",I),U({status:ThreeDSStatus.FAILURE,cleanup:C})},_=()=>{U({status:ThreeDSStatus.CANCELLED,cleanup:C})};M.addEventListener("click",_);const N=(I,x,V)=>{R.remove(),U({status:ThreeDSStatus.SUCCESS,additionalDetails:I,cleanup:C})};getAdyenCheckout().then(I=>I({clientKey:T["op-adyen-client-key"],environment:T["op-adyen-environment"],locale:A,countryCode:P,onAdditionalDetails:N,onPaymentFailed:L,onError:y})).then(I=>{I.createFromAction(D,{challengeWindowSize:"03"}).mount(O)})})},determineLocale=S=>{const T=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,A=S??T,P=AdyenLocale.safeParse(A);return P.success?(log__$q(`Resolved locale: ${P.data}`),P.data):(err__$p(`Resolved invalid locale: ${A}. Defaulting to en-US.`),"en-US")},checkIfRequiresAdyen3ds=S=>S?.["op-adyen-action"]!==void 0,runAdyen3dsFlow=async(S,T,A)=>{const P=parseResponseHeaders$2(T),O=document.createElement("div");O.id="adyen-container";const{host:R,iframe:M,cancelButton:D}=createAndOpenFrame("http://example.com");M.replaceWith(O);const U=await handleAdyen3ds({headers:P,locale:determineLocale(A),countryCode:S,component:O,host:R,cancelButton:D});if(U.cleanup(),U.status===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed");if(U.status===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(U.status===ThreeDSStatus.SUCCESS){if(!U.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return log__$q("3DS verification succeeded"),{existing_cc:{additional_details:U.additionalDetails.data}}}else assertNever(U.status)},ApplePayCpm$1=objectType({provider:literalType("apple_pay"),processor_name:literalType("adyen"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType()})}),GooglePayCpm$1=objectType({provider:literalType("google_pay"),processor_name:literalType("adyen"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType(),google_pay_merchant_id:stringType().nullish()})}),{log__:log__$p}=createOjsFlowLoggers("awx-apple-pay");async function handleValidateMerchant$2(S,T){try{const O=(await preparePaymentFlow(T.connection,{checkout_payment_method:T.checkoutPaymentMethod,processor_specific_metadata:{apple_pay_session:{validation_url:S.validationURL,initiative_context:window.location.hostname,their_account_id:T.processorAccount.processor_account_id}}})).next_action_metadata?.apple_pay_session;if(!O)throw new Error("No session data received from payment flow");T.session.completeMerchantValidation(O),track("apple_pay_complete_merchant_validation",{...O})}catch(A){throw T.session.abort(),A}}async function handlePaymentAuthorized$2(S,T){try{const A=S.payment,P=fillEmptyFormInputsWithApplePay(T.nonCdeFormInputs,A),O=validateNonCdeFormFieldsForCC(P,T.formCallbacks.get.onValidationError,T.defaultFieldValues);track("billing_details_received",{...O}),await startPaymentFlow(T.connection,{payment_provider:T.checkoutPaymentMethod.provider,checkout_payment_method:T.checkoutPaymentMethod,...createCustomerFieldsFromForm(O,T.prefill.checkout_settings)});const R=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{payment_provider:T.checkoutPaymentMethod.provider,browser_info:getFraudMetadata(),mobile_wallet_payment_data:{encrypted_payment_token:JSON.stringify(A.token)}}});if(log__$p("[1st] Confirm payment flow response",R),!R.payment_methods?.[0]?.id)throw new Error("No PM ID found");const D={status:ApplePaySession.STATUS_SUCCESS};return T.session.completePayment(D),performSimpleCheckoutOrSetup({logPrefix:"adyen-applepay",anyCdeConnection:T.connection,checkoutPaymentMethod:T.checkoutPaymentMethod,requiredFormFields:O,confirmResult:R,usePayFirstFlow:!1})}catch(A){const P={status:ApplePaySession.STATUS_FAILURE};throw T.session.completePayment(P),A}}const{log__:log__$o,err__:err__$o}=createOjsFlowLoggers("adyen-apple-pay"),initAdyenApplePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.adyen,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$1);if(!P)return A;if(log__$o("Loading Apple Pay script"),await loadApplePayScript(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return log__$o("Apple Pay is not available on this device/browser"),A;if(log__$o("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return log__$o("No active cards available for Apple Pay"),A;if(!P.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0),L=async y=>{try{await OjsFlows.adyenApplePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{...y,initialPreview:C},initResult:void 0})}catch(_){err__$o("Apple Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.adyen,isAvailable:!0,isLoading:!1,startFlow:L}}),runAdyenApplePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,customParams:P,formCallbacks:O})=>{const R=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$1),{overridePaymentRequest:M,initialPreview:D}=P,U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=getApplePayPaymentRequest({overridePaymentRequest:M,initialPreview:D,prefill:{...C},defaultLabel:R?.metadata?.processor_account_name}),_=new ApplePaySession(3,y),N={session:_,connection:S.anyCdeConnection,checkoutPaymentMethod:T,nonCdeFormInputs:A,processorAccount:R.metadata,prefill:C,isSetupMode:L,baseUrl:S.baseUrl,formCallbacks:O,defaultFieldValues:P?.defaultFieldValues};return track("apple_pay_flow_started",{processor_name:T.processor_name,prefill:excludeProps(C,["brand"]),overridePaymentRequest:M}),new Promise((I,x)=>{const V=()=>{log__$o("Payment cancelled by user"),x(new Error("Payment cancelled by user"))};_.onvalidatemerchant=async k=>{try{await handleValidateMerchant$2(k,N)}catch(F){x(F)}},_.onpaymentmethodselected=async()=>{const k=await getCheckoutPreviewAmount(U,C.token,L,void 0),F={newTotal:createApplePayTotal({overridePaymentRequest:P.overridePaymentRequest,initialPreview:k,defaultLabel:R?.metadata?.processor_account_name,prefill:C}).total};_.completePaymentMethodSelection(F)},_.onpaymentauthorized=async k=>{track("apple_pay_payment_authorized");try{const F=await handlePaymentAuthorized$2(k,N);I(F)}catch(F){x(F)}},_.oncancel=V,_.begin()}).catch(I=>{throw err__$o("Apple Pay payment error",I),track("apple_pay_payment_error",{error:I}),I})}),{log__:log__$n,err__:err__$n}=createOjsFlowLoggers("adyen-google-pay"),initAdyenGooglePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.adyen,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$1);if(!P)return A;log__$n("Google Pay CPM",P);const O=P.metadata;if(!O.processor_account_id)return err__$n("No gateway merchant ID found in processor account"),A;if(log__$n("Loading Google Pay script"),await loadGooglePayScript(),!window.google?.payments?.api)return err__$n("Google Pay SDK not loaded properly"),A;if(await getGooglePayEnvironment(S.baseUrl)==="PRODUCTION"&&!O.google_pay_merchant_id)return err__$n("Google Pay merchant ID is required for production environment"),A;log__$n("Google Pay SDK loaded",window.google.payments);const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0);try{const y=getPaymentDataRequest({prefill:D,gateway:"adyen",gatewayMerchantId:O.processor_account_id,merchantName:O.processor_account_name,merchantId:O.google_pay_merchant_id??"",initialPreview:C}),_=await getGooglePaymentsClient(S.baseUrl,y),{result:N}=await _.isReadyToPay(y);if(!N)return log__$n("Google Pay is not available for this user"),A}catch(y){return err__$n("Error checking Google Pay availability",y),A}const L=async y=>{try{OjsFlows.adyenGooglePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{...y,initialPreview:C}})}catch(_){err__$n("Google Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.adyen,isAvailable:!0,isLoading:!1,startFlow:L}}),runAdyenGooglePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$n("Starting Google Pay flow...");const R=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$1),{overridePaymentRequest:M}=O,D=R.metadata;if(!D.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=await getCheckoutPreviewAmount(U,C.token,L,void 0),_=getPaymentDataRequest({prefill:C,gateway:"adyen",gatewayMerchantId:D.processor_account_id,merchantName:D.processor_account_name,merchantId:D.google_pay_merchant_id??"",initialPreview:y,overridePaymentRequest:M});track("google_pay_flow_started",{processor_name:R.processor_name,prefill:excludeProps(C,["brand"]),overridePaymentRequest:M});const N=await getGooglePaymentsClient(S.baseUrl,_);try{const I=await N.loadPaymentData(_);log__$n("Google Pay Payment data",I);const x=fillEmptyFormInputsWithGooglePay(A,I),V=validateNonCdeFormFieldsForCC(x,P.get.onValidationError,O?.defaultFieldValues);if(track("billing_details_received",{...V}),!I.paymentMethodData?.tokenizationData?.token)throw new Error("No payment token received from Google Pay");const F=await startPaymentFlow(U,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(V,C.checkout_settings)}),W=parseAirwallexStartPaymentFlowResponse(F);log__$n("Start flow next actions",W);let ee=await confirmPaymentFlow(U,{secure_token:C.token,processor_specific_metadata:{payment_provider:T.provider,browser_info:getFraudMetadata(),mobile_wallet_payment_data:{encrypted_payment_token:I.paymentMethodData?.tokenizationData?.token}}});log__$n("[1st] Confirm payment flow response",ee);let ne=ee.payment_methods?.[0]?.id;const le=ee.required_user_actions?.find(Re=>Re.type==="adyen-3ds");if(le&&le.redirect_url){log__$n("Adyen 3DS Required, starting verification...",le);const{status:Re}=await start3dsVerification({url:le.redirect_url,baseUrl:S.baseUrl});if(log__$n(`╰ Adyen 3DS verification completed [Status: ${Re}]`),Re===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(Re===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed")}if(le&&!ne&&(ee=await confirmPaymentFlow(U,{secure_token:C.token,their_pm_id:le.their_pm_id,processor_specific_metadata:{payment_provider:T.provider}}),log__$n("[2nd] Confirm payment flow response after 3DS",ee),ne=ee.payment_methods?.[0]?.id),!ne)throw new Error("No payment method ID found");return performSimpleCheckoutOrSetup({logPrefix:"adyen-googlepay",anyCdeConnection:U,checkoutPaymentMethod:T,requiredFormFields:V,confirmResult:ee,usePayFirstFlow:!1})}catch(I){throw err__$n("Google Pay payment error",I),track("google_pay_payment_error",{error:I}),new Error(I?.message??"Unknown error")}}),{log__:log__$m,err__:err__$m}=createOjsFlowLoggers("awx-ach"),runAirwallexACHFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{const R=validateNonCdeFormFieldsForCC(A,P.get.onValidationError),M=S.anyCdeConnection,D=await getPrefill(M),U=O.verificationMethod??"plaid";let C=null;if(U==="micro_deposit"){log__$m("Micro deposit verification selected, showing form...");try{C=await createAndOpenMicroDepositForm("ach_direct_debit",{width:"450px",height:"400px",baseUrl:S.baseUrl}),log__$m("Micro deposit data collected")}catch{throw log__$m("Micro deposit form cancelled"),new Error("Micro deposit form cancelled")}}const L=await startPaymentFlow(M,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(R,D.checkout_settings),customer_language:detectLanguage()}),_=parseAirwallexStartPaymentFlowResponse(L)?.consent_id,I=(await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_,verification_method:U,direct_debit_data:{type:"ach_direct_debit",ach_direct_debit:{business_account:O.isBusinessAccount??!1,owner_name:getFullName(R[FieldName.FIRST_NAME],R[FieldName.LAST_NAME]),owner_email:R[FieldName.EMAIL],account_number:C?.account_number,aba_routing_number:C?.aba_routing_number}}}})).required_user_actions?.find(V=>V.type==="airwallex_payment_consent")?.redirect_url;if(I){log__$m("Plaid verification Required, starting verification...");const{status:V}=await start3dsVerification({url:I,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"ACH verification"});if(log__$m(`╰ Plaid verification completed [Status: ${V}]`),V===ThreeDSStatus.CANCELLED)throw new Error("Plaid verification cancelled");if(V===ThreeDSStatus.FAILURE)throw new Error("Plaid verification failed")}const x=await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_}});try{return performSimpleCheckoutOrSetup({logPrefix:"awx-ach",anyCdeConnection:M,checkoutPaymentMethod:T,requiredFormFields:R,confirmResult:x,usePayFirstFlow:!1})}catch(V){throw err__$m("ACH payment error",V),track("checkout_error",{error:V}),new Error(V?.message??"Unknown error")}}),{log__:log__$l}=createOjsFlowLoggers("awx-apple-pay");async function handleValidateMerchant$1(S,T){try{const O=(await preparePaymentFlow(T.connection,{checkout_payment_method:T.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:S.validationURL,initiative_context:window.location.hostname,their_account_id:T.processorAccount.processor_account_id}}})).next_action_metadata?.apple_pay_session;if(!O)throw new Error("No session data received from payment flow");T.session.completeMerchantValidation(O),track("apple_pay_complete_merchant_validation",{...O})}catch(A){throw T.session.abort(),A}}async function handle3DS(S,T){if(!S.redirect_url)throw new Error("No redirect URL found");log__$l("3DS Required, starting verification...",S);const{status:A}=await start3dsVerification({url:S.redirect_url,baseUrl:T.baseUrl});if(log__$l(`╰ 3DS verification completed [Status: ${A}]`),A===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(A===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed");const P=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{their_pm_id:S.their_pm_id,airwallex_consent_id:S.consent_id,payment_provider:T.checkoutPaymentMethod.provider}});return log__$l("[2nd] Confirm payment flow response",P),P}async function handlePaymentAuthorized$1(S,T){try{const A=S.payment,P=fillEmptyFormInputsWithApplePay(T.nonCdeFormInputs,A),O=validateNonCdeFormFieldsForCC(P,T.formCallbacks.get.onValidationError,T.defaultFieldValues);track("billing_details_received",{...O});const D=(await startPaymentFlow(T.connection,{payment_provider:T.checkoutPaymentMethod.provider,checkout_payment_method:T.checkoutPaymentMethod,...createCustomerFieldsFromForm(O,T.prefill.checkout_settings)})).required_user_actions[0].consent_id;if(!D)throw new Error("No consent ID received from payment flow");let U=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{payment_provider:T.checkoutPaymentMethod.provider,airwallex_consent_id:D,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(A.token)}}}});log__$l("[1st] Confirm payment flow response",U);let C=U.payment_methods?.[0]?.id;const L=U.required_user_actions?.find(_=>_.type==="airwallex_payment_consent");if(L?.redirect_url&&L.consent_id&&L.their_pm_id&&(U=await handle3DS(L,T),C=U.payment_methods?.[0]?.id),!C)throw new Error("No PM ID found");const y={status:ApplePaySession.STATUS_SUCCESS};return T.session.completePayment(y),performSimpleCheckoutOrSetup({logPrefix:"awx-applepay",anyCdeConnection:T.connection,checkoutPaymentMethod:T.checkoutPaymentMethod,requiredFormFields:O,confirmResult:U,usePayFirstFlow:!1})}catch(A){const P={status:ApplePaySession.STATUS_FAILURE};throw T.session.completePayment(P),A}}const{log__:log__$k,err__:err__$l}=createOjsFlowLoggers("awx-apple-pay"),initAirwallexApplePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$2);if(!P)return A;if(log__$k("Loading Apple Pay script"),await loadApplePayScript(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return log__$k("Apple Pay is not available on this device/browser"),A;if(log__$k("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return log__$k("No active cards available for Apple Pay"),A;if(!P.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0),L=async y=>{try{await OjsFlows.airwallexApplePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{...y,initialPreview:C},initResult:void 0})}catch(_){err__$l("Apple Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:L}}),runAirwallexApplePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,customParams:P,formCallbacks:O})=>{const R=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$2),{overridePaymentRequest:M}=P,D=S.anyCdeConnection,U=await getPrefill(D),C=U.mode==="setup",L=getApplePayPaymentRequest({overridePaymentRequest:M,initialPreview:P.initialPreview,prefill:{...U},defaultLabel:R?.metadata?.processor_account_name}),y=new ApplePaySession(3,L),_={session:y,connection:S.anyCdeConnection,checkoutPaymentMethod:T,nonCdeFormInputs:A,processorAccount:R.metadata,prefill:U,isSetupMode:C,baseUrl:S.baseUrl,formCallbacks:O,defaultFieldValues:P?.defaultFieldValues};return track("apple_pay_flow_started",{processor_name:T.processor_name,prefill:excludeProps(U,["brand"]),overridePaymentRequest:M}),new Promise((N,I)=>{const x=()=>{log__$k("Payment cancelled by user"),I(new Error("Payment cancelled by user"))};y.oncancel=x,y.onvalidatemerchant=async V=>{try{await handleValidateMerchant$1(V,_)}catch(k){I(k)}},y.onpaymentmethodselected=async()=>{const V=await getCheckoutPreviewAmount(D,U.token,C,void 0),k={newTotal:createApplePayTotal({overridePaymentRequest:P.overridePaymentRequest,initialPreview:V,defaultLabel:R?.metadata?.processor_account_name,prefill:U}).total};y.completePaymentMethodSelection(k)},y.onpaymentauthorized=async V=>{track("apple_pay_payment_authorized");try{const k=await handlePaymentAuthorized$1(V,_);N(k)}catch(k){I(k)}},y.begin()}).catch(N=>{throw err__$l("Apple Pay payment error",N),track("apple_pay_payment_error",{error:N}),N})}),{log__:log__$j,err__:err__$k}=createOjsFlowLoggers("awx-google-pay"),initAirwallexGooglePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$2);if(!P)return A;log__$j("Google Pay CPM",P);const O=P.metadata;if(!O.processor_account_id)return err__$k("No gateway merchant ID found in processor account"),A;if(log__$j("Loading Google Pay script"),await loadGooglePayScript(),!window.google?.payments?.api)return err__$k("Google Pay SDK not loaded properly"),A;if(await getGooglePayEnvironment(S.baseUrl)==="PRODUCTION"&&!O.google_pay_merchant_id)return err__$k("Google Pay merchant ID is required for production environment"),A;log__$j("Google Pay SDK loaded",window.google.payments);const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0);try{const y=getPaymentDataRequest({prefill:D,gateway:"airwallex",gatewayMerchantId:O.processor_account_id,merchantName:O.processor_account_name,merchantId:O.google_pay_merchant_id??"",initialPreview:C}),_=await getGooglePaymentsClient(S.baseUrl,y),{result:N}=await _.isReadyToPay(y);if(!N)return log__$j("Google Pay is not available for this user"),A}catch(y){return err__$k("Error checking Google Pay availability",y),A}const L=async y=>{try{OjsFlows.airwallexGooglePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{...y,initialPreview:C}})}catch(_){err__$k("Google Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:L}}),runAirwallexGooglePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$j("Starting Google Pay flow...");const R=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$2),{overridePaymentRequest:M}=O,D=R.metadata;if(!D.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=await getCheckoutPreviewAmount(U,C.token,L,void 0),_=getPaymentDataRequest({prefill:C,gateway:"airwallex",gatewayMerchantId:D.processor_account_id,merchantName:D.processor_account_name,merchantId:D.google_pay_merchant_id??"",initialPreview:y,overridePaymentRequest:M});track("google_pay_flow_started",{processor_name:R.processor_name,prefill:excludeProps(C,["brand"]),overridePaymentRequest:M});const N=await getGooglePaymentsClient(S.baseUrl,_);try{const I=await N.loadPaymentData(_);log__$j("Google Pay Payment data",I);const x=fillEmptyFormInputsWithGooglePay(A,I),V=validateNonCdeFormFieldsForCC(x,P.get.onValidationError,O?.defaultFieldValues);log__$j("___",V),track("billing_details_received",{...V});const k=I.paymentMethodData?.tokenizationData?.token;if(!k)throw new Error("No payment token received from Google Pay");const F=await startPaymentFlow(U,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(V,C.checkout_settings)}),W=parseAirwallexStartPaymentFlowResponse(F);log__$j("Start flow next actions",W);let ee=await confirmPaymentFlow(U,{secure_token:C.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:W?.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:k}}}});log__$j("[1st] Confirm payment flow response",ee);let ne=ee.payment_methods?.[0]?.id;const le=ee.required_user_actions?.find(Re=>Re.type==="airwallex_payment_consent");if(le&&le.redirect_url){log__$j("3DS Required, starting verification...",le);const{status:Re}=await start3dsVerification({url:le.redirect_url,baseUrl:S.baseUrl});if(log__$j(`╰ 3DS verification completed [Status: ${Re}]`),Re===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(Re===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed")}if(le&&!ne&&(ee=await confirmPaymentFlow(U,{secure_token:C.token,their_pm_id:le.their_pm_id,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:le.consent_id}}),log__$j("[2nd] Confirm payment flow response",ee),ne=ee.payment_methods?.[0]?.id),!ne)throw new Error("No PM ID found");return performSimpleCheckoutOrSetup({logPrefix:"awx-googlepay",anyCdeConnection:U,checkoutPaymentMethod:T,requiredFormFields:V,confirmResult:ee,usePayFirstFlow:!1})}catch(I){throw err__$k("Google Pay payment error",I),track("google_pay_payment_error",{error:I}),new Error(I?.message??"Unknown error")}}),{log__:log__$i,err__:err__$j}=createOjsFlowLoggers("klarna"),AirwallexKlarnaCpm=objectType({provider:literalType("klarna"),metadata:objectType({}).nullish(),processor_name:literalType("airwallex")}),initAirwallexKlarnaFlow=async({context:S,formCallbacks:T})=>{const A=findCpmMatchingType(S.checkoutPaymentMethods,AirwallexKlarnaCpm);if(!A)throw new Error("Klarna CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:O=>OjsFlows.airwallexKlarna.run({context:S,checkoutPaymentMethod:A,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:O??{}})}},runAirwallexKlarnaFlow=addBasicCheckoutCallbackHandlers(async({context:S,nonCdeFormInputs:T,checkoutPaymentMethod:A,formCallbacks:P,customParams:O})=>{try{log__$i("Running Klarna flow...",O);const R=S.anyCdeConnection,M=await getPrefill(R),D=!1;log__$i("Verifying CPM...");const U=AirwallexKlarnaCpm.parse(A);log__$i("├ Validating non-CDE form fields");const C=validateNonCdeFormFieldsForCC(T,P.get.onValidationError,{...D?generateAnonymousValues():void 0,...M.checkout_settings}),L=createCustomerFieldsFromForm(C,M.checkout_settings);log__$i("New customer fields",L);const y=await startPaymentFlow(R,{payment_provider:A.provider,checkout_payment_method:A,...createCustomerFieldsFromForm(C,M.checkout_settings)});return console.log("startPaymentFlowResponse",y),performSimpleCheckoutOrSetup({logPrefix:"klarna",anyCdeConnection:R,checkoutPaymentMethod:U,requiredFormFields:C,confirmResult:{payment_methods:[]},usePayFirstFlow:!1})}catch(R){throw err__$j("Klarna payment error",R),track("checkout_error",{payment_method:"klarna",error:R}),new Error(R?.message??"Unknown error")}}),ApplePayCpm=objectType({provider:literalType("apple_pay"),processor_name:literalType("authorize_net"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType()})}),GooglePayCpm=objectType({provider:literalType("google_pay"),processor_name:literalType("authorize_net"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType(),google_pay_merchant_id:stringType().nullish()})});async function handleValidateMerchant(S,T){try{const O=(await preparePaymentFlow(T.connection,{checkout_payment_method:T.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:S.validationURL,initiative_context:window.location.hostname,their_account_id:T.processorAccount.processor_account_id}}})).next_action_metadata?.apple_pay_session;if(!O)throw new Error("No session data received from payment flow");T.session.completeMerchantValidation(O),track("apple_pay_complete_merchant_validation",{...O})}catch(A){throw T.session.abort(),A}}async function handlePaymentAuthorized(S,T){try{const A=S.payment,P=fillEmptyFormInputsWithApplePay(T.nonCdeFormInputs,A),O=validateNonCdeFormFieldsForCC(P,T.formCallbacks.get.onValidationError);track("billing_details_received",{...O}),await startPaymentFlow(T.connection,{payment_provider:T.checkoutPaymentMethod.provider,checkout_payment_method:T.checkoutPaymentMethod,...createCustomerFieldsFromForm(O,T.prefill.checkout_settings),customer_language:detectLanguage()});const R={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(A.token.paymentData))},M=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{payment_provider:T.checkoutPaymentMethod.provider,mobile_wallet_payment_data:R}});if(!M.payment_methods?.[0]?.id)throw new Error("No PM ID found");const U={status:ApplePaySession.STATUS_SUCCESS};return T.session.completePayment(U),performSimpleCheckoutOrSetup({logPrefix:"authnet-applepay",anyCdeConnection:T.connection,checkoutPaymentMethod:T.checkoutPaymentMethod,requiredFormFields:O,confirmResult:M,usePayFirstFlow:!1})}catch(A){const P={status:ApplePaySession.STATUS_FAILURE};throw T.session.completePayment(P),A}}const{log__:log__$h,err__:err__$i}=createOjsFlowLoggers("authnet-applepay"),initAuthnetApplePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm);if(!P)return A;if(log__$h("Loading Apple Pay script"),await loadApplePayScript(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return log__$h("Apple Pay is not available on this device/browser"),A;if(!await ApplePaySession.canMakePayments())return log__$h("No active cards available for Apple Pay"),A;if(!P.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0),L=async y=>{try{await OjsFlows.authorizeNetApplePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{...y,initialPreview:C},initResult:void 0})}catch(_){err__$i("Apple Pay payment error",_),track("apple_pay_payment_error",{error:_}),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:L}}),runAuthnetApplePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,customParams:P,formCallbacks:O})=>{const{initialPreview:R,overridePaymentRequest:M}=P,D=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm),U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=getApplePayPaymentRequest({overridePaymentRequest:M,initialPreview:R,prefill:C,defaultLabel:D?.metadata?.processor_account_name});track("apple_pay_flow_started",{processor_name:T.processor_name,prefill:C,overridePaymentRequest:M});const _=new ApplePaySession(3,y),N={session:_,connection:S.anyCdeConnection,checkoutPaymentMethod:T,nonCdeFormInputs:A,processorAccount:T.metadata,prefill:C,isSetupMode:L,baseUrl:S.baseUrl,formCallbacks:O};return new Promise((I,x)=>{_.oncancel=()=>{log__$h("Payment cancelled by user"),x(new Error("Payment cancelled by user"))},_.onvalidatemerchant=async V=>{try{await handleValidateMerchant(V,N)}catch(k){x(k)}},_.onpaymentmethodselected=async()=>{const V=await getCheckoutPreviewAmount(U,C.token,L,void 0),k={newTotal:createApplePayTotal({overridePaymentRequest:P.overridePaymentRequest,initialPreview:V,defaultLabel:D?.metadata?.processor_account_name,prefill:C}).total};_.completePaymentMethodSelection(k)},_.onpaymentauthorized=async V=>{track("apple_pay_payment_authorized");try{const k=await handlePaymentAuthorized(V,N);I(k)}catch(k){x(k)}},_.begin()}).catch(I=>{throw err__$i("Apple Pay payment error",I),track("apple_pay_payment_error",{error:I}),I})}),{log__:log__$g,err__:err__$h}=createOjsFlowLoggers("authnet-googlepay"),initAuthnetGooglePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{log__$g("Initializing Authnet GooglePay flow");const A={processor:PaymentProcessor.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm);if(!P)return A;log__$g("Google Pay CPM",P);const O=P.metadata;if(!O.processor_account_id)return err__$h("No gateway merchant ID found in processor account"),A;if(log__$g("Loading Google Pay script"),await loadGooglePayScript(),!window.google?.payments?.api)return err__$h("Google Pay SDK not loaded properly"),A;log__$g("Google Pay SDK loaded",window.google.payments);const R=S.anyCdeConnection,M=await getPrefill(R),D=M.mode==="setup",U=await getCheckoutPreviewAmount(R,M.token,D,void 0);try{const L=getPaymentDataRequest({prefill:M,gateway:"authorizenet",gatewayMerchantId:O.processor_account_id,merchantName:O.processor_account_name,merchantId:O.google_pay_merchant_id??"",initialPreview:U}),y=await getGooglePaymentsClient(S.baseUrl,L),{result:_}=await y.isReadyToPay(L);if(!_)return log__$g("Google Pay is not available for this user"),A}catch(L){return err__$h("Error checking Google Pay availability",L),A}const C=async L=>{try{OjsFlows.authorizeNetGooglePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{...L,initialPreview:U}})}catch(y){err__$h("Google Pay payment error",y),track("google_pay_payment_error",{error:y}),T.get.onCheckoutError(y?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:C}}),runAuthnetGooglePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,nonCdeFormInputs:T,checkoutPaymentMethod:A,formCallbacks:P,customParams:O})=>{const{overridePaymentRequest:R}=O,D=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm).metadata,U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=await getCheckoutPreviewAmount(U,C.token,L,void 0),_=getPaymentDataRequest({prefill:C,gateway:"authorizenet",gatewayMerchantId:D.processor_account_id,merchantName:D.processor_account_name,merchantId:D.google_pay_merchant_id??"",initialPreview:y,overridePaymentRequest:R});track("google_pay_flow_started",{processor_name:A.processor_name,prefill:C,overridePaymentRequest:R});const N=await getGooglePaymentsClient(S.baseUrl,_);try{const I=await N.loadPaymentData(_);log__$g("Google Pay Payment data",I);const x=fillEmptyFormInputsWithGooglePay(T,I),V=validateNonCdeFormFieldsForCC(x,P.get.onValidationError);track("billing_details_received",{...V});const k=I.paymentMethodData?.tokenizationData?.token;if(!k)throw new Error("No payment token received from Google Pay");const F=await startPaymentFlow(U,{payment_provider:A.provider,checkout_payment_method:A,...createCustomerFieldsFromForm(V,C.checkout_settings),customer_language:detectLanguage()});log__$g("Start payment flow response",F);const W=await confirmPaymentFlow(U,{secure_token:C.token,processor_specific_metadata:{payment_provider:A.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(k)}}});if(!W.payment_methods?.[0]?.id)throw new Error("No PM ID found");return performSimpleCheckoutOrSetup({logPrefix:"authnet-googlepay",anyCdeConnection:U,checkoutPaymentMethod:A,requiredFormFields:V,confirmResult:W,usePayFirstFlow:!1})}catch(I){throw err__$h("Google Pay payment error",I),track("google_pay_payment_error",{error:I}),new Error(I?.message??"Unknown error")}}),{log__:log__$f,err__:err__$g}=createOjsFlowLoggers("cybs-frame"),attachDeviceDataCollector=(S,T)=>{const A=document.createElement("iframe");A.name="cardinal_collection_iframe",A.style.display="none",A.style.width="10px",A.style.height="10px";const P=document.createElement("form");P.action=S,P.method="POST",P.target=A.name;const O=document.createElement("input");return O.type="hidden",O.name="JWT",O.value=T,P.appendChild(O),document.body.appendChild(A),document.body.appendChild(P),{form:P,detach:()=>{document.body.removeChild(A),document.body.removeChild(P)}}},runDeviceDataCollection=async S=>new Promise((T,A)=>{const{postUrl:P,accessToken:O}=S,R=new URL(P).origin,{form:M,detach:D}=attachDeviceDataCollector(P,O);log__$f("Attached device data collector");const U=L=>{if(L.origin!==R)return;const y=JSON.parse(L.data);if(log__$f("Received event from device data collector:",y),y.MessageType==="profile.completed"){T(y),C();return}},C=()=>{D(),window.removeEventListener("message",U)};try{window.addEventListener("message",U),log__$f("Attached listener to window"),M.submit(),log__$f("Submitted form")}catch(L){err__$g("Error submitting form:",L),C(),A(L)}}),runPayerAuth=S=>{const{stepUpUrl:T,accessToken:A,merchantData:P,iframe:O,host:R}=S,M=document.createElement("form");M.action=T,M.method="POST",M.target=O.name;const D=document.createElement("input");D.type="hidden",D.name="JWT",D.value=A;const U=document.createElement("input");return U.type="hidden",U.name="MD",U.value=P,M.appendChild(D),M.appendChild(U),R.appendChild(M),M},{log__:log__$e,err__:err__$f}=createOjsFlowLoggers("cybs"),CybersourceActionPayload=objectType({step_up_url:stringType(),access_token:stringType(),dd_url:nullOrUndefOr$1(stringType()),dd_token:nullOrUndefOr$1(stringType()),merchant_data:stringType()}),FRIENDLY_ERR="Unable to process your credit card. Please contact support for assistance.",parseResponseHeaders$1=S=>{const T=CybersourceActionPayload.safeParse(S);if(!T.success)throw err__$f(`Cybersource 3DS is required but user action is malformed. Got: ${JSON.stringify(S)}`),new Error(FRIENDLY_ERR);return T.data},checkIfRequiresCybersource3ds=S=>S.type==="cybersource_payer_auth",handleCybersource3ds=async S=>{const{stepUpUrl:T,accessToken:A,merchantData:P,iframe:O,host:R,cancelButton:M}=S,D=new URL(T).origin;return new Promise(U=>{const C=()=>{log__$e("Cleaning up Cybersource 3DS flow"),M.removeEventListener("click",L),R.remove()},L=()=>{log__$e("Cybersource 3DS cancelled"),U({status:ThreeDSStatus.CANCELLED,cleanup:C})},_=startPolling(O,x=>{log__$e("Cybersource 3DS completed with status:",x),U({status:x.status,cleanup:C}),N()},D,"ping-3ds-status",Ping3DSStatusResponse),N=handleEvents({elements:{host:R,cancelButton:M},pollingInterval:_,resolve:x=>{U({status:x.status,cleanup:C})}});M.addEventListener("click",L),runPayerAuth({stepUpUrl:T,accessToken:A,merchantData:P,iframe:O,host:R}).submit()})},runCybersource3dsFlow=async S=>{const T=parseResponseHeaders$1(S),{step_up_url:A,access_token:P,dd_url:O,dd_token:R,merchant_data:M}=T;if(O&&R){const y=await runDeviceDataCollection({postUrl:O,accessToken:R});log__$e("Device data collection completed with status:",y.Status)}else err__$f("No device data collection URL or token provided");const{host:D,iframe:U,cancelButton:C}=createAndOpenFrame("",{name:"cardinal_auth_iframe"});log__$e("Running Cybersource 3DS flow");const L=await handleCybersource3ds({stepUpUrl:A,accessToken:P,merchantData:M,iframe:U,host:D,cancelButton:C});if(L.cleanup(),L.status===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed");if(L.status===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(L.status===ThreeDSStatus.SUCCESS){log__$e("3DS verification succeeded");return}else assertNever(L.status)},{log__:log__$d,err__:err__$e}=createOjsFlowLoggers("pockyt-cc"),Pockyt3dsErrorResponseHeaders=objectType({"op-pockyt-3ds-url":stringType(),"op-pockyt-txn-no":stringType(),"op-pockyt-ref-no":stringType()}),parseResponseHeaders=S=>{const T=Pockyt3dsErrorResponseHeaders.safeParse(S);if(!T.success){const A="Unable to process your credit card. Please contact support for assistance.",P=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(S)}`;throw err__$e(P),new Error(A)}return T.data},parseVaultIdFrom3dsHref=S=>{try{const T=new URL(S??"").searchParams.get("vaultId");if(!T)throw new Error("No vault ID found in 3DS verification result");return log__$d(`3DS verification success. [Vault ID: ${T}]`),T}catch(T){const A="Error verifying 3DS verification result.";throw err__$e(A,`Resulting URL: ${S}.
213
+ Error: ${getErrorMessage(T)}`),new Error(A)}},runAirwallex3dsFlow=async(S,T)=>{const A=parseResponseHeaders$3(T),P=await start3dsVerificationStrict({url:A["op-airwallex-3ds-url"],baseUrl:S}),O=parseIntentIdFrom3dsHref(P.href??""),R=A["op-airwallex-initial-intent-id"];if(R!==O){const D="Unable to process your credit card. Please contact support for assistance.",U=`Intent ID from callback (${O}) does not match the initial intent ID (${R}).`;throw err__$q(U),new Error(D)}return{existing_cc:{initial_intent_id:O,consent_id:A["op-airwallex-consent-id"]}}},ApplePayCpm$2=objectType({provider:literalType("apple_pay"),processor_name:literalType("airwallex"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType()})}),GooglePayCpm$2=objectType({provider:literalType("google_pay"),processor_name:literalType("airwallex"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType(),google_pay_merchant_id:stringType().nullish()})}),loadApplePayScript=()=>loadScript({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession}),fillEmptyFormInputsWithApplePay=(S,T)=>{const A=T.token.paymentMethod.billingContact,P=T.billingContact,O=T.shippingContact,R={...S};if(A||P||O){R[FieldName.EMAIL]=R[FieldName.EMAIL]||A?.emailAddress||P?.emailAddress||O?.emailAddress||"op_unfilled@email.com",R[FieldName.COUNTRY]=R[FieldName.COUNTRY]||A?.countryCode||P?.countryCode||O?.countryCode||"US",R[FieldName.ZIP_CODE]=R[FieldName.ZIP_CODE]||A?.postalCode||P?.postalCode||O?.postalCode||"00000";const M=R[FieldName.FIRST_NAME]||A?.givenName||P?.givenName||O?.givenName||"",D=R[FieldName.LAST_NAME]||A?.familyName||P?.familyName||O?.familyName||"";M||D?(R[FieldName.FIRST_NAME]=M,R[FieldName.LAST_NAME]=D):(R[FieldName.FIRST_NAME]="_OP_UNKNOWN",R[FieldName.LAST_NAME]="")}return R};objectType({data:objectType({messageHeaders:recordType(stringType(),anyType()),errors:arrayType(anyType()),messageType:stringType(),messageBody:recordType(stringType(),anyType())}),origin:literalType("https://applepay.cdn-apple.com")});const createRecurringPaymentRequest=({total:S,prefill:T})=>{if(T.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:S.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${T.token}`,FRAME_BASE_URL).toString()};const A=T.line_items?.[0];if(!A)return;const P=A?.billing_interval==="week"?"day":A?.billing_interval,O=A?.billing_interval_count?A?.billing_interval==="week"?A?.billing_interval_count*7:A?.billing_interval_count:void 0;return{paymentDescription:A?.description??"",regularBilling:{amount:S.amount,label:A?.description??"",recurringPaymentIntervalUnit:P,recurringPaymentIntervalCount:O,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${T.token}`}},createApplePayTotal=({overridePaymentRequest:S,initialPreview:T,prefill:A,defaultLabel:P="Total"})=>{const O=(S?.amount?.currency??A?.currency??T.currency).toUpperCase(),M=((S?.amount?.amountAtom??T?.amountAtom??0)/100).toFixed(2);return{currencyCode:O,total:{label:S?.label??P??"Total",type:S?.pending?"pending":"final",amount:M}}},getApplePayPaymentRequest=({overridePaymentRequest:S,initialPreview:T,prefill:A,defaultLabel:P})=>{const{currencyCode:O,total:R}=createApplePayTotal({overridePaymentRequest:S,initialPreview:T,prefill:A,defaultLabel:P});let M={countryCode:"US",currencyCode:O,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email",...A.checkout_settings.require_full_shipping_address?["postalAddress"]:[]],supportedNetworks:["visa","masterCard","amex","discover","jcb"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],total:R};return A.line_items.every(U=>U.billing_interval&&U.billing_interval_count)&&(M.recurringPaymentRequest=createRecurringPaymentRequest({total:R,prefill:A})),S?.applePayPaymentRequest&&(typeof S.applePayPaymentRequest=="function"?M={...M,...S.applePayPaymentRequest(M)}:M={...M,...S.applePayPaymentRequest}),M},AdyenEnvironment=enumType(["test","live","live-us","live-in","live-apse","live-au"]),AdyenLocale=enumType(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:log__$q,err__:err__$p}=createOjsFlowLoggers("adyen-cc"),Adyen3dsResponseHeaders=objectType({"op-account-id":stringType(),"op-adyen-client-key":stringType(),"op-adyen-environment":AdyenEnvironment,"op-adyen-action":stringType()}),friendlyErr="Unable to process your credit card. Please contact support for assistance.",parseResponseHeaders$2=S=>{const T=Adyen3dsResponseHeaders.safeParse(S);if(!T.success)throw err__$p(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(S)}`),new Error(friendlyErr);return T.data},decodeAdyenAction=S=>JSON.parse(S),isAdyenAvailable=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,getAdyenCheckout=async()=>{log__$q("Waiting for Adyen SDK to load...");for(let S=0;S<10;S++)isAdyenAvailable()||await sleep(500);if(!isAdyenAvailable())throw err__$p("Adyen SDK not loaded properly"),new Error(friendlyErr);return log__$q("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},handleAdyen3ds=S=>{const{headers:T,locale:A,countryCode:P,component:O,host:R,cancelButton:M}=S,D=decodeAdyenAction(T["op-adyen-action"]);return log__$q(`Running Adyen 3DS flow for action type: ${D.type}`),new Promise(U=>{const C=()=>{log__$q("Cleaning up Adyen 3DS flow"),M.removeEventListener("click",_),R.remove()},L=I=>{err__$p("Authentication failed. Result:",I),U({status:ThreeDSStatus.FAILURE,cleanup:C})},y=I=>{err__$p("Adyen error:",I),U({status:ThreeDSStatus.FAILURE,cleanup:C})},_=()=>{U({status:ThreeDSStatus.CANCELLED,cleanup:C})};M.addEventListener("click",_);const N=(I,x,V)=>{R.remove(),U({status:ThreeDSStatus.SUCCESS,additionalDetails:I,cleanup:C})};getAdyenCheckout().then(I=>I({clientKey:T["op-adyen-client-key"],environment:T["op-adyen-environment"],locale:A,countryCode:P,onAdditionalDetails:N,onPaymentFailed:L,onError:y})).then(I=>{I.createFromAction(D,{challengeWindowSize:"03"}).mount(O)})})},determineLocale=S=>{const T=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,A=S??T,P=AdyenLocale.safeParse(A);return P.success?(log__$q(`Resolved locale: ${P.data}`),P.data):(err__$p(`Resolved invalid locale: ${A}. Defaulting to en-US.`),"en-US")},checkIfRequiresAdyen3ds=S=>S?.["op-adyen-action"]!==void 0,runAdyen3dsFlow=async(S,T,A)=>{const P=parseResponseHeaders$2(T),O=document.createElement("div");O.id="adyen-container";const{host:R,iframe:M,cancelButton:D}=createAndOpenFrame("http://example.com");M.replaceWith(O);const U=await handleAdyen3ds({headers:P,locale:determineLocale(A),countryCode:S,component:O,host:R,cancelButton:D});if(U.cleanup(),U.status===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed");if(U.status===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(U.status===ThreeDSStatus.SUCCESS){if(!U.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return log__$q("3DS verification succeeded"),{existing_cc:{additional_details:U.additionalDetails.data}}}else assertNever(U.status)},ApplePayCpm$1=objectType({provider:literalType("apple_pay"),processor_name:literalType("adyen"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType()})}),GooglePayCpm$1=objectType({provider:literalType("google_pay"),processor_name:literalType("adyen"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType(),google_pay_merchant_id:stringType().nullish()})}),{log__:log__$p}=createOjsFlowLoggers("awx-apple-pay");async function handleValidateMerchant$2(S,T){try{const O=(await preparePaymentFlow(T.connection,{checkout_payment_method:T.checkoutPaymentMethod,processor_specific_metadata:{apple_pay_session:{validation_url:S.validationURL,initiative_context:window.location.hostname,their_account_id:T.processorAccount.processor_account_id}}})).next_action_metadata?.apple_pay_session;if(!O)throw new Error("No session data received from payment flow");T.session.completeMerchantValidation(O),track("apple_pay_complete_merchant_validation",{...O})}catch(A){throw T.session.abort(),A}}async function handlePaymentAuthorized$2(S,T){try{const A=S.payment,P=fillEmptyFormInputsWithApplePay(T.nonCdeFormInputs,A),O=validateNonCdeFormFieldsForCC(P,T.formCallbacks.get.onValidationError,T.defaultFieldValues);track("billing_details_received",{...O}),await startPaymentFlow(T.connection,{payment_provider:T.checkoutPaymentMethod.provider,checkout_payment_method:T.checkoutPaymentMethod,...createCustomerFieldsFromForm(O,T.prefill.checkout_settings)});const R=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{payment_provider:T.checkoutPaymentMethod.provider,browser_info:getFraudMetadata(),mobile_wallet_payment_data:{encrypted_payment_token:JSON.stringify(A.token)}}});if(log__$p("[1st] Confirm payment flow response",R),!R.payment_methods?.[0]?.id)throw new Error("No PM ID found");const D={status:ApplePaySession.STATUS_SUCCESS};return T.session.completePayment(D),performSimpleCheckoutOrSetup({logPrefix:"adyen-applepay",anyCdeConnection:T.connection,checkoutPaymentMethod:T.checkoutPaymentMethod,requiredFormFields:O,confirmResult:R,usePayFirstFlow:!1})}catch(A){const P={status:ApplePaySession.STATUS_FAILURE};throw T.session.completePayment(P),A}}const{log__:log__$o,err__:err__$o}=createOjsFlowLoggers("adyen-apple-pay"),initAdyenApplePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.adyen,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$1);if(!P)return A;if(log__$o("Loading Apple Pay script"),await loadApplePayScript(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return log__$o("Apple Pay is not available on this device/browser"),A;if(log__$o("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return log__$o("No active cards available for Apple Pay"),A;if(!P.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0),L=async y=>{try{await OjsFlows.adyenApplePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{...y,initialPreview:C},initResult:void 0})}catch(_){err__$o("Apple Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.adyen,isAvailable:!0,isLoading:!1,startFlow:L}}),runAdyenApplePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,customParams:P,formCallbacks:O})=>{const R=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$1),{overridePaymentRequest:M,initialPreview:D}=P,U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=getApplePayPaymentRequest({overridePaymentRequest:M,initialPreview:D,prefill:{...C},defaultLabel:R?.metadata?.processor_account_name}),_=new ApplePaySession(3,y),N={session:_,connection:S.anyCdeConnection,checkoutPaymentMethod:T,nonCdeFormInputs:A,processorAccount:R.metadata,prefill:C,isSetupMode:L,baseUrl:S.baseUrl,formCallbacks:O,defaultFieldValues:P?.defaultFieldValues};return track("apple_pay_flow_started",{processor_name:T.processor_name,prefill:excludeProps(C,["brand"]),overridePaymentRequest:M}),new Promise((I,x)=>{const V=()=>{log__$o("Payment cancelled by user"),x(new Error("Payment cancelled by user"))};_.onvalidatemerchant=async k=>{try{await handleValidateMerchant$2(k,N)}catch(F){x(F)}},_.onpaymentmethodselected=async()=>{const k=await getCheckoutPreviewAmount(U,C.token,L,void 0),F={newTotal:createApplePayTotal({overridePaymentRequest:P.overridePaymentRequest,initialPreview:k,defaultLabel:R?.metadata?.processor_account_name,prefill:C}).total};_.completePaymentMethodSelection(F)},_.onpaymentauthorized=async k=>{track("apple_pay_payment_authorized");try{const F=await handlePaymentAuthorized$2(k,N);I(F)}catch(F){x(F)}},_.oncancel=V,_.begin()}).catch(I=>{throw err__$o("Apple Pay payment error",I),track("apple_pay_payment_error",{error:I}),I})}),{log__:log__$n,err__:err__$n}=createOjsFlowLoggers("adyen-google-pay"),initAdyenGooglePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.adyen,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$1);if(!P)return A;log__$n("Google Pay CPM",P);const O=P.metadata;if(!O.processor_account_id)return err__$n("No gateway merchant ID found in processor account"),A;if(log__$n("Loading Google Pay script"),await loadGooglePayScript(),!window.google?.payments?.api)return err__$n("Google Pay SDK not loaded properly"),A;if(await getGooglePayEnvironment(S.baseUrl)==="PRODUCTION"&&!O.google_pay_merchant_id)return err__$n("Google Pay merchant ID is required for production environment"),A;log__$n("Google Pay SDK loaded",window.google.payments);const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0);try{const y=getPaymentDataRequest({prefill:D,gateway:"adyen",gatewayMerchantId:O.processor_account_id,merchantName:O.processor_account_name,merchantId:O.google_pay_merchant_id??"",initialPreview:C}),_=await getGooglePaymentsClient(S.baseUrl,y),{result:N}=await _.isReadyToPay(y);if(!N)return log__$n("Google Pay is not available for this user"),A}catch(y){return err__$n("Error checking Google Pay availability",y),A}const L=async y=>{try{OjsFlows.adyenGooglePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{...y,initialPreview:C}})}catch(_){err__$n("Google Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.adyen,isAvailable:!0,isLoading:!1,startFlow:L}}),runAdyenGooglePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$n("Starting Google Pay flow...");const R=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$1),{overridePaymentRequest:M}=O,D=R.metadata;if(!D.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=await getCheckoutPreviewAmount(U,C.token,L,void 0),_=getPaymentDataRequest({prefill:C,gateway:"adyen",gatewayMerchantId:D.processor_account_id,merchantName:D.processor_account_name,merchantId:D.google_pay_merchant_id??"",initialPreview:y,overridePaymentRequest:M});track("google_pay_flow_started",{processor_name:R.processor_name,prefill:excludeProps(C,["brand"]),overridePaymentRequest:M});const N=await getGooglePaymentsClient(S.baseUrl,_);try{const I=await N.loadPaymentData(_);log__$n("Google Pay Payment data",I);const x=fillEmptyFormInputsWithGooglePay(A,I),V=validateNonCdeFormFieldsForCC(x,P.get.onValidationError,O?.defaultFieldValues);if(track("billing_details_received",{...V}),!I.paymentMethodData?.tokenizationData?.token)throw new Error("No payment token received from Google Pay");const F=await startPaymentFlow(U,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(V,C.checkout_settings)}),W=parseAirwallexStartPaymentFlowResponse(F);log__$n("Start flow next actions",W);let ee=await confirmPaymentFlow(U,{secure_token:C.token,processor_specific_metadata:{payment_provider:T.provider,browser_info:getFraudMetadata(),mobile_wallet_payment_data:{encrypted_payment_token:I.paymentMethodData?.tokenizationData?.token}}});log__$n("[1st] Confirm payment flow response",ee);let ne=ee.payment_methods?.[0]?.id;const le=ee.required_user_actions?.find(Re=>Re.type==="adyen-3ds");if(le&&le.redirect_url){log__$n("Adyen 3DS Required, starting verification...",le);const{status:Re}=await start3dsVerification({url:le.redirect_url,baseUrl:S.baseUrl});if(log__$n(`╰ Adyen 3DS verification completed [Status: ${Re}]`),Re===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(Re===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed")}if(le&&!ne&&(ee=await confirmPaymentFlow(U,{secure_token:C.token,their_pm_id:le.their_pm_id,processor_specific_metadata:{payment_provider:T.provider}}),log__$n("[2nd] Confirm payment flow response after 3DS",ee),ne=ee.payment_methods?.[0]?.id),!ne)throw new Error("No payment method ID found");return performSimpleCheckoutOrSetup({logPrefix:"adyen-googlepay",anyCdeConnection:U,checkoutPaymentMethod:T,requiredFormFields:V,confirmResult:ee,usePayFirstFlow:!1})}catch(I){throw err__$n("Google Pay payment error",I),track("google_pay_payment_error",{error:I}),new Error(I?.message??"Unknown error")}}),{log__:log__$m,err__:err__$m}=createOjsFlowLoggers("awx-ach"),runAirwallexACHFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{const R=validateNonCdeFormFieldsForCC(A,P.get.onValidationError),M=S.anyCdeConnection,D=await getPrefill(M),U=O.verificationMethod??"plaid";let C=null;if(U==="micro_deposit"){log__$m("Micro deposit verification selected, showing form...");try{C=await createAndOpenMicroDepositForm("ach_direct_debit",{width:"450px",height:"400px",baseUrl:S.baseUrl}),log__$m("Micro deposit data collected")}catch{throw log__$m("Micro deposit form cancelled"),new Error("Micro deposit form cancelled")}}const L=await startPaymentFlow(M,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(R,D.checkout_settings),customer_language:detectLanguage()}),_=parseAirwallexStartPaymentFlowResponse(L)?.consent_id,I=(await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_,verification_method:U,direct_debit_data:{type:"ach_direct_debit",ach_direct_debit:{business_account:O.isBusinessAccount??!1,owner_name:getFullName(R[FieldName.FIRST_NAME],R[FieldName.LAST_NAME]),owner_email:R[FieldName.EMAIL],account_number:C?.account_number,aba_routing_number:C?.aba_routing_number}}}})).required_user_actions?.find(V=>V.type==="airwallex_payment_consent")?.redirect_url;if(I){log__$m("Plaid verification Required, starting verification...");const{status:V}=await start3dsVerification({url:I,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"ACH verification"});if(log__$m(`╰ Plaid verification completed [Status: ${V}]`),V===ThreeDSStatus.CANCELLED)throw new Error("Plaid verification cancelled");if(V===ThreeDSStatus.FAILURE)throw new Error("Plaid verification failed")}const x=await confirmPaymentFlow(M,{secure_token:D.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:_}});try{return performSimpleCheckoutOrSetup({logPrefix:"awx-ach",anyCdeConnection:M,checkoutPaymentMethod:T,requiredFormFields:R,confirmResult:x,usePayFirstFlow:!1})}catch(V){throw err__$m("ACH payment error",V),track("checkout_error",{error:V}),new Error(V?.message??"Unknown error")}}),{log__:log__$l}=createOjsFlowLoggers("awx-apple-pay");async function handleValidateMerchant$1(S,T){try{const O=(await preparePaymentFlow(T.connection,{checkout_payment_method:T.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:S.validationURL,initiative_context:window.location.hostname,their_account_id:T.processorAccount.processor_account_id}}})).next_action_metadata?.apple_pay_session;if(!O)throw new Error("No session data received from payment flow");T.session.completeMerchantValidation(O),track("apple_pay_complete_merchant_validation",{...O})}catch(A){throw T.session.abort(),A}}async function handle3DS(S,T){if(!S.redirect_url)throw new Error("No redirect URL found");log__$l("3DS Required, starting verification...",S);const{status:A}=await start3dsVerification({url:S.redirect_url,baseUrl:T.baseUrl});if(log__$l(`╰ 3DS verification completed [Status: ${A}]`),A===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(A===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed");const P=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{their_pm_id:S.their_pm_id,airwallex_consent_id:S.consent_id,payment_provider:T.checkoutPaymentMethod.provider}});return log__$l("[2nd] Confirm payment flow response",P),P}async function handlePaymentAuthorized$1(S,T){try{const A=S.payment,P=fillEmptyFormInputsWithApplePay(T.nonCdeFormInputs,A),O=validateNonCdeFormFieldsForCC(P,T.formCallbacks.get.onValidationError,T.defaultFieldValues);track("billing_details_received",{...O});const D=(await startPaymentFlow(T.connection,{payment_provider:T.checkoutPaymentMethod.provider,checkout_payment_method:T.checkoutPaymentMethod,...createCustomerFieldsFromForm(O,T.prefill.checkout_settings)})).required_user_actions[0].consent_id;if(!D)throw new Error("No consent ID received from payment flow");let U=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{payment_provider:T.checkoutPaymentMethod.provider,airwallex_consent_id:D,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(A.token)}}}});log__$l("[1st] Confirm payment flow response",U);let C=U.payment_methods?.[0]?.id;const L=U.required_user_actions?.find(_=>_.type==="airwallex_payment_consent");if(L?.redirect_url&&L.consent_id&&L.their_pm_id&&(U=await handle3DS(L,T),C=U.payment_methods?.[0]?.id),!C)throw new Error("No PM ID found");const y={status:ApplePaySession.STATUS_SUCCESS};return T.session.completePayment(y),performSimpleCheckoutOrSetup({logPrefix:"awx-applepay",anyCdeConnection:T.connection,checkoutPaymentMethod:T.checkoutPaymentMethod,requiredFormFields:O,confirmResult:U,usePayFirstFlow:!1})}catch(A){const P={status:ApplePaySession.STATUS_FAILURE};throw T.session.completePayment(P),A}}const{log__:log__$k,err__:err__$l}=createOjsFlowLoggers("awx-apple-pay"),initAirwallexApplePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$2);if(!P)return A;if(log__$k("Loading Apple Pay script"),await loadApplePayScript(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return log__$k("Apple Pay is not available on this device/browser"),A;if(log__$k("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return log__$k("No active cards available for Apple Pay"),A;if(!P.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0),L=async y=>{try{await OjsFlows.airwallexApplePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{...y,initialPreview:C},initResult:void 0})}catch(_){err__$l("Apple Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:L}}),runAirwallexApplePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,customParams:P,formCallbacks:O})=>{const R=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm$2),{overridePaymentRequest:M}=P,D=S.anyCdeConnection,U=await getPrefill(D),C=U.mode==="setup",L=getApplePayPaymentRequest({overridePaymentRequest:M,initialPreview:P.initialPreview,prefill:{...U},defaultLabel:R?.metadata?.processor_account_name}),y=new ApplePaySession(3,L),_={session:y,connection:S.anyCdeConnection,checkoutPaymentMethod:T,nonCdeFormInputs:A,processorAccount:R.metadata,prefill:U,isSetupMode:C,baseUrl:S.baseUrl,formCallbacks:O,defaultFieldValues:P?.defaultFieldValues};return track("apple_pay_flow_started",{processor_name:T.processor_name,prefill:excludeProps(U,["brand"]),overridePaymentRequest:M}),new Promise((N,I)=>{const x=()=>{log__$k("Payment cancelled by user"),I(new Error("Payment cancelled by user"))};y.oncancel=x,y.onvalidatemerchant=async V=>{try{await handleValidateMerchant$1(V,_)}catch(k){I(k)}},y.onpaymentmethodselected=async()=>{const V=await getCheckoutPreviewAmount(D,U.token,C,void 0),k={newTotal:createApplePayTotal({overridePaymentRequest:P.overridePaymentRequest,initialPreview:V,defaultLabel:R?.metadata?.processor_account_name,prefill:U}).total};y.completePaymentMethodSelection(k)},y.onpaymentauthorized=async V=>{track("apple_pay_payment_authorized");try{const k=await handlePaymentAuthorized$1(V,_);N(k)}catch(k){I(k)}},y.begin()}).catch(N=>{throw err__$l("Apple Pay payment error",N),track("apple_pay_payment_error",{error:N}),N})}),{log__:log__$j,err__:err__$k}=createOjsFlowLoggers("awx-google-pay"),initAirwallexGooglePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$2);if(!P)return A;log__$j("Google Pay CPM",P);const O=P.metadata;if(!O.processor_account_id)return err__$k("No gateway merchant ID found in processor account"),A;if(log__$j("Loading Google Pay script"),await loadGooglePayScript(),!window.google?.payments?.api)return err__$k("Google Pay SDK not loaded properly"),A;if(await getGooglePayEnvironment(S.baseUrl)==="PRODUCTION"&&!O.google_pay_merchant_id)return err__$k("Google Pay merchant ID is required for production environment"),A;log__$j("Google Pay SDK loaded",window.google.payments);const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0);try{const y=getPaymentDataRequest({prefill:D,gateway:"airwallex",gatewayMerchantId:O.processor_account_id,merchantName:O.processor_account_name,merchantId:O.google_pay_merchant_id??"",initialPreview:C}),_=await getGooglePaymentsClient(S.baseUrl,y),{result:N}=await _.isReadyToPay(y);if(!N)return log__$j("Google Pay is not available for this user"),A}catch(y){return err__$k("Error checking Google Pay availability",y),A}const L=async y=>{try{OjsFlows.airwallexGooglePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{...y,initialPreview:C}})}catch(_){err__$k("Google Pay payment error",_),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:L}}),runAirwallexGooglePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$j("Starting Google Pay flow...");const R=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm$2),{overridePaymentRequest:M}=O,D=R.metadata;if(!D.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=await getCheckoutPreviewAmount(U,C.token,L,void 0),_=getPaymentDataRequest({prefill:C,gateway:"airwallex",gatewayMerchantId:D.processor_account_id,merchantName:D.processor_account_name,merchantId:D.google_pay_merchant_id??"",initialPreview:y,overridePaymentRequest:M});track("google_pay_flow_started",{processor_name:R.processor_name,prefill:excludeProps(C,["brand"]),overridePaymentRequest:M});const N=await getGooglePaymentsClient(S.baseUrl,_);try{const I=await N.loadPaymentData(_);log__$j("Google Pay Payment data",I);const x=fillEmptyFormInputsWithGooglePay(A,I),V=validateNonCdeFormFieldsForCC(x,P.get.onValidationError,O?.defaultFieldValues);log__$j("___",V),track("billing_details_received",{...V});const k=I.paymentMethodData?.tokenizationData?.token;if(!k)throw new Error("No payment token received from Google Pay");const F=await startPaymentFlow(U,{payment_provider:T.provider,checkout_payment_method:T,...createCustomerFieldsFromForm(V,C.checkout_settings)}),W=parseAirwallexStartPaymentFlowResponse(F);log__$j("Start flow next actions",W);let ee=await confirmPaymentFlow(U,{secure_token:C.token,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:W?.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:k}}}});log__$j("[1st] Confirm payment flow response",ee);let ne=ee.payment_methods?.[0]?.id;const le=ee.required_user_actions?.find(Re=>Re.type==="airwallex_payment_consent");if(le&&le.redirect_url){log__$j("3DS Required, starting verification...",le);const{status:Re}=await start3dsVerification({url:le.redirect_url,baseUrl:S.baseUrl});if(log__$j(`╰ 3DS verification completed [Status: ${Re}]`),Re===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(Re===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed")}if(le&&!ne&&(ee=await confirmPaymentFlow(U,{secure_token:C.token,their_pm_id:le.their_pm_id,processor_specific_metadata:{payment_provider:T.provider,airwallex_consent_id:le.consent_id}}),log__$j("[2nd] Confirm payment flow response",ee),ne=ee.payment_methods?.[0]?.id),!ne)throw new Error("No PM ID found");return performSimpleCheckoutOrSetup({logPrefix:"awx-googlepay",anyCdeConnection:U,checkoutPaymentMethod:T,requiredFormFields:V,confirmResult:ee,usePayFirstFlow:!1})}catch(I){throw err__$k("Google Pay payment error",I),track("google_pay_payment_error",{error:I}),new Error(I?.message??"Unknown error")}}),{log__:log__$i,err__:err__$j}=createOjsFlowLoggers("klarna"),AirwallexKlarnaCpm=objectType({provider:literalType("klarna"),metadata:objectType({}).nullish(),processor_name:literalType("airwallex")}),initAirwallexKlarnaFlow=async({context:S,formCallbacks:T})=>{const A=findCpmMatchingType(S.checkoutPaymentMethods,AirwallexKlarnaCpm);if(!A)throw new Error("Klarna CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:O=>OjsFlows.airwallexKlarna.run({context:S,checkoutPaymentMethod:A,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:O??{}})}},runAirwallexKlarnaFlow=addBasicCheckoutCallbackHandlers(async({context:S,nonCdeFormInputs:T,checkoutPaymentMethod:A,formCallbacks:P,customParams:O})=>{try{log__$i("Running Klarna flow...",O);const R=S.anyCdeConnection,M=await getPrefill(R),D=!1;log__$i("Verifying CPM...");const U=AirwallexKlarnaCpm.parse(A);log__$i("├ Validating non-CDE form fields");const C=validateNonCdeFormFieldsForCC(T,P.get.onValidationError,{...D?generateAnonymousValues():void 0,...M.checkout_settings}),L=createCustomerFieldsFromForm(C,M.checkout_settings);log__$i("New customer fields",L);const y=await startPaymentFlow(R,{payment_provider:A.provider,checkout_payment_method:A,...createCustomerFieldsFromForm(C,M.checkout_settings)});return console.log("startPaymentFlowResponse",y),performSimpleCheckoutOrSetup({logPrefix:"klarna",anyCdeConnection:R,checkoutPaymentMethod:U,requiredFormFields:C,confirmResult:{payment_methods:[]},usePayFirstFlow:!1})}catch(R){throw err__$j("Klarna payment error",R),track("checkout_error",{payment_method:"klarna",error:R}),new Error(R?.message??"Unknown error")}}),ApplePayCpm=objectType({provider:literalType("apple_pay"),processor_name:literalType("authorize_net"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType()})}),GooglePayCpm=objectType({provider:literalType("google_pay"),processor_name:literalType("authorize_net"),metadata:objectType({processor_account_id:stringType(),processor_account_name:stringType(),google_pay_merchant_id:stringType().nullish()})});async function handleValidateMerchant(S,T){try{const O=(await preparePaymentFlow(T.connection,{checkout_payment_method:T.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:S.validationURL,initiative_context:window.location.hostname,their_account_id:T.processorAccount.processor_account_id}}})).next_action_metadata?.apple_pay_session;if(!O)throw new Error("No session data received from payment flow");T.session.completeMerchantValidation(O),track("apple_pay_complete_merchant_validation",{...O})}catch(A){throw T.session.abort(),A}}async function handlePaymentAuthorized(S,T){try{const A=S.payment,P=fillEmptyFormInputsWithApplePay(T.nonCdeFormInputs,A),O=validateNonCdeFormFieldsForCC(P,T.formCallbacks.get.onValidationError);track("billing_details_received",{...O}),await startPaymentFlow(T.connection,{payment_provider:T.checkoutPaymentMethod.provider,checkout_payment_method:T.checkoutPaymentMethod,...createCustomerFieldsFromForm(O,T.prefill.checkout_settings),customer_language:detectLanguage()});const R={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(A.token.paymentData))},M=await confirmPaymentFlow(T.connection,{secure_token:T.prefill.token,processor_specific_metadata:{payment_provider:T.checkoutPaymentMethod.provider,mobile_wallet_payment_data:R}});if(!M.payment_methods?.[0]?.id)throw new Error("No PM ID found");const U={status:ApplePaySession.STATUS_SUCCESS};return T.session.completePayment(U),performSimpleCheckoutOrSetup({logPrefix:"authnet-applepay",anyCdeConnection:T.connection,checkoutPaymentMethod:T.checkoutPaymentMethod,requiredFormFields:O,confirmResult:M,usePayFirstFlow:!1})}catch(A){const P={status:ApplePaySession.STATUS_FAILURE};throw T.session.completePayment(P),A}}const{log__:log__$h,err__:err__$i}=createOjsFlowLoggers("authnet-applepay"),initAuthnetApplePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A={processor:PaymentProcessor.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm);if(!P)return A;if(log__$h("Loading Apple Pay script"),await loadApplePayScript(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return log__$h("Apple Pay is not available on this device/browser"),A;if(!await ApplePaySession.canMakePayments())return log__$h("No active cards available for Apple Pay"),A;if(!P.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const M=S.anyCdeConnection,D=await getPrefill(M),U=D.mode==="setup",C=await getCheckoutPreviewAmount(M,D.token,U,void 0),L=async y=>{try{await OjsFlows.authorizeNetApplePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{...y,initialPreview:C},initResult:void 0})}catch(_){err__$i("Apple Pay payment error",_),track("apple_pay_payment_error",{error:_}),T.get.onCheckoutError(_?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:L}}),runAuthnetApplePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,customParams:P,formCallbacks:O})=>{const{initialPreview:R,overridePaymentRequest:M}=P,D=findCpmMatchingType(S.checkoutPaymentMethods,ApplePayCpm),U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=getApplePayPaymentRequest({overridePaymentRequest:M,initialPreview:R,prefill:C,defaultLabel:D?.metadata?.processor_account_name});track("apple_pay_flow_started",{processor_name:T.processor_name,prefill:C,overridePaymentRequest:M});const _=new ApplePaySession(3,y),N={session:_,connection:S.anyCdeConnection,checkoutPaymentMethod:T,nonCdeFormInputs:A,processorAccount:T.metadata,prefill:C,isSetupMode:L,baseUrl:S.baseUrl,formCallbacks:O};return new Promise((I,x)=>{_.oncancel=()=>{log__$h("Payment cancelled by user"),x(new Error("Payment cancelled by user"))},_.onvalidatemerchant=async V=>{try{await handleValidateMerchant(V,N)}catch(k){x(k)}},_.onpaymentmethodselected=async()=>{const V=await getCheckoutPreviewAmount(U,C.token,L,void 0),k={newTotal:createApplePayTotal({overridePaymentRequest:P.overridePaymentRequest,initialPreview:V,defaultLabel:D?.metadata?.processor_account_name,prefill:C}).total};_.completePaymentMethodSelection(k)},_.onpaymentauthorized=async V=>{track("apple_pay_payment_authorized");try{const k=await handlePaymentAuthorized(V,N);I(k)}catch(k){x(k)}},_.begin()}).catch(I=>{throw err__$i("Apple Pay payment error",I),track("apple_pay_payment_error",{error:I}),I})}),{log__:log__$g,err__:err__$h}=createOjsFlowLoggers("authnet-googlepay"),initAuthnetGooglePayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{log__$g("Initializing Authnet GooglePay flow");const A={processor:PaymentProcessor.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},P=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm);if(!P)return A;log__$g("Google Pay CPM",P);const O=P.metadata;if(!O.processor_account_id)return err__$h("No gateway merchant ID found in processor account"),A;if(log__$g("Loading Google Pay script"),await loadGooglePayScript(),!window.google?.payments?.api)return err__$h("Google Pay SDK not loaded properly"),A;log__$g("Google Pay SDK loaded",window.google.payments);const R=S.anyCdeConnection,M=await getPrefill(R),D=M.mode==="setup",U=await getCheckoutPreviewAmount(R,M.token,D,void 0);try{const L=getPaymentDataRequest({prefill:M,gateway:"authorizenet",gatewayMerchantId:O.processor_account_id,merchantName:O.processor_account_name,merchantId:O.google_pay_merchant_id??"",initialPreview:U}),y=await getGooglePaymentsClient(S.baseUrl,L),{result:_}=await y.isReadyToPay(L);if(!_)return log__$g("Google Pay is not available for this user"),A}catch(L){return err__$h("Error checking Google Pay availability",L),A}const C=async L=>{try{OjsFlows.authorizeNetGooglePay.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{...L,initialPreview:U}})}catch(y){err__$h("Google Pay payment error",y),track("google_pay_payment_error",{error:y}),T.get.onCheckoutError(y?.message??"Unknown error")}};return{processor:PaymentProcessor.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:C}}),runAuthnetGooglePayFlow=addBasicCheckoutCallbackHandlers(async({context:S,nonCdeFormInputs:T,checkoutPaymentMethod:A,formCallbacks:P,customParams:O})=>{const{overridePaymentRequest:R}=O,D=findCpmMatchingType(S.checkoutPaymentMethods,GooglePayCpm).metadata,U=S.anyCdeConnection,C=await getPrefill(U),L=C.mode==="setup",y=await getCheckoutPreviewAmount(U,C.token,L,void 0),_=getPaymentDataRequest({prefill:C,gateway:"authorizenet",gatewayMerchantId:D.processor_account_id,merchantName:D.processor_account_name,merchantId:D.google_pay_merchant_id??"",initialPreview:y,overridePaymentRequest:R});track("google_pay_flow_started",{processor_name:A.processor_name,prefill:C,overridePaymentRequest:R});const N=await getGooglePaymentsClient(S.baseUrl,_);try{const I=await N.loadPaymentData(_);log__$g("Google Pay Payment data",I);const x=fillEmptyFormInputsWithGooglePay(T,I),V=validateNonCdeFormFieldsForCC(x,P.get.onValidationError);track("billing_details_received",{...V});const k=I.paymentMethodData?.tokenizationData?.token;if(!k)throw new Error("No payment token received from Google Pay");const F=await startPaymentFlow(U,{payment_provider:A.provider,checkout_payment_method:A,...createCustomerFieldsFromForm(V,C.checkout_settings),customer_language:detectLanguage()});log__$g("Start payment flow response",F);const W=await confirmPaymentFlow(U,{secure_token:C.token,processor_specific_metadata:{payment_provider:A.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(k)}}});if(!W.payment_methods?.[0]?.id)throw new Error("No PM ID found");return performSimpleCheckoutOrSetup({logPrefix:"authnet-googlepay",anyCdeConnection:U,checkoutPaymentMethod:A,requiredFormFields:V,confirmResult:W,usePayFirstFlow:!1})}catch(I){throw err__$h("Google Pay payment error",I),track("google_pay_payment_error",{error:I}),new Error(I?.message??"Unknown error")}}),{log__:log__$f,err__:err__$g}=createOjsFlowLoggers("cybs-frame"),attachDeviceDataCollector=(S,T)=>{const A=document.createElement("iframe");A.name="cardinal_collection_iframe",A.style.display="none",A.style.width="10px",A.style.height="10px";const P=document.createElement("form");P.action=S,P.method="POST",P.target=A.name;const O=document.createElement("input");return O.type="hidden",O.name="JWT",O.value=T,P.appendChild(O),document.body.appendChild(A),document.body.appendChild(P),{form:P,detach:()=>{document.body.removeChild(A),document.body.removeChild(P)}}},runDeviceDataCollection=async S=>new Promise((T,A)=>{const{postUrl:P,accessToken:O}=S,R=new URL(P).origin,{form:M,detach:D}=attachDeviceDataCollector(P,O);log__$f("Attached device data collector");const U=L=>{if(L.origin!==R)return;const y=JSON.parse(L.data);if(log__$f("Received event from device data collector:",y),y.MessageType==="profile.completed"){T(y),C();return}},C=()=>{D(),window.removeEventListener("message",U)};try{window.addEventListener("message",U),log__$f("Attached listener to window"),M.submit(),log__$f("Submitted form")}catch(L){err__$g("Error submitting form:",L),C(),A(L)}}),runPayerAuth=S=>{const{stepUpUrl:T,accessToken:A,merchantData:P,iframe:O,host:R}=S,M=document.createElement("form");M.action=T,M.method="POST",M.target=O.name;const D=document.createElement("input");D.type="hidden",D.name="JWT",D.value=A;const U=document.createElement("input");return U.type="hidden",U.name="MD",U.value=P,M.appendChild(D),M.appendChild(U),R.appendChild(M),M},{log__:log__$e,err__:err__$f}=createOjsFlowLoggers("cybs"),CybersourceActionPayload=objectType({step_up_url:stringType(),access_token:stringType(),dd_url:nullOrUndefOr$1(stringType()),dd_token:nullOrUndefOr$1(stringType()),merchant_data:stringType()}),FRIENDLY_ERR="Unable to process your credit card. Please contact support for assistance.",parseResponseHeaders$1=S=>{const T=CybersourceActionPayload.safeParse(S);if(!T.success)throw err__$f(`Cybersource 3DS is required but user action is malformed. Got: ${JSON.stringify(S)}`),new Error(FRIENDLY_ERR);return T.data},checkIfRequiresCybersource3ds=S=>S.type==="cybersource_payer_auth",handleCybersource3ds=async S=>{const{stepUpUrl:T,accessToken:A,merchantData:P,iframe:O,host:R,cancelButton:M}=S,D=new URL(T).origin;return new Promise(U=>{const C=()=>{log__$e("Cleaning up Cybersource 3DS flow"),M.removeEventListener("click",L),R.remove()},L=()=>{log__$e("Cybersource 3DS cancelled"),U({status:ThreeDSStatus.CANCELLED,cleanup:C})},_=startPolling(O,x=>{log__$e("Cybersource 3DS completed with status:",x),U({status:x.status,cleanup:C}),N()},D,"ping-3ds-status",Ping3DSStatusResponse),N=handleEvents({elements:{host:R,cancelButton:M},pollingInterval:_,resolve:x=>{U({status:x.status,cleanup:C})}});M.addEventListener("click",L),runPayerAuth({stepUpUrl:T,accessToken:A,merchantData:P,iframe:O,host:R}).submit()})},runCybersource3dsFlow=async S=>{const T=parseResponseHeaders$1(S),{step_up_url:A,access_token:P,dd_url:O,dd_token:R,merchant_data:M}=T;if(O&&R){const y=await runDeviceDataCollection({postUrl:O,accessToken:R});log__$e("Device data collection completed with status:",y.Status)}else err__$f("No device data collection URL or token provided");const{host:D,iframe:U,cancelButton:C}=createAndOpenFrame("",{name:"cardinal_auth_iframe"});log__$e("Running Cybersource 3DS flow");const L=await handleCybersource3ds({stepUpUrl:A,accessToken:P,merchantData:M,iframe:U,host:D,cancelButton:C});if(L.cleanup(),L.status===ThreeDSStatus.FAILURE)throw new Error("3DS verification failed");if(L.status===ThreeDSStatus.CANCELLED)throw new Error("3DS verification cancelled");if(L.status===ThreeDSStatus.SUCCESS){log__$e("3DS verification succeeded");return}else assertNever(L.status)},{log__:log__$d,err__:err__$e}=createOjsFlowLoggers("pockyt-cc"),Pockyt3dsErrorResponseHeaders=objectType({"op-pockyt-3ds-url":stringType(),"op-pockyt-txn-no":stringType(),"op-pockyt-ref-no":stringType()}),parseResponseHeaders=S=>{const T=Pockyt3dsErrorResponseHeaders.safeParse(S);if(!T.success){const A="Unable to process your credit card. Please contact support for assistance.",P=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(S)}`;throw err__$e(P),new Error(A)}return T.data},parseVaultIdFrom3dsHref=S=>{try{const T=new URL(S??"").searchParams.get("vaultId");if(!T)throw new Error("No vault ID found in 3DS verification result");return log__$d(`3DS verification success. [Vault ID: ${T}]`),T}catch(T){const A="Error verifying 3DS verification result.";throw err__$e(A,`Resulting URL: ${S}.
214
214
  Error: ${getErrorMessage(T)}`),new Error(A)}},parseArgFromHref=(S,T)=>new URL(S).searchParams.get(T),checkIfRequiresPockyt3ds=S=>S?.["op-pockyt-3ds-url"]!==void 0,runPockyt3dsFlow=async(S,T)=>{const A=parseResponseHeaders(T),P=await start3dsVerificationStrict({url:A["op-pockyt-3ds-url"],baseUrl:S});return{existing_cc:{vault_id:parseVaultIdFrom3dsHref(P.href??""),transaction_no:A["op-pockyt-txn-no"],reference_no:A["op-pockyt-ref-no"]}}},{log__:stripeLog__}=createOjsFlowLoggers("stripe-cc"),Stripe3DSMetadataPayload=objectType({stripe_pk:stringType(),client_secret:stringType(),stripe_pm_id:stringType()}),stripeCC3DSFlow=async S=>{track("3ds_stripe_redirect",{...S}),stripeLog__(`├ Using stripe 3DS flow [Client Secret: ${S.client_secret.substring(0,8)}...]`),await launchStripe3DSDialogFlow(S),track("3ds_stripe_complete"),stripeLog__("╰ Stripe 3DS flow completed successfully")},parseUserFEPayload=S=>{const T=Stripe3DSMetadataPayload.safeParse(S);if(!T.success)throw new Error(`Stripe 3DS metadata has unexpected format: ${JSON.stringify(T.error.errors)}`);return{stripe_pk:T.data.stripe_pk,client_secret:T.data.client_secret,stripe_pm_id:T.data.stripe_pm_id}},MAX_CONFIRM_LOOP_ITERATIONS=4,{log__:log__$c,err__:err__$d}=createOjsFlowLoggers("unified-cc"),unsafelyRunUnifiedCcFlow=async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$c("├ Running unified CC flow...",{checkoutPaymentMethod:T});const R=S.anyCdeConnection,M=await getPrefill(R);log__$c(`├ Validating non-CDE form fields [Mode: ${M.mode}]`);const D=validateNonCdeFormFieldsForCC(A,P.get.onValidationError),U={session_id:S.elementsSessionId,checkout_payment_method:T,non_cde_form_fields:D,extra_metadata:{origin:window.location.origin,deviceToken:getDeviceToken()},use_unified_cc_flow:!0,pay_first_flow_cart_info:{line_items:M.line_items,displayed_total_amount_atom:M.amount_total_atom},payment_route_id:O.paymentRouteId};err__$d(O,U),log__$c(`├ Tokenizing card info in Partial PMs [Session: ${S.elementsSessionId}]`);const C=await tokenizeCardOnAllConnections(O.currentCdeConnections,{session_id:S.elementsSessionId});validateTokenizeCardResults(C,P.get.onValidationError);const L=await startPaymentFlowForCC(R,U);if(log__$c("├ startPf result",L),L.checkout_success_response)return returnSuccessResult(M.mode,L);if(!L.checkout_attempt_id)throw new Error("Invalid state: no checkout attempt ID from PF result");return runConfirmLoop({context:S,prefill:M,nonCdeFormInputs:A,commonCheckoutParams:U,anyCdeConnection:R,startPfResult:L,checkoutAttemptId:L.checkout_attempt_id})},runConfirmLoop=async S=>{const{context:T,prefill:A,nonCdeFormInputs:P,commonCheckoutParams:O,anyCdeConnection:R,startPfResult:M,checkoutAttemptId:D}=S;let U=M;for(let C=0;C<MAX_CONFIRM_LOOP_ITERATIONS;C++){log__$c(`├ Running confirm loop iteration ${C}`),track("unified_cc_confirm_loop_iteration",{iteration:C});const{userAction:L}=validatePfResultUserAction(U);try{const y=await runRequiredUserAction(T.baseUrl,L,A,P);O.extra_metadata={...O.extra_metadata,...y.metadataForConfirmStep},log__$c("├ New extra metadata",O.extra_metadata)}catch(y){const _=getErrorMessage(y);err__$d(`├ Error in running user action in iteration ${C}. Continuing to confirm step...`,_),track("unified_cc_user_action_error",{error_message:_,iteration:C})}if(U=await confirmPaymentFlow(R,{secure_token:A.token,checkout_attempt_id:D,processor_specific_metadata:O.extra_metadata}),log__$c(`├ confirmPf result (iteration ${C})`,U),U.checkout_success_response)return returnSuccessResult(A.mode,U)}throw track("unified_cc_unexpected_branch",{secure_token:A.token,checkout_attempt_id:U.checkout_attempt_id,confirmPFResult:U}),new Error("Checkout error, please try another payment method")},runRequiredUserAction=async(S,T,A,P)=>{if(T._unified_cc_action_name==="3DS_REQUIRED"){if(T.type==="stripe_3ds")return await stripeCC3DSFlow(parseUserFEPayload(T)),{metadataForConfirmStep:{}};if(checkIfRequiresAirwallex3ds(T))return{metadataForConfirmStep:{airwallex:await runAirwallex3dsFlow(S,T)}};if(checkIfRequiresAdyen3ds(T))return{metadataForConfirmStep:{adyen:await runAdyen3dsFlow(P[FieldName.COUNTRY],T,A.locale)}};if(checkIfRequiresCybersource3ds(T))return await runCybersource3dsFlow(T),{metadataForConfirmStep:{}};if(checkIfLegacy3DSPath(T))return await commonCC3DSFlow({required_user_actions:[T]},S),{metadataForConfirmStep:{}};throw new Error(`Unhandled 3DS user action: ${JSON.stringify(T)}`)}else throw new Error(`Unknown required user action: ${JSON.stringify(T)}`)},checkIfLegacy3DSPath=S=>{try{return parseCommon3DSNextActionMetadata([S]),!0}catch{return!1}},validatePfResultUserAction=S=>{if(S.required_user_actions){if(S.required_user_actions.length===0)throw new Error("Invalid state: no required user actions");if(S.required_user_actions.length>1)throw new Error("Invalid state: multiple required user actions")}else throw new Error("Invalid state: no required user actions");const T=UserActionFEPayload.safeParse(S.required_user_actions[0]);if(!T.success)throw err__$d("User action raw payload",S.required_user_actions[0]),err__$d("Parsing error",T.error),new Error("Invalid state: schema of user action payload is not valid");return{userAction:T.data}},returnSuccessResult=(S,T)=>{if(S==="setup"){const A=T.cc_pm_id??T.payment_methods?.[0].id;if(!A)throw new Error("Invalid state: no CC PM ID or payment_methods found in PF result");return{mode:"setup",result:{payment_method_id:A}}}else{if(!T.checkout_success_response)throw new Error("Invalid state: no checkout success response from startPF");return{mode:"checkout",result:T.checkout_success_response}}},{log__:log__$b,err__:err__$c}=createOjsFlowLoggers("common-cc");arrayType(objectType({our_existing_pm_id:stringType()})).length(1);const runCommonCcFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$b("├ Running common CC flow...",{checkoutPaymentMethod:T});const R=S.anyCdeConnection,M=await getPrefill(R);track("common_cc_flow_started",{...T,prefill:M});const D=M.final_feature_rollout_settings?.unified_cc??0;log__$b(`├ Unified CC rollout: ${Math.round(D*100)}%`);const U=Math.random(),C=U<D,L={roll:U,unifiedCCRolloutRatio:D,useUnifiedCCFlow:C};if(C)return log__$b(`├ Picked unified CC flow (${U} vs ${D})`),track("unified_cc_flow_picked",L),unsafelyRunUnifiedCcFlow({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O,initResult:void 0});log__$b(`├ Picked legacy CC flow (${U} vs ${D})`),track("legacy_cc_flow_picked",L),log__$b(`├ Validating non-CDE form fields [Mode: ${M.mode}]`);const y=validateNonCdeFormFieldsForCC(A,P.get.onValidationError,M.checkout_settings);track("billing_details_received",{...y});const _={session_id:S.elementsSessionId,checkout_payment_method:T,non_cde_form_fields:y,extra_metadata:{origin:window.location.origin},use_unified_cc_flow:!1,payment_route_id:O.paymentRouteId,customer_language:detectLanguage(),...createCustomerFieldsFromForm(y,M.checkout_settings)};try{log__$b(`├ Tokenizing card info in CDE [Session: ${S.elementsSessionId}]`);const N=await tokenizeCardOnAllConnections(O.currentCdeConnections,{session_id:S.elementsSessionId});if(validateTokenizeCardResults(N,P.get.onValidationError),M.mode==="setup"){log__$b(`├ Setting up payment method in CDE [Token: ${M.token}]`);const I=await setupCheckout(R,_);return log__$b(`╰ Setup completed successfully [PM ID: ${I.payment_method_id}]`),{mode:"setup",result:I}}else{log__$b(`├ Initial checkout flow. Checking out card info in CDE [Session: ${S.elementsSessionId}]`);const I=await checkoutCardElements(R,_);return log__$b("╰ Checkout completed successfully."),{mode:"checkout",result:I}}}catch(N){if(N instanceof CdeError&&N.originalErrorMessage.includes("3DS_REQUIRED")){log__$b("├ Card requires 3DS, starting non-legacy payment flow"),log__$b("Received 3DS error response headers:",N.response.headers),track("3ds_required",{...T,...N.response.headers});const I=N.response.headers??{};"op-existing-cc-pm-id"in I&&(_.existing_cc_pm_id=I["op-existing-cc-pm-id"],log__$b(`├ Existing CC PM ID: ${_.existing_cc_pm_id}`));const x=checkIfRequiresPockyt3ds(N.response.headers);if(x){log__$b("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const le=await runPockyt3dsFlow(S.baseUrl,N.response.headers);_.extra_metadata.pockyt=le}if(checkIfRequiresAirwallex3ds(N.response.headers)){log__$b("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const le=await runAirwallex3dsFlow(S.baseUrl,N.response.headers);_.extra_metadata.airwallex=le}if(checkIfRequiresAdyen3ds(N.response.headers)){log__$b("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const le=await runAdyen3dsFlow(A[FieldName.COUNTRY],N.response.headers,M.locale);_.extra_metadata.adyen=le}const F=await startPaymentFlowForCC(R,_);log__$b("├ Start payment flow result:",F);const W=F.required_user_actions.find(le=>le.type==="cybersource_payer_auth");if(W){log__$b("├ Cybersource 3DS case detected. Going through Cybersource 3DS flow.");const le=CybersourceActionPayload.parse(W),Re=await runCybersource3dsFlow({...le,_unified_cc_action_name:"",_unified_cc_pccs_id:""});_.extra_metadata.cybersource=Re}const ee=N.response.headers?.["op-should-use-new-flow"]!=="true";!x&&!W?ee?(log__$b("├ Using stripe 3DS flow"),await stripeCC3DSFlow(parseStripe3DSNextActionMetadata(F))):(log__$b("├ Using common 3DS flow"),await commonCC3DSFlow(F,S.baseUrl)):log__$b("├ Pre-start 3DS is successful, other 3DS flows will be skipped.");const ne=F.cc_pm_id;if(M.mode==="setup"){log__$b(`├ Confirming payment flow [cc_pm_id: ${ne}]`);const le=await confirmPaymentFlow(R,{secure_token:M.token,existing_cc_pm_id:ne});log__$b("├ Confirm payment flow result received Result:",le);const Re=parseConfirmPaymentFlowResponse(le);return log__$b(`╰ Setup completed successfully [PM ID: ${Re.payment_method_id}]`),{mode:"setup",result:Re}}else{log__$b(`├ Checking out after 3DS flow [Flow: ${ee?"legacy":"new"}]`);const le=await checkoutCardElements(R,{..._,existing_cc_pm_id:ne,do_not_use_legacy_cc_flow:ee});return log__$b("╰ Checkout completed successfully."),{mode:"checkout",result:le}}}throw err__$c("╰ Error checking out card info in CDE"),err__$c(N),N}}),parseStripe3DSNextActionMetadata=S=>{const T=S.required_user_actions.find(A=>A.type==="stripe_3ds");if(!T)throw new Error("No stripe 3DS action found");return Stripe3DSNextActionMetadata.parse(T)},common3DSActionTypes=["airwallex_payment_consent","adyen"],parseCommon3DSNextActionMetadata=S=>{const T=S.find(A=>common3DSActionTypes.includes(A.type));if(!T)throw new Error("No common 3DS action found");return Common3DSNextActionMetadata.parse(T)},commonCC3DSFlow=async(S,T)=>{const A=parseCommon3DSNextActionMetadata(S.required_user_actions);if(A.redirect_url==="3DS_COMPLETE"){log__$b("├ 3DS flow completed successfully"),track("3ds_complete");return}log__$b(`├ Using common 3DS flow [URL: ${A.redirect_url}]`),track("3ds_redirect",{...A});const{status:P}=await start3dsVerification({url:A.redirect_url,baseUrl:T});if(log__$b(`╰ 3DS verification completed [Status: ${P}]`),P===ThreeDSStatus.CANCELLED)throw track("3ds_cancelled"),new Error("3DS verification cancelled");if(P===ThreeDSStatus.FAILURE)throw track("3ds_failure"),new Error("3DS verification failed");track("common_3ds_completed")},LoopCryptoCpm=objectType({processor_name:literalType("loop"),provider:literalType("crypto"),metadata:objectType({merchant_id:stringType(),entity_id:stringType(),api_token:stringType(),supported_currencies:arrayType(stringType()),environment:stringType()})}),{log__:log__$a,err__:err__$b}=createOjsFlowLoggers("loop-crypto"),initLoopFlow=addErrorCatcherForInit(async({context:S})=>{log__$a("Checking if there are any CPMs for Loop Crypto...");const T=findCpmMatchingType(S.checkoutPaymentMethods,LoopCryptoCpm);log__$a(`checkoutPaymentMethod: ${JSON.stringify(T)}`),log__$a("Starting Loop Crypto flow...");const A=await getPrefill(S.anyCdeConnection),P=A.mode==="setup",O=await preparePaymentFlow(S.anyCdeConnection,{checkout_payment_method:T}),R=await getCheckoutPreviewAmount(S.anyCdeConnection,A.token,P,void 0);if(!P&&!T.metadata.supported_currencies.includes(A.currency))throw Error(`Currency ${A.currency} not enabled for Loop. Enabled currencies: ${T.metadata.supported_currencies}`);if(!O||!O.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const M=O.next_action_metadata;let D=M.authorization_amount,U=M.min_authorization_amount;const C=M.allow_customer_to_choose_auth;let L;P?(L=0,D=Math.max(D,U)):(L=(R?R.amountAtom:A.amount_total_atom)*M.token_price,U=Math.max(U,L),D=Math.max(D,U));const y=L,_=v4(),N={paymentUsdAmount:y,suggestedAuthorizationUsdAmount:D,customerRefId:_,minAuthorizationUsdAmount:U,allowCustomerToChooseAuth:C},I={apiToken:T.metadata.api_token,entityId:T.metadata.entity_id,merchantId:T.metadata.merchant_id,environment:T.metadata.environment};return{isAvailable:!0,widgetProps:N,initLoopConnectProps:I}}),runLoopFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$a("Running Loop flow..."),log__$a("context",S),log__$a("checkoutPaymentMethod",T),log__$a("nonCdeFormInputs",A),log__$a("flowCallbacks",P),log__$a("customParams",O);const R=await getPrefill(S.anyCdeConnection);log__$a(`├ Validating non-CDE form fields [Mode: ${R.mode}]`);const M=validateNonCdeFormFieldsForCC(A,P.get.onValidationError,R.checkout_settings),D=S.anyCdeConnection,U=R.mode!=="setup",C=createCustomerFieldsFromForm(M,R.checkout_settings);if(!O)throw new Error("Checkout failed. Failed to properly submit form data.");if(!O.success)throw track("loop_pay_flow_failure",O),new Error("Checkout failed. Success is not true.");const L=await startPaymentFlow(S.anyCdeConnection,{checkout_payment_method:T,payment_provider:T.provider,...C,use_pay_first_flow:U,pay_first_flow_cart_info:U?{line_items:R.line_items,displayed_total_amount_atom:R.amount_total_atom,promotion_code:M[FieldName.PROMOTION_CODE]}:void 0,customer_language:detectLanguage()}),y=await confirmPaymentFlow(D,{secure_token:R.token,their_pm_id:O.paymentMethod.paymentMethodId,checkout_attempt_id:U?L.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:O.customer,loop_payment_method:O.paymentMethod,loop_success:O.success,loop_payin_id:O.payinId}});if(log__$a(`Confirm result: ${y}`),R.mode==="setup"){log__$a("Doing payment setup..."),log__$a("├ Confirm payment flow result received Result:",y);const _=parseConfirmPaymentFlowResponse(y);return log__$a(`╰ Setup completed successfully [PM ID: ${_.payment_method_id}]`),{mode:"setup",result:_}}else{if(log__$a("Doing checkout..."),!y.pay_first_success_response)throw err__$b("Checkout failed, no pay-first success response:",y),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:y.pay_first_success_response}}}),{log__:log__$9,err__:err__$a}=createOjsFlowLoggers("paypal"),PaypalCpm=objectType({provider:literalType("paypal"),metadata:objectType({client_id:stringType()}),processor_name:literalType("paypal")}),initPaypalFlow=async({context:S,formCallbacks:T})=>{const A=findCpmMatchingType(S.checkoutPaymentMethods,PaypalCpm);if(!A)throw new Error("PayPal CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:()=>OjsFlows.paypal.run({context:S,checkoutPaymentMethod:A,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{settings:{}}})}},runPaypalFlow=addBasicCheckoutCallbackHandlers(async({context:S,nonCdeFormInputs:T,checkoutPaymentMethod:A,formCallbacks:P,customParams:O})=>{try{log__$9("Running PayPal flow...");const R=S.anyCdeConnection,M=await getPrefill(R),{isAnonymous:D,useRedirectFlow:U}=O.settings??{};log__$9("Verifying CPM...");const C=PaypalCpm.parse(A);log__$9("├ Validating non-CDE form fields");const L=validateNonCdeFormFieldsForCC(T,P.get.onValidationError,{...D?generateAnonymousValues():void 0,...M.checkout_settings}),y=createCustomerFieldsFromForm(L,M.checkout_settings);log__$9(`Starting payment flow... Mode: ${M.mode}`);const _=v4(),N=!1,I={payment_provider:C.provider,checkout_payment_method:C,use_pay_first_flow:N,pay_first_flow_cart_info:N?{line_items:M.line_items,displayed_total_amount_atom:M.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:U,frontend_token_for_redirect_flow:_},...y},x=new URL("/app/pre-action/start/",S.baseUrl).toString(),V=btoa(JSON.stringify(I)),k=new URLSearchParams({st:M.token,r:V}),F=`${x}?${k.toString()}`;if(U)throw log__$9("Starting redirect mode for PayPal..."),window.location.href=F,await sleep(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");const W=await startPopupWindowVerificationStrict("PayPal",R,_,F);log__$9("Paypal flow result",W);const ee=parseArgFromHref(W.href,"catt"),ne=parseArgFromHref(W.href,"approval_session_id"),le=await confirmPaymentFlow(R,{secure_token:M.token,checkout_attempt_id:N?ee:void 0,their_pm_id:N?ne:void 0});return log__$9("Confirm payment flow result",le),performSimpleCheckoutOrSetup({logPrefix:"paypal",anyCdeConnection:R,checkoutPaymentMethod:C,requiredFormFields:L,confirmResult:le,usePayFirstFlow:N})}catch(R){throw err__$a("PayPal payment error",R),track("checkout_error",{payment_method:"paypal",error:R}),new Error(R?.message??"Unknown error")}}),{log__:log__$8,err__:err__$9}=createOjsFlowLoggers("pockyt-paypal"),PockytPaypalCpm=objectType({processor_name:literalType("pockyt"),provider:literalType("paypal")});arrayType(objectType({paypal_iframe_url:stringType(),verify_token:stringType()})).length(1);const initPockytPaypalFlow=async({context:S,formCallbacks:T})=>{const A=findCpmMatchingType(S.checkoutPaymentMethods,PockytPaypalCpm);if(!A)throw new Error("Pockyt PayPal CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:()=>OjsFlows.pockytPaypal.run({context:S,checkoutPaymentMethod:A,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,initResult:void 0,customParams:{settings:{}}})}},runPockytPaypalFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$8("Running Pockyt Paypal flow...");const R=S.anyCdeConnection,M=await getPrefill(R);log__$8("Verifying CPM...");const D=PockytPaypalCpm.parse(T);log__$8("├ Validating non-CDE form fields");const U=O?.settings,C=validateNonCdeFormFieldsForCC(A,P.get.onValidationError,U?.defaultFieldValues),L=createCustomerFieldsFromForm(C,M.checkout_settings);log__$8(`Starting payment flow... Mode: ${M.mode}`);const y=v4(),_=M.mode!=="setup",N={payment_provider:D.provider,checkout_payment_method:D,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:M.line_items,displayed_total_amount_atom:M.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!O?.settings?.useRedirectFlow,frontend_token_for_redirect_flow:y},...L},I=new URL("/app/pre-action/start/",S.baseUrl).toString(),x=btoa(JSON.stringify(N)),V=new URLSearchParams({st:M.token,r:x}),k=`${I}?${V.toString()}`;if(O?.settings?.useRedirectFlow)throw log__$8("Starting redirect mode for PayPal..."),window.location.href=k,await sleep(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");log__$8("Starting popup mode for PayPal..."),log__$8("Opening paypal iframe...");const F=await startPopupWindowVerificationStrict("PayPal",R,y,k);log__$8("Paypal flow result",F);const W=parseVaultIdFrom3dsHref(F.href),ee=parseArgFromHref(F.href,"catt");if(!ee)throw err__$9("Checkout attempt ID not found in redirect URL:",F.href),new Error("Checkout attempt ID not found in redirect URL");log__$8(`Confirming payment flow using vault ID ${W}`);const ne=await confirmPaymentFlow(R,{secure_token:M.token,their_pm_id:W,checkout_attempt_id:_?ee:void 0});if(log__$8("Confirm payment flow result",ne),M.mode==="setup")return{mode:"setup",result:{payment_method_id:ne.payment_methods[0].id}};if(!ne.pay_first_success_response)throw err__$9("Checkout failed, no pay-first success response:",ne),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:ne.pay_first_success_response}}),{log__:log__$7,err__:err__$8}=createOjsFlowLoggers("stripe-affirm"),StripeAffirmCpm=objectType({provider:literalType("affirm"),processor_name:literalType("stripe"),metadata:objectType({stripe_pk:stringType()})}),StripeAffirmRequiredUserActions=arrayType(objectType({our_existing_pm_id:stringType().nullish(),client_secret:stringType()})).length(1),initStripeAffirmFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{log__$7("Checking if there are any CPMs for Stripe Affirm...");const A=findCpmMatchingType(S.checkoutPaymentMethods,StripeAffirmCpm);if(!A)return log__$7("No Stripe Affirm CPM found"),{isAvailable:!1,startFlow:async()=>{}};log__$7("Starting stripe affirm flow...");const P=S.anyCdeConnection;return(await getPrefill(P)).mode==="setup"?(log__$7("Setup mode is not supported for Stripe Affirm flow"),{isAvailable:!1,startFlow:async()=>{}}):{isAvailable:!0,startFlow:async D=>{try{return OjsFlows.stripeAffirm.run({context:S,checkoutPaymentMethod:A,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:D??{},initResult:{isAvailable:!0}})}catch(U){throw err__$8("Error starting Affirm flow:",U),U}}}}),runStripeAffirmFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P})=>{log__$7("Running Stripe Affirm pay-first flow...");const O=S.anyCdeConnection,R=await getPrefill(O);log__$7("Validating form fields...");const M=validateNonCdeFormFieldsForCC(A,P.get.onValidationError);track("billing_details_received",{...M}),log__$7("Creating cart info for pay-first flow...");const D={line_items:R.line_items.map(k=>({price_id:k.price_id,quantity:k.quantity})),promotion_code:M[FieldName.PROMOTION_CODE]||void 0,displayed_total_amount_atom:R.amount_total_atom};log__$7("Starting pay-first payment flow for Affirm...");const U=await startPaymentFlow(O,{payment_provider:T.provider,checkout_payment_method:T,use_pay_first_flow:!0,pay_first_flow_cart_info:D,...createCustomerFieldsFromForm(M,R.checkout_settings),customer_language:detectLanguage()});log__$7("Start payment flow response",U);const C=StripeAffirmRequiredUserActions.parse(U.required_user_actions),{client_secret:L}=C[0];log__$7("Client secret for payment intent",L);const y=findCpmMatchingType(S.checkoutPaymentMethods,StripeAffirmCpm);if(!y)throw new Error("Stripe Affirm CPM not found");const{stripe:_}=await createStripeElements(y.metadata.stripe_pk,{mode:"payment",currency:R.currency??"usd",amount:R.amount_total_atom});log__$7("Stripe instance created",_);const N=generateBillingAddressFromFields(M),I=`${M[FieldName.FIRST_NAME]} ${M[FieldName.LAST_NAME]}`,x={return_url:new URL("/app/3ds/success/",S.baseUrl).toString(),payment_method:{billing_details:{email:M[FieldName.EMAIL],name:I,address:{line1:N.line1,line2:N.line2||void 0,city:N.city,state:N.state,country:N.country,postal_code:N.zip_code}}}},V={handleActions:!1};log__$7(`Confirming Affirm payment with client secret: ${L}`);try{const{error:k,paymentIntent:F}=await _.confirmAffirmPayment(L,x,V);if(k)throw err__$8("Affirm payment confirmation error:",k),new Error(`Affirm payment failed: ${k.message}`);log__$7("Affirm payment confirmed successfully",F);const W=F?.next_action?.redirect_to_url?.url;if(!W)return err__$8("No redirect URL found in Klarna payment confirmation"),P.get.onCheckoutError("Klarna payment failed"),{mode:"checkout",result:{invoice_urls:[],subscription_ids:[],customer_id:"",payment_method_id:""}};log__$7("Payment requires additional action, starting 3DS verification...");const{status:ee}=await start3dsVerification({url:W,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"Affirm verification"});if(ee===ThreeDSStatus.FAILURE)throw new Error("Verification failed");if(ee===ThreeDSStatus.CANCELLED)throw new Error("Verification cancelled");log__$7("3DS verification completed successfully");const ne=F?.payment_method?.toString()??void 0,le=await confirmPaymentFlow(O,{secure_token:R.token,checkout_attempt_id:U.checkout_attempt_id,their_pm_id:ne});return log__$7("Payment flow confirmed",le),performSimpleCheckoutOrSetup({logPrefix:"stripe-affirm",anyCdeConnection:O,checkoutPaymentMethod:T,requiredFormFields:M,confirmResult:le,usePayFirstFlow:!0})}catch(k){throw err__$8("Error in Affirm payment flow:",k),k}}),{log__:log__$6,err__:err__$7}=createOjsFlowLoggers("stripe-afterpay"),StripeAfterpayCpm=objectType({provider:literalType("afterpay"),processor_name:literalType("stripe"),metadata:objectType({stripe_pk:stringType()})}),StripeAfterpayRequiredUserActions=arrayType(objectType({our_existing_pm_id:stringType().nullish(),client_secret:stringType()})).length(1),initStripeAfterpayFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{log__$6("Checking if there are any CPMs for Stripe Afterpay...");const A=findCpmMatchingType(S.checkoutPaymentMethods,StripeAfterpayCpm);if(!A)return log__$6("No Stripe Afterpay CPM found"),{isAvailable:!1,startFlow:async()=>{}};log__$6("Starting stripe afterpay flow...");const P=S.anyCdeConnection;return(await getPrefill(P)).mode==="setup"?(log__$6("Setup mode not supported for Stripe Afterpay flow"),{isAvailable:!1,startFlow:async()=>{}}):{isAvailable:!0,startFlow:async D=>{try{return OjsFlows.stripeAfterpay.run({context:S,checkoutPaymentMethod:A,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:D??{},initResult:{isAvailable:!0}})}catch(U){throw err__$7("Error starting Afterpay flow:",U),U}}}}),runStripeAfterpayFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P})=>{log__$6("Running Stripe Afterpay pay-first flow...");const O=S.anyCdeConnection,R=await getPrefill(O);log__$6("Validating form fields...");const M=validateNonCdeFormFieldsForCC(A,P.get.onValidationError);track("billing_details_received",{...M}),log__$6("Creating cart info for pay-first flow...");const D={line_items:R.line_items.map(k=>({price_id:k.price_id,quantity:k.quantity})),promotion_code:M[FieldName.PROMOTION_CODE]||void 0,displayed_total_amount_atom:R.amount_total_atom};log__$6("Starting pay-first payment flow for Afterpay...");const U=await startPaymentFlow(O,{payment_provider:T.provider,checkout_payment_method:T,use_pay_first_flow:!0,pay_first_flow_cart_info:D,...createCustomerFieldsFromForm(M,R.checkout_settings),customer_language:detectLanguage()});log__$6("Start payment flow response",U);const C=StripeAfterpayRequiredUserActions.parse(U.required_user_actions),{client_secret:L}=C[0];log__$6("Client secret for payment intent",L);const y=findCpmMatchingType(S.checkoutPaymentMethods,StripeAfterpayCpm);if(!y)throw new Error("Stripe Afterpay CPM not found");const{stripe:_}=await createStripeElements(y.metadata.stripe_pk,{mode:"payment",currency:R.currency??"usd",amount:R.amount_total_atom});log__$6("Stripe instance created",_);const N=generateBillingAddressFromFields(M),I=`${M[FieldName.FIRST_NAME]} ${M[FieldName.LAST_NAME]}`,x={return_url:new URL("/app/3ds/success/",S.baseUrl).toString(),payment_method:{billing_details:{email:M[FieldName.EMAIL],name:I,address:{line1:N.line1,line2:N.line2||void 0,city:N.city,state:N.state,country:N.country,postal_code:N.zip_code}}}},V={handleActions:!1};log__$6(`Confirming Afterpay payment with client secret: ${L}`);try{const k=await _.confirmAfterpayClearpayPayment(L,x,V);if(log__$6("Afterpay payment confirmation result:",k),k.paymentIntent?.next_action?.type==="redirect_to_url"){const F=k.paymentIntent?.next_action?.redirect_to_url?.url;if(!F)return err__$7("No redirect URL found in Afterpay payment confirmation"),P.get.onCheckoutError("Afterpay payment failed"),{mode:"checkout",result:{invoice_urls:[],subscription_ids:[],customer_id:"",payment_method_id:""}};log__$6("Afterpay verification Required, starting verification...");const{status:W}=await start3dsVerification({url:F,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"Afterpay verification"});if(log__$6(`╰ Afterpay verification completed [Status: ${W}]`),W===ThreeDSStatus.CANCELLED)throw new Error("Afterpay verification cancelled");if(W===ThreeDSStatus.FAILURE)throw new Error("Afterpay verification failed");log__$6("Afterpay verification completed, confirming with backend...");const ee=k.paymentIntent?.payment_method?.toString()??void 0,ne=await confirmPaymentFlow(O,{secure_token:R.token,checkout_attempt_id:U.checkout_attempt_id,their_pm_id:ee});return performSimpleCheckoutOrSetup({logPrefix:"stripe-afterpay",anyCdeConnection:O,checkoutPaymentMethod:T,requiredFormFields:M,confirmResult:ne,usePayFirstFlow:!0})}else throw log__$6("No redirect URL found in Afterpay payment confirmation"),new Error("No redirect URL found in Afterpay payment confirmation")}catch(k){err__$7("Error in Afterpay checkout flow:",k);const F=k instanceof Error?k.message:"Afterpay payment failed";throw new Error(F)}}),{log__:log__$5,err__:err__$6}=createOjsFlowLoggers("stripe-klarna"),StripeKlarnaCpm=objectType({provider:literalType("klarna"),processor_name:literalType("stripe"),metadata:objectType({stripe_pk:stringType()})}),StripeKlarnaRequiredUserActions=arrayType(objectType({our_existing_pm_id:stringType().nullish(),client_secret:stringType()})).length(1),initStripeKlarnaFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{log__$5("Checking if there are any CPMs for Stripe Klarna...");const A=findCpmMatchingType(S.checkoutPaymentMethods,StripeKlarnaCpm);if(!A)return log__$5("No Stripe Klarna CPM found"),{isAvailable:!1,startFlow:async()=>{}};log__$5("Starting stripe klarna flow...");const P=S.anyCdeConnection;return(await getPrefill(P)).mode==="setup"?(log__$5("Setup mode is not supported for Stripe Klarna flow"),{isAvailable:!1,startFlow:async()=>{}}):{isAvailable:!0,startFlow:async D=>{try{return OjsFlows.stripeKlarna.run({context:S,checkoutPaymentMethod:A,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:D??{},initResult:{isAvailable:!0}})}catch(U){throw err__$6("Error starting Klarna flow:",U),U}}}}),runStripeKlarnaFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P})=>{log__$5("Running Stripe Klarna pay-first flow...");const O=S.anyCdeConnection,R=await getPrefill(O);log__$5("Validating form fields...");const M=validateNonCdeFormFieldsForCC(A,P.get.onValidationError);track("billing_details_received",{...M}),log__$5("Creating cart info for pay-first flow...");const D={line_items:R.line_items.map(k=>({price_id:k.price_id,quantity:k.quantity})),promotion_code:M[FieldName.PROMOTION_CODE]||void 0,displayed_total_amount_atom:R.amount_total_atom};log__$5("Starting pay-first payment flow for Klarna...");const U=await startPaymentFlow(O,{payment_provider:T.provider,checkout_payment_method:T,use_pay_first_flow:!0,pay_first_flow_cart_info:D,...createCustomerFieldsFromForm(M,R.checkout_settings),customer_language:detectLanguage()});log__$5("Start payment flow response",U);const C=StripeKlarnaRequiredUserActions.parse(U.required_user_actions),{client_secret:L}=C[0];log__$5("Client secret for payment intent",L);const y=findCpmMatchingType(S.checkoutPaymentMethods,StripeKlarnaCpm);if(!y)throw new Error("Stripe Klarna CPM not found");const{stripe:_}=await createStripeElements(y.metadata.stripe_pk,{mode:"payment",currency:R.currency??"usd",amount:R.amount_total_atom});log__$5("Stripe instance created",_);const N=generateBillingAddressFromFields(M),I=`${M[FieldName.FIRST_NAME]} ${M[FieldName.LAST_NAME]}`,x={return_url:new URL("/app/3ds/success/",S.baseUrl).toString(),payment_method:{billing_details:{email:M[FieldName.EMAIL],name:I,address:{line1:N.line1,line2:N.line2||void 0,city:N.city,state:N.state,country:N.country,postal_code:N.zip_code}}}},V={handleActions:!1};log__$5(`Confirming Klarna payment with client secret: ${L}`);try{const k=await _.confirmKlarnaPayment(L,x,V);if(log__$5("Klarna payment confirmation result:",k),k.paymentIntent?.next_action?.type==="redirect_to_url"){const F=k.paymentIntent?.next_action?.redirect_to_url?.url;if(!F)return err__$6("No redirect URL found in Klarna payment confirmation"),P.get.onCheckoutError("Klarna payment failed"),{mode:"checkout",result:{invoice_urls:[],subscription_ids:[],customer_id:"",payment_method_id:""}};log__$5("Klarna verification Required, starting verification...");const{status:W}=await start3dsVerification({url:F,baseUrl:S.baseUrl,frameWidth:"500px",frameHeight:"700px",frameTitle:"Klarna verification"});if(log__$5(`╰ Klarna verification completed [Status: ${W}]`),W===ThreeDSStatus.CANCELLED)throw new Error("Klarna verification cancelled");if(W===ThreeDSStatus.FAILURE)throw new Error("Klarna verification failed");log__$5("Klarna verification completed, confirming with backend...");const ee=k.paymentIntent?.payment_method?.toString()??void 0,ne=await confirmPaymentFlow(O,{secure_token:R.token,checkout_attempt_id:U.checkout_attempt_id,their_pm_id:ee});return performSimpleCheckoutOrSetup({logPrefix:"stripe-klarna",anyCdeConnection:O,checkoutPaymentMethod:T,requiredFormFields:M,confirmResult:ne,usePayFirstFlow:!0})}else throw log__$5("No redirect URL found in Klarna payment confirmation"),new Error("No redirect URL found in Klarna payment confirmation")}catch(k){err__$6("Error in Klarna checkout flow:",k);const F=k instanceof Error?k.message:"Klarna payment failed";throw new Error(F)}}),OJS_STRIPE_LINK_BTN_ID="ojs-stripe-link-btn",{log__:log__$4,err__:err__$5}=createOjsFlowLoggers("stripe-link"),StripeLinkCpm=objectType({provider:literalType("stripe_link"),processor_name:literalType("stripe"),metadata:objectType({stripe_pk:stringType()})}),StripeLinkRequiredUserActions=arrayType(objectType({our_existing_pm_id:stringType()})).length(1),initStripeLinkFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{const A=S.customInitParams.stripeLink;log__$4("Checking if there are any CPMs for Stripe Link...");const P=findCpmMatchingType(S.checkoutPaymentMethods,StripeLinkCpm);log__$4("Starting stripe link flow...");const O=S.anyCdeConnection,R=await getPrefill(O),M=R.mode==="setup";log__$4("Creating stripe elements...");const D=await getCheckoutPreviewAmount(O,R.token,M,void 0),{elements:U,stripe:C}=await createStripeElements(P.metadata.stripe_pk,{mode:"setup",currency:D.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"}),L=U.create("linkAuthentication");log__$4("Creating express checkout...");const y=U.create("expressCheckout",{buttonHeight:A?.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),_=(x,V)=>{let k=document.querySelector(x);k||(err__$5(`Recommanded to render a container with ${x} to avoid rendering in the body`),k=document.body);const F=document.createElement("div");k?.appendChild(F),L.mount(F);let W=!1,ee=!1;if(L.once("ready",()=>{ee=!0,A?.onAuthenticationElementReady?.()}),V){F.style.visibility="hidden",F.style.position="absolute",F.style.top="-1000px",F.style.left="-1000px",F.style.zIndex="-1",L.on("change",le=>{W=le.complete||!!le.value.email,ee&&A?.onAuthenticationStatusChange?.(W)});const ne=F.querySelector("iframe");ne&&new MutationObserver(()=>{const Qe=ne.offsetHeight>160;ee&&A?.onAuthenticationStatusChange?.(W||Qe)}).observe(ne,{attributes:!0,attributeFilter:["style"]})}return L},N=x=>{y.mount(x||`#${OJS_STRIPE_LINK_BTN_ID}`)},I=()=>{y.unmount()};return A?.doNotMountOnInit?log__$4("NOT mounting stripe link button (doNotMountOnInit is true)"):(log__$4("Mounting stripe link button..."),N()),A?.silentlyCheckAuthentication&&(log__$4(`Silently mounting link authentication element at #${OJS_STRIPE_LINK_BTN_ID}...`),_(`#${OJS_STRIPE_LINK_BTN_ID}`,!0)),y.on("click",async x=>{if(log__$4("Stripe Link button clicked"),A?.overrideLinkSubmit&&!await A.overrideLinkSubmit()){log__$4("Stripe Link submit aborted by overrideLinkSubmit");return}x.resolve()}),y.on("confirm",async x=>{log__$4("Stripe Link window confirmed",x);const V=await C.createPaymentMethod({elements:U,params:{billing_details:x.billingDetails}});V.error?(err__$5("error",V.error),T.get.onCheckoutError(V.error.message??"Stripe Link unknown error")):(log__$4("paymentMethod",V.paymentMethod),OjsFlows.stripeLink.run({context:S,checkoutPaymentMethod:P,nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{stripePM:V.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:N,dismountButton:I,mountLinkAuthenticationElement:x=>_(x,!1),waitForButtonToMount:async()=>await getElementByIdAsync(OJS_STRIPE_LINK_BTN_ID)}}}),runStripeLinkFlow=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O})=>{log__$4("Running Stripe Link flow...");const R=S.anyCdeConnection,M=await getPrefill(R);log__$4("Merging PM fields with form fields...");const D=fillEmptyFormInputsWithStripePM(A,O.stripePM),U=validateNonCdeFormFieldsForCC(D,P.get.onValidationError);track("billing_details_received",{...U}),log__$4("Starting payment flow...");const C=await startPaymentFlow(R,{payment_provider:T.provider,checkout_payment_method:T,their_existing_pm_id:O.stripePM.id,...createCustomerFieldsFromForm(U,M.checkout_settings),customer_language:detectLanguage()});log__$4("Start payment flow response",C);const y=StripeLinkRequiredUserActions.parse(C.required_user_actions)[0].our_existing_pm_id;if(M.mode==="setup"){log__$4("Doing payment setup...");const _=await confirmPaymentFlow(R,{secure_token:M.token,existing_cc_pm_id:y});return{mode:"setup",result:parseConfirmPaymentFlowResponse(_)}}else{log__$4("Doing checkout...");const _={secure_token:M.token,payment_input:{provider_type:T.provider},customer_email:U[FieldName.EMAIL],customer_first_name:U[FieldName.FIRST_NAME],customer_last_name:U[FieldName.LAST_NAME],customer_address:generateBillingAddressFromFields(U),customer_shipping_address:generateShippingAddressFromFields(U,M.checkout_settings),promotion_code:U[FieldName.PROMOTION_CODE],line_items:M.line_items,total_amount_atom:M.amount_total_atom,cancel_at_end:!1,checkout_payment_method:T};return{mode:"checkout",result:await performCheckout(R,_)}}}),fillEmptyFormInputsWithStripePM=(S,T)=>{const A={...S},[P,...O]=T.billing_details.name?.trim()?.split(/\s+/)??[],R=O.join(" ")||void 0;A[FieldName.EMAIL]=A[FieldName.EMAIL]||T.link?.email||T.billing_details.email||"op_unfilled@getopenpay.com",A[FieldName.ZIP_CODE]=A[FieldName.ZIP_CODE]||T.billing_details.address?.postal_code||"00000",A[FieldName.COUNTRY]=A[FieldName.COUNTRY]||T.billing_details.address?.country||"US";const M=A[FieldName.FIRST_NAME]||P||"",D=A[FieldName.LAST_NAME]||R||"";return M||D?(A[FieldName.FIRST_NAME]=M,A[FieldName.LAST_NAME]=D):(A[FieldName.FIRST_NAME]="_OP_UNKNOWN",A[FieldName.LAST_NAME]=""),log__$4("Final form inputs:",A),A},getElementByIdAsync=S=>new Promise(T=>{const A=()=>{const P=document.getElementById(S);P?T(P):requestAnimationFrame(A)};A()}),{log__:log__$3,err__:err__$4}=createOjsFlowLoggers("stripe-pr"),StripePrCpm=objectType({provider:unionType([literalType("apple_pay"),literalType("google_pay")]),processor_name:literalType("stripe"),metadata:objectType({stripe_pk:stringType()})}),initStripePrFlow=addErrorCatcherForInit(async({context:S,formCallbacks:T})=>{log__$3("Checking if there are any CPMs for Stripe PR...");const A=findCpmMatchingType(S.checkoutPaymentMethods,StripePrCpm);log__$3("Initializing Stripe PR flow...");const P=S.anyCdeConnection,O=await getPrefill(P),R=O.mode==="setup";log__$3("Getting initial preview amount");const M=await getCheckoutPreviewAmount(P,O.token,R,void 0),D=await createStripePaymentRequest(A.metadata.stripe_pk,M.amountAtom,M.currency,R);log__$3("Checking if can make payment");const U=await D.canMakePayment();if(U===null)return err__$4("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};log__$3("Stripe PR flow initialized successfully. Can make payment",U);const C=(L,y)=>OjsFlows.stripePR.run({context:S,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(S.checkoutPaymentMethods,L),nonCdeFormInputs:createInputsDictFromForm(S.formDiv),formCallbacks:T,customParams:{provider:L,overridePaymentRequest:y?.overridePaymentRequest},initResult:{processor:PaymentProcessor.Enum.stripe,pr:D,isAvailable:!0,availableProviders:{applePay:U.applePay,googlePay:U.googlePay},startFlow:C}});return{processor:PaymentProcessor.Enum.stripe,isAvailable:!0,pr:D,availableProviders:{applePay:U.applePay,googlePay:U.googlePay},startFlow:C}}),runStripePrFlow$1=addBasicCheckoutCallbackHandlers(async({context:S,checkoutPaymentMethod:T,nonCdeFormInputs:A,formCallbacks:P,customParams:O,initResult:R})=>{if(log__$3("Running Stripe PR flow..."),O.provider!==T.provider)throw new Error(`Provider mismatch. Expected ${O.provider}, got ${T.provider}`);const M=S.anyCdeConnection,D=R.pr;if(O?.overridePaymentRequest){const I=O.overridePaymentRequest;log__$3("Overriding PR amount with",I);const x=typeof I.applePayPaymentRequest=="function"?I.applePayPaymentRequest({}):I.applePayPaymentRequest;updatePrWithAmount(D,I.amount,I.pending,x,I.label)}const U=await getPrefill(M);if(!O.overridePaymentRequest){const I=U.mode==="setup";getCheckoutPreviewAmount(M,U.token,I,void 0).then(x=>{D.isShowing()||updatePrWithAmount(D,x,!1,void 0,"Total")})}log__$3("Showing PR dialog..."),D.show();const C=await waitForUserToAddPaymentMethod(D);log__$3("Stripe PM added event:",C),log__$3("Merging PM fields with form fields...");const L=fillEmptyFormInputsWithStripePm(A,C),y=validateNonCdeFormFieldsForCC(L,P.get.onValidationError);track("billing_details_received",{...y}),log__$3("PR dialog finished. Starting p ayment flow...",y);const _=await startPaymentFlowForPR(M,{fields:y,checkoutPaymentMethod:T}),N=parsePRNextActionMetadata(_);if(log__$3("Confirming PR with Stripe..."),await confirmStripePrPM(N,C),U.mode==="setup"){log__$3("Confirming payment flow for setup...");const I=await confirmPaymentFlow(M,{secure_token:U.token});return{mode:"setup",result:parseConfirmPaymentFlowResponse(I)}}else{log__$3("Performing checkout...");const I={secure_token:U.token,payment_input:{provider_type:T.provider},customer_first_name:y[FieldName.FIRST_NAME],customer_last_name:y[FieldName.LAST_NAME],customer_email:y[FieldName.EMAIL],customer_address:generateBillingAddressFromFields(y),customer_shipping_address:generateShippingAddressFromFields(y,U.checkout_settings),promotion_code:y[FieldName.PROMOTION_CODE],line_items:U.line_items,total_amount_atom:U.amount_total_atom,cancel_at_end:!1,checkout_payment_method:T};return{mode:"checkout",result:await performCheckout(M,I)}}}),fillEmptyFormInputsWithStripePm=(S,T)=>{const A={...S},[P,...O]=T.payerName?.trim()?.split(/\s+/)??[],R=O.join(" ")||void 0,M=T.paymentMethod?.billing_details?.address,D=T.shippingAddress;A[FieldName.EMAIL]=A[FieldName.EMAIL]||T.payerEmail||"op_unfilled@getopenpay.com",A[FieldName.ZIP_CODE]=A[FieldName.ZIP_CODE]||M?.postal_code||D?.postalCode||"00000",A[FieldName.COUNTRY]=A[FieldName.COUNTRY]||M?.country||D?.country||"US";const U=A[FieldName.FIRST_NAME]||P||"",C=A[FieldName.LAST_NAME]||R||"";return U||C?(A[FieldName.FIRST_NAME]=U,A[FieldName.LAST_NAME]=C):(A[FieldName.FIRST_NAME]="_OP_UNKNOWN",A[FieldName.LAST_NAME]=""),log__$3("Final form inputs:",A),A},updatePrWithAmount=(S,T,A,P,O)=>{S.update({total:T?{amount:T.amountAtom,label:O??"Total",pending:A}:void 0,currency:T?.currency,applePay:P})},parsePRNextActionMetadata=S=>{if(S.required_user_actions.length!==1)throw new Error(`Error occurred.
215
- Details: got ${S.required_user_actions.length} required user actions`);return PaymentRequestNextActionMetadata.parse(S.required_user_actions[0])},findCheckoutPaymentMethodStrict=(S,T,A)=>{const P=S.filter(O=>{const R=A===void 0?!0:O.processor_name===A,M=O.provider===T;return R&&M});if(P.length===0)throw console.warn("CPMs list",S),new Error(`No CPMs found with provider '${T}' and processor '${A}'`);return P.length!==1&&(console.warn("CPMs list",S),console.warn(`More than one CPM found with provider '${T}' and processor '${A}'`),track("more_than_one_cpm_found",{provider:T,processor:A,cpms:S})),P[0]},OjsFlows={commonCC:{init:async()=>{},run:runCommonCcFlow},stripePR:{init:initStripePrFlow,run:runStripePrFlow$1},stripeLink:{init:initStripeLinkFlow,run:runStripeLinkFlow},stripeKlarna:{init:initStripeKlarnaFlow,run:runStripeKlarnaFlow},stripeAffirm:{init:initStripeAffirmFlow,run:runStripeAffirmFlow},stripeAfterpay:{init:initStripeAfterpayFlow,run:runStripeAfterpayFlow},pockytPaypal:{init:initPockytPaypalFlow,run:runPockytPaypalFlow},paypal:{init:initPaypalFlow,run:runPaypalFlow},airwallexKlarna:{init:initAirwallexKlarnaFlow,run:runAirwallexKlarnaFlow},airwallexGooglePay:{init:initAirwallexGooglePayFlow,run:runAirwallexGooglePayFlow},airwallexApplePay:{init:initAirwallexApplePayFlow,run:runAirwallexApplePayFlow},airwallexACH:{init:async()=>{},run:runAirwallexACHFlow},airwallexEFT:{init:async()=>{},run:runAirwallexEFTFlow},airwallexBACS:{init:async()=>{},run:runAirwallexBACSFlow},airwallexSEPA:{init:async()=>{},run:runAirwallexSEPAFlow},loopCrypto:{init:initLoopFlow,run:runLoopFlow},authorizeNetApplePay:{init:initAuthnetApplePayFlow,run:runAuthnetApplePayFlow},authorizeNetGooglePay:{init:initAuthnetGooglePayFlow,run:runAuthnetGooglePayFlow},adyenGooglePay:{init:initAdyenGooglePayFlow,run:runAdyenGooglePayFlow},adyenApplePay:{init:initAdyenApplePayFlow,run:runAdyenApplePayFlow}},{log__:log__$2,err__:err__$3}=createOjsFlowLoggers("init-flows"),createInitFlowPublisher=(S,T)=>{const A=new LoadedOncePublisher;return{publisher:A,initialize:async P=>{try{if(A.current.isSuccess)throw new Error("This flow has already been initialized.");const O=await T(P);log__$2(`✔ ${S} flow initialized successfully. Result:`,O),A.set(O)}catch(O){err__$3(`𝙭 ${S} flow initialization failed. Error:`,getErrorMessage(O),"Details:",O),A.throw(O,getErrorMessage(O))}}}},startAllInitFlows=async(S,T,A)=>{await Promise.all(Object.values(S).map(P=>P.initialize({context:T,formCallbacks:A})))},createInitFlowsPublishers=()=>({stripePR:createInitFlowPublisher("Stripe PR",OjsFlows.stripePR.init),stripeLink:createInitFlowPublisher("Stripe Link",OjsFlows.stripeLink.init),stripeKlarna:createInitFlowPublisher("Stripe Klarna",OjsFlows.stripeKlarna.init),stripeAffirm:createInitFlowPublisher("Stripe Affirm",OjsFlows.stripeAffirm.init),stripeAfterpay:createInitFlowPublisher("Stripe Afterpay",OjsFlows.stripeAfterpay.init),airwallexGooglePay:createInitFlowPublisher("Airwallex GooglePay",OjsFlows.airwallexGooglePay.init),airwallexApplePay:createInitFlowPublisher("Airwallex ApplePay",OjsFlows.airwallexApplePay.init),loop:createInitFlowPublisher("Loop",OjsFlows.loopCrypto.init),paypal:createInitFlowPublisher("PayPal",OjsFlows.paypal.init),airwallexKlarna:createInitFlowPublisher("Klarna",OjsFlows.airwallexKlarna.init),pockytPaypal:createInitFlowPublisher("Pockyt PayPal",OjsFlows.pockytPaypal.init),authorizeNetGooglePay:createInitFlowPublisher("Authnet GooglePay",OjsFlows.authorizeNetGooglePay.init),authorizeNetApplePay:createInitFlowPublisher("Authnet ApplePay",OjsFlows.authorizeNetApplePay.init),adyenGooglePay:createInitFlowPublisher("Adyen GooglePay",OjsFlows.adyenGooglePay.init),adyenApplePay:createInitFlowPublisher("Adyen ApplePay",OjsFlows.adyenApplePay.init)}),{err__:err__$2}=createOjsFlowLoggers("form-callbacks"),OptionalFn=functionType().optional(),ZodFormCallbacks=objectType({onFocus:OptionalFn,onBlur:OptionalFn,onChange:OptionalFn,onLoad:OptionalFn,onLoadError:OptionalFn,onValidationError:OptionalFn,onCheckoutStarted:OptionalFn,onCheckoutSuccess:OptionalFn,onSetupPaymentMethodSuccess:OptionalFn,onCheckoutError:OptionalFn,onPaymentRequestLoad:OptionalFn}),Ye=class Ye{constructor(){this.setCallbacks=T=>{this._callbacks=Ye.createEmptyCallbacks(),Object.entries(T).forEach(([A,P])=>{const O=makeCallbackSafe(A,P??Ye.NOOP,err__$2);this._callbacks[A]=O})},this._callbacks=Ye.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ye.NOOP=()=>{},Ye.createEmptyCallbacks=()=>{const T={};return Object.keys(ZodFormCallbacks.keyof().enum).forEach(A=>{T[A]=Ye.NOOP}),T},Ye.fromObject=T=>{const A=new Ye;return A.setCallbacks(ZodFormCallbacks.parse(T)),A};let FormCallbacks=Ye;function detectFramework(){try{const S=getWindowSafe(),T=S;if(T?.next||T?.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";if(S?.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(O=>O.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(O=>O._reactRootContainer))return"react";const P=S;return P?.Vue||P?.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function getFrameworkVersion(S){try{switch(S){case"react":return null;case"nextjs":{const A=getWindowSafe();return A?.next?.version||A?.__NEXT_DATA__?.buildId||null}case"nuxt":return null;case"vue":return null;case"angular":{const A=getWindowSafe()?.document?.querySelector("[ng-version]");return A?A.getAttribute("ng-version"):null}default:return null}}catch{return null}}function getFrameworkInfo(){const S=detectFramework(),T=getFrameworkVersion(S);return{framework:S,version:T}}const getFraudMetadata=()=>{const S=window&&window.screen?window.screen.height:null,T=window&&window.screen?window.screen.width:null,A=window&&window.screen?window.screen.colorDepth:null,P=window&&window.navigator?window.navigator.javaEnabled():!1,O=window&&window.navigator?window.navigator.userAgent:null,R="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";let M=null;window&&window.navigator&&(M=window.navigator.language?window.navigator.language:window.navigator.browserLanguage);const D=new Date().getTimezoneOffset();return{color_depth:A,java_enabled:P,javascript_enabled:!0,language:M,screen_height:S,screen_width:T,time_zone_offset:D,user_agent:O,accept_header:R}};var SubmitMethods=(S=>(S.card="card",S.pockytPaypal="pockyt-paypal",S.applePay="apple-pay",S.googlePay="google-pay",S.loopCrypto="loop-crypto",S.paypal="paypal",S.klarna="klarna",S.affirm="affirm",S.afterpay="afterpay",S.stripeLink="stripe-link",S.airwallexGooglePay="airwallex-google-pay",S.airwallexApplePay="airwallex-apple-pay",S.authorizenetGooglePay="authorizenet-google-pay",S.authorizenetApplePay="authorizenet-apple-pay",S.adyenGooglePay="adyen-google-pay",S.adyenApplePay="adyen-apple-pay",S.airwallexACH="airwallex-ach",S.airwallexEFT="airwallex-eft",S.airwallexBACS="airwallex-bacs",S.airwallexSEPA="airwallex-sepa",S))(SubmitMethods||{});nativeEnumType(SubmitMethods);var PaymentProviderType=(S=>(S.ACH="ach",S.EFT="eft",S.BACS="bacs",S.SEPA="sepa",S.APPLE_PAY="apple_pay",S.CREDIT_CARD="credit_card",S.GOOGLE_PAY="google_pay",S.STRIPE_LINK="stripe_link",S.CRYPTO="crypto",S.PAYPAL="paypal",S))(PaymentProviderType||{});const getApplePayProcessors=S=>{const T=[S.airwallexApplePay,S.authorizeNetApplePay,S.adyenApplePay],A=[];T.forEach(O=>{const R=O.publisher.getValueIfLoadedElse(null);R?.isAvailable&&A.push(R)});const P=S.stripePR.publisher.getValueIfLoadedElse(null);return P?.isAvailable&&P.availableProviders.applePay&&A.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:R=>P.startFlow("apple_pay",{overridePaymentRequest:R?.overridePaymentRequest})}),{processors:A.map(O=>O.processor),isAvailable:A.length>0,isLoading:!1,startFlow:O=>startApplePayFlow(A,O)}},getGooglePayProcessors=S=>{const T=[S.airwallexGooglePay,S.authorizeNetGooglePay,S.adyenGooglePay],A=[];T.forEach(O=>{const R=O.publisher.getValueIfLoadedElse(null);R?.isAvailable&&A.push(R)});const P=S.stripePR.publisher.getValueIfLoadedElse(null);return P?.isAvailable&&P.availableProviders.googlePay&&A.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:R=>P.startFlow("google_pay",{overridePaymentRequest:R?.overridePaymentRequest})}),{processors:A.map(O=>O.processor),isAvailable:A.length>0,isLoading:!1,startFlow:O=>startGooglePayFlow(A,O)}},startApplePayFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Apple Pay processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Apple Pay processor found")},startGooglePayFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Google Pay processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Google Pay processor found")},getKlarnaProcessors=S=>{const T=[],A=S.airwallexKlarna.publisher.getValueIfLoadedElse(null);A?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.airwallex,startFlow:O=>A.startFlow(O)});const P=S.stripeKlarna.publisher.getValueIfLoadedElse(null);return P?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:O=>P.startFlow(O)}),{processors:T.map(O=>O.processor),isAvailable:T.length>0,isLoading:!1,startFlow:O=>startKlarnaFlow(T,O)}},startKlarnaFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Klarna processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Klarna processor found")},getAffirmProcessors=S=>{const T=[],A=S.stripeAffirm.publisher.getValueIfLoadedElse(null);return A?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:P=>A.startFlow(P)}),{processors:T.map(P=>P.processor),isAvailable:T.length>0,isLoading:!1,startFlow:P=>startAffirmFlow(T,P)}},startAffirmFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Affirm processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Affirm processor found")},getAfterpayProcessors=S=>{const T=[],A=S.stripeAfterpay.publisher.getValueIfLoadedElse(null);return A?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:P=>A.startFlow(P)}),{processors:T.map(P=>P.processor),isAvailable:T.length>0,isLoading:!1,startFlow:P=>startAfterpayFlow(T,P)}},startAfterpayFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Afterpay processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Afterpay processor found")},convertStylesToQueryString=S=>JSON.stringify(S),{log__:log__$1,err__:err__$1}=createOjsFlowLoggers("tracer"),initTracerSafe=(S,T)=>{try{initTracerUnsafe(S,T)}catch(A){err__$1(`Error initializing tracer: ${A}`)}};let globalTracer;const initTracerUnsafe=async(S,T)=>{if(typeof window>"u")return;const A=await Promise.resolve().then(()=>index$5),{ConsoleSpanExporter:P,SimpleSpanProcessor:O,WebTracerProvider:R}=A,M=await Promise.resolve().then(()=>index$3),{FetchInstrumentation:D}=M,U=await Promise.resolve().then(()=>index$2),{ZoneContextManager:C}=U,L=await Promise.resolve().then(()=>index$4),{registerInstrumentations:y}=L,_=await Promise.resolve().then(()=>index$7),{Resource:N}=_,I=await Promise.resolve().then(()=>detectResources),{detectResourcesSync:x}=I,V=await Promise.resolve().then(()=>index$1),{OTLPTraceExporter:k}=V,F=await Promise.resolve().then(()=>index),{B3Propagator:W,B3InjectEncoding:ee}=F,ne=await Promise.resolve().then(()=>index$6),{BatchSpanProcessor:le}=ne;log__$1(`Initializing tracer with version ${S} and baseUrl ${T}`);const Re=getCollectorUrl(T);log__$1(`Using collector URL ${Re}`);const Qe=new k({url:Re}),je={"service.version":S,"service.name":"ojs"};return new R({resource:new N(je).merge(x()),spanProcessors:[new O(new P),new le(Qe,{scheduledDelayMillis:500})]}).register({contextManager:new C,propagator:new W({injectEncoding:ee.MULTI_HEADER})}),y({instrumentations:[new D({propagateTraceHeaderCorsUrls:[/.*/],ignoreUrls:[/^https:\/\/(.*\.)?adyen\.com/,/^https:\/\/(.*\.)?loopcrypto\.xyz/]})]}),globalTracer=trace.getTracer("openpay-js"),log__$1("Tracer initialized"),globalTracer},getCollectorUrl=S=>{const T=new URL(S).hostname;return T==="cde.openpaystaging.com"?"https://otel.openpaysandbox.com/v1/traces":T==="cde.getopenpay.com"?"https://otel.getopenpay.com/v1/traces":"http://localhost:4319/v1/traces"};class OpenPayFormEventHandler{constructor(T,A,P,O){this.handleMessage=R=>{if(!R.source){console.warn("[OJS] No source found");return}if(getCleanOrigin(R.origin)!==getCleanOrigin(this.baseUrl)||typeof R.data=="object"&&R.data.penpal||typeof R.data=="object"&&R.data.source&&R.data.source==="react-devtools-bridge")return;let M=null;try{M=parseEventPayload(JSON.parse(R.data))}catch{return}if(!this.validateEvent(M))return;const{elementId:U,payload:C}=M,L=C.type;switch(L){case"LAYOUT":this.internalCallbacks.setFormHeight(C.height?`${C.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(U,C.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(U,C.elementType,{obfuscatedValue:C.obfuscatedValue});break;case"CHANGE":this.formCallbacks.get.onChange(U,C.elementType,C.errors);break;case"LOADED":this.eventTargets[U]=R.source,this.internalCallbacks.onCdeLoaded(C);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(C.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(C.elementType,C.errors,U);break;default:console.warn("[form] Unhandled event type:",L)}},this.validateEvent=R=>R.formId!==this.formId||!R.elementId?(console.log("[OJS] formId",this.formId,R.formId),console.warn("[form] Ignoring unknown event:",R),!1):this.nonces.has(R.nonce)?(console.warn("[form] Ignoring duplicate event:",R),!1):(this.nonces.add(R.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=T,this.baseUrl=A,this.formCallbacks=P,this.internalCallbacks=O}}const getCleanOrigin=S=>new URL(S).origin;async function createConnection(S,T){const P=await connectToChild({iframe:S,debug:!1,childOrigin:T}).promise,O=await checkIfValidCdeConnectionObject(P);if(!isResultValid(P,O))throw new Error("Got invalid CDE connection object");return P}class ConnectionManager{constructor(){this.connections=new Map}addConnection(T,A){this.connections.set(T,A)}getConnection(){const T=this.connections.values().next().value;if(!T)throw new Error("Connection not found");return T}getAllConnections(){return this.connections}}const setupPaymentRequestHandlers=(S,T,A)=>{const{stripePR:P}=S;P.publisher.subscribe(O=>{if(O.isSuccess){const R=O.loadedValue,M=R.isAvailable&&R.availableProviders.applePay,D=R.isAvailable&&R.availableProviders.googlePay,U={apple_pay:{isLoading:!1,isAvailable:M,startFlow:async C=>{M&&runStripePrFlow("apple_pay",R,T,A,C)}},google_pay:{isLoading:!1,isAvailable:D,startFlow:async C=>{D&&runStripePrFlow("google_pay",R,T,A,C)}}};A.get.onPaymentRequestLoad(U)}})},runStripePrFlow=(S,T,A,P,O)=>OjsFlows.stripePR.run({context:A,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(A.checkoutPaymentMethods,S),nonCdeFormInputs:createInputsDictFromForm(A.formDiv),formCallbacks:P,customParams:{provider:S,overridePaymentRequest:O?.overridePaymentRequest},initResult:T}),GENERIC_CONN_ERR="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__,err__}=createOjsFlowLoggers("op-form"),$e=class $e{constructor(T){this.isDestroyed=!1,this.cdeLoadEvent=new LoadedOncePublisher,this.anyCdeConn=new LoadedOncePublisher,this.context=new LoadedOncePublisher,this.initFlows=createInitFlowsPublishers(),this.isSubmitting=!1,this.startFormInit=async()=>{const O=trace.getTracer("openpay-js"),R=O.startSpan("form.initialize",{kind:SpanKind.CLIENT,attributes:{"ojs.checkoutSecureToken":this.config.checkoutSecureToken,"ojs.deviceToken":this.deviceToken,"ojs.formId":this.formId,"ojs.version":this.ojsVersion,"ojs.release_version":this.ojsReleaseVersion,"ojs.base_url":this.baseUrl,"ojs.referrer":this.referrer}});return context.with(trace.setSpan(context.active(),R),async()=>{try{const M=this.createElement(ElementTypeEnum.CDE_BRIDGE);M.node.id="__op_internal_cde_bridge",M.node.ariaHidden="true",Object.assign(M.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),M.mount("body"),log__("CDE bridge element mounted"),log__("Initializing OpenPay form:"),log__("├ Waiting for CDE load event...");const D=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:GENERIC_CONN_ERR});log__("├ CDE load event received"),R?.addEvent("waiting_for_cde_connection"),log__("├ Waiting for CDE connection...");const U=O?.startSpan("cde.connect",void 0,context.active()),C=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:GENERIC_CONN_ERR});U?.end(),R?.addEvent("cde_connected"),log__("├ CDE connection received"),await setUserDeviceToken(C,this.deviceToken),log__("├ Creating OJS context, setting up handlers...");const L=$e.buildOjsFlowContext(this.config,D,C,this.getFormDiv());this.context.set(L),setupPaymentRequestHandlers(this.initFlows,L,this.formCallbacks),log__("├ Starting OJS init flows..."),await startAllInitFlows(this.initFlows,L,this.formCallbacks),this.formCallbacks.get.onLoad(D.totalAmountAtoms,D.currency),log__("╰ Done initializing OJS flows."),R?.setStatus({code:SpanStatusCode.OK}),track("form_loaded")}catch(M){const D=getErrorMessage(M);R?.setStatus({code:SpanStatusCode.ERROR,message:D}),err__("╰ Error initializing OP form:",D),track("form_init_error",{error:D}),this.formCallbacks.get.onLoadError(D)}finally{R?.end()}})},this.setFormHeight=O=>{this.formProperties.height=O,this.registeredElements&&Object.values(this.registeredElements).forEach(R=>{!R||R.type===ElementTypeEnum.CDE_BRIDGE||(R.node.style.height=O)})},this.onCdeLoaded=O=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(O),track("cde_loaded"))},this.onCdeLoadError=O=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(O),O),track("cde_load_error",{error:O}))},this.createElement=(O,R={})=>{if(this.checkValidFormInstance("createElement"),!this.config)throw new Error("OpenPay form not initialized");const M=_ElementTypeEnumZod.parse(O),D=document.createElement("iframe"),U=this.buildQueryString(R);D.name=`${M}-element`;const C=new URL(`/app/v1/${D.name}/`,this.config.baseUrl);return C.search=U.toString(),D.src=C.href,D.style.border="none",D.style.width="100%",this.registerIframe(M,D)},this.registerIframe=(O,R)=>{const M={type:O,node:R,mount:D=>{document.querySelector(D)?.appendChild(R),track("element_mounted",{element_type:O})}};return this.connectToElement({type:M.type,node:M.node}),this.registeredElements||(this.registeredElements={[ElementTypeEnum.CARD]:void 0,[ElementTypeEnum.CARD_NUMBER]:void 0,[ElementTypeEnum.CARD_EXPIRY]:void 0,[ElementTypeEnum.CARD_CVC]:void 0,[ElementTypeEnum.CDE_BRIDGE]:void 0}),this.registeredElements[O]=M,M},this.buildQueryString=O=>{const R=new URLSearchParams;return R.append("referer",this.referrer),R.append("formId",this.formId),O.styles&&R.append("styles",convertStylesToQueryString(O.styles)),R.append("secureToken",this.config.checkoutSecureToken),R},this.connectToElement=O=>createTrackingSpan({spanName:"connect_to_element",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},async()=>{const R=await createConnection(O.node);R.tracingContext={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},this.connectionManager.addConnection(O.type,R),!this.anyCdeConn.current.isSuccess&&O.type===ElementTypeEnum.CDE_BRIDGE&&this.anyCdeConn.set(R)}).catch(R=>err__("[FORM] Error connecting to CDE iframe",R)),this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=async O=>{if(this.isSubmitting){err__("Form is already submitting. Please wait for the submission to finish before submitting again.");return}this.isSubmitting=!0;try{const R=await createTrackingSpan({spanName:"submit_card",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer,paymentRouteId:O?.paymentRouteId},async()=>{track("submit_card",{...O}),this.checkValidFormInstance("submitCard");const M=this.context.getValueIfLoadedElse(null);if(!M)throw new Error("Please wait for the form to finish loading before submitting.");await OjsFlows.commonCC.run({context:M,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(M.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:createInputsDictFromForm(M.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:O?.paymentRouteId},initResult:void 0})});return this.isSubmitting=!1,R}catch(R){throw this.isSubmitting=!1,R}},this.getAvailablePaymentMethods=()=>createTrackingSpan({spanName:"get_available_payment_methods",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},()=>{this.checkValidFormInstance("getAvailablePaymentMethods");const O=this.context.getValueIfLoadedElse(null);if(!O)throw new Error("Please wait for the form to finish loading before getting available payment methods.");const{processors:R,isAvailable:M}=getApplePayProcessors(this.initFlows),{processors:D,isAvailable:U}=getGooglePayProcessors(this.initFlows),L=this.initFlows.paypal.publisher.getValueIfLoadedElse(null)?.isAvailable??!1,{processors:y,isAvailable:_}=getKlarnaProcessors(this.initFlows),{processors:N,isAvailable:I}=getAffirmProcessors(this.initFlows),{processors:x,isAvailable:V}=getAfterpayProcessors(this.initFlows),k=O.checkoutPaymentMethods.some(je=>je.processor_name==="pockyt"&&je.provider==="paypal"),W=this.initFlows.loop.publisher.getValueIfLoadedElse(null)?.isAvailable??!1,ee=this.initFlows.stripeLink.publisher.getValueIfLoadedElse(null),ne=ee?.isAvailable??!1,le=[{name:SubmitMethods.card,processors:[],isAvailable:!0},{name:SubmitMethods.applePay,processors:R,isAvailable:M},{name:SubmitMethods.googlePay,processors:D,isAvailable:U},{name:SubmitMethods.paypal,processors:L?[PaymentProcessor.Enum.paypal]:[],isAvailable:L},{name:SubmitMethods.klarna,processors:y,isAvailable:_},{name:SubmitMethods.affirm,processors:N,isAvailable:I},{name:SubmitMethods.afterpay,processors:x,isAvailable:V},{name:SubmitMethods.pockytPaypal,processors:k?[PaymentProcessor.Enum.pockyt]:[],isAvailable:k},{name:SubmitMethods.loopCrypto,processors:W?[PaymentProcessor.Enum.loop]:[],isAvailable:W},{name:SubmitMethods.stripeLink,processors:[PaymentProcessor.Enum.stripe],isAvailable:ne,controller:ee?.isAvailable?ee.controller:void 0}],Re={paypal:SubmitMethods.paypal,airwallexGooglePay:SubmitMethods.airwallexGooglePay,airwallexApplePay:SubmitMethods.airwallexApplePay,authorizeNetGooglePay:SubmitMethods.authorizenetGooglePay,authorizeNetApplePay:SubmitMethods.authorizenetApplePay,adyenGooglePay:SubmitMethods.adyenGooglePay,adyenApplePay:SubmitMethods.adyenApplePay};return[...Object.entries(this.initFlows).map(([je,ot])=>{const at=ot.publisher.getValueIfLoadedElse(null);return{name:Re[je]??je,processors:[],isAvailable:at?.isAvailable??!1}}),...le]}),this.generalSubmit=async(O,R)=>{if(this.isSubmitting){err__("Form is already submitting. Please wait for the submission to finish before submitting again.");return}this.isSubmitting=!0;try{const M=await createTrackingSpan({spanName:"general_form_submit",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},async()=>{track("general_form_submit",{method:O,settings:R}),this.checkValidFormInstance("generalSubmit");const D=this.context.getValueIfLoadedElse(null);if(!D)throw new Error("Please wait for the form to finish loading before submitting.");switch(O){case SubmitMethods.card:return this.submitCard(R);case SubmitMethods.pockytPaypal:return OjsFlows.pockytPaypal.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.PAYPAL,"pockyt"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:R},initResult:void 0});case SubmitMethods.paypal:return OjsFlows.paypal.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.PAYPAL,"paypal"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),initResult:void 0,customParams:{settings:R},formCallbacks:this.formCallbacks});case SubmitMethods.klarna:{const{startFlow:U}=getKlarnaProcessors(this.initFlows);return U(R)}case SubmitMethods.affirm:{const{startFlow:U}=getAffirmProcessors(this.initFlows);return U(R)}case SubmitMethods.afterpay:{const{startFlow:U}=getAfterpayProcessors(this.initFlows);return U(R)}case SubmitMethods.loopCrypto:return OjsFlows.loopCrypto.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.applePay:{const{startFlow:U}=getApplePayProcessors(this.initFlows);return U(R)}case SubmitMethods.googlePay:{const{startFlow:U}=getGooglePayProcessors(this.initFlows);return U(R)}case SubmitMethods.airwallexGooglePay:{const U=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!U){err__("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.airwallexApplePay:{const U=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!U){err__("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.authorizenetGooglePay:{const U=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!U){err__("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.authorizenetApplePay:{const U=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!U){err__("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.adyenGooglePay:{const U=this.initFlows.adyenGooglePay.publisher.getValueIfLoadedElse(null);if(!U){err__("adyen-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.adyenApplePay:{const U=this.initFlows.adyenApplePay.publisher.getValueIfLoadedElse(null);if(!U){err__("adyen-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.airwallexACH:return OjsFlows.airwallexACH.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.ACH,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.airwallexEFT:return OjsFlows.airwallexEFT.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.EFT,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.airwallexBACS:return OjsFlows.airwallexBACS.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.BACS,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.airwallexSEPA:return OjsFlows.airwallexSEPA.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.SEPA,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.stripeLink:{err__("StripeLink cannot be submitted manually. Please mount the button properly and if user completed the payment flow via StripeLink button, the payment will be submitted automatically.");return}default:assertNever(O)}});return this.isSubmitting=!1,M}catch(M){throw this.isSubmitting=!1,M}},this.submitWith=this.generalSubmit,this.submit=this.submitCard,this.destroy=()=>{log__("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const O of Object.values(this.registeredElements??{}))O&&O.node.remove();getWindowSafe()?.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),detachAnalyticsEventListeners(),this.registeredElements=null,delete window.ojs,track("form_destroyed")},this.updateCallbacks=O=>{this.formCallbacks.setCallbacks(O)},$e.assignAsSingleton(this),this.ojsVersion="0.5.23",this.ojsReleaseVersion="0.5.23",this.baseUrl=T.baseUrl??"https://cde.getopenpay.com",this.config={...T,baseUrl:this.baseUrl},this.formCallbacks=FormCallbacks.fromObject(T),this.registeredElements=null,this.formId=`opjs-form-${v4()}`,this.referrer=window.location.origin,this.formTarget=T.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new ConnectionManager,this.deviceToken=getDeviceToken(),attachAnalyticsEventListeners();const{framework:A,version:P}=getFrameworkInfo();getCurrentEnv(this.baseUrl).then(O=>{if(!metricsPublisher.current.isSuccess){const R={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:O,framework:A,frameworkVersion:P,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};metricsPublisher.set(R)}}),track("form_init"),console.log("OJS VERSION",this.ojsVersion),T.allowTracing===!0&&initTracerSafe(this.ojsVersion,this.baseUrl),this.eventHandler=new OpenPayFormEventHandler(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),getWindowSafe()?.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(T="unknown"){const A=$e.getInstance(),P={thisFormId:this.formId,currentFormId:A?.formId||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},O=`
215
+ Details: got ${S.required_user_actions.length} required user actions`);return PaymentRequestNextActionMetadata.parse(S.required_user_actions[0])},findCheckoutPaymentMethodStrict=(S,T,A)=>{const P=S.filter(O=>{const R=A===void 0?!0:O.processor_name===A,M=O.provider===T;return R&&M});if(P.length===0)throw console.warn("CPMs list",S),new Error(`No CPMs found with provider '${T}' and processor '${A}'`);return P.length!==1&&(console.warn("CPMs list",S),console.warn(`More than one CPM found with provider '${T}' and processor '${A}'`),track("more_than_one_cpm_found",{provider:T,processor:A,cpms:S})),P[0]},OjsFlows={commonCC:{init:async()=>{},run:runCommonCcFlow},stripePR:{init:initStripePrFlow,run:runStripePrFlow$1},stripeLink:{init:initStripeLinkFlow,run:runStripeLinkFlow},stripeKlarna:{init:initStripeKlarnaFlow,run:runStripeKlarnaFlow},stripeAffirm:{init:initStripeAffirmFlow,run:runStripeAffirmFlow},stripeAfterpay:{init:initStripeAfterpayFlow,run:runStripeAfterpayFlow},pockytPaypal:{init:initPockytPaypalFlow,run:runPockytPaypalFlow},paypal:{init:initPaypalFlow,run:runPaypalFlow},airwallexKlarna:{init:initAirwallexKlarnaFlow,run:runAirwallexKlarnaFlow},airwallexGooglePay:{init:initAirwallexGooglePayFlow,run:runAirwallexGooglePayFlow},airwallexApplePay:{init:initAirwallexApplePayFlow,run:runAirwallexApplePayFlow},airwallexACH:{init:async()=>{},run:runAirwallexACHFlow},airwallexEFT:{init:async()=>{},run:runAirwallexEFTFlow},airwallexBACS:{init:async()=>{},run:runAirwallexBACSFlow},airwallexSEPA:{init:async()=>{},run:runAirwallexSEPAFlow},loopCrypto:{init:initLoopFlow,run:runLoopFlow},authorizeNetApplePay:{init:initAuthnetApplePayFlow,run:runAuthnetApplePayFlow},authorizeNetGooglePay:{init:initAuthnetGooglePayFlow,run:runAuthnetGooglePayFlow},adyenGooglePay:{init:initAdyenGooglePayFlow,run:runAdyenGooglePayFlow},adyenApplePay:{init:initAdyenApplePayFlow,run:runAdyenApplePayFlow}},{log__:log__$2,err__:err__$3}=createOjsFlowLoggers("init-flows"),createInitFlowPublisher=(S,T)=>{const A=new LoadedOncePublisher;return{publisher:A,initialize:async P=>{try{if(A.current.isSuccess)throw new Error("This flow has already been initialized.");const O=await T(P);log__$2(`✔ ${S} flow initialized successfully. Result:`,O),A.set(O)}catch(O){err__$3(`𝙭 ${S} flow initialization failed. Error:`,getErrorMessage(O),"Details:",O),A.throw(O,getErrorMessage(O))}}}},startAllInitFlows=async(S,T,A)=>{await Promise.all(Object.values(S).map(P=>P.initialize({context:T,formCallbacks:A})))},createInitFlowsPublishers=()=>({stripePR:createInitFlowPublisher("Stripe PR",OjsFlows.stripePR.init),stripeLink:createInitFlowPublisher("Stripe Link",OjsFlows.stripeLink.init),stripeKlarna:createInitFlowPublisher("Stripe Klarna",OjsFlows.stripeKlarna.init),stripeAffirm:createInitFlowPublisher("Stripe Affirm",OjsFlows.stripeAffirm.init),stripeAfterpay:createInitFlowPublisher("Stripe Afterpay",OjsFlows.stripeAfterpay.init),airwallexGooglePay:createInitFlowPublisher("Airwallex GooglePay",OjsFlows.airwallexGooglePay.init),airwallexApplePay:createInitFlowPublisher("Airwallex ApplePay",OjsFlows.airwallexApplePay.init),loop:createInitFlowPublisher("Loop",OjsFlows.loopCrypto.init),paypal:createInitFlowPublisher("PayPal",OjsFlows.paypal.init),airwallexKlarna:createInitFlowPublisher("Klarna",OjsFlows.airwallexKlarna.init),pockytPaypal:createInitFlowPublisher("Pockyt PayPal",OjsFlows.pockytPaypal.init),authorizeNetGooglePay:createInitFlowPublisher("Authnet GooglePay",OjsFlows.authorizeNetGooglePay.init),authorizeNetApplePay:createInitFlowPublisher("Authnet ApplePay",OjsFlows.authorizeNetApplePay.init),adyenGooglePay:createInitFlowPublisher("Adyen GooglePay",OjsFlows.adyenGooglePay.init),adyenApplePay:createInitFlowPublisher("Adyen ApplePay",OjsFlows.adyenApplePay.init)}),{err__:err__$2}=createOjsFlowLoggers("form-callbacks"),OptionalFn=functionType().optional(),ZodFormCallbacks=objectType({onFocus:OptionalFn,onBlur:OptionalFn,onChange:OptionalFn,onLoad:OptionalFn,onLoadError:OptionalFn,onValidationError:OptionalFn,onCheckoutStarted:OptionalFn,onCheckoutSuccess:OptionalFn,onSetupPaymentMethodSuccess:OptionalFn,onCheckoutError:OptionalFn,onPaymentRequestLoad:OptionalFn}),Ye=class Ye{constructor(){this.setCallbacks=T=>{this._callbacks=Ye.createEmptyCallbacks(),Object.entries(T).forEach(([A,P])=>{const O=makeCallbackSafe(A,P??Ye.NOOP,err__$2);this._callbacks[A]=O})},this._callbacks=Ye.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ye.NOOP=()=>{},Ye.createEmptyCallbacks=()=>{const T={};return Object.keys(ZodFormCallbacks.keyof().enum).forEach(A=>{T[A]=Ye.NOOP}),T},Ye.fromObject=T=>{const A=new Ye;return A.setCallbacks(ZodFormCallbacks.parse(T)),A};let FormCallbacks=Ye;function detectFramework(){try{const S=getWindowSafe(),T=S;if(T?.next||T?.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";if(S?.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(O=>O.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(O=>O._reactRootContainer))return"react";const P=S;return P?.Vue||P?.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function getFrameworkVersion(S){try{switch(S){case"react":return null;case"nextjs":{const A=getWindowSafe();return A?.next?.version||A?.__NEXT_DATA__?.buildId||null}case"nuxt":return null;case"vue":return null;case"angular":{const A=getWindowSafe()?.document?.querySelector("[ng-version]");return A?A.getAttribute("ng-version"):null}default:return null}}catch{return null}}function getFrameworkInfo(){const S=detectFramework(),T=getFrameworkVersion(S);return{framework:S,version:T}}const getFraudMetadata=()=>{const S=window&&window.screen?window.screen.height:null,T=window&&window.screen?window.screen.width:null,A=window&&window.screen?window.screen.colorDepth:null,P=window&&window.navigator?window.navigator.javaEnabled():!1,O=window&&window.navigator?window.navigator.userAgent:null,R="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";let M=null;window&&window.navigator&&(M=window.navigator.language?window.navigator.language:window.navigator.browserLanguage);const D=new Date().getTimezoneOffset();return{color_depth:A,java_enabled:P,javascript_enabled:!0,language:M,screen_height:S,screen_width:T,time_zone_offset:D,user_agent:O,accept_header:R}};var SubmitMethods=(S=>(S.card="card",S.pockytPaypal="pockyt-paypal",S.applePay="apple-pay",S.googlePay="google-pay",S.loopCrypto="loop-crypto",S.paypal="paypal",S.klarna="klarna",S.affirm="affirm",S.afterpay="afterpay",S.stripeLink="stripe-link",S.airwallexGooglePay="airwallex-google-pay",S.airwallexApplePay="airwallex-apple-pay",S.authorizenetGooglePay="authorizenet-google-pay",S.authorizenetApplePay="authorizenet-apple-pay",S.adyenGooglePay="adyen-google-pay",S.adyenApplePay="adyen-apple-pay",S.airwallexACH="airwallex-ach",S.airwallexEFT="airwallex-eft",S.airwallexBACS="airwallex-bacs",S.airwallexSEPA="airwallex-sepa",S))(SubmitMethods||{});nativeEnumType(SubmitMethods);var PaymentProviderType=(S=>(S.ACH="ach",S.EFT="eft",S.BACS="bacs",S.SEPA="sepa",S.APPLE_PAY="apple_pay",S.CREDIT_CARD="credit_card",S.GOOGLE_PAY="google_pay",S.STRIPE_LINK="stripe_link",S.CRYPTO="crypto",S.PAYPAL="paypal",S))(PaymentProviderType||{});const getApplePayProcessors=S=>{const T=[S.airwallexApplePay,S.authorizeNetApplePay,S.adyenApplePay],A=[];T.forEach(O=>{const R=O.publisher.getValueIfLoadedElse(null);R?.isAvailable&&A.push(R)});const P=S.stripePR.publisher.getValueIfLoadedElse(null);return P?.isAvailable&&P.availableProviders.applePay&&A.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:R=>P.startFlow("apple_pay",{overridePaymentRequest:R?.overridePaymentRequest})}),{processors:A.map(O=>O.processor),isAvailable:A.length>0,isLoading:!1,startFlow:O=>startApplePayFlow(A,O)}},getGooglePayProcessors=S=>{const T=[S.airwallexGooglePay,S.authorizeNetGooglePay,S.adyenGooglePay],A=[];T.forEach(O=>{const R=O.publisher.getValueIfLoadedElse(null);R?.isAvailable&&A.push(R)});const P=S.stripePR.publisher.getValueIfLoadedElse(null);return P?.isAvailable&&P.availableProviders.googlePay&&A.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:R=>P.startFlow("google_pay",{overridePaymentRequest:R?.overridePaymentRequest})}),{processors:A.map(O=>O.processor),isAvailable:A.length>0,isLoading:!1,startFlow:O=>startGooglePayFlow(A,O)}},startApplePayFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Apple Pay processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Apple Pay processor found")},startGooglePayFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Google Pay processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Google Pay processor found")},getKlarnaProcessors=S=>{const T=[],A=S.airwallexKlarna.publisher.getValueIfLoadedElse(null);A?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.airwallex,startFlow:O=>A.startFlow(O)});const P=S.stripeKlarna.publisher.getValueIfLoadedElse(null);return P?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:O=>P.startFlow(O)}),{processors:T.map(O=>O.processor),isAvailable:T.length>0,isLoading:!1,startFlow:O=>startKlarnaFlow(T,O)}},startKlarnaFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Klarna processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Klarna processor found")},getAffirmProcessors=S=>{const T=[],A=S.stripeAffirm.publisher.getValueIfLoadedElse(null);return A?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:P=>A.startFlow(P)}),{processors:T.map(P=>P.processor),isAvailable:T.length>0,isLoading:!1,startFlow:P=>startAffirmFlow(T,P)}},startAffirmFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Affirm processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Affirm processor found")},getAfterpayProcessors=S=>{const T=[],A=S.stripeAfterpay.publisher.getValueIfLoadedElse(null);return A?.isAvailable&&T.push({isAvailable:!0,isLoading:!1,processor:PaymentProcessor.Enum.stripe,startFlow:P=>A.startFlow(P)}),{processors:T.map(P=>P.processor),isAvailable:T.length>0,isLoading:!1,startFlow:P=>startAfterpayFlow(T,P)}},startAfterpayFlow=(S,T)=>{if(T?.processor){const P=S.find(O=>O.processor===T.processor);if(P?.isAvailable)return P.startFlow(T);throw new Error(`Specified Afterpay processor ${T.processor} is not available`)}const A=S.find(P=>P.isAvailable);if(A)return A.startFlow(T);throw new Error("No available Afterpay processor found")},convertStylesToQueryString=S=>JSON.stringify(S),{log__:log__$1,err__:err__$1}=createOjsFlowLoggers("tracer"),initTracerSafe=(S,T)=>{try{initTracerUnsafe(S,T)}catch(A){err__$1(`Error initializing tracer: ${A}`)}};let globalTracer;const initTracerUnsafe=async(S,T)=>{if(typeof window>"u")return;const A=await Promise.resolve().then(()=>index$5),{ConsoleSpanExporter:P,SimpleSpanProcessor:O,WebTracerProvider:R}=A,M=await Promise.resolve().then(()=>index$3),{FetchInstrumentation:D}=M,U=await Promise.resolve().then(()=>index$2),{ZoneContextManager:C}=U,L=await Promise.resolve().then(()=>index$4),{registerInstrumentations:y}=L,_=await Promise.resolve().then(()=>index$7),{Resource:N}=_,I=await Promise.resolve().then(()=>detectResources),{detectResourcesSync:x}=I,V=await Promise.resolve().then(()=>index$1),{OTLPTraceExporter:k}=V,F=await Promise.resolve().then(()=>index),{B3Propagator:W,B3InjectEncoding:ee}=F,ne=await Promise.resolve().then(()=>index$6),{BatchSpanProcessor:le}=ne;log__$1(`Initializing tracer with version ${S} and baseUrl ${T}`);const Re=getCollectorUrl(T);log__$1(`Using collector URL ${Re}`);const Qe=new k({url:Re}),je={"service.version":S,"service.name":"ojs"};return new R({resource:new N(je).merge(x()),spanProcessors:[new O(new P),new le(Qe,{scheduledDelayMillis:500})]}).register({contextManager:new C,propagator:new W({injectEncoding:ee.MULTI_HEADER})}),y({instrumentations:[new D({propagateTraceHeaderCorsUrls:[/.*/],ignoreUrls:[/^https:\/\/(.*\.)?adyen\.com/,/^https:\/\/(.*\.)?loopcrypto\.xyz/]})]}),globalTracer=trace.getTracer("openpay-js"),log__$1("Tracer initialized"),globalTracer},getCollectorUrl=S=>{const T=new URL(S).hostname;return T==="cde.openpaystaging.com"?"https://otel.openpaysandbox.com/v1/traces":T==="cde.getopenpay.com"?"https://otel.getopenpay.com/v1/traces":"http://localhost:4319/v1/traces"};class OpenPayFormEventHandler{constructor(T,A,P,O){this.handleMessage=R=>{if(!R.source){console.warn("[OJS] No source found");return}if(getCleanOrigin(R.origin)!==getCleanOrigin(this.baseUrl)||typeof R.data=="object"&&R.data.penpal||typeof R.data=="object"&&R.data.source&&R.data.source==="react-devtools-bridge")return;let M=null;try{M=parseEventPayload(JSON.parse(R.data))}catch{return}if(!this.validateEvent(M))return;const{elementId:U,payload:C}=M,L=C.type;switch(L){case"LAYOUT":this.internalCallbacks.setFormHeight(C.height?`${C.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(U,C.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(U,C.elementType,{obfuscatedValue:C.obfuscatedValue});break;case"CHANGE":this.formCallbacks.get.onChange(U,C.elementType,C.errors);break;case"LOADED":this.eventTargets[U]=R.source,this.internalCallbacks.onCdeLoaded(C);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(C.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(C.elementType,C.errors,U);break;default:console.warn("[form] Unhandled event type:",L)}},this.validateEvent=R=>R.formId!==this.formId||!R.elementId?(console.log("[OJS] formId",this.formId,R.formId),console.warn("[form] Ignoring unknown event:",R),!1):this.nonces.has(R.nonce)?(console.warn("[form] Ignoring duplicate event:",R),!1):(this.nonces.add(R.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=T,this.baseUrl=A,this.formCallbacks=P,this.internalCallbacks=O}}const getCleanOrigin=S=>new URL(S).origin;async function createConnection(S,T){const P=await connectToChild({iframe:S,debug:!1,childOrigin:T}).promise,O=await checkIfValidCdeConnectionObject(P);if(!isResultValid(P,O))throw new Error("Got invalid CDE connection object");return P}class ConnectionManager{constructor(){this.connections=new Map}addConnection(T,A){this.connections.set(T,A)}getConnection(){const T=this.connections.values().next().value;if(!T)throw new Error("Connection not found");return T}getAllConnections(){return this.connections}}const setupPaymentRequestHandlers=(S,T,A)=>{const{stripePR:P}=S;P.publisher.subscribe(O=>{if(O.isSuccess){const R=O.loadedValue,M=R.isAvailable&&R.availableProviders.applePay,D=R.isAvailable&&R.availableProviders.googlePay,U={apple_pay:{isLoading:!1,isAvailable:M,startFlow:async C=>{M&&runStripePrFlow("apple_pay",R,T,A,C)}},google_pay:{isLoading:!1,isAvailable:D,startFlow:async C=>{D&&runStripePrFlow("google_pay",R,T,A,C)}}};A.get.onPaymentRequestLoad(U)}})},runStripePrFlow=(S,T,A,P,O)=>OjsFlows.stripePR.run({context:A,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(A.checkoutPaymentMethods,S),nonCdeFormInputs:createInputsDictFromForm(A.formDiv),formCallbacks:P,customParams:{provider:S,overridePaymentRequest:O?.overridePaymentRequest},initResult:T}),GENERIC_CONN_ERR="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__,err__}=createOjsFlowLoggers("op-form"),$e=class $e{constructor(T){this.isDestroyed=!1,this.cdeLoadEvent=new LoadedOncePublisher,this.anyCdeConn=new LoadedOncePublisher,this.context=new LoadedOncePublisher,this.initFlows=createInitFlowsPublishers(),this.isSubmitting=!1,this.startFormInit=async()=>{const O=trace.getTracer("openpay-js"),R=O.startSpan("form.initialize",{kind:SpanKind.CLIENT,attributes:{"ojs.checkoutSecureToken":this.config.checkoutSecureToken,"ojs.deviceToken":this.deviceToken,"ojs.formId":this.formId,"ojs.version":this.ojsVersion,"ojs.release_version":this.ojsReleaseVersion,"ojs.base_url":this.baseUrl,"ojs.referrer":this.referrer}});return context.with(trace.setSpan(context.active(),R),async()=>{try{const M=this.createElement(ElementTypeEnum.CDE_BRIDGE);M.node.id="__op_internal_cde_bridge",M.node.ariaHidden="true",Object.assign(M.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),M.mount("body"),log__("CDE bridge element mounted"),log__("Initializing OpenPay form:"),log__("├ Waiting for CDE load event...");const D=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:GENERIC_CONN_ERR});log__("├ CDE load event received"),R?.addEvent("waiting_for_cde_connection"),log__("├ Waiting for CDE connection...");const U=O?.startSpan("cde.connect",void 0,context.active()),C=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:GENERIC_CONN_ERR});U?.end(),R?.addEvent("cde_connected"),log__("├ CDE connection received"),await setUserDeviceToken(C,this.deviceToken),log__("├ Creating OJS context, setting up handlers...");const L=$e.buildOjsFlowContext(this.config,D,C,this.getFormDiv());this.context.set(L),setupPaymentRequestHandlers(this.initFlows,L,this.formCallbacks),log__("├ Starting OJS init flows..."),await startAllInitFlows(this.initFlows,L,this.formCallbacks),this.formCallbacks.get.onLoad(D.totalAmountAtoms,D.currency),log__("╰ Done initializing OJS flows."),R?.setStatus({code:SpanStatusCode.OK}),track("form_loaded")}catch(M){const D=getErrorMessage(M);R?.setStatus({code:SpanStatusCode.ERROR,message:D}),err__("╰ Error initializing OP form:",D),track("form_init_error",{error:D}),this.formCallbacks.get.onLoadError(D)}finally{R?.end()}})},this.setFormHeight=O=>{this.formProperties.height=O,this.registeredElements&&Object.values(this.registeredElements).forEach(R=>{!R||R.type===ElementTypeEnum.CDE_BRIDGE||(R.node.style.height=O)})},this.onCdeLoaded=O=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(O),track("cde_loaded"))},this.onCdeLoadError=O=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(O),O),track("cde_load_error",{error:O}))},this.createElement=(O,R={})=>{if(this.checkValidFormInstance("createElement"),!this.config)throw new Error("OpenPay form not initialized");const M=_ElementTypeEnumZod.parse(O),D=document.createElement("iframe"),U=this.buildQueryString(R);D.name=`${M}-element`;const C=new URL(`/app/v1/${D.name}/`,this.config.baseUrl);return C.search=U.toString(),D.src=C.href,D.style.border="none",D.style.width="100%",this.registerIframe(M,D)},this.registerIframe=(O,R)=>{const M={type:O,node:R,mount:D=>{document.querySelector(D)?.appendChild(R),track("element_mounted",{element_type:O})}};return this.connectToElement({type:M.type,node:M.node}),this.registeredElements||(this.registeredElements={[ElementTypeEnum.CARD]:void 0,[ElementTypeEnum.CARD_NUMBER]:void 0,[ElementTypeEnum.CARD_EXPIRY]:void 0,[ElementTypeEnum.CARD_CVC]:void 0,[ElementTypeEnum.CDE_BRIDGE]:void 0}),this.registeredElements[O]=M,M},this.buildQueryString=O=>{const R=new URLSearchParams;return R.append("referer",this.referrer),R.append("formId",this.formId),O.styles&&R.append("styles",convertStylesToQueryString(O.styles)),R.append("secureToken",this.config.checkoutSecureToken),R},this.connectToElement=O=>createTrackingSpan({spanName:"connect_to_element",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},async()=>{const R=await createConnection(O.node);R.tracingContext={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},this.connectionManager.addConnection(O.type,R),!this.anyCdeConn.current.isSuccess&&O.type===ElementTypeEnum.CDE_BRIDGE&&this.anyCdeConn.set(R)}).catch(R=>err__("[FORM] Error connecting to CDE iframe",R)),this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=async O=>{if(this.isSubmitting){err__("Form is already submitting. Please wait for the submission to finish before submitting again.");return}this.isSubmitting=!0;try{const R=await createTrackingSpan({spanName:"submit_card",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer,paymentRouteId:O?.paymentRouteId},async()=>{track("submit_card",{...O}),this.checkValidFormInstance("submitCard");const M=this.context.getValueIfLoadedElse(null);if(!M)throw new Error("Please wait for the form to finish loading before submitting.");await OjsFlows.commonCC.run({context:M,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(M.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:createInputsDictFromForm(M.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:O?.paymentRouteId},initResult:void 0})});return this.isSubmitting=!1,R}catch(R){throw this.isSubmitting=!1,R}},this.getAvailablePaymentMethods=()=>createTrackingSpan({spanName:"get_available_payment_methods",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},()=>{this.checkValidFormInstance("getAvailablePaymentMethods");const O=this.context.getValueIfLoadedElse(null);if(!O)throw new Error("Please wait for the form to finish loading before getting available payment methods.");const{processors:R,isAvailable:M}=getApplePayProcessors(this.initFlows),{processors:D,isAvailable:U}=getGooglePayProcessors(this.initFlows),L=this.initFlows.paypal.publisher.getValueIfLoadedElse(null)?.isAvailable??!1,{processors:y,isAvailable:_}=getKlarnaProcessors(this.initFlows),{processors:N,isAvailable:I}=getAffirmProcessors(this.initFlows),{processors:x,isAvailable:V}=getAfterpayProcessors(this.initFlows),k=O.checkoutPaymentMethods.some(je=>je.processor_name==="pockyt"&&je.provider==="paypal"),W=this.initFlows.loop.publisher.getValueIfLoadedElse(null)?.isAvailable??!1,ee=this.initFlows.stripeLink.publisher.getValueIfLoadedElse(null),ne=ee?.isAvailable??!1,le=[{name:SubmitMethods.card,processors:[],isAvailable:!0},{name:SubmitMethods.applePay,processors:R,isAvailable:M},{name:SubmitMethods.googlePay,processors:D,isAvailable:U},{name:SubmitMethods.paypal,processors:L?[PaymentProcessor.Enum.paypal]:[],isAvailable:L},{name:SubmitMethods.klarna,processors:y,isAvailable:_},{name:SubmitMethods.affirm,processors:N,isAvailable:I},{name:SubmitMethods.afterpay,processors:x,isAvailable:V},{name:SubmitMethods.pockytPaypal,processors:k?[PaymentProcessor.Enum.pockyt]:[],isAvailable:k},{name:SubmitMethods.loopCrypto,processors:W?[PaymentProcessor.Enum.loop]:[],isAvailable:W},{name:SubmitMethods.stripeLink,processors:[PaymentProcessor.Enum.stripe],isAvailable:ne,controller:ee?.isAvailable?ee.controller:void 0}],Re={paypal:SubmitMethods.paypal,airwallexGooglePay:SubmitMethods.airwallexGooglePay,airwallexApplePay:SubmitMethods.airwallexApplePay,authorizeNetGooglePay:SubmitMethods.authorizenetGooglePay,authorizeNetApplePay:SubmitMethods.authorizenetApplePay,adyenGooglePay:SubmitMethods.adyenGooglePay,adyenApplePay:SubmitMethods.adyenApplePay};return[...Object.entries(this.initFlows).map(([je,ot])=>{const at=ot.publisher.getValueIfLoadedElse(null);return{name:Re[je]??je,processors:[],isAvailable:at?.isAvailable??!1}}),...le]}),this.generalSubmit=async(O,R)=>{if(this.isSubmitting){err__("Form is already submitting. Please wait for the submission to finish before submitting again.");return}this.isSubmitting=!0;try{const M=await createTrackingSpan({spanName:"general_form_submit",checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,formId:this.formId,version:this.ojsVersion,releaseVersion:this.ojsReleaseVersion,baseUrl:this.baseUrl,referrer:this.referrer},async()=>{track("general_form_submit",{method:O,settings:R}),this.checkValidFormInstance("generalSubmit");const D=this.context.getValueIfLoadedElse(null);if(!D)throw new Error("Please wait for the form to finish loading before submitting.");switch(O){case SubmitMethods.card:return this.submitCard(R);case SubmitMethods.pockytPaypal:return OjsFlows.pockytPaypal.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.PAYPAL,"pockyt"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:R},initResult:void 0});case SubmitMethods.paypal:return OjsFlows.paypal.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.PAYPAL,"paypal"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),initResult:void 0,customParams:{settings:R},formCallbacks:this.formCallbacks});case SubmitMethods.klarna:{const{startFlow:U}=getKlarnaProcessors(this.initFlows);return U(R)}case SubmitMethods.affirm:{const{startFlow:U}=getAffirmProcessors(this.initFlows);return U(R)}case SubmitMethods.afterpay:{const{startFlow:U}=getAfterpayProcessors(this.initFlows);return U(R)}case SubmitMethods.loopCrypto:return OjsFlows.loopCrypto.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.applePay:{const{startFlow:U}=getApplePayProcessors(this.initFlows);return U(R)}case SubmitMethods.googlePay:{const{startFlow:U}=getGooglePayProcessors(this.initFlows);return U(R)}case SubmitMethods.airwallexGooglePay:{const U=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!U){err__("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.airwallexApplePay:{const U=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!U){err__("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.authorizenetGooglePay:{const U=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!U){err__("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.authorizenetApplePay:{const U=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!U){err__("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.adyenGooglePay:{const U=this.initFlows.adyenGooglePay.publisher.getValueIfLoadedElse(null);if(!U){err__("adyen-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.adyenApplePay:{const U=this.initFlows.adyenApplePay.publisher.getValueIfLoadedElse(null);if(!U){err__("adyen-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return U.startFlow(R)}case SubmitMethods.airwallexACH:return OjsFlows.airwallexACH.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.ACH,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.airwallexEFT:return OjsFlows.airwallexEFT.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.EFT,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.airwallexBACS:return OjsFlows.airwallexBACS.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.BACS,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.airwallexSEPA:return OjsFlows.airwallexSEPA.run({context:D,checkoutPaymentMethod:findCheckoutPaymentMethodStrict(D.checkoutPaymentMethods,PaymentProviderType.SEPA,"airwallex"),nonCdeFormInputs:createInputsDictFromForm(D.formDiv),formCallbacks:this.formCallbacks,customParams:R,initResult:void 0});case SubmitMethods.stripeLink:{err__("StripeLink cannot be submitted manually. Please mount the button properly and if user completed the payment flow via StripeLink button, the payment will be submitted automatically.");return}default:assertNever(O)}});return this.isSubmitting=!1,M}catch(M){throw this.isSubmitting=!1,M}},this.submitWith=this.generalSubmit,this.submit=this.submitCard,this.destroy=()=>{log__("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const O of Object.values(this.registeredElements??{}))O&&O.node.remove();getWindowSafe()?.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),detachAnalyticsEventListeners(),this.registeredElements=null,delete window.ojs,track("form_destroyed")},this.updateCallbacks=O=>{this.formCallbacks.setCallbacks(O)},$e.assignAsSingleton(this),this.ojsVersion="0.5.24",this.ojsReleaseVersion="0.5.24",this.baseUrl=T.baseUrl??"https://cde.getopenpay.com",this.config={...T,baseUrl:this.baseUrl},this.formCallbacks=FormCallbacks.fromObject(T),this.registeredElements=null,this.formId=`opjs-form-${v4()}`,this.referrer=window.location.origin,this.formTarget=T.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new ConnectionManager,this.deviceToken=getDeviceToken(),attachAnalyticsEventListeners();const{framework:A,version:P}=getFrameworkInfo();getCurrentEnv(this.baseUrl).then(O=>{if(!metricsPublisher.current.isSuccess){const R={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:O,framework:A,frameworkVersion:P,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};metricsPublisher.set(R)}}),track("form_init"),console.log("OJS VERSION",this.ojsVersion),T.allowTracing===!0&&initTracerSafe(this.ojsVersion,this.baseUrl),this.eventHandler=new OpenPayFormEventHandler(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),getWindowSafe()?.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(T="unknown"){const A=$e.getInstance(),P={thisFormId:this.formId,currentFormId:A?.formId||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},O=`
216
216
  [Warning] Invalid form instance detected.
217
217
  It looks like you are still using an old instance that has been destroyed.
218
218
  Please make sure you are using the latest instance of the form and cleanup event listeners.
@@ -1,4 +1,4 @@
1
- import { r as f, D as s, g as _, u as v } from "./index-DJGDOHhg.js";
1
+ import { r as f, D as s, g as _, u as v } from "./index-B_XmW797.js";
2
2
  var o = /* @__PURE__ */ (function() {
3
3
  var t = function(e, n) {
4
4
  return t = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(r, a) {
@@ -1,4 +1,4 @@
1
- import { c as t } from "./index-DJGDOHhg.js";
1
+ import { c as t } from "./index-B_XmW797.js";
2
2
  var r = t("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
3
3
  function u(e) {
4
4
  return e.setValue(r, !0);
@@ -1,4 +1,4 @@
1
- import { D as P, c as O_, C as s_, r as P_, u as R_, g as D_ } from "./index-DJGDOHhg.js";
1
+ import { D as P, c as O_, C as s_, r as P_, u as R_, g as D_ } from "./index-B_XmW797.js";
2
2
  import { c as A } from "./utils-De78ey-v.js";
3
3
  var C_ = function(S, E) {
4
4
  var T = typeof Symbol == "function" && S[Symbol.iterator];
@@ -1,4 +1,4 @@
1
- import { S as l, a as L, u as h, h as O, t as R } from "./url-C46JLLFd.js";
1
+ import { S as l, a as L, u as h, h as O, t as R } from "./url-UQ0zRf8J.js";
2
2
  var T;
3
3
  (function(t) {
4
4
  t.CONNECT_END = "connectEnd", t.CONNECT_START = "connectStart", t.DECODED_BODY_SIZE = "decodedBodySize", t.DOM_COMPLETE = "domComplete", t.DOM_CONTENT_LOADED_EVENT_END = "domContentLoadedEventEnd", t.DOM_CONTENT_LOADED_EVENT_START = "domContentLoadedEventStart", t.DOM_INTERACTIVE = "domInteractive", t.DOMAIN_LOOKUP_END = "domainLookupEnd", t.DOMAIN_LOOKUP_START = "domainLookupStart", t.ENCODED_BODY_SIZE = "encodedBodySize", t.FETCH_START = "fetchStart", t.LOAD_EVENT_END = "loadEventEnd", t.LOAD_EVENT_START = "loadEventStart", t.NAVIGATION_START = "navigationStart", t.REDIRECT_END = "redirectEnd", t.REDIRECT_START = "redirectStart", t.REQUEST_START = "requestStart", t.RESPONSE_END = "responseEnd", t.RESPONSE_START = "responseStart", t.SECURE_CONNECTION_START = "secureConnectionStart", t.UNLOAD_EVENT_END = "unloadEventEnd", t.UNLOAD_EVENT_START = "unloadEventStart";