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