@getopenpay/openpay-js 0.2.13-alpha.000ac44 → 0.2.13

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 @@ Error: ${ue(e)}`),new Error(t)}},Gi=(r,e)=>new URL(r).searchParams.get(e),Bi=r=>
22
22
  Error: ${ue(e)}`),new Error(t)}},Qi=async(r,e)=>{const t=Ki(e),n=await Nn({url:t["op-airwallex-3ds-url"],baseUrl:r}),o=Ji(n.href??""),s=t["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 Er(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},jn=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()})}),Ln=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()})}),{log__:M,err__:Fn}=U("common-cc"),{log__:Un}=U("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Xi=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var u;M("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=r.anyCdeConnection,i=await W(s);M(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Ne(t,n.get.onValidationError),l={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{}};try{M(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await di(o.currentCdeConnections,{session_id:r.elementsSessionId});if(Ai(d,n.get.onValidationError),i.mode==="setup"){M(`├ Setting up payment method in CDE [Token: ${i.token}]`);const f=await pi(s,l);return M(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{M(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const f=await vn(s,l);return M("╰ Checkout completed successfully."),{mode:"checkout",result:f}}}catch(d){if(d instanceof gn&&d.originalErrorMessage.includes("3DS_REQUIRED")){M("├ Card requires 3DS, starting non-legacy payment flow"),M("Received 3DS error response headers:",d.response.headers);const f=Bi(d.response.headers);if(f){M("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await qi(r.baseUrl,d.response.headers);l.extra_metadata.pockyt=C}if(Hi(d.response.headers)){M("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await Qi(r.baseUrl,d.response.headers);l.extra_metadata.airwallex=C}const p=await ai(s,l);M("├ Payment flow result:",p);const y=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";f?M("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):y?(M("├ Using stripe 3DS flow"),await nc(p)):(M("├ Using common 3DS flow"),await rc(p,r.baseUrl));const w=p.cc_pm_id;if(i.mode==="setup"){M(`├ Confirming payment flow [cc_pm_id: ${w}]`);const C=await pe(s,{secure_token:i.token,existing_cc_pm_id:w});M("├ Confirm payment flow result received Result:",C);const I=qt(C);return M(`╰ Setup completed successfully [PM ID: ${I.payment_method_id}]`),{mode:"setup",result:I}}else{M(`├ Checking out after 3DS flow [Flow: ${y?"legacy":"new"}]`);const C=await vn(s,{...l,existing_cc_pm_id:w,do_not_use_legacy_cc_flow:y});return M("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw Fn("╰ Error checking out card info in CDE"),Fn(d),d}}),ec=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Js.parse(e)},tc=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");if(!e)throw new Error("No common 3DS action found");return Ys.parse(e)},rc=async(r,e)=>{const t=tc(r);if(t.type==="airwallex_payment_consent"&&t.redirect_url==="3DS_COMPLETE"){M("├ Airwallex 3DS flow completed successfully");return}M(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Wt({url:t.redirect_url,baseUrl:e});if(M(`╰ 3DS verification completed [Status: ${n}]`),n===ne.CANCELLED)throw new Error("3DS verification cancelled");if(n===ne.FAILURE)throw new Error("3DS verification failed")},nc=async r=>{const e=ec(r);Un(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await oa(e),Un("╰ Stripe 3DS flow completed successfully")},oe=a.enum(["stripe","airwallex","authorize_net"]);oe.Enum.stripe;const{log__:K,err__:oc}=U("stripe-pr"),sc=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()})}),ac=et(async({context:r,formCallbacks:e})=>{K("Checking if there are any CPMs for Stripe PR...");const t=he(r.checkoutPaymentMethods,sc);K("Initializing Stripe PR flow...");const n=r.anyCdeConnection,o=await W(n),s=o.mode==="setup";K("Getting initial preview amount");const i=await Je(n,o.token,s,void 0),c=await ta(t.metadata.stripe_pk,i.amountAtom,i.currency,s);K("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return oc("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};K("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,f)=>B.stripePR.run({context:r,checkoutPaymentMethod:Qt(r.checkoutPaymentMethods,d),nonCdeFormInputs:be(r.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:f==null?void 0:f.overridePaymentRequest},initResult:{processor:oe.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:oe.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),ic=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{if(K("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=r.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const y=o.overridePaymentRequest;K("Overriding PR amount with",y),lc(c,y.amount,y.pending,y.applePayPaymentRequest)}K("Showing PR dialog..."),c.show();const l=await ra(c);K("Stripe PM added event:",l),K("Merging PM fields with form fields...");const u=cc(t,l),d=Ne(u,n.get.onValidationError);K("PR dialog finished. Starting payment flow...",d);const f=await ii(i,{fields:d,checkoutPaymentMethod:e}),_=uc(f);K("Confirming PR with Stripe..."),await na(_,l);const p=await W(i);if(p.mode==="setup"){K("Confirming payment flow for setup...");const y=await pe(i,{secure_token:p.token});return{mode:"setup",result:qt(y)}}else{K("Performing checkout...");const y={secure_token:p.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:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await _r(i,y)}}}),cc=(r,e)=>{var l,u,d,f;const t={...r},[n,...o]=((u=(l=e.payerName)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:f.address,c=e.shippingAddress;return t[m.FIRST_NAME]=t[m.FIRST_NAME]||n||"_OP_UNKNOWN",t[m.LAST_NAME]=t[m.LAST_NAME]||s||"_OP_UNKNOWN",t[m.EMAIL]=t[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US",K("Final form inputs:",t),t},lc=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},uc=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
23
23
  Details: got ${r.required_user_actions.length} required user actions`);return Qs.parse(r.required_user_actions[0])},{log__:me,err__:$n}=U("pockyt-paypal"),dc=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 pc=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var F,_e;me("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,i=await W(s);me("Verifying CPM...");const c=dc.parse(e);me("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Ne(t,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Pi(u);me(`Starting payment flow... Mode: ${i.mode}`);const f=rn(),_=i.mode!=="setup",p={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:!!((F=o==null?void 0:o.settings)!=null&&F.useRedirectFlow),frontend_token_for_redirect_flow:f},...d},y=new URL("/app/pre-action/start/",r.baseUrl).toString(),w=btoa(JSON.stringify(p)),C=new URLSearchParams({st:i.token,r:w}),I=`${y}?${C.toString()}`;if((_e=o==null?void 0:o.settings)!=null&&_e.useRedirectFlow)throw me("Starting redirect mode for PayPal..."),window.location.href=I,await Xr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");me("Starting popup mode for PayPal..."),me("Opening paypal iframe...");const T=await $i("PayPal",s,f,I);me("Paypal flow result",T);const S=Dn(T.href),D=Gi(T.href,"catt");if(!D)throw $n("Checkout attempt ID not found in redirect URL:",T.href),new Error("Checkout attempt ID not found in redirect URL");me(`Confirming payment flow using vault ID ${S}`);const L=await pe(s,{secure_token:i.token,their_pm_id:S,checkout_attempt_id:_?D:void 0});if(me("Confirm payment flow result",L),i.mode==="setup")return{mode:"setup",result:{payment_method_id:L.payment_methods[0].id}};if(!L.pay_first_success_response)throw $n("Checkout failed, no pay-first success response:",L),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:L.pay_first_success_response}}),Kt=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var f,_;const c=((f=s==null?void 0:s.amount)==null?void 0:f.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:r,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:t},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},Zn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://pay.google.com/gp/p/js/pay.js",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Google Pay SDK")),document.body.appendChild(t)});let Cr=null;const Vn=r=>r===De||r===window.location.origin?"PRODUCTION":"TEST",Ht=(r,e)=>{const t=Vn(r);return Cr===null&&(Cr=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),Cr},fc=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?Qr.parse(e):null},zn=(r,e)=>{var o,s,i,c;const t={...r},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;t[m.EMAIL]=t[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[m.COUNTRY]=t[m.COUNTRY]||n.countryCode||"US",t[m.ADDRESS]=t[m.ADDRESS]||n.address1||"",t[m.CITY]=t[m.CITY]||n.locality||"",t[m.ZIP_CODE]=t[m.ZIP_CODE]||n.postalCode||"00000",t[m.STATE]=t[m.STATE]||n.administrativeArea||"",t[m.FIRST_NAME]=t[m.FIRST_NAME]||l||"_OP_UNKNOWN",t[m.LAST_NAME]=t[m.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:se,err__:tt}=U("awx-google-pay"),hc=et(async({context:r,formCallbacks:e})=>{var f,_;const t={processor:oe.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,Ln);if(!n)return t;se("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return tt("No gateway merchant ID found in processor account"),t;if(se("Loading Google Pay SDK..."),await Zn(),!((_=(f=window.google)==null?void 0:f.payments)!=null&&_.api))return tt("Google Pay SDK not loaded properly"),t;if(Vn(r.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return tt("Google Pay merchant ID is required for production environment"),t;se("Google Pay SDK loaded",window.google.payments);try{const p=Kt({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:y}=await Ht(r.baseUrl,p).isReadyToPay(p);if(!y)return se("Google Pay is not available for this user"),t}catch(p){return tt("Error checking Google Pay availability",p),t}const i=r.anyCdeConnection,c=await W(i),l=c.mode==="setup",u=await Je(i,c.token,l,void 0),d=async p=>{try{B.airwallexGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{...p,initialPreview:u}})}catch(y){tt("Google Pay payment error",y),e.get.onCheckoutError((y==null?void 0:y.message)??"Unknown error")}};return{processor:oe.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),mc=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var f,_,p,y,w,C,I;se("Starting Google Pay flow...");const s=he(r.checkoutPaymentMethods,Ln),{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=Kt({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=Ht(r.baseUrl,u);try{const T=await d.loadPaymentData(u);se("Google Pay Payment data",T);const S=r.anyCdeConnection,D=await W(S),L=zn(t,T),F=Ne(L,n.get.onValidationError,o==null?void 0:o.defaultFieldValues),_e=(_=(f=T.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!_e)throw new Error("No payment token received from Google Pay");const Rl=await St(S,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:F[m.EMAIL],new_customer_first_name:F[m.FIRST_NAME],new_customer_last_name:F[m.LAST_NAME],new_customer_address:{zip_code:F[m.ZIP_CODE],country:F[m.COUNTRY]}}),ar=fc(Rl);se("Start flow next actions",ar);let Ze=await pe(S,{secure_token:D.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:ar==null?void 0:ar.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:_e}}}});se("[1st] Confirm payment flow response",Ze);let Dr=(y=(p=Ze.payment_methods)==null?void 0:p[0])==null?void 0:y.id;const Ve=(w=Ze.required_user_actions)==null?void 0:w.find(Rt=>Rt.type==="airwallex_payment_consent");if(Ve&&Ve.redirect_url){se("3DS Required, starting verification...",Ve);const{status:Rt}=await Wt({url:Ve.redirect_url,baseUrl:r.baseUrl});if(se(`╰ 3DS verification completed [Status: ${Rt}]`),Rt===ne.CANCELLED)throw new Error("3DS verification cancelled");if(Rt===ne.FAILURE)throw new Error("3DS verification failed")}if(Ve&&!Dr&&(Ze=await pe(S,{secure_token:D.token,their_pm_id:Ve.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Ve.consent_id}}),se("[2nd] Confirm payment flow response",Ze),Dr=(I=(C=Ze.payment_methods)==null?void 0:C[0])==null?void 0:I.id),!Dr)throw new Error("No PM ID found");return Yt({logPrefix:"awx-googlepay",anyCdeConnection:S,checkoutPaymentMethod:e,requiredFormFields:F,confirmResult:Ze,usePayFirstFlow:!1})}catch(T){throw tt("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Gn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Apple Pay SDK")),document.body.appendChild(t)}),Bn=(r,e)=>{const t=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...r};return(t||n||o)&&(s[m.EMAIL]=s[m.EMAIL]||(t==null?void 0:t.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(t==null?void 0:t.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(t==null?void 0:t.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000",s[m.FIRST_NAME]=s[m.FIRST_NAME]||(t==null?void 0:t.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"_OP_UNKNOWN",s[m.LAST_NAME]=s[m.LAST_NAME]||(t==null?void 0:t.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"_OP_UNKNOWN"),s},yc=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")}),_c=r=>yc.safeParse(r).data,gc=r=>{const e=new AbortController;return window.addEventListener("message",t=>{var o;const n=_c(t);((o=n==null?void 0:n.data)==null?void 0:o.messageType)==="windowclosing"&&(r(),e.abort())},{signal:e.signal}),{cleanupCancelListener:()=>e.abort()}},qn=({total:r,prefill:e})=>{var n;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:r.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,De).toString()};const t=(n=e.line_items)==null?void 0:n[0];if(t)return{paymentDescription:(t==null?void 0:t.description)??"",regularBilling:{amount:r.amount,label:(t==null?void 0:t.description)??"",recurringPaymentIntervalUnit:t==null?void 0:t.billing_interval,recurringPaymentIntervalCount:(t==null?void 0:t.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},Yn=({overridePaymentRequest:r,initialPreview:e,prefill:t,defaultLabel:n="Total"})=>{var c,l;const o=(((c=r==null?void 0:r.amount)==null?void 0:c.currency)??(t==null?void 0:t.currency)??e.currency).toUpperCase(),i=((((l=r==null?void 0:r.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(r==null?void 0:r.label)??n??"Total",type:r!=null&&r.pending?"pending":"final",amount:i}}},{log__:Jt}=U("awx-apple-pay");async function vc(r,e){try{const n=(await bn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function wc(r,e){if(!r.redirect_url)throw new Error("No redirect URL found");Jt("3DS Required, starting verification...",r);const{status:t}=await Wt({url:r.redirect_url,baseUrl:e.baseUrl});if(Jt(`╰ 3DS verification completed [Status: ${t}]`),t===ne.CANCELLED)throw new Error("3DS verification cancelled");if(t===ne.FAILURE)throw new Error("3DS verification failed");const n=await pe(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:r.their_pm_id,airwallex_consent_id:r.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return Jt("[2nd] Confirm payment flow response",n),n}async function bc(r,e){var t,n,o,s,i;try{const c=r.payment,l=Bn(e.nonCdeFormInputs,c),u=Ne(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues),_=(await St(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 p=await pe(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)}}}});Jt("[1st] Confirm payment flow response",p);let y=(n=(t=p.payment_methods)==null?void 0:t[0])==null?void 0:n.id;const w=(o=p.required_user_actions)==null?void 0:o.find(I=>I.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(p=await wc(w,e),y=(i=(s=p.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!y)throw new Error("No PM ID found");const C={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(C),Yt({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:p,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:rt,err__:Sr}=U("awx-apple-pay"),kc=et(async({context:r,formCallbacks:e})=>{const t={processor:oe.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,jn);if(!n)return t;rt("Loading Apple Pay SDK...");try{await Gn(),rt("Apple Pay SDK loaded successfully")}catch(f){return Sr("Failed to load Apple Pay SDK",f),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return rt("Apple Pay is not available on this device/browser"),t;if(rt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return rt("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await W(i),l=c.mode==="setup",u=await Je(i,c.token,l,void 0),d=async f=>{try{await B.airwallexApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(_){Sr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:oe.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Ec=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var C;const s=he(r.checkoutPaymentMethods,jn),{overridePaymentRequest:i,initialPreview:c}=n,l=r.anyCdeConnection,u=await W(l),d=u.mode==="setup",{currencyCode:f,total:_}=Yn({overridePaymentRequest:i,initialPreview:c,defaultLabel:(C=s==null?void 0:s.metadata)==null?void 0:C.processor_account_name}),p={countryCode:"US",currencyCode:f,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:qn({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},y=new ApplePaySession(3,p),w={session:y,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:r.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return new Promise((I,T)=>{const S=()=>{rt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},{cleanupCancelListener:D}=gc(S);y.oncancel=S,y.onvalidatemerchant=async L=>{try{await vc(L,w)}catch(F){T(F)}},y.onpaymentmethodselected=()=>{const L={newTotal:{..._}};y.completePaymentMethodSelection(L)},y.onpaymentauthorized=async L=>{try{const F=await bc(L,w);D(),I(F)}catch(F){T(F)}},y.begin()}).catch(I=>{throw Sr("Apple Pay payment error",I),I})});async function Cc(r,e){try{const n=(await bn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function Sc(r,e){var t,n;try{const o=r.payment,s=Bn(e.nonCdeFormInputs,o),i=Ne(s,e.formCallbacks.get.onValidationError);await St(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 pe(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((n=(t=l.payment_methods)==null?void 0:t[0])==null?void 0:n.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),Yt({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 Wn=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()})}),Kn=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__:xt,err__:Pr}=U("authnet-applepay"),Pc=et(async({context:r,formCallbacks:e})=>{const t={processor:oe.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,Wn);if(!n)return t;xt("Loading Apple Pay SDK...");try{await Gn(),xt("Apple Pay SDK loaded successfully")}catch(f){return Pr("Failed to load Apple Pay SDK",f),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return xt("Apple Pay is not available on this device/browser"),t;if(!await ApplePaySession.canMakePayments())return xt("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await W(i),l=c.mode==="setup",u=await Je(i,c.token,l,void 0),d=async f=>{try{await B.authorizeNetApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(_){Pr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:oe.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Ac=Oe(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var C;const{initialPreview:s,overridePaymentRequest:i}=n,c=he(r.checkoutPaymentMethods,Wn),{currencyCode:l,total:u}=Yn({overridePaymentRequest:i,initialPreview:s,defaultLabel:(C=c==null?void 0:c.metadata)==null?void 0:C.processor_account_name}),d=r.anyCdeConnection,f=await W(d),_=f.mode==="setup",p={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:qn({total:u,prefill:f}),...(i==null?void 0:i.applePayPaymentRequest)??{}},y=new ApplePaySession(3,p),w={session:y,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:e.metadata,prefill:f,isSetupMode:_,baseUrl:r.baseUrl,formCallbacks:o};return new Promise((I,T)=>{y.oncancel=()=>{xt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},y.onvalidatemerchant=async S=>{try{await Cc(S,w)}catch(D){T(D)}},y.onpaymentmethodselected=()=>{const S={newTotal:p.total};y.completePaymentMethodSelection(S)},y.onpaymentauthorized=async S=>{try{const D=await Sc(S,w);I(D)}catch(D){T(D)}},y.begin()}).catch(I=>{throw Pr("Apple Pay payment error",I),I})}),{log__:$e,err__:Tt}=U("authnet-googlepay"),xc=et(async({context:r,formCallbacks:e})=>{var d,f;$e("Initializing Authnet GooglePay flow");const t={processor:oe.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=he(r.checkoutPaymentMethods,Kn);if(!n)return t;$e("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Tt("No gateway merchant ID found in processor account"),t;if($e("Loading Google Pay SDK..."),await Zn(),!((f=(d=window.google)==null?void 0:d.payments)!=null&&f.api))return Tt("Google Pay SDK not loaded properly"),t;$e("Google Pay SDK loaded",window.google.payments);try{const _=Kt({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:p}=await Ht(r.baseUrl,_).isReadyToPay(_);if(!p)return $e("Google Pay is not available for this user"),t}catch(_){return Tt("Error checking Google Pay availability",_),t}const s=r.anyCdeConnection,i=await W(s),c=i.mode==="setup",l=await Je(s,i.token,c,void 0),u=async _=>{try{B.authorizeNetGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:be(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(p){Tt("Google Pay payment error",p),e.get.onCheckoutError((p==null?void 0:p.message)??"Unknown error")}};return{processor:oe.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Tc=Oe(async({context:r,nonCdeFormInputs:e,checkoutPaymentMethod:t,formCallbacks:n,customParams:o})=>{var f,_,p,y;const{initialPreview:s,overridePaymentRequest:i}=o,l=he(r.checkoutPaymentMethods,Kn).metadata,u=Kt({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=Ht(r.baseUrl,u);try{const w=await d.loadPaymentData(u);$e("Google Pay Payment data",w);const C=r.anyCdeConnection,I=await W(C),T=zn(e,w),S=Ne(T,n.get.onValidationError),D=(_=(f=w.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:_.token;if(!D)throw new Error("No payment token received from Google Pay");const L=await St(C,{payment_provider:t.provider,checkout_payment_method:t,new_customer_email:S[m.EMAIL],new_customer_first_name:S[m.FIRST_NAME],new_customer_last_name:S[m.LAST_NAME],new_customer_address:{zip_code:S[m.ZIP_CODE],country:S[m.COUNTRY]}});$e("Start payment flow response",L);const F=await pe(C,{secure_token:I.token,processor_specific_metadata:{payment_provider:t.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(D)}}});if(!((y=(p=F.payment_methods)==null?void 0:p[0])==null?void 0:y.id))throw new Error("No PM ID found");return Yt({logPrefix:"authnet-googlepay",anyCdeConnection:C,checkoutPaymentMethod:t,requiredFormFields:S,confirmResult:F,usePayFirstFlow:!1})}catch(w){throw Tt("Google Pay payment error",w),new Error((w==null?void 0:w.message)??"Unknown error")}}),Qt=(r,e,t)=>{const n=r.filter(o=>{const s=t===void 0?!0:o.processor_name===t,i=o.provider===e;return s&&i});if(n.length===0)throw console.error("CPMs list",r),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(n.length!==1)throw console.error("CPMs list",r),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return n[0]},B={commonCC:{init:async()=>{},run:Xi},stripePR:{init:ac,run:ic},stripeLink:{init:Ri,run:Oi},pockytPaypal:{run:pc},airwallexGooglePay:{init:hc,run:mc},airwallexApplePay:{init:kc,run:Ec},authorizeNetApplePay:{init:Pc,run:Ac},authorizeNetGooglePay:{init:xc,run:Tc}};var Ar=function(r,e){return Ar=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},Ar(r,e)};function Me(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ar(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Ic(r,e,t,n){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(f){i(f)}}function l(d){try{u(n.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(r,e||[])).next())})}function Hn(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(t=0)),t;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,o=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){t.label=u[1];break}if(u[0]===6&&t.label<s[1]){t.label=s[1],s=u;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(u);break}s[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function nt(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Xt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return s}function er(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))}function ot(r){return this instanceof ot?(this.v=r,this):new ot(r)}function Rc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(p){return function(y){return Promise.resolve(y).then(p,f)}}function c(p,y){n[p]&&(o[p]=function(w){return new Promise(function(C,I){s.push([p,w,C,I])>1||l(p,w)})},y&&(o[p]=y(o[p])))}function l(p,y){try{u(n[p](y))}catch(w){_(s[0][3],w)}}function u(p){p.value instanceof ot?Promise.resolve(p.value.v).then(d,f):_(s[0][2],p)}function d(p){l("next",p)}function f(p){l("throw",p)}function _(p,y){p(y),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Oc(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof nt=="function"?nt(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(i){return new Promise(function(c,l){i=r[s](i),o(c,l,i.done,i.value)})}}function o(s,i,c,l){Promise.resolve(l).then(function(u){s({value:u,done:c})},i)}}typeof SuppressedError=="function"&&SuppressedError;function V(r){return typeof r=="function"}function tr(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var xr=tr(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
24
24
  `+t.map(function(n,o){return o+1+") "+n.toString()}).join(`
25
- `):"",this.name="UnsubscriptionError",this.errors=t}});function rr(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var It=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=nt(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(V(d))try{d()}catch(w){s=w instanceof xr?w.errors:[w]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var _=nt(f),p=_.next();!p.done;p=_.next()){var y=p.value;try{Xn(y)}catch(w){s=s??[],w instanceof xr?s=er(er([],Xt(s)),Xt(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{p&&!p.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new xr(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Xn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&rr(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&rr(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Jn=It.EMPTY;function Qn(r){return r instanceof It||r&&"closed"in r&&V(r.remove)&&V(r.add)&&V(r.unsubscribe)}function Xn(r){V(r)?r():r.unsubscribe()}var eo={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},to={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,er([r,e],Xt(t)))},clearTimeout:function(r){var e=to.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function ro(r){to.setTimeout(function(){throw r})}function no(){}function nr(r){r()}var Tr=function(r){Me(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Qn(t)&&t.add(n)):n.destination=jc,n}return e.create=function(t,n,o){return new Rr(t,n,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(It),Nc=Function.prototype.bind;function Ir(r,e){return Nc.call(r,e)}var Mc=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){or(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){or(n)}else or(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){or(t)}},r}(),Rr=function(r){Me(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(V(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&eo.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Ir(t.next,c),error:t.error&&Ir(t.error,c),complete:t.complete&&Ir(t.complete,c)}):i=t}return s.destination=new Mc(i),s}return e}(Tr);function or(r){ro(r)}function Dc(r){throw r}var jc={closed:!0,next:no,error:Dc,complete:no},Or=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Lc(r){return r}function Fc(r){return r.length===0?Lc:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var ke=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,s=$c(e)?e:new Rr(e,t,n);return nr(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=oo(t),new t(function(o,s){var i=new Rr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Or]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=oo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r}();function oo(r){var e;return(e=r??eo.Promise)!==null&&e!==void 0?e:Promise}function Uc(r){return r&&V(r.next)&&V(r.error)&&V(r.complete)}function $c(r){return r&&r instanceof Tr||Uc(r)&&Qn(r)}function Zc(r){return V(r==null?void 0:r.lift)}function Vc(r){return function(e){if(Zc(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function zc(r,e,t,n,o){return new Gc(r,e,t,n,o)}var Gc=function(r){Me(e,r);function e(t,n,o,s,i,c){var l=r.call(this,t)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){t.error(d)}}:r.prototype._next,l._error=s?function(u){try{s(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,l._complete=o?function(){try{o()}catch(u){t.error(u)}finally{this.unsubscribe()}}:r.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(Tr),Bc=tr(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),so=function(r){Me(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new ao(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Bc},e.prototype.next=function(t){var n=this;nr(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=nt(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(t)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(t){var n=this;nr(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var o=n.observers;o.length;)o.shift().error(t)}})},e.prototype.complete=function(){var t=this;nr(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Jn:(this.currentObservers=null,c.push(t),new It(function(){n.currentObservers=null,rr(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?t.error(s):i&&t.complete()},e.prototype.asObservable=function(){var t=new ke;return t.source=this,t},e.create=function(t,n){return new ao(t,n)},e}(ke),ao=function(r){Me(e,r);function e(t,n){var o=r.call(this)||this;return o.destination=t,o.source=n,o}return e.prototype.next=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,t)},e.prototype.error=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&o!==void 0?o:Jn},e}(so),qc={now:function(){return Date.now()},delegate:void 0},Yc=function(r){Me(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(It),io={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,er([r,e],Xt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},Wc=function(r){Me(e,r);function e(t,n){var o=r.call(this,t,n)||this;return o.scheduler=t,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(t,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(t,n,o){return o===void 0&&(o=0),io.setInterval(t.flush.bind(t,this),o)},e.prototype.recycleAsyncId=function(t,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&io.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(t,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var o=!1,s;try{this.work(t)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,o=t.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,rr(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(Yc),co=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=qc.now,r}(),Kc=function(r){Me(e,r);function e(t,n){n===void 0&&(n=co.now);var o=r.call(this,t,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var o;this._active=!0;do if(o=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,o){for(;t=n.shift();)t.unsubscribe();throw o}},e}(co),Hc=new Kc(Wc),Jc=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Qc(r){return V(r==null?void 0:r.then)}function Xc(r){return V(r[Or])}function el(r){return Symbol.asyncIterator&&V(r==null?void 0:r[Symbol.asyncIterator])}function tl(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function rl(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var nl=rl();function ol(r){return V(r==null?void 0:r[nl])}function sl(r){return Rc(this,arguments,function(){var t,n,o,s;return Hn(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,ot(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,ot(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,ot(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function al(r){return V(r==null?void 0:r.getReader)}function il(r){if(r instanceof ke)return r;if(r!=null){if(Xc(r))return cl(r);if(Jc(r))return ll(r);if(Qc(r))return ul(r);if(el(r))return lo(r);if(ol(r))return dl(r);if(al(r))return pl(r)}throw tl(r)}function cl(r){return new ke(function(e){var t=r[Or]();if(V(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ll(r){return new ke(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function ul(r){return new ke(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,ro)})}function dl(r){return new ke(function(e){var t,n;try{for(var o=nt(r),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function lo(r){return new ke(function(e){fl(r,e).catch(function(t){return e.error(t)})})}function pl(r){return lo(sl(r))}function fl(r,e){var t,n,o,s;return Ic(this,void 0,void 0,function(){var i,c;return Hn(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Oc(r),l.label=1;case 1:return[4,t.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function hl(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function ml(r,e){var t=V(r)?r:function(){return r},n=function(o){return o.error(t())};return new ke(n)}var yl=tr(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function _l(r,e){return new Promise(function(t,n){var o=!1,s;r.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?t(s):n(new yl)}})})}function gl(r){return r instanceof Date&&!isNaN(r)}var vl=tr(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function wl(r,e){var t=gl(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,o=t.each,s=t.with,i=s===void 0?bl:s,c=t.scheduler,l=c===void 0?Hc:c,u=t.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return Vc(function(f,_){var p,y,w=null,C=0,I=function(T){y=hl(_,l,function(){try{p.unsubscribe(),il(i({meta:d,lastValue:w,seen:C})).subscribe(_)}catch(S){_.error(S)}},T)};p=f.subscribe(zc(_,function(T){y==null||y.unsubscribe(),C++,_.next(w=T),o>0&&I(o)},void 0,void 0,function(){y!=null&&y.closed||y==null||y.unsubscribe(),w=null})),!C&&I(n!=null?typeof n=="number"?n:+n-l.now():o)})}function bl(r){throw new vl(r)}class sr{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&gr(this._current);const t={first:e.timeoutSec*1e3,with:()=>ml(()=>new Error(e.timeoutErrMsg))};return _l(this._subject.pipe(wl(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new so}get current(){return this._current}}const{log__:kl,err__:El}=U("init-flows"),st=(r,e)=>{const t=new sr;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);kl(`✔ ${r} flow initialized successfully. Result:`,o),t.set(o)}catch(o){El(`𝙭 ${r} flow initialization failed. Error:`,ue(o),"Details:",o),t.throw(o,ue(o))}}}},Cl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Sl=()=>({stripePR:st("Stripe PR",B.stripePR.init),stripeLink:st("Stripe Link",B.stripeLink.init),airwallexGooglePay:st("Airwallex GooglePay",B.airwallexGooglePay.init),airwallexApplePay:st("Airwallex ApplePay",B.airwallexApplePay.init),authorizeNetGooglePay:st("Authnet GooglePay",B.authorizeNetGooglePay.init),authorizeNetApplePay:st("Authnet ApplePay",B.authorizeNetApplePay.init)}),{err__:Pl}=U("form-callbacks"),ae=a.function().optional(),uo=a.object({onFocus:ae,onBlur:ae,onChange:ae,onLoad:ae,onLoadError:ae,onValidationError:ae,onCheckoutStarted:ae,onCheckoutSuccess:ae,onSetupPaymentMethodSuccess:ae,onCheckoutError:ae,onPaymentRequestLoad:ae}),ye=class ye{constructor(){this.setCallbacks=e=>{this._callbacks=ye.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const o=ws(t,n??ye.NOOP,Pl);this._callbacks[t]=o})},this._callbacks=ye.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ye.NOOP=()=>{},ye.createEmptyCallbacks=()=>{const e={};return Object.keys(uo.keyof().enum).forEach(t=>{e[t]=ye.NOOP}),e},ye.fromObject=e=>{const t=new ye;return t.setCallbacks(uo.parse(e)),t};let Nr=ye;class Al{constructor(e,t,n,o){this.handleMessage=s=>{if(!s.source)throw new Error("No source found");if(po(s.origin)!==po(this.baseUrl)||typeof s.data=="object"&&s.data.penpal)return;let i=null;try{i=ua(JSON.parse(s.data))}catch(f){console.warn("[OJS] Unknown event. Ignoring:",f);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=t,this.formCallbacks=n,this.internalCallbacks=o}}const po=r=>new URL(r).origin;async function xl(r,e){const n=await cn({iframe:r,debug:!1,childOrigin:e}).promise,o=await Oa(n);if(!Na(n,o))throw new Error("Got invalid CDE connection object");return n}class Tl{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Il=(r,e,t)=>{const{stripePR:n}=r;n.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,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&fo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},fo=(r,e,t,n,o)=>B.stripePR.run({context:t,checkoutPaymentMethod:Qt(t.checkoutPaymentMethods,r),nonCdeFormInputs:be(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),ho="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ee,err__:Ce}=U("op-form"),Se=class Se{constructor(e){this.cdeLoadEvent=new sr,this.anyCdeConn=new sr,this.context=new sr,this.initFlows=Sl(),this.startFormInit=async()=>{try{Ee("Initializing OpenPay form:"),Ee("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:ho});Ee("├ CDE load event received"),Ee("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:ho});Ee("├ CDE connection received"),Ee("├ Creating OJS context, setting up handlers...");const o=Se.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(o),Il(this.initFlows,o,this.formCallbacks),Ee("├ Starting OJS init flows..."),await Cl(this.initFlows,o,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Ee("╰ Done initializing OJS flows.")}catch(t){const n=ue(t);Ce("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const o=ks.parse(t),s=document.createElement("iframe"),i=this.buildQueryString(n);s.name=`${o}-element`;const c=new URL(`/app/v1/${s.name}/`,this.config.baseUrl);return c.search=i.toString(),s.src=c.href,s.style.border="none",s.style.width="100%",this.registerIframe(o,s)},this.registerIframe=(t,n)=>{const o={type:t,node:n,mount:s=>{var i;return(i=document.querySelector(s))==null?void 0:i.appendChild(n)}};return this.connectToElement({type:o.type,node:o.node}),this.registeredElements||(this.registeredElements={[Ke.CARD]:void 0,[Ke.CARD_NUMBER]:void 0,[Ke.CARD_EXPIRY]:void 0,[Ke.CARD_CVC]:void 0}),this.registeredElements[t]=o,o},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",sa(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{xl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Ce("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Ce("Please wait for the form to finish loading before submitting.");return}B.commonCC.run({context:t,checkoutPaymentMethod:Qt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:be(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Ce("Please wait for the form to finish loading before getting available payment methods.");return}const n={airwallexGooglePay:Q.airwallexGooglePay,airwallexApplePay:Q.airwallexApplePay,authorizeNetGooglePay:Q.authorizenetGooglePay,authorizeNetApplePay:Q.authorizenetApplePay};return Object.entries(this.initFlows).map(([o,s])=>({name:n[o]??o,...s.publisher.getValueIfLoadedElse(null)}))},this.generalSubmit=(t,n)=>{const o=this.context.getValueIfLoadedElse(null);if(!o){Ce("Please wait for the form to finish loading before submitting.");return}switch(t){case Q.pockytPaypal:return B.pockytPaypal.run({context:o,checkoutPaymentMethod:Qt(o.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:be(o.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case Q.airwallexGooglePay:{const s=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.airwallexApplePay:{const s=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.authorizenetGooglePay:{const s=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.authorizenetApplePay:{const s=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}default:gr(t)}},this.submit=this.submitCard,this.destroy=()=>{Ee("Destroying OpenPay form...");for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},Se.assignAsSingleton(this),this.ojsVersion="0.2.13",this.ojsReleaseVersion="0.2.13-alpha.000ac44",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Nr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${rn()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Tl,this.eventHandler=new Al(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}};Se.ojsFlows=B,Se.assignAsSingleton=e=>{if(Se.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Se.getInstance=()=>window.ojs??null,Se.buildOjsFlowContext=(e,t,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??De).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Mr=Se;ge.FieldName=m,ge.OpenPayForm=Mr,ge.SubmitMethod=bs,ge.SubmitMethods=Q,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})});
25
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function rr(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var It=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=nt(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(V(d))try{d()}catch(w){s=w instanceof xr?w.errors:[w]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var _=nt(f),p=_.next();!p.done;p=_.next()){var y=p.value;try{Xn(y)}catch(w){s=s??[],w instanceof xr?s=er(er([],Xt(s)),Xt(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{p&&!p.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new xr(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Xn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&rr(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&rr(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Jn=It.EMPTY;function Qn(r){return r instanceof It||r&&"closed"in r&&V(r.remove)&&V(r.add)&&V(r.unsubscribe)}function Xn(r){V(r)?r():r.unsubscribe()}var eo={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},to={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,er([r,e],Xt(t)))},clearTimeout:function(r){var e=to.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function ro(r){to.setTimeout(function(){throw r})}function no(){}function nr(r){r()}var Tr=function(r){Me(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Qn(t)&&t.add(n)):n.destination=jc,n}return e.create=function(t,n,o){return new Rr(t,n,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(It),Nc=Function.prototype.bind;function Ir(r,e){return Nc.call(r,e)}var Mc=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){or(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){or(n)}else or(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){or(t)}},r}(),Rr=function(r){Me(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(V(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&eo.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Ir(t.next,c),error:t.error&&Ir(t.error,c),complete:t.complete&&Ir(t.complete,c)}):i=t}return s.destination=new Mc(i),s}return e}(Tr);function or(r){ro(r)}function Dc(r){throw r}var jc={closed:!0,next:no,error:Dc,complete:no},Or=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Lc(r){return r}function Fc(r){return r.length===0?Lc:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var ke=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,s=$c(e)?e:new Rr(e,t,n);return nr(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=oo(t),new t(function(o,s){var i=new Rr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Or]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=oo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r}();function oo(r){var e;return(e=r??eo.Promise)!==null&&e!==void 0?e:Promise}function Uc(r){return r&&V(r.next)&&V(r.error)&&V(r.complete)}function $c(r){return r&&r instanceof Tr||Uc(r)&&Qn(r)}function Zc(r){return V(r==null?void 0:r.lift)}function Vc(r){return function(e){if(Zc(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function zc(r,e,t,n,o){return new Gc(r,e,t,n,o)}var Gc=function(r){Me(e,r);function e(t,n,o,s,i,c){var l=r.call(this,t)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){t.error(d)}}:r.prototype._next,l._error=s?function(u){try{s(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,l._complete=o?function(){try{o()}catch(u){t.error(u)}finally{this.unsubscribe()}}:r.prototype._complete,l}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(Tr),Bc=tr(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),so=function(r){Me(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new ao(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Bc},e.prototype.next=function(t){var n=this;nr(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=nt(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(t)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(t){var n=this;nr(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var o=n.observers;o.length;)o.shift().error(t)}})},e.prototype.complete=function(){var t=this;nr(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Jn:(this.currentObservers=null,c.push(t),new It(function(){n.currentObservers=null,rr(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?t.error(s):i&&t.complete()},e.prototype.asObservable=function(){var t=new ke;return t.source=this,t},e.create=function(t,n){return new ao(t,n)},e}(ke),ao=function(r){Me(e,r);function e(t,n){var o=r.call(this)||this;return o.destination=t,o.source=n,o}return e.prototype.next=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,t)},e.prototype.error=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&o!==void 0?o:Jn},e}(so),qc={now:function(){return Date.now()},delegate:void 0},Yc=function(r){Me(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(It),io={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,er([r,e],Xt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},Wc=function(r){Me(e,r);function e(t,n){var o=r.call(this,t,n)||this;return o.scheduler=t,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(t,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(t,n,o){return o===void 0&&(o=0),io.setInterval(t.flush.bind(t,this),o)},e.prototype.recycleAsyncId=function(t,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&io.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(t,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var o=!1,s;try{this.work(t)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,o=t.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,rr(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(Yc),co=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=qc.now,r}(),Kc=function(r){Me(e,r);function e(t,n){n===void 0&&(n=co.now);var o=r.call(this,t,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var o;this._active=!0;do if(o=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,o){for(;t=n.shift();)t.unsubscribe();throw o}},e}(co),Hc=new Kc(Wc),Jc=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Qc(r){return V(r==null?void 0:r.then)}function Xc(r){return V(r[Or])}function el(r){return Symbol.asyncIterator&&V(r==null?void 0:r[Symbol.asyncIterator])}function tl(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function rl(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var nl=rl();function ol(r){return V(r==null?void 0:r[nl])}function sl(r){return Rc(this,arguments,function(){var t,n,o,s;return Hn(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,ot(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,ot(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,ot(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function al(r){return V(r==null?void 0:r.getReader)}function il(r){if(r instanceof ke)return r;if(r!=null){if(Xc(r))return cl(r);if(Jc(r))return ll(r);if(Qc(r))return ul(r);if(el(r))return lo(r);if(ol(r))return dl(r);if(al(r))return pl(r)}throw tl(r)}function cl(r){return new ke(function(e){var t=r[Or]();if(V(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ll(r){return new ke(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function ul(r){return new ke(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,ro)})}function dl(r){return new ke(function(e){var t,n;try{for(var o=nt(r),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function lo(r){return new ke(function(e){fl(r,e).catch(function(t){return e.error(t)})})}function pl(r){return lo(sl(r))}function fl(r,e){var t,n,o,s;return Ic(this,void 0,void 0,function(){var i,c;return Hn(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Oc(r),l.label=1;case 1:return[4,t.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function hl(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function ml(r,e){var t=V(r)?r:function(){return r},n=function(o){return o.error(t())};return new ke(n)}var yl=tr(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function _l(r,e){return new Promise(function(t,n){var o=!1,s;r.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?t(s):n(new yl)}})})}function gl(r){return r instanceof Date&&!isNaN(r)}var vl=tr(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function wl(r,e){var t=gl(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,o=t.each,s=t.with,i=s===void 0?bl:s,c=t.scheduler,l=c===void 0?Hc:c,u=t.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return Vc(function(f,_){var p,y,w=null,C=0,I=function(T){y=hl(_,l,function(){try{p.unsubscribe(),il(i({meta:d,lastValue:w,seen:C})).subscribe(_)}catch(S){_.error(S)}},T)};p=f.subscribe(zc(_,function(T){y==null||y.unsubscribe(),C++,_.next(w=T),o>0&&I(o)},void 0,void 0,function(){y!=null&&y.closed||y==null||y.unsubscribe(),w=null})),!C&&I(n!=null?typeof n=="number"?n:+n-l.now():o)})}function bl(r){throw new vl(r)}class sr{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&gr(this._current);const t={first:e.timeoutSec*1e3,with:()=>ml(()=>new Error(e.timeoutErrMsg))};return _l(this._subject.pipe(wl(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new so}get current(){return this._current}}const{log__:kl,err__:El}=U("init-flows"),st=(r,e)=>{const t=new sr;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);kl(`✔ ${r} flow initialized successfully. Result:`,o),t.set(o)}catch(o){El(`𝙭 ${r} flow initialization failed. Error:`,ue(o),"Details:",o),t.throw(o,ue(o))}}}},Cl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Sl=()=>({stripePR:st("Stripe PR",B.stripePR.init),stripeLink:st("Stripe Link",B.stripeLink.init),airwallexGooglePay:st("Airwallex GooglePay",B.airwallexGooglePay.init),airwallexApplePay:st("Airwallex ApplePay",B.airwallexApplePay.init),authorizeNetGooglePay:st("Authnet GooglePay",B.authorizeNetGooglePay.init),authorizeNetApplePay:st("Authnet ApplePay",B.authorizeNetApplePay.init)}),{err__:Pl}=U("form-callbacks"),ae=a.function().optional(),uo=a.object({onFocus:ae,onBlur:ae,onChange:ae,onLoad:ae,onLoadError:ae,onValidationError:ae,onCheckoutStarted:ae,onCheckoutSuccess:ae,onSetupPaymentMethodSuccess:ae,onCheckoutError:ae,onPaymentRequestLoad:ae}),ye=class ye{constructor(){this.setCallbacks=e=>{this._callbacks=ye.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const o=ws(t,n??ye.NOOP,Pl);this._callbacks[t]=o})},this._callbacks=ye.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ye.NOOP=()=>{},ye.createEmptyCallbacks=()=>{const e={};return Object.keys(uo.keyof().enum).forEach(t=>{e[t]=ye.NOOP}),e},ye.fromObject=e=>{const t=new ye;return t.setCallbacks(uo.parse(e)),t};let Nr=ye;class Al{constructor(e,t,n,o){this.handleMessage=s=>{if(!s.source)throw new Error("No source found");if(po(s.origin)!==po(this.baseUrl)||typeof s.data=="object"&&s.data.penpal)return;let i=null;try{i=ua(JSON.parse(s.data))}catch(f){console.warn("[OJS] Unknown event. Ignoring:",f);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=t,this.formCallbacks=n,this.internalCallbacks=o}}const po=r=>new URL(r).origin;async function xl(r,e){const n=await cn({iframe:r,debug:!1,childOrigin:e}).promise,o=await Oa(n);if(!Na(n,o))throw new Error("Got invalid CDE connection object");return n}class Tl{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Il=(r,e,t)=>{const{stripePR:n}=r;n.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,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&fo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},fo=(r,e,t,n,o)=>B.stripePR.run({context:t,checkoutPaymentMethod:Qt(t.checkoutPaymentMethods,r),nonCdeFormInputs:be(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),ho="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ee,err__:Ce}=U("op-form"),Se=class Se{constructor(e){this.cdeLoadEvent=new sr,this.anyCdeConn=new sr,this.context=new sr,this.initFlows=Sl(),this.startFormInit=async()=>{try{Ee("Initializing OpenPay form:"),Ee("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:ho});Ee("├ CDE load event received"),Ee("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:ho});Ee("├ CDE connection received"),Ee("├ Creating OJS context, setting up handlers...");const o=Se.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(o),Il(this.initFlows,o,this.formCallbacks),Ee("├ Starting OJS init flows..."),await Cl(this.initFlows,o,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Ee("╰ Done initializing OJS flows.")}catch(t){const n=ue(t);Ce("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const o=ks.parse(t),s=document.createElement("iframe"),i=this.buildQueryString(n);s.name=`${o}-element`;const c=new URL(`/app/v1/${s.name}/`,this.config.baseUrl);return c.search=i.toString(),s.src=c.href,s.style.border="none",s.style.width="100%",this.registerIframe(o,s)},this.registerIframe=(t,n)=>{const o={type:t,node:n,mount:s=>{var i;return(i=document.querySelector(s))==null?void 0:i.appendChild(n)}};return this.connectToElement({type:o.type,node:o.node}),this.registeredElements||(this.registeredElements={[Ke.CARD]:void 0,[Ke.CARD_NUMBER]:void 0,[Ke.CARD_EXPIRY]:void 0,[Ke.CARD_CVC]:void 0}),this.registeredElements[t]=o,o},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",sa(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{xl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Ce("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Ce("Please wait for the form to finish loading before submitting.");return}B.commonCC.run({context:t,checkoutPaymentMethod:Qt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:be(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Ce("Please wait for the form to finish loading before getting available payment methods.");return}const n={airwallexGooglePay:Q.airwallexGooglePay,airwallexApplePay:Q.airwallexApplePay,authorizeNetGooglePay:Q.authorizenetGooglePay,authorizeNetApplePay:Q.authorizenetApplePay};return Object.entries(this.initFlows).map(([o,s])=>({name:n[o]??o,...s.publisher.getValueIfLoadedElse(null)}))},this.generalSubmit=(t,n)=>{const o=this.context.getValueIfLoadedElse(null);if(!o){Ce("Please wait for the form to finish loading before submitting.");return}switch(t){case Q.pockytPaypal:return B.pockytPaypal.run({context:o,checkoutPaymentMethod:Qt(o.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:be(o.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case Q.airwallexGooglePay:{const s=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.airwallexApplePay:{const s=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.authorizenetGooglePay:{const s=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case Q.authorizenetApplePay:{const s=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ce("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}default:gr(t)}},this.submit=this.submitCard,this.destroy=()=>{Ee("Destroying OpenPay form...");for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},Se.assignAsSingleton(this),this.ojsVersion="0.2.13",this.ojsReleaseVersion="0.2.13",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Nr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${rn()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Tl,this.eventHandler=new Al(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}};Se.ojsFlows=B,Se.assignAsSingleton=e=>{if(Se.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Se.getInstance=()=>window.ojs??null,Se.buildOjsFlowContext=(e,t,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??De).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Mr=Se;ge.FieldName=m,ge.OpenPayForm=Mr,ge.SubmitMethod=bs,ge.SubmitMethods=Q,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getopenpay/openpay-js",
3
- "version": "0.2.13-alpha.000ac44",
3
+ "version": "0.2.13",
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",