@getopenpay/openpay-js 0.3.2 → 0.3.3

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
@@ -3,13 +3,13 @@ ${t.map(n=>`• ${An(n.msg)}`).join(`
3
3
  `)}`,ea=t=>`Encountered the following errors:
4
4
  ${t.map(n=>`- ${n.path.join("/")}: ${n.message}`).join(`
5
5
  `)}`,re=t=>{if(t instanceof Error)if(Qs(t.message)){const e=JSON.parse(t.message);return Ws.safeParse(e).success?Xs(e):Ks.safeParse(e).success?ea(e):(console.warn(`Encountered unknown stringified JSON object:
6
- ${t.message}`),t.message)}else return An(t.message);if(typeof t=="object")try{return JSON.stringify(t)}catch(e){return e+""}else return t+""},ta=(t,e,n)=>(...r)=>{try{return e(...r)}catch(o){n(`[form] Error running callback (${t}):`,o);return}};var X=(t=>(t.pockytPaypal="pockyt-paypal",t.airwallexGooglePay="airwallex-google-pay",t.airwallexApplePay="airwallex-apple-pay",t.authorizenetGooglePay="authorizenet-google-pay",t.authorizenetApplePay="authorizenet-apple-pay",t.loopCrypto="loop-crypto",t.paypal="paypal",t))(X||{});const na=a.nativeEnum(X),V=a.string().trim().min(1,{message:"Cannot be blank"}),O=a.string().trim().optional(),q=t=>a.nullable(t.optional());var h=(t=>(t.FIRST_NAME="firstName",t.LAST_NAME="lastName",t.EMAIL="email",t.ZIP_CODE="zipCode",t.CITY="city",t.STATE="state",t.COUNTRY="country",t.ADDRESS="address",t.PHONE="phone",t.PROMOTION_CODE="promotionCode",t))(h||{});const lr=a.nativeEnum(h);var ur=(t=>(t.CARD_NUMBER="cardNumber",t.CARD_EXPIRY="cardExpiry",t.CARD_CVC="cardCvc",t))(ur||{});const dr=a.nativeEnum(ur),pr=a.union([lr,dr]);var ge=(t=>(t.CARD="card",t.CARD_NUMBER="card-number",t.CARD_EXPIRY="card-expiry",t.CARD_CVC="card-cvc",t.CDE_BRIDGE="cde-bridge",t))(ge||{});const ra=a.nativeEnum(ge),Xt=a.object({provider:a.string(),processor_name:q(a.string()),metadata:q(a.record(a.string(),a.any()))}),oa=a.object({id:a.string()});a.object({cardNumber:O,expiry:O,cvc:O}),a.object({backgroundColor:O,color:O,fontFamily:O,fontSize:O,fontWeight:O,margin:O,padding:O,letterSpacing:O,lineHeight:O,hideIcon:O});const ue=a.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),sa=ue.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),aa=a.object({type:sa}),ia=ue.extract(["BLUR","FOCUS","CHANGE"]),ca=a.object({type:ia,elementType:dr,errors:a.array(a.string()).optional()}),la=ue.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),ua=a.object({type:la,message:V,headers:a.record(a.string(),a.string()).optional()}),da=ue.extract(["VALIDATION_ERROR"]),pa=a.object({type:da,elementType:pr,errors:a.array(a.string())}),fa=a.object({type:a.literal(ue.enum.LAYOUT),height:V}),ma=a.object({type:a.literal(ue.enum.LOADED),sessionId:V,totalAmountAtoms:a.number(),currency:O,checkoutPaymentMethods:a.array(Xt)}),ha=a.object({type:a.literal(ue.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),ya=a.object({type:a.literal(ue.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),Rt=a.object({firstName:V,lastName:V,email:V,zipCode:V,country:V,promotionCode:O}),_a=a.object({firstName:O,lastName:O,email:V,zipCode:V,country:V,promotionCode:O,address:O,city:O,state:O}),ga=ue.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),va=a.object({type:ga,sessionId:V,checkoutPaymentMethod:Xt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:O,paymentRouteId:O}).extend(Rt.shape),wa=a.object({type:a.literal(ue.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),ba=a.object({type:a.literal(ue.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),Ea=a.discriminatedUnion("type",[aa,ca,ua,pa,fa,ma,va,wa,ba,ha,ya]),ka=a.object({payload:Ea,nonce:V,formId:V,elementId:V});a.object({amountAtom:a.number(),currency:V}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:q(a.string()),their_pm_id:q(a.string()),checkout_attempt_id:q(a.string()),processor_specific_metadata:q(a.record(a.string(),a.any()))});const Tn=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:q(a.array(a.string()))}),Ca=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const Sa=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(Ca)}),Pa=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),Sa]);a.object({session_id:a.string(),checkout_payment_method:Xt,non_cde_form_fields:Rt,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:q(a.string()),extra_metadata:a.record(a.string(),a.any()),payment_route_id:q(a.string())}),a.object({session_id:a.string(),checkout_payment_method:Xt,non_cde_form_fields:Rt,extra_metadata:a.record(a.string(),a.any()).optional(),payment_route_id:q(a.string())});var Z=(t=>(t.SUCCESS="success",t.FAILURE="failure",t.CANCELLED="cancelled",t))(Z||{});const Aa=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Ta=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),fr=a.object({type:a.string(),redirect_url:q(a.string()),initial_intent_id:q(a.string()),consent_id:q(a.string()),their_pm_id:q(a.string()),payment_session:q(a.record(a.string(),a.any()))}),Ia=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),xa=a.object({payment_methods:a.array(oa),pay_first_success_response:q(Tn),required_user_actions:q(a.array(fr))}),mr=t=>{const e={};return Object.entries(t).forEach(([n,r])=>{try{const o=lr.parse(n);Array.isArray(r)?e[o]=r:Array.isArray(r._errors)&&(e[o]=r._errors)}catch{return}}),e},Ra=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Na=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Oa={usd:"usd",brl:"brl"},en=async t=>{for(let n=0;n<10;n++)hr()||await tn(500);if(!hr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(t)},Ma=async(t,e)=>{const n=await en(t);return{elements:n.elements(e),stripe:n}},Da=async(t,e,n,r,o)=>{const s=await en(t),i=Oa[n.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:r},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},tn=t=>new Promise(e=>{setTimeout(e,t)}),hr=()=>"Stripe"in window,Fa=async t=>new Promise((e,n)=>{try{t.on("paymentmethod",async r=>{console.log("paymentmethod EVT:: ",r),e(r)}),t.on("token",async r=>{console.log("token EVT:: ",r)}),t.on("cancel",()=>{n(new Error("Payment cancelled, please click Submit again to pay"))})}catch(r){n(r)}}),La=async(t,e)=>{if(!t.stripe_pk||!t.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(t)}`);const r=await(await en(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:e.paymentMethod.id});if(r.error)throw e.complete("fail"),new Error(`Payment failed: ${r.error.message??"unknown"}`);return e.complete("success"),r},ja=async t=>{var o,s,i,c;const n=await(await en(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:t.stripe_pm_id}),r=(o=n.setupIntent)==null?void 0:o.status;if(r==="succeeded")console.log("[3DS] CONFIRMING PM:",t.stripe_pm_id),console.log("[3DS] Setup intent created:",n.setupIntent);else throw r==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=n.error)==null?void 0:s.message)??((c=(i=n.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Ua=t=>JSON.stringify(t);for(var Y=[],In=0;In<256;++In)Y.push((In+256).toString(16).slice(1));function $a(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}var nn,Va=new Uint8Array(16);function Za(){if(!nn&&(nn=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!nn))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return nn(Va)}var za=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const yr={randomUUID:za};function rt(t,e,n){if(yr.randomUUID&&!e&&!t)return yr.randomUUID();t=t||{};var r=t.random||(t.rng||Za)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,$a(r)}const oe=(t,e)=>Array.from(t.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),Ga=t=>{try{return ka.parse(t)}catch(e){throw console.error("Error parsing event payload:",t,e),e}};var ve;(function(t){t.Call="call",t.Reply="reply",t.Syn="syn",t.SynAck="synAck",t.Ack="ack"})(ve||(ve={}));var ze;(function(t){t.Fulfilled="fulfilled",t.Rejected="rejected"})(ze||(ze={}));var Nt;(function(t){t.ConnectionDestroyed="ConnectionDestroyed",t.ConnectionTimeout="ConnectionTimeout",t.NoIframeSrc="NoIframeSrc"})(Nt||(Nt={}));var xn;(function(t){t.DataCloneError="DataCloneError"})(xn||(xn={}));var Le;(function(t){t.Message="message"})(Le||(Le={}));const Ba=(t,e)=>{const n=[];let r=!1;return{destroy(o){r||(r=!0,e(`${t}: Destroying connection`),n.forEach(s=>{s(o)}))},onDestroy(o){r?o():n.push(o)}}},qa=t=>(...e)=>{t&&console.log("[Penpal]",...e)},Ya={"http:":"80","https:":"443"},Wa=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ha=["file:","data:"],Ka=t=>{if(t&&Ha.find(c=>t.startsWith(c)))return"null";const e=document.location,n=Wa.exec(t);let r,o,s;n?(r=n[1]?n[1]:e.protocol,o=n[2],s=n[4]):(r=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==Ya[r]?`:${s}`:"";return`${r}//${o}${i}`},_r=({name:t,message:e,stack:n})=>({name:t,message:e,stack:n}),Ja=t=>{const e=new Error;return Object.keys(t).forEach(n=>e[n]=t[n]),e},Qa=(t,e,n)=>{const{localName:r,local:o,remote:s,originForSending:i,originForReceiving:c}=t;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==ve.Call)return;if(c!=="*"&&d.origin!==c){n(`${r} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const f=d.data,{methodName:m,args:p,id:_}=f;n(`${r}: Received ${m}() call`);const w=A=>k=>{if(n(`${r}: Sending ${m}() reply`),l){n(`${r}: Unable to send ${m}() reply due to destroyed connection`);return}const x={penpal:ve.Reply,id:_,resolution:A,returnValue:k};A===ze.Rejected&&k instanceof Error&&(x.returnValue=_r(k),x.returnValueIsError=!0);try{s.postMessage(x,i)}catch(I){if(I.name===xn.DataCloneError){const L={penpal:ve.Reply,id:_,resolution:ze.Rejected,returnValue:_r(I),returnValueIsError:!0};s.postMessage(L,i)}throw I}};new Promise(A=>A(e[m].apply(e,p))).then(w(ze.Fulfilled),w(ze.Rejected))};return o.addEventListener(Le.Message,u),()=>{l=!0,o.removeEventListener(Le.Message,u)}};let Xa=0;const ei=()=>++Xa,gr=".",vr=t=>t?t.split(gr):[],ti=t=>t.join(gr),ni=(t,e)=>{const n=vr(e||"");return n.push(t),ti(n)},ri=(t,e,n)=>{const r=vr(e);return r.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===r.length-1&&(o[s]=n),o[s]),t),t},wr=(t,e)=>{const n={};return Object.keys(t).forEach(r=>{const o=t[r],s=ni(r,e);typeof o=="object"&&Object.assign(n,wr(o,s)),typeof o=="function"&&(n[s]=o)}),n},oi=t=>{const e={};for(const n in t)ri(e,n,t[n]);return e},si=(t,e,n,r,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const f=p=>(..._)=>{o(`${s}: Sending ${p}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&r(),d){const A=new Error(`Unable to send ${p}() call due to destroyed connection`);throw A.code=Nt.ConnectionDestroyed,A}return new Promise((A,k)=>{const x=ei(),I=B=>{if(B.source!==c||B.data.penpal!==ve.Reply||B.data.id!==x)return;if(u!=="*"&&B.origin!==u){o(`${s} received message from origin ${B.origin} which did not match expected origin ${u}`);return}const $=B.data;o(`${s}: Received ${p}() reply`),i.removeEventListener(Le.Message,I);let Pe=$.returnValue;$.returnValueIsError&&(Pe=Ja(Pe)),($.resolution===ze.Fulfilled?A:k)(Pe)};i.addEventListener(Le.Message,I);const L={penpal:ve.Call,id:x,methodName:p,args:_};c.postMessage(L,l)})},m=n.reduce((p,_)=>(p[_]=f(_),p),{});return Object.assign(t,oi(m)),()=>{d=!0}},ai=(t,e,n,r,o)=>{const{destroy:s,onDestroy:i}=r;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const f={localName:"Parent",local:window,remote:d.source,originForSending:n,originForReceiving:e};c&&c(),c=Qa(f,t,o),i(c),l&&l.forEach(p=>{delete u[p]}),l=d.data.methodNames;const m=si(u,f,l,s,o);return i(m),u}},ii=(t,e,n,r)=>o=>{if(!o.source)return;if(n!=="*"&&o.origin!==n){t(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${n}`);return}t("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:ve.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,r)},ci=6e4,li=(t,e)=>{const{destroy:n,onDestroy:r}=e,o=setInterval(()=>{t.isConnected||(clearInterval(o),n())},ci);r(()=>{clearInterval(o)})},ui=(t,e)=>{let n;return t!==void 0&&(n=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${t}ms`);r.code=Nt.ConnectionTimeout,e(r)},t)),()=>{clearTimeout(n)}},di=t=>{if(!t.src&&!t.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Nt.NoIframeSrc,e}},br=t=>{let{iframe:e,methods:n={},childOrigin:r,timeout:o,debug:s=!1}=t;const i=qa(s),c=Ba("Parent",i),{onDestroy:l,destroy:u}=c;r||(di(e),r=Ka(e.src));const d=r==="null"?"*":r,f=wr(n),m=ii(i,f,r,d),p=ai(f,r,d,c,i);return{promise:new Promise((w,A)=>{const k=ui(o,u),x=I=>{if(!(I.source!==e.contentWindow||!I.data)){if(I.data.penpal===ve.Syn){m(I);return}if(I.data.penpal===ve.Ack){const L=p(I);L&&(k(),w(L));return}}};window.addEventListener(Le.Message,x),i("Parent: Awaiting handshake"),li(e,c),l(I=>{window.removeEventListener(Le.Message,x),I&&A(I)})}),destroy(){u()}}},pi=async t=>{if(typeof t!="object"||!t)return!1;try{const e={type:"ping"},n=await t.send(e);if(n!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(n)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},fi=(t,e)=>!!t&&e,P=t=>a.nullable(t.optional());a.string().trim().min(1,{message:"Cannot be blank"});const mi=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const Er=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),kr=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:P(a.string()),price_id:a.string(),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),quantity:a.number().int()}),hi=a.record(a.string(),a.any()),yi=a.object({name:a.string(),settings:P(hi)}),ot=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),_i=a.object({quantity:a.number()}),gi=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(_i),trial_start:P(a.string()),trial_end:P(a.string())}),Cr=a.object({amount_atom:a.number()}),vi=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(Cr),subscription_item_id:a.string()}),wi=a.object({coupon:Er}),bi=a.object({currency:a.string(),discounts:a.array(wi),hosted_invoice_url:P(a.string()),lines:a.array(vi),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(Cr)}),Sr=a.object({created:a.array(gi),invoices:a.array(bi),processors_used:P(a.array(a.string()))}),Pr=a.object({preview:Sr,preview_post_trial:P(Sr),coupons:a.array(Er)}),Ar=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(kr),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:yi,subs_preview:P(Pr),methods_available:a.array(ot)}),Tr=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Ar.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Ar.shape)]),Ei=a.object({status:a.literal("complete")}),ki=a.object({status:a.literal("expired")});a.union([Tr,Ei,ki]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(kr),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:ot,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:P(a.string()),payment_route_id:P(a.string())});const Ir=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Ci=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Ci);const Si=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),Pi=a.object({price_id:a.string(),quantity:a.number().int()}),Ai=a.object({line_items:a.array(Pi),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),Ti=a.object({processor_specific_metadata:P(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:ot,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:Ai.optional()}).extend(Si.shape).extend(Ti.shape);const xr=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:_a,checkoutPaymentMethod:ot,payment_route_id:P(a.string())}),a.object({session_id:a.string(),non_cde_form_fields:Rt,checkout_payment_method:ot,extra_metadata:a.record(a.string(),a.any()),payment_route_id:P(a.string())});const Ii=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:P(a.string()),last_name:P(a.string()),line1:P(a.string()),line2:P(a.string()),line3:P(a.string()),city:P(a.string()),state:P(a.string()),country:P(a.string()),zip_code:P(a.string()),email:P(a.string()),billing_email:P(a.string()),phone_number:P(a.string()),update_processor_customer:P(a.boolean())}),a.object({id:a.string(),email:P(a.string()),first_name:P(a.string()),last_name:P(a.string()),phone_number:P(a.string()),billing_email:P(a.string()),address:P(a.record(a.string(),a.any()))}),a.object({message:a.string()});const xi=a.object({error_code:a.string()});a.object({checkout_payment_method:ot,processor_specific_metadata:a.record(a.any()).optional(),payment_route_id:P(a.string())});const Ri=a.object({next_action_metadata:P(a.record(a.any()))});a.object({events:a.array(a.object({event_name:a.string(),device_token:a.string(),properties:a.record(a.any()).optional(),context_properties:a.record(a.any()).optional()}))}),a.any().optional(),a.object({device_token:a.string()});const Ni=a.object({}),Oi=t=>t.reduce((e,n)=>e+n,0);function Mi(t,e){var n=Object.setPrototypeOf;n?n(t,e):t.__proto__=e}function Di(t,e){e===void 0&&(e=t.constructor);var n=Error.captureStackTrace;n&&n(t,e)}var Fi=function(){var t=function(n,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},t(n,r)};return function(e,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),Li=function(t){Fi(e,t);function e(n,r){var o=this.constructor,s=t.call(this,n,r)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),Mi(s,o.prototype),Di(s),s}return e}(Error);const Rn=10,Rr=(t=0)=>e=>`\x1B[${e+t}m`,Nr=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Or=(t=0)=>(e,n,r)=>`\x1B[${38+t};2;${e};${n};${r}m`,M={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(M.modifier);const ji=Object.keys(M.color),Ui=Object.keys(M.bgColor);[...ji,...Ui];function $i(){const t=new Map;for(const[e,n]of Object.entries(M)){for(const[r,o]of Object.entries(n))M[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=M[r],t.set(o[0],o[1]);Object.defineProperty(M,e,{value:n,enumerable:!1})}return Object.defineProperty(M,"codes",{value:t,enumerable:!1}),M.color.close="\x1B[39m",M.bgColor.close="\x1B[49m",M.color.ansi=Rr(),M.color.ansi256=Nr(),M.color.ansi16m=Or(),M.bgColor.ansi=Rr(Rn),M.bgColor.ansi256=Nr(Rn),M.bgColor.ansi16m=Or(Rn),Object.defineProperties(M,{rgbToAnsi256:{value(e,n,r){return e===n&&n===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>M.rgbToAnsi256(...M.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let n,r,o;if(e>=232)n=((e-232)*10+8)/255,r=n,o=n;else{e-=16;const c=e%36;n=Math.floor(e/36)/5,r=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,n,r)=>M.ansi256ToAnsi(M.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>M.ansi256ToAnsi(M.hexToAnsi256(e)),enumerable:!1}}),M}const we=$i(),rn=(()=>{if(navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Mr=rn!==0&&{level:rn,hasBasic:!0,has256:rn>=2,has16m:rn>=3},Vi={stdout:Mr,stderr:Mr};function Zi(t,e,n){let r=t.indexOf(e);if(r===-1)return t;const o=e.length;let s=0,i="";do i+=t.slice(s,r)+e+n,s=r+o,r=t.indexOf(e,s);while(r!==-1);return i+=t.slice(s),i}function zi(t,e,n,r){let o=0,s="";do{const i=t[r-1]==="\r";s+=t.slice(o,i?r-1:r)+e+(i?`\r
6
+ ${t.message}`),t.message)}else return An(t.message);if(typeof t=="object")try{return JSON.stringify(t)}catch(e){return e+""}else return t+""},ta=(t,e,n)=>(...r)=>{try{return e(...r)}catch(o){n(`[form] Error running callback (${t}):`,o);return}};var X=(t=>(t.pockytPaypal="pockyt-paypal",t.airwallexGooglePay="airwallex-google-pay",t.airwallexApplePay="airwallex-apple-pay",t.authorizenetGooglePay="authorizenet-google-pay",t.authorizenetApplePay="authorizenet-apple-pay",t.loopCrypto="loop-crypto",t.paypal="paypal",t))(X||{});const na=a.nativeEnum(X),V=a.string().trim().min(1,{message:"Cannot be blank"}),O=a.string().trim().optional(),q=t=>a.nullable(t.optional());var h=(t=>(t.FIRST_NAME="firstName",t.LAST_NAME="lastName",t.EMAIL="email",t.ZIP_CODE="zipCode",t.CITY="city",t.STATE="state",t.COUNTRY="country",t.ADDRESS="address",t.PHONE="phone",t.PROMOTION_CODE="promotionCode",t))(h||{});const lr=a.nativeEnum(h);var ur=(t=>(t.CARD_NUMBER="cardNumber",t.CARD_EXPIRY="cardExpiry",t.CARD_CVC="cardCvc",t))(ur||{});const dr=a.nativeEnum(ur),pr=a.union([lr,dr]);var ge=(t=>(t.CARD="card",t.CARD_NUMBER="card-number",t.CARD_EXPIRY="card-expiry",t.CARD_CVC="card-cvc",t.CDE_BRIDGE="cde-bridge",t))(ge||{});const ra=a.nativeEnum(ge),Xt=a.object({provider:a.string(),processor_name:q(a.string()),metadata:q(a.record(a.string(),a.any()))}),oa=a.object({id:a.string()});a.object({cardNumber:O,expiry:O,cvc:O}),a.object({backgroundColor:O,color:O,fontFamily:O,fontSize:O,fontWeight:O,margin:O,padding:O,letterSpacing:O,lineHeight:O,hideIcon:O});const ue=a.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),sa=ue.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),aa=a.object({type:sa}),ia=ue.extract(["BLUR","FOCUS","CHANGE"]),ca=a.object({type:ia,elementType:dr,errors:a.array(a.string()).optional()}),la=ue.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),ua=a.object({type:la,message:V,headers:a.record(a.string(),a.string()).optional()}),da=ue.extract(["VALIDATION_ERROR"]),pa=a.object({type:da,elementType:pr,errors:a.array(a.string())}),fa=a.object({type:a.literal(ue.enum.LAYOUT),height:V}),ma=a.object({type:a.literal(ue.enum.LOADED),sessionId:V,totalAmountAtoms:a.number(),currency:O,checkoutPaymentMethods:a.array(Xt)}),ha=a.object({type:a.literal(ue.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),ya=a.object({type:a.literal(ue.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),Rt=a.object({firstName:V,lastName:V,email:V,zipCode:V,country:V,promotionCode:O}),_a=a.object({firstName:O,lastName:O,email:V,zipCode:V,country:V,promotionCode:O,address:O,city:O,state:O}),ga=ue.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),va=a.object({type:ga,sessionId:V,checkoutPaymentMethod:Xt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:O,paymentRouteId:O}).extend(Rt.shape),wa=a.object({type:a.literal(ue.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),ba=a.object({type:a.literal(ue.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),Ea=a.discriminatedUnion("type",[aa,ca,ua,pa,fa,ma,va,wa,ba,ha,ya]),ka=a.object({payload:Ea,nonce:V,formId:V,elementId:V});a.object({amountAtom:a.number(),currency:V}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:q(a.string()),their_pm_id:q(a.string()),checkout_attempt_id:q(a.string()),processor_specific_metadata:q(a.record(a.string(),a.any()))});const Tn=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:q(a.array(a.string()))}),Ca=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const Sa=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(Ca)}),Pa=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),Sa]);a.object({session_id:a.string(),checkout_payment_method:Xt,non_cde_form_fields:Rt,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:q(a.string()),extra_metadata:a.record(a.string(),a.any()),payment_route_id:q(a.string())}),a.object({session_id:a.string(),checkout_payment_method:Xt,non_cde_form_fields:Rt,extra_metadata:a.record(a.string(),a.any()).optional(),payment_route_id:q(a.string())});var Z=(t=>(t.SUCCESS="success",t.FAILURE="failure",t.CANCELLED="cancelled",t))(Z||{});const Aa=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const Ta=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),fr=a.object({type:a.string(),redirect_url:q(a.string()),initial_intent_id:q(a.string()),consent_id:q(a.string()),their_pm_id:q(a.string()),payment_session:q(a.record(a.string(),a.any()))}),Ia=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),xa=a.object({payment_methods:a.array(oa),pay_first_success_response:q(Tn),required_user_actions:q(a.array(fr))}),mr=t=>{const e={};return Object.entries(t).forEach(([n,r])=>{try{const o=lr.parse(n);Array.isArray(r)?e[o]=r:Array.isArray(r._errors)&&(e[o]=r._errors)}catch{return}}),e},Ra=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Na=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),Oa={usd:"usd",brl:"brl"},en=async t=>{for(let n=0;n<10;n++)hr()||await tn(500);if(!hr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(t)},Ma=async(t,e)=>{const n=await en(t);return{elements:n.elements(e),stripe:n}},Da=async(t,e,n,r,o)=>{const s=await en(t),i=Oa[n.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:r},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},tn=t=>new Promise(e=>{setTimeout(e,t)}),hr=()=>"Stripe"in window,Fa=async t=>new Promise((e,n)=>{try{t.on("paymentmethod",async r=>{console.log("paymentmethod EVT:: ",r),e(r)}),t.on("token",async r=>{console.log("token EVT:: ",r)}),t.on("cancel",()=>{n(new Error("Payment cancelled, please click Submit again to pay"))})}catch(r){n(r)}}),La=async(t,e)=>{if(!t.stripe_pk||!t.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(t)}`);const r=await(await en(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:e.paymentMethod.id});if(r.error)throw e.complete("fail"),new Error(`Payment failed: ${r.error.message??"unknown"}`);return e.complete("success"),r},ja=async t=>{var o,s,i,c;const n=await(await en(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:t.stripe_pm_id}),r=(o=n.setupIntent)==null?void 0:o.status;if(r==="succeeded")console.log("[3DS] CONFIRMING PM:",t.stripe_pm_id),console.log("[3DS] Setup intent created:",n.setupIntent);else throw r==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=n.error)==null?void 0:s.message)??((c=(i=n.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Ua=t=>JSON.stringify(t);for(var Y=[],In=0;In<256;++In)Y.push((In+256).toString(16).slice(1));function $a(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}var nn,Va=new Uint8Array(16);function Za(){if(!nn&&(nn=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!nn))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return nn(Va)}var za=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const yr={randomUUID:za};function rt(t,e,n){if(yr.randomUUID&&!e&&!t)return yr.randomUUID();t=t||{};var r=t.random||(t.rng||Za)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,$a(r)}const oe=(t,e)=>Array.from(t.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),Ga=t=>{try{return ka.parse(t)}catch(e){throw console.error("Error parsing event payload:",t,e),e}};var ve;(function(t){t.Call="call",t.Reply="reply",t.Syn="syn",t.SynAck="synAck",t.Ack="ack"})(ve||(ve={}));var ze;(function(t){t.Fulfilled="fulfilled",t.Rejected="rejected"})(ze||(ze={}));var Nt;(function(t){t.ConnectionDestroyed="ConnectionDestroyed",t.ConnectionTimeout="ConnectionTimeout",t.NoIframeSrc="NoIframeSrc"})(Nt||(Nt={}));var xn;(function(t){t.DataCloneError="DataCloneError"})(xn||(xn={}));var Le;(function(t){t.Message="message"})(Le||(Le={}));const Ba=(t,e)=>{const n=[];let r=!1;return{destroy(o){r||(r=!0,e(`${t}: Destroying connection`),n.forEach(s=>{s(o)}))},onDestroy(o){r?o():n.push(o)}}},qa=t=>(...e)=>{t&&console.log("[Penpal]",...e)},Ya={"http:":"80","https:":"443"},Wa=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ha=["file:","data:"],Ka=t=>{if(t&&Ha.find(c=>t.startsWith(c)))return"null";const e=document.location,n=Wa.exec(t);let r,o,s;n?(r=n[1]?n[1]:e.protocol,o=n[2],s=n[4]):(r=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==Ya[r]?`:${s}`:"";return`${r}//${o}${i}`},_r=({name:t,message:e,stack:n})=>({name:t,message:e,stack:n}),Ja=t=>{const e=new Error;return Object.keys(t).forEach(n=>e[n]=t[n]),e},Qa=(t,e,n)=>{const{localName:r,local:o,remote:s,originForSending:i,originForReceiving:c}=t;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==ve.Call)return;if(c!=="*"&&d.origin!==c){n(`${r} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const f=d.data,{methodName:m,args:p,id:_}=f;n(`${r}: Received ${m}() call`);const w=A=>k=>{if(n(`${r}: Sending ${m}() reply`),l){n(`${r}: Unable to send ${m}() reply due to destroyed connection`);return}const x={penpal:ve.Reply,id:_,resolution:A,returnValue:k};A===ze.Rejected&&k instanceof Error&&(x.returnValue=_r(k),x.returnValueIsError=!0);try{s.postMessage(x,i)}catch(I){if(I.name===xn.DataCloneError){const L={penpal:ve.Reply,id:_,resolution:ze.Rejected,returnValue:_r(I),returnValueIsError:!0};s.postMessage(L,i)}throw I}};new Promise(A=>A(e[m].apply(e,p))).then(w(ze.Fulfilled),w(ze.Rejected))};return o.addEventListener(Le.Message,u),()=>{l=!0,o.removeEventListener(Le.Message,u)}};let Xa=0;const ei=()=>++Xa,gr=".",vr=t=>t?t.split(gr):[],ti=t=>t.join(gr),ni=(t,e)=>{const n=vr(e||"");return n.push(t),ti(n)},ri=(t,e,n)=>{const r=vr(e);return r.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===r.length-1&&(o[s]=n),o[s]),t),t},wr=(t,e)=>{const n={};return Object.keys(t).forEach(r=>{const o=t[r],s=ni(r,e);typeof o=="object"&&Object.assign(n,wr(o,s)),typeof o=="function"&&(n[s]=o)}),n},oi=t=>{const e={};for(const n in t)ri(e,n,t[n]);return e},si=(t,e,n,r,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const f=p=>(..._)=>{o(`${s}: Sending ${p}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&r(),d){const A=new Error(`Unable to send ${p}() call due to destroyed connection`);throw A.code=Nt.ConnectionDestroyed,A}return new Promise((A,k)=>{const x=ei(),I=B=>{if(B.source!==c||B.data.penpal!==ve.Reply||B.data.id!==x)return;if(u!=="*"&&B.origin!==u){o(`${s} received message from origin ${B.origin} which did not match expected origin ${u}`);return}const $=B.data;o(`${s}: Received ${p}() reply`),i.removeEventListener(Le.Message,I);let Pe=$.returnValue;$.returnValueIsError&&(Pe=Ja(Pe)),($.resolution===ze.Fulfilled?A:k)(Pe)};i.addEventListener(Le.Message,I);const L={penpal:ve.Call,id:x,methodName:p,args:_};c.postMessage(L,l)})},m=n.reduce((p,_)=>(p[_]=f(_),p),{});return Object.assign(t,oi(m)),()=>{d=!0}},ai=(t,e,n,r,o)=>{const{destroy:s,onDestroy:i}=r;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const f={localName:"Parent",local:window,remote:d.source,originForSending:n,originForReceiving:e};c&&c(),c=Qa(f,t,o),i(c),l&&l.forEach(p=>{delete u[p]}),l=d.data.methodNames;const m=si(u,f,l,s,o);return i(m),u}},ii=(t,e,n,r)=>o=>{if(!o.source)return;if(n!=="*"&&o.origin!==n){t(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${n}`);return}t("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:ve.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,r)},ci=6e4,li=(t,e)=>{const{destroy:n,onDestroy:r}=e,o=setInterval(()=>{t.isConnected||(clearInterval(o),n())},ci);r(()=>{clearInterval(o)})},ui=(t,e)=>{let n;return t!==void 0&&(n=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${t}ms`);r.code=Nt.ConnectionTimeout,e(r)},t)),()=>{clearTimeout(n)}},di=t=>{if(!t.src&&!t.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Nt.NoIframeSrc,e}},br=t=>{let{iframe:e,methods:n={},childOrigin:r,timeout:o,debug:s=!1}=t;const i=qa(s),c=Ba("Parent",i),{onDestroy:l,destroy:u}=c;r||(di(e),r=Ka(e.src));const d=r==="null"?"*":r,f=wr(n),m=ii(i,f,r,d),p=ai(f,r,d,c,i);return{promise:new Promise((w,A)=>{const k=ui(o,u),x=I=>{if(!(I.source!==e.contentWindow||!I.data)){if(I.data.penpal===ve.Syn){m(I);return}if(I.data.penpal===ve.Ack){const L=p(I);L&&(k(),w(L));return}}};window.addEventListener(Le.Message,x),i("Parent: Awaiting handshake"),li(e,c),l(I=>{window.removeEventListener(Le.Message,x),I&&A(I)})}),destroy(){u()}}},pi=async t=>{if(typeof t!="object"||!t)return!1;try{const e={type:"ping"},n=await t.send(e);if(n!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(n)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},fi=(t,e)=>!!t&&e;function mi(t,e){var n=Object.setPrototypeOf;n?n(t,e):t.__proto__=e}function hi(t,e){e===void 0&&(e=t.constructor);var n=Error.captureStackTrace;n&&n(t,e)}var yi=function(){var t=function(n,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},t(n,r)};return function(e,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),_i=function(t){yi(e,t);function e(n,r){var o=this.constructor,s=t.call(this,n,r)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),mi(s,o.prototype),hi(s),s}return e}(Error);const P=t=>a.nullable(t.optional());a.string().trim().min(1,{message:"Cannot be blank"});const gi=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const Er=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),kr=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:P(a.string()),price_id:a.string(),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),quantity:a.number().int()}),vi=a.record(a.string(),a.any()),wi=a.object({name:a.string(),settings:P(vi)}),ot=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),bi=a.object({quantity:a.number()}),Ei=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(bi),trial_start:P(a.string()),trial_end:P(a.string())}),Cr=a.object({amount_atom:a.number()}),ki=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(Cr),subscription_item_id:a.string()}),Ci=a.object({coupon:Er}),Si=a.object({currency:a.string(),discounts:a.array(Ci),hosted_invoice_url:P(a.string()),lines:a.array(ki),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(Cr)}),Sr=a.object({created:a.array(Ei),invoices:a.array(Si),processors_used:P(a.array(a.string()))}),Pr=a.object({preview:Sr,preview_post_trial:P(Sr),coupons:a.array(Er)}),Ar=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(kr),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:wi,subs_preview:P(Pr),methods_available:a.array(ot)}),Tr=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(Ar.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(Ar.shape)]),Pi=a.object({status:a.literal("complete")}),Ai=a.object({status:a.literal("expired")});a.union([Tr,Pi,Ai]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(kr),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:ot,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:P(a.string()),payment_route_id:P(a.string())});const Ir=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Ti=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Ti);const Ii=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),xi=a.object({price_id:a.string(),quantity:a.number().int()}),Ri=a.object({line_items:a.array(xi),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),Ni=a.object({processor_specific_metadata:P(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:ot,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:Ri.optional()}).extend(Ii.shape).extend(Ni.shape);const xr=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:_a,checkoutPaymentMethod:ot,payment_route_id:P(a.string())}),a.object({session_id:a.string(),non_cde_form_fields:Rt,checkout_payment_method:ot,extra_metadata:a.record(a.string(),a.any()),payment_route_id:P(a.string())});const Oi=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:P(a.string()),last_name:P(a.string()),line1:P(a.string()),line2:P(a.string()),line3:P(a.string()),city:P(a.string()),state:P(a.string()),country:P(a.string()),zip_code:P(a.string()),email:P(a.string()),billing_email:P(a.string()),phone_number:P(a.string()),update_processor_customer:P(a.boolean())}),a.object({id:a.string(),email:P(a.string()),first_name:P(a.string()),last_name:P(a.string()),phone_number:P(a.string()),billing_email:P(a.string()),address:P(a.record(a.string(),a.any()))}),a.object({message:a.string()});const Mi=a.object({error_code:a.string()});a.object({checkout_payment_method:ot,processor_specific_metadata:a.record(a.any()).optional(),payment_route_id:P(a.string())});const Di=a.object({next_action_metadata:P(a.record(a.any()))});a.object({events:a.array(a.object({event_name:a.string(),device_token:a.string(),properties:a.record(a.any()).optional(),context_properties:a.record(a.any()).optional()}))}),a.any().optional(),a.object({device_token:a.string()});const Fi=a.object({}),Li=t=>t.reduce((e,n)=>e+n,0),Rn=10,Rr=(t=0)=>e=>`\x1B[${e+t}m`,Nr=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Or=(t=0)=>(e,n,r)=>`\x1B[${38+t};2;${e};${n};${r}m`,M={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(M.modifier);const ji=Object.keys(M.color),Ui=Object.keys(M.bgColor);[...ji,...Ui];function $i(){const t=new Map;for(const[e,n]of Object.entries(M)){for(const[r,o]of Object.entries(n))M[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=M[r],t.set(o[0],o[1]);Object.defineProperty(M,e,{value:n,enumerable:!1})}return Object.defineProperty(M,"codes",{value:t,enumerable:!1}),M.color.close="\x1B[39m",M.bgColor.close="\x1B[49m",M.color.ansi=Rr(),M.color.ansi256=Nr(),M.color.ansi16m=Or(),M.bgColor.ansi=Rr(Rn),M.bgColor.ansi256=Nr(Rn),M.bgColor.ansi16m=Or(Rn),Object.defineProperties(M,{rgbToAnsi256:{value(e,n,r){return e===n&&n===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>M.rgbToAnsi256(...M.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let n,r,o;if(e>=232)n=((e-232)*10+8)/255,r=n,o=n;else{e-=16;const c=e%36;n=Math.floor(e/36)/5,r=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,n,r)=>M.ansi256ToAnsi(M.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>M.ansi256ToAnsi(M.hexToAnsi256(e)),enumerable:!1}}),M}const we=$i(),rn=(()=>{if(navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Mr=rn!==0&&{level:rn,hasBasic:!0,has256:rn>=2,has16m:rn>=3},Vi={stdout:Mr,stderr:Mr};function Zi(t,e,n){let r=t.indexOf(e);if(r===-1)return t;const o=e.length;let s=0,i="";do i+=t.slice(s,r)+e+n,s=r+o,r=t.indexOf(e,s);while(r!==-1);return i+=t.slice(s),i}function zi(t,e,n,r){let o=0,s="";do{const i=t[r-1]==="\r";s+=t.slice(o,i?r-1:r)+e+(i?`\r
7
7
  `:`
8
8
  `)+n,o=r+1,r=t.indexOf(`
9
9
  `,o)}while(r!==-1);return s+=t.slice(o),s}const{stdout:Dr,stderr:Fr}=Vi,Nn=Symbol("GENERATOR"),st=Symbol("STYLER"),Ot=Symbol("IS_EMPTY"),Lr=["ansi","ansi","ansi256","ansi16m"],at=Object.create(null),Gi=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=Dr?Dr.level:0;t.level=e.level===void 0?n:e.level},Bi=t=>{const e=(...n)=>n.join(" ");return Gi(e,t),Object.setPrototypeOf(e,Mt.prototype),e};function Mt(t){return Bi(t)}Object.setPrototypeOf(Mt.prototype,Function.prototype);for(const[t,e]of Object.entries(we))at[t]={get(){const n=on(this,Mn(e.open,e.close,this[st]),this[Ot]);return Object.defineProperty(this,t,{value:n}),n}};at.visible={get(){const t=on(this,this[st],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const On=(t,e,n,...r)=>t==="rgb"?e==="ansi16m"?we[n].ansi16m(...r):e==="ansi256"?we[n].ansi256(we.rgbToAnsi256(...r)):we[n].ansi(we.rgbToAnsi(...r)):t==="hex"?On("rgb",e,n,...we.hexToRgb(...r)):we[n][t](...r),qi=["rgb","hex","ansi256"];for(const t of qi){at[t]={get(){const{level:n}=this;return function(...r){const o=Mn(On(t,Lr[n],"color",...r),we.color.close,this[st]);return on(this,o,this[Ot])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);at[e]={get(){const{level:n}=this;return function(...r){const o=Mn(On(t,Lr[n],"bgColor",...r),we.bgColor.close,this[st]);return on(this,o,this[Ot])}}}}const Yi=Object.defineProperties(()=>{},{...at,level:{enumerable:!0,get(){return this[Nn].level},set(t){this[Nn].level=t}}}),Mn=(t,e,n)=>{let r,o;return n===void 0?(r=t,o=e):(r=n.openAll+t,o=e+n.closeAll),{open:t,close:e,openAll:r,closeAll:o,parent:n}},on=(t,e,n)=>{const r=(...o)=>Wi(r,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(r,Yi),r[Nn]=t,r[st]=e,r[Ot]=n,r},Wi=(t,e)=>{if(t.level<=0||!e)return t[Ot]?"":e;let n=t[st];if(n===void 0)return e;const{openAll:r,closeAll:o}=n;if(e.includes("\x1B"))for(;n!==void 0;)e=Zi(e,n.close,n.open),n=n.parent;const s=e.indexOf(`
10
- `);return s!==-1&&(e=zi(e,o,r,s)),r+e+o};Object.defineProperties(Mt.prototype,at);const sn=Mt();Mt({level:Fr?Fr.level:0});const be=t=>async e=>{var n,r;try{(r=(n=e.formCallbacks.get).onCheckoutStarted)==null||r.call(n),E("checkout_started",{cpm:e.checkoutPaymentMethod});const o=await t(e);if(E("checkout_success",{cpm:e.checkoutPaymentMethod,...o}),o.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(o.result.payment_method_id);else if(o.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(o.result.invoice_urls,o.result.subscription_ids,o.result.customer_id,o.result.processors_used??[]);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=re(o),i=await co(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),E("checkout_error",{cpm:e.checkoutPaymentMethod,errorMessage:s,errorCode:i})}},Ge=t=>async e=>{try{return await t(e)}catch(n){const{err__:r}=D("init-error-catcher"),o=re(n),s=await co(e.context.anyCdeConnection,o);return r(s,o,n),E("init_flow_error",{errorMessage:o,errorCode:s}),{isAvailable:!1,reason:o,errorCode:s,isLoading:!1}}},D=t=>{const e=(...r)=>{window.console.log(`${sn.green.bold("ojs/")}${sn.bold.gray(`${t}`)} `,...r)},n=(...r)=>{window.console.warn(`${sn.red.bold("ojs/")}${sn.bold.gray(`${t}`)} `,...r)};return{log:e,err:n,log__:e,err__:n}};var Dn=function(t,e){return Dn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},Dn(t,e)};function je(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Dn(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Hi(t,e,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function c(d){try{u(r.next(d))}catch(f){i(f)}}function l(d){try{u(r.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((r=r.apply(t,e||[])).next())})}function jr(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,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(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(n=0)),n;)try{if(r=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 n.label++,{value:u[1],done:!1};case 5:n.label++,o=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(d){u=[6,d],o=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function it(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function an(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s}function cn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}function ct(t){return this instanceof ct?(this.v=t,this):new ct(t)}function Ki(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(p){return function(_){return Promise.resolve(_).then(p,f)}}function c(p,_){r[p]&&(o[p]=function(w){return new Promise(function(A,k){s.push([p,w,A,k])>1||l(p,w)})},_&&(o[p]=_(o[p])))}function l(p,_){try{u(r[p](_))}catch(w){m(s[0][3],w)}}function u(p){p.value instanceof ct?Promise.resolve(p.value.v).then(d,f):m(s[0][2],p)}function d(p){l("next",p)}function f(p){l("throw",p)}function m(p,_){p(_),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Ji(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof it=="function"?it(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(i){return new Promise(function(c,l){i=t[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 W(t){return typeof t=="function"}function ln(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Fn=ln(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
10
+ `);return s!==-1&&(e=zi(e,o,r,s)),r+e+o};Object.defineProperties(Mt.prototype,at);const sn=Mt();Mt({level:Fr?Fr.level:0});const be=t=>async e=>{var n,r;try{(r=(n=e.formCallbacks.get).onCheckoutStarted)==null||r.call(n),E("checkout_started",{cpm:e.checkoutPaymentMethod});const o=await t(e);if(E("checkout_success",{cpm:e.checkoutPaymentMethod,...o}),o.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(o.result.payment_method_id);else if(o.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(o.result.invoice_urls,o.result.subscription_ids,o.result.customer_id,o.result.processors_used??[]);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=re(o),i=await co(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),E("checkout_error",{cpm:e.checkoutPaymentMethod,errorMessage:s,errorCode:i,error:o})}},Ge=t=>async e=>{try{return await t(e)}catch(n){const{err__:r}=D("init-error-catcher"),o=re(n),s=await co(e.context.anyCdeConnection,o);return r(s,o,n),E("init_flow_error",{errorMessage:o,errorCode:s,error:n}),{isAvailable:!1,reason:o,errorCode:s,isLoading:!1}}},D=t=>{const e=(...r)=>{window.console.log(`${sn.green.bold("ojs/")}${sn.bold.gray(`${t}`)} `,...r)},n=(...r)=>{window.console.warn(`${sn.red.bold("ojs/")}${sn.bold.gray(`${t}`)} `,...r)};return{log:e,err:n,log__:e,err__:n}};var Dn=function(t,e){return Dn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},Dn(t,e)};function je(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Dn(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Hi(t,e,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function c(d){try{u(r.next(d))}catch(f){i(f)}}function l(d){try{u(r.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((r=r.apply(t,e||[])).next())})}function jr(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,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(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(n=0)),n;)try{if(r=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 n.label++,{value:u[1],done:!1};case 5:n.label++,o=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(d){u=[6,d],o=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function it(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function an(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s}function cn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}function ct(t){return this instanceof ct?(this.v=t,this):new ct(t)}function Ki(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(p){return function(_){return Promise.resolve(_).then(p,f)}}function c(p,_){r[p]&&(o[p]=function(w){return new Promise(function(A,k){s.push([p,w,A,k])>1||l(p,w)})},_&&(o[p]=_(o[p])))}function l(p,_){try{u(r[p](_))}catch(w){m(s[0][3],w)}}function u(p){p.value instanceof ct?Promise.resolve(p.value.v).then(d,f):m(s[0][2],p)}function d(p){l("next",p)}function f(p){l("throw",p)}function m(p,_){p(_),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Ji(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof it=="function"?it(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(i){return new Promise(function(c,l){i=t[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 W(t){return typeof t=="function"}function ln(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Fn=ln(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
11
11
  `+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
12
- `):"",this.name="UnsubscriptionError",this.errors=n}});function un(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var Dt=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,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=it(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&&(n=c.return)&&n.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(W(d))try{d()}catch(w){s=w instanceof Fn?w.errors:[w]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var m=it(f),p=m.next();!p.done;p=m.next()){var _=p.value;try{Vr(_)}catch(w){s=s??[],w instanceof Fn?s=cn(cn([],an(s)),an(w.errors)):s.push(w)}}}catch(w){r={error:w}}finally{try{p&&!p.done&&(o=m.return)&&o.call(m)}finally{if(r)throw r.error}}}if(s)throw new Fn(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Vr(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&un(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&un(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),Ur=Dt.EMPTY;function $r(t){return t instanceof Dt||t&&"closed"in t&&W(t.remove)&&W(t.add)&&W(t.unsubscribe)}function Vr(t){W(t)?t():t.unsubscribe()}var Zr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},zr={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,cn([t,e],an(n)))},clearTimeout:function(t){var e=zr.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Gr(t){zr.setTimeout(function(){throw t})}function Br(){}function dn(t){t()}var Ln=function(t){je(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,$r(n)&&n.add(r)):r.destination=tc,r}return e.create=function(n,r,o){return new Un(n,r,o)},e.prototype.next=function(n){this.isStopped||this._next(n)},e.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Dt),Qi=Function.prototype.bind;function jn(t,e){return Qi.call(t,e)}var Xi=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){pn(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){pn(r)}else pn(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){pn(n)}},t}(),Un=function(t){je(e,t);function e(n,r,o){var s=t.call(this)||this,i;if(W(n)||!n)i={next:n??void 0,error:r??void 0,complete:o??void 0};else{var c;s&&Zr.useDeprecatedNextContext?(c=Object.create(n),c.unsubscribe=function(){return s.unsubscribe()},i={next:n.next&&jn(n.next,c),error:n.error&&jn(n.error,c),complete:n.complete&&jn(n.complete,c)}):i=n}return s.destination=new Xi(i),s}return e}(Ln);function pn(t){Gr(t)}function ec(t){throw t}var tc={closed:!0,next:Br,error:ec,complete:Br},$n=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function nc(t){return t}function rc(t){return t.length===0?nc:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var xe=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,s=sc(e)?e:new Un(e,n,r);return dn(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},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=qr(n),new n(function(o,s){var i=new Un({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[$n]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return rc(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=qr(e),new e(function(r,o){var s;n.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},t.create=function(e){return new t(e)},t}();function qr(t){var e;return(e=t??Zr.Promise)!==null&&e!==void 0?e:Promise}function oc(t){return t&&W(t.next)&&W(t.error)&&W(t.complete)}function sc(t){return t&&t instanceof Ln||oc(t)&&$r(t)}function ac(t){return W(t==null?void 0:t.lift)}function ic(t){return function(e){if(ac(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function cc(t,e,n,r,o){return new lc(t,e,n,r,o)}var lc=function(t){je(e,t);function e(n,r,o,s,i,c){var l=t.call(this,n)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=r?function(u){try{r(u)}catch(d){n.error(d)}}:t.prototype._next,l._error=s?function(u){try{s(u)}catch(d){n.error(d)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){n.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e}(Ln),uc=ln(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Yr=function(t){je(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new Wr(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new uc},e.prototype.next=function(n){var r=this;dn(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=it(r.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(n)}}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(n){var r=this;dn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;dn(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Ur:(this.currentObservers=null,c.push(n),new Dt(function(){r.currentObservers=null,un(c,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?n.error(s):i&&n.complete()},e.prototype.asObservable=function(){var n=new xe;return n.source=this,n},e.create=function(n,r){return new Wr(n,r)},e}(xe),Wr=function(t){je(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:Ur},e}(Yr),dc={now:function(){return Date.now()},delegate:void 0},pc=function(t){je(e,t);function e(n,r){return t.call(this)||this}return e.prototype.schedule=function(n,r){return this},e}(Dt),Hr={setInterval:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,cn([t,e],an(n)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},fc=function(t){je(e,t);function e(n,r){var o=t.call(this,n,r)||this;return o.scheduler=n,o.work=r,o.pending=!1,o}return e.prototype.schedule=function(n,r){var o;if(r===void 0&&(r=0),this.closed)return this;this.state=n;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,r)),this.pending=!0,this.delay=r,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,r),this},e.prototype.requestAsyncId=function(n,r,o){return o===void 0&&(o=0),Hr.setInterval(n.flush.bind(n,this),o)},e.prototype.recycleAsyncId=function(n,r,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return r;r!=null&&Hr.clearInterval(r)},e.prototype.execute=function(n,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(n,r);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(n,r){var o=!1,s;try{this.work(n)}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 n=this,r=n.id,o=n.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,un(s,this),r!=null&&(this.id=this.recycleAsyncId(o,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(pc),Kr=function(){function t(e,n){n===void 0&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(e,n,r){return n===void 0&&(n=0),new this.schedulerActionCtor(this,e).schedule(r,n)},t.now=dc.now,t}(),mc=function(t){je(e,t);function e(n,r){r===void 0&&(r=Kr.now);var o=t.call(this,n,r)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(n){var r=this.actions;if(this._active){r.push(n);return}var o;this._active=!0;do if(o=n.execute(n.state,n.delay))break;while(n=r.shift());if(this._active=!1,o){for(;n=r.shift();)n.unsubscribe();throw o}},e}(Kr),hc=new mc(fc),yc=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function _c(t){return W(t==null?void 0:t.then)}function gc(t){return W(t[$n])}function vc(t){return Symbol.asyncIterator&&W(t==null?void 0:t[Symbol.asyncIterator])}function wc(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function bc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ec=bc();function kc(t){return W(t==null?void 0:t[Ec])}function Cc(t){return Ki(this,arguments,function(){var n,r,o,s;return jr(this,function(i){switch(i.label){case 0:n=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,ct(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,ct(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,ct(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function Sc(t){return W(t==null?void 0:t.getReader)}function Pc(t){if(t instanceof xe)return t;if(t!=null){if(gc(t))return Ac(t);if(yc(t))return Tc(t);if(_c(t))return Ic(t);if(vc(t))return Jr(t);if(kc(t))return xc(t);if(Sc(t))return Rc(t)}throw wc(t)}function Ac(t){return new xe(function(e){var n=t[$n]();if(W(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Tc(t){return new xe(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Ic(t){return new xe(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Gr)})}function xc(t){return new xe(function(e){var n,r;try{for(var o=it(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){n={error:c}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function Jr(t){return new xe(function(e){Nc(t,e).catch(function(n){return e.error(n)})})}function Rc(t){return Jr(Cc(t))}function Nc(t,e){var n,r,o,s;return Hi(this,void 0,void 0,function(){var i,c;return jr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Ji(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(i=r.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]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[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 Oc(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!o)return s}function Mc(t,e){var n=W(t)?t:function(){return t},r=function(o){return o.error(n())};return new xe(r)}var Dc=ln(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Fc(t,e){return new Promise(function(n,r){var o=!1,s;t.subscribe({next:function(i){s=i,o=!0},error:r,complete:function(){o?n(s):r(new Dc)}})})}function Lc(t){return t instanceof Date&&!isNaN(t)}var jc=ln(function(t){return function(n){n===void 0&&(n=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=n}});function Uc(t,e){var n=Lc(t)?{first:t}:typeof t=="number"?{each:t}:t,r=n.first,o=n.each,s=n.with,i=s===void 0?$c:s,c=n.scheduler,l=c===void 0?hc:c,u=n.meta,d=u===void 0?null:u;if(r==null&&o==null)throw new TypeError("No timeout provided.");return ic(function(f,m){var p,_,w=null,A=0,k=function(x){_=Oc(m,l,function(){try{p.unsubscribe(),Pc(i({meta:d,lastValue:w,seen:A})).subscribe(m)}catch(I){m.error(I)}},x)};p=f.subscribe(cc(m,function(x){_==null||_.unsubscribe(),A++,m.next(w=x),o>0&&k(o)},void 0,void 0,function(){_!=null&&_.closed||_==null||_.unsubscribe(),w=null})),!A&&k(r!=null?typeof r=="number"?r:+r-l.now():o)})}function $c(t){throw new jc(t)}class Ft{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,n)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:n},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 n=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),n.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"&&fn(this._current);const n={first:e.timeoutSec*1e3,with:()=>Mc(()=>new Error(e.timeoutErrMsg))};return Fc(this._subject.pipe(Uc(n)))},this._current={status:"initial",isSuccess:!1},this._subject=new Yr}get current(){return this._current}}const Qr=a.enum(["dev","stg","prod"]),Vc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Zc=t=>Vc[t],Vn={},Xr=async t=>{if(Vn[t])return Vn[t];try{const e=await fetch(new URL("/health/environment",t)).then(r=>r.json()),n=Qr.parse(e.environment);return Vn[t]=n,n}catch{return Qr.Values.prod}};function fn(t){throw new Error(`Unhandled case: ${t}`)}const eo=(t,e)=>Object.fromEntries(Object.entries(t).filter(([n])=>!e.includes(n))),z=()=>{if(!(typeof window>"u"))return window},Zn=new Ft,to="op_metrics_queue",zc=3,Gc=3,Bc=1e3,{log__:mn}=D("op-metrics");class qc{constructor(){var e,n;this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{mn("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{mn("Network online, processing metrics queue"),this.processQueue()},this.loadQueueFromStorage(),(e=z())==null||e.addEventListener("offline",this.offlineListener),(n=z())==null||n.addEventListener("online",this.onlineListener)}addEvent(e,n,r){const o={eventName:e,properties:n||{},contextProperties:r||{},nonce:rt(),timestamp:performance.now(),datetime:new Date().toISOString(),attemptCount:0,timeDiffFromPreviousEvent:this.lastEventTimestamp?performance.now()-this.lastEventTimestamp:0};this.lastEventTimestamp=o.timestamp,this.queue.push(o),this.saveQueueToStorage(),this.scheduleBatchProcessing()}loadQueueFromStorage(){var e,n;try{const r=(n=(e=z())==null?void 0:e.localStorage)==null?void 0:n.getItem(to);r&&(this.queue=JSON.parse(r))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=z())==null||e.localStorage.setItem(to,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=z();e&&navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=e.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},Bc))}cancelBatchProcessing(){var e;this.batchTimeout&&((e=z())==null||e.clearTimeout(this.batchTimeout),this.batchTimeout=null),this.processingQueue=!1}processQueue(){!navigator.onLine||this.processingQueue||this.queue.length===0||(this.processingQueue=!0,this.sendBatch().finally(()=>{this.processingQueue=!1,this.queue.length>0&&this.scheduleBatchProcessing()}))}async sendBatch(){if(this.queue.length===0)return;const e=Zn.getValueIfLoadedElse(void 0);if(!e){mn("Metrics context not available, will retry later");return}const n=this.queue.slice(0,Gc);try{const r={events:n.map(c=>({event_name:c.eventName,device_token:e.deviceToken,context_properties:{...e,...c.contextProperties},properties:{nonce:c.nonce,datetime:c.datetime,timestamp:c.timestamp,time_diff_from_previous_event:c.timeDiffFromPreviousEvent,checkout_secure_token:e.checkoutSecureToken,...c.properties}}))},o=Zc(e.environment),s=new URL("/metrics/public/capture",o);(await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).ok?(this.queue=this.queue.slice(n.length),this.saveQueueToStorage()):this.handleFailedBatch(n)}catch(r){mn("Error sending metrics batch:",r),this.handleFailedBatch(n)}}handleFailedBatch(e){e.forEach(r=>{r.attemptCount++});const n=e.filter(r=>r.attemptCount<zc);this.queue=this.queue.slice(e.length),this.queue=[...n,...this.queue],this.saveQueueToStorage()}cleanup(){var e,n;(e=z())==null||e.removeEventListener("offline",this.offlineListener),(n=z())==null||n.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const no=new qc,E=(t,e,n)=>{no.addEvent(t,e,n)},ro=t=>{const e=re(t.reason);E("unhandled_rejection_error",{error_message:e,error_name:t.reason})},oo=t=>{var n,r;const e=re(t.error);E("uncaught_error",{error_message:e,error_name:(n=t.error)==null?void 0:n.name,error_stack:(r=t.error)==null?void 0:r.stack,file_name:t.filename,line_number:t.lineno,column_number:t.colno})},Yc=()=>{var t,e;(t=z())==null||t.addEventListener("error",oo),(e=z())==null||e.addEventListener("unhandledrejection",ro)},Wc=()=>{var t,e;(t=z())==null||t.removeEventListener("error",oo),(e=z())==null||e.removeEventListener("unhandledrejection",ro)};(Ho=z())==null||Ho.addEventListener("beforeunload",()=>{no.processQueue()});class so extends Li{constructor(e){const n=`${e.message}`;super(n),this.response=e}get originalErrorMessage(){return this.response.message}}const J=async(t,e,n,r)=>{r&&E(r,{...e});const o=await t.send(e);if(Kc(o))throw new so(o);if(!Hc(o,n)){const s=n.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",n,"Actual:",o),s.error)}return r&&E(r,{...o}),o},Hc=(t,e)=>e.safeParse(t).success,Kc=t=>mi.safeParse(t).success,Jc=async(t,e)=>await J(t,{type:"get_checkout_preview",payload:e},Pr),G=async t=>await J(t,{type:"get_prefill",payload:{}},Tr),lt=async(t,e)=>await J(t,{type:"v2_start_payment_flow",payload:e},xr,"start_payment_flow"),Qc=async(t,e)=>await J(t,{type:"start_payment_flow_for_cc",payload:e},Ii,"start_payment_flow_for_cc"),Xc=async(t,e)=>{E("start_payment_flow_for_pr",{...e});const n=await J(t,{type:"start_payment_flow_for_pr",payload:e},xr);return E("start_payment_flow_for_pr_result",{...n}),n},se=async(t,e)=>await J(t,{type:"confirm_payment_flow",payload:e},xa,"confirm_payment_flow"),el=async(t,e)=>await J(t,{type:"finalize_setup_payment_method",payload:e},Ir,"finalize_setup_payment_method"),tl=async(t,e)=>await J(t,{type:"check_if_popup_window_verified",payload:e},Ia,"check_if_popup_window_verified"),nl=async(t,e,n)=>{const r=await Jc(t,{secure_token:e,promotion_code:n}),o=new Set(r.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=Oi(r.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},ut=async(t,e,n,r)=>{if(n)return{amountAtom:0,currency:"usd"};{r=r||void 0;const o=await nl(t,e,r);return{amountAtom:o.amountAtom,currency:o.currency}}},rl=async(t,e)=>{if(t.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(t.values()).map(r=>J(r,{type:"tokenize_card",payload:e},Pa)))},ao=async(t,e)=>await J(t,{type:"checkout_card_elements",payload:e},Tn,"checkout_card_elements"),ol=async(t,e)=>await J(t,{type:"setup_payment_method",payload:e},Ir,"setup_checkout"),zn=async(t,e)=>await J(t,{type:"checkout",payload:e},Tn,"perform_checkout"),io=1e3,sl=async(t,e)=>{console.log(e);const r=await br({iframe:t,debug:!0,timeout:io,childOrigin:"*"}).promise,o=await J(r,{type:"ping-3ds-status"},Aa);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Gn=async(t,e)=>await J(t,{type:"prepare_payment_flow",payload:e},Ri,"prepare_payment_flow"),co=async(t,e)=>{try{return(await J(t,{type:"get_standardized_error_code",payload:{message:e}},xi)).error_code}catch(n){return console.error("[cde-client] Error during getStandardizedErrorCode:",re(n)),"PAYMENT_FAILED_GENERIC"}},al=async(t,e)=>await J(t,{type:"set_user_device_token",payload:{device_token:e}},Ni),de=a.enum(["stripe","airwallex","authorize_net"]);de.Enum.stripe;const lo=({scriptId:t,src:e,checkLoadedFn:n})=>{const r=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=t,i.async=!0;const c=document.getElementById(t);n()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{r.abort(),o()},{signal:r.signal}),i.addEventListener("error",()=>{r.abort(),s("Failed to load the script")},{signal:r.signal})})},uo=()=>lo({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),po=(t,e)=>{const n=e.token.paymentMethod.billingContact,r=e.billingContact,o=e.shippingContact,s={...t};if(n||r||o){s[h.EMAIL]=s[h.EMAIL]||(n==null?void 0:n.emailAddress)||(r==null?void 0:r.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[h.COUNTRY]=s[h.COUNTRY]||(n==null?void 0:n.countryCode)||(r==null?void 0:r.countryCode)||(o==null?void 0:o.countryCode)||"US",s[h.ZIP_CODE]=s[h.ZIP_CODE]||(n==null?void 0:n.postalCode)||(r==null?void 0:r.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[h.FIRST_NAME]||(n==null?void 0:n.givenName)||(r==null?void 0:r.givenName)||(o==null?void 0:o.givenName)||"",c=s[h.LAST_NAME]||(n==null?void 0:n.familyName)||(r==null?void 0:r.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[h.FIRST_NAME]=i,s[h.LAST_NAME]=c):(s[h.FIRST_NAME]="_OP_UNKNOWN",s[h.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const il=({total:t,prefill:e})=>{var r;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Ke).toString()};const n=(r=e.line_items)==null?void 0:r[0];if(n)return{paymentDescription:(n==null?void 0:n.description)??"",regularBilling:{amount:t.amount,label:(n==null?void 0:n.description)??"",recurringPaymentIntervalUnit:n==null?void 0:n.billing_interval,recurringPaymentIntervalCount:(n==null?void 0:n.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},cl=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(n==null?void 0:n.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??r??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},fo=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r})=>{const{currencyCode:o,total:s}=cl({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r});let i={countryCode:"US",currencyCode:o,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:s,recurringPaymentRequest:il({total:s,prefill:n})};return t!=null&&t.applePayPaymentRequest&&(typeof t.applePayPaymentRequest=="function"?i={...i,...t.applePayPaymentRequest(i)}:i={...i,...t.applePayPaymentRequest}),i},{log__:td,err__:mo}=D("common"),Lt=t=>{if(t.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${t.payment_methods.length}`);return{payment_method_id:t.payment_methods[0].id}},ae=(t,e)=>{const n=t.find(r=>e.safeParse(r).success);if(!n)throw mo("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(n)},ho=t=>({new_customer_email:t.email,new_customer_address:{zip_code:t.zipCode,country:t.country},new_customer_first_name:t.firstName,new_customer_last_name:t.lastName}),jt=async t=>{const{log__:e}=D(t.logPrefix),n=await G(t.anyCdeConnection),r=Lt(t.confirmResult);if(n.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await el(t.anyCdeConnection,{secure_token:n.token,pm_id:r.payment_method_id})};{if(t.usePayFirstFlow){if(e("Using pay-first flow..."),!t.confirmResult.pay_first_success_response)throw mo("Checkout failed, no pay-first success response:",t.confirmResult),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:t.confirmResult.pay_first_success_response}}e("Doing checkout...");const o={secure_token:n.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},customer_email:t.requiredFormFields[h.EMAIL],customer_zip_code:t.requiredFormFields[h.ZIP_CODE],customer_country:t.requiredFormFields[h.COUNTRY],promotion_code:t.requiredFormFields[h.PROMOTION_CODE],line_items:n.line_items,total_amount_atom:n.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,use_confirmed_pm_id:r.payment_method_id};return{mode:"checkout",result:await zn(t.anyCdeConnection,o)}}},ll="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame,#adyen-container,#adyen-container>*{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",yo=t=>{const e=document.createElement("template");e.innerHTML=`
12
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function un(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var Dt=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,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=it(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&&(n=c.return)&&n.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(W(d))try{d()}catch(w){s=w instanceof Fn?w.errors:[w]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var m=it(f),p=m.next();!p.done;p=m.next()){var _=p.value;try{Vr(_)}catch(w){s=s??[],w instanceof Fn?s=cn(cn([],an(s)),an(w.errors)):s.push(w)}}}catch(w){r={error:w}}finally{try{p&&!p.done&&(o=m.return)&&o.call(m)}finally{if(r)throw r.error}}}if(s)throw new Fn(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Vr(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&un(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&un(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),Ur=Dt.EMPTY;function $r(t){return t instanceof Dt||t&&"closed"in t&&W(t.remove)&&W(t.add)&&W(t.unsubscribe)}function Vr(t){W(t)?t():t.unsubscribe()}var Zr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},zr={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,cn([t,e],an(n)))},clearTimeout:function(t){var e=zr.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Gr(t){zr.setTimeout(function(){throw t})}function Br(){}function dn(t){t()}var Ln=function(t){je(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,$r(n)&&n.add(r)):r.destination=tc,r}return e.create=function(n,r,o){return new Un(n,r,o)},e.prototype.next=function(n){this.isStopped||this._next(n)},e.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Dt),Qi=Function.prototype.bind;function jn(t,e){return Qi.call(t,e)}var Xi=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){pn(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){pn(r)}else pn(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){pn(n)}},t}(),Un=function(t){je(e,t);function e(n,r,o){var s=t.call(this)||this,i;if(W(n)||!n)i={next:n??void 0,error:r??void 0,complete:o??void 0};else{var c;s&&Zr.useDeprecatedNextContext?(c=Object.create(n),c.unsubscribe=function(){return s.unsubscribe()},i={next:n.next&&jn(n.next,c),error:n.error&&jn(n.error,c),complete:n.complete&&jn(n.complete,c)}):i=n}return s.destination=new Xi(i),s}return e}(Ln);function pn(t){Gr(t)}function ec(t){throw t}var tc={closed:!0,next:Br,error:ec,complete:Br},$n=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function nc(t){return t}function rc(t){return t.length===0?nc:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var xe=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,s=sc(e)?e:new Un(e,n,r);return dn(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},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=qr(n),new n(function(o,s){var i=new Un({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[$n]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return rc(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=qr(e),new e(function(r,o){var s;n.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},t.create=function(e){return new t(e)},t}();function qr(t){var e;return(e=t??Zr.Promise)!==null&&e!==void 0?e:Promise}function oc(t){return t&&W(t.next)&&W(t.error)&&W(t.complete)}function sc(t){return t&&t instanceof Ln||oc(t)&&$r(t)}function ac(t){return W(t==null?void 0:t.lift)}function ic(t){return function(e){if(ac(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function cc(t,e,n,r,o){return new lc(t,e,n,r,o)}var lc=function(t){je(e,t);function e(n,r,o,s,i,c){var l=t.call(this,n)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=r?function(u){try{r(u)}catch(d){n.error(d)}}:t.prototype._next,l._error=s?function(u){try{s(u)}catch(d){n.error(d)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){n.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e}(Ln),uc=ln(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Yr=function(t){je(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new Wr(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new uc},e.prototype.next=function(n){var r=this;dn(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=it(r.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(n)}}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(n){var r=this;dn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;dn(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Ur:(this.currentObservers=null,c.push(n),new Dt(function(){r.currentObservers=null,un(c,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?n.error(s):i&&n.complete()},e.prototype.asObservable=function(){var n=new xe;return n.source=this,n},e.create=function(n,r){return new Wr(n,r)},e}(xe),Wr=function(t){je(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:Ur},e}(Yr),dc={now:function(){return Date.now()},delegate:void 0},pc=function(t){je(e,t);function e(n,r){return t.call(this)||this}return e.prototype.schedule=function(n,r){return this},e}(Dt),Hr={setInterval:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,cn([t,e],an(n)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},fc=function(t){je(e,t);function e(n,r){var o=t.call(this,n,r)||this;return o.scheduler=n,o.work=r,o.pending=!1,o}return e.prototype.schedule=function(n,r){var o;if(r===void 0&&(r=0),this.closed)return this;this.state=n;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,r)),this.pending=!0,this.delay=r,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,r),this},e.prototype.requestAsyncId=function(n,r,o){return o===void 0&&(o=0),Hr.setInterval(n.flush.bind(n,this),o)},e.prototype.recycleAsyncId=function(n,r,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return r;r!=null&&Hr.clearInterval(r)},e.prototype.execute=function(n,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(n,r);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(n,r){var o=!1,s;try{this.work(n)}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 n=this,r=n.id,o=n.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,un(s,this),r!=null&&(this.id=this.recycleAsyncId(o,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(pc),Kr=function(){function t(e,n){n===void 0&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(e,n,r){return n===void 0&&(n=0),new this.schedulerActionCtor(this,e).schedule(r,n)},t.now=dc.now,t}(),mc=function(t){je(e,t);function e(n,r){r===void 0&&(r=Kr.now);var o=t.call(this,n,r)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(n){var r=this.actions;if(this._active){r.push(n);return}var o;this._active=!0;do if(o=n.execute(n.state,n.delay))break;while(n=r.shift());if(this._active=!1,o){for(;n=r.shift();)n.unsubscribe();throw o}},e}(Kr),hc=new mc(fc),yc=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function _c(t){return W(t==null?void 0:t.then)}function gc(t){return W(t[$n])}function vc(t){return Symbol.asyncIterator&&W(t==null?void 0:t[Symbol.asyncIterator])}function wc(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function bc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ec=bc();function kc(t){return W(t==null?void 0:t[Ec])}function Cc(t){return Ki(this,arguments,function(){var n,r,o,s;return jr(this,function(i){switch(i.label){case 0:n=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,ct(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,ct(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,ct(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function Sc(t){return W(t==null?void 0:t.getReader)}function Pc(t){if(t instanceof xe)return t;if(t!=null){if(gc(t))return Ac(t);if(yc(t))return Tc(t);if(_c(t))return Ic(t);if(vc(t))return Jr(t);if(kc(t))return xc(t);if(Sc(t))return Rc(t)}throw wc(t)}function Ac(t){return new xe(function(e){var n=t[$n]();if(W(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Tc(t){return new xe(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Ic(t){return new xe(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Gr)})}function xc(t){return new xe(function(e){var n,r;try{for(var o=it(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){n={error:c}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function Jr(t){return new xe(function(e){Nc(t,e).catch(function(n){return e.error(n)})})}function Rc(t){return Jr(Cc(t))}function Nc(t,e){var n,r,o,s;return Hi(this,void 0,void 0,function(){var i,c;return jr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Ji(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(i=r.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]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[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 Oc(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!o)return s}function Mc(t,e){var n=W(t)?t:function(){return t},r=function(o){return o.error(n())};return new xe(r)}var Dc=ln(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Fc(t,e){return new Promise(function(n,r){var o=!1,s;t.subscribe({next:function(i){s=i,o=!0},error:r,complete:function(){o?n(s):r(new Dc)}})})}function Lc(t){return t instanceof Date&&!isNaN(t)}var jc=ln(function(t){return function(n){n===void 0&&(n=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=n}});function Uc(t,e){var n=Lc(t)?{first:t}:typeof t=="number"?{each:t}:t,r=n.first,o=n.each,s=n.with,i=s===void 0?$c:s,c=n.scheduler,l=c===void 0?hc:c,u=n.meta,d=u===void 0?null:u;if(r==null&&o==null)throw new TypeError("No timeout provided.");return ic(function(f,m){var p,_,w=null,A=0,k=function(x){_=Oc(m,l,function(){try{p.unsubscribe(),Pc(i({meta:d,lastValue:w,seen:A})).subscribe(m)}catch(I){m.error(I)}},x)};p=f.subscribe(cc(m,function(x){_==null||_.unsubscribe(),A++,m.next(w=x),o>0&&k(o)},void 0,void 0,function(){_!=null&&_.closed||_==null||_.unsubscribe(),w=null})),!A&&k(r!=null?typeof r=="number"?r:+r-l.now():o)})}function $c(t){throw new jc(t)}class Ft{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,n)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:n},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 n=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),n.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"&&fn(this._current);const n={first:e.timeoutSec*1e3,with:()=>Mc(()=>new Error(e.timeoutErrMsg))};return Fc(this._subject.pipe(Uc(n)))},this._current={status:"initial",isSuccess:!1},this._subject=new Yr}get current(){return this._current}}const Qr=a.enum(["dev","stg","prod"]),Vc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Zc=t=>Vc[t],Vn={},Xr=async t=>{if(Vn[t])return Vn[t];try{const e=await fetch(new URL("/health/environment",t)).then(r=>r.json()),n=Qr.parse(e.environment);return Vn[t]=n,n}catch{return Qr.Values.prod}};function fn(t){throw new Error(`Unhandled case: ${t}`)}const eo=(t,e)=>Object.fromEntries(Object.entries(t).filter(([n])=>!e.includes(n))),z=()=>{if(!(typeof window>"u"))return window},Zn=new Ft,to="op_metrics_queue",zc=3,Gc=3,Bc=1e3,{log__:mn}=D("op-metrics");class qc{constructor(){var e,n;this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{mn("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{mn("Network online, processing metrics queue"),this.processQueue()},this.loadQueueFromStorage(),(e=z())==null||e.addEventListener("offline",this.offlineListener),(n=z())==null||n.addEventListener("online",this.onlineListener)}addEvent(e,n,r){const o={eventName:e,properties:n||{},contextProperties:r||{},nonce:rt(),timestamp:performance.now(),datetime:new Date().toISOString(),attemptCount:0,timeDiffFromPreviousEvent:this.lastEventTimestamp?performance.now()-this.lastEventTimestamp:0};this.lastEventTimestamp=o.timestamp,this.queue.push(o),this.saveQueueToStorage(),this.scheduleBatchProcessing()}loadQueueFromStorage(){var e,n;try{const r=(n=(e=z())==null?void 0:e.localStorage)==null?void 0:n.getItem(to);r&&(this.queue=JSON.parse(r))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=z())==null||e.localStorage.setItem(to,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=z();e&&navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=e.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},Bc))}cancelBatchProcessing(){var e;this.batchTimeout&&((e=z())==null||e.clearTimeout(this.batchTimeout),this.batchTimeout=null),this.processingQueue=!1}processQueue(){!navigator.onLine||this.processingQueue||this.queue.length===0||(this.processingQueue=!0,this.sendBatch().finally(()=>{this.processingQueue=!1,this.queue.length>0&&this.scheduleBatchProcessing()}))}async sendBatch(){if(this.queue.length===0)return;const e=Zn.getValueIfLoadedElse(void 0);if(!e){mn("Metrics context not available, will retry later");return}const n=this.queue.slice(0,Gc);try{const r={events:n.map(c=>({event_name:c.eventName,device_token:e.deviceToken,context_properties:{...e,...c.contextProperties},properties:{nonce:c.nonce,datetime:c.datetime,timestamp:c.timestamp,time_diff_from_previous_event:c.timeDiffFromPreviousEvent,checkout_secure_token:e.checkoutSecureToken,...c.properties}}))},o=Zc(e.environment),s=new URL("/metrics/public/capture",o);(await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).ok?(this.queue=this.queue.slice(n.length),this.saveQueueToStorage()):this.handleFailedBatch(n)}catch(r){mn("Error sending metrics batch:",r),this.handleFailedBatch(n)}}handleFailedBatch(e){e.forEach(r=>{r.attemptCount++});const n=e.filter(r=>r.attemptCount<zc);this.queue=this.queue.slice(e.length),this.queue=[...n,...this.queue],this.saveQueueToStorage()}cleanup(){var e,n;(e=z())==null||e.removeEventListener("offline",this.offlineListener),(n=z())==null||n.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const no=new qc,E=(t,e,n)=>{no.addEvent(t,e,n)},ro=t=>{const e=re(t.reason);E("unhandled_rejection_error",{error_message:e,error_name:t.reason})},oo=t=>{var n,r;const e=re(t.error);E("uncaught_error",{error_message:e,error_name:(n=t.error)==null?void 0:n.name,error_stack:(r=t.error)==null?void 0:r.stack,file_name:t.filename,line_number:t.lineno,column_number:t.colno})},Yc=()=>{var t,e;(t=z())==null||t.addEventListener("error",oo),(e=z())==null||e.addEventListener("unhandledrejection",ro)},Wc=()=>{var t,e;(t=z())==null||t.removeEventListener("error",oo),(e=z())==null||e.removeEventListener("unhandledrejection",ro)};(Ho=z())==null||Ho.addEventListener("beforeunload",()=>{no.processQueue()});class so extends _i{constructor(e){const n=`${e.message}`;super(n),this.response=e}get originalErrorMessage(){return this.response.message}}const J=async(t,e,n,r)=>{r&&E(r,{...e});const o=await t.send(e);if(Kc(o))throw E("cde_response_error",{...o}),new so(o);if(!Hc(o,n)){const s=n.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",n,"Actual:",o),s.error)}return r&&E(r,{...o}),o},Hc=(t,e)=>e.safeParse(t).success,Kc=t=>gi.safeParse(t).success,Jc=async(t,e)=>await J(t,{type:"get_checkout_preview",payload:e},Pr),G=async t=>await J(t,{type:"get_prefill",payload:{}},Tr),lt=async(t,e)=>await J(t,{type:"v2_start_payment_flow",payload:e},xr,"start_payment_flow"),Qc=async(t,e)=>await J(t,{type:"start_payment_flow_for_cc",payload:e},Oi,"start_payment_flow_for_cc"),Xc=async(t,e)=>{E("start_payment_flow_for_pr",{...e});const n=await J(t,{type:"start_payment_flow_for_pr",payload:e},xr);return E("start_payment_flow_for_pr_result",{...n}),n},se=async(t,e)=>await J(t,{type:"confirm_payment_flow",payload:e},xa,"confirm_payment_flow"),el=async(t,e)=>await J(t,{type:"finalize_setup_payment_method",payload:e},Ir,"finalize_setup_payment_method"),tl=async(t,e)=>await J(t,{type:"check_if_popup_window_verified",payload:e},Ia,"check_if_popup_window_verified"),nl=async(t,e,n)=>{const r=await Jc(t,{secure_token:e,promotion_code:n}),o=new Set(r.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=Li(r.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},ut=async(t,e,n,r)=>{if(n)return{amountAtom:0,currency:"usd"};{r=r||void 0;const o=await nl(t,e,r);return{amountAtom:o.amountAtom,currency:o.currency}}},rl=async(t,e)=>{if(t.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(t.values()).map(r=>J(r,{type:"tokenize_card",payload:e},Pa)))},ao=async(t,e)=>await J(t,{type:"checkout_card_elements",payload:e},Tn,"checkout_card_elements"),ol=async(t,e)=>await J(t,{type:"setup_payment_method",payload:e},Ir,"setup_checkout"),zn=async(t,e)=>await J(t,{type:"checkout",payload:e},Tn,"perform_checkout"),io=1e3,sl=async(t,e)=>{console.log(e);const r=await br({iframe:t,debug:!0,timeout:io,childOrigin:"*"}).promise,o=await J(r,{type:"ping-3ds-status"},Aa);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Gn=async(t,e)=>await J(t,{type:"prepare_payment_flow",payload:e},Di,"prepare_payment_flow"),co=async(t,e)=>{try{return(await J(t,{type:"get_standardized_error_code",payload:{message:e}},Mi)).error_code}catch(n){return console.error("[cde-client] Error during getStandardizedErrorCode:",re(n)),"PAYMENT_FAILED_GENERIC"}},al=async(t,e)=>await J(t,{type:"set_user_device_token",payload:{device_token:e}},Fi),de=a.enum(["stripe","airwallex","authorize_net"]);de.Enum.stripe;const lo=({scriptId:t,src:e,checkLoadedFn:n})=>{const r=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=t,i.async=!0;const c=document.getElementById(t);n()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{r.abort(),o()},{signal:r.signal}),i.addEventListener("error",()=>{r.abort(),s("Failed to load the script")},{signal:r.signal})})},uo=()=>lo({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),po=(t,e)=>{const n=e.token.paymentMethod.billingContact,r=e.billingContact,o=e.shippingContact,s={...t};if(n||r||o){s[h.EMAIL]=s[h.EMAIL]||(n==null?void 0:n.emailAddress)||(r==null?void 0:r.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[h.COUNTRY]=s[h.COUNTRY]||(n==null?void 0:n.countryCode)||(r==null?void 0:r.countryCode)||(o==null?void 0:o.countryCode)||"US",s[h.ZIP_CODE]=s[h.ZIP_CODE]||(n==null?void 0:n.postalCode)||(r==null?void 0:r.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[h.FIRST_NAME]||(n==null?void 0:n.givenName)||(r==null?void 0:r.givenName)||(o==null?void 0:o.givenName)||"",c=s[h.LAST_NAME]||(n==null?void 0:n.familyName)||(r==null?void 0:r.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[h.FIRST_NAME]=i,s[h.LAST_NAME]=c):(s[h.FIRST_NAME]="_OP_UNKNOWN",s[h.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const il=({total:t,prefill:e})=>{var r;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Ke).toString()};const n=(r=e.line_items)==null?void 0:r[0];if(n)return{paymentDescription:(n==null?void 0:n.description)??"",regularBilling:{amount:t.amount,label:(n==null?void 0:n.description)??"",recurringPaymentIntervalUnit:n==null?void 0:n.billing_interval,recurringPaymentIntervalCount:(n==null?void 0:n.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},cl=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(n==null?void 0:n.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??r??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},fo=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r})=>{const{currencyCode:o,total:s}=cl({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r});let i={countryCode:"US",currencyCode:o,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:s,recurringPaymentRequest:il({total:s,prefill:n})};return t!=null&&t.applePayPaymentRequest&&(typeof t.applePayPaymentRequest=="function"?i={...i,...t.applePayPaymentRequest(i)}:i={...i,...t.applePayPaymentRequest}),i},{log__:td,err__:mo}=D("common"),Lt=t=>{if(t.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${t.payment_methods.length}`);return{payment_method_id:t.payment_methods[0].id}},ae=(t,e)=>{const n=t.find(r=>e.safeParse(r).success);if(!n)throw mo("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(n)},ho=t=>({new_customer_email:t.email,new_customer_address:{zip_code:t.zipCode,country:t.country},new_customer_first_name:t.firstName,new_customer_last_name:t.lastName}),jt=async t=>{const{log__:e}=D(t.logPrefix),n=await G(t.anyCdeConnection),r=Lt(t.confirmResult);if(n.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await el(t.anyCdeConnection,{secure_token:n.token,pm_id:r.payment_method_id})};{if(t.usePayFirstFlow){if(e("Using pay-first flow..."),!t.confirmResult.pay_first_success_response)throw mo("Checkout failed, no pay-first success response:",t.confirmResult),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:t.confirmResult.pay_first_success_response}}e("Doing checkout...");const o={secure_token:n.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},customer_email:t.requiredFormFields[h.EMAIL],customer_zip_code:t.requiredFormFields[h.ZIP_CODE],customer_country:t.requiredFormFields[h.COUNTRY],promotion_code:t.requiredFormFields[h.PROMOTION_CODE],line_items:n.line_items,total_amount_atom:n.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,use_confirmed_pm_id:r.payment_method_id};return{mode:"checkout",result:await zn(t.anyCdeConnection,o)}}},ll="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame,#adyen-container,#adyen-container>*{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",yo=t=>{const e=document.createElement("template");e.innerHTML=`
13
13
  <style>
14
14
  ${ll}
15
15
  </style>
@@ -22,7 +22,7 @@ ${t.message}`),t.message)}else return An(t.message);if(typeof t=="object")try{re
22
22
  `;const n=document.createElement("div"),r=n.attachShadow({mode:"open"});r.appendChild(e.content.cloneNode(!0));const o=r.querySelector("#three-ds-iframe"),s=r.querySelector(".cancel-button");return document.body.appendChild(n),{host:n,iframe:o,cancelButton:s}};function ul(t,e,n){const r=async()=>{try{const s=await sl(t,n);s&&(clearInterval(o),e(s))}catch{}};r();const o=setInterval(r,io);return o}function dl({elements:t,pollingInterval:e,resolve:n}){const r=()=>{clearInterval(e),t.host.remove(),n({status:Z.CANCELLED})};return t.cancelButton.addEventListener("click",r),()=>{t.cancelButton.removeEventListener("click",r)}}async function hn(t){const{url:e,baseUrl:n}=t,r=yo(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{r.host.remove()},1e3),o(l),c==null||c()},i=ul(r.iframe,s,new URL(n).origin),c=dl({elements:r,pollingInterval:i,resolve:o})})}const _o=async t=>{const e=await hn(t);if(e.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===Z.FAILURE)throw new Error("3DS verification failed");return e.status!==Z.SUCCESS&&fn(e.status),{href:e.href}},pl=(t,e)=>{const n=window.open(e,"_blank");if(!n)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return n},go=async(t,e,n,r)=>{const{err__:o}=D("popup-verify");return new Promise((s,i)=>{const c=pl(t,r),l=setInterval(async()=>{try{const u=await tl(e,n);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(re(u)),clearInterval(l),i(re(u))}},1e3)})},{log__:fl,err__:Bn}=D("airwallex-cc"),ml=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),hl=t=>{const e=ml.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Bn(r),new Error(n)}return e.data},yl=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,_l=t=>{try{const e=new URL(t??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return fl(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const n="Error verifying Airwallex 3DS verification result.";throw Bn(n,`Resulting URL: ${t}.
23
23
  Error: ${re(e)}`),new Error(n)}},gl=async(t,e)=>{const n=hl(e),r=await _o({url:n["op-airwallex-3ds-url"],baseUrl:t}),o=_l(r.href??""),s=n["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Bn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:n["op-airwallex-consent-id"]}}},vo=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()})}),wo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:bo,err__:Eo}=D("common-cc"),Re=(t,e,n)=>{if(n){bo(`Received default field values: ${JSON.stringify(n)}`);for(const[o,s]of Object.entries(n))t[o]||(t[o]=s)}const r=Rt.safeParse(t);if(!r.success){const o=r.error.format(),s=mr(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Eo("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},vl=(t,e)=>{for(const n of t)if(n.success===!1)throw n.errors.forEach(r=>{const o=pr.safeParse(r.elementType);if(!o.success)Eo(`Unknown field name in onValidationError: ${r.elementType}. Error object:`,r);else{const s=o.data;e(s,r.errors)}}),bo(`Error tokenizing card: got validation errors: ${JSON.stringify(n.errors)}`),new Error("Got validation errors while tokenizing card")},{log__:yn}=D("awx-apple-pay");async function wl(t,e){try{const r=(await Gn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function bl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");yn("3DS Required, starting verification...",t);const{status:n}=await hn({url:t.redirect_url,baseUrl:e.baseUrl});if(yn(`╰ 3DS verification completed [Status: ${n}]`),n===Z.CANCELLED)throw new Error("3DS verification cancelled");if(n===Z.FAILURE)throw new Error("3DS verification failed");const r=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return yn("[2nd] Confirm payment flow response",r),r}async function El(t,e){var n,r,o,s,i;try{const c=t.payment,l=po(e.nonCdeFormInputs,c),u=Re(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);E("billing_details_received",{...u});const m=(await lt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[h.EMAIL],new_customer_first_name:u[h.FIRST_NAME],new_customer_last_name:u[h.LAST_NAME],new_customer_address:{zip_code:u[h.ZIP_CODE],country:u[h.COUNTRY]}})).required_user_actions[0].consent_id;if(!m)throw new Error("No consent ID received from payment flow");let p=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:m,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});yn("[1st] Confirm payment flow response",p);let _=(r=(n=p.payment_methods)==null?void 0:n[0])==null?void 0:r.id;const w=(o=p.required_user_actions)==null?void 0:o.find(k=>k.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(p=await bl(w,e),_=(i=(s=p.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!_)throw new Error("No PM ID found");const A={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(A),jt({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:p,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Ut,err__:ko}=D("awx-apple-pay"),kl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:de.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,vo);if(!r)return n;if(Ut("Loading Apple Pay script"),await uo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Ut("Apple Pay is not available on this device/browser"),n;if(Ut("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Ut("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await ut(i,c.token,l,void 0),d=async f=>{try{await U.airwallexApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(m){ko("Apple Pay payment error",m),e.get.onCheckoutError((m==null?void 0:m.message)??"Unknown error")}};return{processor:de.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Cl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var _;const s=ae(t.checkoutPaymentMethods,vo),{overridePaymentRequest:i,initialPreview:c}=r,l=t.anyCdeConnection,u=await G(l),d=u.mode==="setup",f=fo({overridePaymentRequest:i,initialPreview:c,prefill:{...u},defaultLabel:(_=s==null?void 0:s.metadata)==null?void 0:_.processor_account_name}),m=new ApplePaySession(3,f),p={session:m,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:eo(u,["brand"]),overridePaymentRequest:i}),new Promise((w,A)=>{const k=()=>{Ut("Payment cancelled by user"),A(new Error("Payment cancelled by user"))};m.oncancel=k,m.onvalidatemerchant=async x=>{try{await wl(x,p)}catch(I){A(I)}},m.onpaymentmethodselected=()=>{const x={newTotal:{...f.total}};m.completePaymentMethodSelection(x)},m.onpaymentauthorized=async x=>{E("apple_pay_payment_authorized");try{const I=await El(x,p);w(I)}catch(I){A(I)}},m.begin()}).catch(w=>{throw ko("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),_n=({gateway:t,gatewayMerchantId:e,merchantName:n,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var f,m;const c=((f=s==null?void 0:s.amount)==null?void 0:f.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((m=s==null?void 0:s.amount)==null?void 0:m.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:n},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?typeof s.googlePayPaymentRequest=="function"?{...d,...s.googlePayPaymentRequest(d)}:{...d,...s.googlePayPaymentRequest}:d},Co=()=>lo({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let qn=null;const So=async t=>await Xr(t)==="prod"?"PRODUCTION":"TEST",gn=async(t,e)=>{const n=await So(t);return qn===null&&(qn=new window.google.payments.api.PaymentsClient({environment:n,merchantInfo:e.merchantInfo})),qn},Sl=t=>{const e=t.required_user_actions.find(n=>n.type==="airwallex_payment_consent");return e?fr.parse(e):null},Po=(t,e)=>{var o,s,i,c;const n={...t},r=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(r){const[l,...u]=((c=(i=r.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;n[h.EMAIL]=n[h.EMAIL]||e.email||"op_unfilled@getopenpay.com",n[h.COUNTRY]=n[h.COUNTRY]||r.countryCode||"US",n[h.ADDRESS]=n[h.ADDRESS]||r.address1||"",n[h.CITY]=n[h.CITY]||r.locality||"",n[h.ZIP_CODE]=n[h.ZIP_CODE]||r.postalCode||"00000",n[h.STATE]=n[h.STATE]||r.administrativeArea||"";const f=n[h.FIRST_NAME]||l||"",m=n[h.LAST_NAME]||d||"";f||m?(n[h.FIRST_NAME]=f,n[h.LAST_NAME]=m):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]="")}return n},{log__:pe,err__:dt}=D("awx-google-pay"),Pl=Ge(async({context:t,formCallbacks:e})=>{var f,m;const n={processor:de.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,wo);if(!r)return n;pe("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return dt("No gateway merchant ID found in processor account"),n;if(pe("Loading Google Pay script"),await Co(),!((m=(f=window.google)==null?void 0:f.payments)!=null&&m.api))return dt("Google Pay SDK not loaded properly"),n;if(await So(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return dt("Google Pay merchant ID is required for production environment"),n;pe("Google Pay SDK loaded",window.google.payments);try{const p=_n({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),_=await gn(t.baseUrl,p),{result:w}=await _.isReadyToPay(p);if(!w)return pe("Google Pay is not available for this user"),n}catch(p){return dt("Error checking Google Pay availability",p),n}const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await ut(i,c.token,l,void 0),d=async p=>{try{U.airwallexGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...p,initialPreview:u}})}catch(_){dt("Google Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:de.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Al=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var p,_,w,A,k,x,I;pe("Starting Google Pay flow...");const s=ae(t.checkoutPaymentMethods,wo),{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=_n({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,f=await G(d);E("google_pay_flow_started",{processor_name:s.processor_name,prefill:eo(f,["brand"]),overridePaymentRequest:c});const m=await gn(t.baseUrl,u);try{const L=await m.loadPaymentData(u);pe("Google Pay Payment data",L);const B=Po(n,L),$=Re(B,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);E("billing_details_received",{...$});const Pe=(_=(p=L.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!Pe)throw new Error("No payment token received from Google Pay");const Hu=await lt(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:$[h.EMAIL],new_customer_first_name:$[h.FIRST_NAME],new_customer_last_name:$[h.LAST_NAME],new_customer_address:{zip_code:$[h.ZIP_CODE],country:$[h.COUNTRY]}}),wn=Sl(Hu);pe("Start flow next actions",wn);let We=await se(d,{secure_token:f.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:wn==null?void 0:wn.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Pe}}}});pe("[1st] Confirm payment flow response",We);let Kn=(A=(w=We.payment_methods)==null?void 0:w[0])==null?void 0:A.id;const He=(k=We.required_user_actions)==null?void 0:k.find(Gt=>Gt.type==="airwallex_payment_consent");if(He&&He.redirect_url){pe("3DS Required, starting verification...",He);const{status:Gt}=await hn({url:He.redirect_url,baseUrl:t.baseUrl});if(pe(`╰ 3DS verification completed [Status: ${Gt}]`),Gt===Z.CANCELLED)throw new Error("3DS verification cancelled");if(Gt===Z.FAILURE)throw new Error("3DS verification failed")}if(He&&!Kn&&(We=await se(d,{secure_token:f.token,their_pm_id:He.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:He.consent_id}}),pe("[2nd] Confirm payment flow response",We),Kn=(I=(x=We.payment_methods)==null?void 0:x[0])==null?void 0:I.id),!Kn)throw new Error("No PM ID found");return jt({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:$,confirmResult:We,usePayFirstFlow:!1})}catch(L){throw dt("Google Pay payment error",L),E("google_pay_payment_error",{error:L}),new Error((L==null?void 0:L.message)??"Unknown error")}}),Ao=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()})});async function Tl(t,e){try{const r=(await Gn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),E("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function Il(t,e){var n,r;try{const o=t.payment,s=po(e.nonCdeFormInputs,o),i=Re(s,e.formCallbacks.get.onValidationError);E("billing_details_received",{...i}),await lt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[h.EMAIL],new_customer_first_name:i[h.FIRST_NAME],new_customer_last_name:i[h.LAST_NAME],new_customer_address:{zip_code:i[h.ZIP_CODE],country:i[h.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(!((r=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),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{log__:vn,err__:Io}=D("authnet-applepay"),xl=Ge(async({context:t,formCallbacks:e})=>{const n={processor:de.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,Ao);if(!r)return n;if(vn("Loading Apple Pay script"),await uo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return vn("Apple Pay is not available on this device/browser"),n;if(!await ApplePaySession.canMakePayments())return vn("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await G(i),l=c.mode==="setup",u=await ut(i,c.token,l,void 0),d=async f=>{try{await U.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{...f,initialPreview:u},initResult:void 0})}catch(m){Io("Apple Pay payment error",m),E("apple_pay_payment_error",{error:m}),e.get.onCheckoutError((m==null?void 0:m.message)??"Unknown error")}};return{processor:de.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Rl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var _;const{initialPreview:s,overridePaymentRequest:i}=r,c=ae(t.checkoutPaymentMethods,Ao),l=t.anyCdeConnection,u=await G(l),d=u.mode==="setup",f=fo({overridePaymentRequest:i,initialPreview:s,prefill:u,defaultLabel:(_=c==null?void 0:c.metadata)==null?void 0:_.processor_account_name});E("apple_pay_flow_started",{processor_name:e.processor_name,prefill:u,overridePaymentRequest:i});const m=new ApplePaySession(3,f),p={session:m,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:e.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((w,A)=>{m.oncancel=()=>{vn("Payment cancelled by user"),A(new Error("Payment cancelled by user"))},m.onvalidatemerchant=async k=>{try{await Tl(k,p)}catch(x){A(x)}},m.onpaymentmethodselected=()=>{const k={newTotal:f.total};m.completePaymentMethodSelection(k)},m.onpaymentauthorized=async k=>{E("apple_pay_payment_authorized");try{const x=await Il(k,p);w(x)}catch(x){A(x)}},m.begin()}).catch(w=>{throw Io("Apple Pay payment error",w),E("apple_pay_payment_error",{error:w}),w})}),{log__:Be,err__:$t}=D("authnet-googlepay"),Nl=Ge(async({context:t,formCallbacks:e})=>{var d,f;Be("Initializing Authnet GooglePay flow");const n={processor:de.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ae(t.checkoutPaymentMethods,To);if(!r)return n;Be("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return $t("No gateway merchant ID found in processor account"),n;if(Be("Loading Google Pay script"),await Co(),!((f=(d=window.google)==null?void 0:d.payments)!=null&&f.api))return $t("Google Pay SDK not loaded properly"),n;Be("Google Pay SDK loaded",window.google.payments);try{const m=_n({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),p=await gn(t.baseUrl,m),{result:_}=await p.isReadyToPay(m);if(!_)return Be("Google Pay is not available for this user"),n}catch(m){return $t("Error checking Google Pay availability",m),n}const s=t.anyCdeConnection,i=await G(s),c=i.mode==="setup",l=await ut(s,i.token,c,void 0),u=async m=>{try{U.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...m,initialPreview:l}})}catch(p){$t("Google Pay payment error",p),E("google_pay_payment_error",{error:p}),e.get.onCheckoutError((p==null?void 0:p.message)??"Unknown error")}};return{processor:de.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Ol=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var p,_,w,A;const{initialPreview:s,overridePaymentRequest:i}=o,l=ae(t.checkoutPaymentMethods,To).metadata,u=_n({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,f=await G(d);E("google_pay_flow_started",{processor_name:n.processor_name,prefill:f,overridePaymentRequest:i});const m=await gn(t.baseUrl,u);try{const k=await m.loadPaymentData(u);Be("Google Pay Payment data",k);const x=Po(e,k),I=Re(x,r.get.onValidationError);E("billing_details_received",{...I});const L=(_=(p=k.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!L)throw new Error("No payment token received from Google Pay");const B=await lt(d,{payment_provider:n.provider,checkout_payment_method:n,new_customer_email:I[h.EMAIL],new_customer_first_name:I[h.FIRST_NAME],new_customer_last_name:I[h.LAST_NAME],new_customer_address:{zip_code:I[h.ZIP_CODE],country:I[h.COUNTRY]}});Be("Start payment flow response",B);const $=await se(d,{secure_token:f.token,processor_specific_metadata:{payment_provider:n.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(L)}}});if(!((A=(w=$.payment_methods)==null?void 0:w[0])==null?void 0:A.id))throw new Error("No PM ID found");return jt({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:n,requiredFormFields:I,confirmResult:$,usePayFirstFlow:!1})}catch(k){throw $t("Google Pay payment error",k),E("google_pay_payment_error",{error:k}),new Error((k==null?void 0:k.message)??"Unknown error")}}),{log__:Ml,err__:xo}=D("pockyt-cc"),Dl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),Fl=t=>{const e=Dl.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw xo(r),new Error(n)}return e.data},Ro=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return Ml(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const n="Error verifying 3DS verification result.";throw xo(n,`Resulting URL: ${t}.
24
24
  Error: ${re(e)}`),new Error(n)}},Yn=(t,e)=>new URL(t).searchParams.get(e),Ll=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,jl=async(t,e)=>{const n=Fl(e),r=await _o({url:n["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:Ro(r.href??""),transaction_no:n["op-pockyt-txn-no"],reference_no:n["op-pockyt-ref-no"]}}},Ul=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),$l=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:pt,err__:Vt}=D("adyen-cc"),Vl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":Ul,"op-adyen-action":a.string()}),No="Unable to process your credit card. Please contact support for assistance.",Zl=t=>{const e=Vl.safeParse(t);if(!e.success)throw Vt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(No);return e.data},zl=t=>JSON.parse(t),Oo=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Gl=async()=>{pt("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)Oo()||await tn(500);if(!Oo())throw Vt("Adyen SDK not loaded properly"),new Error(No);return pt("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},Bl=t=>{const{headers:e,locale:n,countryCode:r,component:o,host:s,cancelButton:i}=t,c=zl(e["op-adyen-action"]);return pt(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{pt("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",m),s.remove()},d=_=>{Vt("Authentication failed. Result:",_),l({status:Z.FAILURE,cleanup:u})},f=_=>{Vt("Adyen error:",_),l({status:Z.FAILURE,cleanup:u})},m=()=>{l({status:Z.CANCELLED,cleanup:u})};i.addEventListener("click",m);const p=(_,w,A)=>{s.remove(),l({status:Z.SUCCESS,additionalDetails:_,cleanup:u})};Gl().then(_=>_({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:n,countryCode:r,onAdditionalDetails:p,onPaymentFailed:d,onError:f})).then(_=>{_.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},ql=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,n=t??e,r=$l.safeParse(n);return r.success?(pt(`Resolved locale: ${r.data}`),r.data):(Vt(`Resolved invalid locale: ${n}. Defaulting to en-US.`),"en-US")},Yl=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Wl=async(t,e,n)=>{const r=Zl(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=yo("http://example.com");i.replaceWith(o);const l=await Bl({headers:r,locale:ql(n),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===Z.FAILURE)throw new Error("3DS verification failed");if(l.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===Z.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return pt("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else fn(l.status)},{log__:F,err__:Mo}=D("common-cc"),{log__:Do}=D("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Hl=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var u;F("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await G(s);E("common_cc_flow_started",{...e,prefill:i}),F(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Re(n,r.get.onValidationError);E("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin},payment_route_id:o.paymentRouteId};try{F(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await rl(o.currentCdeConnections,{session_id:t.elementsSessionId});if(vl(d,r.get.onValidationError),i.mode==="setup"){F(`├ Setting up payment method in CDE [Token: ${i.token}]`);const f=await ol(s,l);return F(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{F(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const f=await ao(s,l);return F("╰ Checkout completed successfully."),{mode:"checkout",result:f}}}catch(d){if(d instanceof so&&d.originalErrorMessage.includes("3DS_REQUIRED")){F("├ Card requires 3DS, starting non-legacy payment flow"),F("Received 3DS error response headers:",d.response.headers),E("3ds_required",{...e,...d.response.headers});const f=Ll(d.response.headers);if(f){F("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const k=await jl(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=k}if(yl(d.response.headers)){F("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const k=await gl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=k}if(Yl(d.response.headers)){F("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const k=await Wl(n[h.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=k}const _=await Qc(s,l);F("├ Payment flow result:",_);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";f?F("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(F("├ Using stripe 3DS flow"),await eu(_)):(F("├ Using common 3DS flow"),await Xl(_,t.baseUrl));const A=_.cc_pm_id;if(i.mode==="setup"){F(`├ Confirming payment flow [cc_pm_id: ${A}]`);const k=await se(s,{secure_token:i.token,existing_cc_pm_id:A});F("├ Confirm payment flow result received Result:",k);const x=Lt(k);return F(`╰ Setup completed successfully [PM ID: ${x.payment_method_id}]`),{mode:"setup",result:x}}else{F(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const k=await ao(s,{...l,existing_cc_pm_id:A,do_not_use_legacy_cc_flow:w});return F("╰ Checkout completed successfully."),{mode:"checkout",result:k}}}throw Mo("╰ Error checking out card info in CDE"),Mo(d),d}}),Kl=t=>{const e=t.required_user_actions.find(n=>n.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Ra.parse(e)},Jl=["airwallex_payment_consent","adyen"],Ql=t=>{const e=t.required_user_actions.find(n=>Jl.includes(n.type));if(!e)throw new Error("No common 3DS action found");return Ta.parse(e)},Xl=async(t,e)=>{const n=Ql(t);if(n.redirect_url==="3DS_COMPLETE"){F("├ 3DS flow completed successfully"),E("3ds_complete");return}F(`├ Using common 3DS flow [URL: ${n.redirect_url}]`),E("3ds_redirect",{...n});const{status:r}=await hn({url:n.redirect_url,baseUrl:e});if(F(`╰ 3DS verification completed [Status: ${r}]`),r===Z.CANCELLED)throw E("3ds_cancelled"),new Error("3DS verification cancelled");if(r===Z.FAILURE)throw E("3ds_failure"),new Error("3DS verification failed")},eu=async t=>{const e=Kl(t);E("3ds_stripe_redirect",{...e}),Do(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await ja(e),E("3ds_stripe_complete"),Do("╰ Stripe 3DS flow completed successfully")},tu=1,nu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:te,err__:Fo}=D("loop-crypto"),ru=a.object({loopFirstName:V,loopLastName:V,loopEmail:V,[h.PROMOTION_CODE]:O}),ou=a.object({loopFirstName:O,loopLastName:O,loopEmail:O,[h.PROMOTION_CODE]:O}),Lo=(t,e,n,r)=>{const o=n.safeParse(t);if(!o.success){const s=o.error.format(),i=mr(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Fo("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},su=Ge(async({context:t})=>{te("Checking if there are any CPMs for Loop Crypto...");const e=ae(t.checkoutPaymentMethods,nu);te(`checkoutPaymentMethod: ${JSON.stringify(e)}`),te("Starting Loop Crypto flow...");const n=await G(t.anyCdeConnection),r=await Gn(t.anyCdeConnection,{checkout_payment_method:e});if(n.mode!=="setup"&&!e.metadata.supported_currencies.includes(n.currency))throw Error(`Currency ${n.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!r||!r.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=r.next_action_metadata;let s;n.mode==="setup"?s=tu:s=n.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=rt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),au=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{te("Running Loop flow..."),te("context",t),te("checkoutPaymentMethod",e),te("nonCdeFormInputs",n),te("flowCallbacks",r),te("customParams",o);let s;o!=null&&o.success?s=Lo(n,r.get.onValidationError,ru):s=Lo(n,r.get.onValidationError,ou);const i=t.anyCdeConnection,c=await G(t.anyCdeConnection),l=c.mode!=="setup",u=await lt(t.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await se(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_debug_info:o.success?void 0:o.debugInfo,loop_success:o.success}});if(te(`Confirm result: ${d}`),c.mode==="setup"){te("Doing payment setup..."),te("├ Confirm payment flow result received Result:",d);const f=Lt(d);return te(`╰ Setup completed successfully [PM ID: ${f.payment_method_id}]`),{mode:"setup",result:f}}else{if(te("Doing checkout..."),!d.pay_first_success_response)throw Fo("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}}}),{log__:Ee,err__:jo}=D("pockyt-paypal"),iu=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 cu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var $,Pe;Ee("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await G(s);Ee("Verifying CPM...");const c=iu.parse(e);Ee("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Re(n,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=ho(u);Ee(`Starting payment flow... Mode: ${i.mode}`);const f=rt(),m=i.mode!=="setup",p={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:m,pay_first_flow_cart_info:m?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!(($=o==null?void 0:o.settings)!=null&&$.useRedirectFlow),frontend_token_for_redirect_flow:f},...d},_=new URL("/app/pre-action/start/",t.baseUrl).toString(),w=btoa(JSON.stringify(p)),A=new URLSearchParams({st:i.token,r:w}),k=`${_}?${A.toString()}`;if((Pe=o==null?void 0:o.settings)!=null&&Pe.useRedirectFlow)throw Ee("Starting redirect mode for PayPal..."),window.location.href=k,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");Ee("Starting popup mode for PayPal..."),Ee("Opening paypal iframe...");const x=await go("PayPal",s,f,k);Ee("Paypal flow result",x);const I=Ro(x.href),L=Yn(x.href,"catt");if(!L)throw jo("Checkout attempt ID not found in redirect URL:",x.href),new Error("Checkout attempt ID not found in redirect URL");Ee(`Confirming payment flow using vault ID ${I}`);const B=await se(s,{secure_token:i.token,their_pm_id:I,checkout_attempt_id:m?L:void 0});if(Ee("Confirm payment flow result",B),i.mode==="setup")return{mode:"setup",result:{payment_method_id:B.payment_methods[0].id}};if(!B.pay_first_success_response)throw jo("Checkout failed, no pay-first success response:",B),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:B.pay_first_success_response}}),Uo="ojs-stripe-link-btn",{log__:H,err__:lu}=D("stripe-link"),uu=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),du=a.array(a.object({our_existing_pm_id:a.string()})).length(1),pu=Ge(async({context:t,formCallbacks:e})=>{const n=t.customInitParams.stripeLink;H("Checking if there are any CPMs for Stripe Link...");const r=ae(t.checkoutPaymentMethods,uu);H("Starting stripe link flow...");const o=t.anyCdeConnection,s=await G(o),i=s.mode==="setup";H("Creating stripe elements...");const c=await ut(o,s.token,i,void 0),{elements:l,stripe:u}=await Ma(r.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});H("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:n==null?void 0:n.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),f=()=>{d.mount(`#${Uo}`)},m=()=>{d.unmount()};return n!=null&&n.doNotMountOnInit?H("NOT mounting stripe link button (doNotMountOnInit is true)"):(H("Mounting stripe link button..."),f()),d.on("click",async p=>{if(H("Stripe Link button clicked"),n!=null&&n.overrideLinkSubmit&&!await n.overrideLinkSubmit()){H("Stripe Link submit aborted by overrideLinkSubmit");return}p.resolve()}),d.on("confirm",async p=>{H("Stripe Link window confirmed",p);const _=await u.createPaymentMethod({elements:l,params:{billing_details:p.billingDetails}});_.error?(lu("error",_.error),e.get.onCheckoutError(_.error.message??"Stripe Link unknown error")):(H("paymentMethod",_.paymentMethod),U.stripeLink.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{stripePM:_.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:f,dismountButton:m,waitForButtonToMount:async()=>await hu(Uo)}}}),fu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{H("Running Stripe Link flow...");const s=t.anyCdeConnection;H("Merging PM fields with form fields...");const i=mu(n,o.stripePM),c=Re(i,r.get.onValidationError);E("billing_details_received",{...c}),H("Starting payment flow...");const l=await lt(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[h.EMAIL],new_customer_first_name:c[h.FIRST_NAME],new_customer_last_name:c[h.LAST_NAME],new_customer_address:{zip_code:c[h.ZIP_CODE],country:c[h.COUNTRY]}});H("Start payment flow response",l);const d=du.parse(l.required_user_actions)[0].our_existing_pm_id,f=await G(s);if(f.mode==="setup"){H("Doing payment setup...");const m=await se(s,{secure_token:f.token,existing_cc_pm_id:d});return{mode:"setup",result:Lt(m)}}else{H("Doing checkout...");const m={secure_token:f.token,payment_input:{provider_type:e.provider},customer_email:c[h.EMAIL],customer_zip_code:c[h.ZIP_CODE],customer_country:c[h.COUNTRY],promotion_code:c[h.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 zn(s,m)}}}),mu=(t,e)=>{var l,u,d,f,m;const n={...t},[r,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;n[h.EMAIL]=n[h.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",n[h.ZIP_CODE]=n[h.ZIP_CODE]||((f=e.billing_details.address)==null?void 0:f.postal_code)||"00000",n[h.COUNTRY]=n[h.COUNTRY]||((m=e.billing_details.address)==null?void 0:m.country)||"US";const i=n[h.FIRST_NAME]||r||"",c=n[h.LAST_NAME]||s||"";return i||c?(n[h.FIRST_NAME]=i,n[h.LAST_NAME]=c):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]=""),H("Final form inputs:",n),n},hu=t=>new Promise(e=>{const n=()=>{const r=document.getElementById(t);r?e(r):requestAnimationFrame(n)};n()}),{log__:ee,err__:yu}=D("stripe-pr"),_u=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()})}),gu=Ge(async({context:t,formCallbacks:e})=>{ee("Checking if there are any CPMs for Stripe PR...");const n=ae(t.checkoutPaymentMethods,_u);ee("Initializing Stripe PR flow...");const r=t.anyCdeConnection,o=await G(r),s=o.mode==="setup";ee("Getting initial preview amount");const i=await ut(r,o.token,s,void 0),c=await Da(n.metadata.stripe_pk,i.amountAtom,i.currency,s);ee("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return yu("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};ee("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,f)=>U.stripePR.run({context:t,checkoutPaymentMethod:ft(t.checkoutPaymentMethods,d),nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:f==null?void 0:f.overridePaymentRequest},initResult:{processor:de.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:de.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),vu=be(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o,initResult:s})=>{if(ee("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const _=o.overridePaymentRequest;ee("Overriding PR amount with",_);const w=typeof _.applePayPaymentRequest=="function"?_.applePayPaymentRequest({}):_.applePayPaymentRequest;bu(c,_.amount,_.pending,w,_.label)}ee("Showing PR dialog..."),c.show();const l=await Fa(c);ee("Stripe PM added event:",l),ee("Merging PM fields with form fields...");const u=wu(n,l),d=Re(u,r.get.onValidationError);E("billing_details_received",{...d}),ee("PR dialog finished. Starting payment flow...",d);const f=await Xc(i,{fields:d,checkoutPaymentMethod:e}),m=Eu(f);ee("Confirming PR with Stripe..."),await La(m,l);const p=await G(i);if(p.mode==="setup"){ee("Confirming payment flow for setup...");const _=await se(i,{secure_token:p.token});return{mode:"setup",result:Lt(_)}}else{ee("Performing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_first_name:d[h.FIRST_NAME],customer_last_name:d[h.LAST_NAME],customer_email:d[h.EMAIL],customer_zip_code:d[h.ZIP_CODE],customer_country:d[h.COUNTRY],promotion_code:d[h.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await zn(i,_)}}}),wu=(t,e)=>{var d,f,m,p;const n={...t},[r,...o]=((f=(d=e.payerName)==null?void 0:d.trim())==null?void 0:f.split(/\s+/))??[],s=o.join(" ")||void 0,i=(p=(m=e.paymentMethod)==null?void 0:m.billing_details)==null?void 0:p.address,c=e.shippingAddress;n[h.EMAIL]=n[h.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",n[h.ZIP_CODE]=n[h.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",n[h.COUNTRY]=n[h.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=n[h.FIRST_NAME]||r||"",u=n[h.LAST_NAME]||s||"";return l||u?(n[h.FIRST_NAME]=l,n[h.LAST_NAME]=u):(n[h.FIRST_NAME]="_OP_UNKNOWN",n[h.LAST_NAME]=""),ee("Final form inputs:",n),n},bu=(t,e,n,r,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:n},currency:e.currency,applePay:r})},Eu=t=>{if(t.required_user_actions.length!==1)throw new Error(`Error occurred.
25
- Details: got ${t.required_user_actions.length} required user actions`);return Na.parse(t.required_user_actions[0])},ku=()=>{const t=rt().split("-")[0];return{firstName:`xx_${t}`,lastName:`xx_${t}`,email:`xx_${t}@email.com`,zipCode:`xx_${t}`,country:"US"}},{log__:qe,err__:Cu}=D("paypal"),$o=a.object({provider:a.literal("paypal"),metadata:a.object({client_id:a.string()}),processor_name:a.literal("paypal")}),Su=async({context:t,formCallbacks:e})=>{const n=ae(t.checkoutPaymentMethods,$o);if(!n)throw new Error("PayPal CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:()=>U.paypal.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{settings:{}}})}},Pu=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{try{qe("Running PayPal flow...");const s=t.anyCdeConnection,i=await G(s),{isAnonymous:c,useRedirectFlow:l}=o.settings??{};qe("Verifying CPM...");const u=$o.parse(n);qe("├ Validating non-CDE form fields");const d=Re(e,r.get.onValidationError,c?ku():void 0),f=ho(d);qe(`Starting payment flow... Mode: ${i.mode}`);const m=rt(),p=i.mode!=="setup",_={payment_provider:u.provider,checkout_payment_method:u,use_pay_first_flow:p,pay_first_flow_cart_info:p?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:l,frontend_token_for_redirect_flow:m},...f},w=new URL("/app/pre-action/start/",t.baseUrl).toString(),A=btoa(JSON.stringify(_)),k=new URLSearchParams({st:i.token,r:A}),x=`${w}?${k.toString()}`;if(l)throw qe("Starting redirect mode for PayPal..."),window.location.href=x,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");const I=await go("PayPal",s,m,x);qe("Paypal flow result",I);const L=Yn(I.href,"catt"),B=Yn(I.href,"approval_session_id"),$=await se(s,{secure_token:i.token,checkout_attempt_id:p?L:void 0,their_pm_id:p?B:void 0});return qe("Confirm payment flow result",$),jt({logPrefix:"paypal",anyCdeConnection:s,checkoutPaymentMethod:u,requiredFormFields:d,confirmResult:$,usePayFirstFlow:p})}catch(s){throw Cu("PayPal payment error",s),E("checkout_error",{payment_method:"paypal",error:s}),new Error((s==null?void 0:s.message)??"Unknown error")}}),ft=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);return r.length!==1&&(console.warn("CPMs list",t),console.warn(`More than one CPM found with provider '${e}' and processor '${n}'`),E("more_than_one_cpm_found",{provider:e,processor:n,cpms:t})),r[0]},U={commonCC:{init:async()=>{},run:Hl},stripePR:{init:gu,run:vu},stripeLink:{init:pu,run:fu},pockytPaypal:{run:cu},paypal:{init:Su,run:Pu},airwallexGooglePay:{init:Pl,run:Al},airwallexApplePay:{init:kl,run:Cl},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:xl,run:Rl},authorizeNetGooglePay:{init:Nl,run:Ol}},{log__:Au,err__:Tu}=D("init-flows"),Ue=(t,e)=>{const n=new Ft;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);Au(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){Tu(`𝙭 ${t} flow initialization failed. Error:`,re(o),"Details:",o),n.throw(o,re(o))}}}},Iu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},xu=()=>({stripePR:Ue("Stripe PR",U.stripePR.init),stripeLink:Ue("Stripe Link",U.stripeLink.init),airwallexGooglePay:Ue("Airwallex GooglePay",U.airwallexGooglePay.init),airwallexApplePay:Ue("Airwallex ApplePay",U.airwallexApplePay.init),loop:Ue("Loop",U.loopCrypto.init),paypal:Ue("PayPal",U.paypal.init),authorizeNetGooglePay:Ue("Authnet GooglePay",U.authorizeNetGooglePay.init),authorizeNetApplePay:Ue("Authnet ApplePay",U.authorizeNetApplePay.init)}),{err__:Ru}=D("form-callbacks"),fe=a.function().optional(),Vo=a.object({onFocus:fe,onBlur:fe,onChange:fe,onLoad:fe,onLoadError:fe,onValidationError:fe,onCheckoutStarted:fe,onCheckoutSuccess:fe,onSetupPaymentMethodSuccess:fe,onCheckoutError:fe,onPaymentRequestLoad:fe}),Ce=class Ce{constructor(){this.setCallbacks=e=>{this._callbacks=Ce.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=ta(n,r??Ce.NOOP,Ru);this._callbacks[n]=o})},this._callbacks=Ce.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ce.NOOP=()=>{},Ce.createEmptyCallbacks=()=>{const e={};return Object.keys(Vo.keyof().enum).forEach(n=>{e[n]=Ce.NOOP}),e},Ce.fromObject=e=>{const n=new Ce;return n.setCallbacks(Vo.parse(e)),n};let Wn=Ce;const Zo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Zt=32,Nu=16,zo=10,Go=0xffffffffffff;var Ye;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(Ye||(Ye={}));class zt extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function Ou(t){let e=Math.floor(t()*Zt);return e===Zt&&(e=Zt-1),Zo.charAt(e)}function Mu(t){const e=Du(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new zt(Ye.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Du(){return ju()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Fu(t,e){let n="";for(;t>0;t--)n=Ou(e)+n;return n}function Lu(t,e=zo){if(isNaN(t))throw new zt(Ye.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Go)throw new zt(Ye.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Go}: ${t}`);if(t<0)throw new zt(Ye.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new zt(Ye.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Zt,r=Zo.charAt(n)+r,t=(t-n)/Zt;return r}function ju(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Uu(t,e){const n=Mu(),r=Date.now();return Lu(r,zo)+Fu(Nu,n)}const Bo="op_analytics_device_token",$u=()=>{const t=document.cookie.split(";").find(n=>n.includes(Bo));if(t)return t.split("=")[1];const e=Uu();return Vu(e),e},Vu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Bo}=${t}; path=/; expires=${e.toUTCString()}`};function Zu(){try{const t=z(),e=t;if(e!=null&&e.next||e!=null&&e.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const n=t;if(n!=null&&n.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(o=>o.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(o=>o._reactRootContainer))return"react";const r=t;return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function zu(t){var e,n,r;try{switch(t){case"react":return null;case"nextjs":{const s=z();return((e=s==null?void 0:s.next)==null?void 0:e.version)||((n=s==null?void 0:s.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=z())==null?void 0:r.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Gu(){const t=Zu(),e=zu(t);return{framework:t,version:e}}class Bu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(qo(s.origin)!==qo(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=Ga(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=n,this.formCallbacks=r,this.internalCallbacks=o}}const qo=t=>new URL(t).origin;async function qu(t,e){const r=await br({iframe:t,debug:!1,childOrigin:e}).promise,o=await pi(r);if(!fi(r,o))throw new Error("Got invalid CDE connection object");return r}class Yu{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Wu=(t,e,n)=>{const{stripePR:r}=t;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Yo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Yo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Yo=(t,e,n,r,o)=>U.stripePR.run({context:n,checkoutPaymentMethod:ft(n.checkoutPaymentMethods,t),nonCdeFormInputs:oe(n.formDiv),formCallbacks:r,customParams:{provider:t,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__:ke,err__:me}=D("op-form"),Se=class Se{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ft,this.anyCdeConn=new Ft,this.context=new Ft,this.initFlows=xu(),this.startFormInit=async()=>{try{const s=this.createElement(ge.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),ke("CDE bridge element mounted"),ke("Initializing OpenPay form:"),ke("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE load event received"),ke("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE connection received"),await al(c,this.deviceToken),ke("├ Creating OJS context, setting up handlers...");const l=Se.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Wu(this.initFlows,l,this.formCallbacks),ke("├ Starting OJS init flows..."),await Iu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),ke("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);me("╰ Error initializing OP form:",i),E("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===ge.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),E("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),E("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(this.checkValidFormInstance("createElement"),!this.config)throw new Error("OpenPay form not initialized");const c=ra.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),E("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[ge.CARD]:void 0,[ge.CARD_NUMBER]:void 0,[ge.CARD_EXPIRY]:void 0,[ge.CARD_CVC]:void 0,[ge.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Ua(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{qu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ge.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>me("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=s=>{E("submit_card",{...s}),this.checkValidFormInstance("submitCard");const i=this.context.getValueIfLoadedElse(null);if(!i){me("Please wait for the form to finish loading before submitting.");return}U.commonCC.run({context:i,checkoutPaymentMethod:ft(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:oe(i.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:s==null?void 0:s.paymentRouteId},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(this.checkValidFormInstance("getAvailablePaymentMethods"),!this.context.getValueIfLoadedElse(null)){me("Please wait for the form to finish loading before getting available payment methods.");return}const i={paypal:X.paypal,airwallexGooglePay:X.airwallexGooglePay,airwallexApplePay:X.airwallexApplePay,authorizeNetGooglePay:X.authorizenetGooglePay,authorizeNetApplePay:X.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return E("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{E("general_form_submit",{method:s,settings:i}),this.checkValidFormInstance("generalSubmit");const c=this.context.getValueIfLoadedElse(null);if(!c){me("Please wait for the form to finish loading before submitting.");return}switch(s){case X.pockytPaypal:return U.pockytPaypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case X.paypal:return U.paypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","paypal"),nonCdeFormInputs:oe(c.formDiv),initResult:void 0,customParams:{settings:{...i,useRedirectFlow:!0}},formCallbacks:this.formCallbacks});case X.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.loopCrypto:return U.loopCrypto.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:fn(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;ke("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=z())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Wc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Se.assignAsSingleton(this),this.ojsVersion="0.3.2",this.ojsReleaseVersion="0.3.2",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Wn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${rt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Yu,this.deviceToken=$u(),Yc();const{framework:n,version:r}=Gu();Xr(this.baseUrl).then(s=>{if(!Zn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Zn.set(i)}}),E("form_init"),this.eventHandler=new Bu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=z())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(e="unknown"){const n=Se.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(n==null?void 0:n.formId)||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},o=`
25
+ Details: got ${t.required_user_actions.length} required user actions`);return Na.parse(t.required_user_actions[0])},ku=()=>{const t=rt().split("-")[0];return{firstName:`xx_${t}`,lastName:`xx_${t}`,email:`xx_${t}@email.com`,zipCode:`xx_${t}`,country:"US"}},{log__:qe,err__:Cu}=D("paypal"),$o=a.object({provider:a.literal("paypal"),metadata:a.object({client_id:a.string()}),processor_name:a.literal("paypal")}),Su=async({context:t,formCallbacks:e})=>{const n=ae(t.checkoutPaymentMethods,$o);if(!n)throw new Error("PayPal CPM not found in available payment methods");return{isLoading:!1,isAvailable:!0,startFlow:()=>U.paypal.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:oe(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{settings:{}}})}},Pu=be(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{try{qe("Running PayPal flow...");const s=t.anyCdeConnection,i=await G(s),{isAnonymous:c,useRedirectFlow:l}=o.settings??{};qe("Verifying CPM...");const u=$o.parse(n);qe("├ Validating non-CDE form fields");const d=Re(e,r.get.onValidationError,c?ku():void 0),f=ho(d);qe(`Starting payment flow... Mode: ${i.mode}`);const m=rt(),p=i.mode!=="setup",_={payment_provider:u.provider,checkout_payment_method:u,use_pay_first_flow:p,pay_first_flow_cart_info:p?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:l,frontend_token_for_redirect_flow:m},...f},w=new URL("/app/pre-action/start/",t.baseUrl).toString(),A=btoa(JSON.stringify(_)),k=new URLSearchParams({st:i.token,r:A}),x=`${w}?${k.toString()}`;if(l)throw qe("Starting redirect mode for PayPal..."),window.location.href=x,await tn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");const I=await go("PayPal",s,m,x);qe("Paypal flow result",I);const L=Yn(I.href,"catt"),B=Yn(I.href,"approval_session_id"),$=await se(s,{secure_token:i.token,checkout_attempt_id:p?L:void 0,their_pm_id:p?B:void 0});return qe("Confirm payment flow result",$),jt({logPrefix:"paypal",anyCdeConnection:s,checkoutPaymentMethod:u,requiredFormFields:d,confirmResult:$,usePayFirstFlow:p})}catch(s){throw Cu("PayPal payment error",s),E("checkout_error",{payment_method:"paypal",error:s}),new Error((s==null?void 0:s.message)??"Unknown error")}}),ft=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.warn("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);return r.length!==1&&(console.warn("CPMs list",t),console.warn(`More than one CPM found with provider '${e}' and processor '${n}'`),E("more_than_one_cpm_found",{provider:e,processor:n,cpms:t})),r[0]},U={commonCC:{init:async()=>{},run:Hl},stripePR:{init:gu,run:vu},stripeLink:{init:pu,run:fu},pockytPaypal:{run:cu},paypal:{init:Su,run:Pu},airwallexGooglePay:{init:Pl,run:Al},airwallexApplePay:{init:kl,run:Cl},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:xl,run:Rl},authorizeNetGooglePay:{init:Nl,run:Ol}},{log__:Au,err__:Tu}=D("init-flows"),Ue=(t,e)=>{const n=new Ft;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);Au(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){Tu(`𝙭 ${t} flow initialization failed. Error:`,re(o),"Details:",o),n.throw(o,re(o))}}}},Iu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},xu=()=>({stripePR:Ue("Stripe PR",U.stripePR.init),stripeLink:Ue("Stripe Link",U.stripeLink.init),airwallexGooglePay:Ue("Airwallex GooglePay",U.airwallexGooglePay.init),airwallexApplePay:Ue("Airwallex ApplePay",U.airwallexApplePay.init),loop:Ue("Loop",U.loopCrypto.init),paypal:Ue("PayPal",U.paypal.init),authorizeNetGooglePay:Ue("Authnet GooglePay",U.authorizeNetGooglePay.init),authorizeNetApplePay:Ue("Authnet ApplePay",U.authorizeNetApplePay.init)}),{err__:Ru}=D("form-callbacks"),fe=a.function().optional(),Vo=a.object({onFocus:fe,onBlur:fe,onChange:fe,onLoad:fe,onLoadError:fe,onValidationError:fe,onCheckoutStarted:fe,onCheckoutSuccess:fe,onSetupPaymentMethodSuccess:fe,onCheckoutError:fe,onPaymentRequestLoad:fe}),Ce=class Ce{constructor(){this.setCallbacks=e=>{this._callbacks=Ce.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=ta(n,r??Ce.NOOP,Ru);this._callbacks[n]=o})},this._callbacks=Ce.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ce.NOOP=()=>{},Ce.createEmptyCallbacks=()=>{const e={};return Object.keys(Vo.keyof().enum).forEach(n=>{e[n]=Ce.NOOP}),e},Ce.fromObject=e=>{const n=new Ce;return n.setCallbacks(Vo.parse(e)),n};let Wn=Ce;const Zo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Zt=32,Nu=16,zo=10,Go=0xffffffffffff;var Ye;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(Ye||(Ye={}));class zt extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function Ou(t){let e=Math.floor(t()*Zt);return e===Zt&&(e=Zt-1),Zo.charAt(e)}function Mu(t){const e=Du(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new zt(Ye.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Du(){return ju()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Fu(t,e){let n="";for(;t>0;t--)n=Ou(e)+n;return n}function Lu(t,e=zo){if(isNaN(t))throw new zt(Ye.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Go)throw new zt(Ye.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Go}: ${t}`);if(t<0)throw new zt(Ye.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new zt(Ye.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Zt,r=Zo.charAt(n)+r,t=(t-n)/Zt;return r}function ju(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Uu(t,e){const n=Mu(),r=Date.now();return Lu(r,zo)+Fu(Nu,n)}const Bo="op_analytics_device_token",$u=()=>{const t=document.cookie.split(";").find(n=>n.includes(Bo));if(t)return t.split("=")[1];const e=Uu();return Vu(e),e},Vu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Bo}=${t}; path=/; expires=${e.toUTCString()}`};function Zu(){try{const t=z(),e=t;if(e!=null&&e.next||e!=null&&e.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const n=t;if(n!=null&&n.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(o=>o.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(o=>o._reactRootContainer))return"react";const r=t;return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function zu(t){var e,n,r;try{switch(t){case"react":return null;case"nextjs":{const s=z();return((e=s==null?void 0:s.next)==null?void 0:e.version)||((n=s==null?void 0:s.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(r=z())==null?void 0:r.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Gu(){const t=Zu(),e=zu(t);return{framework:t,version:e}}class Bu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(qo(s.origin)!==qo(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=Ga(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=n,this.formCallbacks=r,this.internalCallbacks=o}}const qo=t=>new URL(t).origin;async function qu(t,e){const r=await br({iframe:t,debug:!1,childOrigin:e}).promise,o=await pi(r);if(!fi(r,o))throw new Error("Got invalid CDE connection object");return r}class Yu{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Wu=(t,e,n)=>{const{stripePR:r}=t;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Yo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Yo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Yo=(t,e,n,r,o)=>U.stripePR.run({context:n,checkoutPaymentMethod:ft(n.checkoutPaymentMethods,t),nonCdeFormInputs:oe(n.formDiv),formCallbacks:r,customParams:{provider:t,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__:ke,err__:me}=D("op-form"),Se=class Se{constructor(e){var o;this.isDestroyed=!1,this.cdeLoadEvent=new Ft,this.anyCdeConn=new Ft,this.context=new Ft,this.initFlows=xu(),this.startFormInit=async()=>{try{const s=this.createElement(ge.CDE_BRIDGE);s.node.id="__op_internal_cde_bridge",s.node.ariaHidden="true",Object.assign(s.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),s.mount("body"),ke("CDE bridge element mounted"),ke("Initializing OpenPay form:"),ke("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE load event received"),ke("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Wo});ke("├ CDE connection received"),await al(c,this.deviceToken),ke("├ Creating OJS context, setting up handlers...");const l=Se.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Wu(this.initFlows,l,this.formCallbacks),ke("├ Starting OJS init flows..."),await Iu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),ke("╰ Done initializing OJS flows."),E("form_loaded")}catch(s){const i=re(s);me("╰ Error initializing OP form:",i),E("form_init_error",{error:i}),this.formCallbacks.get.onLoadError(i)}},this.setFormHeight=s=>{this.formProperties.height=s,this.registeredElements&&Object.values(this.registeredElements).forEach(i=>{!i||i.type===ge.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),E("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),E("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(this.checkValidFormInstance("createElement"),!this.config)throw new Error("OpenPay form not initialized");const c=ra.parse(s),l=document.createElement("iframe"),u=this.buildQueryString(i);l.name=`${c}-element`;const d=new URL(`/app/v1/${l.name}/`,this.config.baseUrl);return d.search=u.toString(),l.src=d.href,l.style.border="none",l.style.width="100%",this.registerIframe(c,l)},this.registerIframe=(s,i)=>{const c={type:s,node:i,mount:l=>{var u;(u=document.querySelector(l))==null||u.appendChild(i),E("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[ge.CARD]:void 0,[ge.CARD_NUMBER]:void 0,[ge.CARD_EXPIRY]:void 0,[ge.CARD_CVC]:void 0,[ge.CDE_BRIDGE]:void 0}),this.registeredElements[s]=c,c},this.buildQueryString=s=>{const i=new URLSearchParams;return i.append("referer",this.referrer),i.append("formId",this.formId),s.styles&&i.append("styles",Ua(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{qu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ge.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>me("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=s=>{E("submit_card",{...s}),this.checkValidFormInstance("submitCard");const i=this.context.getValueIfLoadedElse(null);if(!i){me("Please wait for the form to finish loading before submitting.");return}U.commonCC.run({context:i,checkoutPaymentMethod:ft(i.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:oe(i.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections(),paymentRouteId:s==null?void 0:s.paymentRouteId},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(this.checkValidFormInstance("getAvailablePaymentMethods"),!this.context.getValueIfLoadedElse(null)){me("Please wait for the form to finish loading before getting available payment methods.");return}const i={paypal:X.paypal,airwallexGooglePay:X.airwallexGooglePay,airwallexApplePay:X.airwallexApplePay,authorizeNetGooglePay:X.authorizenetGooglePay,authorizeNetApplePay:X.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return E("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{E("general_form_submit",{method:s,settings:i}),this.checkValidFormInstance("generalSubmit");const c=this.context.getValueIfLoadedElse(null);if(!c){me("Please wait for the form to finish loading before submitting.");return}switch(s){case X.pockytPaypal:return U.pockytPaypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case X.paypal:return U.paypal.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"paypal","paypal"),nonCdeFormInputs:oe(c.formDiv),initResult:void 0,customParams:{settings:{...i,useRedirectFlow:!0}},formCallbacks:this.formCallbacks});case X.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){me("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case X.loopCrypto:return U.loopCrypto.run({context:c,checkoutPaymentMethod:ft(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:oe(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:fn(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;ke("Destroying OpenPay form..."),this.checkValidFormInstance("destroy"),this.isDestroyed=!0;for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=z())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Wc(),this.registeredElements=null,delete window.ojs,E("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Se.assignAsSingleton(this),this.ojsVersion="0.3.3",this.ojsReleaseVersion="0.3.3",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Wn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${rt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Yu,this.deviceToken=$u(),Yc();const{framework:n,version:r}=Gu();Xr(this.baseUrl).then(s=>{if(!Zn.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};Zn.set(i)}}),E("form_init"),this.eventHandler=new Bu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=z())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}checkValidFormInstance(e="unknown"){const n=Se.getInstance(),r={caller:e,thisFormId:this.formId,currentFormId:(n==null?void 0:n.formId)||"no-current-instance",isDestroyed:this.isDestroyed,checkoutToken:this.config.checkoutSecureToken.substring(0,10)+"..."},o=`
26
26
  [Warning] Invalid form instance detected.
27
27
  It looks like you are still using an old instance that has been destroyed.
28
28
  Please make sure you are using the latest instance of the form and cleanup event listeners.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getopenpay/openpay-js",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
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",