@getopenpay/openpay-js 0.2.29-alpha.5211859 → 0.2.30

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
@@ -7,7 +7,7 @@ ${t.message}`),t.message)}else return Sr(t.message);if(typeof t=="object")try{re
7
7
  `:`
8
8
  `)+r,o=n+1,n=t.indexOf(`
9
9
  `,o)}while(n!==-1);return s+=t.slice(o),s}const{stdout:On,stderr:Mn}=Di,Rr=Symbol("GENERATOR"),ot=Symbol("STYLER"),Rt=Symbol("IS_EMPTY"),Dn=["ansi","ansi","ansi256","ansi16m"],st=Object.create(null),Fi=(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 r=On?On.level:0;t.level=e.level===void 0?r:e.level},Ui=t=>{const e=(...r)=>r.join(" ");return Fi(e,t),Object.setPrototypeOf(e,Nt.prototype),e};function Nt(t){return Ui(t)}Object.setPrototypeOf(Nt.prototype,Function.prototype);for(const[t,e]of Object.entries(ve))st[t]={get(){const r=rr(this,Or(e.open,e.close,this[ot]),this[Rt]);return Object.defineProperty(this,t,{value:r}),r}};st.visible={get(){const t=rr(this,this[ot],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const Nr=(t,e,r,...n)=>t==="rgb"?e==="ansi16m"?ve[r].ansi16m(...n):e==="ansi256"?ve[r].ansi256(ve.rgbToAnsi256(...n)):ve[r].ansi(ve.rgbToAnsi(...n)):t==="hex"?Nr("rgb",e,r,...ve.hexToRgb(...n)):ve[r][t](...n),$i=["rgb","hex","ansi256"];for(const t of $i){st[t]={get(){const{level:r}=this;return function(...n){const o=Or(Nr(t,Dn[r],"color",...n),ve.color.close,this[ot]);return rr(this,o,this[Rt])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);st[e]={get(){const{level:r}=this;return function(...n){const o=Or(Nr(t,Dn[r],"bgColor",...n),ve.bgColor.close,this[ot]);return rr(this,o,this[Rt])}}}}const Zi=Object.defineProperties(()=>{},{...st,level:{enumerable:!0,get(){return this[Rr].level},set(t){this[Rr].level=t}}}),Or=(t,e,r)=>{let n,o;return r===void 0?(n=t,o=e):(n=r.openAll+t,o=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:o,parent:r}},rr=(t,e,r)=>{const n=(...o)=>Vi(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,Zi),n[Rr]=t,n[ot]=e,n[Rt]=r,n},Vi=(t,e)=>{if(t.level<=0||!e)return t[Rt]?"":e;let r=t[ot];if(r===void 0)return e;const{openAll:n,closeAll:o}=r;if(e.includes("\x1B"))for(;r!==void 0;)e=Li(e,r.close,r.open),r=r.parent;const s=e.indexOf(`
10
- `);return s!==-1&&(e=ji(e,o,n,s)),n+e+o};Object.defineProperties(Nt.prototype,st);const nr=Nt();Nt({level:Mn?Mn.level:0});const Ae=t=>async e=>{var r,n;try{(n=(r=e.formCallbacks.get).onCheckoutStarted)==null||n.call(r),C("checkout_started");const o=await t(e);if(C("checkout_success",{...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=ne(o),i=await so(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),C("checkout_error",{errorMessage:s,errorCode:i})}},Be=t=>async e=>{try{return await t(e)}catch(r){const{err__:n}=F("init-error-catcher"),o=ne(r),s=await so(e.context.anyCdeConnection,o);return n(s,o,r),C("init_flow_error",{errorMessage:o,errorCode:s}),{isAvailable:!1,reason:o,errorCode:s,isLoading:!1}}},F=t=>{const e=(...n)=>{window.console.log(`${nr.green.bold("ojs/")}${nr.bold.gray(`${t}`)} `,...n)},r=(...n)=>{window.console.warn(`${nr.red.bold("ojs/")}${nr.bold.gray(`${t}`)} `,...n)};return{log:e,err:r,log__:e,err__:r}};var Mr=function(t,e){return Mr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Mr(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");Mr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function zi(t,e,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(p){i(p)}}function l(d){try{u(n.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(t,e||[])).next())})}function Ln(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(r=0)),r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function at(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function or(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function sr(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}function it(t){return this instanceof it?(this.v=t,this):new it(t)}function Gi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.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(f){return function(h){return Promise.resolve(h).then(f,p)}}function c(f,h){n[f]&&(o[f]=function(b){return new Promise(function(I,E){s.push([f,b,I,E])>1||l(f,b)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(n[f](h))}catch(b){_(s[0][3],b)}}function u(f){f.value instanceof it?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Bi(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof at=="function"?at(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[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 B(t){return typeof t=="function"}function ar(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Dr=ar(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
10
+ `);return s!==-1&&(e=ji(e,o,n,s)),n+e+o};Object.defineProperties(Nt.prototype,st);const nr=Nt();Nt({level:Mn?Mn.level:0});const Ae=t=>async e=>{var r,n;try{(n=(r=e.formCallbacks.get).onCheckoutStarted)==null||n.call(r),C("checkout_started",{cpm:e.checkoutPaymentMethod});const o=await t(e);if(C("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=ne(o),i=await so(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),C("checkout_error",{cpm:e.checkoutPaymentMethod,errorMessage:s,errorCode:i})}},Be=t=>async e=>{try{return await t(e)}catch(r){const{err__:n}=F("init-error-catcher"),o=ne(r),s=await so(e.context.anyCdeConnection,o);return n(s,o,r),C("init_flow_error",{errorMessage:o,errorCode:s}),{isAvailable:!1,reason:o,errorCode:s,isLoading:!1}}},F=t=>{const e=(...n)=>{window.console.log(`${nr.green.bold("ojs/")}${nr.bold.gray(`${t}`)} `,...n)},r=(...n)=>{window.console.warn(`${nr.red.bold("ojs/")}${nr.bold.gray(`${t}`)} `,...n)};return{log:e,err:r,log__:e,err__:r}};var Mr=function(t,e){return Mr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Mr(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");Mr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function zi(t,e,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(p){i(p)}}function l(d){try{u(n.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(t,e||[])).next())})}function Ln(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(r=0)),r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function at(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function or(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function sr(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}function it(t){return this instanceof it?(this.v=t,this):new it(t)}function Gi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.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(f){return function(h){return Promise.resolve(h).then(f,p)}}function c(f,h){n[f]&&(o[f]=function(b){return new Promise(function(I,E){s.push([f,b,I,E])>1||l(f,b)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(n[f](h))}catch(b){_(s[0][3],b)}}function u(f){f.value instanceof it?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Bi(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof at=="function"?at(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[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 B(t){return typeof t=="function"}function ar(t){var e=function(n){Error.call(n),n.stack=new Error().stack},r=t(e);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Dr=ar(function(t){return function(r){t(this),this.message=r?r.length+` errors occurred during unsubscription:
11
11
  `+r.map(function(n,o){return o+1+") "+n.toString()}).join(`
12
12
  `):"",this.name="UnsubscriptionError",this.errors=r}});function ir(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var Ot=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,r,n,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=at(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(b){e={error:b}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(B(d))try{d()}catch(b){s=b instanceof Dr?b.errors:[b]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=at(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{Un(h)}catch(b){s=s??[],b instanceof Dr?s=sr(sr([],or(s)),or(b.errors)):s.push(b)}}}catch(b){n={error:b}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new Dr(s)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)Un(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(e)}},t.prototype._hasParent=function(e){var r=this._parentage;return r===e||Array.isArray(r)&&r.includes(e)},t.prototype._addParent=function(e){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(e),r):r?[r,e]:e},t.prototype._removeParent=function(e){var r=this._parentage;r===e?this._parentage=null:Array.isArray(r)&&ir(r,e)},t.prototype.remove=function(e){var r=this._finalizers;r&&ir(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),jn=Ot.EMPTY;function Fn(t){return t instanceof Ot||t&&"closed"in t&&B(t.remove)&&B(t.add)&&B(t.unsubscribe)}function Un(t){B(t)?t():t.unsubscribe()}var $n={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Zn={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,sr([t,e],or(r)))},clearTimeout:function(t){var e=Zn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function Vn(t){Zn.setTimeout(function(){throw t})}function zn(){}function cr(t){t()}var Lr=function(t){je(e,t);function e(r){var n=t.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Fn(r)&&r.add(n)):n.destination=Hi,n}return e.create=function(r,n,o){return new Fr(r,n,o)},e.prototype.next=function(r){this.isStopped||this._next(r)},e.prototype.error=function(r){this.isStopped||(this.isStopped=!0,this._error(r))},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(r){this.destination.next(r)},e.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Ot),qi=Function.prototype.bind;function jr(t,e){return qi.call(t,e)}var Yi=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var r=this.partialObserver;if(r.next)try{r.next(e)}catch(n){lr(n)}},t.prototype.error=function(e){var r=this.partialObserver;if(r.error)try{r.error(e)}catch(n){lr(n)}else lr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(r){lr(r)}},t}(),Fr=function(t){je(e,t);function e(r,n,o){var s=t.call(this)||this,i;if(B(r)||!r)i={next:r??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&$n.useDeprecatedNextContext?(c=Object.create(r),c.unsubscribe=function(){return s.unsubscribe()},i={next:r.next&&jr(r.next,c),error:r.error&&jr(r.error,c),complete:r.complete&&jr(r.complete,c)}):i=r}return s.destination=new Yi(i),s}return e}(Lr);function lr(t){Vn(t)}function Wi(t){throw t}var Hi={closed:!0,next:zn,error:Wi,complete:zn},Ur=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Ki(t){return t}function Ji(t){return t.length===0?Ki:t.length===1?t[0]:function(r){return t.reduce(function(n,o){return o(n)},r)}}var Te=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(e,r,n){var o=this,s=Xi(e)?e:new Fr(e,r,n);return cr(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(r){e.error(r)}},t.prototype.forEach=function(e,r){var n=this;return r=Gn(r),new r(function(o,s){var i=new Fr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},t.prototype._subscribe=function(e){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(e)},t.prototype[Ur]=function(){return this},t.prototype.pipe=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Ji(e)(this)},t.prototype.toPromise=function(e){var r=this;return e=Gn(e),new e(function(n,o){var s;r.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},t.create=function(e){return new t(e)},t}();function Gn(t){var e;return(e=t??$n.Promise)!==null&&e!==void 0?e:Promise}function Qi(t){return t&&B(t.next)&&B(t.error)&&B(t.complete)}function Xi(t){return t&&t instanceof Lr||Qi(t)&&Fn(t)}function ec(t){return B(t==null?void 0:t.lift)}function tc(t){return function(e){if(ec(e))return e.lift(function(r){try{return t(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function rc(t,e,r,n,o){return new nc(t,e,r,n,o)}var nc=function(t){je(e,t);function e(r,n,o,s,i,c){var l=t.call(this,r)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){r.error(d)}}:t.prototype._next,l._error=s?function(u){try{s(u)}catch(d){r.error(d)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){r.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;t.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},e}(Lr),oc=ar(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Bn=function(t){je(e,t);function e(){var r=t.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return e.prototype.lift=function(r){var n=new qn(this,this);return n.operator=r,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new oc},e.prototype.next=function(r){var n=this;cr(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=at(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(r)}}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(r){var n=this;cr(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},e.prototype.complete=function(){var r=this;cr(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(r){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,r)},e.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},e.prototype._innerSubscribe=function(r){var n=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?jn:(this.currentObservers=null,c.push(r),new Ot(function(){n.currentObservers=null,ir(c,r)}))},e.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?r.error(s):i&&r.complete()},e.prototype.asObservable=function(){var r=new Te;return r.source=this,r},e.create=function(r,n){return new qn(r,n)},e}(Te),qn=function(t){je(e,t);function e(r,n){var o=t.call(this)||this;return o.destination=r,o.source=n,o}return e.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},e.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},e.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},e.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:jn},e}(Bn),sc={now:function(){return Date.now()},delegate:void 0},ac=function(t){je(e,t);function e(r,n){return t.call(this)||this}return e.prototype.schedule=function(r,n){return this},e}(Ot),Yn={setInterval:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,sr([t,e],or(r)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},ic=function(t){je(e,t);function e(r,n){var o=t.call(this,r,n)||this;return o.scheduler=r,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(r,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=r;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(r,n,o){return o===void 0&&(o=0),Yn.setInterval(r.flush.bind(r,this),o)},e.prototype.recycleAsyncId=function(r,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&Yn.clearInterval(n)},e.prototype.execute=function(r,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(r,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(r,n){var o=!1,s;try{this.work(r)}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 r=this,n=r.id,o=r.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ir(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(ac),Wn=function(){function t(e,r){r===void 0&&(r=t.now),this.schedulerActionCtor=e,this.now=r}return t.prototype.schedule=function(e,r,n){return r===void 0&&(r=0),new this.schedulerActionCtor(this,e).schedule(n,r)},t.now=sc.now,t}(),cc=function(t){je(e,t);function e(r,n){n===void 0&&(n=Wn.now);var o=t.call(this,r,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(r){var n=this.actions;if(this._active){n.push(r);return}var o;this._active=!0;do if(o=r.execute(r.state,r.delay))break;while(r=n.shift());if(this._active=!1,o){for(;r=n.shift();)r.unsubscribe();throw o}},e}(Wn),lc=new cc(ic),uc=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function dc(t){return B(t==null?void 0:t.then)}function pc(t){return B(t[Ur])}function fc(t){return Symbol.asyncIterator&&B(t==null?void 0:t[Symbol.asyncIterator])}function mc(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 hc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var yc=hc();function _c(t){return B(t==null?void 0:t[yc])}function gc(t){return Gi(this,arguments,function(){var r,n,o,s;return Ln(this,function(i){switch(i.label){case 0:r=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,it(r.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,it(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,it(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function vc(t){return B(t==null?void 0:t.getReader)}function wc(t){if(t instanceof Te)return t;if(t!=null){if(pc(t))return bc(t);if(uc(t))return Ec(t);if(dc(t))return kc(t);if(fc(t))return Hn(t);if(_c(t))return Cc(t);if(vc(t))return Sc(t)}throw mc(t)}function bc(t){return new Te(function(e){var r=t[Ur]();if(B(r.subscribe))return r.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ec(t){return new Te(function(e){for(var r=0;r<t.length&&!e.closed;r++)e.next(t[r]);e.complete()})}function kc(t){return new Te(function(e){t.then(function(r){e.closed||(e.next(r),e.complete())},function(r){return e.error(r)}).then(null,Vn)})}function Cc(t){return new Te(function(e){var r,n;try{for(var o=at(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()})}function Hn(t){return new Te(function(e){Pc(t,e).catch(function(r){return e.error(r)})})}function Sc(t){return Hn(gc(t))}function Pc(t,e){var r,n,o,s;return zi(this,void 0,void 0,function(){var i,c;return Ln(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),r=Bi(t),l.label=1;case 1:return[4,r.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(s=r.return)?[4,s.call(r)]:[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 Ac(t,e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){r(),o?t.add(this.schedule(null,n)):this.unsubscribe()},n);if(t.add(s),!o)return s}function Tc(t,e){var r=B(t)?t:function(){return t},n=function(o){return o.error(r())};return new Te(n)}var xc=ar(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Ic(t,e){return new Promise(function(r,n){var o=!1,s;t.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?r(s):n(new xc)}})})}function Rc(t){return t instanceof Date&&!isNaN(t)}var Nc=ar(function(t){return function(r){r===void 0&&(r=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=r}});function Oc(t,e){var r=Rc(t)?{first:t}:typeof t=="number"?{each:t}:t,n=r.first,o=r.each,s=r.with,i=s===void 0?Mc:s,c=r.scheduler,l=c===void 0?lc:c,u=r.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return tc(function(p,_){var f,h,b=null,I=0,E=function(N){h=Ac(_,l,function(){try{f.unsubscribe(),wc(i({meta:d,lastValue:b,seen:I})).subscribe(_)}catch(x){_.error(x)}},N)};f=p.subscribe(rc(_,function(N){h==null||h.unsubscribe(),I++,_.next(b=N),o>0&&E(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),b=null})),!I&&E(n!=null?typeof n=="number"?n:+n-l.now():o)})}function Mc(t){throw new Nc(t)}class Mt{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,r)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:r},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 r=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),r.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"&&ur(this._current);const r={first:e.timeoutSec*1e3,with:()=>Tc(()=>new Error(e.timeoutErrMsg))};return Ic(this._subject.pipe(Oc(r)))},this._current={status:"initial",isSuccess:!1},this._subject=new Bn}get current(){return this._current}}const Kn=a.enum(["dev","stg","prod"]),Dc={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Lc=t=>Dc[t],jc=async t=>{try{const e=await fetch(new URL("/health/environment",t)).then(r=>r.json());return Kn.parse(e.environment)}catch{return Kn.Values.prod}};function ur(t){throw new Error(`Unhandled case: ${t}`)}const Jn=(t,e)=>Object.fromEntries(Object.entries(t).filter(([r])=>!e.includes(r))),$=()=>{if(!(typeof window>"u"))return window},$r=new Mt,Qn="op_metrics_queue",Fc=3,Uc=3,$c=1e3,{log__:dr}=F("op-metrics");class Zc{constructor(){var e,r;this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{dr("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{dr("Network online, processing metrics queue"),this.processQueue()},this.loadQueueFromStorage(),(e=$())==null||e.addEventListener("offline",this.offlineListener),(r=$())==null||r.addEventListener("online",this.onlineListener)}addEvent(e,r,n){const o={eventName:e,properties:r||{},contextProperties:n||{},nonce:er(),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,r;try{const n=(r=(e=$())==null?void 0:e.localStorage)==null?void 0:r.getItem(Qn);n&&(this.queue=JSON.parse(n))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){var e;(e=$())==null||e.localStorage.setItem(Qn,JSON.stringify(this.queue))}scheduleBatchProcessing(){const e=$();e&&navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=e.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},$c))}cancelBatchProcessing(){var e;this.batchTimeout&&((e=$())==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=$r.getValueIfLoadedElse(void 0);if(!e){dr("Metrics context not available, will retry later");return}const r=this.queue.slice(0,Uc);try{const n={events:r.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=Lc(e.environment),s=new URL("/metrics/public/capture",o);(await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok?(this.queue=this.queue.slice(r.length),this.saveQueueToStorage()):this.handleFailedBatch(r)}catch(n){dr("Error sending metrics batch:",n),this.handleFailedBatch(r)}}handleFailedBatch(e){e.forEach(n=>{n.attemptCount++});const r=e.filter(n=>n.attemptCount<Fc);this.queue=this.queue.slice(e.length),this.queue=[...r,...this.queue],this.saveQueueToStorage()}cleanup(){var e,r;(e=$())==null||e.removeEventListener("offline",this.offlineListener),(r=$())==null||r.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const Xn=new Zc,C=(t,e,r)=>{Xn.addEvent(t,e,r)},eo=t=>{const e=ne(t.reason);C("unhandled_rejection_error",{error_message:e,error_name:t.reason})},to=t=>{var r,n;const e=ne(t.error);C("uncaught_error",{error_message:e,error_name:(r=t.error)==null?void 0:r.name,error_stack:(n=t.error)==null?void 0:n.stack,file_name:t.filename,line_number:t.lineno,column_number:t.colno})},Vc=()=>{var t,e;(t=$())==null||t.addEventListener("error",to),(e=$())==null||e.addEventListener("unhandledrejection",eo)},zc=()=>{var t,e;(t=$())==null||t.removeEventListener("error",to),(e=$())==null||e.removeEventListener("unhandledrejection",eo)};(zo=$())==null||zo.addEventListener("beforeunload",()=>{Xn.processQueue()});class ro extends Ri{constructor(e){const r=`${e.message}`;super(r),this.response=e}get originalErrorMessage(){return this.response.message}}const K=async(t,e,r,n)=>{n&&C(n,{...e});const o=await t.send(e);if(Bc(o))throw new ro(o);if(!Gc(o,r)){const s=r.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",r,"Actual:",o),s.error)}return n&&C(n,{...o}),o},Gc=(t,e)=>e.safeParse(t).success,Bc=t=>ci.safeParse(t).success,qc=async(t,e)=>await K(t,{type:"get_checkout_preview",payload:e},Cn),q=async t=>await K(t,{type:"get_prefill",payload:{}},Pn),ct=async(t,e)=>await K(t,{type:"v2_start_payment_flow",payload:e},Tn,"start_payment_flow"),Yc=async(t,e)=>await K(t,{type:"start_payment_flow_for_cc",payload:e},ki,"start_payment_flow_for_cc"),Wc=async(t,e)=>{C("start_payment_flow_for_pr",{...e});const r=await K(t,{type:"start_payment_flow_for_pr",payload:e},Tn);return C("start_payment_flow_for_pr_result",{...r}),r},ce=async(t,e)=>await K(t,{type:"confirm_payment_flow",payload:e},Ca,"confirm_payment_flow"),Hc=async(t,e)=>await K(t,{type:"finalize_setup_payment_method",payload:e},An,"finalize_setup_payment_method"),Kc=async(t,e)=>await K(t,{type:"check_if_popup_window_verified",payload:e},ka,"check_if_popup_window_verified"),Jc=async(t,e,r)=>{const n=await qc(t,{secure_token:e,promotion_code:r}),o=new Set(n.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=Ai(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},lt=async(t,e,r,n)=>{if(r)return{amountAtom:0,currency:"usd"};{n=n||void 0;const o=await Jc(t,e,n);return{amountAtom:o.amountAtom,currency:o.currency}}},Qc=async(t,e)=>{if(t.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(t.values()).map(n=>K(n,{type:"tokenize_card",payload:e},wa)))},no=async(t,e)=>await K(t,{type:"checkout_card_elements",payload:e},Pr,"checkout_card_elements"),Xc=async(t,e)=>await K(t,{type:"setup_payment_method",payload:e},An,"setup_checkout"),Zr=async(t,e)=>await K(t,{type:"checkout",payload:e},Pr,"perform_checkout"),oo=1e3,el=async(t,e)=>{console.log(e);const n=await vn({iframe:t,debug:!0,timeout:oo,childOrigin:"*"}).promise,o=await K(n,{type:"ping-3ds-status"},ba);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Vr=async(t,e)=>await K(t,{type:"prepare_payment_flow",payload:e},Si,"prepare_payment_flow"),so=async(t,e)=>{try{return(await K(t,{type:"get_standardized_error_code",payload:{message:e}},Ci)).error_code}catch(r){return console.error("[cde-client] Error during getStandardizedErrorCode:",ne(r)),"PAYMENT_FAILED_GENERIC"}},tl=async(t,e)=>await K(t,{type:"set_user_device_token",payload:{device_token:e}},Pi),{log__:Qu,err__:rl}=F("common"),Dt=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}},le=(t,e)=>{const r=t.find(n=>e.safeParse(n).success);if(!r)throw rl("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(r)},nl=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}),pr=async t=>{const{log__:e}=F(t.logPrefix),r=await q(t.anyCdeConnection),n=Dt(t.confirmResult);if(r.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await Hc(t.anyCdeConnection,{secure_token:r.token,pm_id:n.payment_method_id})};{e("Doing checkout...");const o={secure_token:r.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},customer_email:t.requiredFormFields[m.EMAIL],customer_zip_code:t.requiredFormFields[m.ZIP_CODE],customer_country:t.requiredFormFields[m.COUNTRY],promotion_code:t.requiredFormFields[m.PROMOTION_CODE],line_items:r.line_items,total_amount_atom:r.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,use_confirmed_pm_id:n.payment_method_id};return{mode:"checkout",result:await Zr(t.anyCdeConnection,o)}}},{log__:ao,err__:io}=F("common-cc"),Fe=(t,e,r)=>{if(r){ao(`Received default field values: ${JSON.stringify(r)}`);for(const[o,s]of Object.entries(r))t[o]||(t[o]=s)}const n=xt.safeParse(t);if(!n.success){const o=n.error.format(),s=pn(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw io("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return n.data},ol=(t,e)=>{for(const r of t)if(r.success===!1)throw r.errors.forEach(n=>{const o=un.safeParse(n.elementType);if(!o.success)io(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const s=o.data;e(s,n.errors)}}),ao(`Error tokenizing card: got validation errors: ${JSON.stringify(r.errors)}`),new Error("Got validation errors while tokenizing card")},co="ojs-stripe-link-btn",{log__:Y,err__:sl}=F("stripe-link"),al=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),il=a.array(a.object({our_existing_pm_id:a.string()})).length(1),cl=Be(async({context:t,formCallbacks:e})=>{const r=t.customInitParams.stripeLink;Y("Checking if there are any CPMs for Stripe Link...");const n=le(t.checkoutPaymentMethods,al);Y("Starting stripe link flow...");const o=t.anyCdeConnection,s=await q(o),i=s.mode==="setup";Y("Creating stripe elements...");const c=await lt(o,s.token,i,void 0),{elements:l,stripe:u}=await Ta(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});Y("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:r==null?void 0:r.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),p=()=>{d.mount(`#${co}`)},_=()=>{d.unmount()};return r!=null&&r.doNotMountOnInit?Y("NOT mounting stripe link button (doNotMountOnInit is true)"):(Y("Mounting stripe link button..."),p()),d.on("click",async f=>{if(Y("Stripe Link button clicked"),r!=null&&r.overrideLinkSubmit&&!await r.overrideLinkSubmit()){Y("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{Y("Stripe Link window confirmed",f);const h=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});h.error?(sl("error",h.error),e.get.onCheckoutError(h.error.message??"Stripe Link unknown error")):(Y("paymentMethod",h.paymentMethod),z.stripeLink.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{stripePM:h.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:_,waitForButtonToMount:async()=>await dl(co)}}}),ll=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{Y("Running Stripe Link flow...");const s=t.anyCdeConnection;Y("Merging PM fields with form fields...");const i=ul(r,o.stripePM),c=Fe(i,n.get.onValidationError);C("billing_details_received",{...c}),Y("Starting payment flow...");const l=await ct(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[m.EMAIL],new_customer_first_name:c[m.FIRST_NAME],new_customer_last_name:c[m.LAST_NAME],new_customer_address:{zip_code:c[m.ZIP_CODE],country:c[m.COUNTRY]}});Y("Start payment flow response",l);const d=il.parse(l.required_user_actions)[0].our_existing_pm_id,p=await q(s);if(p.mode==="setup"){Y("Doing payment setup...");const _=await ce(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:Dt(_)}}else{Y("Doing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:c[m.EMAIL],customer_zip_code:c[m.ZIP_CODE],customer_country:c[m.COUNTRY],promotion_code:c[m.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zr(s,_)}}}),ul=(t,e)=>{var l,u,d,p,_;const r={...t},[n,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;r[m.EMAIL]=r[m.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",r[m.ZIP_CODE]=r[m.ZIP_CODE]||((p=e.billing_details.address)==null?void 0:p.postal_code)||"00000",r[m.COUNTRY]=r[m.COUNTRY]||((_=e.billing_details.address)==null?void 0:_.country)||"US";const i=r[m.FIRST_NAME]||n||"",c=r[m.LAST_NAME]||s||"";return i||c?(r[m.FIRST_NAME]=i,r[m.LAST_NAME]=c):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]=""),Y("Final form inputs:",r),r},dl=t=>new Promise(e=>{const r=()=>{const n=document.getElementById(t);n?e(n):requestAnimationFrame(r)};r()}),pl="@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}",lo=t=>{const e=document.createElement("template");e.innerHTML=`
13
13
  <style>
@@ -22,4 +22,4 @@ ${t.message}`),t.message)}else return Sr(t.message);if(typeof t=="object")try{re
22
22
  `;const r=document.createElement("div"),n=r.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const o=n.querySelector("#three-ds-iframe"),s=n.querySelector(".cancel-button");return document.body.appendChild(r),{host:r,iframe:o,cancelButton:s}};function fl(t,e,r){const n=async()=>{try{const s=await el(t,r);s&&(clearInterval(o),e(s))}catch{}};n();const o=setInterval(n,oo);return o}function ml({elements:t,pollingInterval:e,resolve:r}){const n=()=>{clearInterval(e),t.host.remove(),r({status:V.CANCELLED})};return t.cancelButton.addEventListener("click",n),()=>{t.cancelButton.removeEventListener("click",n)}}async function fr(t){const{url:e,baseUrl:r}=t,n=lo(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{n.host.remove()},1e3),o(l),c==null||c()},i=fl(n.iframe,s,new URL(r).origin),c=ml({elements:n,pollingInterval:i,resolve:o})})}const uo=async t=>{const e=await fr(t);if(e.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===V.FAILURE)throw new Error("3DS verification failed");return e.status!==V.SUCCESS&&ur(e.status),{href:e.href}},hl=(t,e)=>{const r=window.open(e,"_blank");if(!r)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return r},yl=async(t,e,r,n)=>{const{err__:o}=F("popup-verify");return new Promise((s,i)=>{const c=hl(t,n),l=setInterval(async()=>{try{const u=await Kc(e,r);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(ne(u)),clearInterval(l),i(ne(u))}},1e3)})},{log__:_l,err__:po}=F("pockyt-cc"),gl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),vl=t=>{const e=gl.safeParse(t);if(!e.success){const r="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw po(n),new Error(r)}return e.data},fo=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return _l(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const r="Error verifying 3DS verification result.";throw po(r,`Resulting URL: ${t}.
23
23
  Error: ${ne(e)}`),new Error(r)}},wl=(t,e)=>new URL(t).searchParams.get(e),bl=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,El=async(t,e)=>{const r=vl(e),n=await uo({url:r["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:fo(n.href??""),transaction_no:r["op-pockyt-txn-no"],reference_no:r["op-pockyt-ref-no"]}}},{log__:kl,err__:zr}=F("airwallex-cc"),Cl=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),Sl=t=>{const e=Cl.safeParse(t);if(!e.success){const r="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw zr(n),new Error(r)}return e.data},Pl=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,Al=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 kl(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const r="Error verifying Airwallex 3DS verification result.";throw zr(r,`Resulting URL: ${t}.
24
24
  Error: ${ne(e)}`),new Error(r)}},Tl=async(t,e)=>{const r=Sl(e),n=await uo({url:r["op-airwallex-3ds-url"],baseUrl:t}),o=Al(n.href??""),s=r["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 zr(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:r["op-airwallex-consent-id"]}}},mo=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()})}),ho=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()})}),xl=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),Il=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__:ut,err__:Lt}=F("adyen-cc"),Rl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":xl,"op-adyen-action":a.string()}),yo="Unable to process your credit card. Please contact support for assistance.",Nl=t=>{const e=Rl.safeParse(t);if(!e.success)throw Lt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(yo);return e.data},Ol=t=>JSON.parse(t),_o=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Ml=async()=>{ut("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)_o()||await Ar(500);if(!_o())throw Lt("Adyen SDK not loaded properly"),new Error(yo);return ut("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},Dl=t=>{const{headers:e,locale:r,countryCode:n,component:o,host:s,cancelButton:i}=t,c=Ol(e["op-adyen-action"]);return ut(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{ut("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Lt("Authentication failed. Result:",h),l({status:V.FAILURE,cleanup:u})},p=h=>{Lt("Adyen error:",h),l({status:V.FAILURE,cleanup:u})},_=()=>{l({status:V.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,b,I)=>{s.remove(),l({status:V.SUCCESS,additionalDetails:h,cleanup:u})};Ml().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:r,countryCode:n,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},Ll=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,r=t??e,n=Il.safeParse(r);return n.success?(ut(`Resolved locale: ${n.data}`),n.data):(Lt(`Resolved invalid locale: ${r}. Defaulting to en-US.`),"en-US")},jl=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Fl=async(t,e,r)=>{const n=Nl(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=lo("http://example.com");i.replaceWith(o);const l=await Dl({headers:n,locale:Ll(r),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===V.FAILURE)throw new Error("3DS verification failed");if(l.status===V.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===V.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return ut("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else ur(l.status)},{log__:L,err__:go}=F("common-cc"),{log__:vo}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Ul=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var u;L("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await q(s);C("common_cc_flow_started",{...e,prefill:i}),L(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=Fe(r,n.get.onValidationError);C("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{L(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await Qc(o.currentCdeConnections,{session_id:t.elementsSessionId});if(ol(d,n.get.onValidationError),i.mode==="setup"){L(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await Xc(s,l);return L(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{L(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const p=await no(s,l);return L("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof ro&&d.originalErrorMessage.includes("3DS_REQUIRED")){L("├ Card requires 3DS, starting non-legacy payment flow"),L("Received 3DS error response headers:",d.response.headers),C("3ds_required",{...e,...d.response.headers});const p=bl(d.response.headers);if(p){L("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const E=await El(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=E}if(Pl(d.response.headers)){L("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const E=await Tl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=E}if(jl(d.response.headers)){L("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const E=await Fl(r[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=E}const h=await Yc(s,l);L("├ Payment flow result:",h);const b=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?L("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):b?(L("├ Using stripe 3DS flow"),await Gl(h)):(L("├ Using common 3DS flow"),await zl(h,t.baseUrl));const I=h.cc_pm_id;if(i.mode==="setup"){L(`├ Confirming payment flow [cc_pm_id: ${I}]`);const E=await ce(s,{secure_token:i.token,existing_cc_pm_id:I});L("├ Confirm payment flow result received Result:",E);const N=Dt(E);return L(`╰ Setup completed successfully [PM ID: ${N.payment_method_id}]`),{mode:"setup",result:N}}else{L(`├ Checking out after 3DS flow [Flow: ${b?"legacy":"new"}]`);const E=await no(s,{...l,existing_cc_pm_id:I,do_not_use_legacy_cc_flow:b});return L("╰ Checkout completed successfully."),{mode:"checkout",result:E}}}throw go("╰ Error checking out card info in CDE"),go(d),d}}),$l=t=>{const e=t.required_user_actions.find(r=>r.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Sa.parse(e)},Zl=["airwallex_payment_consent","adyen"],Vl=t=>{const e=t.required_user_actions.find(r=>Zl.includes(r.type));if(!e)throw new Error("No common 3DS action found");return Ea.parse(e)},zl=async(t,e)=>{const r=Vl(t);if(r.redirect_url==="3DS_COMPLETE"){L("├ 3DS flow completed successfully"),C("3ds_complete");return}L(`├ Using common 3DS flow [URL: ${r.redirect_url}]`),C("3ds_redirect",{...r});const{status:n}=await fr({url:r.redirect_url,baseUrl:e});if(L(`╰ 3DS verification completed [Status: ${n}]`),n===V.CANCELLED)throw C("3ds_cancelled"),new Error("3DS verification cancelled");if(n===V.FAILURE)throw C("3ds_failure"),new Error("3DS verification failed")},Gl=async t=>{const e=$l(t);C("3ds_stripe_redirect",{...e}),vo(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Na(e),C("3ds_stripe_complete"),vo("╰ Stripe 3DS flow completed successfully")},ue=a.enum(["stripe","airwallex","authorize_net"]);ue.Enum.stripe;const wo=({scriptId:t,src:e,checkLoadedFn:r})=>{const n=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);r()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{n.abort(),o()},{signal:n.signal}),i.addEventListener("error",()=>{n.abort(),s("Failed to load the script")},{signal:n.signal})})},{log__:X,err__:Bl}=F("stripe-pr"),ql=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()})}),Yl=Be(async({context:t,formCallbacks:e})=>{X("Checking if there are any CPMs for Stripe PR...");const r=le(t.checkoutPaymentMethods,ql);X("Initializing Stripe PR flow...");const n=t.anyCdeConnection,o=await q(n),s=o.mode==="setup";X("Getting initial preview amount");const i=await lt(n,o.token,s,void 0),c=await xa(r.metadata.stripe_pk,i.amountAtom,i.currency,s);X("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return Bl("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};X("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>z.stripePR.run({context:t,checkoutPaymentMethod:Ut(t.checkoutPaymentMethods,d),nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:ue.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:ue.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),Wl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o,initResult:s})=>{if(X("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const h=o.overridePaymentRequest;X("Overriding PR amount with",h),Kl(c,h.amount,h.pending,h.applePayPaymentRequest,h.label)}X("Showing PR dialog..."),c.show();const l=await Ia(c);X("Stripe PM added event:",l),X("Merging PM fields with form fields...");const u=Hl(r,l),d=Fe(u,n.get.onValidationError);C("billing_details_received",{...d}),X("PR dialog finished. Starting payment flow...",d);const p=await Wc(i,{fields:d,checkoutPaymentMethod:e}),_=Jl(p);X("Confirming PR with Stripe..."),await Ra(_,l);const f=await q(i);if(f.mode==="setup"){X("Confirming payment flow for setup...");const h=await ce(i,{secure_token:f.token});return{mode:"setup",result:Dt(h)}}else{X("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await Zr(i,h)}}}),Hl=(t,e)=>{var d,p,_,f;const r={...t},[n,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(_=e.paymentMethod)==null?void 0:_.billing_details)==null?void 0:f.address,c=e.shippingAddress;r[m.EMAIL]=r[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",r[m.ZIP_CODE]=r[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",r[m.COUNTRY]=r[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=r[m.FIRST_NAME]||n||"",u=r[m.LAST_NAME]||s||"";return l||u?(r[m.FIRST_NAME]=l,r[m.LAST_NAME]=u):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]=""),X("Final form inputs:",r),r},Kl=(t,e,r,n,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:r},currency:e.currency,applePay:n})},Jl=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 Pa.parse(t.required_user_actions[0])},{log__:we,err__:bo}=F("pockyt-paypal"),Ql=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 Xl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var W,ke;we("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await q(s);we("Verifying CPM...");const c=Ql.parse(e);we("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Fe(r,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=nl(u);we(`Starting payment flow... Mode: ${i.mode}`);const p=er(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((W=o==null?void 0:o.settings)!=null&&W.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",t.baseUrl).toString(),b=btoa(JSON.stringify(f)),I=new URLSearchParams({st:i.token,r:b}),E=`${h}?${I.toString()}`;if((ke=o==null?void 0:o.settings)!=null&&ke.useRedirectFlow)throw we("Starting redirect mode for PayPal..."),window.location.href=E,await Ar(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");we("Starting popup mode for PayPal..."),we("Opening paypal iframe...");const N=await yl("PayPal",s,p,E);we("Paypal flow result",N);const x=fo(N.href),O=wl(N.href,"catt");if(!O)throw bo("Checkout attempt ID not found in redirect URL:",N.href),new Error("Checkout attempt ID not found in redirect URL");we(`Confirming payment flow using vault ID ${x}`);const U=await ce(s,{secure_token:i.token,their_pm_id:x,checkout_attempt_id:_?O:void 0});if(we("Confirm payment flow result",U),i.mode==="setup")return{mode:"setup",result:{payment_method_id:U.payment_methods[0].id}};if(!U.pay_first_success_response)throw bo("Checkout failed, no pay-first success response:",U),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:U.pay_first_success_response}}),mr=({gateway:t,gatewayMerchantId:e,merchantName:r,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:r},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},Eo=()=>wo({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 Gr=null;const ko=t=>t===$e||t===window.location.origin?"PRODUCTION":"TEST",hr=(t,e)=>{const r=ko(t);return Gr===null&&(Gr=new window.google.payments.api.PaymentsClient({environment:r,merchantInfo:e.merchantInfo})),Gr},eu=t=>{const e=t.required_user_actions.find(r=>r.type==="airwallex_payment_consent");return e?dn.parse(e):null},Co=(t,e)=>{var o,s,i,c;const r={...t},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;r[m.EMAIL]=r[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",r[m.COUNTRY]=r[m.COUNTRY]||n.countryCode||"US",r[m.ADDRESS]=r[m.ADDRESS]||n.address1||"",r[m.CITY]=r[m.CITY]||n.locality||"",r[m.ZIP_CODE]=r[m.ZIP_CODE]||n.postalCode||"00000",r[m.STATE]=r[m.STATE]||n.administrativeArea||"";const p=r[m.FIRST_NAME]||l||"",_=r[m.LAST_NAME]||d||"";p||_?(r[m.FIRST_NAME]=p,r[m.LAST_NAME]=_):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]="")}return r},{log__:de,err__:dt}=F("awx-google-pay"),tu=Be(async({context:t,formCallbacks:e})=>{var p,_;const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,ho);if(!n)return r;de("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return dt("No gateway merchant ID found in processor account"),r;if(de("Loading Google Pay script"),await Eo(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return dt("Google Pay SDK not loaded properly"),r;if(ko(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return dt("Google Pay merchant ID is required for production environment"),r;de("Google Pay SDK loaded",window.google.payments);try{const f=mr({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await hr(t.baseUrl,f).isReadyToPay(f);if(!h)return de("Google Pay is not available for this user"),r}catch(f){return dt("Error checking Google Pay availability",f),r}const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async f=>{try{z.airwallexGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){dt("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),ru=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var f,h,b,I,E,N,x;de("Starting Google Pay flow...");const s=le(t.checkoutPaymentMethods,ho),{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=mr({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,p=await q(d);C("google_pay_flow_started",{processor_name:s.processor_name,prefill:Jn(p,["brand"]),overridePaymentRequest:c});const _=hr(t.baseUrl,u);try{const O=await _.loadPaymentData(u);de("Google Pay Payment data",O);const U=Co(r,O),W=Fe(U,n.get.onValidationError,o==null?void 0:o.defaultFieldValues);C("billing_details_received",{...W});const ke=(h=(f=O.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!ke)throw new Error("No payment token received from Google Pay");const qu=await ct(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:W[m.EMAIL],new_customer_first_name:W[m.FIRST_NAME],new_customer_last_name:W[m.LAST_NAME],new_customer_address:{zip_code:W[m.ZIP_CODE],country:W[m.COUNTRY]}}),gr=eu(qu);de("Start flow next actions",gr);let He=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:gr==null?void 0:gr.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ke}}}});de("[1st] Confirm payment flow response",He);let Yr=(I=(b=He.payment_methods)==null?void 0:b[0])==null?void 0:I.id;const Ke=(E=He.required_user_actions)==null?void 0:E.find(Vt=>Vt.type==="airwallex_payment_consent");if(Ke&&Ke.redirect_url){de("3DS Required, starting verification...",Ke);const{status:Vt}=await fr({url:Ke.redirect_url,baseUrl:t.baseUrl});if(de(`╰ 3DS verification completed [Status: ${Vt}]`),Vt===V.CANCELLED)throw new Error("3DS verification cancelled");if(Vt===V.FAILURE)throw new Error("3DS verification failed")}if(Ke&&!Yr&&(He=await ce(d,{secure_token:p.token,their_pm_id:Ke.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Ke.consent_id}}),de("[2nd] Confirm payment flow response",He),Yr=(x=(N=He.payment_methods)==null?void 0:N[0])==null?void 0:x.id),!Yr)throw new Error("No PM ID found");return pr({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:W,confirmResult:He,usePayFirstFlow:!1})}catch(O){throw dt("Google Pay payment error",O),C("google_pay_payment_error",{error:O}),new Error((O==null?void 0:O.message)??"Unknown error")}}),So=()=>wo({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 r=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...t};if(r||n||o){s[m.EMAIL]=s[m.EMAIL]||(r==null?void 0:r.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(r==null?void 0:r.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(r==null?void 0:r.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(r==null?void 0:r.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(r==null?void 0:r.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const Ao=({total:t,prefill:e})=>{var n;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}`,$e).toString()};const r=(n=e.line_items)==null?void 0:n[0];if(r)return{paymentDescription:(r==null?void 0:r.description)??"",regularBilling:{amount:t.amount,label:(r==null?void 0:r.description)??"",recurringPaymentIntervalUnit:r==null?void 0:r.billing_interval,recurringPaymentIntervalCount:(r==null?void 0:r.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},To=({overridePaymentRequest:t,initialPreview:e,prefill:r,defaultLabel:n="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(r==null?void 0:r.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)??n??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},{log__:yr}=F("awx-apple-pay");async function nu(t,e){try{const n=(await Vr(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=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function ou(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");yr("3DS Required, starting verification...",t);const{status:r}=await fr({url:t.redirect_url,baseUrl:e.baseUrl});if(yr(`╰ 3DS verification completed [Status: ${r}]`),r===V.CANCELLED)throw new Error("3DS verification cancelled");if(r===V.FAILURE)throw new Error("3DS verification failed");const n=await ce(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 yr("[2nd] Confirm payment flow response",n),n}async function su(t,e){var r,n,o,s,i;try{const c=t.payment,l=Po(e.nonCdeFormInputs,c),u=Fe(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);C("billing_details_received",{...u});const _=(await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});yr("[1st] Confirm payment flow response",f);let h=(n=(r=f.payment_methods)==null?void 0:r[0])==null?void 0:n.id;const b=(o=f.required_user_actions)==null?void 0:o.find(E=>E.type==="airwallex_payment_consent");if(b!=null&&b.redirect_url&&b.consent_id&&b.their_pm_id&&(f=await ou(b,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const I={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(I),pr({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:jt,err__:xo}=F("awx-apple-pay"),au=Be(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,mo);if(!n)return r;if(jt("Loading Apple Pay script"),await So(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return jt("Apple Pay is not available on this device/browser"),r;if(jt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return jt("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await z.airwallexApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){xo("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),iu=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const s=le(t.checkoutPaymentMethods,mo),{overridePaymentRequest:i,initialPreview:c}=n,l=t.anyCdeConnection,u=await q(l),d=u.mode==="setup",{currencyCode:p,total:_}=To({overridePaymentRequest:i,initialPreview:c,defaultLabel:(I=s==null?void 0:s.metadata)==null?void 0:I.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Ao({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:Jn(u,["brand"]),overridePaymentRequest:i}),new Promise((E,N)=>{const x=()=>{jt("Payment cancelled by user"),N(new Error("Payment cancelled by user"))};h.oncancel=x,h.onvalidatemerchant=async O=>{try{await nu(O,b)}catch(U){N(U)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{C("apple_pay_payment_authorized");try{const U=await su(O,b);E(U)}catch(U){N(U)}},h.begin()}).catch(E=>{throw xo("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),cu=1,lu=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__:ee,err__:Io}=F("loop-crypto"),uu=a.object({loopFirstName:Z,loopLastName:Z,loopEmail:Z,[m.PROMOTION_CODE]:M}),du=a.object({loopFirstName:M,loopLastName:M,loopEmail:M,[m.PROMOTION_CODE]:M}),Ro=(t,e,r,n)=>{const o=r.safeParse(t);if(!o.success){const s=o.error.format(),i=pn(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Io("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},pu=Be(async({context:t})=>{ee("Checking if there are any CPMs for Loop Crypto...");const e=le(t.checkoutPaymentMethods,lu);ee(`checkoutPaymentMethod: ${JSON.stringify(e)}`),ee("Starting Loop Crypto flow...");const r=await q(t.anyCdeConnection),n=await Vr(t.anyCdeConnection,{checkout_payment_method:e});if(r.mode!=="setup"&&!e.metadata.supported_currencies.includes(r.currency))throw Error(`Currency ${r.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!n||!n.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=n.next_action_metadata;let s;r.mode==="setup"?s=cu:s=r.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=er(),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}}),fu=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{ee("Running Loop flow..."),ee("context",t),ee("checkoutPaymentMethod",e),ee("nonCdeFormInputs",r),ee("flowCallbacks",n),ee("customParams",o);let s;o!=null&&o.success?s=Ro(r,n.get.onValidationError,uu):s=Ro(r,n.get.onValidationError,du);const i=t.anyCdeConnection,c=await q(t.anyCdeConnection),l=c.mode!=="setup",u=await ct(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 ce(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(ee(`Confirm result: ${d}`),c.mode==="setup"){ee("Doing payment setup..."),ee("├ Confirm payment flow result received Result:",d);const p=Dt(d);return ee(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(ee("Doing checkout..."),!d.pay_first_success_response)throw Io("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}});async function mu(t,e){try{const n=(await Vr(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=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function hu(t,e){var r,n;try{const o=t.payment,s=Po(e.nonCdeFormInputs,o),i=Fe(s,e.formCallbacks.get.onValidationError);C("billing_details_received",{...i}),await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((n=(r=l.payment_methods)==null?void 0:r[0])==null?void 0:n.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),pr({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 No=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()})}),Oo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:_r,err__:Mo}=F("authnet-applepay"),yu=Be(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,No);if(!n)return r;if(_r("Loading Apple Pay script"),await So(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return _r("Apple Pay is not available on this device/browser"),r;if(!await ApplePaySession.canMakePayments())return _r("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await z.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Mo("Apple Pay payment error",_),C("apple_pay_payment_error",{error:_}),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),_u=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const{initialPreview:s,overridePaymentRequest:i}=n,c=le(t.checkoutPaymentMethods,No),{currencyCode:l,total:u}=To({overridePaymentRequest:i,initialPreview:s,defaultLabel:(I=c==null?void 0:c.metadata)==null?void 0:I.processor_account_name}),d=t.anyCdeConnection,p=await q(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Ao({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}};C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:p,overridePaymentRequest:i});const h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((E,N)=>{h.oncancel=()=>{_r("Payment cancelled by user"),N(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async x=>{try{await mu(x,b)}catch(O){N(O)}},h.onpaymentmethodselected=()=>{const x={newTotal:f.total};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{C("apple_pay_payment_authorized");try{const O=await hu(x,b);E(O)}catch(O){N(O)}},h.begin()}).catch(E=>{throw Mo("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),{log__:qe,err__:Ft}=F("authnet-googlepay"),gu=Be(async({context:t,formCallbacks:e})=>{var d,p;qe("Initializing Authnet GooglePay flow");const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,Oo);if(!n)return r;qe("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Ft("No gateway merchant ID found in processor account"),r;if(qe("Loading Google Pay script"),await Eo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Ft("Google Pay SDK not loaded properly"),r;qe("Google Pay SDK loaded",window.google.payments);try{const _=mr({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await hr(t.baseUrl,_).isReadyToPay(_);if(!f)return qe("Google Pay is not available for this user"),r}catch(_){return Ft("Error checking Google Pay availability",_),r}const s=t.anyCdeConnection,i=await q(s),c=i.mode==="setup",l=await lt(s,i.token,c,void 0),u=async _=>{try{z.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Ft("Google Pay payment error",f),C("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),vu=Ae(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:r,formCallbacks:n,customParams:o})=>{var f,h,b,I;const{initialPreview:s,overridePaymentRequest:i}=o,l=le(t.checkoutPaymentMethods,Oo).metadata,u=mr({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,p=await q(d);C("google_pay_flow_started",{processor_name:r.processor_name,prefill:p,overridePaymentRequest:i});const _=hr(t.baseUrl,u);try{const E=await _.loadPaymentData(u);qe("Google Pay Payment data",E);const N=Co(e,E),x=Fe(N,n.get.onValidationError);C("billing_details_received",{...x});const O=(h=(f=E.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!O)throw new Error("No payment token received from Google Pay");const U=await ct(d,{payment_provider:r.provider,checkout_payment_method:r,new_customer_email:x[m.EMAIL],new_customer_first_name:x[m.FIRST_NAME],new_customer_last_name:x[m.LAST_NAME],new_customer_address:{zip_code:x[m.ZIP_CODE],country:x[m.COUNTRY]}});qe("Start payment flow response",U);const W=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:r.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((I=(b=W.payment_methods)==null?void 0:b[0])==null?void 0:I.id))throw new Error("No PM ID found");return pr({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:r,requiredFormFields:x,confirmResult:W,usePayFirstFlow:!1})}catch(E){throw Ft("Google Pay payment error",E),C("google_pay_payment_error",{error:E}),new Error((E==null?void 0:E.message)??"Unknown error")}}),Ut=(t,e,r)=>{const n=t.filter(o=>{const s=r===void 0?!0:o.processor_name===r,i=o.provider===e;return s&&i});if(n.length===0)throw console.error("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${r}'`);if(n.length!==1)throw console.error("CPMs list",t),new Error(`More than one CPM found with provider '${e}' and processor '${r}'`);return n[0]},z={commonCC:{init:async()=>{},run:Ul},stripePR:{init:Yl,run:Wl},stripeLink:{init:cl,run:ll},pockytPaypal:{run:Xl},airwallexGooglePay:{init:tu,run:ru},airwallexApplePay:{init:au,run:iu},loopCrypto:{init:pu,run:fu},authorizeNetApplePay:{init:yu,run:_u},authorizeNetGooglePay:{init:gu,run:vu}},{log__:wu,err__:bu}=F("init-flows"),Ye=(t,e)=>{const r=new Mt;return{publisher:r,initialize:async n=>{try{if(r.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);wu(`✔ ${t} flow initialized successfully. Result:`,o),r.set(o)}catch(o){bu(`𝙭 ${t} flow initialization failed. Error:`,ne(o),"Details:",o),r.throw(o,ne(o))}}}},Eu=async(t,e,r)=>{await Promise.all(Object.values(t).map(n=>n.initialize({context:e,formCallbacks:r})))},ku=()=>({stripePR:Ye("Stripe PR",z.stripePR.init),stripeLink:Ye("Stripe Link",z.stripeLink.init),airwallexGooglePay:Ye("Airwallex GooglePay",z.airwallexGooglePay.init),airwallexApplePay:Ye("Airwallex ApplePay",z.airwallexApplePay.init),loop:Ye("Loop",z.loopCrypto.init),authorizeNetGooglePay:Ye("Authnet GooglePay",z.authorizeNetGooglePay.init),authorizeNetApplePay:Ye("Authnet ApplePay",z.authorizeNetApplePay.init)}),{err__:Cu}=F("form-callbacks"),pe=a.function().optional(),Do=a.object({onFocus:pe,onBlur:pe,onChange:pe,onLoad:pe,onLoadError:pe,onValidationError:pe,onCheckoutStarted:pe,onCheckoutSuccess:pe,onSetupPaymentMethodSuccess:pe,onCheckoutError:pe,onPaymentRequestLoad:pe}),Ee=class Ee{constructor(){this.setCallbacks=e=>{this._callbacks=Ee.createEmptyCallbacks(),Object.entries(e).forEach(([r,n])=>{const o=Hs(r,n??Ee.NOOP,Cu);this._callbacks[r]=o})},this._callbacks=Ee.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ee.NOOP=()=>{},Ee.createEmptyCallbacks=()=>{const e={};return Object.keys(Do.keyof().enum).forEach(r=>{e[r]=Ee.NOOP}),e},Ee.fromObject=e=>{const r=new Ee;return r.setCallbacks(Do.parse(e)),r};let Br=Ee;const Su="error",Pu="debug",Au=console.error,Tu=console.debug,Ue=$();Ue&&(Ue._ojs_console_callbacks=[]),console.error=function(...t){var e;Au.call(console,...t),(e=Ue==null?void 0:Ue._ojs_console_callbacks)==null||e.forEach(r=>r(Su,...t))},console.debug=function(...t){var e;Tu.call(console,...t),(e=Ue==null?void 0:Ue._ojs_console_callbacks)==null||e.forEach(r=>r(Pu,...t))};const Lo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$t=32,xu=16,jo=10,Fo=0xffffffffffff;var We;(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"})(We||(We={}));class Zt extends Error{constructor(e,r){super(`${r} (${e})`),this.name="ULIDError",this.code=e}}function Iu(t){let e=Math.floor(t()*$t);return e===$t&&(e=$t-1),Lo.charAt(e)}function Ru(t){const e=Nu(),r=e&&(e.crypto||e.msCrypto)||null;if(typeof(r==null?void 0:r.getRandomValues)=="function")return()=>{const n=new Uint8Array(1);return r.getRandomValues(n),n[0]/255};if(typeof(r==null?void 0:r.randomBytes)=="function")return()=>r.randomBytes(1).readUInt8()/255;throw new Zt(We.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Nu(){return Du()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ou(t,e){let r="";for(;t>0;t--)r=Iu(e)+r;return r}function Mu(t,e=jo){if(isNaN(t))throw new Zt(We.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Fo)throw new Zt(We.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Fo}: ${t}`);if(t<0)throw new Zt(We.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new Zt(We.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let r,n="";for(let o=e;o>0;o--)r=t%$t,n=Lo.charAt(r)+n,t=(t-r)/$t;return n}function Du(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Lu(t,e){const r=Ru(),n=Date.now();return Mu(n,jo)+Ou(xu,r)}const Uo="op_analytics_device_token",ju=()=>{const t=document.cookie.split(";").find(r=>r.includes(Uo));if(t)return t.split("=")[1];const e=Lu();return Fu(e),e},Fu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Uo}=${t}; path=/; expires=${e.toUTCString()}`};function Uu(){try{const t=$();if(t!=null&&t.next||t!=null&&t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=$();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(n=>n.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(n=>n._reactRootContainer))return"react";const r=$();return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function $u(t){var e,r,n;try{switch(t){case"react":return null;case"nextjs":{const o=$();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((r=o==null?void 0:o.__NEXT_DATA__)==null?void 0:r.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(n=$())==null?void 0:n.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Zu(){const t=Uu(),e=$u(t);return{framework:t,version:e}}class Vu{constructor(e,r,n,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if($o(s.origin)!==$o(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=Fa(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=r,this.formCallbacks=n,this.internalCallbacks=o}}const $o=t=>new URL(t).origin;async function zu(t,e){const n=await vn({iframe:t,debug:!1,childOrigin:e}).promise,o=await ai(n);if(!ii(n,o))throw new Error("Got invalid CDE connection object");return n}class Gu{constructor(){this.connections=new Map}addConnection(e,r){this.connections.set(e,r)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Bu=(t,e,r)=>{const{stripePR:n}=t;n.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Zo("apple_pay",s,e,r,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Zo("google_pay",s,e,r,u)}}};r.get.onPaymentRequestLoad(l)}})},Zo=(t,e,r,n,o)=>z.stripePR.run({context:r,checkoutPaymentMethod:Ut(r.checkoutPaymentMethods,t),nonCdeFormInputs:_e(r.formDiv),formCallbacks:n,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Vo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:be,err__:xe}=F("op-form"),Ie=class Ie{constructor(e){var o;this.cdeLoadEvent=new Mt,this.anyCdeConn=new Mt,this.context=new Mt,this.initFlows=ku(),this.startFormInit=async()=>{try{const s=this.createElement(ye.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"),be("CDE bridge element mounted"),be("Initializing OpenPay form:"),be("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Vo});be("├ CDE load event received"),be("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Vo});be("├ CDE connection received"),await tl(c,this.deviceToken),be("├ Creating OJS context, setting up handlers...");const l=Ie.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Bu(this.initFlows,l,this.formCallbacks),be("├ Starting OJS init flows..."),await Eu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),be("╰ Done initializing OJS flows."),C("form_loaded")}catch(s){const i=ne(s);xe("╰ Error initializing OP form:",i),C("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===ye.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),C("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),C("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const c=Js.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),C("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[ye.CARD]:void 0,[ye.CARD_NUMBER]:void 0,[ye.CARD_EXPIRY]:void 0,[ye.CARD_CVC]:void 0,[ye.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",Oa(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{zu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ye.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>xe("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{C("submit_card");const s=this.context.getValueIfLoadedElse(null);if(!s){xe("Please wait for the form to finish loading before submitting.");return}z.commonCC.run({context:s,checkoutPaymentMethod:Ut(s.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:_e(s.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){xe("Please wait for the form to finish loading before getting available payment methods.");return}const i={airwallexGooglePay:re.airwallexGooglePay,airwallexApplePay:re.airwallexApplePay,authorizeNetGooglePay:re.authorizenetGooglePay,authorizeNetApplePay:re.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return C("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{C("general_form_submit",{method:s,settings:i});const c=this.context.getValueIfLoadedElse(null);if(!c){xe("Please wait for the form to finish loading before submitting.");return}switch(s){case re.pockytPaypal:return z.pockytPaypal.run({context:c,checkoutPaymentMethod:Ut(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case re.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.loopCrypto:return z.loopCrypto.run({context:c,checkoutPaymentMethod:Ut(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:ur(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;be("Destroying OpenPay form...");for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=$())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),zc(),this.registeredElements=null,delete window.ojs,C("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Ie.assignAsSingleton(this),this.ojsVersion="0.2.29",this.ojsReleaseVersion="0.2.29-alpha.5211859",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Br.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${er()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Gu,this.deviceToken=ju(),Vc();const{framework:r,version:n}=Zu();jc(this.baseUrl).then(s=>{$r.current.isSuccess||$r.set({checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:r,frameworkVersion:n,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl})}),C("form_init"),this.eventHandler=new Vu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=$())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};Ie.ojsFlows=z,Ie.assignAsSingleton=e=>{if(Ie.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ie.getInstance=()=>window.ojs??null,Ie.buildOjsFlowContext=(e,r,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??$e).origin,formDiv:o,elementsSessionId:r.sessionId,checkoutPaymentMethods:r.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let qr=Ie;Ce.FieldName=m,Ce.OpenPayForm=qr,Ce.SubmitMethod=Ks,Ce.SubmitMethods=re,Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"})});
25
+ Details: got ${t.required_user_actions.length} required user actions`);return Pa.parse(t.required_user_actions[0])},{log__:we,err__:bo}=F("pockyt-paypal"),Ql=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 Xl=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var W,ke;we("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await q(s);we("Verifying CPM...");const c=Ql.parse(e);we("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=Fe(r,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=nl(u);we(`Starting payment flow... Mode: ${i.mode}`);const p=er(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((W=o==null?void 0:o.settings)!=null&&W.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",t.baseUrl).toString(),b=btoa(JSON.stringify(f)),I=new URLSearchParams({st:i.token,r:b}),E=`${h}?${I.toString()}`;if((ke=o==null?void 0:o.settings)!=null&&ke.useRedirectFlow)throw we("Starting redirect mode for PayPal..."),window.location.href=E,await Ar(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");we("Starting popup mode for PayPal..."),we("Opening paypal iframe...");const N=await yl("PayPal",s,p,E);we("Paypal flow result",N);const x=fo(N.href),O=wl(N.href,"catt");if(!O)throw bo("Checkout attempt ID not found in redirect URL:",N.href),new Error("Checkout attempt ID not found in redirect URL");we(`Confirming payment flow using vault ID ${x}`);const U=await ce(s,{secure_token:i.token,their_pm_id:x,checkout_attempt_id:_?O:void 0});if(we("Confirm payment flow result",U),i.mode==="setup")return{mode:"setup",result:{payment_method_id:U.payment_methods[0].id}};if(!U.pay_first_success_response)throw bo("Checkout failed, no pay-first success response:",U),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:U.pay_first_success_response}}),mr=({gateway:t,gatewayMerchantId:e,merchantName:r,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:r},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},Eo=()=>wo({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 Gr=null;const ko=t=>t===$e||t===window.location.origin?"PRODUCTION":"TEST",hr=(t,e)=>{const r=ko(t);return Gr===null&&(Gr=new window.google.payments.api.PaymentsClient({environment:r,merchantInfo:e.merchantInfo})),Gr},eu=t=>{const e=t.required_user_actions.find(r=>r.type==="airwallex_payment_consent");return e?dn.parse(e):null},Co=(t,e)=>{var o,s,i,c;const r={...t},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;r[m.EMAIL]=r[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",r[m.COUNTRY]=r[m.COUNTRY]||n.countryCode||"US",r[m.ADDRESS]=r[m.ADDRESS]||n.address1||"",r[m.CITY]=r[m.CITY]||n.locality||"",r[m.ZIP_CODE]=r[m.ZIP_CODE]||n.postalCode||"00000",r[m.STATE]=r[m.STATE]||n.administrativeArea||"";const p=r[m.FIRST_NAME]||l||"",_=r[m.LAST_NAME]||d||"";p||_?(r[m.FIRST_NAME]=p,r[m.LAST_NAME]=_):(r[m.FIRST_NAME]="_OP_UNKNOWN",r[m.LAST_NAME]="")}return r},{log__:de,err__:dt}=F("awx-google-pay"),tu=Be(async({context:t,formCallbacks:e})=>{var p,_;const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,ho);if(!n)return r;de("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return dt("No gateway merchant ID found in processor account"),r;if(de("Loading Google Pay script"),await Eo(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return dt("Google Pay SDK not loaded properly"),r;if(ko(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return dt("Google Pay merchant ID is required for production environment"),r;de("Google Pay SDK loaded",window.google.payments);try{const f=mr({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await hr(t.baseUrl,f).isReadyToPay(f);if(!h)return de("Google Pay is not available for this user"),r}catch(f){return dt("Error checking Google Pay availability",f),r}const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async f=>{try{z.airwallexGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){dt("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),ru=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{var f,h,b,I,E,N,x;de("Starting Google Pay flow...");const s=le(t.checkoutPaymentMethods,ho),{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=mr({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,p=await q(d);C("google_pay_flow_started",{processor_name:s.processor_name,prefill:Jn(p,["brand"]),overridePaymentRequest:c});const _=hr(t.baseUrl,u);try{const O=await _.loadPaymentData(u);de("Google Pay Payment data",O);const U=Co(r,O),W=Fe(U,n.get.onValidationError,o==null?void 0:o.defaultFieldValues);C("billing_details_received",{...W});const ke=(h=(f=O.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!ke)throw new Error("No payment token received from Google Pay");const qu=await ct(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:W[m.EMAIL],new_customer_first_name:W[m.FIRST_NAME],new_customer_last_name:W[m.LAST_NAME],new_customer_address:{zip_code:W[m.ZIP_CODE],country:W[m.COUNTRY]}}),gr=eu(qu);de("Start flow next actions",gr);let He=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:gr==null?void 0:gr.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ke}}}});de("[1st] Confirm payment flow response",He);let Yr=(I=(b=He.payment_methods)==null?void 0:b[0])==null?void 0:I.id;const Ke=(E=He.required_user_actions)==null?void 0:E.find(Vt=>Vt.type==="airwallex_payment_consent");if(Ke&&Ke.redirect_url){de("3DS Required, starting verification...",Ke);const{status:Vt}=await fr({url:Ke.redirect_url,baseUrl:t.baseUrl});if(de(`╰ 3DS verification completed [Status: ${Vt}]`),Vt===V.CANCELLED)throw new Error("3DS verification cancelled");if(Vt===V.FAILURE)throw new Error("3DS verification failed")}if(Ke&&!Yr&&(He=await ce(d,{secure_token:p.token,their_pm_id:Ke.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Ke.consent_id}}),de("[2nd] Confirm payment flow response",He),Yr=(x=(N=He.payment_methods)==null?void 0:N[0])==null?void 0:x.id),!Yr)throw new Error("No PM ID found");return pr({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:W,confirmResult:He,usePayFirstFlow:!1})}catch(O){throw dt("Google Pay payment error",O),C("google_pay_payment_error",{error:O}),new Error((O==null?void 0:O.message)??"Unknown error")}}),So=()=>wo({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 r=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...t};if(r||n||o){s[m.EMAIL]=s[m.EMAIL]||(r==null?void 0:r.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(r==null?void 0:r.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(r==null?void 0:r.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(r==null?void 0:r.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(r==null?void 0:r.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const Ao=({total:t,prefill:e})=>{var n;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}`,$e).toString()};const r=(n=e.line_items)==null?void 0:n[0];if(r)return{paymentDescription:(r==null?void 0:r.description)??"",regularBilling:{amount:t.amount,label:(r==null?void 0:r.description)??"",recurringPaymentIntervalUnit:r==null?void 0:r.billing_interval,recurringPaymentIntervalCount:(r==null?void 0:r.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},To=({overridePaymentRequest:t,initialPreview:e,prefill:r,defaultLabel:n="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(r==null?void 0:r.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)??n??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},{log__:yr}=F("awx-apple-pay");async function nu(t,e){try{const n=(await Vr(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=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function ou(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");yr("3DS Required, starting verification...",t);const{status:r}=await fr({url:t.redirect_url,baseUrl:e.baseUrl});if(yr(`╰ 3DS verification completed [Status: ${r}]`),r===V.CANCELLED)throw new Error("3DS verification cancelled");if(r===V.FAILURE)throw new Error("3DS verification failed");const n=await ce(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 yr("[2nd] Confirm payment flow response",n),n}async function su(t,e){var r,n,o,s,i;try{const c=t.payment,l=Po(e.nonCdeFormInputs,c),u=Fe(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);C("billing_details_received",{...u});const _=(await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});yr("[1st] Confirm payment flow response",f);let h=(n=(r=f.payment_methods)==null?void 0:r[0])==null?void 0:n.id;const b=(o=f.required_user_actions)==null?void 0:o.find(E=>E.type==="airwallex_payment_consent");if(b!=null&&b.redirect_url&&b.consent_id&&b.their_pm_id&&(f=await ou(b,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const I={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(I),pr({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:jt,err__:xo}=F("awx-apple-pay"),au=Be(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,mo);if(!n)return r;if(jt("Loading Apple Pay script"),await So(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return jt("Apple Pay is not available on this device/browser"),r;if(jt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return jt("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await z.airwallexApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){xo("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),iu=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const s=le(t.checkoutPaymentMethods,mo),{overridePaymentRequest:i,initialPreview:c}=n,l=t.anyCdeConnection,u=await q(l),d=u.mode==="setup",{currencyCode:p,total:_}=To({overridePaymentRequest:i,initialPreview:c,defaultLabel:(I=s==null?void 0:s.metadata)==null?void 0:I.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Ao({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:Jn(u,["brand"]),overridePaymentRequest:i}),new Promise((E,N)=>{const x=()=>{jt("Payment cancelled by user"),N(new Error("Payment cancelled by user"))};h.oncancel=x,h.onvalidatemerchant=async O=>{try{await nu(O,b)}catch(U){N(U)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{C("apple_pay_payment_authorized");try{const U=await su(O,b);E(U)}catch(U){N(U)}},h.begin()}).catch(E=>{throw xo("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),cu=1,lu=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__:ee,err__:Io}=F("loop-crypto"),uu=a.object({loopFirstName:Z,loopLastName:Z,loopEmail:Z,[m.PROMOTION_CODE]:M}),du=a.object({loopFirstName:M,loopLastName:M,loopEmail:M,[m.PROMOTION_CODE]:M}),Ro=(t,e,r,n)=>{const o=r.safeParse(t);if(!o.success){const s=o.error.format(),i=pn(s);for(const[c,l]of Object.entries(i))e(c,l,c);throw Io("Got validation errors in non-CDE form fields",i),new Error("Got validation errors in non-CDE form fields")}return o.data},pu=Be(async({context:t})=>{ee("Checking if there are any CPMs for Loop Crypto...");const e=le(t.checkoutPaymentMethods,lu);ee(`checkoutPaymentMethod: ${JSON.stringify(e)}`),ee("Starting Loop Crypto flow...");const r=await q(t.anyCdeConnection),n=await Vr(t.anyCdeConnection,{checkout_payment_method:e});if(r.mode!=="setup"&&!e.metadata.supported_currencies.includes(r.currency))throw Error(`Currency ${r.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!n||!n.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=n.next_action_metadata;let s;r.mode==="setup"?s=cu:s=r.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=er(),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}}),fu=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,formCallbacks:n,customParams:o})=>{ee("Running Loop flow..."),ee("context",t),ee("checkoutPaymentMethod",e),ee("nonCdeFormInputs",r),ee("flowCallbacks",n),ee("customParams",o);let s;o!=null&&o.success?s=Ro(r,n.get.onValidationError,uu):s=Ro(r,n.get.onValidationError,du);const i=t.anyCdeConnection,c=await q(t.anyCdeConnection),l=c.mode!=="setup",u=await ct(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 ce(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(ee(`Confirm result: ${d}`),c.mode==="setup"){ee("Doing payment setup..."),ee("├ Confirm payment flow result received Result:",d);const p=Dt(d);return ee(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(ee("Doing checkout..."),!d.pay_first_success_response)throw Io("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}});async function mu(t,e){try{const n=(await Vr(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=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(r){throw e.session.abort(),r}}async function hu(t,e){var r,n;try{const o=t.payment,s=Po(e.nonCdeFormInputs,o),i=Fe(s,e.formCallbacks.get.onValidationError);C("billing_details_received",{...i}),await ct(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((n=(r=l.payment_methods)==null?void 0:r[0])==null?void 0:n.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),pr({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 No=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()})}),Oo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:_r,err__:Mo}=F("authnet-applepay"),yu=Be(async({context:t,formCallbacks:e})=>{const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,No);if(!n)return r;if(_r("Loading Apple Pay script"),await So(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return _r("Apple Pay is not available on this device/browser"),r;if(!await ApplePaySession.canMakePayments())return _r("No active cards available for Apple Pay"),r;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await q(i),l=c.mode==="setup",u=await lt(i,c.token,l,void 0),d=async p=>{try{await z.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Mo("Apple Pay payment error",_),C("apple_pay_payment_error",{error:_}),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),_u=Ae(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:r,customParams:n,formCallbacks:o})=>{var I;const{initialPreview:s,overridePaymentRequest:i}=n,c=le(t.checkoutPaymentMethods,No),{currencyCode:l,total:u}=To({overridePaymentRequest:i,initialPreview:s,defaultLabel:(I=c==null?void 0:c.metadata)==null?void 0:I.processor_account_name}),d=t.anyCdeConnection,p=await q(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Ao({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}};C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:p,overridePaymentRequest:i});const h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:r,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((E,N)=>{h.oncancel=()=>{_r("Payment cancelled by user"),N(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async x=>{try{await mu(x,b)}catch(O){N(O)}},h.onpaymentmethodselected=()=>{const x={newTotal:f.total};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{C("apple_pay_payment_authorized");try{const O=await hu(x,b);E(O)}catch(O){N(O)}},h.begin()}).catch(E=>{throw Mo("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),{log__:qe,err__:Ft}=F("authnet-googlepay"),gu=Be(async({context:t,formCallbacks:e})=>{var d,p;qe("Initializing Authnet GooglePay flow");const r={processor:ue.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=le(t.checkoutPaymentMethods,Oo);if(!n)return r;qe("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Ft("No gateway merchant ID found in processor account"),r;if(qe("Loading Google Pay script"),await Eo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Ft("Google Pay SDK not loaded properly"),r;qe("Google Pay SDK loaded",window.google.payments);try{const _=mr({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await hr(t.baseUrl,_).isReadyToPay(_);if(!f)return qe("Google Pay is not available for this user"),r}catch(_){return Ft("Error checking Google Pay availability",_),r}const s=t.anyCdeConnection,i=await q(s),c=i.mode==="setup",l=await lt(s,i.token,c,void 0),u=async _=>{try{z.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:n,nonCdeFormInputs:_e(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Ft("Google Pay payment error",f),C("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:ue.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),vu=Ae(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:r,formCallbacks:n,customParams:o})=>{var f,h,b,I;const{initialPreview:s,overridePaymentRequest:i}=o,l=le(t.checkoutPaymentMethods,Oo).metadata,u=mr({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,p=await q(d);C("google_pay_flow_started",{processor_name:r.processor_name,prefill:p,overridePaymentRequest:i});const _=hr(t.baseUrl,u);try{const E=await _.loadPaymentData(u);qe("Google Pay Payment data",E);const N=Co(e,E),x=Fe(N,n.get.onValidationError);C("billing_details_received",{...x});const O=(h=(f=E.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!O)throw new Error("No payment token received from Google Pay");const U=await ct(d,{payment_provider:r.provider,checkout_payment_method:r,new_customer_email:x[m.EMAIL],new_customer_first_name:x[m.FIRST_NAME],new_customer_last_name:x[m.LAST_NAME],new_customer_address:{zip_code:x[m.ZIP_CODE],country:x[m.COUNTRY]}});qe("Start payment flow response",U);const W=await ce(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:r.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((I=(b=W.payment_methods)==null?void 0:b[0])==null?void 0:I.id))throw new Error("No PM ID found");return pr({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:r,requiredFormFields:x,confirmResult:W,usePayFirstFlow:!1})}catch(E){throw Ft("Google Pay payment error",E),C("google_pay_payment_error",{error:E}),new Error((E==null?void 0:E.message)??"Unknown error")}}),Ut=(t,e,r)=>{const n=t.filter(o=>{const s=r===void 0?!0:o.processor_name===r,i=o.provider===e;return s&&i});if(n.length===0)throw console.error("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${r}'`);if(n.length!==1)throw console.error("CPMs list",t),new Error(`More than one CPM found with provider '${e}' and processor '${r}'`);return n[0]},z={commonCC:{init:async()=>{},run:Ul},stripePR:{init:Yl,run:Wl},stripeLink:{init:cl,run:ll},pockytPaypal:{run:Xl},airwallexGooglePay:{init:tu,run:ru},airwallexApplePay:{init:au,run:iu},loopCrypto:{init:pu,run:fu},authorizeNetApplePay:{init:yu,run:_u},authorizeNetGooglePay:{init:gu,run:vu}},{log__:wu,err__:bu}=F("init-flows"),Ye=(t,e)=>{const r=new Mt;return{publisher:r,initialize:async n=>{try{if(r.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);wu(`✔ ${t} flow initialized successfully. Result:`,o),r.set(o)}catch(o){bu(`𝙭 ${t} flow initialization failed. Error:`,ne(o),"Details:",o),r.throw(o,ne(o))}}}},Eu=async(t,e,r)=>{await Promise.all(Object.values(t).map(n=>n.initialize({context:e,formCallbacks:r})))},ku=()=>({stripePR:Ye("Stripe PR",z.stripePR.init),stripeLink:Ye("Stripe Link",z.stripeLink.init),airwallexGooglePay:Ye("Airwallex GooglePay",z.airwallexGooglePay.init),airwallexApplePay:Ye("Airwallex ApplePay",z.airwallexApplePay.init),loop:Ye("Loop",z.loopCrypto.init),authorizeNetGooglePay:Ye("Authnet GooglePay",z.authorizeNetGooglePay.init),authorizeNetApplePay:Ye("Authnet ApplePay",z.authorizeNetApplePay.init)}),{err__:Cu}=F("form-callbacks"),pe=a.function().optional(),Do=a.object({onFocus:pe,onBlur:pe,onChange:pe,onLoad:pe,onLoadError:pe,onValidationError:pe,onCheckoutStarted:pe,onCheckoutSuccess:pe,onSetupPaymentMethodSuccess:pe,onCheckoutError:pe,onPaymentRequestLoad:pe}),Ee=class Ee{constructor(){this.setCallbacks=e=>{this._callbacks=Ee.createEmptyCallbacks(),Object.entries(e).forEach(([r,n])=>{const o=Hs(r,n??Ee.NOOP,Cu);this._callbacks[r]=o})},this._callbacks=Ee.createEmptyCallbacks()}get get(){return{...this._callbacks}}};Ee.NOOP=()=>{},Ee.createEmptyCallbacks=()=>{const e={};return Object.keys(Do.keyof().enum).forEach(r=>{e[r]=Ee.NOOP}),e},Ee.fromObject=e=>{const r=new Ee;return r.setCallbacks(Do.parse(e)),r};let Br=Ee;const Su="error",Pu="debug",Au=console.error,Tu=console.debug,Ue=$();Ue&&(Ue._ojs_console_callbacks=[]),console.error=function(...t){var e;Au.call(console,...t),(e=Ue==null?void 0:Ue._ojs_console_callbacks)==null||e.forEach(r=>r(Su,...t))},console.debug=function(...t){var e;Tu.call(console,...t),(e=Ue==null?void 0:Ue._ojs_console_callbacks)==null||e.forEach(r=>r(Pu,...t))};const Lo="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$t=32,xu=16,jo=10,Fo=0xffffffffffff;var We;(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"})(We||(We={}));class Zt extends Error{constructor(e,r){super(`${r} (${e})`),this.name="ULIDError",this.code=e}}function Iu(t){let e=Math.floor(t()*$t);return e===$t&&(e=$t-1),Lo.charAt(e)}function Ru(t){const e=Nu(),r=e&&(e.crypto||e.msCrypto)||null;if(typeof(r==null?void 0:r.getRandomValues)=="function")return()=>{const n=new Uint8Array(1);return r.getRandomValues(n),n[0]/255};if(typeof(r==null?void 0:r.randomBytes)=="function")return()=>r.randomBytes(1).readUInt8()/255;throw new Zt(We.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Nu(){return Du()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ou(t,e){let r="";for(;t>0;t--)r=Iu(e)+r;return r}function Mu(t,e=jo){if(isNaN(t))throw new Zt(We.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Fo)throw new Zt(We.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Fo}: ${t}`);if(t<0)throw new Zt(We.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new Zt(We.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let r,n="";for(let o=e;o>0;o--)r=t%$t,n=Lo.charAt(r)+n,t=(t-r)/$t;return n}function Du(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Lu(t,e){const r=Ru(),n=Date.now();return Mu(n,jo)+Ou(xu,r)}const Uo="op_analytics_device_token",ju=()=>{const t=document.cookie.split(";").find(r=>r.includes(Uo));if(t)return t.split("=")[1];const e=Lu();return Fu(e),e},Fu=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Uo}=${t}; path=/; expires=${e.toUTCString()}`};function Uu(){try{const t=$();if(t!=null&&t.next||t!=null&&t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";const e=$();if(e!=null&&e.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(n=>n.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(n=>n._reactRootContainer))return"react";const r=$();return r!=null&&r.Vue||r!=null&&r.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function $u(t){var e,r,n;try{switch(t){case"react":return null;case"nextjs":{const o=$();return((e=o==null?void 0:o.next)==null?void 0:e.version)||((r=o==null?void 0:o.__NEXT_DATA__)==null?void 0:r.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const o=(n=$())==null?void 0:n.document,s=o==null?void 0:o.querySelector("[ng-version]");return s?s.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Zu(){const t=Uu(),e=$u(t);return{framework:t,version:e}}class Vu{constructor(e,r,n,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if($o(s.origin)!==$o(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=Fa(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=r,this.formCallbacks=n,this.internalCallbacks=o}}const $o=t=>new URL(t).origin;async function zu(t,e){const n=await vn({iframe:t,debug:!1,childOrigin:e}).promise,o=await ai(n);if(!ii(n,o))throw new Error("Got invalid CDE connection object");return n}class Gu{constructor(){this.connections=new Map}addConnection(e,r){this.connections.set(e,r)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Bu=(t,e,r)=>{const{stripePR:n}=t;n.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Zo("apple_pay",s,e,r,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Zo("google_pay",s,e,r,u)}}};r.get.onPaymentRequestLoad(l)}})},Zo=(t,e,r,n,o)=>z.stripePR.run({context:r,checkoutPaymentMethod:Ut(r.checkoutPaymentMethods,t),nonCdeFormInputs:_e(r.formDiv),formCallbacks:n,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Vo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:be,err__:xe}=F("op-form"),Ie=class Ie{constructor(e){var o;this.cdeLoadEvent=new Mt,this.anyCdeConn=new Mt,this.context=new Mt,this.initFlows=ku(),this.startFormInit=async()=>{try{const s=this.createElement(ye.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"),be("CDE bridge element mounted"),be("Initializing OpenPay form:"),be("├ Waiting for CDE load event...");const i=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Vo});be("├ CDE load event received"),be("├ Waiting for CDE connection...");const c=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Vo});be("├ CDE connection received"),await tl(c,this.deviceToken),be("├ Creating OJS context, setting up handlers...");const l=Ie.buildOjsFlowContext(this.config,i,c,this.getFormDiv());this.context.set(l),Bu(this.initFlows,l,this.formCallbacks),be("├ Starting OJS init flows..."),await Eu(this.initFlows,l,this.formCallbacks),this.formCallbacks.get.onLoad(i.totalAmountAtoms,i.currency),be("╰ Done initializing OJS flows."),C("form_loaded")}catch(s){const i=ne(s);xe("╰ Error initializing OP form:",i),C("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===ye.CDE_BRIDGE||(i.node.style.height=s)})},this.onCdeLoaded=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(s),C("cde_loaded"))},this.onCdeLoadError=s=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(s),s),C("cde_load_error",{error:s}))},this.createElement=(s,i={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const c=Js.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),C("element_mounted",{element_type:s})}};return this.connectToElement({type:c.type,node:c.node}),this.registeredElements||(this.registeredElements={[ye.CARD]:void 0,[ye.CARD_NUMBER]:void 0,[ye.CARD_EXPIRY]:void 0,[ye.CARD_CVC]:void 0,[ye.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",Oa(s.styles)),i.append("secureToken",this.config.checkoutSecureToken),i},this.connectToElement=s=>{zu(s.node).then(i=>{this.connectionManager.addConnection(s.type,i),!this.anyCdeConn.current.isSuccess&&s.type===ye.CDE_BRIDGE&&this.anyCdeConn.set(i)}).catch(i=>xe("[FORM] Error connecting to CDE iframe",i))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{C("submit_card");const s=this.context.getValueIfLoadedElse(null);if(!s){xe("Please wait for the form to finish loading before submitting.");return}z.commonCC.run({context:s,checkoutPaymentMethod:Ut(s.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:_e(s.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){xe("Please wait for the form to finish loading before getting available payment methods.");return}const i={airwallexGooglePay:re.airwallexGooglePay,airwallexApplePay:re.airwallexApplePay,authorizeNetGooglePay:re.authorizenetGooglePay,authorizeNetApplePay:re.authorizenetApplePay},c=Object.entries(this.initFlows).map(([l,u])=>({name:i[l]??l,...u.publisher.getValueIfLoadedElse(null)}));return C("get_available_payment_methods",{available_payment_methods:c}),c},this.generalSubmit=(s,i)=>{C("general_form_submit",{method:s,settings:i});const c=this.context.getValueIfLoadedElse(null);if(!c){xe("Please wait for the form to finish loading before submitting.");return}switch(s){case re.pockytPaypal:return z.pockytPaypal.run({context:c,checkoutPaymentMethod:Ut(c.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:i},initResult:void 0});case re.airwallexGooglePay:{const l=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.airwallexApplePay:{const l=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetGooglePay:{const l=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.authorizenetApplePay:{const l=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!l){xe("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return l.startFlow(i)}case re.loopCrypto:return z.loopCrypto.run({context:c,checkoutPaymentMethod:Ut(c.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:_e(c.formDiv),formCallbacks:this.formCallbacks,customParams:i,initResult:void 0});default:ur(s)}},this.submit=this.submitCard,this.destroy=()=>{var s;be("Destroying OpenPay form...");for(const i of Object.values(this.registeredElements??{}))i&&i.node.remove();(s=$())==null||s.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),zc(),this.registeredElements=null,delete window.ojs,C("form_destroyed")},this.updateCallbacks=s=>{this.formCallbacks.setCallbacks(s)},Ie.assignAsSingleton(this),this.ojsVersion="0.2.30",this.ojsReleaseVersion="0.2.30",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Br.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${er()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Gu,this.deviceToken=ju(),Vc();const{framework:r,version:n}=Zu();jc(this.baseUrl).then(s=>{if(!$r.current.isSuccess){const i={checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,environment:s,framework:r,frameworkVersion:n,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl};$r.set(i)}}),C("form_init"),this.eventHandler=new Vu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),(o=$())==null||o.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};Ie.ojsFlows=z,Ie.assignAsSingleton=e=>{if(Ie.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},Ie.getInstance=()=>window.ojs??null,Ie.buildOjsFlowContext=(e,r,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??$e).origin,formDiv:o,elementsSessionId:r.sessionId,checkoutPaymentMethods:r.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let qr=Ie;Ce.FieldName=m,Ce.OpenPayForm=qr,Ce.SubmitMethod=Ks,Ce.SubmitMethods=re,Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getopenpay/openpay-js",
3
- "version": "0.2.29-alpha.5211859",
3
+ "version": "0.2.30",
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",