@getopenpay/openpay-js 0.2.15-alpha.adaa258 → 0.2.16-alpha.1b02bc3

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
@@ -19,7 +19,7 @@ ${r.message}`),r.message)}else return _r(r.message);if(typeof r=="object")try{re
19
19
  </div>
20
20
  `;const t=document.createElement("div"),n=t.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const o=n.querySelector("#three-ds-iframe"),s=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:o,cancelButton:s}};function Vi(r,e,t){const n=async()=>{try{const s=await vi(r,t);s&&(clearInterval(o),e(s))}catch{}};n();const o=setInterval(n,En);return o}function zi({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t({status:$.CANCELLED})};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Qt(r){const{url:e,baseUrl:t}=r,n=jn(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{n.host.remove()},1e3),o(l),c==null||c()},i=Vi(n.iframe,s,new URL(t).origin),c=zi({elements:n,pollingInterval:i,resolve:o})})}const Ln=async r=>{const e=await Qt(r);if(e.status===$.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===$.FAILURE)throw new Error("3DS verification failed");return e.status!==$.SUCCESS&&Yt(e.status),{href:e.href}},Gi=(r,e)=>{const t=window.open(e,"_blank");if(!t)throw new Error(`${r} popup window blocked. Please allow popups for this site.`);return t},Bi=async(r,e,t,n)=>{const{err__:o}=L("popup-verify");return new Promise((s,i)=>{const c=Gi(r,n),l=setInterval(async()=>{try{const u=await mi(e,t);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${r} payment cancelled`)}catch(u){o(fe(u)),clearInterval(l),i(fe(u))}},1e3)})},{log__:qi,err__:Fn}=L("pockyt-cc"),Yi=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Wi=r=>{const e=Yi.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw Fn(n),new Error(t)}return e.data},Un=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return qi(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw Fn(t,`Resulting URL: ${r}.
21
21
  Error: ${fe(e)}`),new Error(t)}},Ki=(r,e)=>new URL(r).searchParams.get(e),Hi=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,Ji=async(r,e)=>{const t=Wi(e),n=await Ln({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:Un(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:Qi,err__:xr}=L("airwallex-cc"),Xi=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),ec=r=>{const e=Xi.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw xr(n),new Error(t)}return e.data},tc=r=>(r==null?void 0:r["op-airwallex-3ds-url"])!==void 0,rc=r=>{try{const e=new URL(r??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return Qi(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw xr(t,`Resulting URL: ${r}.
22
- Error: ${fe(e)}`),new Error(t)}},nc=async(r,e)=>{const t=ec(e),n=await Ln({url:t["op-airwallex-3ds-url"],baseUrl:r}),o=rc(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 xr(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},$n=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()})}),Zn=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()})}),oc=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),{log__:Tt,err__:Xt}=L("adyen-cc"),sc=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":oc,"op-adyen-action":a.string()}),Vn="Unable to process your credit card. Please contact support for assistance.",ac=r=>{const e=sc.safeParse(r);if(!e.success)throw Xt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`),new Error(Vn);return e.data},ic=r=>{const e=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(e)},zn=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,cc=async()=>{Tt("Waiting for Adyen SDK to load...");for(let r=0;r<10;r++)zn()||await vr(500);if(!zn())throw Xt("Adyen SDK not loaded properly"),new Error(Vn);return Tt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},lc=r=>{const{headers:e,locale:t,countryCode:n,component:o,host:s,cancelButton:i}=r,c=ic(e["op-adyen-action"]);return Tt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{Tt("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Xt("Authentication failed. Result:",h),l({status:$.FAILURE,cleanup:u})},p=h=>{Xt("Adyen error:",h),l({status:$.FAILURE,cleanup:u})},_=()=>{l({status:$.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,w,x)=>{s.remove(),l({status:$.SUCCESS,additionalDetails:h,cleanup:u})};cc().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:t,countryCode:n,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},uc=r=>(r==null?void 0:r["op-adyen-action"])!==void 0,dc=async(r,e,t)=>{const n=ac(t),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=jn("http://example.com");i.replaceWith(o);const l=await lc({headers:n,locale:r,countryCode:e,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===$.FAILURE)throw new Error("3DS verification failed");if(l.status===$.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===$.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return Tt("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else Yt(l.status)},{log__:N,err__:Gn}=L("common-cc"),{log__:Bn}=L("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const pc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var u;N("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=r.anyCdeConnection,i=await z(s);N(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Me(t,n.get.onValidationError),l={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{N(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await _i(o.currentCdeConnections,{session_id:r.elementsSessionId});if(Ni(d,n.get.onValidationError),i.mode==="setup"){N(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await gi(s,l);return N(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{N(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const p=await kn(s,l);return N("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof bn&&d.originalErrorMessage.includes("3DS_REQUIRED")){N("├ Card requires 3DS, starting non-legacy payment flow"),N("Received 3DS error response headers:",d.response.headers);const p=Hi(d.response.headers);if(p){N("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await Ji(r.baseUrl,d.response.headers);l.extra_metadata.pockyt=C}if(tc(d.response.headers)){N("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await nc(r.baseUrl,d.response.headers);l.extra_metadata.airwallex=C}if(uc(d.response.headers)){N("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const C=await dc(i.locale,t[y.COUNTRY],d.response.headers);l.extra_metadata.adyen=C}const h=await pi(s,l);N("├ Payment flow result:",h);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?N("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(N("├ Using stripe 3DS flow"),await _c(h)):(N("├ Using common 3DS flow"),await yc(h,r.baseUrl));const x=h.cc_pm_id;if(i.mode==="setup"){N(`├ Confirming payment flow [cc_pm_id: ${x}]`);const C=await se(s,{secure_token:i.token,existing_cc_pm_id:x});N("├ Confirm payment flow result received Result:",C);const T=It(C);return N(`╰ Setup completed successfully [PM ID: ${T.payment_method_id}]`),{mode:"setup",result:T}}else{N(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const C=await kn(s,{...l,existing_cc_pm_id:x,do_not_use_legacy_cc_flow:w});return N("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw Gn("╰ Error checking out card info in CDE"),Gn(d),d}}),fc=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return na.parse(e)},hc=["airwallex_payment_consent","adyen"],mc=r=>{const e=r.required_user_actions.find(t=>hc.includes(t.type));if(!e)throw new Error("No common 3DS action found");return Xs.parse(e)},yc=async(r,e)=>{const t=mc(r);if(t.redirect_url==="3DS_COMPLETE"){N("├ 3DS flow completed successfully");return}N(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Qt({url:t.redirect_url,baseUrl:e});if(N(`╰ 3DS verification completed [Status: ${n}]`),n===$.CANCELLED)throw new Error("3DS verification cancelled");if(n===$.FAILURE)throw new Error("3DS verification failed")},_c=async r=>{const e=fc(r);Bn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await ua(e),Bn("╰ Stripe 3DS flow completed successfully")},ie=a.enum(["stripe","airwallex","authorize_net"]);ie.Enum.stripe;const{log__:H,err__:gc}=L("stripe-pr"),vc=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()})}),wc=Ze(async({context:r,formCallbacks:e})=>{H("Checking if there are any CPMs for Stripe PR...");const t=ae(r.checkoutPaymentMethods,vc);H("Initializing Stripe PR flow...");const n=r.anyCdeConnection,o=await z(n),s=o.mode==="setup";H("Getting initial preview amount");const i=await tt(n,o.token,s,void 0),c=await ia(t.metadata.stripe_pk,i.amountAtom,i.currency,s);H("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return gc("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};H("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>Z.stripePR.run({context:r,checkoutPaymentMethod:Nt(r.checkoutPaymentMethods,d),nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:ie.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:ie.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),bc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{if(H("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 h=o.overridePaymentRequest;H("Overriding PR amount with",h),Ec(c,h.amount,h.pending,h.applePayPaymentRequest)}H("Showing PR dialog..."),c.show();const l=await ca(c);H("Stripe PM added event:",l),H("Merging PM fields with form fields...");const u=kc(t,l),d=Me(u,n.get.onValidationError);H("PR dialog finished. Starting payment flow...",d);const p=await fi(i,{fields:d,checkoutPaymentMethod:e}),_=Cc(p);H("Confirming PR with Stripe..."),await la(_,l);const f=await z(i);if(f.mode==="setup"){H("Confirming payment flow for setup...");const h=await se(i,{secure_token:f.token});return{mode:"setup",result:It(h)}}else{H("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[y.FIRST_NAME],customer_last_name:d[y.LAST_NAME],customer_email:d[y.EMAIL],customer_zip_code:d[y.ZIP_CODE],customer_country:d[y.COUNTRY],promotion_code:d[y.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Er(i,h)}}}),kc=(r,e)=>{var l,u,d,p;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=(p=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:p.address,c=e.shippingAddress;return t[y.FIRST_NAME]=t[y.FIRST_NAME]||n||"_OP_UNKNOWN",t[y.LAST_NAME]=t[y.LAST_NAME]||s||"_OP_UNKNOWN",t[y.EMAIL]=t[y.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[y.ZIP_CODE]=t[y.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[y.COUNTRY]=t[y.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US",H("Final form inputs:",t),t},Ec=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Cc=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
22
+ Error: ${fe(e)}`),new Error(t)}},nc=async(r,e)=>{const t=ec(e),n=await Ln({url:t["op-airwallex-3ds-url"],baseUrl:r}),o=rc(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 xr(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},$n=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()})}),Zn=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()})}),oc=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),{log__:Tt,err__:Xt}=L("adyen-cc"),sc=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":oc,"op-adyen-action":a.string()}),Vn="Unable to process your credit card. Please contact support for assistance.",ac=r=>{const e=sc.safeParse(r);if(!e.success)throw Xt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`),new Error(Vn);return e.data},ic=r=>JSON.parse(r),zn=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,cc=async()=>{Tt("Waiting for Adyen SDK to load...");for(let r=0;r<10;r++)zn()||await vr(500);if(!zn())throw Xt("Adyen SDK not loaded properly"),new Error(Vn);return Tt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},lc=r=>{const{headers:e,locale:t,countryCode:n,component:o,host:s,cancelButton:i}=r,c=ic(e["op-adyen-action"]);return Tt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{Tt("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Xt("Authentication failed. Result:",h),l({status:$.FAILURE,cleanup:u})},p=h=>{Xt("Adyen error:",h),l({status:$.FAILURE,cleanup:u})},_=()=>{l({status:$.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,w,x)=>{s.remove(),l({status:$.SUCCESS,additionalDetails:h,cleanup:u})};cc().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:t,countryCode:n,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},uc=r=>(r==null?void 0:r["op-adyen-action"])!==void 0,dc=async(r,e,t)=>{const n=ac(t),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=jn("http://example.com");i.replaceWith(o);const l=await lc({headers:n,locale:r,countryCode:e,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===$.FAILURE)throw new Error("3DS verification failed");if(l.status===$.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===$.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return Tt("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else Yt(l.status)},{log__:N,err__:Gn}=L("common-cc"),{log__:Bn}=L("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const pc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var u;N("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=r.anyCdeConnection,i=await z(s);N(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Me(t,n.get.onValidationError),l={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{N(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await _i(o.currentCdeConnections,{session_id:r.elementsSessionId});if(Ni(d,n.get.onValidationError),i.mode==="setup"){N(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await gi(s,l);return N(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{N(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const p=await kn(s,l);return N("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof bn&&d.originalErrorMessage.includes("3DS_REQUIRED")){N("├ Card requires 3DS, starting non-legacy payment flow"),N("Received 3DS error response headers:",d.response.headers);const p=Hi(d.response.headers);if(p){N("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await Ji(r.baseUrl,d.response.headers);l.extra_metadata.pockyt=C}if(tc(d.response.headers)){N("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await nc(r.baseUrl,d.response.headers);l.extra_metadata.airwallex=C}if(uc(d.response.headers)){N("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const C=await dc(i.locale,t[y.COUNTRY],d.response.headers);l.extra_metadata.adyen=C}const h=await pi(s,l);N("├ Payment flow result:",h);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?N("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(N("├ Using stripe 3DS flow"),await _c(h)):(N("├ Using common 3DS flow"),await yc(h,r.baseUrl));const x=h.cc_pm_id;if(i.mode==="setup"){N(`├ Confirming payment flow [cc_pm_id: ${x}]`);const C=await se(s,{secure_token:i.token,existing_cc_pm_id:x});N("├ Confirm payment flow result received Result:",C);const T=It(C);return N(`╰ Setup completed successfully [PM ID: ${T.payment_method_id}]`),{mode:"setup",result:T}}else{N(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const C=await kn(s,{...l,existing_cc_pm_id:x,do_not_use_legacy_cc_flow:w});return N("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw Gn("╰ Error checking out card info in CDE"),Gn(d),d}}),fc=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return na.parse(e)},hc=["airwallex_payment_consent","adyen"],mc=r=>{const e=r.required_user_actions.find(t=>hc.includes(t.type));if(!e)throw new Error("No common 3DS action found");return Xs.parse(e)},yc=async(r,e)=>{const t=mc(r);if(t.redirect_url==="3DS_COMPLETE"){N("├ 3DS flow completed successfully");return}N(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Qt({url:t.redirect_url,baseUrl:e});if(N(`╰ 3DS verification completed [Status: ${n}]`),n===$.CANCELLED)throw new Error("3DS verification cancelled");if(n===$.FAILURE)throw new Error("3DS verification failed")},_c=async r=>{const e=fc(r);Bn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await ua(e),Bn("╰ Stripe 3DS flow completed successfully")},ie=a.enum(["stripe","airwallex","authorize_net"]);ie.Enum.stripe;const{log__:H,err__:gc}=L("stripe-pr"),vc=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()})}),wc=Ze(async({context:r,formCallbacks:e})=>{H("Checking if there are any CPMs for Stripe PR...");const t=ae(r.checkoutPaymentMethods,vc);H("Initializing Stripe PR flow...");const n=r.anyCdeConnection,o=await z(n),s=o.mode==="setup";H("Getting initial preview amount");const i=await tt(n,o.token,s,void 0),c=await ia(t.metadata.stripe_pk,i.amountAtom,i.currency,s);H("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return gc("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};H("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>Z.stripePR.run({context:r,checkoutPaymentMethod:Nt(r.checkoutPaymentMethods,d),nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:ie.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:ie.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),bc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{if(H("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 h=o.overridePaymentRequest;H("Overriding PR amount with",h),Ec(c,h.amount,h.pending,h.applePayPaymentRequest)}H("Showing PR dialog..."),c.show();const l=await ca(c);H("Stripe PM added event:",l),H("Merging PM fields with form fields...");const u=kc(t,l),d=Me(u,n.get.onValidationError);H("PR dialog finished. Starting payment flow...",d);const p=await fi(i,{fields:d,checkoutPaymentMethod:e}),_=Cc(p);H("Confirming PR with Stripe..."),await la(_,l);const f=await z(i);if(f.mode==="setup"){H("Confirming payment flow for setup...");const h=await se(i,{secure_token:f.token});return{mode:"setup",result:It(h)}}else{H("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[y.FIRST_NAME],customer_last_name:d[y.LAST_NAME],customer_email:d[y.EMAIL],customer_zip_code:d[y.ZIP_CODE],customer_country:d[y.COUNTRY],promotion_code:d[y.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Er(i,h)}}}),kc=(r,e)=>{var l,u,d,p;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=(p=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:p.address,c=e.shippingAddress;return t[y.FIRST_NAME]=t[y.FIRST_NAME]||n||"_OP_UNKNOWN",t[y.LAST_NAME]=t[y.LAST_NAME]||s||"_OP_UNKNOWN",t[y.EMAIL]=t[y.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[y.ZIP_CODE]=t[y.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[y.COUNTRY]=t[y.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US",H("Final form inputs:",t),t},Ec=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Cc=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 oa.parse(r.required_user_actions[0])},{log__:_e,err__:qn}=L("pockyt-paypal"),Sc=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=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var U,ve;_e("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,i=await z(s);_e("Verifying CPM...");const c=Sc.parse(e);_e("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Me(t,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Oi(u);_e(`Starting payment flow... Mode: ${i.mode}`);const p=br(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((U=o==null?void 0:o.settings)!=null&&U.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",r.baseUrl).toString(),w=btoa(JSON.stringify(f)),x=new URLSearchParams({st:i.token,r:w}),C=`${h}?${x.toString()}`;if((ve=o==null?void 0:o.settings)!=null&&ve.useRedirectFlow)throw _e("Starting redirect mode for PayPal..."),window.location.href=C,await vr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");_e("Starting popup mode for PayPal..."),_e("Opening paypal iframe...");const T=await Bi("PayPal",s,p,C);_e("Paypal flow result",T);const S=Un(T.href),D=Ki(T.href,"catt");if(!D)throw qn("Checkout attempt ID not found in redirect URL:",T.href),new Error("Checkout attempt ID not found in redirect URL");_e(`Confirming payment flow using vault ID ${S}`);const F=await se(s,{secure_token:i.token,their_pm_id:S,checkout_attempt_id:_?D:void 0});if(_e("Confirm payment flow result",F),i.mode==="setup")return{mode:"setup",result:{payment_method_id:F.payment_methods[0].id}};if(!F.pay_first_success_response)throw qn("Checkout failed, no pay-first success response:",F),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:F.pay_first_success_response}}),er=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway: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},Yn=()=>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 Ir=null;const Wn=r=>r===je||r===window.location.origin?"PRODUCTION":"TEST",tr=(r,e)=>{const t=Wn(r);return Ir===null&&(Ir=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),Ir},Ac=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?nn.parse(e):null},Kn=(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[y.EMAIL]=t[y.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[y.COUNTRY]=t[y.COUNTRY]||n.countryCode||"US",t[y.ADDRESS]=t[y.ADDRESS]||n.address1||"",t[y.CITY]=t[y.CITY]||n.locality||"",t[y.ZIP_CODE]=t[y.ZIP_CODE]||n.postalCode||"00000",t[y.STATE]=t[y.STATE]||n.administrativeArea||"",t[y.FIRST_NAME]=t[y.FIRST_NAME]||l||"_OP_UNKNOWN",t[y.LAST_NAME]=t[y.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:ce,err__:ot}=L("awx-google-pay"),xc=Ze(async({context:r,formCallbacks:e})=>{var p,_;const t={processor:ie.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,Zn);if(!n)return t;ce("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return ot("No gateway merchant ID found in processor account"),t;if(ce("Loading Google Pay SDK..."),await Yn(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return ot("Google Pay SDK not loaded properly"),t;if(Wn(r.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return ot("Google Pay merchant ID is required for production environment"),t;ce("Google Pay SDK loaded",window.google.payments);try{const f=er({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await tr(r.baseUrl,f).isReadyToPay(f);if(!h)return ce("Google Pay is not available for this user"),t}catch(f){return ot("Error checking Google Pay availability",f),t}const i=r.anyCdeConnection,c=await z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async f=>{try{Z.airwallexGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){ot("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:ie.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Ic=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var p,_,f,h,w,x,C;ce("Starting Google Pay flow...");const s=ae(r.checkoutPaymentMethods,Zn),{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=er({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=tr(r.baseUrl,u);try{const T=await d.loadPaymentData(u);ce("Google Pay Payment data",T);const S=r.anyCdeConnection,D=await z(S),F=Kn(t,T),U=Me(F,n.get.onValidationError,o==null?void 0:o.defaultFieldValues),ve=(_=(p=T.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!ve)throw new Error("No payment token received from Google Pay");const Hl=await et(S,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:U[y.EMAIL],new_customer_first_name:U[y.FIRST_NAME],new_customer_last_name:U[y.LAST_NAME],new_customer_address:{zip_code:U[y.ZIP_CODE],country:U[y.COUNTRY]}}),ur=Ac(Hl);ce("Start flow next actions",ur);let Ge=await se(S,{secure_token:D.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:ur==null?void 0:ur.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ve}}}});ce("[1st] Confirm payment flow response",Ge);let $r=(h=(f=Ge.payment_methods)==null?void 0:f[0])==null?void 0:h.id;const Be=(w=Ge.required_user_actions)==null?void 0:w.find(Dt=>Dt.type==="airwallex_payment_consent");if(Be&&Be.redirect_url){ce("3DS Required, starting verification...",Be);const{status:Dt}=await Qt({url:Be.redirect_url,baseUrl:r.baseUrl});if(ce(`╰ 3DS verification completed [Status: ${Dt}]`),Dt===$.CANCELLED)throw new Error("3DS verification cancelled");if(Dt===$.FAILURE)throw new Error("3DS verification failed")}if(Be&&!$r&&(Ge=await se(S,{secure_token:D.token,their_pm_id:Be.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Be.consent_id}}),ce("[2nd] Confirm payment flow response",Ge),$r=(C=(x=Ge.payment_methods)==null?void 0:x[0])==null?void 0:C.id),!$r)throw new Error("No PM ID found");return Jt({logPrefix:"awx-googlepay",anyCdeConnection:S,checkoutPaymentMethod:e,requiredFormFields:U,confirmResult:Ge,usePayFirstFlow:!1})}catch(T){throw ot("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Hn=()=>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)}),Jn=(r,e)=>{const t=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...r};return(t||n||o)&&(s[y.EMAIL]=s[y.EMAIL]||(t==null?void 0:t.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[y.COUNTRY]=s[y.COUNTRY]||(t==null?void 0:t.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[y.ZIP_CODE]=s[y.ZIP_CODE]||(t==null?void 0:t.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000",s[y.FIRST_NAME]=s[y.FIRST_NAME]||(t==null?void 0:t.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"_OP_UNKNOWN",s[y.LAST_NAME]=s[y.LAST_NAME]||(t==null?void 0:t.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"_OP_UNKNOWN"),s},Tc=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")}),Rc=r=>Tc.safeParse(r).data,Oc=r=>{const e=new AbortController;return window.addEventListener("message",t=>{var o;const n=Rc(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}`,je).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}`}},Xn=({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__:rr}=L("awx-apple-pay");async function Nc(r,e){try{const n=(await Cn(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 Mc(r,e){if(!r.redirect_url)throw new Error("No redirect URL found");rr("3DS Required, starting verification...",r);const{status:t}=await Qt({url:r.redirect_url,baseUrl:e.baseUrl});if(rr(`╰ 3DS verification completed [Status: ${t}]`),t===$.CANCELLED)throw new Error("3DS verification cancelled");if(t===$.FAILURE)throw new Error("3DS verification failed");const n=await se(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 rr("[2nd] Confirm payment flow response",n),n}async function Dc(r,e){var t,n,o,s,i;try{const c=r.payment,l=Jn(e.nonCdeFormInputs,c),u=Me(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues),_=(await et(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[y.EMAIL],new_customer_first_name:u[y.FIRST_NAME],new_customer_last_name:u[y.LAST_NAME],new_customer_address:{zip_code:u[y.ZIP_CODE],country:u[y.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await se(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)}}}});rr("[1st] Confirm payment flow response",f);let h=(n=(t=f.payment_methods)==null?void 0:t[0])==null?void 0:n.id;const w=(o=f.required_user_actions)==null?void 0:o.find(C=>C.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(f=await Mc(w,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const x={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(x),Jt({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:st,err__:Tr}=L("awx-apple-pay"),jc=Ze(async({context:r,formCallbacks:e})=>{const t={processor:ie.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,$n);if(!n)return t;st("Loading Apple Pay SDK...");try{await Hn(),st("Apple Pay SDK loaded successfully")}catch(p){return Tr("Failed to load Apple Pay SDK",p),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return st("Apple Pay is not available on this device/browser"),t;if(st("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return st("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 z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async p=>{try{await Z.airwallexApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Tr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ie.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Lc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var x;const s=ae(r.checkoutPaymentMethods,$n),{overridePaymentRequest:i,initialPreview:c}=n,l=r.anyCdeConnection,u=await z(l),d=u.mode==="setup",{currencyCode:p,total:_}=Xn({overridePaymentRequest:i,initialPreview:c,defaultLabel:(x=s==null?void 0:s.metadata)==null?void 0:x.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Qn({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,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((C,T)=>{const S=()=>{st("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},{cleanupCancelListener:D}=Oc(S);h.oncancel=S,h.onvalidatemerchant=async F=>{try{await Nc(F,w)}catch(U){T(U)}},h.onpaymentmethodselected=()=>{const F={newTotal:{..._}};h.completePaymentMethodSelection(F)},h.onpaymentauthorized=async F=>{try{const U=await Dc(F,w);D(),C(U)}catch(U){T(U)}},h.begin()}).catch(C=>{throw Tr("Apple Pay payment error",C),C})}),Fc=1,Uc=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string()})}),{log__:J,err__:$c}=L("loop-crypto"),Zc=Ze(async({context:r})=>{J("Checking if there are any CPMs for Loop Crypto...");const e=ae(r.checkoutPaymentMethods,Uc);J(`checkoutPaymentMethod: ${JSON.stringify(e)}`),J("Starting Loop Crypto flow...");const t=await z(r.anyCdeConnection);let n;if(t.mode==="setup"?n=Fc:n=t.amount_total_atom,t.currency!=="usd"&&t.mode!=="setup")throw Error("Cannot support non USD currency for Loop");const o=n,s=Math.max(o*12,1e5),i=br(),c={paymentUsdAmount:o,suggestedAuthorizationUsdAmount:s,customerRefId:i},l={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id};return{isAvailable:!0,widgetProps:c,initLoopConnectProps:l}}),Vc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{J("Running Loop flow..."),J("context",r),J("checkoutPaymentMethod",e),J("nonCdeFormInputs",t),J("flowCallbacks",n),J("customParams",o),J("initResult",s);const i=r.anyCdeConnection;if(!s.isAvailable)throw Error("Failed to initialize Loop flow. Cannot submit without initialization. Exiting running Loop flow.");const c=await z(r.anyCdeConnection),l=c.mode!=="setup",u=await et(r.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:o.email,new_customer_first_name:o.firstName,new_customer_last_name:o.lastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:s.widgetProps.paymentUsdAmount}:void 0});if(!o.success)throw Error(`Payin was not successful: ${o.detail.type} ${o.detail.message} ${JSON.stringify(o.detail.data)}`);const d=await se(i,{secure_token:c.token,their_pm_id:o.payin.paymentMethod.paymentMethodId,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.customer,loop_payin:o.payin}});if(J(`Confirm result: ${d}`),c.mode==="setup"){J("Doing payment setup..."),J("├ Confirm payment flow result received Result:",d);const p=It(d);return J(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(J("Doing checkout..."),!d.pay_first_success_response)throw $c("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}});async function zc(r,e){try{const n=(await Cn(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 Gc(r,e){var t,n;try{const o=r.payment,s=Jn(e.nonCdeFormInputs,o),i=Me(s,e.formCallbacks.get.onValidationError);await et(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[y.EMAIL],new_customer_first_name:i[y.FIRST_NAME],new_customer_last_name:i[y.LAST_NAME],new_customer_address:{zip_code:i[y.ZIP_CODE],country:i[y.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await se(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),Jt({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 eo=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()})}),to=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__:Rt,err__:Rr}=L("authnet-applepay"),Bc=Ze(async({context:r,formCallbacks:e})=>{const t={processor:ie.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,eo);if(!n)return t;Rt("Loading Apple Pay SDK...");try{await Hn(),Rt("Apple Pay SDK loaded successfully")}catch(p){return Rr("Failed to load Apple Pay SDK",p),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return Rt("Apple Pay is not available on this device/browser"),t;if(!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 z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async p=>{try{await Z.authorizeNetApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Rr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ie.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),qc=Ee(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var x;const{initialPreview:s,overridePaymentRequest:i}=n,c=ae(r.checkoutPaymentMethods,eo),{currencyCode:l,total:u}=Xn({overridePaymentRequest:i,initialPreview:s,defaultLabel:(x=c==null?void 0:c.metadata)==null?void 0:x.processor_account_name}),d=r.anyCdeConnection,p=await z(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Qn({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:r.baseUrl,formCallbacks:o};return new Promise((C,T)=>{h.oncancel=()=>{Rt("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async S=>{try{await zc(S,w)}catch(D){T(D)}},h.onpaymentmethodselected=()=>{const S={newTotal:f.total};h.completePaymentMethodSelection(S)},h.onpaymentauthorized=async S=>{try{const D=await Gc(S,w);C(D)}catch(D){T(D)}},h.begin()}).catch(C=>{throw Rr("Apple Pay payment error",C),C})}),{log__:Ve,err__:Ot}=L("authnet-googlepay"),Yc=Ze(async({context:r,formCallbacks:e})=>{var d,p;Ve("Initializing Authnet GooglePay flow");const t={processor:ie.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,to);if(!n)return t;Ve("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Ot("No gateway merchant ID found in processor account"),t;if(Ve("Loading Google Pay SDK..."),await Yn(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Ot("Google Pay SDK not loaded properly"),t;Ve("Google Pay SDK loaded",window.google.payments);try{const _=er({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await tr(r.baseUrl,_).isReadyToPay(_);if(!f)return Ve("Google Pay is not available for this user"),t}catch(_){return Ot("Error checking Google Pay availability",_),t}const s=r.anyCdeConnection,i=await z(s),c=i.mode==="setup",l=await tt(s,i.token,c,void 0),u=async _=>{try{Z.authorizeNetGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:he(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Ot("Google Pay payment error",f),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:ie.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Wc=Ee(async({context:r,nonCdeFormInputs:e,checkoutPaymentMethod:t,formCallbacks:n,customParams:o})=>{var p,_,f,h;const{initialPreview:s,overridePaymentRequest:i}=o,l=ae(r.checkoutPaymentMethods,to).metadata,u=er({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=tr(r.baseUrl,u);try{const w=await d.loadPaymentData(u);Ve("Google Pay Payment data",w);const x=r.anyCdeConnection,C=await z(x),T=Kn(e,w),S=Me(T,n.get.onValidationError),D=(_=(p=w.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!D)throw new Error("No payment token received from Google Pay");const F=await et(x,{payment_provider:t.provider,checkout_payment_method:t,new_customer_email:S[y.EMAIL],new_customer_first_name:S[y.FIRST_NAME],new_customer_last_name:S[y.LAST_NAME],new_customer_address:{zip_code:S[y.ZIP_CODE],country:S[y.COUNTRY]}});Ve("Start payment flow response",F);const U=await se(x,{secure_token:C.token,processor_specific_metadata:{payment_provider:t.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(D)}}});if(!((h=(f=U.payment_methods)==null?void 0:f[0])==null?void 0:h.id))throw new Error("No PM ID found");return Jt({logPrefix:"authnet-googlepay",anyCdeConnection:x,checkoutPaymentMethod:t,requiredFormFields:S,confirmResult:U,usePayFirstFlow:!1})}catch(w){throw Ot("Google Pay payment error",w),new Error((w==null?void 0:w.message)??"Unknown error")}}),Nt=(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]},Z={commonCC:{init:async()=>{},run:pc},stripePR:{init:wc,run:bc},stripeLink:{init:Li,run:Fi},pockytPaypal:{run:Pc},airwallexGooglePay:{init:xc,run:Ic},airwallexApplePay:{init:jc,run:Lc},loopCrypto:{init:Zc,run:Vc},authorizeNetApplePay:{init:Bc,run:qc},authorizeNetGooglePay:{init:Yc,run:Wc}};var Or=function(r,e){return Or=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])},Or(r,e)};function De(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Or(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Kc(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(p){i(p)}}function l(d){try{u(n.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(r,e||[])).next())})}function ro(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 at(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 nr(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 or(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 it(r){return this instanceof it?(this.v=r,this):new it(r)}function Hc(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(f){return function(h){return Promise.resolve(h).then(f,p)}}function c(f,h){n[f]&&(o[f]=function(w){return new Promise(function(x,C){s.push([f,w,x,C])>1||l(f,w)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(n[f](h))}catch(w){_(s[0][3],w)}}function u(f){f.value instanceof it?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Jc(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 at=="function"?at(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 B(r){return typeof r=="function"}function sr(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 Nr=sr(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 ar(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Mt=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=at(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(B(d))try{d()}catch(w){s=w instanceof Nr?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=at(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{so(h)}catch(w){s=s??[],w instanceof Nr?s=or(or([],nr(s)),nr(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new Nr(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)so(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)&&ar(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ar(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),no=Mt.EMPTY;function oo(r){return r instanceof Mt||r&&"closed"in r&&B(r.remove)&&B(r.add)&&B(r.unsubscribe)}function so(r){B(r)?r():r.unsubscribe()}var ao={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},io={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,or([r,e],nr(t)))},clearTimeout:function(r){var e=io.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function co(r){io.setTimeout(function(){throw r})}function lo(){}function ir(r){r()}var Mr=function(r){De(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,oo(t)&&t.add(n)):n.destination=tl,n}return e.create=function(t,n,o){return new jr(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}(Mt),Qc=Function.prototype.bind;function Dr(r,e){return Qc.call(r,e)}var Xc=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){cr(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){cr(n)}else cr(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){cr(t)}},r}(),jr=function(r){De(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(B(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&ao.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Dr(t.next,c),error:t.error&&Dr(t.error,c),complete:t.complete&&Dr(t.complete,c)}):i=t}return s.destination=new Xc(i),s}return e}(Mr);function cr(r){co(r)}function el(r){throw r}var tl={closed:!0,next:lo,error:el,complete:lo},Lr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function rl(r){return r}function nl(r){return r.length===0?rl:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var Ce=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=sl(e)?e:new jr(e,t,n);return ir(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=uo(t),new t(function(o,s){var i=new jr({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[Lr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return nl(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=uo(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 uo(r){var e;return(e=r??ao.Promise)!==null&&e!==void 0?e:Promise}function ol(r){return r&&B(r.next)&&B(r.error)&&B(r.complete)}function sl(r){return r&&r instanceof Mr||ol(r)&&oo(r)}function al(r){return B(r==null?void 0:r.lift)}function il(r){return function(e){if(al(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 cl(r,e,t,n,o){return new ll(r,e,t,n,o)}var ll=function(r){De(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}(Mr),ul=sr(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),po=function(r){De(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 fo(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new ul},e.prototype.next=function(t){var n=this;ir(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=at(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;ir(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;ir(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?no:(this.currentObservers=null,c.push(t),new Mt(function(){n.currentObservers=null,ar(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 Ce;return t.source=this,t},e.create=function(t,n){return new fo(t,n)},e}(Ce),fo=function(r){De(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:no},e}(po),dl={now:function(){return Date.now()},delegate:void 0},pl=function(r){De(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(Mt),ho={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,or([r,e],nr(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},fl=function(r){De(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),ho.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&&ho.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,ar(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(pl),mo=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=dl.now,r}(),hl=function(r){De(e,r);function e(t,n){n===void 0&&(n=mo.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}(mo),ml=new hl(fl),yl=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function _l(r){return B(r==null?void 0:r.then)}function gl(r){return B(r[Lr])}function vl(r){return Symbol.asyncIterator&&B(r==null?void 0:r[Symbol.asyncIterator])}function wl(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 bl(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var kl=bl();function El(r){return B(r==null?void 0:r[kl])}function Cl(r){return Hc(this,arguments,function(){var t,n,o,s;return ro(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,it(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,it(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,it(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 Sl(r){return B(r==null?void 0:r.getReader)}function Pl(r){if(r instanceof Ce)return r;if(r!=null){if(gl(r))return Al(r);if(yl(r))return xl(r);if(_l(r))return Il(r);if(vl(r))return yo(r);if(El(r))return Tl(r);if(Sl(r))return Rl(r)}throw wl(r)}function Al(r){return new Ce(function(e){var t=r[Lr]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function xl(r){return new Ce(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Il(r){return new Ce(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,co)})}function Tl(r){return new Ce(function(e){var t,n;try{for(var o=at(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 yo(r){return new Ce(function(e){Ol(r,e).catch(function(t){return e.error(t)})})}function Rl(r){return yo(Cl(r))}function Ol(r,e){var t,n,o,s;return Kc(this,void 0,void 0,function(){var i,c;return ro(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Jc(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 Nl(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=B(r)?r:function(){return r},n=function(o){return o.error(t())};return new Ce(n)}var Dl=sr(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function jl(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 Dl)}})})}function Ll(r){return r instanceof Date&&!isNaN(r)}var Fl=sr(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Ul(r,e){var t=Ll(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,o=t.each,s=t.with,i=s===void 0?$l:s,c=t.scheduler,l=c===void 0?ml:c,u=t.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return il(function(p,_){var f,h,w=null,x=0,C=function(T){h=Nl(_,l,function(){try{f.unsubscribe(),Pl(i({meta:d,lastValue:w,seen:x})).subscribe(_)}catch(S){_.error(S)}},T)};f=p.subscribe(cl(_,function(T){h==null||h.unsubscribe(),x++,_.next(w=T),o>0&&C(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),w=null})),!x&&C(n!=null?typeof n=="number"?n:+n-l.now():o)})}function $l(r){throw new Fl(r)}class lr{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"&&Yt(this._current);const t={first:e.timeoutSec*1e3,with:()=>Ml(()=>new Error(e.timeoutErrMsg))};return jl(this._subject.pipe(Ul(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new po}get current(){return this._current}}const{log__:Zl,err__:Vl}=L("init-flows"),ze=(r,e)=>{const t=new lr;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);Zl(`✔ ${r} flow initialized successfully. Result:`,o),t.set(o)}catch(o){Vl(`𝙭 ${r} flow initialization failed. Error:`,fe(o),"Details:",o),t.throw(o,fe(o))}}}},zl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Gl=()=>({stripePR:ze("Stripe PR",Z.stripePR.init),stripeLink:ze("Stripe Link",Z.stripeLink.init),airwallexGooglePay:ze("Airwallex GooglePay",Z.airwallexGooglePay.init),airwallexApplePay:ze("Airwallex ApplePay",Z.airwallexApplePay.init),loop:ze("Loop",Z.loopCrypto.init),authorizeNetGooglePay:ze("Authnet GooglePay",Z.authorizeNetGooglePay.init),authorizeNetApplePay:ze("Authnet ApplePay",Z.authorizeNetApplePay.init)}),{err__:Bl}=L("form-callbacks"),le=a.function().optional(),_o=a.object({onFocus:le,onBlur:le,onChange:le,onLoad:le,onLoadError:le,onValidationError:le,onCheckoutStarted:le,onCheckoutSuccess:le,onSetupPaymentMethodSuccess:le,onCheckoutError:le,onPaymentRequestLoad:le}),ge=class ge{constructor(){this.setCallbacks=e=>{this._callbacks=ge.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const o=Ps(t,n??ge.NOOP,Bl);this._callbacks[t]=o})},this._callbacks=ge.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ge.NOOP=()=>{},ge.createEmptyCallbacks=()=>{const e={};return Object.keys(_o.keyof().enum).forEach(t=>{e[t]=ge.NOOP}),e},ge.fromObject=e=>{const t=new ge;return t.setCallbacks(_o.parse(e)),t};let Fr=ge;class ql{constructor(e,t,n,o){this.handleMessage=s=>{if(!s.source)throw new Error("No source found");if(go(s.origin)!==go(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=ya(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=o}}const go=r=>new URL(r).origin;async function Yl(r,e){const n=await dn({iframe:r,debug:!1,childOrigin:e}).promise,o=await Fa(n);if(!Ua(n,o))throw new Error("Got invalid CDE connection object");return n}class Wl{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 Kl=(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&&vo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&vo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},vo=(r,e,t,n,o)=>Z.stripePR.run({context:t,checkoutPaymentMethod:Nt(t.checkoutPaymentMethods,r),nonCdeFormInputs:he(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),wo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Se,err__:Pe}=L("op-form"),Ae=class Ae{constructor(e){this.cdeLoadEvent=new lr,this.anyCdeConn=new lr,this.context=new lr,this.initFlows=Gl(),this.startFormInit=async()=>{try{Se("Initializing OpenPay form:"),Se("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:wo});Se("├ CDE load event received"),Se("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:wo});Se("├ CDE connection received"),Se("├ Creating OJS context, setting up handlers...");const o=Ae.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(o),Kl(this.initFlows,o,this.formCallbacks),Se("├ Starting OJS init flows..."),await zl(this.initFlows,o,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Se("╰ Done initializing OJS flows.")}catch(t){const n=fe(t);Pe("╰ 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=xs.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={[Qe.CARD]:void 0,[Qe.CARD_NUMBER]:void 0,[Qe.CARD_EXPIRY]:void 0,[Qe.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",da(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{Yl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Pe("[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){Pe("Please wait for the form to finish loading before submitting.");return}Z.commonCC.run({context:t,checkoutPaymentMethod:Nt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:he(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Pe("Please wait for the form to finish loading before getting available payment methods.");return}const n={airwallexGooglePay:ee.airwallexGooglePay,airwallexApplePay:ee.airwallexApplePay,authorizeNetGooglePay:ee.authorizenetGooglePay,authorizeNetApplePay:ee.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){Pe("Please wait for the form to finish loading before submitting.");return}switch(t){case ee.pockytPaypal:return Z.pockytPaypal.run({context:o,checkoutPaymentMethod:Nt(o.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:he(o.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case ee.airwallexGooglePay:{const s=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.airwallexApplePay:{const s=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetGooglePay:{const s=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetApplePay:{const s=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.loopCrypto:{const s=this.initFlows.loop.publisher.current;if(!s.isSuccess)throw Error("Loop has not successfully initialized. Cannot submit.");return Z.loopCrypto.run({context:o,checkoutPaymentMethod:Nt(o.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:he(o.formDiv),formCallbacks:this.formCallbacks,customParams:n&&"success"in n&&n.success?{customer:n.customer,payin:n.payin,email:n.email,firstName:n.firstName,lastName:n.lastName,success:!0}:{detail:n.detail,email:n.email,firstName:n.firstName,lastName:n.lastName,success:!1},initResult:s.loadedValue})}default:Yt(t)}},this.submit=this.submitCard,this.destroy=()=>{Se("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)},Ae.assignAsSingleton(this),this.ojsVersion="0.2.15",this.ojsReleaseVersion="0.2.15-alpha.adaa258",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Fr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${br()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Wl,this.eventHandler=new ql(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}};Ae.ojsFlows=Z,Ae.assignAsSingleton=e=>{if(Ae.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ae.getInstance=()=>window.ojs??null,Ae.buildOjsFlowContext=(e,t,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??je).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Ur=Ae;we.FieldName=y,we.OpenPayForm=Ur,we.SubmitMethod=As,we.SubmitMethods=ee,Object.defineProperty(we,Symbol.toStringTag,{value:"Module"})});
25
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function ar(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Mt=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=at(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(B(d))try{d()}catch(w){s=w instanceof Nr?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=at(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{so(h)}catch(w){s=s??[],w instanceof Nr?s=or(or([],nr(s)),nr(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new Nr(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)so(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)&&ar(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ar(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),no=Mt.EMPTY;function oo(r){return r instanceof Mt||r&&"closed"in r&&B(r.remove)&&B(r.add)&&B(r.unsubscribe)}function so(r){B(r)?r():r.unsubscribe()}var ao={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},io={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,or([r,e],nr(t)))},clearTimeout:function(r){var e=io.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function co(r){io.setTimeout(function(){throw r})}function lo(){}function ir(r){r()}var Mr=function(r){De(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,oo(t)&&t.add(n)):n.destination=tl,n}return e.create=function(t,n,o){return new jr(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}(Mt),Qc=Function.prototype.bind;function Dr(r,e){return Qc.call(r,e)}var Xc=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){cr(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){cr(n)}else cr(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){cr(t)}},r}(),jr=function(r){De(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(B(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&ao.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Dr(t.next,c),error:t.error&&Dr(t.error,c),complete:t.complete&&Dr(t.complete,c)}):i=t}return s.destination=new Xc(i),s}return e}(Mr);function cr(r){co(r)}function el(r){throw r}var tl={closed:!0,next:lo,error:el,complete:lo},Lr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function rl(r){return r}function nl(r){return r.length===0?rl:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var Ce=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=sl(e)?e:new jr(e,t,n);return ir(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=uo(t),new t(function(o,s){var i=new jr({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[Lr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return nl(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=uo(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 uo(r){var e;return(e=r??ao.Promise)!==null&&e!==void 0?e:Promise}function ol(r){return r&&B(r.next)&&B(r.error)&&B(r.complete)}function sl(r){return r&&r instanceof Mr||ol(r)&&oo(r)}function al(r){return B(r==null?void 0:r.lift)}function il(r){return function(e){if(al(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 cl(r,e,t,n,o){return new ll(r,e,t,n,o)}var ll=function(r){De(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}(Mr),ul=sr(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),po=function(r){De(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 fo(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new ul},e.prototype.next=function(t){var n=this;ir(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=at(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;ir(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;ir(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?no:(this.currentObservers=null,c.push(t),new Mt(function(){n.currentObservers=null,ar(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 Ce;return t.source=this,t},e.create=function(t,n){return new fo(t,n)},e}(Ce),fo=function(r){De(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:no},e}(po),dl={now:function(){return Date.now()},delegate:void 0},pl=function(r){De(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(Mt),ho={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,or([r,e],nr(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},fl=function(r){De(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),ho.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&&ho.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,ar(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(pl),mo=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=dl.now,r}(),hl=function(r){De(e,r);function e(t,n){n===void 0&&(n=mo.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}(mo),ml=new hl(fl),yl=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function _l(r){return B(r==null?void 0:r.then)}function gl(r){return B(r[Lr])}function vl(r){return Symbol.asyncIterator&&B(r==null?void 0:r[Symbol.asyncIterator])}function wl(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 bl(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var kl=bl();function El(r){return B(r==null?void 0:r[kl])}function Cl(r){return Hc(this,arguments,function(){var t,n,o,s;return ro(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,it(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,it(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,it(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 Sl(r){return B(r==null?void 0:r.getReader)}function Pl(r){if(r instanceof Ce)return r;if(r!=null){if(gl(r))return Al(r);if(yl(r))return xl(r);if(_l(r))return Il(r);if(vl(r))return yo(r);if(El(r))return Tl(r);if(Sl(r))return Rl(r)}throw wl(r)}function Al(r){return new Ce(function(e){var t=r[Lr]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function xl(r){return new Ce(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Il(r){return new Ce(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,co)})}function Tl(r){return new Ce(function(e){var t,n;try{for(var o=at(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 yo(r){return new Ce(function(e){Ol(r,e).catch(function(t){return e.error(t)})})}function Rl(r){return yo(Cl(r))}function Ol(r,e){var t,n,o,s;return Kc(this,void 0,void 0,function(){var i,c;return ro(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Jc(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 Nl(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=B(r)?r:function(){return r},n=function(o){return o.error(t())};return new Ce(n)}var Dl=sr(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function jl(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 Dl)}})})}function Ll(r){return r instanceof Date&&!isNaN(r)}var Fl=sr(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Ul(r,e){var t=Ll(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,o=t.each,s=t.with,i=s===void 0?$l:s,c=t.scheduler,l=c===void 0?ml:c,u=t.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return il(function(p,_){var f,h,w=null,x=0,C=function(T){h=Nl(_,l,function(){try{f.unsubscribe(),Pl(i({meta:d,lastValue:w,seen:x})).subscribe(_)}catch(S){_.error(S)}},T)};f=p.subscribe(cl(_,function(T){h==null||h.unsubscribe(),x++,_.next(w=T),o>0&&C(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),w=null})),!x&&C(n!=null?typeof n=="number"?n:+n-l.now():o)})}function $l(r){throw new Fl(r)}class lr{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"&&Yt(this._current);const t={first:e.timeoutSec*1e3,with:()=>Ml(()=>new Error(e.timeoutErrMsg))};return jl(this._subject.pipe(Ul(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new po}get current(){return this._current}}const{log__:Zl,err__:Vl}=L("init-flows"),ze=(r,e)=>{const t=new lr;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);Zl(`✔ ${r} flow initialized successfully. Result:`,o),t.set(o)}catch(o){Vl(`𝙭 ${r} flow initialization failed. Error:`,fe(o),"Details:",o),t.throw(o,fe(o))}}}},zl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Gl=()=>({stripePR:ze("Stripe PR",Z.stripePR.init),stripeLink:ze("Stripe Link",Z.stripeLink.init),airwallexGooglePay:ze("Airwallex GooglePay",Z.airwallexGooglePay.init),airwallexApplePay:ze("Airwallex ApplePay",Z.airwallexApplePay.init),loop:ze("Loop",Z.loopCrypto.init),authorizeNetGooglePay:ze("Authnet GooglePay",Z.authorizeNetGooglePay.init),authorizeNetApplePay:ze("Authnet ApplePay",Z.authorizeNetApplePay.init)}),{err__:Bl}=L("form-callbacks"),le=a.function().optional(),_o=a.object({onFocus:le,onBlur:le,onChange:le,onLoad:le,onLoadError:le,onValidationError:le,onCheckoutStarted:le,onCheckoutSuccess:le,onSetupPaymentMethodSuccess:le,onCheckoutError:le,onPaymentRequestLoad:le}),ge=class ge{constructor(){this.setCallbacks=e=>{this._callbacks=ge.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const o=Ps(t,n??ge.NOOP,Bl);this._callbacks[t]=o})},this._callbacks=ge.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ge.NOOP=()=>{},ge.createEmptyCallbacks=()=>{const e={};return Object.keys(_o.keyof().enum).forEach(t=>{e[t]=ge.NOOP}),e},ge.fromObject=e=>{const t=new ge;return t.setCallbacks(_o.parse(e)),t};let Fr=ge;class ql{constructor(e,t,n,o){this.handleMessage=s=>{if(!s.source)throw new Error("No source found");if(go(s.origin)!==go(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=ya(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=o}}const go=r=>new URL(r).origin;async function Yl(r,e){const n=await dn({iframe:r,debug:!1,childOrigin:e}).promise,o=await Fa(n);if(!Ua(n,o))throw new Error("Got invalid CDE connection object");return n}class Wl{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 Kl=(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&&vo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&vo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},vo=(r,e,t,n,o)=>Z.stripePR.run({context:t,checkoutPaymentMethod:Nt(t.checkoutPaymentMethods,r),nonCdeFormInputs:he(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),wo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Se,err__:Pe}=L("op-form"),Ae=class Ae{constructor(e){this.cdeLoadEvent=new lr,this.anyCdeConn=new lr,this.context=new lr,this.initFlows=Gl(),this.startFormInit=async()=>{try{Se("Initializing OpenPay form:"),Se("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:wo});Se("├ CDE load event received"),Se("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:wo});Se("├ CDE connection received"),Se("├ Creating OJS context, setting up handlers...");const o=Ae.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(o),Kl(this.initFlows,o,this.formCallbacks),Se("├ Starting OJS init flows..."),await zl(this.initFlows,o,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Se("╰ Done initializing OJS flows.")}catch(t){const n=fe(t);Pe("╰ 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=xs.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={[Qe.CARD]:void 0,[Qe.CARD_NUMBER]:void 0,[Qe.CARD_EXPIRY]:void 0,[Qe.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",da(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{Yl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Pe("[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){Pe("Please wait for the form to finish loading before submitting.");return}Z.commonCC.run({context:t,checkoutPaymentMethod:Nt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:he(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Pe("Please wait for the form to finish loading before getting available payment methods.");return}const n={airwallexGooglePay:ee.airwallexGooglePay,airwallexApplePay:ee.airwallexApplePay,authorizeNetGooglePay:ee.authorizenetGooglePay,authorizeNetApplePay:ee.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){Pe("Please wait for the form to finish loading before submitting.");return}switch(t){case ee.pockytPaypal:return Z.pockytPaypal.run({context:o,checkoutPaymentMethod:Nt(o.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:he(o.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case ee.airwallexGooglePay:{const s=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.airwallexApplePay:{const s=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetGooglePay:{const s=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetApplePay:{const s=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!s){Pe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.loopCrypto:{const s=this.initFlows.loop.publisher.current;if(!s.isSuccess)throw Error("Loop has not successfully initialized. Cannot submit.");return Z.loopCrypto.run({context:o,checkoutPaymentMethod:Nt(o.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:he(o.formDiv),formCallbacks:this.formCallbacks,customParams:n&&"success"in n&&n.success?{customer:n.customer,payin:n.payin,email:n.email,firstName:n.firstName,lastName:n.lastName,success:!0}:{detail:n.detail,email:n.email,firstName:n.firstName,lastName:n.lastName,success:!1},initResult:s.loadedValue})}default:Yt(t)}},this.submit=this.submitCard,this.destroy=()=>{Se("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)},Ae.assignAsSingleton(this),this.ojsVersion="0.2.16",this.ojsReleaseVersion="0.2.16-alpha.1b02bc3",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Fr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${br()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Wl,this.eventHandler=new ql(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}};Ae.ojsFlows=Z,Ae.assignAsSingleton=e=>{if(Ae.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ae.getInstance=()=>window.ojs??null,Ae.buildOjsFlowContext=(e,t,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??je).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Ur=Ae;we.FieldName=y,we.OpenPayForm=Ur,we.SubmitMethod=As,we.SubmitMethods=ee,Object.defineProperty(we,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getopenpay/openpay-js",
3
- "version": "0.2.15-alpha.adaa258",
3
+ "version": "0.2.16-alpha.1b02bc3",
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",