@getopenpay/openpay-js 0.2.26 → 0.2.27-alpha.03957a5

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
@@ -22,4 +22,4 @@ ${t.message}`),t.message)}else return Cn(t.message);if(typeof t=="object")try{re
22
22
  `;const n=document.createElement("div"),r=n.attachShadow({mode:"open"});r.appendChild(e.content.cloneNode(!0));const o=r.querySelector("#three-ds-iframe"),s=r.querySelector(".cancel-button");return document.body.appendChild(n),{host:n,iframe:o,cancelButton:s}};function al(t,e,n){const r=async()=>{try{const s=await Yc(t,n);s&&(clearInterval(o),e(s))}catch{}};r();const o=setInterval(r,eo);return o}function il({elements:t,pollingInterval:e,resolve:n}){const r=()=>{clearInterval(e),t.host.remove(),n({status:Z.CANCELLED})};return t.cancelButton.addEventListener("click",r),()=>{t.cancelButton.removeEventListener("click",r)}}async function pn(t){const{url:e,baseUrl:n}=t,r=ao(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{r.host.remove()},1e3),o(l),c==null||c()},i=al(r.iframe,s,new URL(n).origin),c=il({elements:r,pollingInterval:i,resolve:o})})}const io=async t=>{const e=await pn(t);if(e.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===Z.FAILURE)throw new Error("3DS verification failed");return e.status!==Z.SUCCESS&&un(e.status),{href:e.href}},cl=(t,e)=>{const n=window.open(e,"_blank");if(!n)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return n},ll=async(t,e,n,r)=>{const{err__:o}=F("popup-verify");return new Promise((s,i)=>{const c=cl(t,r),l=setInterval(async()=>{try{const u=await zc(e,n);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(ne(u)),clearInterval(l),i(ne(u))}},1e3)})},{log__:ul,err__:co}=F("pockyt-cc"),dl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),pl=t=>{const e=dl.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw co(r),new Error(n)}return e.data},lo=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return ul(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const n="Error verifying 3DS verification result.";throw co(n,`Resulting URL: ${t}.
23
23
  Error: ${ne(e)}`),new Error(n)}},fl=(t,e)=>new URL(t).searchParams.get(e),ml=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,hl=async(t,e)=>{const n=pl(e),r=await io({url:n["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:lo(r.href??""),transaction_no:n["op-pockyt-txn-no"],reference_no:n["op-pockyt-ref-no"]}}},{log__:yl,err__:Vn}=F("airwallex-cc"),_l=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),gl=t=>{const e=_l.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Vn(r),new Error(n)}return e.data},vl=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,wl=t=>{try{const e=new URL(t??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return yl(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const n="Error verifying Airwallex 3DS verification result.";throw Vn(n,`Resulting URL: ${t}.
24
24
  Error: ${ne(e)}`),new Error(n)}},bl=async(t,e)=>{const n=gl(e),r=await io({url:n["op-airwallex-3ds-url"],baseUrl:t}),o=wl(r.href??""),s=n["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Vn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:n["op-airwallex-consent-id"]}}},uo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),po=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),El=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),kl=a.enum(["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__:ct,err__:Mt}=F("adyen-cc"),Cl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":El,"op-adyen-action":a.string()}),fo="Unable to process your credit card. Please contact support for assistance.",Sl=t=>{const e=Cl.safeParse(t);if(!e.success)throw Mt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(fo);return e.data},Pl=t=>JSON.parse(t),mo=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Al=async()=>{ct("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)mo()||await Pn(500);if(!mo())throw Mt("Adyen SDK not loaded properly"),new Error(fo);return ct("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},Tl=t=>{const{headers:e,locale:n,countryCode:r,component:o,host:s,cancelButton:i}=t,c=Pl(e["op-adyen-action"]);return ct(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{ct("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Mt("Authentication failed. Result:",h),l({status:Z.FAILURE,cleanup:u})},p=h=>{Mt("Adyen error:",h),l({status:Z.FAILURE,cleanup:u})},_=()=>{l({status:Z.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,b,I)=>{s.remove(),l({status:Z.SUCCESS,additionalDetails:h,cleanup:u})};Al().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:n,countryCode:r,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},xl=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,n=t??e,r=kl.safeParse(n);return r.success?(ct(`Resolved locale: ${r.data}`),r.data):(Mt(`Resolved invalid locale: ${n}. Defaulting to en-US.`),"en-US")},Il=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Rl=async(t,e,n)=>{const r=Sl(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=ao("http://example.com");i.replaceWith(o);const l=await Tl({headers:r,locale:xl(n),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===Z.FAILURE)throw new Error("3DS verification failed");if(l.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===Z.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return ct("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else un(l.status)},{log__:D,err__:ho}=F("common-cc"),{log__:yo}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Nl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var u;D("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await B(s);C("common_cc_flow_started",{...e,prefill:i}),D(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=je(n,r.get.onValidationError);C("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{D(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await Bc(o.currentCdeConnections,{session_id:t.elementsSessionId});if(Jc(d,r.get.onValidationError),i.mode==="setup"){D(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await qc(s,l);return D(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{D(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const p=await Xr(s,l);return D("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof Qr&&d.originalErrorMessage.includes("3DS_REQUIRED")){D("├ Card requires 3DS, starting non-legacy payment flow"),D("Received 3DS error response headers:",d.response.headers),C("3ds_required",{...e,...d.response.headers});const p=ml(d.response.headers);if(p){D("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const E=await hl(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=E}if(vl(d.response.headers)){D("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const E=await bl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=E}if(Il(d.response.headers)){D("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const E=await Rl(n[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=E}const h=await $c(s,l);D("├ Payment flow result:",h);const b=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?D("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):b?(D("├ Using stripe 3DS flow"),await jl(h)):(D("├ Using common 3DS flow"),await Ll(h,t.baseUrl));const I=h.cc_pm_id;if(i.mode==="setup"){D(`├ Confirming payment flow [cc_pm_id: ${I}]`);const E=await ie(s,{secure_token:i.token,existing_cc_pm_id:I});D("├ Confirm payment flow result received Result:",E);const N=Ot(E);return D(`╰ Setup completed successfully [PM ID: ${N.payment_method_id}]`),{mode:"setup",result:N}}else{D(`├ Checking out after 3DS flow [Flow: ${b?"legacy":"new"}]`);const E=await Xr(s,{...l,existing_cc_pm_id:I,do_not_use_legacy_cc_flow:b});return D("╰ Checkout completed successfully."),{mode:"checkout",result:E}}}throw ho("╰ Error checking out card info in CDE"),ho(d),d}}),Ol=t=>{const e=t.required_user_actions.find(n=>n.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return ba.parse(e)},Ml=["airwallex_payment_consent","adyen"],Dl=t=>{const e=t.required_user_actions.find(n=>Ml.includes(n.type));if(!e)throw new Error("No common 3DS action found");return ga.parse(e)},Ll=async(t,e)=>{const n=Dl(t);if(n.redirect_url==="3DS_COMPLETE"){D("├ 3DS flow completed successfully"),C("3ds_complete");return}D(`├ Using common 3DS flow [URL: ${n.redirect_url}]`),C("3ds_redirect",{...n});const{status:r}=await pn({url:n.redirect_url,baseUrl:e});if(D(`╰ 3DS verification completed [Status: ${r}]`),r===Z.CANCELLED)throw C("3ds_cancelled"),new Error("3DS verification cancelled");if(r===Z.FAILURE)throw C("3ds_failure"),new Error("3DS verification failed")},jl=async t=>{const e=Ol(t);C("3ds_stripe_redirect",{...e}),yo(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Ta(e),C("3ds_stripe_complete"),yo("╰ Stripe 3DS flow completed successfully")},le=a.enum(["stripe","airwallex","authorize_net"]);le.Enum.stripe;const _o=({scriptId:t,src:e,checkLoadedFn:n})=>{const r=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=t,i.async=!0;const c=document.getElementById(t);n()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{r.abort(),o()},{signal:r.signal}),i.addEventListener("error",()=>{r.abort(),s("Failed to load the script")},{signal:r.signal})})},{log__:Q,err__:Fl}=F("stripe-pr"),Ul=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),$l=ze(async({context:t,formCallbacks:e})=>{Q("Checking if there are any CPMs for Stripe PR...");const n=ce(t.checkoutPaymentMethods,Ul);Q("Initializing Stripe PR flow...");const r=t.anyCdeConnection,o=await B(r),s=o.mode==="setup";Q("Getting initial preview amount");const i=await it(r,o.token,s,void 0),c=await Sa(n.metadata.stripe_pk,i.amountAtom,i.currency,s);Q("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return Fl("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};Q("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>V.stripePR.run({context:t,checkoutPaymentMethod:jt(t.checkoutPaymentMethods,d),nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:le.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:le.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),Zl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o,initResult:s})=>{if(Q("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const h=o.overridePaymentRequest;Q("Overriding PR amount with",h),zl(c,h.amount,h.pending,h.applePayPaymentRequest,h.label)}Q("Showing PR dialog..."),c.show();const l=await Pa(c);Q("Stripe PM added event:",l),Q("Merging PM fields with form fields...");const u=Vl(n,l),d=je(u,r.get.onValidationError);C("billing_details_received",{...d}),Q("PR dialog finished. Starting payment flow...",d);const p=await Zc(i,{fields:d,checkoutPaymentMethod:e}),_=Gl(p);Q("Confirming PR with Stripe..."),await Aa(_,l);const f=await B(i);if(f.mode==="setup"){Q("Confirming payment flow for setup...");const h=await ie(i,{secure_token:f.token});return{mode:"setup",result:Ot(h)}}else{Q("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await $n(i,h)}}}),Vl=(t,e)=>{var d,p,_,f;const n={...t},[r,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(_=e.paymentMethod)==null?void 0:_.billing_details)==null?void 0:f.address,c=e.shippingAddress;n[m.EMAIL]=n[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",n[m.ZIP_CODE]=n[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",n[m.COUNTRY]=n[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=n[m.FIRST_NAME]||r||"",u=n[m.LAST_NAME]||s||"";return l||u?(n[m.FIRST_NAME]=l,n[m.LAST_NAME]=u):(n[m.FIRST_NAME]="_OP_UNKNOWN",n[m.LAST_NAME]=""),Q("Final form inputs:",n),n},zl=(t,e,n,r,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:n},currency:e.currency,applePay:r})},Gl=t=>{if(t.required_user_actions.length!==1)throw new Error(`Error occurred.
25
- Details: got ${t.required_user_actions.length} required user actions`);return Ea.parse(t.required_user_actions[0])},{log__:ve,err__:go}=F("pockyt-paypal"),Bl=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const ql=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var Y,Ee;ve("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await B(s);ve("Verifying CPM...");const c=Bl.parse(e);ve("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=je(n,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Kc(u);ve(`Starting payment flow... Mode: ${i.mode}`);const p=Qt(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((Y=o==null?void 0:o.settings)!=null&&Y.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",t.baseUrl).toString(),b=btoa(JSON.stringify(f)),I=new URLSearchParams({st:i.token,r:b}),E=`${h}?${I.toString()}`;if((Ee=o==null?void 0:o.settings)!=null&&Ee.useRedirectFlow)throw ve("Starting redirect mode for PayPal..."),window.location.href=E,await Pn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");ve("Starting popup mode for PayPal..."),ve("Opening paypal iframe...");const N=await ll("PayPal",s,p,E);ve("Paypal flow result",N);const x=lo(N.href),O=fl(N.href,"catt");if(!O)throw go("Checkout attempt ID not found in redirect URL:",N.href),new Error("Checkout attempt ID not found in redirect URL");ve(`Confirming payment flow using vault ID ${x}`);const U=await ie(s,{secure_token:i.token,their_pm_id:x,checkout_attempt_id:_?O:void 0});if(ve("Confirm payment flow result",U),i.mode==="setup")return{mode:"setup",result:{payment_method_id:U.payment_methods[0].id}};if(!U.pay_first_success_response)throw go("Checkout failed, no pay-first success response:",U),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:U.pay_first_success_response}}),fn=({gateway:t,gatewayMerchantId:e,merchantName:n,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={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:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:n},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},vo=()=>_o({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let zn=null;const wo=t=>t===Fe||t===window.location.origin?"PRODUCTION":"TEST",mn=(t,e)=>{const n=wo(t);return zn===null&&(zn=new window.google.payments.api.PaymentsClient({environment:n,merchantInfo:e.merchantInfo})),zn},Yl=t=>{const e=t.required_user_actions.find(n=>n.type==="airwallex_payment_consent");return e?lr.parse(e):null},bo=(t,e)=>{var o,s,i,c;const n={...t},r=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(r){const[l,...u]=((c=(i=r.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;n[m.EMAIL]=n[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",n[m.COUNTRY]=n[m.COUNTRY]||r.countryCode||"US",n[m.ADDRESS]=n[m.ADDRESS]||r.address1||"",n[m.CITY]=n[m.CITY]||r.locality||"",n[m.ZIP_CODE]=n[m.ZIP_CODE]||r.postalCode||"00000",n[m.STATE]=n[m.STATE]||r.administrativeArea||"";const p=n[m.FIRST_NAME]||l||"",_=n[m.LAST_NAME]||d||"";p||_?(n[m.FIRST_NAME]=p,n[m.LAST_NAME]=_):(n[m.FIRST_NAME]="_OP_UNKNOWN",n[m.LAST_NAME]="")}return n},{log__:ue,err__:lt}=F("awx-google-pay"),Wl=ze(async({context:t,formCallbacks:e})=>{var p,_;const n={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,po);if(!r)return n;ue("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return lt("No gateway merchant ID found in processor account"),n;if(ue("Loading Google Pay script"),await vo(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return lt("Google Pay SDK not loaded properly"),n;if(wo(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return lt("Google Pay merchant ID is required for production environment"),n;ue("Google Pay SDK loaded",window.google.payments);try{const f=fn({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await mn(t.baseUrl,f).isReadyToPay(f);if(!h)return ue("Google Pay is not available for this user"),n}catch(f){return lt("Error checking Google Pay availability",f),n}const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async f=>{try{V.airwallexGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){lt("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Hl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var f,h,b,I,E,N,x;ue("Starting Google Pay flow...");const s=ce(t.checkoutPaymentMethods,po),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=fn({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,p=await B(d);C("google_pay_flow_started",{processor_name:s.processor_name,prefill:no(p,["brand"]),overridePaymentRequest:c});const _=mn(t.baseUrl,u);try{const O=await _.loadPaymentData(u);ue("Google Pay Payment data",O);const U=bo(n,O),Y=je(U,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);C("billing_details_received",{...Y});const Ee=(h=(f=O.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!Ee)throw new Error("No payment token received from Google Pay");const Vu=await at(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:Y[m.EMAIL],new_customer_first_name:Y[m.FIRST_NAME],new_customer_last_name:Y[m.LAST_NAME],new_customer_address:{zip_code:Y[m.ZIP_CODE],country:Y[m.COUNTRY]}}),_n=Yl(Vu);ue("Start flow next actions",_n);let Ye=await ie(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:_n==null?void 0:_n.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Ee}}}});ue("[1st] Confirm payment flow response",Ye);let qn=(I=(b=Ye.payment_methods)==null?void 0:b[0])==null?void 0:I.id;const We=(E=Ye.required_user_actions)==null?void 0:E.find($t=>$t.type==="airwallex_payment_consent");if(We&&We.redirect_url){ue("3DS Required, starting verification...",We);const{status:$t}=await pn({url:We.redirect_url,baseUrl:t.baseUrl});if(ue(`╰ 3DS verification completed [Status: ${$t}]`),$t===Z.CANCELLED)throw new Error("3DS verification cancelled");if($t===Z.FAILURE)throw new Error("3DS verification failed")}if(We&&!qn&&(Ye=await ie(d,{secure_token:p.token,their_pm_id:We.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:We.consent_id}}),ue("[2nd] Confirm payment flow response",Ye),qn=(x=(N=Ye.payment_methods)==null?void 0:N[0])==null?void 0:x.id),!qn)throw new Error("No PM ID found");return dn({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:Y,confirmResult:Ye,usePayFirstFlow:!1})}catch(O){throw lt("Google Pay payment error",O),C("google_pay_payment_error",{error:O}),new Error((O==null?void 0:O.message)??"Unknown error")}}),Eo=()=>_o({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),ko=(t,e)=>{const n=e.token.paymentMethod.billingContact,r=e.billingContact,o=e.shippingContact,s={...t};if(n||r||o){s[m.EMAIL]=s[m.EMAIL]||(n==null?void 0:n.emailAddress)||(r==null?void 0:r.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(n==null?void 0:n.countryCode)||(r==null?void 0:r.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(n==null?void 0:n.postalCode)||(r==null?void 0:r.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(n==null?void 0:n.givenName)||(r==null?void 0:r.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(n==null?void 0:n.familyName)||(r==null?void 0:r.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const Co=({total:t,prefill:e})=>{var r;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Fe).toString()};const n=(r=e.line_items)==null?void 0:r[0];if(n)return{paymentDescription:(n==null?void 0:n.description)??"",regularBilling:{amount:t.amount,label:(n==null?void 0:n.description)??"",recurringPaymentIntervalUnit:n==null?void 0:n.billing_interval,recurringPaymentIntervalCount:(n==null?void 0:n.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},So=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(n==null?void 0:n.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??r??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},{log__:hn}=F("awx-apple-pay");async function Kl(t,e){try{const r=(await Zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function Jl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");hn("3DS Required, starting verification...",t);const{status:n}=await pn({url:t.redirect_url,baseUrl:e.baseUrl});if(hn(`╰ 3DS verification completed [Status: ${n}]`),n===Z.CANCELLED)throw new Error("3DS verification cancelled");if(n===Z.FAILURE)throw new Error("3DS verification failed");const r=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return hn("[2nd] Confirm payment flow response",r),r}async function Ql(t,e){var n,r,o,s,i;try{const c=t.payment,l=ko(e.nonCdeFormInputs,c),u=je(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);C("billing_details_received",{...u});const _=(await at(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});hn("[1st] Confirm payment flow response",f);let h=(r=(n=f.payment_methods)==null?void 0:n[0])==null?void 0:r.id;const b=(o=f.required_user_actions)==null?void 0:o.find(E=>E.type==="airwallex_payment_consent");if(b!=null&&b.redirect_url&&b.consent_id&&b.their_pm_id&&(f=await Jl(b,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const I={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(I),dn({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Dt,err__:Po}=F("awx-apple-pay"),Xl=ze(async({context:t,formCallbacks:e})=>{const n={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,uo);if(!r)return n;if(Dt("Loading Apple Pay script"),await Eo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Dt("Apple Pay is not available on this device/browser"),n;if(Dt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Dt("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async p=>{try{await V.airwallexApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Po("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),eu=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var I;const s=ce(t.checkoutPaymentMethods,uo),{overridePaymentRequest:i,initialPreview:c}=r,l=t.anyCdeConnection,u=await B(l),d=u.mode==="setup",{currencyCode:p,total:_}=So({overridePaymentRequest:i,initialPreview:c,defaultLabel:(I=s==null?void 0:s.metadata)==null?void 0:I.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Co({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:no(u,["brand"]),overridePaymentRequest:i}),new Promise((E,N)=>{const x=()=>{Dt("Payment cancelled by user"),N(new Error("Payment cancelled by user"))};h.oncancel=x,h.onvalidatemerchant=async O=>{try{await Kl(O,b)}catch(U){N(U)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{C("apple_pay_payment_authorized");try{const U=await Ql(O,b);E(U)}catch(U){N(U)}},h.begin()}).catch(E=>{throw Po("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),tu=1,nu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:X,err__:Ao}=F("loop-crypto"),ru=a.object({loopFirstName:$,loopLastName:$,loopEmail:$,[m.PROMOTION_CODE]:j}),ou=(t,e,n)=>{const r=ru.safeParse(t);if(!r.success){const o=r.error.format(),s=ur(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Ao("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},su=ze(async({context:t})=>{X("Checking if there are any CPMs for Loop Crypto...");const e=ce(t.checkoutPaymentMethods,nu);X(`checkoutPaymentMethod: ${JSON.stringify(e)}`),X("Starting Loop Crypto flow...");const n=await B(t.anyCdeConnection),r=await Zn(t.anyCdeConnection,{checkout_payment_method:e});if(n.mode!=="setup"&&!e.metadata.supported_currencies.includes(n.currency))throw Error(`Currency ${n.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!r||!r.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=r.next_action_metadata;let s;n.mode==="setup"?s=tu:s=n.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=Qt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),au=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{X("Running Loop flow..."),X("context",t),X("checkoutPaymentMethod",e),X("nonCdeFormInputs",n),X("flowCallbacks",r),X("customParams",o);const s=ou(n,r.get.onValidationError),i=t.anyCdeConnection,c=await B(t.anyCdeConnection),l=c.mode!=="setup",u=await at(t.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await ie(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_success:o.success}});if(X(`Confirm result: ${d}`),c.mode==="setup"){X("Doing payment setup..."),X("├ Confirm payment flow result received Result:",d);const p=Ot(d);return X(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(X("Doing checkout..."),!d.pay_first_success_response)throw Ao("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}});async function iu(t,e){try{const r=(await Zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function cu(t,e){var n,r;try{const o=t.payment,s=ko(e.nonCdeFormInputs,o),i=je(s,e.formCallbacks.get.onValidationError);C("billing_details_received",{...i}),await at(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((r=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),dn({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const To=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),xo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:yn,err__:Io}=F("authnet-applepay"),lu=ze(async({context:t,formCallbacks:e})=>{const n={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,To);if(!r)return n;if(yn("Loading Apple Pay script"),await Eo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return yn("Apple Pay is not available on this device/browser"),n;if(!await ApplePaySession.canMakePayments())return yn("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async p=>{try{await V.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Io("Apple Pay payment error",_),C("apple_pay_payment_error",{error:_}),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),uu=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var I;const{initialPreview:s,overridePaymentRequest:i}=r,c=ce(t.checkoutPaymentMethods,To),{currencyCode:l,total:u}=So({overridePaymentRequest:i,initialPreview:s,defaultLabel:(I=c==null?void 0:c.metadata)==null?void 0:I.processor_account_name}),d=t.anyCdeConnection,p=await B(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Co({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}};C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:p,overridePaymentRequest:i});const h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((E,N)=>{h.oncancel=()=>{yn("Payment cancelled by user"),N(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async x=>{try{await iu(x,b)}catch(O){N(O)}},h.onpaymentmethodselected=()=>{const x={newTotal:f.total};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{C("apple_pay_payment_authorized");try{const O=await cu(x,b);E(O)}catch(O){N(O)}},h.begin()}).catch(E=>{throw Io("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),{log__:Ge,err__:Lt}=F("authnet-googlepay"),du=ze(async({context:t,formCallbacks:e})=>{var d,p;Ge("Initializing Authnet GooglePay flow");const n={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,xo);if(!r)return n;Ge("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return Lt("No gateway merchant ID found in processor account"),n;if(Ge("Loading Google Pay script"),await vo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Lt("Google Pay SDK not loaded properly"),n;Ge("Google Pay SDK loaded",window.google.payments);try{const _=fn({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await mn(t.baseUrl,_).isReadyToPay(_);if(!f)return Ge("Google Pay is not available for this user"),n}catch(_){return Lt("Error checking Google Pay availability",_),n}const s=t.anyCdeConnection,i=await B(s),c=i.mode==="setup",l=await it(s,i.token,c,void 0),u=async _=>{try{V.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Lt("Google Pay payment error",f),C("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),pu=Pe(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var f,h,b,I;const{initialPreview:s,overridePaymentRequest:i}=o,l=ce(t.checkoutPaymentMethods,xo).metadata,u=fn({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,p=await B(d);C("google_pay_flow_started",{processor_name:n.processor_name,prefill:p,overridePaymentRequest:i});const _=mn(t.baseUrl,u);try{const E=await _.loadPaymentData(u);Ge("Google Pay Payment data",E);const N=bo(e,E),x=je(N,r.get.onValidationError);C("billing_details_received",{...x});const O=(h=(f=E.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!O)throw new Error("No payment token received from Google Pay");const U=await at(d,{payment_provider:n.provider,checkout_payment_method:n,new_customer_email:x[m.EMAIL],new_customer_first_name:x[m.FIRST_NAME],new_customer_last_name:x[m.LAST_NAME],new_customer_address:{zip_code:x[m.ZIP_CODE],country:x[m.COUNTRY]}});Ge("Start payment flow response",U);const Y=await ie(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:n.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((I=(b=Y.payment_methods)==null?void 0:b[0])==null?void 0:I.id))throw new Error("No PM ID found");return dn({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:n,requiredFormFields:x,confirmResult:Y,usePayFirstFlow:!1})}catch(E){throw Lt("Google Pay payment error",E),C("google_pay_payment_error",{error:E}),new Error((E==null?void 0:E.message)??"Unknown error")}}),jt=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.error("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);if(r.length!==1)throw console.error("CPMs list",t),new Error(`More than one CPM found with provider '${e}' and processor '${n}'`);return r[0]},V={commonCC:{init:async()=>{},run:Nl},stripePR:{init:$l,run:Zl},stripeLink:{init:tl,run:nl},pockytPaypal:{run:ql},airwallexGooglePay:{init:Wl,run:Hl},airwallexApplePay:{init:Xl,run:eu},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:lu,run:uu},authorizeNetGooglePay:{init:du,run:pu}},{log__:fu,err__:mu}=F("init-flows"),Be=(t,e)=>{const n=new Nt;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);fu(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){mu(`𝙭 ${t} flow initialization failed. Error:`,ne(o),"Details:",o),n.throw(o,ne(o))}}}},hu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},yu=()=>({stripePR:Be("Stripe PR",V.stripePR.init),stripeLink:Be("Stripe Link",V.stripeLink.init),airwallexGooglePay:Be("Airwallex GooglePay",V.airwallexGooglePay.init),airwallexApplePay:Be("Airwallex ApplePay",V.airwallexApplePay.init),loop:Be("Loop",V.loopCrypto.init),authorizeNetGooglePay:Be("Authnet GooglePay",V.authorizeNetGooglePay.init),authorizeNetApplePay:Be("Authnet ApplePay",V.authorizeNetApplePay.init)}),{err__:_u}=F("form-callbacks"),de=a.function().optional(),Ro=a.object({onFocus:de,onBlur:de,onChange:de,onLoad:de,onLoadError:de,onValidationError:de,onCheckoutStarted:de,onCheckoutSuccess:de,onSetupPaymentMethodSuccess:de,onCheckoutError:de,onPaymentRequestLoad:de}),be=class be{constructor(){this.setCallbacks=e=>{this._callbacks=be.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=Bs(n,r??be.NOOP,_u);this._callbacks[n]=o})},this._callbacks=be.createEmptyCallbacks()}get get(){return{...this._callbacks}}};be.NOOP=()=>{},be.createEmptyCallbacks=()=>{const e={};return Object.keys(Ro.keyof().enum).forEach(n=>{e[n]=be.NOOP}),e},be.fromObject=e=>{const n=new be;return n.setCallbacks(Ro.parse(e)),n};let Gn=be;const gu="error",vu="debug",wu=console.error,bu=console.debug;typeof window<"u"&&(window._ojs_console_callbacks=[]),console.error=function(...t){wu.call(console,...t),window._ojs_console_callbacks.forEach(e=>e(gu,...t))},console.debug=function(...t){bu.call(console,...t),window._ojs_console_callbacks.forEach(e=>e(vu,...t))};const No="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ft=32,Eu=16,Oo=10,Mo=0xffffffffffff;var qe;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(qe||(qe={}));class Ut extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function ku(t){let e=Math.floor(t()*Ft);return e===Ft&&(e=Ft-1),No.charAt(e)}function Cu(t){const e=Su(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new Ut(qe.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Su(){return Tu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Pu(t,e){let n="";for(;t>0;t--)n=ku(e)+n;return n}function Au(t,e=Oo){if(isNaN(t))throw new Ut(qe.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Mo)throw new Ut(qe.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Mo}: ${t}`);if(t<0)throw new Ut(qe.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new Ut(qe.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Ft,r=No.charAt(n)+r,t=(t-n)/Ft;return r}function Tu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function xu(t,e){const n=Cu(),r=Date.now();return Au(r,Oo)+Pu(Eu,n)}const Do="op_analytics_device_token",Iu=()=>{const t=document.cookie.split(";").find(n=>n.includes(Do));if(t)return t.split("=")[1];const e=xu();return Ru(e),e},Ru=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Do}=${t}; path=/; expires=${e.toUTCString()}`};function Nu(){if(typeof window>"u")return"unknown";try{const t=window;if(t.next||t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";if(window.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(r=>r.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(r=>r._reactRootContainer))return"react";const n=window;return n.Vue||n.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Ou(t){var e,n;if(typeof window>"u")return null;try{switch(t){case"react":return null;case"nextjs":{const r=window;return((e=r.next)==null?void 0:e.version)||((n=r.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const r=document.querySelector("[ng-version]");return r?r.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Mu(){const t=Nu(),e=Ou(t);return{framework:t,version:e}}const Lo=a.enum(["dev","stg","prod"]),Du={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Lu=t=>Du[t],ju=async t=>{try{const e=await fetch(new URL("/health/environment",t)).then(n=>n.json());return Lo.parse(e.environment)}catch{return Lo.Values.prod}};class Fu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(jo(s.origin)!==jo(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=Ma(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=n,this.formCallbacks=r,this.internalCallbacks=o}}const jo=t=>new URL(t).origin;async function Uu(t,e){const r=await _r({iframe:t,debug:!1,childOrigin:e}).promise,o=await ni(r);if(!ri(r,o))throw new Error("Got invalid CDE connection object");return r}class $u{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Zu=(t,e,n)=>{const{stripePR:r}=t;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Fo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Fo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Fo=(t,e,n,r,o)=>V.stripePR.run({context:n,checkoutPaymentMethod:jt(n.checkoutPaymentMethods,t),nonCdeFormInputs:ye(n.formDiv),formCallbacks:r,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Uo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:we,err__:Te}=F("op-form"),xe=class xe{constructor(e){this.cdeLoadEvent=new Nt,this.anyCdeConn=new Nt,this.context=new Nt,this.initFlows=yu(),this.startFormInit=async()=>{try{const o=this.createElement(he.CDE_BRIDGE);o.node.id="__op_internal_cde_bridge",o.node.ariaHidden="true",Object.assign(o.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),o.mount("body"),we("CDE bridge element mounted"),we("Initializing OpenPay form:"),we("├ Waiting for CDE load event...");const s=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Uo});we("├ CDE load event received"),we("├ Waiting for CDE connection...");const i=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Uo});we("├ CDE connection received"),await Wc(i,this.deviceToken),we("├ Creating OJS context, setting up handlers...");const c=xe.buildOjsFlowContext(this.config,s,i,this.getFormDiv());this.context.set(c),Zu(this.initFlows,c,this.formCallbacks),we("├ Starting OJS init flows..."),await hu(this.initFlows,c,this.formCallbacks),this.formCallbacks.get.onLoad(s.totalAmountAtoms,s.currency),we("╰ Done initializing OJS flows."),C("form_loaded")}catch(o){const s=ne(o);Te("╰ Error initializing OP form:",s),C("form_init_error",{error:s}),this.formCallbacks.get.onLoadError(s)}},this.setFormHeight=o=>{this.formProperties.height=o,this.registeredElements&&Object.values(this.registeredElements).forEach(s=>{!s||s.type===he.CDE_BRIDGE||(s.node.style.height=o)})},this.onCdeLoaded=o=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(o),C("cde_loaded"))},this.onCdeLoadError=o=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(o),o),C("cde_load_error",{error:o}))},this.createElement=(o,s={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const i=Ys.parse(o),c=document.createElement("iframe"),l=this.buildQueryString(s);c.name=`${i}-element`;const u=new URL(`/app/v1/${c.name}/`,this.config.baseUrl);return u.search=l.toString(),c.src=u.href,c.style.border="none",c.style.width="100%",this.registerIframe(i,c)},this.registerIframe=(o,s)=>{const i={type:o,node:s,mount:c=>{var l;(l=document.querySelector(c))==null||l.appendChild(s),C("element_mounted",{element_type:o})}};return this.connectToElement({type:i.type,node:i.node}),this.registeredElements||(this.registeredElements={[he.CARD]:void 0,[he.CARD_NUMBER]:void 0,[he.CARD_EXPIRY]:void 0,[he.CARD_CVC]:void 0,[he.CDE_BRIDGE]:void 0}),this.registeredElements[o]=i,i},this.buildQueryString=o=>{const s=new URLSearchParams;return s.append("referer",this.referrer),s.append("formId",this.formId),o.styles&&s.append("styles",xa(o.styles)),s.append("secureToken",this.config.checkoutSecureToken),s},this.connectToElement=o=>{Uu(o.node).then(s=>{this.connectionManager.addConnection(o.type,s),!this.anyCdeConn.current.isSuccess&&o.type===he.CDE_BRIDGE&&this.anyCdeConn.set(s)}).catch(s=>Te("[FORM] Error connecting to CDE iframe",s))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{C("submit_card");const o=this.context.getValueIfLoadedElse(null);if(!o){Te("Please wait for the form to finish loading before submitting.");return}V.commonCC.run({context:o,checkoutPaymentMethod:jt(o.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ye(o.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Te("Please wait for the form to finish loading before getting available payment methods.");return}const s={airwallexGooglePay:te.airwallexGooglePay,airwallexApplePay:te.airwallexApplePay,authorizeNetGooglePay:te.authorizenetGooglePay,authorizeNetApplePay:te.authorizenetApplePay},i=Object.entries(this.initFlows).map(([c,l])=>({name:s[c]??c,...l.publisher.getValueIfLoadedElse(null)}));return C("get_available_payment_methods",{available_payment_methods:i}),i},this.generalSubmit=(o,s)=>{C("general_form_submit",{method:o,settings:s});const i=this.context.getValueIfLoadedElse(null);if(!i){Te("Please wait for the form to finish loading before submitting.");return}switch(o){case te.pockytPaypal:return V.pockytPaypal.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ye(i.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:s},initResult:void 0});case te.airwallexGooglePay:{const c=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!c){Te("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.airwallexApplePay:{const c=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!c){Te("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.authorizenetGooglePay:{const c=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!c){Te("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.authorizenetApplePay:{const c=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!c){Te("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.loopCrypto:return V.loopCrypto.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:ye(i.formDiv),formCallbacks:this.formCallbacks,customParams:s,initResult:void 0});default:un(o)}},this.submit=this.submitCard,this.destroy=()=>{we("Destroying OpenPay form...");for(const o of Object.values(this.registeredElements??{}))o&&o.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Lc(),this.registeredElements=null,delete window.ojs,C("form_destroyed")},this.updateCallbacks=o=>{this.formCallbacks.setCallbacks(o)},xe.assignAsSingleton(this),this.ojsVersion="0.2.26",this.ojsReleaseVersion="0.2.26",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Gn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Qt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new $u,this.deviceToken=Iu(),Dc();const{framework:n,version:r}=Mu();ju(this.baseUrl).then(o=>{Un.current.isSuccess||Un.set({checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:o,framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl})}),C("form_init"),this.eventHandler=new Fu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};xe.ojsFlows=V,xe.assignAsSingleton=e=>{if(xe.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},xe.getInstance=()=>window.ojs??null,xe.buildOjsFlowContext=(e,n,r,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Fe).origin,formDiv:o,elementsSessionId:n.sessionId,checkoutPaymentMethods:n.checkoutPaymentMethods,anyCdeConnection:r,customInitParams:e.customInitParams??{}});let Bn=xe;ke.FieldName=m,ke.OpenPayForm=Bn,ke.SubmitMethod=qs,ke.SubmitMethods=te,Object.defineProperty(ke,Symbol.toStringTag,{value:"Module"})});
25
+ Details: got ${t.required_user_actions.length} required user actions`);return Ea.parse(t.required_user_actions[0])},{log__:ve,err__:go}=F("pockyt-paypal"),Bl=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const ql=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var Y,Ee;ve("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await B(s);ve("Verifying CPM...");const c=Bl.parse(e);ve("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=je(n,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Kc(u);ve(`Starting payment flow... Mode: ${i.mode}`);const p=Qt(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((Y=o==null?void 0:o.settings)!=null&&Y.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",t.baseUrl).toString(),b=btoa(JSON.stringify(f)),I=new URLSearchParams({st:i.token,r:b}),E=`${h}?${I.toString()}`;if((Ee=o==null?void 0:o.settings)!=null&&Ee.useRedirectFlow)throw ve("Starting redirect mode for PayPal..."),window.location.href=E,await Pn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");ve("Starting popup mode for PayPal..."),ve("Opening paypal iframe...");const N=await ll("PayPal",s,p,E);ve("Paypal flow result",N);const x=lo(N.href),O=fl(N.href,"catt");if(!O)throw go("Checkout attempt ID not found in redirect URL:",N.href),new Error("Checkout attempt ID not found in redirect URL");ve(`Confirming payment flow using vault ID ${x}`);const U=await ie(s,{secure_token:i.token,their_pm_id:x,checkout_attempt_id:_?O:void 0});if(ve("Confirm payment flow result",U),i.mode==="setup")return{mode:"setup",result:{payment_method_id:U.payment_methods[0].id}};if(!U.pay_first_success_response)throw go("Checkout failed, no pay-first success response:",U),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:U.pay_first_success_response}}),fn=({gateway:t,gatewayMerchantId:e,merchantName:n,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={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:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:n},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},vo=()=>_o({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let zn=null;const wo=t=>t===Fe||t===window.location.origin?"PRODUCTION":"TEST",mn=(t,e)=>{const n=wo(t);return zn===null&&(zn=new window.google.payments.api.PaymentsClient({environment:n,merchantInfo:e.merchantInfo})),zn},Yl=t=>{const e=t.required_user_actions.find(n=>n.type==="airwallex_payment_consent");return e?lr.parse(e):null},bo=(t,e)=>{var o,s,i,c;const n={...t},r=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(r){const[l,...u]=((c=(i=r.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;n[m.EMAIL]=n[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",n[m.COUNTRY]=n[m.COUNTRY]||r.countryCode||"US",n[m.ADDRESS]=n[m.ADDRESS]||r.address1||"",n[m.CITY]=n[m.CITY]||r.locality||"",n[m.ZIP_CODE]=n[m.ZIP_CODE]||r.postalCode||"00000",n[m.STATE]=n[m.STATE]||r.administrativeArea||"";const p=n[m.FIRST_NAME]||l||"",_=n[m.LAST_NAME]||d||"";p||_?(n[m.FIRST_NAME]=p,n[m.LAST_NAME]=_):(n[m.FIRST_NAME]="_OP_UNKNOWN",n[m.LAST_NAME]="")}return n},{log__:ue,err__:lt}=F("awx-google-pay"),Wl=ze(async({context:t,formCallbacks:e})=>{var p,_;const n={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,po);if(!r)return n;ue("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return lt("No gateway merchant ID found in processor account"),n;if(ue("Loading Google Pay script"),await vo(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return lt("Google Pay SDK not loaded properly"),n;if(wo(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return lt("Google Pay merchant ID is required for production environment"),n;ue("Google Pay SDK loaded",window.google.payments);try{const f=fn({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await mn(t.baseUrl,f).isReadyToPay(f);if(!h)return ue("Google Pay is not available for this user"),n}catch(f){return lt("Error checking Google Pay availability",f),n}const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async f=>{try{V.airwallexGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){lt("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Hl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var f,h,b,I,E,N,x;ue("Starting Google Pay flow...");const s=ce(t.checkoutPaymentMethods,po),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=fn({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,p=await B(d);C("google_pay_flow_started",{processor_name:s.processor_name,prefill:no(p,["brand"]),overridePaymentRequest:c});const _=mn(t.baseUrl,u);try{const O=await _.loadPaymentData(u);ue("Google Pay Payment data",O);const U=bo(n,O),Y=je(U,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);C("billing_details_received",{...Y});const Ee=(h=(f=O.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!Ee)throw new Error("No payment token received from Google Pay");const Vu=await at(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:Y[m.EMAIL],new_customer_first_name:Y[m.FIRST_NAME],new_customer_last_name:Y[m.LAST_NAME],new_customer_address:{zip_code:Y[m.ZIP_CODE],country:Y[m.COUNTRY]}}),_n=Yl(Vu);ue("Start flow next actions",_n);let Ye=await ie(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:_n==null?void 0:_n.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Ee}}}});ue("[1st] Confirm payment flow response",Ye);let qn=(I=(b=Ye.payment_methods)==null?void 0:b[0])==null?void 0:I.id;const We=(E=Ye.required_user_actions)==null?void 0:E.find($t=>$t.type==="airwallex_payment_consent");if(We&&We.redirect_url){ue("3DS Required, starting verification...",We);const{status:$t}=await pn({url:We.redirect_url,baseUrl:t.baseUrl});if(ue(`╰ 3DS verification completed [Status: ${$t}]`),$t===Z.CANCELLED)throw new Error("3DS verification cancelled");if($t===Z.FAILURE)throw new Error("3DS verification failed")}if(We&&!qn&&(Ye=await ie(d,{secure_token:p.token,their_pm_id:We.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:We.consent_id}}),ue("[2nd] Confirm payment flow response",Ye),qn=(x=(N=Ye.payment_methods)==null?void 0:N[0])==null?void 0:x.id),!qn)throw new Error("No PM ID found");return dn({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:Y,confirmResult:Ye,usePayFirstFlow:!1})}catch(O){throw lt("Google Pay payment error",O),C("google_pay_payment_error",{error:O}),new Error((O==null?void 0:O.message)??"Unknown error")}}),Eo=()=>_o({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),ko=(t,e)=>{const n=e.token.paymentMethod.billingContact,r=e.billingContact,o=e.shippingContact,s={...t};if(n||r||o){s[m.EMAIL]=s[m.EMAIL]||(n==null?void 0:n.emailAddress)||(r==null?void 0:r.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(n==null?void 0:n.countryCode)||(r==null?void 0:r.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(n==null?void 0:n.postalCode)||(r==null?void 0:r.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(n==null?void 0:n.givenName)||(r==null?void 0:r.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(n==null?void 0:n.familyName)||(r==null?void 0:r.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const Co=({total:t,prefill:e})=>{var r;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Fe).toString()};const n=(r=e.line_items)==null?void 0:r[0];if(n)return{paymentDescription:(n==null?void 0:n.description)??"",regularBilling:{amount:t.amount,label:(n==null?void 0:n.description)??"",recurringPaymentIntervalUnit:n==null?void 0:n.billing_interval,recurringPaymentIntervalCount:(n==null?void 0:n.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},So=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(n==null?void 0:n.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??r??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},{log__:hn}=F("awx-apple-pay");async function Kl(t,e){try{const r=(await Zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function Jl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");hn("3DS Required, starting verification...",t);const{status:n}=await pn({url:t.redirect_url,baseUrl:e.baseUrl});if(hn(`╰ 3DS verification completed [Status: ${n}]`),n===Z.CANCELLED)throw new Error("3DS verification cancelled");if(n===Z.FAILURE)throw new Error("3DS verification failed");const r=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return hn("[2nd] Confirm payment flow response",r),r}async function Ql(t,e){var n,r,o,s,i;try{const c=t.payment,l=ko(e.nonCdeFormInputs,c),u=je(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);C("billing_details_received",{...u});const _=(await at(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});hn("[1st] Confirm payment flow response",f);let h=(r=(n=f.payment_methods)==null?void 0:n[0])==null?void 0:r.id;const b=(o=f.required_user_actions)==null?void 0:o.find(E=>E.type==="airwallex_payment_consent");if(b!=null&&b.redirect_url&&b.consent_id&&b.their_pm_id&&(f=await Jl(b,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const I={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(I),dn({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Dt,err__:Po}=F("awx-apple-pay"),Xl=ze(async({context:t,formCallbacks:e})=>{const n={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,uo);if(!r)return n;if(Dt("Loading Apple Pay script"),await Eo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Dt("Apple Pay is not available on this device/browser"),n;if(Dt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Dt("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async p=>{try{await V.airwallexApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Po("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),eu=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var I;const s=ce(t.checkoutPaymentMethods,uo),{overridePaymentRequest:i,initialPreview:c}=r,l=t.anyCdeConnection,u=await B(l),d=u.mode==="setup",{currencyCode:p,total:_}=So({overridePaymentRequest:i,initialPreview:c,defaultLabel:(I=s==null?void 0:s.metadata)==null?void 0:I.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Co({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:no(u,["brand"]),overridePaymentRequest:i}),new Promise((E,N)=>{const x=()=>{Dt("Payment cancelled by user"),N(new Error("Payment cancelled by user"))};h.oncancel=x,h.onvalidatemerchant=async O=>{try{await Kl(O,b)}catch(U){N(U)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{C("apple_pay_payment_authorized");try{const U=await Ql(O,b);E(U)}catch(U){N(U)}},h.begin()}).catch(E=>{throw Po("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),tu=1,nu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:X,err__:Ao}=F("loop-crypto"),ru=a.object({loopFirstName:$,loopLastName:$,loopEmail:$,[m.PROMOTION_CODE]:j}),ou=(t,e,n)=>{const r=ru.safeParse(t);if(!r.success){const o=r.error.format(),s=ur(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Ao("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},su=ze(async({context:t})=>{X("Checking if there are any CPMs for Loop Crypto...");const e=ce(t.checkoutPaymentMethods,nu);X(`checkoutPaymentMethod: ${JSON.stringify(e)}`),X("Starting Loop Crypto flow...");const n=await B(t.anyCdeConnection),r=await Zn(t.anyCdeConnection,{checkout_payment_method:e});if(n.mode!=="setup"&&!e.metadata.supported_currencies.includes(n.currency))throw Error(`Currency ${n.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!r||!r.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=r.next_action_metadata;let s;n.mode==="setup"?s=tu:s=n.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=Qt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),au=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{X("Running Loop flow..."),X("context",t),X("checkoutPaymentMethod",e),X("nonCdeFormInputs",n),X("flowCallbacks",r),X("customParams",o);const s=ou(n,r.get.onValidationError),i=t.anyCdeConnection,c=await B(t.anyCdeConnection),l=c.mode!=="setup",u=await at(t.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await ie(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_debug_info:o.success?void 0:o.debugInfo,loop_success:o.success}});if(X(`Confirm result: ${d}`),c.mode==="setup"){X("Doing payment setup..."),X("├ Confirm payment flow result received Result:",d);const p=Ot(d);return X(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(X("Doing checkout..."),!d.pay_first_success_response)throw Ao("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}});async function iu(t,e){try{const r=(await Zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function cu(t,e){var n,r;try{const o=t.payment,s=ko(e.nonCdeFormInputs,o),i=je(s,e.formCallbacks.get.onValidationError);C("billing_details_received",{...i}),await at(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((r=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),dn({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const To=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),xo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:yn,err__:Io}=F("authnet-applepay"),lu=ze(async({context:t,formCallbacks:e})=>{const n={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,To);if(!r)return n;if(yn("Loading Apple Pay script"),await Eo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return yn("Apple Pay is not available on this device/browser"),n;if(!await ApplePaySession.canMakePayments())return yn("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async p=>{try{await V.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Io("Apple Pay payment error",_),C("apple_pay_payment_error",{error:_}),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),uu=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var I;const{initialPreview:s,overridePaymentRequest:i}=r,c=ce(t.checkoutPaymentMethods,To),{currencyCode:l,total:u}=So({overridePaymentRequest:i,initialPreview:s,defaultLabel:(I=c==null?void 0:c.metadata)==null?void 0:I.processor_account_name}),d=t.anyCdeConnection,p=await B(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Co({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}};C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:p,overridePaymentRequest:i});const h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((E,N)=>{h.oncancel=()=>{yn("Payment cancelled by user"),N(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async x=>{try{await iu(x,b)}catch(O){N(O)}},h.onpaymentmethodselected=()=>{const x={newTotal:f.total};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{C("apple_pay_payment_authorized");try{const O=await cu(x,b);E(O)}catch(O){N(O)}},h.begin()}).catch(E=>{throw Io("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),{log__:Ge,err__:Lt}=F("authnet-googlepay"),du=ze(async({context:t,formCallbacks:e})=>{var d,p;Ge("Initializing Authnet GooglePay flow");const n={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,xo);if(!r)return n;Ge("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return Lt("No gateway merchant ID found in processor account"),n;if(Ge("Loading Google Pay script"),await vo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Lt("Google Pay SDK not loaded properly"),n;Ge("Google Pay SDK loaded",window.google.payments);try{const _=fn({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await mn(t.baseUrl,_).isReadyToPay(_);if(!f)return Ge("Google Pay is not available for this user"),n}catch(_){return Lt("Error checking Google Pay availability",_),n}const s=t.anyCdeConnection,i=await B(s),c=i.mode==="setup",l=await it(s,i.token,c,void 0),u=async _=>{try{V.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Lt("Google Pay payment error",f),C("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),pu=Pe(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var f,h,b,I;const{initialPreview:s,overridePaymentRequest:i}=o,l=ce(t.checkoutPaymentMethods,xo).metadata,u=fn({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,p=await B(d);C("google_pay_flow_started",{processor_name:n.processor_name,prefill:p,overridePaymentRequest:i});const _=mn(t.baseUrl,u);try{const E=await _.loadPaymentData(u);Ge("Google Pay Payment data",E);const N=bo(e,E),x=je(N,r.get.onValidationError);C("billing_details_received",{...x});const O=(h=(f=E.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!O)throw new Error("No payment token received from Google Pay");const U=await at(d,{payment_provider:n.provider,checkout_payment_method:n,new_customer_email:x[m.EMAIL],new_customer_first_name:x[m.FIRST_NAME],new_customer_last_name:x[m.LAST_NAME],new_customer_address:{zip_code:x[m.ZIP_CODE],country:x[m.COUNTRY]}});Ge("Start payment flow response",U);const Y=await ie(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:n.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((I=(b=Y.payment_methods)==null?void 0:b[0])==null?void 0:I.id))throw new Error("No PM ID found");return dn({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:n,requiredFormFields:x,confirmResult:Y,usePayFirstFlow:!1})}catch(E){throw Lt("Google Pay payment error",E),C("google_pay_payment_error",{error:E}),new Error((E==null?void 0:E.message)??"Unknown error")}}),jt=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.error("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);if(r.length!==1)throw console.error("CPMs list",t),new Error(`More than one CPM found with provider '${e}' and processor '${n}'`);return r[0]},V={commonCC:{init:async()=>{},run:Nl},stripePR:{init:$l,run:Zl},stripeLink:{init:tl,run:nl},pockytPaypal:{run:ql},airwallexGooglePay:{init:Wl,run:Hl},airwallexApplePay:{init:Xl,run:eu},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:lu,run:uu},authorizeNetGooglePay:{init:du,run:pu}},{log__:fu,err__:mu}=F("init-flows"),Be=(t,e)=>{const n=new Nt;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);fu(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){mu(`𝙭 ${t} flow initialization failed. Error:`,ne(o),"Details:",o),n.throw(o,ne(o))}}}},hu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},yu=()=>({stripePR:Be("Stripe PR",V.stripePR.init),stripeLink:Be("Stripe Link",V.stripeLink.init),airwallexGooglePay:Be("Airwallex GooglePay",V.airwallexGooglePay.init),airwallexApplePay:Be("Airwallex ApplePay",V.airwallexApplePay.init),loop:Be("Loop",V.loopCrypto.init),authorizeNetGooglePay:Be("Authnet GooglePay",V.authorizeNetGooglePay.init),authorizeNetApplePay:Be("Authnet ApplePay",V.authorizeNetApplePay.init)}),{err__:_u}=F("form-callbacks"),de=a.function().optional(),Ro=a.object({onFocus:de,onBlur:de,onChange:de,onLoad:de,onLoadError:de,onValidationError:de,onCheckoutStarted:de,onCheckoutSuccess:de,onSetupPaymentMethodSuccess:de,onCheckoutError:de,onPaymentRequestLoad:de}),be=class be{constructor(){this.setCallbacks=e=>{this._callbacks=be.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=Bs(n,r??be.NOOP,_u);this._callbacks[n]=o})},this._callbacks=be.createEmptyCallbacks()}get get(){return{...this._callbacks}}};be.NOOP=()=>{},be.createEmptyCallbacks=()=>{const e={};return Object.keys(Ro.keyof().enum).forEach(n=>{e[n]=be.NOOP}),e},be.fromObject=e=>{const n=new be;return n.setCallbacks(Ro.parse(e)),n};let Gn=be;const gu="error",vu="debug",wu=console.error,bu=console.debug;typeof window<"u"&&(window._ojs_console_callbacks=[]),console.error=function(...t){wu.call(console,...t),window._ojs_console_callbacks.forEach(e=>e(gu,...t))},console.debug=function(...t){bu.call(console,...t),window._ojs_console_callbacks.forEach(e=>e(vu,...t))};const No="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ft=32,Eu=16,Oo=10,Mo=0xffffffffffff;var qe;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(qe||(qe={}));class Ut extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function ku(t){let e=Math.floor(t()*Ft);return e===Ft&&(e=Ft-1),No.charAt(e)}function Cu(t){const e=Su(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new Ut(qe.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Su(){return Tu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Pu(t,e){let n="";for(;t>0;t--)n=ku(e)+n;return n}function Au(t,e=Oo){if(isNaN(t))throw new Ut(qe.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Mo)throw new Ut(qe.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Mo}: ${t}`);if(t<0)throw new Ut(qe.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new Ut(qe.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Ft,r=No.charAt(n)+r,t=(t-n)/Ft;return r}function Tu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function xu(t,e){const n=Cu(),r=Date.now();return Au(r,Oo)+Pu(Eu,n)}const Do="op_analytics_device_token",Iu=()=>{const t=document.cookie.split(";").find(n=>n.includes(Do));if(t)return t.split("=")[1];const e=xu();return Ru(e),e},Ru=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Do}=${t}; path=/; expires=${e.toUTCString()}`};function Nu(){if(typeof window>"u")return"unknown";try{const t=window;if(t.next||t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";if(window.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(r=>r.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(r=>r._reactRootContainer))return"react";const n=window;return n.Vue||n.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Ou(t){var e,n;if(typeof window>"u")return null;try{switch(t){case"react":return null;case"nextjs":{const r=window;return((e=r.next)==null?void 0:e.version)||((n=r.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const r=document.querySelector("[ng-version]");return r?r.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Mu(){const t=Nu(),e=Ou(t);return{framework:t,version:e}}const Lo=a.enum(["dev","stg","prod"]),Du={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Lu=t=>Du[t],ju=async t=>{try{const e=await fetch(new URL("/health/environment",t)).then(n=>n.json());return Lo.parse(e.environment)}catch{return Lo.Values.prod}};class Fu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(jo(s.origin)!==jo(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=Ma(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=n,this.formCallbacks=r,this.internalCallbacks=o}}const jo=t=>new URL(t).origin;async function Uu(t,e){const r=await _r({iframe:t,debug:!1,childOrigin:e}).promise,o=await ni(r);if(!ri(r,o))throw new Error("Got invalid CDE connection object");return r}class $u{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Zu=(t,e,n)=>{const{stripePR:r}=t;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Fo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Fo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Fo=(t,e,n,r,o)=>V.stripePR.run({context:n,checkoutPaymentMethod:jt(n.checkoutPaymentMethods,t),nonCdeFormInputs:ye(n.formDiv),formCallbacks:r,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Uo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:we,err__:Te}=F("op-form"),xe=class xe{constructor(e){this.cdeLoadEvent=new Nt,this.anyCdeConn=new Nt,this.context=new Nt,this.initFlows=yu(),this.startFormInit=async()=>{try{const o=this.createElement(he.CDE_BRIDGE);o.node.id="__op_internal_cde_bridge",o.node.ariaHidden="true",Object.assign(o.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),o.mount("body"),we("CDE bridge element mounted"),we("Initializing OpenPay form:"),we("├ Waiting for CDE load event...");const s=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Uo});we("├ CDE load event received"),we("├ Waiting for CDE connection...");const i=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Uo});we("├ CDE connection received"),await Wc(i,this.deviceToken),we("├ Creating OJS context, setting up handlers...");const c=xe.buildOjsFlowContext(this.config,s,i,this.getFormDiv());this.context.set(c),Zu(this.initFlows,c,this.formCallbacks),we("├ Starting OJS init flows..."),await hu(this.initFlows,c,this.formCallbacks),this.formCallbacks.get.onLoad(s.totalAmountAtoms,s.currency),we("╰ Done initializing OJS flows."),C("form_loaded")}catch(o){const s=ne(o);Te("╰ Error initializing OP form:",s),C("form_init_error",{error:s}),this.formCallbacks.get.onLoadError(s)}},this.setFormHeight=o=>{this.formProperties.height=o,this.registeredElements&&Object.values(this.registeredElements).forEach(s=>{!s||s.type===he.CDE_BRIDGE||(s.node.style.height=o)})},this.onCdeLoaded=o=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(o),C("cde_loaded"))},this.onCdeLoadError=o=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(o),o),C("cde_load_error",{error:o}))},this.createElement=(o,s={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const i=Ys.parse(o),c=document.createElement("iframe"),l=this.buildQueryString(s);c.name=`${i}-element`;const u=new URL(`/app/v1/${c.name}/`,this.config.baseUrl);return u.search=l.toString(),c.src=u.href,c.style.border="none",c.style.width="100%",this.registerIframe(i,c)},this.registerIframe=(o,s)=>{const i={type:o,node:s,mount:c=>{var l;(l=document.querySelector(c))==null||l.appendChild(s),C("element_mounted",{element_type:o})}};return this.connectToElement({type:i.type,node:i.node}),this.registeredElements||(this.registeredElements={[he.CARD]:void 0,[he.CARD_NUMBER]:void 0,[he.CARD_EXPIRY]:void 0,[he.CARD_CVC]:void 0,[he.CDE_BRIDGE]:void 0}),this.registeredElements[o]=i,i},this.buildQueryString=o=>{const s=new URLSearchParams;return s.append("referer",this.referrer),s.append("formId",this.formId),o.styles&&s.append("styles",xa(o.styles)),s.append("secureToken",this.config.checkoutSecureToken),s},this.connectToElement=o=>{Uu(o.node).then(s=>{this.connectionManager.addConnection(o.type,s),!this.anyCdeConn.current.isSuccess&&o.type===he.CDE_BRIDGE&&this.anyCdeConn.set(s)}).catch(s=>Te("[FORM] Error connecting to CDE iframe",s))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{C("submit_card");const o=this.context.getValueIfLoadedElse(null);if(!o){Te("Please wait for the form to finish loading before submitting.");return}V.commonCC.run({context:o,checkoutPaymentMethod:jt(o.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ye(o.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Te("Please wait for the form to finish loading before getting available payment methods.");return}const s={airwallexGooglePay:te.airwallexGooglePay,airwallexApplePay:te.airwallexApplePay,authorizeNetGooglePay:te.authorizenetGooglePay,authorizeNetApplePay:te.authorizenetApplePay},i=Object.entries(this.initFlows).map(([c,l])=>({name:s[c]??c,...l.publisher.getValueIfLoadedElse(null)}));return C("get_available_payment_methods",{available_payment_methods:i}),i},this.generalSubmit=(o,s)=>{C("general_form_submit",{method:o,settings:s});const i=this.context.getValueIfLoadedElse(null);if(!i){Te("Please wait for the form to finish loading before submitting.");return}switch(o){case te.pockytPaypal:return V.pockytPaypal.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ye(i.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:s},initResult:void 0});case te.airwallexGooglePay:{const c=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!c){Te("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.airwallexApplePay:{const c=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!c){Te("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.authorizenetGooglePay:{const c=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!c){Te("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.authorizenetApplePay:{const c=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!c){Te("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.loopCrypto:return V.loopCrypto.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:ye(i.formDiv),formCallbacks:this.formCallbacks,customParams:s,initResult:void 0});default:un(o)}},this.submit=this.submitCard,this.destroy=()=>{we("Destroying OpenPay form...");for(const o of Object.values(this.registeredElements??{}))o&&o.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Lc(),this.registeredElements=null,delete window.ojs,C("form_destroyed")},this.updateCallbacks=o=>{this.formCallbacks.setCallbacks(o)},xe.assignAsSingleton(this),this.ojsVersion="0.2.27",this.ojsReleaseVersion="0.2.27-alpha.03957a5",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Gn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Qt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new $u,this.deviceToken=Iu(),Dc();const{framework:n,version:r}=Mu();ju(this.baseUrl).then(o=>{Un.current.isSuccess||Un.set({checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:o,framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl})}),C("form_init"),this.eventHandler=new Fu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};xe.ojsFlows=V,xe.assignAsSingleton=e=>{if(xe.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},xe.getInstance=()=>window.ojs??null,xe.buildOjsFlowContext=(e,n,r,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Fe).origin,formDiv:o,elementsSessionId:n.sessionId,checkoutPaymentMethods:n.checkoutPaymentMethods,anyCdeConnection:r,customInitParams:e.customInitParams??{}});let Bn=xe;ke.FieldName=m,ke.OpenPayForm=Bn,ke.SubmitMethod=qs,ke.SubmitMethods=te,Object.defineProperty(ke,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getopenpay/openpay-js",
3
- "version": "0.2.26",
3
+ "version": "0.2.27-alpha.03957a5",
4
4
  "description": "Accept payments through OpenPay, right on your site",
5
5
  "author": "OpenPay <info@getopenpay.com> (https://getopenpay.com)",
6
6
  "license": "ISC",