@getopenpay/openpay-js 0.1.1-alpha.3 → 0.1.1
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.d.ts +4 -13
- package/dist/index.es.js +2 -0
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -48,10 +48,7 @@ declare const CheckoutPaymentMethod: z.ZodObject<{
|
|
|
48
48
|
|
|
49
49
|
declare type CheckoutPaymentMethod = z.infer<typeof CheckoutPaymentMethod>;
|
|
50
50
|
|
|
51
|
-
export declare type Config =
|
|
52
|
-
formTarget?: string;
|
|
53
|
-
onPaymentRequestLoad?: (paymentRequests: Record<'apple_pay' | 'google_pay', PaymentRequestStatus>) => void;
|
|
54
|
-
};
|
|
51
|
+
export declare type Config = ElementsFormProps;
|
|
55
52
|
|
|
56
53
|
declare class ConnectionManager {
|
|
57
54
|
private connections;
|
|
@@ -64,17 +61,9 @@ declare type ElementProps<PlaceholderType extends z.ZodTypeAny = z.ZodString> =
|
|
|
64
61
|
styles?: ElementsStyle<z.ZodOptional<PlaceholderType>>;
|
|
65
62
|
};
|
|
66
63
|
|
|
67
|
-
declare type
|
|
68
|
-
submit: () => void;
|
|
69
|
-
applePay: PaymentRequestStatus;
|
|
70
|
-
googlePay: PaymentRequestStatus;
|
|
71
|
-
loaded: boolean;
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
declare type ElementsFormProps = {
|
|
64
|
+
export declare type ElementsFormProps = {
|
|
75
65
|
className?: string;
|
|
76
66
|
checkoutSecureToken: string;
|
|
77
|
-
children: (props: ElementsFormChildrenProps) => JSX.Element;
|
|
78
67
|
onFocus?: (elementId: string) => void;
|
|
79
68
|
onBlur?: (elementId: string) => void;
|
|
80
69
|
onChange?: (elementId: string) => void;
|
|
@@ -86,6 +75,8 @@ declare type ElementsFormProps = {
|
|
|
86
75
|
onSetupPaymentMethodSuccess?: (paymentMethodId: string) => void;
|
|
87
76
|
onCheckoutError?: (message: string) => void;
|
|
88
77
|
baseUrl?: string;
|
|
78
|
+
formTarget?: string;
|
|
79
|
+
onPaymentRequestLoad?: (paymentRequests: Record<'apple_pay' | 'google_pay', PaymentRequestStatus>) => void;
|
|
89
80
|
};
|
|
90
81
|
|
|
91
82
|
declare const ElementsStyle: <T extends z.ZodTypeAny>(placeholderType: T) => z.ZodObject<z.objectUtil.extendShape<{
|
package/dist/index.es.js
CHANGED
|
@@ -3777,6 +3777,8 @@ class Lo {
|
|
|
3777
3777
|
), this.config.onPaymentRequestLoad && this.config.onPaymentRequestLoad(this.paymentRequests));
|
|
3778
3778
|
}
|
|
3779
3779
|
destroy() {
|
|
3780
|
+
for (const a of Object.values(this.elements ?? {}))
|
|
3781
|
+
a.node.remove();
|
|
3780
3782
|
window.removeEventListener("message", this.eventHandler.handleMessage.bind(this.eventHandler));
|
|
3781
3783
|
}
|
|
3782
3784
|
}
|
package/dist/index.umd.js
CHANGED
|
@@ -78,4 +78,4 @@ Check the render method of \``+e+"`."}return""}function Ir(e){if(e!==void 0){var
|
|
|
78
78
|
|
|
79
79
|
Check your code at `+t+":"+n+"."}return""}function jr(e){return e!=null?Ir(e.__source):""}var bt={};function Ar(e){var t=_t();if(!t){var n=typeof e=="string"?e:e.displayName||e.name;n&&(t=`
|
|
80
80
|
|
|
81
|
-
Check the top-level render call using <`+n+">.")}return t}function Et(e,t){if(!(!e._store||e._store.validated||e.key!=null)){e._store.validated=!0;var n=Ar(t);if(!bt[n]){bt[n]=!0;var o="";e&&e._owner&&e._owner!==V.current&&(o=" It was passed a child from "+X(e._owner.type)+"."),le(e),f('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,o),le(null)}}}function wt(e,t){if(typeof e=="object"){if(Ce(e))for(var n=0;n<e.length;n++){var o=e[n];ce(o)&&Et(o,t)}else if(ce(e))e._store&&(e._store.validated=!0);else if(e){var u=ae(e);if(typeof u=="function"&&u!==e.entries)for(var p=u.call(e),l;!(l=p.next()).done;)ce(l.value)&&Et(l.value,t)}}}function Ct(e){{var t=e.type;if(t==null||typeof t=="string")return;var n;if(typeof t=="function")n=t.propTypes;else if(typeof t=="object"&&(t.$$typeof===U||t.$$typeof===Y))n=t.propTypes;else return;if(n){var o=X(t);Pr(n,e.props,"prop",o,e)}else if(t.PropTypes!==void 0&&!Ve){Ve=!0;var u=X(t);f("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",u||"Unknown")}typeof t.getDefaultProps=="function"&&!t.getDefaultProps.isReactClassApproved&&f("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Mr(e){{for(var t=Object.keys(e.props),n=0;n<t.length;n++){var o=t[n];if(o!=="children"&&o!=="key"){le(e),f("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",o),le(null);break}}e.ref!==null&&(le(e),f("Invalid attribute `ref` supplied to `React.Fragment`."),le(null))}}function St(e,t,n){var o=st(e);if(!o){var u="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(u+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var p=jr(t);p?u+=p:u+=_t();var l;e===null?l="null":Ce(e)?l="array":e!==void 0&&e.$$typeof===m?(l="<"+(X(e.type)||"Unknown")+" />",u=" Did you accidentally export a JSX literal instead of a component?"):l=typeof e,f("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",l,u)}var y=Kt.apply(this,arguments);if(y==null)return y;if(o)for(var v=2;v<arguments.length;v++)wt(arguments[v],e);return e===b?Mr(y):Ct(y),y}var Rt=!1;function Dr(e){var t=St.bind(null,e);return t.type=e,Rt||(Rt=!0,Q("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(t,"type",{enumerable:!1,get:function(){return Q("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:e}),e}}),t}function $r(e,t,n){for(var o=Gt.apply(this,arguments),u=2;u<arguments.length;u++)wt(arguments[u],o.type);return Ct(o),o}function Fr(e,t){var n=B.transition;B.transition={};var o=B.transition;B.transition._updatedFibers=new Set;try{e()}finally{if(B.transition=n,n===null&&o._updatedFibers){var u=o._updatedFibers.size;u>10&&Q("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),o._updatedFibers.clear()}}}var kt=!1,je=null;function xr(e){if(je===null)try{var t=("require"+Math.random()).slice(0,7),n=c&&c[t];je=n.call(c,"timers").setImmediate}catch{je=function(o){kt===!1&&(kt=!0,typeof MessageChannel>"u"&&f("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var u=new MessageChannel;u.port1.onmessage=o,u.port2.postMessage(void 0)}}return je(e)}var fe=0,Ot=!1;function Tt(e){{var t=fe;fe++,$.current===null&&($.current=[]);var n=$.isBatchingLegacy,o;try{if($.isBatchingLegacy=!0,o=e(),!n&&$.didScheduleLegacyUpdate){var u=$.current;u!==null&&($.didScheduleLegacyUpdate=!1,He(u))}}catch(T){throw Ae(t),T}finally{$.isBatchingLegacy=n}if(o!==null&&typeof o=="object"&&typeof o.then=="function"){var p=o,l=!1,y={then:function(T,A){l=!0,p.then(function(F){Ae(t),fe===0?qe(F,T,A):T(F)},function(F){Ae(t),A(F)})}};return!Ot&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){l||(Ot=!0,f("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),y}else{var v=o;if(Ae(t),fe===0){var w=$.current;w!==null&&(He(w),$.current=null);var S={then:function(T,A){$.current===null?($.current=[],qe(v,T,A)):T(v)}};return S}else{var R={then:function(T,A){T(v)}};return R}}}}function Ae(e){e!==fe-1&&f("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),fe=e}function qe(e,t,n){{var o=$.current;if(o!==null)try{He(o),xr(function(){o.length===0?($.current=null,t(e)):qe(e,t,n)})}catch(u){n(u)}else t(e)}}var Ye=!1;function He(e){if(!Ye){Ye=!0;var t=0;try{for(;t<e.length;t++){var n=e[t];do n=n(!0);while(n!==null)}e.length=0}catch(o){throw e=e.slice(t+1),o}finally{Ye=!1}}}var Lr=St,Nr=$r,Ur=Dr,zr={map:ke,forEach:er,count:Xt,toArray:tr,only:rr};a.Children=zr,a.Component=_,a.Fragment=b,a.Profiler=I,a.PureComponent=C,a.StrictMode=j,a.Suspense=z,a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=H,a.act=Tt,a.cloneElement=Nr,a.createContext=nr,a.createElement=Lr,a.createFactory=Ur,a.createRef=Nt,a.forwardRef=sr,a.isValidElement=ce,a.lazy=ir,a.memo=ur,a.startTransition=Fr,a.unstable_act=Tt,a.useCallback=hr,a.useContext=cr,a.useDebugValue=_r,a.useDeferredValue=Er,a.useEffect=dr,a.useId=wr,a.useImperativeHandle=gr,a.useInsertionEffect=yr,a.useLayoutEffect=mr,a.useMemo=vr,a.useReducer=fr,a.useRef=pr,a.useState=lr,a.useSyncExternalStore=Cr,a.useTransition=br,a.version=d,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()}(Mt,Mt.exports)),Mt.exports}process.env.NODE_ENV==="production"?ao():io();const so=async c=>{if(typeof c!="object"||!c)return!1;try{const a={type:"ping"},d=await c.send(a);if(d!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(d)}`);return!0}catch{return!1}},uo=(c,a)=>!!c&&a,W=c=>i.z.nullable(c.optional());i.z.string().trim().min(1,{message:"Cannot be blank"});const co=i.z.object({cde_response_type:i.z.literal("error"),message:i.z.string()}),lo=i.z.enum(["usd","brl"]),un=i.z.object({name:i.z.string(),amount_atom_off:W(i.z.number()),percent_off:W(i.z.number()),currency:W(i.z.string()),duration:i.z.string(),duration_in_months:W(i.z.number())}),fo=i.z.object({amount_subtotal_atom:i.z.number().int(),amount_total_atom:i.z.number().int(),currency:i.z.string(),description:W(i.z.string()),price_id:i.z.string(),billing_interval:W(i.z.string()),billing_interval_count:W(i.z.number().int()),quantity:i.z.number().int()}),po=i.z.record(i.z.string(),i.z.any()),yo=i.z.object({name:i.z.string(),settings:W(po)}),mo=i.z.object({provider:i.z.string(),processor_name:W(i.z.string()),metadata:W(i.z.record(i.z.string(),i.z.any()))}),ho=i.z.object({quantity:i.z.number()}),vo=i.z.object({id:W(i.z.string()),billing_interval:W(i.z.string()),billing_interval_count:W(i.z.number().int()),subscription_items:i.z.array(ho),trial_start:W(i.z.string()),trial_end:W(i.z.string())}),cn=i.z.object({amount_atom:i.z.number()}),go=i.z.object({amount_atom:i.z.number(),amount_atom_considering_discount_applied:i.z.number(),currency:i.z.string(),discount_amount_atoms:i.z.array(cn),subscription_item_id:i.z.string()}),_o=i.z.object({coupon:un}),bo=i.z.object({currency:i.z.string(),discounts:i.z.array(_o),hosted_invoice_url:W(i.z.string()),lines:i.z.array(go),remaining_amount_atom:i.z.number(),tax_amount_atom:i.z.number(),total_amount_atom:i.z.number(),total_discount_amount_atoms:i.z.array(cn)}),ln=i.z.object({created:i.z.array(vo),invoices:i.z.array(bo)}),fn=i.z.object({preview:ln,preview_post_trial:W(ln),coupons:i.z.array(un)}),pn=i.z.object({status:i.z.literal("open"),token:i.z.string(),email:W(i.z.string()),line_items:i.z.array(fo),amount_subtotal_atom:i.z.number().int(),amount_total_atom:i.z.number().int(),brand:yo,subs_preview:W(fn),methods_available:i.z.array(mo)}),dn=i.z.discriminatedUnion("mode",[i.z.object({mode:i.z.literal("setup"),currency:i.z.nullable(i.z.undefined())}).extend(pn.shape),i.z.object({mode:i.z.enum(["payment","subscription"]),currency:lo}).extend(pn.shape)]),Eo=i.z.object({status:i.z.literal("complete")}),wo=i.z.object({status:i.z.literal("expired")});i.z.union([dn,Eo,wo]),i.z.object({logo:i.z.string(),icon:i.z.string(),primary_color:i.z.string(),secondary_color:i.z.string()}),i.z.object({invoice_urls:i.z.array(i.z.string()),subscription_ids:i.z.array(i.z.string()),customer_id:i.z.string()}),i.z.object({payment_method_id:i.z.string()}),i.z.object({id:i.z.string(),return_url:i.z.string()});const Co=i.z.object({type:i.z.string(),loc:i.z.array(i.z.string()),msg:i.z.string(),url:i.z.string()});i.z.array(Co),i.z.object({required_user_actions:i.z.array(i.z.record(i.z.string(),i.z.any()))}),i.z.object({required_user_actions:i.z.array(i.z.record(i.z.string(),i.z.any())),cc_pm_id:i.z.string()});const Lt=async(c,a,d)=>{const m=await c.send(a);if(Ro(m))throw new Error(`[cde-client] Error querying CDE: ${m.message}`);if(!So(m,d)){const g=d.safeParse(m);throw g.success?new Error("Invalid state"):g.error}return m},So=(c,a)=>a.safeParse(c).success,Ro=c=>co.safeParse(c).success,ko=async(c,a)=>await Lt(c,{type:"get_checkout_preview",payload:a},fn),yn=async c=>await Lt(c,{type:"get_prefill",payload:{}},dn),Oo=async(c,a)=>await Lt(c,{type:"confirm_payment_flow",payload:a},Gn);class To{constructor(a){this.formInstance=a,this.config=a.config,this.formId=a.formId,this.eventTargets={},this.nonces=new Set,this.tokenizedData=null,this.tokenized=0,this.connectionManager=a.getConnectionManager()}setTokenizedData(a){this.tokenizedData=a}handleMessage(a){if(a.origin!==this.formInstance.config.baseUrl||!a.source)return;const d=oo(JSON.parse(a.data));if(!this.validateEvent(d))return;const{elementId:g,payload:b}=d;switch(b.type){case"LAYOUT":this.handleLayoutEvent(b);break;case"FOCUS":this.handleFocusEvent(g);break;case"BLUR":this.handleBlurEvent(g);break;case"CHANGE":this.handleChangeEvent(g);break;case"LOADED":this.handleLoadedEvent(a.source,g,b);break;case"TOKENIZE_STARTED":this.handleTokenizeStartedEvent();break;case"PAYMENT_FLOW_STARTED":this.handlePaymentFlowStartedEvent(b,a.source,g);break;case"TOKENIZE_SUCCESS":this.handleTokenizeSuccessEvent(a.source,g,b);break;case"CHECKOUT_SUCCESS":this.handleCheckoutSuccessEvent(b);break;case"SETUP_PAYMENT_METHOD_SUCCESS":this.handleSetupPaymentMethodSuccessEvent(b);break;case"LOAD_ERROR":this.handleLoadErrorEvent(b);break;case"VALIDATION_ERROR":this.handleValidationErrorEvent(b,g);break;case"TOKENIZE_ERROR":case"CHECKOUT_ERROR":this.handleErrorEvent(b);break}}validateEvent(a){return a.formId!==this.formInstance.formId||!a.elementId||this.nonces.has(a.nonce)?!1:(this.nonces.add(a.nonce),!0)}handleLayoutEvent(a){const d=a.height?`${a.height}px`:"100%";this.formInstance.setFormHeight(d)}handleFocusEvent(a){this.config.onFocus&&this.config.onFocus(a)}handleBlurEvent(a){this.config.onBlur&&this.config.onBlur(a)}handleChangeEvent(a){this.config.onChange&&this.config.onChange(a)}handleLoadedEvent(a,d,m){this.eventTargets[d]=a,this.formInstance.sessionId||(this.formInstance.sessionId=m.sessionId),this.config.onLoad&&this.config.onLoad(m.totalAmountAtoms,m.currency),this.formInstance.checkoutPaymentMethods=m.checkoutPaymentMethods}handleTokenizeStartedEvent(){this.formInstance.config.onCheckoutStarted&&this.formInstance.config.onCheckoutStarted()}async handlePaymentFlowStartedEvent(a,d,m){var j;if(!this.tokenizedData)throw new Error("tokenizedData not populated");const g=this.connectionManager.getConnection(),b=async()=>{var q;const I=a.nextActionMetadata.type;if(I!==void 0)if(I==="stripe_3ds")await ro(a);else if(I==="stripe_payment_request"){if(!this.formInstance.getStripePm())throw new Error("Stripe PM not set");await to(a,this.formInstance.getStripePm())}else throw new Error(`Unknown next action type: ${I}`);const x=await yn(g);if(x.mode==="setup"){const{payment_methods:U}=await Oo(g,{secure_token:x.token,existing_cc_pm_id:(q=this.tokenizedData)==null?void 0:q.existingCCPMId});if(U.length!==1)throw new Error(`Expected exactly one payment method, got ${U.length}`);return this.tokenized=0,this.formInstance.checkoutFired=!1,this.formInstance.config.onSetupPaymentMethodSuccess&&this.formInstance.config.onSetupPaymentMethodSuccess(U[0].id),{proceedToCheckout:!1}}else return{proceedToCheckout:!0}};try{const{proceedToCheckout:I}=await b();if(!I)return;let x;if(this.tokenizedData.checkoutPaymentMethod.provider==="credit_card"&&(x=(j=a.startPFMetadata)==null?void 0:j.cc_pm_id,!x))throw new Error("CC PM ID not found");on(d,this.formInstance.formId,m,{...this.tokenizedData,type:"CHECKOUT",doNotUseLegacyCCFlow:!0,existingCCPMId:x},this.formInstance.config.baseUrl),this.formInstance.checkoutFired=!0,this.tokenizedData=null,this.formInstance.config.onCheckoutStarted&&this.formInstance.config.onCheckoutStarted()}catch(I){const x=Gr(I);this.formInstance.checkoutFired=!1,this.formInstance.config.onCheckoutError&&this.formInstance.config.onCheckoutError(x)}}handleTokenizeSuccessEvent(a,d,m){if(!this.tokenizedData)throw new Error("Tokenized data not found");const g=this.tokenized+1,b=g===Object.keys(this.eventTargets).length;!this.formInstance.checkoutFired&&(b||m.isReadyForCheckout)?(this.tokenizedData.type=this.tokenizedData.type===G.enum.TOKENIZE?G.enum.CHECKOUT:G.enum.START_PAYMENT_FLOW,this.postEventToFrame(a,d,this.tokenizedData),this.tokenizedData=null):this.tokenized=g}handleCheckoutSuccessEvent(a){this.formInstance.config.onCheckoutSuccess&&this.formInstance.config.onCheckoutSuccess(a.invoiceUrls,a.subscriptionIds,a.customerId)}handleSetupPaymentMethodSuccessEvent(a){this.formInstance.config.onSetupPaymentMethodSuccess&&this.formInstance.config.onSetupPaymentMethodSuccess(a.paymentMethodId)}handleLoadErrorEvent(a){this.formInstance.config.onLoadError&&this.formInstance.config.onLoadError(a.message)}handleValidationErrorEvent(a,d){this.formInstance.config.onValidationError&&this.formInstance.config.onValidationError(a.elementType,a.errors,d)}handleErrorEvent(a){var d;if(a.message==="3DS_REQUIRED"){const m=(d=this.formInstance.checkoutPaymentMethods)==null?void 0:d.find(g=>g.provider==="credit_card");if(!this.formInstance.sessionId||!this.formInstance.formTarget||!this.config.onValidationError||!m)return;for(const[g,b]of Object.entries(this.eventTargets)){if(!b)continue;const j=At(G.enum.START_PAYMENT_FLOW,this.formInstance.sessionId,document.querySelector(this.formInstance.formTarget)??document.body,this.config.onValidationError,{...m,processor_name:"stripe"},!1);if(j){this.formInstance.checkoutFired=!0,this.tokenizedData=j,this.postEventToFrame(b,g,j);break}}}else this.formInstance.checkoutFired=!1,this.formInstance.config.onCheckoutError&&this.formInstance.config.onCheckoutError(a.message)}handleFormSubmit(){var m;if(!this.formInstance.sessionId||!((m=this.formInstance.checkoutPaymentMethods)!=null&&m.length)||!this.config.onValidationError)return;const a=this.formInstance.checkoutPaymentMethods.find(g=>g.provider==="credit_card");if(!a)throw new Error("Card not available as a payment method in checkout");const d=At(G.enum.TOKENIZE,this.formInstance.sessionId,document.querySelector(this.formInstance.formTarget)??document.body,this.config.onValidationError,a,!1);if(!d)throw new Error("Error constructing tokenize data");for(const[g,b]of Object.entries(this.eventTargets))b&&this.postEventToFrame(b,g,d);this.tokenizedData=d}postEventToFrame(a,d,m){on(a,this.formId,d,m,this.config.baseUrl)}}async function Po(c){const d=await hn.connectToChild({iframe:c,debug:!0}).promise,m=await so(d);if(!uo(d,m))throw new Error("Got invalid CDE connection object");return d}class Io{constructor(){this.connections=new Map}addConnection(a,d){this.connections.set(a,d)}getConnection(){const a=this.connections.values().next().value;if(!a)throw new Error("Connection not found");return a}}async function jo(c,a,d,m,g,b){const j={apple_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}},google_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}}};for(const I of["apple_pay","google_pay"])try{const x=a.find(z=>z.provider===I&&z.processor_name==="stripe");if(!x)throw new Error(`${I} is not available as a checkout method`);const q=eo(x.metadata),U=await Ao(q,I);j[I]={isLoading:!1,isAvailable:U,startFlow:z=>Mo(d,c.checkoutSecureToken,document.querySelector(c.formTarget),x,q,m,g,b,z)}}catch{j[I]={isLoading:!1,isAvailable:!1,startFlow:async()=>{}}}return j}async function Ao(c,a){const m=await tn(c,1e3,"usd"),g=await m.canMakePayment();if(m.abort(),!g)throw new Error(`Cannot make payment with ${a} for this session`);return g[a==="apple_pay"?"applePay":"googlePay"]}async function Mo(c,a,d,m,g,b,j,I,x){try{const q=nn(d,{});if(!Do(d,j,m))return;const z=(await yn(c)).mode==="setup",ee=await $o(z,x,q,c,a),Y=await tn(g,ee.amountAtom,ee.currency,z);await Y.canMakePayment(),Y.show();const J=await Xn(Y);b(J,m)}catch(q){I(Gr(q))}}function Do(c,a,d){return!!At(G.enum.START_PAYMENT_FLOW,"dummy",c,a??(()=>{}),d,!1)}async function $o(c,a,d,m,g){if(c)return(a==null?void 0:a.amountToDisplayForSetupMode)??{amountAtom:0,currency:"usd"};a!=null&&a.amountToDisplayForSetupMode;const b=ne.safeParse(d[Ke.PROMOTION_CODE]);if(!b.success)throw new Error(`Unknown promo code type: ${b.error.message}`);const j=await ko(m,{secure_token:g,promotion_code:b.data}),I=new Set(j.preview.invoices.map(U=>U.currency));if(I.size!==1)throw new Error(`Expected exactly one currency, got ${I.size}`);const x=I.values().next().value;return{amountAtom:j.preview.invoices.reduce((U,z)=>U+z.remaining_amount_atom,0),currency:x}}class Fo{constructor(a){this.config={...a,baseUrl:a.baseUrl??"https://cde.getopenpay.com"},this.elements=null,this.formId=`opjs-form-${window.crypto.randomUUID()}`,this.referer=window.location.origin,this.formTarget=a.formTarget??"body",this.formProperties={height:"1px"},this.sessionId=null,this.checkoutPaymentMethods=[],this.checkoutFired=!1,this.stripePm=void 0,this.paymentRequests=this.initPaymentRequests(),this.connectionManager=new Io,this.eventHandler=new To(this),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler))}getStripePm(){return this.stripePm}getConnectionManager(){return this.connectionManager}setFormHeight(a){this.formProperties.height=a,this.elements&&Object.values(this.elements).forEach(d=>{d.node.style.height=a})}initPaymentRequests(){return{apple_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}},google_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}}}}createElement(a,d={}){if(!this.config)throw new Error("OpenPay form not initialized");const m=document.createElement("iframe"),g=this.buildQueryString(d);m.name=`${a}-element`,m.src=`${this.config.baseUrl}/app/v1/${a}-element/?${g.toString()}`,m.style.border="none",m.style.width="100%";const b={type:a,node:m,mount:j=>{var I;return(I=document.querySelector(j))==null?void 0:I.appendChild(m)}};return this.elements?this.elements[a]=b:(this.elements={[a]:b},this.connectToElement(b)),b}buildQueryString(a){const d=new URLSearchParams;return d.append("referer",this.referer),d.append("formId",this.formId),a.styles&&d.append("styles",no(a.styles)),d.append("secureToken",this.config.checkoutSecureToken),d}connectToElement(a){Po(a.node).then(d=>{this.connectionManager.addConnection(a.type,d),this.initializePaymentRequests()}).catch(d=>{})}submit(){this.eventHandler.handleFormSubmit()}async onUserCompletePaymentRequestUI(a,d){if(!(!this.config.onValidationError||!this.sessionId||!this.checkoutPaymentMethods))for(const[m,g]of Object.entries(this.eventHandler.eventTargets??{})){const b={stripePmId:a.paymentMethod.id},j=At(G.enum.START_PAYMENT_FLOW,this.sessionId,document.querySelector(this.formTarget)??document.body,this.config.onValidationError,d,!1,b);if(j){this.stripePm=a,this.checkoutFired=!0,this.eventHandler.setTokenizedData(j),this.eventHandler.postEventToFrame(g,m,j);break}}}onPaymentRequestError(a){this.checkoutFired=!1,this.config.onCheckoutError&&this.config.onCheckoutError(a)}async initializePaymentRequests(){if(!this.config.checkoutSecureToken||!this.checkoutPaymentMethods||!this.formTarget)return;const a=this.connectionManager.getConnection();a&&(this.paymentRequests=await jo(this.config,this.checkoutPaymentMethods,a,this.onUserCompletePaymentRequestUI.bind(this),this.config.onValidationError,this.onPaymentRequestError.bind(this)),this.config.onPaymentRequestLoad&&this.config.onPaymentRequestLoad(this.paymentRequests))}destroy(){window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler))}}ve.FieldName=Ke,ve.OpenPayForm=Fo,Object.defineProperty(ve,Symbol.toStringTag,{value:"Module"})});
|
|
81
|
+
Check the top-level render call using <`+n+">.")}return t}function Et(e,t){if(!(!e._store||e._store.validated||e.key!=null)){e._store.validated=!0;var n=Ar(t);if(!bt[n]){bt[n]=!0;var o="";e&&e._owner&&e._owner!==V.current&&(o=" It was passed a child from "+X(e._owner.type)+"."),le(e),f('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,o),le(null)}}}function wt(e,t){if(typeof e=="object"){if(Ce(e))for(var n=0;n<e.length;n++){var o=e[n];ce(o)&&Et(o,t)}else if(ce(e))e._store&&(e._store.validated=!0);else if(e){var u=ae(e);if(typeof u=="function"&&u!==e.entries)for(var p=u.call(e),l;!(l=p.next()).done;)ce(l.value)&&Et(l.value,t)}}}function Ct(e){{var t=e.type;if(t==null||typeof t=="string")return;var n;if(typeof t=="function")n=t.propTypes;else if(typeof t=="object"&&(t.$$typeof===U||t.$$typeof===Y))n=t.propTypes;else return;if(n){var o=X(t);Pr(n,e.props,"prop",o,e)}else if(t.PropTypes!==void 0&&!Ve){Ve=!0;var u=X(t);f("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",u||"Unknown")}typeof t.getDefaultProps=="function"&&!t.getDefaultProps.isReactClassApproved&&f("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Mr(e){{for(var t=Object.keys(e.props),n=0;n<t.length;n++){var o=t[n];if(o!=="children"&&o!=="key"){le(e),f("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",o),le(null);break}}e.ref!==null&&(le(e),f("Invalid attribute `ref` supplied to `React.Fragment`."),le(null))}}function St(e,t,n){var o=st(e);if(!o){var u="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(u+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var p=jr(t);p?u+=p:u+=_t();var l;e===null?l="null":Ce(e)?l="array":e!==void 0&&e.$$typeof===m?(l="<"+(X(e.type)||"Unknown")+" />",u=" Did you accidentally export a JSX literal instead of a component?"):l=typeof e,f("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",l,u)}var y=Kt.apply(this,arguments);if(y==null)return y;if(o)for(var v=2;v<arguments.length;v++)wt(arguments[v],e);return e===b?Mr(y):Ct(y),y}var Rt=!1;function Dr(e){var t=St.bind(null,e);return t.type=e,Rt||(Rt=!0,Q("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(t,"type",{enumerable:!1,get:function(){return Q("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:e}),e}}),t}function $r(e,t,n){for(var o=Gt.apply(this,arguments),u=2;u<arguments.length;u++)wt(arguments[u],o.type);return Ct(o),o}function Fr(e,t){var n=B.transition;B.transition={};var o=B.transition;B.transition._updatedFibers=new Set;try{e()}finally{if(B.transition=n,n===null&&o._updatedFibers){var u=o._updatedFibers.size;u>10&&Q("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),o._updatedFibers.clear()}}}var kt=!1,je=null;function xr(e){if(je===null)try{var t=("require"+Math.random()).slice(0,7),n=c&&c[t];je=n.call(c,"timers").setImmediate}catch{je=function(o){kt===!1&&(kt=!0,typeof MessageChannel>"u"&&f("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var u=new MessageChannel;u.port1.onmessage=o,u.port2.postMessage(void 0)}}return je(e)}var fe=0,Ot=!1;function Tt(e){{var t=fe;fe++,$.current===null&&($.current=[]);var n=$.isBatchingLegacy,o;try{if($.isBatchingLegacy=!0,o=e(),!n&&$.didScheduleLegacyUpdate){var u=$.current;u!==null&&($.didScheduleLegacyUpdate=!1,He(u))}}catch(T){throw Ae(t),T}finally{$.isBatchingLegacy=n}if(o!==null&&typeof o=="object"&&typeof o.then=="function"){var p=o,l=!1,y={then:function(T,A){l=!0,p.then(function(F){Ae(t),fe===0?qe(F,T,A):T(F)},function(F){Ae(t),A(F)})}};return!Ot&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){l||(Ot=!0,f("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),y}else{var v=o;if(Ae(t),fe===0){var w=$.current;w!==null&&(He(w),$.current=null);var S={then:function(T,A){$.current===null?($.current=[],qe(v,T,A)):T(v)}};return S}else{var R={then:function(T,A){T(v)}};return R}}}}function Ae(e){e!==fe-1&&f("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),fe=e}function qe(e,t,n){{var o=$.current;if(o!==null)try{He(o),xr(function(){o.length===0?($.current=null,t(e)):qe(e,t,n)})}catch(u){n(u)}else t(e)}}var Ye=!1;function He(e){if(!Ye){Ye=!0;var t=0;try{for(;t<e.length;t++){var n=e[t];do n=n(!0);while(n!==null)}e.length=0}catch(o){throw e=e.slice(t+1),o}finally{Ye=!1}}}var Lr=St,Nr=$r,Ur=Dr,zr={map:ke,forEach:er,count:Xt,toArray:tr,only:rr};a.Children=zr,a.Component=_,a.Fragment=b,a.Profiler=I,a.PureComponent=C,a.StrictMode=j,a.Suspense=z,a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=H,a.act=Tt,a.cloneElement=Nr,a.createContext=nr,a.createElement=Lr,a.createFactory=Ur,a.createRef=Nt,a.forwardRef=sr,a.isValidElement=ce,a.lazy=ir,a.memo=ur,a.startTransition=Fr,a.unstable_act=Tt,a.useCallback=hr,a.useContext=cr,a.useDebugValue=_r,a.useDeferredValue=Er,a.useEffect=dr,a.useId=wr,a.useImperativeHandle=gr,a.useInsertionEffect=yr,a.useLayoutEffect=mr,a.useMemo=vr,a.useReducer=fr,a.useRef=pr,a.useState=lr,a.useSyncExternalStore=Cr,a.useTransition=br,a.version=d,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()}(Mt,Mt.exports)),Mt.exports}process.env.NODE_ENV==="production"?ao():io();const so=async c=>{if(typeof c!="object"||!c)return!1;try{const a={type:"ping"},d=await c.send(a);if(d!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(d)}`);return!0}catch{return!1}},uo=(c,a)=>!!c&&a,W=c=>i.z.nullable(c.optional());i.z.string().trim().min(1,{message:"Cannot be blank"});const co=i.z.object({cde_response_type:i.z.literal("error"),message:i.z.string()}),lo=i.z.enum(["usd","brl"]),un=i.z.object({name:i.z.string(),amount_atom_off:W(i.z.number()),percent_off:W(i.z.number()),currency:W(i.z.string()),duration:i.z.string(),duration_in_months:W(i.z.number())}),fo=i.z.object({amount_subtotal_atom:i.z.number().int(),amount_total_atom:i.z.number().int(),currency:i.z.string(),description:W(i.z.string()),price_id:i.z.string(),billing_interval:W(i.z.string()),billing_interval_count:W(i.z.number().int()),quantity:i.z.number().int()}),po=i.z.record(i.z.string(),i.z.any()),yo=i.z.object({name:i.z.string(),settings:W(po)}),mo=i.z.object({provider:i.z.string(),processor_name:W(i.z.string()),metadata:W(i.z.record(i.z.string(),i.z.any()))}),ho=i.z.object({quantity:i.z.number()}),vo=i.z.object({id:W(i.z.string()),billing_interval:W(i.z.string()),billing_interval_count:W(i.z.number().int()),subscription_items:i.z.array(ho),trial_start:W(i.z.string()),trial_end:W(i.z.string())}),cn=i.z.object({amount_atom:i.z.number()}),go=i.z.object({amount_atom:i.z.number(),amount_atom_considering_discount_applied:i.z.number(),currency:i.z.string(),discount_amount_atoms:i.z.array(cn),subscription_item_id:i.z.string()}),_o=i.z.object({coupon:un}),bo=i.z.object({currency:i.z.string(),discounts:i.z.array(_o),hosted_invoice_url:W(i.z.string()),lines:i.z.array(go),remaining_amount_atom:i.z.number(),tax_amount_atom:i.z.number(),total_amount_atom:i.z.number(),total_discount_amount_atoms:i.z.array(cn)}),ln=i.z.object({created:i.z.array(vo),invoices:i.z.array(bo)}),fn=i.z.object({preview:ln,preview_post_trial:W(ln),coupons:i.z.array(un)}),pn=i.z.object({status:i.z.literal("open"),token:i.z.string(),email:W(i.z.string()),line_items:i.z.array(fo),amount_subtotal_atom:i.z.number().int(),amount_total_atom:i.z.number().int(),brand:yo,subs_preview:W(fn),methods_available:i.z.array(mo)}),dn=i.z.discriminatedUnion("mode",[i.z.object({mode:i.z.literal("setup"),currency:i.z.nullable(i.z.undefined())}).extend(pn.shape),i.z.object({mode:i.z.enum(["payment","subscription"]),currency:lo}).extend(pn.shape)]),Eo=i.z.object({status:i.z.literal("complete")}),wo=i.z.object({status:i.z.literal("expired")});i.z.union([dn,Eo,wo]),i.z.object({logo:i.z.string(),icon:i.z.string(),primary_color:i.z.string(),secondary_color:i.z.string()}),i.z.object({invoice_urls:i.z.array(i.z.string()),subscription_ids:i.z.array(i.z.string()),customer_id:i.z.string()}),i.z.object({payment_method_id:i.z.string()}),i.z.object({id:i.z.string(),return_url:i.z.string()});const Co=i.z.object({type:i.z.string(),loc:i.z.array(i.z.string()),msg:i.z.string(),url:i.z.string()});i.z.array(Co),i.z.object({required_user_actions:i.z.array(i.z.record(i.z.string(),i.z.any()))}),i.z.object({required_user_actions:i.z.array(i.z.record(i.z.string(),i.z.any())),cc_pm_id:i.z.string()});const Lt=async(c,a,d)=>{const m=await c.send(a);if(Ro(m))throw new Error(`[cde-client] Error querying CDE: ${m.message}`);if(!So(m,d)){const g=d.safeParse(m);throw g.success?new Error("Invalid state"):g.error}return m},So=(c,a)=>a.safeParse(c).success,Ro=c=>co.safeParse(c).success,ko=async(c,a)=>await Lt(c,{type:"get_checkout_preview",payload:a},fn),yn=async c=>await Lt(c,{type:"get_prefill",payload:{}},dn),Oo=async(c,a)=>await Lt(c,{type:"confirm_payment_flow",payload:a},Gn);class To{constructor(a){this.formInstance=a,this.config=a.config,this.formId=a.formId,this.eventTargets={},this.nonces=new Set,this.tokenizedData=null,this.tokenized=0,this.connectionManager=a.getConnectionManager()}setTokenizedData(a){this.tokenizedData=a}handleMessage(a){if(a.origin!==this.formInstance.config.baseUrl||!a.source)return;const d=oo(JSON.parse(a.data));if(!this.validateEvent(d))return;const{elementId:g,payload:b}=d;switch(b.type){case"LAYOUT":this.handleLayoutEvent(b);break;case"FOCUS":this.handleFocusEvent(g);break;case"BLUR":this.handleBlurEvent(g);break;case"CHANGE":this.handleChangeEvent(g);break;case"LOADED":this.handleLoadedEvent(a.source,g,b);break;case"TOKENIZE_STARTED":this.handleTokenizeStartedEvent();break;case"PAYMENT_FLOW_STARTED":this.handlePaymentFlowStartedEvent(b,a.source,g);break;case"TOKENIZE_SUCCESS":this.handleTokenizeSuccessEvent(a.source,g,b);break;case"CHECKOUT_SUCCESS":this.handleCheckoutSuccessEvent(b);break;case"SETUP_PAYMENT_METHOD_SUCCESS":this.handleSetupPaymentMethodSuccessEvent(b);break;case"LOAD_ERROR":this.handleLoadErrorEvent(b);break;case"VALIDATION_ERROR":this.handleValidationErrorEvent(b,g);break;case"TOKENIZE_ERROR":case"CHECKOUT_ERROR":this.handleErrorEvent(b);break}}validateEvent(a){return a.formId!==this.formInstance.formId||!a.elementId||this.nonces.has(a.nonce)?!1:(this.nonces.add(a.nonce),!0)}handleLayoutEvent(a){const d=a.height?`${a.height}px`:"100%";this.formInstance.setFormHeight(d)}handleFocusEvent(a){this.config.onFocus&&this.config.onFocus(a)}handleBlurEvent(a){this.config.onBlur&&this.config.onBlur(a)}handleChangeEvent(a){this.config.onChange&&this.config.onChange(a)}handleLoadedEvent(a,d,m){this.eventTargets[d]=a,this.formInstance.sessionId||(this.formInstance.sessionId=m.sessionId),this.config.onLoad&&this.config.onLoad(m.totalAmountAtoms,m.currency),this.formInstance.checkoutPaymentMethods=m.checkoutPaymentMethods}handleTokenizeStartedEvent(){this.formInstance.config.onCheckoutStarted&&this.formInstance.config.onCheckoutStarted()}async handlePaymentFlowStartedEvent(a,d,m){var j;if(!this.tokenizedData)throw new Error("tokenizedData not populated");const g=this.connectionManager.getConnection(),b=async()=>{var q;const I=a.nextActionMetadata.type;if(I!==void 0)if(I==="stripe_3ds")await ro(a);else if(I==="stripe_payment_request"){if(!this.formInstance.getStripePm())throw new Error("Stripe PM not set");await to(a,this.formInstance.getStripePm())}else throw new Error(`Unknown next action type: ${I}`);const x=await yn(g);if(x.mode==="setup"){const{payment_methods:U}=await Oo(g,{secure_token:x.token,existing_cc_pm_id:(q=this.tokenizedData)==null?void 0:q.existingCCPMId});if(U.length!==1)throw new Error(`Expected exactly one payment method, got ${U.length}`);return this.tokenized=0,this.formInstance.checkoutFired=!1,this.formInstance.config.onSetupPaymentMethodSuccess&&this.formInstance.config.onSetupPaymentMethodSuccess(U[0].id),{proceedToCheckout:!1}}else return{proceedToCheckout:!0}};try{const{proceedToCheckout:I}=await b();if(!I)return;let x;if(this.tokenizedData.checkoutPaymentMethod.provider==="credit_card"&&(x=(j=a.startPFMetadata)==null?void 0:j.cc_pm_id,!x))throw new Error("CC PM ID not found");on(d,this.formInstance.formId,m,{...this.tokenizedData,type:"CHECKOUT",doNotUseLegacyCCFlow:!0,existingCCPMId:x},this.formInstance.config.baseUrl),this.formInstance.checkoutFired=!0,this.tokenizedData=null,this.formInstance.config.onCheckoutStarted&&this.formInstance.config.onCheckoutStarted()}catch(I){const x=Gr(I);this.formInstance.checkoutFired=!1,this.formInstance.config.onCheckoutError&&this.formInstance.config.onCheckoutError(x)}}handleTokenizeSuccessEvent(a,d,m){if(!this.tokenizedData)throw new Error("Tokenized data not found");const g=this.tokenized+1,b=g===Object.keys(this.eventTargets).length;!this.formInstance.checkoutFired&&(b||m.isReadyForCheckout)?(this.tokenizedData.type=this.tokenizedData.type===G.enum.TOKENIZE?G.enum.CHECKOUT:G.enum.START_PAYMENT_FLOW,this.postEventToFrame(a,d,this.tokenizedData),this.tokenizedData=null):this.tokenized=g}handleCheckoutSuccessEvent(a){this.formInstance.config.onCheckoutSuccess&&this.formInstance.config.onCheckoutSuccess(a.invoiceUrls,a.subscriptionIds,a.customerId)}handleSetupPaymentMethodSuccessEvent(a){this.formInstance.config.onSetupPaymentMethodSuccess&&this.formInstance.config.onSetupPaymentMethodSuccess(a.paymentMethodId)}handleLoadErrorEvent(a){this.formInstance.config.onLoadError&&this.formInstance.config.onLoadError(a.message)}handleValidationErrorEvent(a,d){this.formInstance.config.onValidationError&&this.formInstance.config.onValidationError(a.elementType,a.errors,d)}handleErrorEvent(a){var d;if(a.message==="3DS_REQUIRED"){const m=(d=this.formInstance.checkoutPaymentMethods)==null?void 0:d.find(g=>g.provider==="credit_card");if(!this.formInstance.sessionId||!this.formInstance.formTarget||!this.config.onValidationError||!m)return;for(const[g,b]of Object.entries(this.eventTargets)){if(!b)continue;const j=At(G.enum.START_PAYMENT_FLOW,this.formInstance.sessionId,document.querySelector(this.formInstance.formTarget)??document.body,this.config.onValidationError,{...m,processor_name:"stripe"},!1);if(j){this.formInstance.checkoutFired=!0,this.tokenizedData=j,this.postEventToFrame(b,g,j);break}}}else this.formInstance.checkoutFired=!1,this.formInstance.config.onCheckoutError&&this.formInstance.config.onCheckoutError(a.message)}handleFormSubmit(){var m;if(!this.formInstance.sessionId||!((m=this.formInstance.checkoutPaymentMethods)!=null&&m.length)||!this.config.onValidationError)return;const a=this.formInstance.checkoutPaymentMethods.find(g=>g.provider==="credit_card");if(!a)throw new Error("Card not available as a payment method in checkout");const d=At(G.enum.TOKENIZE,this.formInstance.sessionId,document.querySelector(this.formInstance.formTarget)??document.body,this.config.onValidationError,a,!1);if(!d)throw new Error("Error constructing tokenize data");for(const[g,b]of Object.entries(this.eventTargets))b&&this.postEventToFrame(b,g,d);this.tokenizedData=d}postEventToFrame(a,d,m){on(a,this.formId,d,m,this.config.baseUrl)}}async function Po(c){const d=await hn.connectToChild({iframe:c,debug:!0}).promise,m=await so(d);if(!uo(d,m))throw new Error("Got invalid CDE connection object");return d}class Io{constructor(){this.connections=new Map}addConnection(a,d){this.connections.set(a,d)}getConnection(){const a=this.connections.values().next().value;if(!a)throw new Error("Connection not found");return a}}async function jo(c,a,d,m,g,b){const j={apple_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}},google_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}}};for(const I of["apple_pay","google_pay"])try{const x=a.find(z=>z.provider===I&&z.processor_name==="stripe");if(!x)throw new Error(`${I} is not available as a checkout method`);const q=eo(x.metadata),U=await Ao(q,I);j[I]={isLoading:!1,isAvailable:U,startFlow:z=>Mo(d,c.checkoutSecureToken,document.querySelector(c.formTarget),x,q,m,g,b,z)}}catch{j[I]={isLoading:!1,isAvailable:!1,startFlow:async()=>{}}}return j}async function Ao(c,a){const m=await tn(c,1e3,"usd"),g=await m.canMakePayment();if(m.abort(),!g)throw new Error(`Cannot make payment with ${a} for this session`);return g[a==="apple_pay"?"applePay":"googlePay"]}async function Mo(c,a,d,m,g,b,j,I,x){try{const q=nn(d,{});if(!Do(d,j,m))return;const z=(await yn(c)).mode==="setup",ee=await $o(z,x,q,c,a),Y=await tn(g,ee.amountAtom,ee.currency,z);await Y.canMakePayment(),Y.show();const J=await Xn(Y);b(J,m)}catch(q){I(Gr(q))}}function Do(c,a,d){return!!At(G.enum.START_PAYMENT_FLOW,"dummy",c,a??(()=>{}),d,!1)}async function $o(c,a,d,m,g){if(c)return(a==null?void 0:a.amountToDisplayForSetupMode)??{amountAtom:0,currency:"usd"};a!=null&&a.amountToDisplayForSetupMode;const b=ne.safeParse(d[Ke.PROMOTION_CODE]);if(!b.success)throw new Error(`Unknown promo code type: ${b.error.message}`);const j=await ko(m,{secure_token:g,promotion_code:b.data}),I=new Set(j.preview.invoices.map(U=>U.currency));if(I.size!==1)throw new Error(`Expected exactly one currency, got ${I.size}`);const x=I.values().next().value;return{amountAtom:j.preview.invoices.reduce((U,z)=>U+z.remaining_amount_atom,0),currency:x}}class Fo{constructor(a){this.config={...a,baseUrl:a.baseUrl??"https://cde.getopenpay.com"},this.elements=null,this.formId=`opjs-form-${window.crypto.randomUUID()}`,this.referer=window.location.origin,this.formTarget=a.formTarget??"body",this.formProperties={height:"1px"},this.sessionId=null,this.checkoutPaymentMethods=[],this.checkoutFired=!1,this.stripePm=void 0,this.paymentRequests=this.initPaymentRequests(),this.connectionManager=new Io,this.eventHandler=new To(this),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler))}getStripePm(){return this.stripePm}getConnectionManager(){return this.connectionManager}setFormHeight(a){this.formProperties.height=a,this.elements&&Object.values(this.elements).forEach(d=>{d.node.style.height=a})}initPaymentRequests(){return{apple_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}},google_pay:{isLoading:!0,isAvailable:!1,startFlow:async()=>{}}}}createElement(a,d={}){if(!this.config)throw new Error("OpenPay form not initialized");const m=document.createElement("iframe"),g=this.buildQueryString(d);m.name=`${a}-element`,m.src=`${this.config.baseUrl}/app/v1/${a}-element/?${g.toString()}`,m.style.border="none",m.style.width="100%";const b={type:a,node:m,mount:j=>{var I;return(I=document.querySelector(j))==null?void 0:I.appendChild(m)}};return this.elements?this.elements[a]=b:(this.elements={[a]:b},this.connectToElement(b)),b}buildQueryString(a){const d=new URLSearchParams;return d.append("referer",this.referer),d.append("formId",this.formId),a.styles&&d.append("styles",no(a.styles)),d.append("secureToken",this.config.checkoutSecureToken),d}connectToElement(a){Po(a.node).then(d=>{this.connectionManager.addConnection(a.type,d),this.initializePaymentRequests()}).catch(d=>{})}submit(){this.eventHandler.handleFormSubmit()}async onUserCompletePaymentRequestUI(a,d){if(!(!this.config.onValidationError||!this.sessionId||!this.checkoutPaymentMethods))for(const[m,g]of Object.entries(this.eventHandler.eventTargets??{})){const b={stripePmId:a.paymentMethod.id},j=At(G.enum.START_PAYMENT_FLOW,this.sessionId,document.querySelector(this.formTarget)??document.body,this.config.onValidationError,d,!1,b);if(j){this.stripePm=a,this.checkoutFired=!0,this.eventHandler.setTokenizedData(j),this.eventHandler.postEventToFrame(g,m,j);break}}}onPaymentRequestError(a){this.checkoutFired=!1,this.config.onCheckoutError&&this.config.onCheckoutError(a)}async initializePaymentRequests(){if(!this.config.checkoutSecureToken||!this.checkoutPaymentMethods||!this.formTarget)return;const a=this.connectionManager.getConnection();a&&(this.paymentRequests=await jo(this.config,this.checkoutPaymentMethods,a,this.onUserCompletePaymentRequestUI.bind(this),this.config.onValidationError,this.onPaymentRequestError.bind(this)),this.config.onPaymentRequestLoad&&this.config.onPaymentRequestLoad(this.paymentRequests))}destroy(){for(const a of Object.values(this.elements??{}))a.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler))}}ve.FieldName=Ke,ve.OpenPayForm=Fo,Object.defineProperty(ve,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED