@getopenpay/openpay-js 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,15 +1,15 @@
1
- (function(Ae,je){typeof exports=="object"&&typeof module<"u"?je(exports):typeof define=="function"&&define.amd?define(["exports"],je):(Ae=typeof globalThis<"u"?globalThis:Ae||self,je(Ae.OpenPay={}))})(this,function(Ae){"use strict";const je="https://cde.getopenpay.com";var P;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},r.getValidEnumValues=s=>{const o=r.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of o)a[c]=s[c];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(o){return s[o]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},r.find=(s,o)=>{for(const a of s)if(o(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(P||(P={}));var Jt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Jt||(Jt={}));const _=P.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ye=r=>{switch(typeof r){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(r)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(r)?_.array:r===null?_.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?_.promise:typeof Map<"u"&&r instanceof Map?_.map:typeof Set<"u"&&r instanceof Set?_.set:typeof Date<"u"&&r instanceof Date?_.date:_.object;default:return _.unknown}},p=P.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Bn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class q extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let c=n,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof q))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,P.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}q.create=r=>new q(r);const De=(r,e)=>{let t;switch(r.code){case p.invalid_type:r.received===_.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case p.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,P.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:t=`Unrecognized key(s) in object: ${P.joinValues(r.keys,", ")}`;break;case p.invalid_union:t="Invalid input";break;case p.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${P.joinValues(r.options)}`;break;case p.invalid_enum_value:t=`Invalid enum value. Expected ${P.joinValues(r.options)}, received '${r.received}'`;break;case p.invalid_arguments:t="Invalid function arguments";break;case p.invalid_return_type:t="Invalid function return type";break;case p.invalid_date:t="Invalid date";break;case p.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:P.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case p.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case p.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case p.custom:t="Invalid input";break;case p.invalid_intersection_types:t="Intersection results could not be merged";break;case p.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case p.not_finite:t="Number must be finite";break;default:t=e.defaultError,P.assertNever(r)}return{message:t}};let xr=De;function qn(r){xr=r}function kt(){return xr}const Et=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,o=[...t,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let c="";const u=n.filter(l=>!!l).slice().reverse();for(const l of u)c=l(a,{data:e,defaultError:c}).message;return{...s,path:o,message:c}},Gn=[];function y(r,e){const t=kt(),n=Et({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===De?void 0:De].filter(s=>!!s)});r.common.issues.push(n)}class F{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if(s.status==="aborted")return k;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return F.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return k;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const k=Object.freeze({status:"aborted"}),Le=r=>({status:"dirty",value:r}),V=r=>({status:"valid",value:r}),Xt=r=>r.status==="aborted",Qt=r=>r.status==="dirty",Je=r=>r.status==="valid",Xe=r=>typeof Promise<"u"&&r instanceof Promise;function St(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Pr(r,e,t,n,s){if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}typeof SuppressedError=="function"&&SuppressedError;var v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(v||(v={}));var Qe,et;class re{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ar=(r,e)=>{if(Je(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new q(r.common.issues);return this._error=t,this._error}}};function S(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,c)=>{var u,l;const{message:d}=r;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??n)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:c.defaultError}},description:s}}class x{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return ye(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new F,ctx:{common:e.parent.common,data:e.data,parsedType:ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Xe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ye(e)},o=this._parseSync({data:e,path:s.path,parent:s});return Ar(s,o)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ye(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Xe(s)?s:Promise.resolve(s));return Ar(n,o)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const a=e(s),c=()=>o.addIssue({code:p.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new J({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return se.create(this,this._def)}nullable(){return we.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K.create(this,this._def)}promise(){return Ze.create(this,this._def)}or(e){return st.create([this,e],this._def)}and(e){return ot.create(this,e,this._def)}transform(e){return new J({...S(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ut({...S(this._def),innerType:this,defaultValue:t,typeName:w.ZodDefault})}brand(){return new rr({typeName:w.ZodBranded,type:this,...S(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new dt({...S(this._def),innerType:this,catchValue:t,typeName:w.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return pt.create(this,e)}readonly(){return ft.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Yn=/^c[^\s-]{8,}$/i,Wn=/^[0-9a-z]+$/,Hn=/^[0-9A-HJKMNP-TV-Z]{26}$/,Kn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Jn=/^[a-z0-9_-]{21}$/i,Xn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Qn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,es="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let er;const ts=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rs=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ns=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ss=new RegExp(`^${Tr}$`);function Ir(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function os(r){return new RegExp(`^${Ir(r)}$`)}function Rr(r){let e=`${Tr}T${Ir(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function is(r,e){return!!((e==="v4"||!e)&&ts.test(r)||(e==="v6"||!e)&&rs.test(r))}class H extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_.string){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.string,received:o.parsedType}),k}const n=new F;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,c=e.data.length<o.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?y(s,{code:p.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&y(s,{code:p.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Qn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"email",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")er||(er=new RegExp(es,"u")),er.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"emoji",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Kn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"uuid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Jn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"nanoid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Yn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Wn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid2",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Hn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ulid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),y(s,{validation:"url",code:p.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"regex",code:p.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Rr(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?ss.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?os(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Xn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"duration",code:p.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?is(e.data,o.version)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ip",code:p.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?ns.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"base64",code:p.invalid_string,message:o.message}),n.dirty()):P.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:p.invalid_string,...v.errToObj(n)})}_addCheck(e){return new H({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...v.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...v.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...v.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new H({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new H({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new H({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}H.create=r=>{var e;return new H({checks:[],typeName:w.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};function as(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,o=parseInt(r.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class _e extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==_.number){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.number,received:o.parsedType}),k}let n;const s=new F;for(const o of this._def.checks)o.kind==="int"?P.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:p.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?as(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:p.not_finite,message:o.message}),s.dirty()):P.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new _e({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new _e({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&P.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}_e.create=r=>new _e({checks:[],typeName:w.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class ge extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==_.bigint){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.bigint,received:o.parsedType}),k}let n;const s=new F;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):P.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new ge({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new ge({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ge.create=r=>{var e;return new ge({checks:[],typeName:w.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};class tt extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_.boolean){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.boolean,received:n.parsedType}),k}return V(e.data)}}tt.create=r=>new tt({typeName:w.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Te extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_.date){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.date,received:o.parsedType}),k}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_date}),k}const n=new F;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):P.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Te({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Te.create=r=>new Te({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:w.ZodDate,...S(r)});class Ct extends x{_parse(e){if(this._getType(e)!==_.symbol){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.symbol,received:n.parsedType}),k}return V(e.data)}}Ct.create=r=>new Ct({typeName:w.ZodSymbol,...S(r)});class rt extends x{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.undefined,received:n.parsedType}),k}return V(e.data)}}rt.create=r=>new rt({typeName:w.ZodUndefined,...S(r)});class nt extends x{_parse(e){if(this._getType(e)!==_.null){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.null,received:n.parsedType}),k}return V(e.data)}}nt.create=r=>new nt({typeName:w.ZodNull,...S(r)});class Ue extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return V(e.data)}}Ue.create=r=>new Ue({typeName:w.ZodAny,...S(r)});class Ie extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return V(e.data)}}Ie.create=r=>new Ie({typeName:w.ZodUnknown,...S(r)});class le extends x{_parse(e){const t=this._getOrReturnCtx(e);return y(t,{code:p.invalid_type,expected:_.never,received:t.parsedType}),k}}le.create=r=>new le({typeName:w.ZodNever,...S(r)});class xt extends x{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.void,received:n.parsedType}),k}return V(e.data)}}xt.create=r=>new xt({typeName:w.ZodVoid,...S(r)});class K extends x{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==_.array)return y(t,{code:p.invalid_type,expected:_.array,received:t.parsedType}),k;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(a||c)&&(y(t,{code:a?p.too_big:p.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(y(t,{code:p.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(y(t,{code:p.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>s.type._parseAsync(new re(t,a,t.path,c)))).then(a=>F.mergeArray(n,a));const o=[...t.data].map((a,c)=>s.type._parseSync(new re(t,a,t.path,c)));return F.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new K({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new K({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new K({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}K.create=(r,e)=>new K({type:r,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...S(e)});function $e(r){if(r instanceof O){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=se.create($e(n))}return new O({...r._def,shape:()=>e})}else return r instanceof K?new K({...r._def,type:$e(r.element)}):r instanceof se?se.create($e(r.unwrap())):r instanceof we?we.create($e(r.unwrap())):r instanceof ne?ne.create(r.items.map(e=>$e(e))):r}class O extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=P.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==_.object){const l=this._getOrReturnCtx(e);return y(l,{code:p.invalid_type,expected:_.object,received:l.parsedType}),k}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof le&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||c.push(l);const u=[];for(const l of a){const d=o[l],h=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new re(s,h,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof le){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")c.length>0&&(y(s,{code:p.unrecognized_keys,keys:c}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of c){const h=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new re(s,h,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of u){const h=await d.key,b=await d.value;l.push({key:h,value:b,alwaysSet:d.alwaysSet})}return l}).then(l=>F.mergeObjectSync(n,l)):F.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new O({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,o,a,c;const u=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,t,n).message)!==null&&a!==void 0?a:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:u}:{message:u}}}:{}})}strip(){return new O({...this._def,unknownKeys:"strip"})}passthrough(){return new O({...this._def,unknownKeys:"passthrough"})}extend(e){return new O({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new O({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:w.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new O({...this._def,catchall:e})}pick(e){const t={};return P.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new O({...this._def,shape:()=>t})}omit(e){const t={};return P.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new O({...this._def,shape:()=>t})}deepPartial(){return $e(this)}partial(e){const t={};return P.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new O({...this._def,shape:()=>t})}required(e){const t={};return P.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof se;)o=o._def.innerType;t[n]=o}}),new O({...this._def,shape:()=>t})}keyof(){return Or(P.objectKeys(this.shape))}}O.create=(r,e)=>new O({shape:()=>r,unknownKeys:"strip",catchall:le.create(),typeName:w.ZodObject,...S(e)}),O.strictCreate=(r,e)=>new O({shape:()=>r,unknownKeys:"strict",catchall:le.create(),typeName:w.ZodObject,...S(e)}),O.lazycreate=(r,e)=>new O({shape:r,unknownKeys:"strip",catchall:le.create(),typeName:w.ZodObject,...S(e)});class st extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const a=o.map(c=>new q(c.ctx.common.issues));return y(t,{code:p.invalid_union,unionErrors:a}),k}if(t.common.async)return Promise.all(n.map(async o=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const u of n){const l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(u=>new q(u));return y(t,{code:p.invalid_union,unionErrors:c}),k}}get options(){return this._def.options}}st.create=(r,e)=>new st({options:r,typeName:w.ZodUnion,...S(e)});const ue=r=>r instanceof at?ue(r.schema):r instanceof J?ue(r.innerType()):r instanceof ct?[r.value]:r instanceof ve?r.options:r instanceof lt?P.objectValues(r.enum):r instanceof ut?ue(r._def.innerType):r instanceof rt?[void 0]:r instanceof nt?[null]:r instanceof se?[void 0,...ue(r.unwrap())]:r instanceof we?[null,...ue(r.unwrap())]:r instanceof rr||r instanceof ft?ue(r.unwrap()):r instanceof dt?ue(r._def.innerType):[];class Pt extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.object)return y(t,{code:p.invalid_type,expected:_.object,received:t.parsedType}),k;const n=this.discriminator,s=t.data[n],o=this.optionsMap.get(s);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(y(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),k)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const s=new Map;for(const o of t){const a=ue(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,o)}}return new Pt({typeName:w.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...S(n)})}}function tr(r,e){const t=ye(r),n=ye(e);if(r===e)return{valid:!0,data:r};if(t===_.object&&n===_.object){const s=P.objectKeys(e),o=P.objectKeys(r).filter(c=>s.indexOf(c)!==-1),a={...r,...e};for(const c of o){const u=tr(r[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(t===_.array&&n===_.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<r.length;o++){const a=r[o],c=e[o],u=tr(a,c);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===_.date&&n===_.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class ot extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Xt(o)||Xt(a))return k;const c=tr(o.value,a.value);return c.valid?((Qt(o)||Qt(a))&&t.dirty(),{status:t.value,value:c.data}):(y(n,{code:p.invalid_intersection_types}),k)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ot.create=(r,e,t)=>new ot({left:r,right:e,typeName:w.ZodIntersection,...S(t)});class ne extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.array)return y(n,{code:p.invalid_type,expected:_.array,received:n.parsedType}),k;if(n.data.length<this._def.items.length)return y(n,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),k;!this._def.rest&&n.data.length>this._def.items.length&&(y(n,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...n.data].map((a,c)=>{const u=this._def.items[c]||this._def.rest;return u?u._parse(new re(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>F.mergeArray(t,a)):F.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ne({...this._def,rest:e})}}ne.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ne({items:r,typeName:w.ZodTuple,rest:null,...S(e)})};class it extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.object)return y(n,{code:p.invalid_type,expected:_.object,received:n.parsedType}),k;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in n.data)s.push({key:o._parse(new re(n,c,n.path,c)),value:a._parse(new re(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?F.mergeObjectAsync(t,s):F.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new it({keyType:e,valueType:t,typeName:w.ZodRecord,...S(n)}):new it({keyType:H.create(),valueType:e,typeName:w.ZodRecord,...S(t)})}}class At extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.map)return y(n,{code:p.invalid_type,expected:_.map,received:n.parsedType}),k;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([c,u],l)=>({key:s._parse(new re(n,c,n.path,[l,"key"])),value:o._parse(new re(n,u,n.path,[l,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const u of a){const l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return k;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const u of a){const l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return k;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}}}}At.create=(r,e,t)=>new At({valueType:e,keyType:r,typeName:w.ZodMap,...S(t)});class Re extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.set)return y(n,{code:p.invalid_type,expected:_.set,received:n.parsedType}),k;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(y(n,{code:p.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(y(n,{code:p.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function a(u){const l=new Set;for(const d of u){if(d.status==="aborted")return k;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}const c=[...n.data.values()].map((u,l)=>o._parse(new re(n,u,n.path,l)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,t){return new Re({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new Re({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Re.create=(r,e)=>new Re({valueType:r,minSize:null,maxSize:null,typeName:w.ZodSet,...S(e)});class Fe extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.function)return y(t,{code:p.invalid_type,expected:_.function,received:t.parsedType}),k;function n(c,u){return Et({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kt(),De].filter(l=>!!l),issueData:{code:p.invalid_arguments,argumentsError:u}})}function s(c,u){return Et({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kt(),De].filter(l=>!!l),issueData:{code:p.invalid_return_type,returnTypeError:u}})}const o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Ze){const c=this;return V(async function(...u){const l=new q([]),d=await c._def.args.parseAsync(u,o).catch(m=>{throw l.addIssue(n(u,m)),l}),h=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(h,o).catch(m=>{throw l.addIssue(s(h,m)),l})})}else{const c=this;return V(function(...u){const l=c._def.args.safeParse(u,o);if(!l.success)throw new q([n(u,l.error)]);const d=Reflect.apply(a,this,l.data),h=c._def.returns.safeParse(d,o);if(!h.success)throw new q([s(d,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Fe({...this._def,args:ne.create(e).rest(Ie.create())})}returns(e){return new Fe({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Fe({args:e||ne.create([]).rest(Ie.create()),returns:t||Ie.create(),typeName:w.ZodFunction,...S(n)})}}class at extends x{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}at.create=(r,e)=>new at({getter:r,typeName:w.ZodLazy,...S(e)});class ct extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return y(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),k}return{status:"valid",value:e.data}}get value(){return this._def.value}}ct.create=(r,e)=>new ct({value:r,typeName:w.ZodLiteral,...S(e)});function Or(r,e){return new ve({values:r,typeName:w.ZodEnum,...S(e)})}class ve extends x{constructor(){super(...arguments),Qe.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{expected:P.joinValues(n),received:t.parsedType,code:p.invalid_type}),k}if(St(this,Qe)||Pr(this,Qe,new Set(this._def.values)),!St(this,Qe).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{received:t.data,code:p.invalid_enum_value,options:n}),k}return V(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ve.create(e,{...this._def,...t})}exclude(e,t=this._def){return ve.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}Qe=new WeakMap,ve.create=Or;class lt extends x{constructor(){super(...arguments),et.set(this,void 0)}_parse(e){const t=P.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==_.string&&n.parsedType!==_.number){const s=P.objectValues(t);return y(n,{expected:P.joinValues(s),received:n.parsedType,code:p.invalid_type}),k}if(St(this,et)||Pr(this,et,new Set(P.getValidEnumValues(this._def.values))),!St(this,et).has(e.data)){const s=P.objectValues(t);return y(n,{received:n.data,code:p.invalid_enum_value,options:s}),k}return V(e.data)}get enum(){return this._def.values}}et=new WeakMap,lt.create=(r,e)=>new lt({values:r,typeName:w.ZodNativeEnum,...S(e)});class Ze extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.promise&&t.common.async===!1)return y(t,{code:p.invalid_type,expected:_.promise,received:t.parsedType}),k;const n=t.parsedType===_.promise?t.data:Promise.resolve(t.data);return V(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ze.create=(r,e)=>new Ze({type:r,typeName:w.ZodPromise,...S(e)});class J extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{y(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return k;const u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?k:u.status==="dirty"||t.value==="dirty"?Le(u.value):u});{if(t.value==="aborted")return k;const c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?k:c.status==="dirty"||t.value==="dirty"?Le(c.value):c}}if(s.type==="refinement"){const a=c=>{const u=s.refinement(c,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){const c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?k:(c.status==="dirty"&&t.dirty(),a(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?k:(c.status==="dirty"&&t.dirty(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Je(a))return a;const c=s.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Je(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:t.value,value:c})):a);P.assertNever(s)}}J.create=(r,e,t)=>new J({schema:r,typeName:w.ZodEffects,effect:e,...S(t)}),J.createWithPreprocess=(r,e,t)=>new J({schema:e,effect:{type:"preprocess",transform:r},typeName:w.ZodEffects,...S(t)});class se extends x{_parse(e){return this._getType(e)===_.undefined?V(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}se.create=(r,e)=>new se({innerType:r,typeName:w.ZodOptional,...S(e)});class we extends x{_parse(e){return this._getType(e)===_.null?V(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}we.create=(r,e)=>new we({innerType:r,typeName:w.ZodNullable,...S(e)});class ut extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===_.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ut.create=(r,e)=>new ut({innerType:r,typeName:w.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});class dt extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Xe(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new q(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new q(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}dt.create=(r,e)=>new dt({innerType:r,typeName:w.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});class Tt extends x{_parse(e){if(this._getType(e)!==_.nan){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.nan,received:n.parsedType}),k}return{status:"valid",value:e.data}}}Tt.create=r=>new Tt({typeName:w.ZodNaN,...S(r)});const cs=Symbol("zod_brand");class rr extends x{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class pt extends x{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?k:o.status==="dirty"?(t.dirty(),Le(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?k:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new pt({in:e,out:t,typeName:w.ZodPipeline})}}class ft extends x{_parse(e){const t=this._def.innerType._parse(e),n=s=>(Je(s)&&(s.value=Object.freeze(s.value)),s);return Xe(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}ft.create=(r,e)=>new ft({innerType:r,typeName:w.ZodReadonly,...S(e)});function Nr(r,e={},t){return r?Ue.create().superRefine((n,s)=>{var o,a;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,u=(a=(o=c.fatal)!==null&&o!==void 0?o:t)!==null&&a!==void 0?a:!0,l=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...l,fatal:u})}}):Ue.create()}const ls={object:O.lazycreate};var w;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(w||(w={}));const us=(r,e={message:`Input not instance of ${r.name}`})=>Nr(t=>t instanceof r,e),Mr=H.create,jr=_e.create,ds=Tt.create,ps=ge.create,Dr=tt.create,fs=Te.create,hs=Ct.create,ms=rt.create,ys=nt.create,_s=Ue.create,gs=Ie.create,vs=le.create,ws=xt.create,bs=K.create,ks=O.create,Es=O.strictCreate,Ss=st.create,Cs=Pt.create,xs=ot.create,Ps=ne.create,As=it.create,Ts=At.create,Is=Re.create,Rs=Fe.create,Os=at.create,Ns=ct.create,Ms=ve.create,js=lt.create,Ds=Ze.create,Lr=J.create,Ls=se.create,Us=we.create,$s=J.createWithPreprocess,Fs=pt.create;var i=Object.freeze({__proto__:null,defaultErrorMap:De,setErrorMap:qn,getErrorMap:kt,makeIssue:Et,EMPTY_PATH:Gn,addIssueToContext:y,ParseStatus:F,INVALID:k,DIRTY:Le,OK:V,isAborted:Xt,isDirty:Qt,isValid:Je,isAsync:Xe,get util(){return P},get objectUtil(){return Jt},ZodParsedType:_,getParsedType:ye,ZodType:x,datetimeRegex:Rr,ZodString:H,ZodNumber:_e,ZodBigInt:ge,ZodBoolean:tt,ZodDate:Te,ZodSymbol:Ct,ZodUndefined:rt,ZodNull:nt,ZodAny:Ue,ZodUnknown:Ie,ZodNever:le,ZodVoid:xt,ZodArray:K,ZodObject:O,ZodUnion:st,ZodDiscriminatedUnion:Pt,ZodIntersection:ot,ZodTuple:ne,ZodRecord:it,ZodMap:At,ZodSet:Re,ZodFunction:Fe,ZodLazy:at,ZodLiteral:ct,ZodEnum:ve,ZodNativeEnum:lt,ZodPromise:Ze,ZodEffects:J,ZodTransformer:J,ZodOptional:se,ZodNullable:we,ZodDefault:ut,ZodCatch:dt,ZodNaN:Tt,BRAND:cs,ZodBranded:rr,ZodPipeline:pt,ZodReadonly:ft,custom:Nr,Schema:x,ZodSchema:x,late:ls,get ZodFirstPartyTypeKind(){return w},coerce:{string:r=>H.create({...r,coerce:!0}),number:r=>_e.create({...r,coerce:!0}),boolean:r=>tt.create({...r,coerce:!0}),bigint:r=>ge.create({...r,coerce:!0}),date:r=>Te.create({...r,coerce:!0})},any:_s,array:bs,bigint:ps,boolean:Dr,date:fs,discriminatedUnion:Cs,effect:Lr,enum:Ms,function:Rs,instanceof:us,intersection:xs,lazy:Os,literal:Ns,map:Ts,nan:ds,nativeEnum:js,never:vs,null:ys,nullable:Us,number:jr,object:ks,oboolean:()=>Dr().optional(),onumber:()=>jr().optional(),optional:Ls,ostring:()=>Mr().optional(),pipeline:Fs,preprocess:$s,promise:Ds,record:As,set:Is,strictObject:Es,string:Mr,symbol:hs,transformer:Lr,tuple:Ps,undefined:ms,union:Ss,unknown:gs,void:ws,NEVER:k,ZodIssueCode:p,quotelessJson:Bn,ZodError:q});const Zs=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()}),Vs=i.array(Zs),zs=i.object({code:i.string(),message:i.string(),path:i.array(i.string())}),Bs=i.array(zs),qs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},nr=r=>{const e=r.toLowerCase().trim();return qs[e]??r},Gs=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},Ys=r=>r.length===1?nr(r[0].msg):`Please fix the following errors:
1
+ (function(Te,je){typeof exports=="object"&&typeof module<"u"?je(exports):typeof define=="function"&&define.amd?define(["exports"],je):(Te=typeof globalThis<"u"?globalThis:Te||self,je(Te.OpenPay={}))})(this,function(Te){"use strict";const je="https://cde.getopenpay.com";var x;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},r.getValidEnumValues=s=>{const o=r.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of o)a[c]=s[c];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(o){return s[o]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},r.find=(s,o)=>{for(const a of s)if(o(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(x||(x={}));var Jt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Jt||(Jt={}));const _=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ge=r=>{switch(typeof r){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(r)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(r)?_.array:r===null?_.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?_.promise:typeof Map<"u"&&r instanceof Map?_.map:typeof Set<"u"&&r instanceof Set?_.set:typeof Date<"u"&&r instanceof Date?_.date:_.object;default:return _.unknown}},p=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class W extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let c=n,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof W))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}W.create=r=>new W(r);const De=(r,e)=>{let t;switch(r.code){case p.invalid_type:r.received===_.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case p.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case p.invalid_union:t="Invalid input";break;case p.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case p.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case p.invalid_arguments:t="Invalid function arguments";break;case p.invalid_return_type:t="Invalid function return type";break;case p.invalid_date:t="Invalid date";break;case p.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case p.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case p.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case p.custom:t="Invalid input";break;case p.invalid_intersection_types:t="Intersection results could not be merged";break;case p.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case p.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}};let Pr=De;function Yn(r){Pr=r}function kt(){return Pr}const Et=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,o=[...t,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let c="";const u=n.filter(l=>!!l).slice().reverse();for(const l of u)c=l(a,{data:e,defaultError:c}).message;return{...s,path:o,message:c}},Wn=[];function y(r,e){const t=kt(),n=Et({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===De?void 0:De].filter(s=>!!s)});r.common.issues.push(n)}class z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if(s.status==="aborted")return k;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return z.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return k;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const k=Object.freeze({status:"aborted"}),Le=r=>({status:"dirty",value:r}),q=r=>({status:"valid",value:r}),Xt=r=>r.status==="aborted",Qt=r=>r.status==="dirty",Je=r=>r.status==="valid",Xe=r=>typeof Promise<"u"&&r instanceof Promise;function St(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Ar(r,e,t,n,s){if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}typeof SuppressedError=="function"&&SuppressedError;var v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(v||(v={}));var Qe,et;class oe{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Tr=(r,e)=>{if(Je(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new W(r.common.issues);return this._error=t,this._error}}};function S(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,c)=>{var u,l;const{message:d}=r;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??n)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:c.defaultError}},description:s}}class C{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return ge(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ge(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new z,ctx:{common:e.parent.common,data:e.data,parsedType:ge(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Xe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ge(e)},o=this._parseSync({data:e,path:s.path,parent:s});return Tr(s,o)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ge(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Xe(s)?s:Promise.resolve(s));return Tr(n,o)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const a=e(s),c=()=>o.addIssue({code:p.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ee({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ae.create(this,this._def)}nullable(){return ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this,this._def)}promise(){return Ze.create(this,this._def)}or(e){return st.create([this,e],this._def)}and(e){return ot.create(this,e,this._def)}transform(e){return new ee({...S(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ut({...S(this._def),innerType:this,defaultValue:t,typeName:b.ZodDefault})}brand(){return new rr({typeName:b.ZodBranded,type:this,...S(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new dt({...S(this._def),innerType:this,catchValue:t,typeName:b.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return pt.create(this,e)}readonly(){return ft.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Hn=/^c[^\s-]{8,}$/i,Kn=/^[0-9a-z]+$/,Jn=/^[0-9A-HJKMNP-TV-Z]{26}$/,Xn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Qn=/^[a-z0-9_-]{21}$/i,es=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ts=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let er;const ns=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ss=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,os=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ir="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",is=new RegExp(`^${Ir}$`);function Or(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function as(r){return new RegExp(`^${Or(r)}$`)}function Rr(r){let e=`${Ir}T${Or(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function cs(r,e){return!!((e==="v4"||!e)&&ns.test(r)||(e==="v6"||!e)&&ss.test(r))}class X extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_.string){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.string,received:o.parsedType}),k}const n=new z;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,c=e.data.length<o.value;(a||c)&&(s=this._getOrReturnCtx(e,s),a?y(s,{code:p.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&y(s,{code:p.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")ts.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"email",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")er||(er=new RegExp(rs,"u")),er.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"emoji",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Xn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"uuid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Qn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"nanoid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Hn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Kn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"cuid2",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Jn.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ulid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),y(s,{validation:"url",code:p.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"regex",code:p.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Rr(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?is.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?as(o).test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{code:p.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?es.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"duration",code:p.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?cs(e.data,o.version)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"ip",code:p.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?os.test(e.data)||(s=this._getOrReturnCtx(e,s),y(s,{validation:"base64",code:p.invalid_string,message:o.message}),n.dirty()):x.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:p.invalid_string,...v.errToObj(n)})}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...v.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...v.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...v.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new X({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}X.create=r=>{var e;return new X({checks:[],typeName:b.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};function ls(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,o=parseInt(r.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class ve extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==_.number){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.number,received:o.parsedType}),k}let n;const s=new z;for(const o of this._def.checks)o.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:p.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?ls(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:p.not_finite,message:o.message}),s.dirty()):x.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new ve({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new ve({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ve.create=r=>new ve({checks:[],typeName:b.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class we extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==_.bigint){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.bigint,received:o.parsedType}),k}let n;const s=new z;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),y(n,{code:p.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):x.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new we({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new we({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}we.create=r=>{var e;return new we({checks:[],typeName:b.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...S(r)})};class tt extends C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_.boolean){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.boolean,received:n.parsedType}),k}return q(e.data)}}tt.create=r=>new tt({typeName:b.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Ie extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_.date){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_type,expected:_.date,received:o.parsedType}),k}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return y(o,{code:p.invalid_date}),k}const n=new z;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),y(s,{code:p.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):x.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ie({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Ie.create=r=>new Ie({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:b.ZodDate,...S(r)});class Ct extends C{_parse(e){if(this._getType(e)!==_.symbol){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.symbol,received:n.parsedType}),k}return q(e.data)}}Ct.create=r=>new Ct({typeName:b.ZodSymbol,...S(r)});class rt extends C{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.undefined,received:n.parsedType}),k}return q(e.data)}}rt.create=r=>new rt({typeName:b.ZodUndefined,...S(r)});class nt extends C{_parse(e){if(this._getType(e)!==_.null){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.null,received:n.parsedType}),k}return q(e.data)}}nt.create=r=>new nt({typeName:b.ZodNull,...S(r)});class Fe extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return q(e.data)}}Fe.create=r=>new Fe({typeName:b.ZodAny,...S(r)});class Oe extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return q(e.data)}}Oe.create=r=>new Oe({typeName:b.ZodUnknown,...S(r)});class pe extends C{_parse(e){const t=this._getOrReturnCtx(e);return y(t,{code:p.invalid_type,expected:_.never,received:t.parsedType}),k}}pe.create=r=>new pe({typeName:b.ZodNever,...S(r)});class xt extends C{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.void,received:n.parsedType}),k}return q(e.data)}}xt.create=r=>new xt({typeName:b.ZodVoid,...S(r)});class Q extends C{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==_.array)return y(t,{code:p.invalid_type,expected:_.array,received:t.parsedType}),k;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(a||c)&&(y(t,{code:a?p.too_big:p.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(y(t,{code:p.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(y(t,{code:p.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>s.type._parseAsync(new oe(t,a,t.path,c)))).then(a=>z.mergeArray(n,a));const o=[...t.data].map((a,c)=>s.type._parseSync(new oe(t,a,t.path,c)));return z.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}Q.create=(r,e)=>new Q({type:r,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...S(e)});function $e(r){if(r instanceof R){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=ae.create($e(n))}return new R({...r._def,shape:()=>e})}else return r instanceof Q?new Q({...r._def,type:$e(r.element)}):r instanceof ae?ae.create($e(r.unwrap())):r instanceof ke?ke.create($e(r.unwrap())):r instanceof ie?ie.create(r.items.map(e=>$e(e))):r}class R extends C{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==_.object){const l=this._getOrReturnCtx(e);return y(l,{code:p.invalid_type,expected:_.object,received:l.parsedType}),k}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof pe&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||c.push(l);const u=[];for(const l of a){const d=o[l],m=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new oe(s,m,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof pe){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")c.length>0&&(y(s,{code:p.unrecognized_keys,keys:c}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of c){const m=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new oe(s,m,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of u){const m=await d.key,w=await d.value;l.push({key:m,value:w,alwaysSet:d.alwaysSet})}return l}).then(l=>z.mergeObjectSync(n,l)):z.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new R({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,o,a,c;const u=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,t,n).message)!==null&&a!==void 0?a:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:u}:{message:u}}}:{}})}strip(){return new R({...this._def,unknownKeys:"strip"})}passthrough(){return new R({...this._def,unknownKeys:"passthrough"})}extend(e){return new R({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new R({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new R({...this._def,catchall:e})}pick(e){const t={};return x.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new R({...this._def,shape:()=>t})}omit(e){const t={};return x.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new R({...this._def,shape:()=>t})}deepPartial(){return $e(this)}partial(e){const t={};return x.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new R({...this._def,shape:()=>t})}required(e){const t={};return x.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ae;)o=o._def.innerType;t[n]=o}}),new R({...this._def,shape:()=>t})}keyof(){return Nr(x.objectKeys(this.shape))}}R.create=(r,e)=>new R({shape:()=>r,unknownKeys:"strip",catchall:pe.create(),typeName:b.ZodObject,...S(e)}),R.strictCreate=(r,e)=>new R({shape:()=>r,unknownKeys:"strict",catchall:pe.create(),typeName:b.ZodObject,...S(e)}),R.lazycreate=(r,e)=>new R({shape:r,unknownKeys:"strip",catchall:pe.create(),typeName:b.ZodObject,...S(e)});class st extends C{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const a=o.map(c=>new W(c.ctx.common.issues));return y(t,{code:p.invalid_union,unionErrors:a}),k}if(t.common.async)return Promise.all(n.map(async o=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const u of n){const l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(u=>new W(u));return y(t,{code:p.invalid_union,unionErrors:c}),k}}get options(){return this._def.options}}st.create=(r,e)=>new st({options:r,typeName:b.ZodUnion,...S(e)});const fe=r=>r instanceof at?fe(r.schema):r instanceof ee?fe(r.innerType()):r instanceof ct?[r.value]:r instanceof be?r.options:r instanceof lt?x.objectValues(r.enum):r instanceof ut?fe(r._def.innerType):r instanceof rt?[void 0]:r instanceof nt?[null]:r instanceof ae?[void 0,...fe(r.unwrap())]:r instanceof ke?[null,...fe(r.unwrap())]:r instanceof rr||r instanceof ft?fe(r.unwrap()):r instanceof dt?fe(r._def.innerType):[];class Pt extends C{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.object)return y(t,{code:p.invalid_type,expected:_.object,received:t.parsedType}),k;const n=this.discriminator,s=t.data[n],o=this.optionsMap.get(s);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(y(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),k)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const s=new Map;for(const o of t){const a=fe(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,o)}}return new Pt({typeName:b.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...S(n)})}}function tr(r,e){const t=ge(r),n=ge(e);if(r===e)return{valid:!0,data:r};if(t===_.object&&n===_.object){const s=x.objectKeys(e),o=x.objectKeys(r).filter(c=>s.indexOf(c)!==-1),a={...r,...e};for(const c of o){const u=tr(r[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(t===_.array&&n===_.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<r.length;o++){const a=r[o],c=e[o],u=tr(a,c);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===_.date&&n===_.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class ot extends C{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Xt(o)||Xt(a))return k;const c=tr(o.value,a.value);return c.valid?((Qt(o)||Qt(a))&&t.dirty(),{status:t.value,value:c.data}):(y(n,{code:p.invalid_intersection_types}),k)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ot.create=(r,e,t)=>new ot({left:r,right:e,typeName:b.ZodIntersection,...S(t)});class ie extends C{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.array)return y(n,{code:p.invalid_type,expected:_.array,received:n.parsedType}),k;if(n.data.length<this._def.items.length)return y(n,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),k;!this._def.rest&&n.data.length>this._def.items.length&&(y(n,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...n.data].map((a,c)=>{const u=this._def.items[c]||this._def.rest;return u?u._parse(new oe(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>z.mergeArray(t,a)):z.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ie({...this._def,rest:e})}}ie.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ie({items:r,typeName:b.ZodTuple,rest:null,...S(e)})};class it extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.object)return y(n,{code:p.invalid_type,expected:_.object,received:n.parsedType}),k;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in n.data)s.push({key:o._parse(new oe(n,c,n.path,c)),value:a._parse(new oe(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?z.mergeObjectAsync(t,s):z.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof C?new it({keyType:e,valueType:t,typeName:b.ZodRecord,...S(n)}):new it({keyType:X.create(),valueType:e,typeName:b.ZodRecord,...S(t)})}}class At extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.map)return y(n,{code:p.invalid_type,expected:_.map,received:n.parsedType}),k;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([c,u],l)=>({key:s._parse(new oe(n,c,n.path,[l,"key"])),value:o._parse(new oe(n,u,n.path,[l,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const u of a){const l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return k;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const u of a){const l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return k;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}}}}At.create=(r,e,t)=>new At({valueType:e,keyType:r,typeName:b.ZodMap,...S(t)});class Re extends C{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.set)return y(n,{code:p.invalid_type,expected:_.set,received:n.parsedType}),k;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(y(n,{code:p.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(y(n,{code:p.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function a(u){const l=new Set;for(const d of u){if(d.status==="aborted")return k;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}const c=[...n.data.values()].map((u,l)=>o._parse(new oe(n,u,n.path,l)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,t){return new Re({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new Re({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Re.create=(r,e)=>new Re({valueType:r,minSize:null,maxSize:null,typeName:b.ZodSet,...S(e)});class Ue extends C{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.function)return y(t,{code:p.invalid_type,expected:_.function,received:t.parsedType}),k;function n(c,u){return Et({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kt(),De].filter(l=>!!l),issueData:{code:p.invalid_arguments,argumentsError:u}})}function s(c,u){return Et({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kt(),De].filter(l=>!!l),issueData:{code:p.invalid_return_type,returnTypeError:u}})}const o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Ze){const c=this;return q(async function(...u){const l=new W([]),d=await c._def.args.parseAsync(u,o).catch(h=>{throw l.addIssue(n(u,h)),l}),m=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(m,o).catch(h=>{throw l.addIssue(s(m,h)),l})})}else{const c=this;return q(function(...u){const l=c._def.args.safeParse(u,o);if(!l.success)throw new W([n(u,l.error)]);const d=Reflect.apply(a,this,l.data),m=c._def.returns.safeParse(d,o);if(!m.success)throw new W([s(d,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ue({...this._def,args:ie.create(e).rest(Oe.create())})}returns(e){return new Ue({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Ue({args:e||ie.create([]).rest(Oe.create()),returns:t||Oe.create(),typeName:b.ZodFunction,...S(n)})}}class at extends C{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}at.create=(r,e)=>new at({getter:r,typeName:b.ZodLazy,...S(e)});class ct extends C{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return y(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),k}return{status:"valid",value:e.data}}get value(){return this._def.value}}ct.create=(r,e)=>new ct({value:r,typeName:b.ZodLiteral,...S(e)});function Nr(r,e){return new be({values:r,typeName:b.ZodEnum,...S(e)})}class be extends C{constructor(){super(...arguments),Qe.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{expected:x.joinValues(n),received:t.parsedType,code:p.invalid_type}),k}if(St(this,Qe)||Ar(this,Qe,new Set(this._def.values)),!St(this,Qe).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{received:t.data,code:p.invalid_enum_value,options:n}),k}return q(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}Qe=new WeakMap,be.create=Nr;class lt extends C{constructor(){super(...arguments),et.set(this,void 0)}_parse(e){const t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==_.string&&n.parsedType!==_.number){const s=x.objectValues(t);return y(n,{expected:x.joinValues(s),received:n.parsedType,code:p.invalid_type}),k}if(St(this,et)||Ar(this,et,new Set(x.getValidEnumValues(this._def.values))),!St(this,et).has(e.data)){const s=x.objectValues(t);return y(n,{received:n.data,code:p.invalid_enum_value,options:s}),k}return q(e.data)}get enum(){return this._def.values}}et=new WeakMap,lt.create=(r,e)=>new lt({values:r,typeName:b.ZodNativeEnum,...S(e)});class Ze extends C{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.promise&&t.common.async===!1)return y(t,{code:p.invalid_type,expected:_.promise,received:t.parsedType}),k;const n=t.parsedType===_.promise?t.data:Promise.resolve(t.data);return q(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ze.create=(r,e)=>new Ze({type:r,typeName:b.ZodPromise,...S(e)});class ee extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{y(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return k;const u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?k:u.status==="dirty"||t.value==="dirty"?Le(u.value):u});{if(t.value==="aborted")return k;const c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?k:c.status==="dirty"||t.value==="dirty"?Le(c.value):c}}if(s.type==="refinement"){const a=c=>{const u=s.refinement(c,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){const c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?k:(c.status==="dirty"&&t.dirty(),a(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?k:(c.status==="dirty"&&t.dirty(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Je(a))return a;const c=s.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Je(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:t.value,value:c})):a);x.assertNever(s)}}ee.create=(r,e,t)=>new ee({schema:r,typeName:b.ZodEffects,effect:e,...S(t)}),ee.createWithPreprocess=(r,e,t)=>new ee({schema:e,effect:{type:"preprocess",transform:r},typeName:b.ZodEffects,...S(t)});class ae extends C{_parse(e){return this._getType(e)===_.undefined?q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ae.create=(r,e)=>new ae({innerType:r,typeName:b.ZodOptional,...S(e)});class ke extends C{_parse(e){return this._getType(e)===_.null?q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ke.create=(r,e)=>new ke({innerType:r,typeName:b.ZodNullable,...S(e)});class ut extends C{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===_.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ut.create=(r,e)=>new ut({innerType:r,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});class dt extends C{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Xe(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new W(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new W(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}dt.create=(r,e)=>new dt({innerType:r,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});class Tt extends C{_parse(e){if(this._getType(e)!==_.nan){const n=this._getOrReturnCtx(e);return y(n,{code:p.invalid_type,expected:_.nan,received:n.parsedType}),k}return{status:"valid",value:e.data}}}Tt.create=r=>new Tt({typeName:b.ZodNaN,...S(r)});const us=Symbol("zod_brand");class rr extends C{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class pt extends C{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?k:o.status==="dirty"?(t.dirty(),Le(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?k:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new pt({in:e,out:t,typeName:b.ZodPipeline})}}class ft extends C{_parse(e){const t=this._def.innerType._parse(e),n=s=>(Je(s)&&(s.value=Object.freeze(s.value)),s);return Xe(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}ft.create=(r,e)=>new ft({innerType:r,typeName:b.ZodReadonly,...S(e)});function Mr(r,e={},t){return r?Fe.create().superRefine((n,s)=>{var o,a;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,u=(a=(o=c.fatal)!==null&&o!==void 0?o:t)!==null&&a!==void 0?a:!0,l=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...l,fatal:u})}}):Fe.create()}const ds={object:R.lazycreate};var b;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(b||(b={}));const ps=(r,e={message:`Input not instance of ${r.name}`})=>Mr(t=>t instanceof r,e),jr=X.create,Dr=ve.create,fs=Tt.create,hs=we.create,Lr=tt.create,ms=Ie.create,ys=Ct.create,_s=rt.create,gs=nt.create,vs=Fe.create,ws=Oe.create,bs=pe.create,ks=xt.create,Es=Q.create,Ss=R.create,Cs=R.strictCreate,xs=st.create,Ps=Pt.create,As=ot.create,Ts=ie.create,Is=it.create,Os=At.create,Rs=Re.create,Ns=Ue.create,Ms=at.create,js=ct.create,Ds=be.create,Ls=lt.create,Fs=Ze.create,Fr=ee.create,$s=ae.create,Us=ke.create,Zs=ee.createWithPreprocess,Vs=pt.create;var i=Object.freeze({__proto__:null,defaultErrorMap:De,setErrorMap:Yn,getErrorMap:kt,makeIssue:Et,EMPTY_PATH:Wn,addIssueToContext:y,ParseStatus:z,INVALID:k,DIRTY:Le,OK:q,isAborted:Xt,isDirty:Qt,isValid:Je,isAsync:Xe,get util(){return x},get objectUtil(){return Jt},ZodParsedType:_,getParsedType:ge,ZodType:C,datetimeRegex:Rr,ZodString:X,ZodNumber:ve,ZodBigInt:we,ZodBoolean:tt,ZodDate:Ie,ZodSymbol:Ct,ZodUndefined:rt,ZodNull:nt,ZodAny:Fe,ZodUnknown:Oe,ZodNever:pe,ZodVoid:xt,ZodArray:Q,ZodObject:R,ZodUnion:st,ZodDiscriminatedUnion:Pt,ZodIntersection:ot,ZodTuple:ie,ZodRecord:it,ZodMap:At,ZodSet:Re,ZodFunction:Ue,ZodLazy:at,ZodLiteral:ct,ZodEnum:be,ZodNativeEnum:lt,ZodPromise:Ze,ZodEffects:ee,ZodTransformer:ee,ZodOptional:ae,ZodNullable:ke,ZodDefault:ut,ZodCatch:dt,ZodNaN:Tt,BRAND:us,ZodBranded:rr,ZodPipeline:pt,ZodReadonly:ft,custom:Mr,Schema:C,ZodSchema:C,late:ds,get ZodFirstPartyTypeKind(){return b},coerce:{string:r=>X.create({...r,coerce:!0}),number:r=>ve.create({...r,coerce:!0}),boolean:r=>tt.create({...r,coerce:!0}),bigint:r=>we.create({...r,coerce:!0}),date:r=>Ie.create({...r,coerce:!0})},any:vs,array:Es,bigint:hs,boolean:Lr,date:ms,discriminatedUnion:Ps,effect:Fr,enum:Ds,function:Ns,instanceof:ps,intersection:As,lazy:Ms,literal:js,map:Os,nan:fs,nativeEnum:Ls,never:bs,null:gs,nullable:Us,number:Dr,object:Ss,oboolean:()=>Lr().optional(),onumber:()=>Dr().optional(),optional:$s,ostring:()=>jr().optional(),pipeline:Vs,preprocess:Zs,promise:Fs,record:Is,set:Rs,strictObject:Cs,string:jr,symbol:ys,transformer:Fr,tuple:Ts,undefined:_s,union:xs,unknown:ws,void:ks,NEVER:k,ZodIssueCode:p,quotelessJson:Gn,ZodError:W});const zs=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()}),Bs=i.array(zs),qs=i.object({code:i.string(),message:i.string(),path:i.array(i.string())}),Gs=i.array(qs),Ys={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},nr=r=>{const e=r.toLowerCase().trim();return Ys[e]??r},Ws=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},Hs=r=>r.length===1?nr(r[0].msg):`Please fix the following errors:
2
2
  ${r.map(t=>`• ${nr(t.msg)}`).join(`
3
- `)}`,Ws=r=>`Encountered the following errors:
3
+ `)}`,Ks=r=>`Encountered the following errors:
4
4
  ${r.map(t=>`- ${t.path.join("/")}: ${t.message}`).join(`
5
- `)}`,de=r=>{if(r instanceof Error)if(Gs(r.message)){const e=JSON.parse(r.message);return Vs.safeParse(e).success?Ys(e):Bs.safeParse(e).success?Ws(e):(console.warn(`Encountered unknown stringified JSON object:
6
- ${r.message}`),r.message)}else return nr(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},Hs=(r,e,t)=>(...n)=>{try{return e(...n)}catch(s){t(`[form] Error running callback (${r}):`,s);return}},Z=i.string().trim().min(1,{message:"Cannot be blank"}),N=i.string().trim().optional(),B=r=>i.nullable(r.optional());var f=(r=>(r.FIRST_NAME="firstName",r.LAST_NAME="lastName",r.EMAIL="email",r.ZIP_CODE="zipCode",r.CITY="city",r.STATE="state",r.COUNTRY="country",r.ADDRESS="address",r.PHONE="phone",r.PROMOTION_CODE="promotionCode",r))(f||{});const Ur=i.nativeEnum(f);var $r=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))($r||{});const Fr=i.nativeEnum($r),Zr=i.union([Ur,Fr]);var Ve=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(Ve||{});const Ks=i.nativeEnum(Ve),It=i.object({provider:i.string(),processor_name:B(i.string()),metadata:B(i.record(i.string(),i.any()))}),Js=i.object({id:i.string()});i.object({cardNumber:N,expiry:N,cvc:N}),i.object({backgroundColor:N,color:N,fontFamily:N,fontSize:N,fontWeight:N,margin:N,padding:N,letterSpacing:N,lineHeight:N,hideIcon:N});const X=i.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),Xs=X.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Qs=i.object({type:Xs}),eo=X.extract(["BLUR","FOCUS","CHANGE"]),to=i.object({type:eo,elementType:Fr,errors:i.array(i.string()).optional()}),ro=X.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),no=i.object({type:ro,message:Z,headers:i.record(i.string(),i.string()).optional()}),so=X.extract(["VALIDATION_ERROR"]),oo=i.object({type:so,elementType:Zr,errors:i.array(i.string())}),io=i.object({type:i.literal(X.enum.LAYOUT),height:Z}),ao=i.object({type:i.literal(X.enum.LOADED),sessionId:Z,totalAmountAtoms:i.number(),currency:N,checkoutPaymentMethods:i.array(It)}),co=i.object({type:i.literal(X.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:i.record(i.string(),i.any()),paymentFlowMetadata:i.any().optional(),startPFMetadata:i.optional(i.record(i.string(),i.any()))}),lo=i.object({type:i.literal(X.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:i.string()}),ht=i.object({firstName:Z,lastName:Z,email:Z,zipCode:Z,country:Z,promotionCode:N}),uo=i.object({firstName:N,lastName:N,email:Z,zipCode:Z,country:Z,promotionCode:N,address:N,city:N,state:N}),po=X.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),fo=i.object({type:po,sessionId:Z,checkoutPaymentMethod:It,paymentFlowMetadata:i.any().optional(),doNotUseLegacyCCFlow:i.boolean().optional(),existingCCPMId:N}).extend(ht.shape),ho=i.object({type:i.literal(X.enum.TOKENIZE_SUCCESS),isReadyForCheckout:i.boolean()}),mo=i.object({type:i.literal(X.enum.CHECKOUT_SUCCESS),invoiceUrls:i.array(i.string()),subscriptionIds:i.array(i.string()),customerId:i.string()}),yo=i.discriminatedUnion("type",[Qs,to,no,oo,io,ao,fo,ho,mo,co,lo]),_o=i.object({payload:yo,nonce:Z,formId:Z,elementId:Z});i.object({amountAtom:i.number(),currency:Z}),i.enum(["apple_pay","google_pay"]),i.object({secure_token:i.string(),promotion_code:i.string().optional()}),i.object({secure_token:i.string(),existing_cc_pm_id:B(i.string()),their_pm_id:B(i.string()),checkout_attempt_id:B(i.string()),processor_specific_metadata:B(i.record(i.string(),i.any()))});const sr=i.object({invoice_urls:i.array(i.string()),subscription_ids:i.array(i.string()),customer_id:i.string()}),go=i.object({elementType:i.string(),errors:i.array(i.string())});i.object({session_id:i.string()});const vo=i.object({success:i.literal(!1),error_type:i.literal("validation_error"),errors:i.array(go)}),wo=i.discriminatedUnion("success",[i.object({success:i.literal(!0)}),vo]);i.object({session_id:i.string(),checkout_payment_method:It,non_cde_form_fields:ht,do_not_use_legacy_cc_flow:i.boolean().optional(),existing_cc_pm_id:B(i.string())}),i.object({session_id:i.string(),checkout_payment_method:It,non_cde_form_fields:ht,extra_metadata:i.record(i.string(),i.any()).optional()});var Q=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))(Q||{});const bo=i.object({status:i.enum(["success","failure","cancelled"]),href:i.string().optional().nullable()});i.object({href:i.string().optional().nullable()});const ko=i.object({type:i.string(),redirect_url:i.string(),initial_intent_id:i.string(),consent_id:i.string(),their_pm_id:i.string().optional()}),Vr=i.object({type:i.string(),redirect_url:B(i.string()),initial_intent_id:B(i.string()),consent_id:B(i.string()),their_pm_id:B(i.string()),payment_session:B(i.record(i.string(),i.any()))}),Eo=i.discriminatedUnion("present",[i.object({present:i.literal(!0),href:i.string()}),i.object({present:i.literal(!1)})]),So=i.object({payment_methods:i.array(Js),pay_first_success_response:B(sr),required_user_actions:B(i.array(Vr))}),Co=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const s=Ur.parse(t);Array.isArray(n)?e[s]=n:Array.isArray(n._errors)&&(e[s]=n._errors)}catch{return}}),e},xo=i.object({stripe_pk:i.string(),client_secret:i.string(),stripe_pm_id:i.string()}),Po=i.object({type:i.string(),client_secret:i.string(),stripe_pk:i.string()}),Ao={usd:"usd",brl:"brl"},Rt=async r=>{for(let t=0;t<10;t++)zr()||await Ro(500);if(!zr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},To=async(r,e)=>{const t=await Rt(r);return{elements:t.elements(e),stripe:t}},Io=async(r,e,t,n,s)=>{const o=await Rt(r),a=Ao[t.toLowerCase().trim()];return o.paymentRequest({country:"US",currency:a,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},Ro=r=>new Promise(e=>{setTimeout(e,r)}),zr=()=>"Stripe"in window,Oo=async r=>new Promise((e,t)=>{try{r.on("paymentmethod",async n=>{console.log("paymentmethod EVT:: ",n),e(n)}),r.on("token",async n=>{console.log("token EVT:: ",n)}),r.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){t(n)}}),No=async(r,e)=>{if(!r.stripe_pk||!r.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(r)}`);const n=await(await Rt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:e.paymentMethod.id});if(n.error)throw e.complete("fail"),new Error(`Payment failed: ${n.error.message??"unknown"}`);return e.complete("success"),n},Mo=async r=>{var s,o,a,c;const t=await(await Rt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(s=t.setupIntent)==null?void 0:s.status;if(n==="succeeded")console.log("[3DS] CONFIRMING PM:",r.stripe_pm_id),console.log("[3DS] Setup intent created:",t.setupIntent);else throw n==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((o=t.error)==null?void 0:o.message)??((c=(a=t.setupIntent)==null?void 0:a.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},jo=r=>JSON.stringify(r);for(var D=[],or=0;or<256;++or)D.push((or+256).toString(16).slice(1));function Do(r,e=0){return(D[r[e+0]]+D[r[e+1]]+D[r[e+2]]+D[r[e+3]]+"-"+D[r[e+4]]+D[r[e+5]]+"-"+D[r[e+6]]+D[r[e+7]]+"-"+D[r[e+8]]+D[r[e+9]]+"-"+D[r[e+10]]+D[r[e+11]]+D[r[e+12]]+D[r[e+13]]+D[r[e+14]]+D[r[e+15]]).toLowerCase()}var Ot,Lo=new Uint8Array(16);function Uo(){if(!Ot&&(Ot=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ot))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ot(Lo)}var $o=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Br={randomUUID:$o};function Fo(r,e,t){if(Br.randomUUID&&!e&&!r)return Br.randomUUID();r=r||{};var n=r.random||(r.rng||Uo)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Do(n)}const ze=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((s,o)=>{const a=o.getAttribute("data-opid");return a?{...s,[a]:o.value}:s},{}),Zo=r=>{try{return _o.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var oe;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(oe||(oe={}));var Oe;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(Oe||(Oe={}));var mt;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(mt||(mt={}));var ir;(function(r){r.DataCloneError="DataCloneError"})(ir||(ir={}));var be;(function(r){r.Message="message"})(be||(be={}));const Vo=(r,e)=>{const t=[];let n=!1;return{destroy(s){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(o=>{o(s)}))},onDestroy(s){n?s():t.push(s)}}},zo=r=>(...e)=>{r&&console.log("[Penpal]",...e)},Bo={"http:":"80","https:":"443"},qo=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Go=["file:","data:"],Yo=r=>{if(r&&Go.find(c=>r.startsWith(c)))return"null";const e=document.location,t=qo.exec(r);let n,s,o;t?(n=t[1]?t[1]:e.protocol,s=t[2],o=t[4]):(n=e.protocol,s=e.hostname,o=e.port);const a=o&&o!==Bo[n]?`:${o}`:"";return`${n}//${s}${a}`},qr=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Wo=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Ho=(r,e,t)=>{const{localName:n,local:s,remote:o,originForSending:a,originForReceiving:c}=r;let u=!1;const l=d=>{if(d.source!==o||d.data.penpal!==oe.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const h=d.data,{methodName:b,args:m,id:g}=h;t(`${n}: Received ${b}() call`);const E=I=>C=>{if(t(`${n}: Sending ${b}() reply`),u){t(`${n}: Unable to send ${b}() reply due to destroyed connection`);return}const A={penpal:oe.Reply,id:g,resolution:I,returnValue:C};I===Oe.Rejected&&C instanceof Error&&(A.returnValue=qr(C),A.returnValueIsError=!0);try{o.postMessage(A,a)}catch(T){if(T.name===ir.DataCloneError){const me={penpal:oe.Reply,id:g,resolution:Oe.Rejected,returnValue:qr(T),returnValueIsError:!0};o.postMessage(me,a)}throw T}};new Promise(I=>I(e[b].apply(e,m))).then(E(Oe.Fulfilled),E(Oe.Rejected))};return s.addEventListener(be.Message,l),()=>{u=!0,s.removeEventListener(be.Message,l)}};let Ko=0;const Jo=()=>++Ko,Gr=".",Yr=r=>r?r.split(Gr):[],Xo=r=>r.join(Gr),Qo=(r,e)=>{const t=Yr(e||"");return t.push(r),Xo(t)},ei=(r,e,t)=>{const n=Yr(e);return n.reduce((s,o,a)=>(typeof s[o]>"u"&&(s[o]={}),a===n.length-1&&(s[o]=t),s[o]),r),r},Wr=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const s=r[n],o=Qo(n,e);typeof s=="object"&&Object.assign(t,Wr(s,o)),typeof s=="function"&&(t[o]=s)}),t},ti=r=>{const e={};for(const t in r)ei(e,t,r[t]);return e},ri=(r,e,t,n,s)=>{const{localName:o,local:a,remote:c,originForSending:u,originForReceiving:l}=e;let d=!1;s(`${o}: Connecting call sender`);const h=m=>(...g)=>{s(`${o}: Sending ${m}() call`);let E;try{c.closed&&(E=!0)}catch{E=!0}if(E&&n(),d){const I=new Error(`Unable to send ${m}() call due to destroyed connection`);throw I.code=mt.ConnectionDestroyed,I}return new Promise((I,C)=>{const A=Jo(),T=xe=>{if(xe.source!==c||xe.data.penpal!==oe.Reply||xe.data.id!==A)return;if(l!=="*"&&xe.origin!==l){s(`${o} received message from origin ${xe.origin} which did not match expected origin ${l}`);return}const Pe=xe.data;s(`${o}: Received ${m}() reply`),a.removeEventListener(be.Message,T);let Ne=Pe.returnValue;Pe.returnValueIsError&&(Ne=Wo(Ne)),(Pe.resolution===Oe.Fulfilled?I:C)(Ne)};a.addEventListener(be.Message,T);const me={penpal:oe.Call,id:A,methodName:m,args:g};c.postMessage(me,u)})},b=t.reduce((m,g)=>(m[g]=h(g),m),{});return Object.assign(r,ti(b)),()=>{d=!0}},ni=(r,e,t,n,s)=>{const{destroy:o,onDestroy:a}=n;let c,u;const l={};return d=>{if(e!=="*"&&d.origin!==e){s(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}s("Parent: Handshake - Received ACK");const h={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=Ho(h,r,s),a(c),u&&u.forEach(m=>{delete l[m]}),u=d.data.methodNames;const b=ri(l,h,u,o,s);return a(b),l}},si=(r,e,t,n)=>s=>{if(!s.source)return;if(t!=="*"&&s.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${s.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const o={penpal:oe.SynAck,methodNames:Object.keys(e)};s.source.postMessage(o,n)},oi=6e4,ii=(r,e)=>{const{destroy:t,onDestroy:n}=e,s=setInterval(()=>{r.isConnected||(clearInterval(s),t())},oi);n(()=>{clearInterval(s)})},ai=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=mt.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},ci=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=mt.NoIframeSrc,e}},Hr=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:s,debug:o=!1}=r;const a=zo(o),c=Vo("Parent",a),{onDestroy:u,destroy:l}=c;n||(ci(e),n=Yo(e.src));const d=n==="null"?"*":n,h=Wr(t),b=si(a,h,n,d),m=ni(h,n,d,c,a);return{promise:new Promise((E,I)=>{const C=ai(s,l),A=T=>{if(!(T.source!==e.contentWindow||!T.data)){if(T.data.penpal===oe.Syn){b(T);return}if(T.data.penpal===oe.Ack){const me=m(T);me&&(C(),E(me));return}}};window.addEventListener(be.Message,A),a("Parent: Awaiting handshake"),ii(e,c),u(T=>{window.removeEventListener(be.Message,A),T&&I(T)})}),destroy(){l()}}},li=async r=>{if(typeof r!="object"||!r)return!1;try{const e={type:"ping"},t=await r.send(e);if(t!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(t)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},ui=(r,e)=>!!r&&e,M=r=>i.nullable(r.optional());i.string().trim().min(1,{message:"Cannot be blank"});const di=i.object({cde_response_type:i.literal("error"),message:i.string(),headers:i.record(i.string(),i.string()).optional()});i.enum(["usd","brl"]);const Kr=i.object({name:i.string(),amount_atom_off:M(i.number()),percent_off:M(i.number()),currency:M(i.string()),duration:i.string(),duration_in_months:M(i.number())}),Jr=i.object({amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),currency:i.string(),description:M(i.string()),price_id:i.string(),billing_interval:M(i.string()),billing_interval_count:M(i.number().int()),quantity:i.number().int()}),pi=i.record(i.string(),i.any()),fi=i.object({name:i.string(),settings:M(pi)}),yt=i.object({provider:i.string(),processor_name:M(i.string()),metadata:M(i.record(i.string(),i.any()))}),hi=i.object({quantity:i.number()}),mi=i.object({id:M(i.string()),billing_interval:M(i.string()),billing_interval_count:M(i.number().int()),subscription_items:i.array(hi),trial_start:M(i.string()),trial_end:M(i.string())}),Xr=i.object({amount_atom:i.number()}),yi=i.object({amount_atom:i.number(),amount_atom_considering_discount_applied:i.number(),currency:i.string(),discount_amount_atoms:i.array(Xr),subscription_item_id:i.string()}),_i=i.object({coupon:Kr}),gi=i.object({currency:i.string(),discounts:i.array(_i),hosted_invoice_url:M(i.string()),lines:i.array(yi),remaining_amount_atom:i.number(),tax_amount_atom:i.number(),total_amount_atom:i.number(),total_discount_amount_atoms:i.array(Xr)}),Qr=i.object({created:i.array(mi),invoices:i.array(gi)}),en=i.object({preview:Qr,preview_post_trial:M(Qr),coupons:i.array(Kr)}),tn=i.object({status:i.literal("open"),token:i.string(),email:M(i.string()),line_items:i.array(Jr),amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),brand:fi,subs_preview:M(en),methods_available:i.array(yt)}),rn=i.discriminatedUnion("mode",[i.object({mode:i.literal("setup"),currency:i.nullable(i.undefined())}).extend(tn.shape),i.object({mode:i.enum(["payment","subscription"]),currency:i.string()}).extend(tn.shape)]),vi=i.object({status:i.literal("complete")}),wi=i.object({status:i.literal("expired")});i.union([rn,vi,wi]),i.object({logo:i.string(),icon:i.string(),primary_color:i.string(),secondary_color:i.string()}),i.object({secure_token:i.string(),pm_id:i.string()}),i.object({secure_token:i.string(),payment_input:i.any(),customer_first_name:i.string().optional(),customer_last_name:i.string().optional(),customer_email:i.string(),customer_zip_code:i.string(),customer_country:i.string(),line_items:i.array(Jr),total_amount_atom:i.number().int(),cancel_at_end:i.boolean(),checkout_payment_method:yt,promotion_code:i.string().optional(),do_not_use_legacy_cc_flow:i.boolean().optional(),use_confirmed_pm_id:M(i.string())});const bi=i.object({payment_method_id:i.string()});i.object({id:i.string(),return_url:i.string()});const ki=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()});i.array(ki);const Ei=i.object({new_customer_email:i.string().optional(),new_customer_address:i.record(i.string(),i.any()).optional(),new_customer_first_name:i.string().optional(),new_customer_last_name:i.string().optional()}),Si=i.object({price_id:i.string(),quantity:i.number().int()}),Ci=i.object({line_items:i.array(Si),promotion_code:i.string().optional(),displayed_total_amount_atom:i.number().int()}),xi=i.object({processor_specific_metadata:M(i.record(i.string(),i.any()))});i.object({payment_provider:i.string(),checkout_payment_method:yt,existing_cc_pm_id:i.string().optional(),their_existing_pm_id:i.string().optional(),use_pay_first_flow:i.boolean().optional(),pay_first_flow_cart_info:Ci.optional()}).extend(Ei.shape).extend(xi.shape);const nn=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),checkout_attempt_id:M(i.string())});i.object({fields:uo,checkoutPaymentMethod:yt}),i.object({session_id:i.string(),non_cde_form_fields:ht,checkout_payment_method:yt,extra_metadata:i.record(i.string(),i.any())});const Pi=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),cc_pm_id:i.string()});i.record(i.any());const Ai=r=>r.reduce((e,t)=>e+t,0);function Ti(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function Ii(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var Ri=function(){var r=function(t,n){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(s[a]=o[a])},r(t,n)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Oi=function(r){Ri(e,r);function e(t,n){var s=this.constructor,o=r.call(this,t,n)||this;return Object.defineProperty(o,"name",{value:s.name,enumerable:!1,configurable:!0}),Ti(o,s.prototype),Ii(o),o}return e}(Error);class sn extends Oi{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const Y=async(r,e,t)=>{const n=await r.send(e);if(Mi(n))throw new sn(n);if(!Ni(n,t)){const s=t.safeParse(n);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),s.error)}return n},Ni=(r,e)=>e.safeParse(r).success,Mi=r=>di.safeParse(r).success,ji=async(r,e)=>await Y(r,{type:"get_checkout_preview",payload:e},en),ke=async r=>await Y(r,{type:"get_prefill",payload:{}},rn),Nt=async(r,e)=>await Y(r,{type:"v2_start_payment_flow",payload:e},nn),Di=async(r,e)=>await Y(r,{type:"start_payment_flow_for_cc",payload:e},Pi),Li=async(r,e)=>await Y(r,{type:"start_payment_flow_for_pr",payload:e},nn),Ee=async(r,e)=>await Y(r,{type:"confirm_payment_flow",payload:e},So),Ui=async(r,e)=>await Y(r,{type:"check_if_popup_window_verified",payload:e},Eo),$i=async(r,e,t)=>{const n=await ji(r,{secure_token:e,promotion_code:t}),s=new Set(n.preview.invoices.map(c=>c.currency));if(s.size!==1)throw new Error(`Expected exactly one currency, got ${s.size}`);const o=s.values().next().value??"usd",a=Ai(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:o,amountAtom:a}},Mt=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const s=await $i(r,e,n);return{amountAtom:s.amountAtom,currency:s.currency}}},Fi=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>Y(n,{type:"tokenize_card",payload:e},wo)))},on=async(r,e)=>{try{return await Y(r,{type:"checkout_card_elements",payload:e},sr)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},Zi=async(r,e)=>await Y(r,{type:"setup_payment_method",payload:e},bi),jt=async(r,e)=>await Y(r,{type:"checkout",payload:e},sr),an=1e3,Vi=async(r,e)=>{console.log(e);const n=await Hr({iframe:r,debug:!0,timeout:an,childOrigin:"*"}).promise,s=await Y(n,{type:"ping-3ds-status"},bo);return console.log("🟢 CDE connection successful! Stopping polling... Result:",s),s};function ar(r){throw new Error(`Unhandled case: ${r}`)}const cr=10,cn=(r=0)=>e=>`\x1B[${e+r}m`,ln=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,un=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,R={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(R.modifier);const zi=Object.keys(R.color),Bi=Object.keys(R.bgColor);[...zi,...Bi];function qi(){const r=new Map;for(const[e,t]of Object.entries(R)){for(const[n,s]of Object.entries(t))R[n]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[n]=R[n],r.set(s[0],s[1]);Object.defineProperty(R,e,{value:t,enumerable:!1})}return Object.defineProperty(R,"codes",{value:r,enumerable:!1}),R.color.close="\x1B[39m",R.bgColor.close="\x1B[49m",R.color.ansi=cn(),R.color.ansi256=ln(),R.color.ansi16m=un(),R.bgColor.ansi=cn(cr),R.bgColor.ansi256=ln(cr),R.bgColor.ansi16m=un(cr),Object.defineProperties(R,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(o=>o+o).join(""));const s=Number.parseInt(n,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>R.rgbToAnsi256(...R.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,s;if(e>=232)t=((e-232)*10+8)/255,n=t,s=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,s=c%6/5}const o=Math.max(t,n,s)*2;if(o===0)return 30;let a=30+(Math.round(s)<<2|Math.round(n)<<1|Math.round(t));return o===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>R.ansi256ToAnsi(R.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>R.ansi256ToAnsi(R.hexToAnsi256(e)),enumerable:!1}}),R}const ie=qi(),Dt=(()=>{if(navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),dn=Dt!==0&&{level:Dt,hasBasic:!0,has256:Dt>=2,has16m:Dt>=3},Gi={stdout:dn,stderr:dn};function Yi(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const s=e.length;let o=0,a="";do a+=r.slice(o,n)+e+t,o=n+s,n=r.indexOf(e,o);while(n!==-1);return a+=r.slice(o),a}function Wi(r,e,t,n){let s=0,o="";do{const a=r[n-1]==="\r";o+=r.slice(s,a?n-1:n)+e+(a?`\r
5
+ `)}`,he=r=>{if(r instanceof Error)if(Ws(r.message)){const e=JSON.parse(r.message);return Bs.safeParse(e).success?Hs(e):Gs.safeParse(e).success?Ks(e):(console.warn(`Encountered unknown stringified JSON object:
6
+ ${r.message}`),r.message)}else return nr(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},Js=(r,e,t)=>(...n)=>{try{return e(...n)}catch(s){t(`[form] Error running callback (${r}):`,s);return}},B=i.string().trim().min(1,{message:"Cannot be blank"}),N=i.string().trim().optional(),Y=r=>i.nullable(r.optional());var f=(r=>(r.FIRST_NAME="firstName",r.LAST_NAME="lastName",r.EMAIL="email",r.ZIP_CODE="zipCode",r.CITY="city",r.STATE="state",r.COUNTRY="country",r.ADDRESS="address",r.PHONE="phone",r.PROMOTION_CODE="promotionCode",r))(f||{});const $r=i.nativeEnum(f);var Ur=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(Ur||{});const Zr=i.nativeEnum(Ur),Vr=i.union([$r,Zr]);var Ve=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(Ve||{});const Xs=i.nativeEnum(Ve),It=i.object({provider:i.string(),processor_name:Y(i.string()),metadata:Y(i.record(i.string(),i.any()))}),Qs=i.object({id:i.string()});i.object({cardNumber:N,expiry:N,cvc:N}),i.object({backgroundColor:N,color:N,fontFamily:N,fontSize:N,fontWeight:N,margin:N,padding:N,letterSpacing:N,lineHeight:N,hideIcon:N});const te=i.enum(["LAYOUT","LOADED","BLUR","FOCUS","CHANGE","TOKENIZE_STARTED","CHECKOUT_STARTED","PAYMENT_FLOW_STARTED","TOKENIZE_SUCCESS","CHECKOUT_SUCCESS","LOAD_ERROR","VALIDATION_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR","SETUP_PAYMENT_METHOD_SUCCESS","TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),eo=te.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),to=i.object({type:eo}),ro=te.extract(["BLUR","FOCUS","CHANGE"]),no=i.object({type:ro,elementType:Zr,errors:i.array(i.string()).optional()}),so=te.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),oo=i.object({type:so,message:B,headers:i.record(i.string(),i.string()).optional()}),io=te.extract(["VALIDATION_ERROR"]),ao=i.object({type:io,elementType:Vr,errors:i.array(i.string())}),co=i.object({type:i.literal(te.enum.LAYOUT),height:B}),lo=i.object({type:i.literal(te.enum.LOADED),sessionId:B,totalAmountAtoms:i.number(),currency:N,checkoutPaymentMethods:i.array(It)}),uo=i.object({type:i.literal(te.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:i.record(i.string(),i.any()),paymentFlowMetadata:i.any().optional(),startPFMetadata:i.optional(i.record(i.string(),i.any()))}),po=i.object({type:i.literal(te.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:i.string()}),ht=i.object({firstName:B,lastName:B,email:B,zipCode:B,country:B,promotionCode:N}),fo=i.object({firstName:N,lastName:N,email:B,zipCode:B,country:B,promotionCode:N,address:N,city:N,state:N}),ho=te.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),mo=i.object({type:ho,sessionId:B,checkoutPaymentMethod:It,paymentFlowMetadata:i.any().optional(),doNotUseLegacyCCFlow:i.boolean().optional(),existingCCPMId:N}).extend(ht.shape),yo=i.object({type:i.literal(te.enum.TOKENIZE_SUCCESS),isReadyForCheckout:i.boolean()}),_o=i.object({type:i.literal(te.enum.CHECKOUT_SUCCESS),invoiceUrls:i.array(i.string()),subscriptionIds:i.array(i.string()),customerId:i.string()}),go=i.discriminatedUnion("type",[to,no,oo,ao,co,lo,mo,yo,_o,uo,po]),vo=i.object({payload:go,nonce:B,formId:B,elementId:B});i.object({amountAtom:i.number(),currency:B}),i.enum(["apple_pay","google_pay"]),i.object({secure_token:i.string(),promotion_code:i.string().optional()}),i.object({secure_token:i.string(),existing_cc_pm_id:Y(i.string()),their_pm_id:Y(i.string()),checkout_attempt_id:Y(i.string()),processor_specific_metadata:Y(i.record(i.string(),i.any()))});const sr=i.object({invoice_urls:i.array(i.string()),subscription_ids:i.array(i.string()),customer_id:i.string()}),wo=i.object({elementType:i.string(),errors:i.array(i.string())});i.object({session_id:i.string()});const bo=i.object({success:i.literal(!1),error_type:i.literal("validation_error"),errors:i.array(wo)}),ko=i.discriminatedUnion("success",[i.object({success:i.literal(!0)}),bo]);i.object({session_id:i.string(),checkout_payment_method:It,non_cde_form_fields:ht,do_not_use_legacy_cc_flow:i.boolean().optional(),existing_cc_pm_id:Y(i.string())}),i.object({session_id:i.string(),checkout_payment_method:It,non_cde_form_fields:ht,extra_metadata:i.record(i.string(),i.any()).optional()});var re=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))(re||{});const Eo=i.object({status:i.enum(["success","failure","cancelled"]),href:i.string().optional().nullable()});i.object({href:i.string().optional().nullable()});const So=i.object({type:i.string(),redirect_url:i.string(),initial_intent_id:i.string(),consent_id:i.string(),their_pm_id:i.string().optional()}),zr=i.object({type:i.string(),redirect_url:Y(i.string()),initial_intent_id:Y(i.string()),consent_id:Y(i.string()),their_pm_id:Y(i.string()),payment_session:Y(i.record(i.string(),i.any()))}),Co=i.discriminatedUnion("present",[i.object({present:i.literal(!0),href:i.string()}),i.object({present:i.literal(!1)})]),xo=i.object({payment_methods:i.array(Qs),pay_first_success_response:Y(sr),required_user_actions:Y(i.array(zr))}),Po=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const s=$r.parse(t);Array.isArray(n)?e[s]=n:Array.isArray(n._errors)&&(e[s]=n._errors)}catch{return}}),e},Ao=i.object({stripe_pk:i.string(),client_secret:i.string(),stripe_pm_id:i.string()}),To=i.object({type:i.string(),client_secret:i.string(),stripe_pk:i.string()}),Io={usd:"usd",brl:"brl"},Ot=async r=>{for(let t=0;t<10;t++)Br()||await No(500);if(!Br())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},Oo=async(r,e)=>{const t=await Ot(r);return{elements:t.elements(e),stripe:t}},Ro=async(r,e,t,n,s)=>{const o=await Ot(r),a=Io[t.toLowerCase().trim()];return o.paymentRequest({country:"US",currency:a,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},No=r=>new Promise(e=>{setTimeout(e,r)}),Br=()=>"Stripe"in window,Mo=async r=>new Promise((e,t)=>{try{r.on("paymentmethod",async n=>{console.log("paymentmethod EVT:: ",n),e(n)}),r.on("token",async n=>{console.log("token EVT:: ",n)}),r.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){t(n)}}),jo=async(r,e)=>{if(!r.stripe_pk||!r.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(r)}`);const n=await(await Ot(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:e.paymentMethod.id});if(n.error)throw e.complete("fail"),new Error(`Payment failed: ${n.error.message??"unknown"}`);return e.complete("success"),n},Do=async r=>{var s,o,a,c;const t=await(await Ot(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(s=t.setupIntent)==null?void 0:s.status;if(n==="succeeded")console.log("[3DS] CONFIRMING PM:",r.stripe_pm_id),console.log("[3DS] Setup intent created:",t.setupIntent);else throw n==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((o=t.error)==null?void 0:o.message)??((c=(a=t.setupIntent)==null?void 0:a.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},Lo=r=>JSON.stringify(r);for(var F=[],or=0;or<256;++or)F.push((or+256).toString(16).slice(1));function Fo(r,e=0){return(F[r[e+0]]+F[r[e+1]]+F[r[e+2]]+F[r[e+3]]+"-"+F[r[e+4]]+F[r[e+5]]+"-"+F[r[e+6]]+F[r[e+7]]+"-"+F[r[e+8]]+F[r[e+9]]+"-"+F[r[e+10]]+F[r[e+11]]+F[r[e+12]]+F[r[e+13]]+F[r[e+14]]+F[r[e+15]]).toLowerCase()}var Rt,$o=new Uint8Array(16);function Uo(){if(!Rt&&(Rt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Rt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Rt($o)}var Zo=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const qr={randomUUID:Zo};function Vo(r,e,t){if(qr.randomUUID&&!e&&!r)return qr.randomUUID();r=r||{};var n=r.random||(r.rng||Uo)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Fo(n)}const ze=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((s,o)=>{const a=o.getAttribute("data-opid");return a?{...s,[a]:o.value}:s},{}),zo=r=>{try{return vo.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var ce;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(ce||(ce={}));var Ne;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(Ne||(Ne={}));var mt;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(mt||(mt={}));var ir;(function(r){r.DataCloneError="DataCloneError"})(ir||(ir={}));var Ee;(function(r){r.Message="message"})(Ee||(Ee={}));const Bo=(r,e)=>{const t=[];let n=!1;return{destroy(s){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(o=>{o(s)}))},onDestroy(s){n?s():t.push(s)}}},qo=r=>(...e)=>{r&&console.log("[Penpal]",...e)},Go={"http:":"80","https:":"443"},Yo=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Wo=["file:","data:"],Ho=r=>{if(r&&Wo.find(c=>r.startsWith(c)))return"null";const e=document.location,t=Yo.exec(r);let n,s,o;t?(n=t[1]?t[1]:e.protocol,s=t[2],o=t[4]):(n=e.protocol,s=e.hostname,o=e.port);const a=o&&o!==Go[n]?`:${o}`:"";return`${n}//${s}${a}`},Gr=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Ko=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Jo=(r,e,t)=>{const{localName:n,local:s,remote:o,originForSending:a,originForReceiving:c}=r;let u=!1;const l=d=>{if(d.source!==o||d.data.penpal!==ce.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const m=d.data,{methodName:w,args:h,id:g}=m;t(`${n}: Received ${w}() call`);const E=P=>T=>{if(t(`${n}: Sending ${w}() reply`),u){t(`${n}: Unable to send ${w}() reply due to destroyed connection`);return}const A={penpal:ce.Reply,id:g,resolution:P,returnValue:T};P===Ne.Rejected&&T instanceof Error&&(A.returnValue=Gr(T),A.returnValueIsError=!0);try{o.postMessage(A,a)}catch(I){if(I.name===ir.DataCloneError){const D={penpal:ce.Reply,id:g,resolution:Ne.Rejected,returnValue:Gr(I),returnValueIsError:!0};o.postMessage(D,a)}throw I}};new Promise(P=>P(e[w].apply(e,h))).then(E(Ne.Fulfilled),E(Ne.Rejected))};return s.addEventListener(Ee.Message,l),()=>{u=!0,s.removeEventListener(Ee.Message,l)}};let Xo=0;const Qo=()=>++Xo,Yr=".",Wr=r=>r?r.split(Yr):[],ei=r=>r.join(Yr),ti=(r,e)=>{const t=Wr(e||"");return t.push(r),ei(t)},ri=(r,e,t)=>{const n=Wr(e);return n.reduce((s,o,a)=>(typeof s[o]>"u"&&(s[o]={}),a===n.length-1&&(s[o]=t),s[o]),r),r},Hr=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const s=r[n],o=ti(n,e);typeof s=="object"&&Object.assign(t,Hr(s,o)),typeof s=="function"&&(t[o]=s)}),t},ni=r=>{const e={};for(const t in r)ri(e,t,r[t]);return e},si=(r,e,t,n,s)=>{const{localName:o,local:a,remote:c,originForSending:u,originForReceiving:l}=e;let d=!1;s(`${o}: Connecting call sender`);const m=h=>(...g)=>{s(`${o}: Sending ${h}() call`);let E;try{c.closed&&(E=!0)}catch{E=!0}if(E&&n(),d){const P=new Error(`Unable to send ${h}() call due to destroyed connection`);throw P.code=mt.ConnectionDestroyed,P}return new Promise((P,T)=>{const A=Qo(),I=L=>{if(L.source!==c||L.data.penpal!==ce.Reply||L.data.id!==A)return;if(l!=="*"&&L.origin!==l){s(`${o} received message from origin ${L.origin} which did not match expected origin ${l}`);return}const V=L.data;s(`${o}: Received ${h}() reply`),a.removeEventListener(Ee.Message,I);let Ae=V.returnValue;V.returnValueIsError&&(Ae=Ko(Ae)),(V.resolution===Ne.Fulfilled?P:T)(Ae)};a.addEventListener(Ee.Message,I);const D={penpal:ce.Call,id:A,methodName:h,args:g};c.postMessage(D,u)})},w=t.reduce((h,g)=>(h[g]=m(g),h),{});return Object.assign(r,ni(w)),()=>{d=!0}},oi=(r,e,t,n,s)=>{const{destroy:o,onDestroy:a}=n;let c,u;const l={};return d=>{if(e!=="*"&&d.origin!==e){s(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}s("Parent: Handshake - Received ACK");const m={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=Jo(m,r,s),a(c),u&&u.forEach(h=>{delete l[h]}),u=d.data.methodNames;const w=si(l,m,u,o,s);return a(w),l}},ii=(r,e,t,n)=>s=>{if(!s.source)return;if(t!=="*"&&s.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${s.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const o={penpal:ce.SynAck,methodNames:Object.keys(e)};s.source.postMessage(o,n)},ai=6e4,ci=(r,e)=>{const{destroy:t,onDestroy:n}=e,s=setInterval(()=>{r.isConnected||(clearInterval(s),t())},ai);n(()=>{clearInterval(s)})},li=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=mt.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},ui=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=mt.NoIframeSrc,e}},Kr=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:s,debug:o=!1}=r;const a=qo(o),c=Bo("Parent",a),{onDestroy:u,destroy:l}=c;n||(ui(e),n=Ho(e.src));const d=n==="null"?"*":n,m=Hr(t),w=ii(a,m,n,d),h=oi(m,n,d,c,a);return{promise:new Promise((E,P)=>{const T=li(s,l),A=I=>{if(!(I.source!==e.contentWindow||!I.data)){if(I.data.penpal===ce.Syn){w(I);return}if(I.data.penpal===ce.Ack){const D=h(I);D&&(T(),E(D));return}}};window.addEventListener(Ee.Message,A),a("Parent: Awaiting handshake"),ci(e,c),u(I=>{window.removeEventListener(Ee.Message,A),I&&P(I)})}),destroy(){l()}}},di=async r=>{if(typeof r!="object"||!r)return!1;try{const e={type:"ping"},t=await r.send(e);if(t!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(t)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},pi=(r,e)=>!!r&&e,M=r=>i.nullable(r.optional());i.string().trim().min(1,{message:"Cannot be blank"});const fi=i.object({cde_response_type:i.literal("error"),message:i.string(),headers:i.record(i.string(),i.string()).optional()});i.enum(["usd","brl"]);const Jr=i.object({name:i.string(),amount_atom_off:M(i.number()),percent_off:M(i.number()),currency:M(i.string()),duration:i.string(),duration_in_months:M(i.number())}),Xr=i.object({amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),currency:i.string(),description:M(i.string()),price_id:i.string(),billing_interval:M(i.string()),billing_interval_count:M(i.number().int()),quantity:i.number().int()}),hi=i.record(i.string(),i.any()),mi=i.object({name:i.string(),settings:M(hi)}),yt=i.object({provider:i.string(),processor_name:M(i.string()),metadata:M(i.record(i.string(),i.any()))}),yi=i.object({quantity:i.number()}),_i=i.object({id:M(i.string()),billing_interval:M(i.string()),billing_interval_count:M(i.number().int()),subscription_items:i.array(yi),trial_start:M(i.string()),trial_end:M(i.string())}),Qr=i.object({amount_atom:i.number()}),gi=i.object({amount_atom:i.number(),amount_atom_considering_discount_applied:i.number(),currency:i.string(),discount_amount_atoms:i.array(Qr),subscription_item_id:i.string()}),vi=i.object({coupon:Jr}),wi=i.object({currency:i.string(),discounts:i.array(vi),hosted_invoice_url:M(i.string()),lines:i.array(gi),remaining_amount_atom:i.number(),tax_amount_atom:i.number(),total_amount_atom:i.number(),total_discount_amount_atoms:i.array(Qr)}),en=i.object({created:i.array(_i),invoices:i.array(wi)}),tn=i.object({preview:en,preview_post_trial:M(en),coupons:i.array(Jr)}),rn=i.object({status:i.literal("open"),token:i.string(),email:M(i.string()),line_items:i.array(Xr),amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),brand:mi,subs_preview:M(tn),methods_available:i.array(yt)}),nn=i.discriminatedUnion("mode",[i.object({mode:i.literal("setup"),currency:i.nullable(i.undefined())}).extend(rn.shape),i.object({mode:i.enum(["payment","subscription"]),currency:i.string()}).extend(rn.shape)]),bi=i.object({status:i.literal("complete")}),ki=i.object({status:i.literal("expired")});i.union([nn,bi,ki]),i.object({logo:i.string(),icon:i.string(),primary_color:i.string(),secondary_color:i.string()}),i.object({secure_token:i.string(),pm_id:i.string()}),i.object({secure_token:i.string(),payment_input:i.any(),customer_first_name:i.string().optional(),customer_last_name:i.string().optional(),customer_email:i.string(),customer_zip_code:i.string(),customer_country:i.string(),line_items:i.array(Xr),total_amount_atom:i.number().int(),cancel_at_end:i.boolean(),checkout_payment_method:yt,promotion_code:i.string().optional(),do_not_use_legacy_cc_flow:i.boolean().optional(),use_confirmed_pm_id:M(i.string())});const Ei=i.object({payment_method_id:i.string()});i.object({id:i.string(),return_url:i.string()});const Si=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()});i.array(Si);const Ci=i.object({new_customer_email:i.string().optional(),new_customer_address:i.record(i.string(),i.any()).optional(),new_customer_first_name:i.string().optional(),new_customer_last_name:i.string().optional()}),xi=i.object({price_id:i.string(),quantity:i.number().int()}),Pi=i.object({line_items:i.array(xi),promotion_code:i.string().optional(),displayed_total_amount_atom:i.number().int()}),Ai=i.object({processor_specific_metadata:M(i.record(i.string(),i.any()))});i.object({payment_provider:i.string(),checkout_payment_method:yt,existing_cc_pm_id:i.string().optional(),their_existing_pm_id:i.string().optional(),use_pay_first_flow:i.boolean().optional(),pay_first_flow_cart_info:Pi.optional()}).extend(Ci.shape).extend(Ai.shape);const sn=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),checkout_attempt_id:M(i.string())});i.object({fields:fo,checkoutPaymentMethod:yt}),i.object({session_id:i.string(),non_cde_form_fields:ht,checkout_payment_method:yt,extra_metadata:i.record(i.string(),i.any())});const Ti=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),cc_pm_id:i.string()});i.record(i.any());const Ii=r=>r.reduce((e,t)=>e+t,0);function Oi(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function Ri(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var Ni=function(){var r=function(t,n){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(s[a]=o[a])},r(t,n)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Mi=function(r){Ni(e,r);function e(t,n){var s=this.constructor,o=r.call(this,t,n)||this;return Object.defineProperty(o,"name",{value:s.name,enumerable:!1,configurable:!0}),Oi(o,s.prototype),Ri(o),o}return e}(Error);class on extends Mi{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const K=async(r,e,t)=>{const n=await r.send(e);if(Di(n))throw new on(n);if(!ji(n,t)){const s=t.safeParse(n);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),s.error)}return n},ji=(r,e)=>e.safeParse(r).success,Di=r=>fi.safeParse(r).success,Li=async(r,e)=>await K(r,{type:"get_checkout_preview",payload:e},tn),Se=async r=>await K(r,{type:"get_prefill",payload:{}},nn),Nt=async(r,e)=>await K(r,{type:"v2_start_payment_flow",payload:e},sn),Fi=async(r,e)=>await K(r,{type:"start_payment_flow_for_cc",payload:e},Ti),$i=async(r,e)=>await K(r,{type:"start_payment_flow_for_pr",payload:e},sn),Ce=async(r,e)=>await K(r,{type:"confirm_payment_flow",payload:e},xo),Ui=async(r,e)=>await K(r,{type:"check_if_popup_window_verified",payload:e},Co),Zi=async(r,e,t)=>{const n=await Li(r,{secure_token:e,promotion_code:t}),s=new Set(n.preview.invoices.map(c=>c.currency));if(s.size!==1)throw new Error(`Expected exactly one currency, got ${s.size}`);const o=s.values().next().value??"usd",a=Ii(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:o,amountAtom:a}},Mt=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const s=await Zi(r,e,n);return{amountAtom:s.amountAtom,currency:s.currency}}},Vi=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>K(n,{type:"tokenize_card",payload:e},ko)))},an=async(r,e)=>{try{return await K(r,{type:"checkout_card_elements",payload:e},sr)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},zi=async(r,e)=>await K(r,{type:"setup_payment_method",payload:e},Ei),jt=async(r,e)=>await K(r,{type:"checkout",payload:e},sr),cn=1e3,Bi=async(r,e)=>{console.log(e);const n=await Kr({iframe:r,debug:!0,timeout:cn,childOrigin:"*"}).promise,s=await K(n,{type:"ping-3ds-status"},Eo);return console.log("🟢 CDE connection successful! Stopping polling... Result:",s),s};function ar(r){throw new Error(`Unhandled case: ${r}`)}const cr=10,ln=(r=0)=>e=>`\x1B[${e+r}m`,un=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,dn=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,O={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(O.modifier);const qi=Object.keys(O.color),Gi=Object.keys(O.bgColor);[...qi,...Gi];function Yi(){const r=new Map;for(const[e,t]of Object.entries(O)){for(const[n,s]of Object.entries(t))O[n]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[n]=O[n],r.set(s[0],s[1]);Object.defineProperty(O,e,{value:t,enumerable:!1})}return Object.defineProperty(O,"codes",{value:r,enumerable:!1}),O.color.close="\x1B[39m",O.bgColor.close="\x1B[49m",O.color.ansi=ln(),O.color.ansi256=un(),O.color.ansi16m=dn(),O.bgColor.ansi=ln(cr),O.bgColor.ansi256=un(cr),O.bgColor.ansi16m=dn(cr),Object.defineProperties(O,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(o=>o+o).join(""));const s=Number.parseInt(n,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>O.rgbToAnsi256(...O.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,s;if(e>=232)t=((e-232)*10+8)/255,n=t,s=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,s=c%6/5}const o=Math.max(t,n,s)*2;if(o===0)return 30;let a=30+(Math.round(s)<<2|Math.round(n)<<1|Math.round(t));return o===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>O.ansi256ToAnsi(O.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>O.ansi256ToAnsi(O.hexToAnsi256(e)),enumerable:!1}}),O}const le=Yi(),Dt=(()=>{if(navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),pn=Dt!==0&&{level:Dt,hasBasic:!0,has256:Dt>=2,has16m:Dt>=3},Wi={stdout:pn,stderr:pn};function Hi(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const s=e.length;let o=0,a="";do a+=r.slice(o,n)+e+t,o=n+s,n=r.indexOf(e,o);while(n!==-1);return a+=r.slice(o),a}function Ki(r,e,t,n){let s=0,o="";do{const a=r[n-1]==="\r";o+=r.slice(s,a?n-1:n)+e+(a?`\r
7
7
  `:`
8
8
  `)+t,s=n+1,n=r.indexOf(`
9
- `,s)}while(n!==-1);return o+=r.slice(s),o}const{stdout:pn,stderr:fn}=Gi,lr=Symbol("GENERATOR"),Be=Symbol("STYLER"),_t=Symbol("IS_EMPTY"),hn=["ansi","ansi","ansi256","ansi16m"],qe=Object.create(null),Hi=(r,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 t=pn?pn.level:0;r.level=e.level===void 0?t:e.level},Ki=r=>{const e=(...t)=>t.join(" ");return Hi(e,r),Object.setPrototypeOf(e,gt.prototype),e};function gt(r){return Ki(r)}Object.setPrototypeOf(gt.prototype,Function.prototype);for(const[r,e]of Object.entries(ie))qe[r]={get(){const t=Lt(this,dr(e.open,e.close,this[Be]),this[_t]);return Object.defineProperty(this,r,{value:t}),t}};qe.visible={get(){const r=Lt(this,this[Be],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const ur=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?ie[t].ansi16m(...n):e==="ansi256"?ie[t].ansi256(ie.rgbToAnsi256(...n)):ie[t].ansi(ie.rgbToAnsi(...n)):r==="hex"?ur("rgb",e,t,...ie.hexToRgb(...n)):ie[t][r](...n),Ji=["rgb","hex","ansi256"];for(const r of Ji){qe[r]={get(){const{level:t}=this;return function(...n){const s=dr(ur(r,hn[t],"color",...n),ie.color.close,this[Be]);return Lt(this,s,this[_t])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);qe[e]={get(){const{level:t}=this;return function(...n){const s=dr(ur(r,hn[t],"bgColor",...n),ie.bgColor.close,this[Be]);return Lt(this,s,this[_t])}}}}const Xi=Object.defineProperties(()=>{},{...qe,level:{enumerable:!0,get(){return this[lr].level},set(r){this[lr].level=r}}}),dr=(r,e,t)=>{let n,s;return t===void 0?(n=r,s=e):(n=t.openAll+r,s=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:s,parent:t}},Lt=(r,e,t)=>{const n=(...s)=>Qi(n,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(n,Xi),n[lr]=r,n[Be]=e,n[_t]=t,n},Qi=(r,e)=>{if(r.level<=0||!e)return r[_t]?"":e;let t=r[Be];if(t===void 0)return e;const{openAll:n,closeAll:s}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Yi(e,t.close,t.open),t=t.parent;const o=e.indexOf(`
10
- `);return o!==-1&&(e=Wi(e,s,n,o)),n+e+s};Object.defineProperties(gt.prototype,qe);const Ut=gt();gt({level:fn?fn.level:0});const Ge=r=>async e=>{var t,n;try{(n=(t=e.formCallbacks.get).onCheckoutStarted)==null||n.call(t);const s=await r(e);if(s.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(s.result.payment_method_id);else if(s.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(s.result.invoice_urls,s.result.subscription_ids,s.result.customer_id);else throw new Error(`Unhandled mode: ${s}`)}catch(s){e.formCallbacks.get.onCheckoutError(de(s))}},$t=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=L("init-error-catcher");return n(t),{isAvailable:!1,reason:de(t)}}},L=r=>{const e=(...n)=>{window.console.log(`${Ut.green.bold("ojs/")}${Ut.bold.gray(`${r}`)} `,...n)},t=(...n)=>{window.console.warn(`${Ut.red.bold("ojs/")}${Ut.bold.gray(`${r}`)} `,...n)};return{log:e,err:t,log__:e,err__:t}},{log__:cl,err__:ea}=L("common"),pr=r=>{if(r.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${r.payment_methods.length}`);return{payment_method_id:r.payment_methods[0].id}},Ye=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw ea("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},ta=r=>({new_customer_email:r.email,new_customer_address:{zip_code:r.zipCode,country:r.country},new_customer_first_name:r.firstName,new_customer_last_name:r.lastName}),{log__:ra,err__:mn}=L("common-cc"),We=(r,e)=>{const t=ht.safeParse(r);if(!t.success){const n=t.error.format(),s=Co(n);for(const[o,a]of Object.entries(s))e(o,a,o);throw mn("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return t.data},na=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const s=Zr.safeParse(n.elementType);if(!s.success)mn(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const o=s.data;e(o,n.errors)}}),ra(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},yn="ojs-stripe-link-btn",{log__:U,err__:sa}=L("stripe-link"),oa=i.object({provider:i.literal("stripe_link"),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),ia=i.array(i.object({our_existing_pm_id:i.string()})).length(1),aa=$t(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;U("Checking if there are any CPMs for Stripe Link...");const n=Ye(r.checkoutPaymentMethods,oa);U("Starting stripe link flow...");const s=r.anyCdeConnection,o=await ke(s),a=o.mode==="setup";U("Creating stripe elements...");const c=await Mt(s,o.token,a,void 0),{elements:u,stripe:l}=await To(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});U("Creating express checkout...");const d=u.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),h=()=>{d.mount(`#${yn}`)},b=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?U("NOT mounting stripe link button (doNotMountOnInit is true)"):(U("Mounting stripe link button..."),h()),d.on("click",async m=>{if(U("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){U("Stripe Link submit aborted by overrideLinkSubmit");return}m.resolve()}),d.on("confirm",async m=>{U("Stripe Link window confirmed",m);const g=await l.createPaymentMethod({elements:u,params:{billing_details:m.billingDetails}});g.error?(sa("error",g.error),e.get.onCheckoutError(g.error.message??"Stripe Link unknown error")):(U("paymentMethod",g.paymentMethod),ee.stripeLink.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,customParams:{stripePM:g.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:h,dismountButton:b,waitForButtonToMount:async()=>await ua(yn)}}}),ca=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{U("Running Stripe Link flow...");const o=r.anyCdeConnection;U("Merging PM fields with form fields...");const a=la(t,s.stripePM),c=We(a,n.get.onValidationError);U("Starting payment flow...");const u=await Nt(o,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:s.stripePM.id,new_customer_email:c[f.EMAIL],new_customer_first_name:c[f.FIRST_NAME],new_customer_last_name:c[f.LAST_NAME],new_customer_address:{zip_code:c[f.ZIP_CODE],country:c[f.COUNTRY]}});U("Start payment flow response",u);const d=ia.parse(u.required_user_actions)[0].our_existing_pm_id,h=await ke(o);if(h.mode==="setup"){U("Doing payment setup...");const b=await Ee(o,{secure_token:h.token,existing_cc_pm_id:d});return{mode:"setup",result:pr(b)}}else{U("Doing checkout...");const b={secure_token:h.token,payment_input:{provider_type:e.provider},customer_email:c[f.EMAIL],customer_zip_code:c[f.ZIP_CODE],customer_country:c[f.COUNTRY],promotion_code:c[f.PROMOTION_CODE],line_items:h.line_items,total_amount_atom:h.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await jt(o,b)}}}),la=(r,e)=>{var a,c,u,l,d;const t={...r},[n,...s]=((c=(a=e.billing_details.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],o=s.join(" ")||void 0;return t[f.FIRST_NAME]=t[f.FIRST_NAME]||n||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||o||"_OP_UNKNOWN",t[f.EMAIL]=t[f.EMAIL]||((u=e.link)==null?void 0:u.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[f.ZIP_CODE]=t[f.ZIP_CODE]||((l=e.billing_details.address)==null?void 0:l.postal_code)||"00000",t[f.COUNTRY]=t[f.COUNTRY]||((d=e.billing_details.address)==null?void 0:d.country)||"US",U("Final form inputs:",t),t},ua=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),da="@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{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}",pa=r=>{const e=document.createElement("template");e.innerHTML=`
9
+ `,s)}while(n!==-1);return o+=r.slice(s),o}const{stdout:fn,stderr:hn}=Wi,lr=Symbol("GENERATOR"),Be=Symbol("STYLER"),_t=Symbol("IS_EMPTY"),mn=["ansi","ansi","ansi256","ansi16m"],qe=Object.create(null),Ji=(r,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 t=fn?fn.level:0;r.level=e.level===void 0?t:e.level},Xi=r=>{const e=(...t)=>t.join(" ");return Ji(e,r),Object.setPrototypeOf(e,gt.prototype),e};function gt(r){return Xi(r)}Object.setPrototypeOf(gt.prototype,Function.prototype);for(const[r,e]of Object.entries(le))qe[r]={get(){const t=Lt(this,dr(e.open,e.close,this[Be]),this[_t]);return Object.defineProperty(this,r,{value:t}),t}};qe.visible={get(){const r=Lt(this,this[Be],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const ur=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?le[t].ansi16m(...n):e==="ansi256"?le[t].ansi256(le.rgbToAnsi256(...n)):le[t].ansi(le.rgbToAnsi(...n)):r==="hex"?ur("rgb",e,t,...le.hexToRgb(...n)):le[t][r](...n),Qi=["rgb","hex","ansi256"];for(const r of Qi){qe[r]={get(){const{level:t}=this;return function(...n){const s=dr(ur(r,mn[t],"color",...n),le.color.close,this[Be]);return Lt(this,s,this[_t])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);qe[e]={get(){const{level:t}=this;return function(...n){const s=dr(ur(r,mn[t],"bgColor",...n),le.bgColor.close,this[Be]);return Lt(this,s,this[_t])}}}}const ea=Object.defineProperties(()=>{},{...qe,level:{enumerable:!0,get(){return this[lr].level},set(r){this[lr].level=r}}}),dr=(r,e,t)=>{let n,s;return t===void 0?(n=r,s=e):(n=t.openAll+r,s=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:s,parent:t}},Lt=(r,e,t)=>{const n=(...s)=>ta(n,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(n,ea),n[lr]=r,n[Be]=e,n[_t]=t,n},ta=(r,e)=>{if(r.level<=0||!e)return r[_t]?"":e;let t=r[Be];if(t===void 0)return e;const{openAll:n,closeAll:s}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Hi(e,t.close,t.open),t=t.parent;const o=e.indexOf(`
10
+ `);return o!==-1&&(e=Ki(e,s,n,o)),n+e+s};Object.defineProperties(gt.prototype,qe);const Ft=gt();gt({level:hn?hn.level:0});const Ge=r=>async e=>{var t,n;try{(n=(t=e.formCallbacks.get).onCheckoutStarted)==null||n.call(t);const s=await r(e);if(s.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(s.result.payment_method_id);else if(s.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(s.result.invoice_urls,s.result.subscription_ids,s.result.customer_id);else throw new Error(`Unhandled mode: ${s}`)}catch(s){e.formCallbacks.get.onCheckoutError(he(s))}},$t=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=$("init-error-catcher");return n(t),{isAvailable:!1,reason:he(t)}}},$=r=>{const e=(...n)=>{window.console.log(`${Ft.green.bold("ojs/")}${Ft.bold.gray(`${r}`)} `,...n)},t=(...n)=>{window.console.warn(`${Ft.red.bold("ojs/")}${Ft.bold.gray(`${r}`)} `,...n)};return{log:e,err:t,log__:e,err__:t}},{log__:ll,err__:ra}=$("common"),pr=r=>{if(r.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${r.payment_methods.length}`);return{payment_method_id:r.payment_methods[0].id}},Ye=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw ra("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},na=r=>({new_customer_email:r.email,new_customer_address:{zip_code:r.zipCode,country:r.country},new_customer_first_name:r.firstName,new_customer_last_name:r.lastName}),{log__:yn,err__:_n}=$("common-cc"),We=(r,e,t)=>{if(t){yn(`Received default field values: ${JSON.stringify(t)}`);for(const[s,o]of Object.entries(t))r[s]||(r[s]=o)}const n=ht.safeParse(r);if(!n.success){const s=n.error.format(),o=Po(s);for(const[a,c]of Object.entries(o))e(a,c,a);throw _n("Got validation errors in non-CDE form fields",o),new Error("Got validation errors in non-CDE form fields")}return n.data},sa=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const s=Vr.safeParse(n.elementType);if(!s.success)_n(`Unknown field name in onValidationError: ${n.elementType}. Error object:`,n);else{const o=s.data;e(o,n.errors)}}),yn(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},gn="ojs-stripe-link-btn",{log__:U,err__:oa}=$("stripe-link"),ia=i.object({provider:i.literal("stripe_link"),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),aa=i.array(i.object({our_existing_pm_id:i.string()})).length(1),ca=$t(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;U("Checking if there are any CPMs for Stripe Link...");const n=Ye(r.checkoutPaymentMethods,ia);U("Starting stripe link flow...");const s=r.anyCdeConnection,o=await Se(s),a=o.mode==="setup";U("Creating stripe elements...");const c=await Mt(s,o.token,a,void 0),{elements:u,stripe:l}=await Oo(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});U("Creating express checkout...");const d=u.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),m=()=>{d.mount(`#${gn}`)},w=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?U("NOT mounting stripe link button (doNotMountOnInit is true)"):(U("Mounting stripe link button..."),m()),d.on("click",async h=>{if(U("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){U("Stripe Link submit aborted by overrideLinkSubmit");return}h.resolve()}),d.on("confirm",async h=>{U("Stripe Link window confirmed",h);const g=await l.createPaymentMethod({elements:u,params:{billing_details:h.billingDetails}});g.error?(oa("error",g.error),e.get.onCheckoutError(g.error.message??"Stripe Link unknown error")):(U("paymentMethod",g.paymentMethod),ne.stripeLink.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,customParams:{stripePM:g.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:m,dismountButton:w,waitForButtonToMount:async()=>await da(gn)}}}),la=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{U("Running Stripe Link flow...");const o=r.anyCdeConnection;U("Merging PM fields with form fields...");const a=ua(t,s.stripePM),c=We(a,n.get.onValidationError);U("Starting payment flow...");const u=await Nt(o,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:s.stripePM.id,new_customer_email:c[f.EMAIL],new_customer_first_name:c[f.FIRST_NAME],new_customer_last_name:c[f.LAST_NAME],new_customer_address:{zip_code:c[f.ZIP_CODE],country:c[f.COUNTRY]}});U("Start payment flow response",u);const d=aa.parse(u.required_user_actions)[0].our_existing_pm_id,m=await Se(o);if(m.mode==="setup"){U("Doing payment setup...");const w=await Ce(o,{secure_token:m.token,existing_cc_pm_id:d});return{mode:"setup",result:pr(w)}}else{U("Doing checkout...");const w={secure_token:m.token,payment_input:{provider_type:e.provider},customer_email:c[f.EMAIL],customer_zip_code:c[f.ZIP_CODE],customer_country:c[f.COUNTRY],promotion_code:c[f.PROMOTION_CODE],line_items:m.line_items,total_amount_atom:m.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await jt(o,w)}}}),ua=(r,e)=>{var a,c,u,l,d;const t={...r},[n,...s]=((c=(a=e.billing_details.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],o=s.join(" ")||void 0;return t[f.FIRST_NAME]=t[f.FIRST_NAME]||n||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||o||"_OP_UNKNOWN",t[f.EMAIL]=t[f.EMAIL]||((u=e.link)==null?void 0:u.email)||e.billing_details.email||"op_unfilled@getopenpay.com",t[f.ZIP_CODE]=t[f.ZIP_CODE]||((l=e.billing_details.address)==null?void 0:l.postal_code)||"00000",t[f.COUNTRY]=t[f.COUNTRY]||((d=e.billing_details.address)==null?void 0:d.country)||"US",U("Final form inputs:",t),t},da=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),pa="@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{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}",fa=r=>{const e=document.createElement("template");e.innerHTML=`
11
11
  <style>
12
- ${da}
12
+ ${pa}
13
13
  </style>
14
14
  <div class="overlay">
15
15
  <div class="container">
@@ -17,9 +17,9 @@ ${r.message}`),r.message)}else return nr(r.message);if(typeof r=="object")try{re
17
17
  <iframe src="${r}" class="frame" id="three-ds-iframe" title="3D Secure verification" allow="payment"></iframe>
18
18
  </div>
19
19
  </div>
20
- `;const t=document.createElement("div"),n=t.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const s=n.querySelector("#three-ds-iframe"),o=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:s,cancelButton:o}};function fa(r,e,t){const n=async()=>{try{const o=await Vi(r,t);o&&(clearInterval(s),e(o))}catch{}};n();const s=setInterval(n,an);return s}function ha({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t({status:Q.CANCELLED})};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Ft(r){const{url:e,baseUrl:t}=r,n=pa(e);return new Promise(s=>{const o=u=>{setTimeout(()=>{n.host.remove()},1e3),s(u),c==null||c()},a=fa(n.iframe,o,new URL(t).origin),c=ha({elements:n,pollingInterval:a,resolve:s})})}const _n=async r=>{const e=await Ft(r);if(e.status===Q.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===Q.FAILURE)throw new Error("3DS verification failed");return e.status!==Q.SUCCESS&&ar(e.status),{href:e.href}},ma=(r,e)=>{const t=window.open(e,"_blank");if(!t)throw new Error(`${r} popup window blocked. Please allow popups for this site.`);return t},ya=async(r,e,t,n)=>{const{err__:s}=L("popup-verify");return new Promise((o,a)=>{const c=ma(r,n),u=setInterval(async()=>{try{const l=await Ui(e,t);if(l.present)clearInterval(u),c.close(),o({href:l.href});else if(c.closed)throw new Error(`${r} payment cancelled`)}catch(l){s(de(l)),clearInterval(u),a(de(l))}},1e3)})},{log__:_a,err__:gn}=L("pockyt-cc"),ga=i.object({"op-pockyt-3ds-url":i.string(),"op-pockyt-txn-no":i.string(),"op-pockyt-ref-no":i.string()}),va=r=>{const e=ga.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw gn(n),new Error(t)}return e.data},vn=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return _a(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw gn(t,`Resulting URL: ${r}.
21
- Error: ${de(e)}`),new Error(t)}},wa=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,ba=async(r,e)=>{const t=va(e),n=await _n({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:vn(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:ka,err__:fr}=L("airwallex-cc"),Ea=i.object({"op-airwallex-3ds-url":i.string(),"op-airwallex-initial-intent-id":i.string(),"op-airwallex-consent-id":i.string()}),Sa=r=>{const e=Ea.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw fr(n),new Error(t)}return e.data},Ca=r=>(r==null?void 0:r["op-airwallex-3ds-url"])!==void 0,xa=r=>{try{const e=new URL(r??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return ka(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw fr(t,`Resulting URL: ${r}.
22
- Error: ${de(e)}`),new Error(t)}},Pa=async(r,e)=>{const t=Sa(e),n=await _n({url:t["op-airwallex-3ds-url"],baseUrl:r}),s=xa(n.href??""),o=t["op-airwallex-initial-intent-id"];if(o!==s){const c="Unable to process your credit card. Please contact support for assistance.",u=`Intent ID from callback (${s}) does not match the initial intent ID (${o}).`;throw fr(u),new Error(c)}return{existing_cc:{initial_intent_id:s,consent_id:t["op-airwallex-consent-id"]}}},{log__:j,err__:wn}=L("common-cc"),{log__:bn}=L("stripe-cc");i.array(i.object({our_existing_pm_id:i.string()})).length(1);const Aa=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var l;j("├ Running common CC flow...",{checkoutPaymentMethod:e});const o=r.anyCdeConnection,a=await ke(o);j(`├ Validating non-CDE form fields [Mode: ${a.mode}]`);const c=We(t,n.get.onValidationError),u={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{}};try{j(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await Fi(s.currentCdeConnections,{session_id:r.elementsSessionId});if(na(d,n.get.onValidationError),a.mode==="setup"){j(`├ Setting up payment method in CDE [Token: ${a.token}]`);const h=await Zi(o,u);return j(`╰ Setup completed successfully [PM ID: ${h.payment_method_id}]`),{mode:"setup",result:h}}else{j(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const h=await on(o,u);return j("╰ Checkout completed successfully."),{mode:"checkout",result:h}}}catch(d){if(d instanceof sn&&d.originalErrorMessage.includes("3DS_REQUIRED")){j("├ Card requires 3DS, starting non-legacy payment flow"),j("Received 3DS error response headers:",d.response.headers);const h=wa(d.response.headers);if(h){j("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await ba(r.baseUrl,d.response.headers);u.extra_metadata.pockyt=C}const b=Ca(d.response.headers);if(b){j("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await Pa(r.baseUrl,d.response.headers);u.extra_metadata.airwallex=C}const m=await Di(o,u);j("├ Payment flow result:",m);const g=h||b,E=((l=d.response.headers)==null?void 0:l["op-should-use-new-flow"])!=="true";g?j("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):E?(j("├ Using stripe 3DS flow"),await Oa(m)):(j("├ Using common 3DS flow"),await Ra(m,r.baseUrl));const I=m.cc_pm_id;if(a.mode==="setup"){j(`├ Confirming payment flow [cc_pm_id: ${I}]`);const C=await Ee(o,{secure_token:a.token,existing_cc_pm_id:I});j("├ Confirm payment flow result received Result:",C);const A=pr(C);return j(`╰ Setup completed successfully [PM ID: ${A.payment_method_id}]`),{mode:"setup",result:A}}else{j(`├ Checking out after 3DS flow [Flow: ${E?"legacy":"new"}]`);const C=await on(o,{...u,existing_cc_pm_id:I,do_not_use_legacy_cc_flow:E});return j("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw wn("╰ Error checking out card info in CDE"),wn(d),d}}),Ta=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return xo.parse(e)},Ia=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");if(!e)throw new Error("No common 3DS action found");return ko.parse(e)},Ra=async(r,e)=>{const t=Ia(r);j(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Ft({url:t.redirect_url,baseUrl:e});if(j(`╰ 3DS verification completed [Status: ${n}]`),n===Q.CANCELLED)throw new Error("3DS verification cancelled");if(n===Q.FAILURE)throw new Error("3DS verification failed")},Oa=async r=>{const e=Ta(r);bn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Mo(e),bn("╰ Stripe 3DS flow completed successfully")},{log__:z,err__:Na}=L("stripe-pr"),Ma=i.object({provider:i.union([i.literal("apple_pay"),i.literal("google_pay")]),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),ja=$t(async({context:r})=>{z("Checking if there are any CPMs for Stripe PR...");const e=Ye(r.checkoutPaymentMethods,Ma);z("Initializing Stripe PR flow...");const t=r.anyCdeConnection,n=await ke(t),s=n.mode==="setup";z("Getting initial preview amount");const o=await Mt(t,n.token,s,void 0),a=await Io(e.metadata.stripe_pk,o.amountAtom,o.currency,s);z("Checking if can make payment");const c=await a.canMakePayment();return c===null?(Na("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(z("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:a,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),Da=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s,initResult:o})=>{if(z("Running Stripe PR flow..."),s.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${s.provider}, got ${e.provider}`);const a=r.anyCdeConnection,c=o.pr;if(s!=null&&s.overridePaymentRequest){const g=s.overridePaymentRequest;z("Overriding PR amount with",g),Ua(c,g.amount,g.pending,g.stripeApplePay)}z("Showing PR dialog..."),c.show();const u=await Oo(c);z("Stripe PM added event:",u),z("Merging PM fields with form fields...");const l=La(t,u),d=We(l,n.get.onValidationError);z("PR dialog finished. Starting payment flow...",d);const h=await Li(a,{fields:d,checkoutPaymentMethod:e}),b=$a(h);z("Confirming PR with Stripe..."),await No(b,u);const m=await ke(a);if(m.mode==="setup"){z("Confirming payment flow for setup...");const g=await Ee(a,{secure_token:m.token});return{mode:"setup",result:pr(g)}}else{z("Performing checkout...");const g={secure_token:m.token,payment_input:{provider_type:e.provider},customer_first_name:d[f.FIRST_NAME],customer_last_name:d[f.LAST_NAME],customer_email:d[f.EMAIL],customer_zip_code:d[f.ZIP_CODE],customer_country:d[f.COUNTRY],promotion_code:d[f.PROMOTION_CODE],line_items:m.line_items,total_amount_atom:m.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await jt(a,g)}}}),La=(r,e)=>{var u,l,d,h;const t={...r},[n,...s]=((l=(u=e.payerName)==null?void 0:u.trim())==null?void 0:l.split(/\s+/))??[],o=s.join(" ")||void 0,a=(h=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:h.address,c=e.shippingAddress;return t[f.FIRST_NAME]=t[f.FIRST_NAME]||n||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||o||"_OP_UNKNOWN",t[f.EMAIL]=t[f.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[f.ZIP_CODE]=t[f.ZIP_CODE]||(a==null?void 0:a.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[f.COUNTRY]=t[f.COUNTRY]||(a==null?void 0:a.country)||(c==null?void 0:c.country)||"US",z("Final form inputs:",t),t},Ua=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},$a=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
23
- Details: got ${r.required_user_actions.length} required user actions`);return Po.parse(r.required_user_actions[0])},{log__:pe,err__:kn}=L("pockyt-paypal"),Fa=i.object({processor_name:i.literal("pockyt"),provider:i.literal("paypal")}),Za=i.array(i.object({paypal_iframe_url:i.string(),verify_token:i.string()})).length(1),Va=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n})=>{pe("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,o=await ke(s);pe("Verifying CPM...");const a=Fa.parse(e);pe("├ Validating non-CDE form fields");const c=We(t,n.get.onValidationError),u=ta(c);pe(`Starting payment flow... Mode: ${o.mode}`);const l=o.mode!=="setup",d=await Nt(s,{payment_provider:a.provider,checkout_payment_method:a,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:o.line_items,displayed_total_amount_atom:o.amount_total_atom}:void 0,...u});if(pe("Start payment flow response",d),!d.checkout_attempt_id)throw kn("Checkout attempt ID not found in response:",d),new Error("An error occurred during checkout, please try again with another payment method.");const h=Za.parse(d.required_user_actions)[0];pe("Opening paypal iframe...");const b=await ya("PayPal",s,h.verify_token,h.paypal_iframe_url);pe("Paypal flow result",b);const m=vn(b.href);pe(`Confirming payment flow using vault ID ${m}`);const g=await Ee(s,{secure_token:o.token,their_pm_id:m,checkout_attempt_id:l?d.checkout_attempt_id:void 0});if(pe("Confirm payment flow result",g),o.mode==="setup")return{mode:"setup",result:{payment_method_id:g.payment_methods[0].id}};if(!g.pay_first_success_response)throw kn("Checkout failed, no pay-first success response:",g),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:g.pay_first_success_response}}),hr=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:s})=>{var c;const o={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:r,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n,merchantName:t}};if(!s)return o;const a=Math.max(s.amountAtom/100,0);return{...o,transactionInfo:{countryCode:"US",currencyCode:((c=s.currency)==null?void 0:c.toUpperCase())??"USD",totalPriceStatus:"FINAL",totalPrice:a.toFixed(2)}}},za=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://pay.google.com/gp/p/js/pay.js",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Google Pay SDK")),document.body.appendChild(t)}),Ba=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?Vr.parse(e):null},qa=(r,e)=>{var s,o,a,c;const t={...r},n=(o=(s=e.paymentMethodData)==null?void 0:s.info)==null?void 0:o.billingAddress;if(n){const[u,...l]=((c=(a=n.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],d=l.join(" ")||void 0;t[f.EMAIL]=t[f.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[f.COUNTRY]=t[f.COUNTRY]||n.countryCode||"US",t[f.ADDRESS]=t[f.ADDRESS]||n.address1||"",t[f.CITY]=t[f.CITY]||n.locality||"",t[f.ZIP_CODE]=t[f.ZIP_CODE]||n.postalCode||"00000",t[f.STATE]=t[f.STATE]||n.administrativeArea||"",t[f.FIRST_NAME]=t[f.FIRST_NAME]||u||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:W,err__:vt}=L("gpay");let mr=null;const En=r=>{const e=r===je?"PRODUCTION":"TEST";return mr===null&&(mr=new window.google.payments.api.PaymentsClient({environment:e,merchantInfo:hr({gateway:"airwallex",gatewayMerchantId:"",merchantName:""}).merchantInfo})),mr},Sn=i.object({provider:i.literal("google_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string()})}),Ga=$t(async({context:r,formCallbacks:e})=>{var o,a;const t=Ye(r.checkoutPaymentMethods,Sn);if(!t)return{isAvailable:!1};W("Google Pay CPM",t);const n=t.metadata;if(!n.processor_account_id)return vt("No gateway merchant ID found in processor account"),{isAvailable:!1};if(W("Loading Google Pay SDK..."),await za(),!((a=(o=window.google)==null?void 0:o.payments)!=null&&a.api))return vt("Google Pay SDK not loaded properly"),{isAvailable:!1};W("Google Pay SDK loaded",window.google.payments);try{const{result:c}=await En(r.baseUrl).isReadyToPay(hr({gateway:"airwallex",gatewayMerchantId:n.processor_account_id,merchantName:n.processor_account_name,merchantId:"",initialPreview:void 0}));if(!c)return W("Google Pay is not available for this user"),{isAvailable:!1}}catch(c){return vt("Error checking Google Pay availability",c),{isAvailable:!1}}return{isAvailable:!0,startFlow:async()=>{try{ee.airwallexGooglePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,customParams:void 0,initResult:void 0})}catch(c){vt("Google Pay payment error",c),e.get.onCheckoutError((c==null?void 0:c.message)??"Unknown error")}}}}),Ya=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n})=>{var d,h,b,m,g,E,I;W("Starting Google Pay flow...");const s=Ye(r.checkoutPaymentMethods,Sn),o=En(r.baseUrl),a=r.anyCdeConnection,c=await ke(a),u=s.metadata;if(!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const l=hr({gateway:"airwallex",gatewayMerchantId:u.processor_account_id,merchantName:u.processor_account_name,merchantId:"",initialPreview:await Mt(a,c.token,c.mode==="setup",void 0)});try{const C=await o.loadPaymentData(l);W("Google Pay Payment data",C);const A=qa(t,C),T=We(A,n.get.onValidationError),me=(h=(d=C.paymentMethodData)==null?void 0:d.tokenizationData)==null?void 0:h.token;if(!me)throw new Error("No payment token received from Google Pay");const xe=await Nt(a,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:T[f.EMAIL],new_customer_first_name:T[f.FIRST_NAME],new_customer_last_name:T[f.LAST_NAME],new_customer_address:{postal_code:T[f.ZIP_CODE],country_code:T[f.COUNTRY]}}),Pe=Ba(xe);W("Start flow next actions",Pe);const Ne=await Ee(a,{secure_token:c.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Pe==null?void 0:Pe.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:me}}}});W("[1st] Confirm payment flow response",Ne);let bt=(m=(b=Ne.payment_methods)==null?void 0:b[0])==null?void 0:m.id;const Me=(g=Ne.required_user_actions)==null?void 0:g.find(ce=>ce.type==="airwallex_payment_consent");if(Me&&Me.redirect_url){W("3DS Required, starting verification...",Me);const{status:ce}=await Ft({url:Me.redirect_url,baseUrl:r.baseUrl});if(W(`╰ 3DS verification completed [Status: ${ce}]`),ce===Q.CANCELLED)throw new Error("3DS verification cancelled");if(ce===Q.FAILURE)throw new Error("3DS verification failed")}if(Me&&!bt){const ce=await Ee(a,{secure_token:c.token,their_pm_id:Me.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Me.consent_id}});W("[2nd] Confirm payment flow response",ce),bt=(I=(E=ce.payment_methods)==null?void 0:E[0])==null?void 0:I.id}if(!bt)throw new Error("No PM ID found");if(c.mode==="setup")return{mode:"setup",result:{payment_method_id:bt}};{W("Starting one-time payment flow...");const ce={secure_token:c.token,payment_input:{provider_type:e.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:bt,line_items:c.line_items,total_amount_atom:c.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e,customer_email:T[f.EMAIL],customer_zip_code:T[f.ZIP_CODE],customer_country:T[f.COUNTRY],promotion_code:T[f.PROMOTION_CODE],customer_first_name:T[f.FIRST_NAME],customer_last_name:T[f.LAST_NAME]};return{mode:"checkout",result:await jt(a,ce)}}}catch(C){throw vt("Google Pay payment error",C),new Error((C==null?void 0:C.message)??"Unknown error")}}),Wa=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Apple Pay SDK")),document.body.appendChild(t)}),Ha=(r,e)=>{var n;const t={...r};return e&&(t[f.EMAIL]=t[f.EMAIL]||e.emailAddress||"op_unfilled@getopenpay.com",t[f.COUNTRY]=t[f.COUNTRY]||e.countryCode||"US",t[f.ADDRESS]=t[f.ADDRESS]||((n=e.addressLines)==null?void 0:n[0])||"",t[f.CITY]=t[f.CITY]||e.locality||"",t[f.ZIP_CODE]=t[f.ZIP_CODE]||e.postalCode||"00000",t[f.STATE]=t[f.STATE]||e.administrativeArea||"",t[f.FIRST_NAME]=t[f.FIRST_NAME]||e.givenName||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||e.familyName||"_OP_UNKNOWN"),t},{log__:Zt}=L("applepay-session");async function Ka(r,e){try{const n=(await Nt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:e.nonCdeFormInputs[f.EMAIL],new_customer_first_name:e.nonCdeFormInputs[f.FIRST_NAME],new_customer_last_name:e.nonCdeFormInputs[f.LAST_NAME],processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).required_user_actions[0],s=n.payment_session,o=n.consent_id;if(!s)throw new Error("No session data received from payment flow");if(!o)throw new Error("No consent ID received from payment flow");return e.session.completeMerchantValidation(s),o}catch(t){throw e.session.abort(),t}}async function Ja(r,e){var s,o;if(!r.redirect_url)throw new Error("No redirect URL found");Zt("3DS Required, starting verification...",r);const{status:t}=await Ft({url:r.redirect_url,baseUrl:e.baseUrl});if(Zt(`╰ 3DS verification completed [Status: ${t}]`),t===Q.CANCELLED)throw new Error("3DS verification cancelled");if(t===Q.FAILURE)throw new Error("3DS verification failed");const n=await Ee(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:r.their_pm_id,airwallex_consent_id:r.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return Zt("[2nd] Confirm payment flow response",n),(o=(s=n.payment_methods)==null?void 0:s[0])==null?void 0:o.id}async function Xa(r,e,t){return{mode:"checkout",result:await jt(t.connection,{secure_token:t.prefill.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:r,line_items:t.prefill.line_items,total_amount_atom:t.prefill.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,customer_email:e[f.EMAIL],customer_zip_code:e[f.ZIP_CODE],customer_country:e[f.COUNTRY],promotion_code:e[f.PROMOTION_CODE]})}}async function Qa(r,e,t){var n,s,o;try{const a=r.payment,c=Ha(e.nonCdeFormInputs,a.billingContact),u=We(c,e.formCallbacks.get.onValidationError),l=await Ee(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:t,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(a.token)}}}});Zt("[1st] Confirm payment flow response",l);let d=(s=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:s.id;const h=(o=l.required_user_actions)==null?void 0:o.find(m=>m.type==="airwallex_payment_consent");if(h!=null&&h.redirect_url&&h.consent_id&&h.their_pm_id&&(d=await Ja(h,e)),!d)throw new Error("No PM ID found");const b={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(b),e.isSetupMode?{mode:"setup",result:{payment_method_id:d}}:await Xa(d,u,e)}catch(a){const c={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(c),a}}const{log__:G,err__:yr}=L("applepay"),Cn=i.object({provider:i.literal("apple_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string()})}),ec=$t(async({context:r,formCallbacks:e})=>{const t=Ye(r.checkoutPaymentMethods,Cn);if(!t)return{isAvailable:!1};G("Loading Apple Pay SDK...");try{await Wa(),G("Apple Pay SDK loaded successfully")}catch(d){return yr("Failed to load Apple Pay SDK",d),{isAvailable:!1}}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return G("Apple Pay is not available on this device/browser"),{isAvailable:!1};if(G("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return G("No active cards available for Apple Pay"),{isAvailable:!1};const s=r.anyCdeConnection,o=await ke(s),a=o.mode==="setup",c=await Mt(s,o.token,a,void 0),u=t.metadata;if(G("processorAccount",u),!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");return{isAvailable:!0,startFlow:async()=>{try{await ee.airwallexApplePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,customParams:{initialPreview:c,isSetupMode:a,prefill:o},initResult:void 0})}catch(d){yr("Apple Pay payment error",d),e.get.onCheckoutError((d==null?void 0:d.message)??"Unknown error")}}}}),tc=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:s})=>{var g;const o=Ye(r.checkoutPaymentMethods,Cn),{initialPreview:a,isSetupMode:c,prefill:u}=n,l={label:c?"Setup Payment":"Payment Total",amount:c?"0.00":(a.amountAtom/100).toFixed(2),type:"final"},d={countryCode:"US",currencyCode:((g=a.currency)==null?void 0:g.toUpperCase())??"USD",supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:l};G("Payment Request",d);const h=new ApplePaySession(3,d);G("ApplePaySession",h);const b={session:h,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:o.metadata,prefill:u,isSetupMode:c,baseUrl:r.baseUrl,formCallbacks:s};let m;return new Promise((E,I)=>{h.oncancel=()=>{G("Payment cancelled by user"),I(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async C=>{try{m=await Ka(C,b)}catch(A){I(A)}},h.onshippingmethodselected=C=>{G("Shipping method selected",C.shippingMethod)},h.onshippingmethodselected=C=>{G("Shipping method selected",C.shippingMethod);const A={};h.completeShippingMethodSelection(A)},h.onshippingcontactselected=C=>{G("Shipping contact selected",C.shippingContact);const A={};h.completeShippingContactSelection(A)},h.onpaymentmethodselected=C=>{G("Payment method selected",C.paymentMethod);const A={newTotal:{...l}};h.completePaymentMethodSelection(A)},h.onpaymentauthorized=async C=>{try{const A=await Qa(C,b,m);E(A)}catch(A){I(A)}},h.begin()}).catch(E=>{throw yr("Apple Pay payment error",E),E})}),_r=(r,e,t)=>{const n=r.filter(s=>{const o=t===void 0?!0:s.processor_name===t,a=s.provider===e;return o&&a});if(n.length===0)throw console.error("CPMs list",r),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(n.length!==1)throw console.error("CPMs list",r),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return n[0]},ee={commonCC:{init:async()=>{},run:Aa},stripePR:{init:ja,run:Da},stripeLink:{init:aa,run:ca},pockytPaypal:{run:Va},airwallexGooglePay:{init:Ga,run:Ya},airwallexApplePay:{init:ec,run:tc}};var gr=function(r,e){return gr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])},gr(r,e)};function Se(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");gr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function rc(r,e,t,n){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function c(d){try{l(n.next(d))}catch(h){a(h)}}function u(d){try{l(n.throw(d))}catch(h){a(h)}}function l(d){d.done?o(d.value):s(d.value).then(c,u)}l((n=n.apply(r,e||[])).next())})}function xn(r,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,s,o,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(l){return function(d){return u([l,d])}}function u(l){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(n=1,s&&(o=l[0]&2?s.return:l[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,l[1])).done)return o;switch(s=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,s=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){t.label=l[1];break}if(l[0]===6&&t.label<o[1]){t.label=o[1],o=l;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(l);break}o[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(d){l=[6,d],s=0}finally{n=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function He(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){a={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o}function zt(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))}function Ke(r){return this instanceof Ke?(this.v=r,this):new Ke(r)}function nc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(m){return function(g){return Promise.resolve(g).then(m,h)}}function c(m,g){n[m]&&(s[m]=function(E){return new Promise(function(I,C){o.push([m,E,I,C])>1||u(m,E)})},g&&(s[m]=g(s[m])))}function u(m,g){try{l(n[m](g))}catch(E){b(o[0][3],E)}}function l(m){m.value instanceof Ke?Promise.resolve(m.value.v).then(d,h):b(o[0][2],m)}function d(m){u("next",m)}function h(m){u("throw",m)}function b(m,g){m(g),o.shift(),o.length&&u(o[0][0],o[0][1])}}function sc(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof He=="function"?He(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(a){return new Promise(function(c,u){a=r[o](a),s(c,u,a.done,a.value)})}}function s(o,a,c,u){Promise.resolve(u).then(function(l){o({value:l,done:c})},a)}}typeof SuppressedError=="function"&&SuppressedError;function $(r){return typeof r=="function"}function Bt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var vr=Bt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
20
+ `;const t=document.createElement("div"),n=t.attachShadow({mode:"open"});n.appendChild(e.content.cloneNode(!0));const s=n.querySelector("#three-ds-iframe"),o=n.querySelector(".cancel-button");return document.body.appendChild(t),{host:t,iframe:s,cancelButton:o}};function ha(r,e,t){const n=async()=>{try{const o=await Bi(r,t);o&&(clearInterval(s),e(o))}catch{}};n();const s=setInterval(n,cn);return s}function ma({elements:r,pollingInterval:e,resolve:t}){const n=()=>{clearInterval(e),r.host.remove(),t({status:re.CANCELLED})};return r.cancelButton.addEventListener("click",n),()=>{r.cancelButton.removeEventListener("click",n)}}async function Ut(r){const{url:e,baseUrl:t}=r,n=fa(e);return new Promise(s=>{const o=u=>{setTimeout(()=>{n.host.remove()},1e3),s(u),c==null||c()},a=ha(n.iframe,o,new URL(t).origin),c=ma({elements:n,pollingInterval:a,resolve:s})})}const vn=async r=>{const e=await Ut(r);if(e.status===re.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===re.FAILURE)throw new Error("3DS verification failed");return e.status!==re.SUCCESS&&ar(e.status),{href:e.href}},ya=(r,e)=>{const t=window.open(e,"_blank");if(!t)throw new Error(`${r} popup window blocked. Please allow popups for this site.`);return t},_a=async(r,e,t,n)=>{const{err__:s}=$("popup-verify");return new Promise((o,a)=>{const c=ya(r,n),u=setInterval(async()=>{try{const l=await Ui(e,t);if(l.present)clearInterval(u),c.close(),o({href:l.href});else if(c.closed)throw new Error(`${r} payment cancelled`)}catch(l){s(he(l)),clearInterval(u),a(he(l))}},1e3)})},{log__:ga,err__:wn}=$("pockyt-cc"),va=i.object({"op-pockyt-3ds-url":i.string(),"op-pockyt-txn-no":i.string(),"op-pockyt-ref-no":i.string()}),wa=r=>{const e=va.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw wn(n),new Error(t)}return e.data},bn=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return ga(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw wn(t,`Resulting URL: ${r}.
21
+ Error: ${he(e)}`),new Error(t)}},ba=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,ka=async(r,e)=>{const t=wa(e),n=await vn({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:bn(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:Ea,err__:fr}=$("airwallex-cc"),Sa=i.object({"op-airwallex-3ds-url":i.string(),"op-airwallex-initial-intent-id":i.string(),"op-airwallex-consent-id":i.string()}),Ca=r=>{const e=Sa.safeParse(r);if(!e.success){const t="Unable to process your credit card. Please contact support for assistance.",n=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`;throw fr(n),new Error(t)}return e.data},xa=r=>(r==null?void 0:r["op-airwallex-3ds-url"])!==void 0,Pa=r=>{try{const e=new URL(r??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return Ea(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const t="Error verifying Airwallex 3DS verification result.";throw fr(t,`Resulting URL: ${r}.
22
+ Error: ${he(e)}`),new Error(t)}},Aa=async(r,e)=>{const t=Ca(e),n=await vn({url:t["op-airwallex-3ds-url"],baseUrl:r}),s=Pa(n.href??""),o=t["op-airwallex-initial-intent-id"];if(o!==s){const c="Unable to process your credit card. Please contact support for assistance.",u=`Intent ID from callback (${s}) does not match the initial intent ID (${o}).`;throw fr(u),new Error(c)}return{existing_cc:{initial_intent_id:s,consent_id:t["op-airwallex-consent-id"]}}},{log__:j,err__:kn}=$("common-cc"),{log__:En}=$("stripe-cc");i.array(i.object({our_existing_pm_id:i.string()})).length(1);const Ta=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var l;j("├ Running common CC flow...",{checkoutPaymentMethod:e});const o=r.anyCdeConnection,a=await Se(o);j(`├ Validating non-CDE form fields [Mode: ${a.mode}]`);const c=We(t,n.get.onValidationError),u={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{}};try{j(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await Vi(s.currentCdeConnections,{session_id:r.elementsSessionId});if(sa(d,n.get.onValidationError),a.mode==="setup"){j(`├ Setting up payment method in CDE [Token: ${a.token}]`);const m=await zi(o,u);return j(`╰ Setup completed successfully [PM ID: ${m.payment_method_id}]`),{mode:"setup",result:m}}else{j(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const m=await an(o,u);return j("╰ Checkout completed successfully."),{mode:"checkout",result:m}}}catch(d){if(d instanceof on&&d.originalErrorMessage.includes("3DS_REQUIRED")){j("├ Card requires 3DS, starting non-legacy payment flow"),j("Received 3DS error response headers:",d.response.headers);const m=ba(d.response.headers);if(m){j("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const T=await ka(r.baseUrl,d.response.headers);u.extra_metadata.pockyt=T}const w=xa(d.response.headers);if(w){j("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const T=await Aa(r.baseUrl,d.response.headers);u.extra_metadata.airwallex=T}const h=await Fi(o,u);j("├ Payment flow result:",h);const g=m||w,E=((l=d.response.headers)==null?void 0:l["op-should-use-new-flow"])!=="true";g?j("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):E?(j("├ Using stripe 3DS flow"),await Na(h)):(j("├ Using common 3DS flow"),await Ra(h,r.baseUrl));const P=h.cc_pm_id;if(a.mode==="setup"){j(`├ Confirming payment flow [cc_pm_id: ${P}]`);const T=await Ce(o,{secure_token:a.token,existing_cc_pm_id:P});j("├ Confirm payment flow result received Result:",T);const A=pr(T);return j(`╰ Setup completed successfully [PM ID: ${A.payment_method_id}]`),{mode:"setup",result:A}}else{j(`├ Checking out after 3DS flow [Flow: ${E?"legacy":"new"}]`);const T=await an(o,{...u,existing_cc_pm_id:P,do_not_use_legacy_cc_flow:E});return j("╰ Checkout completed successfully."),{mode:"checkout",result:T}}}throw kn("╰ Error checking out card info in CDE"),kn(d),d}}),Ia=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return Ao.parse(e)},Oa=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");if(!e)throw new Error("No common 3DS action found");return So.parse(e)},Ra=async(r,e)=>{const t=Oa(r);j(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Ut({url:t.redirect_url,baseUrl:e});if(j(`╰ 3DS verification completed [Status: ${n}]`),n===re.CANCELLED)throw new Error("3DS verification cancelled");if(n===re.FAILURE)throw new Error("3DS verification failed")},Na=async r=>{const e=Ia(r);En(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Do(e),En("╰ Stripe 3DS flow completed successfully")},{log__:G,err__:Ma}=$("stripe-pr"),ja=i.object({provider:i.union([i.literal("apple_pay"),i.literal("google_pay")]),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),Da=$t(async({context:r})=>{G("Checking if there are any CPMs for Stripe PR...");const e=Ye(r.checkoutPaymentMethods,ja);G("Initializing Stripe PR flow...");const t=r.anyCdeConnection,n=await Se(t),s=n.mode==="setup";G("Getting initial preview amount");const o=await Mt(t,n.token,s,void 0),a=await Ro(e.metadata.stripe_pk,o.amountAtom,o.currency,s);G("Checking if can make payment");const c=await a.canMakePayment();return c===null?(Ma("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(G("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:a,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),La=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s,initResult:o})=>{if(G("Running Stripe PR flow..."),s.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${s.provider}, got ${e.provider}`);const a=r.anyCdeConnection,c=o.pr;if(s!=null&&s.overridePaymentRequest){const g=s.overridePaymentRequest;G("Overriding PR amount with",g),$a(c,g.amount,g.pending,g.stripeApplePay)}G("Showing PR dialog..."),c.show();const u=await Mo(c);G("Stripe PM added event:",u),G("Merging PM fields with form fields...");const l=Fa(t,u),d=We(l,n.get.onValidationError);G("PR dialog finished. Starting payment flow...",d);const m=await $i(a,{fields:d,checkoutPaymentMethod:e}),w=Ua(m);G("Confirming PR with Stripe..."),await jo(w,u);const h=await Se(a);if(h.mode==="setup"){G("Confirming payment flow for setup...");const g=await Ce(a,{secure_token:h.token});return{mode:"setup",result:pr(g)}}else{G("Performing checkout...");const g={secure_token:h.token,payment_input:{provider_type:e.provider},customer_first_name:d[f.FIRST_NAME],customer_last_name:d[f.LAST_NAME],customer_email:d[f.EMAIL],customer_zip_code:d[f.ZIP_CODE],customer_country:d[f.COUNTRY],promotion_code:d[f.PROMOTION_CODE],line_items:h.line_items,total_amount_atom:h.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await jt(a,g)}}}),Fa=(r,e)=>{var u,l,d,m;const t={...r},[n,...s]=((l=(u=e.payerName)==null?void 0:u.trim())==null?void 0:l.split(/\s+/))??[],o=s.join(" ")||void 0,a=(m=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:m.address,c=e.shippingAddress;return t[f.FIRST_NAME]=t[f.FIRST_NAME]||n||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||o||"_OP_UNKNOWN",t[f.EMAIL]=t[f.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[f.ZIP_CODE]=t[f.ZIP_CODE]||(a==null?void 0:a.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[f.COUNTRY]=t[f.COUNTRY]||(a==null?void 0:a.country)||(c==null?void 0:c.country)||"US",G("Final form inputs:",t),t},$a=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Ua=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
23
+ Details: got ${r.required_user_actions.length} required user actions`);return To.parse(r.required_user_actions[0])},{log__:me,err__:Sn}=$("pockyt-paypal"),Za=i.object({processor_name:i.literal("pockyt"),provider:i.literal("paypal")}),Va=i.array(i.object({paypal_iframe_url:i.string(),verify_token:i.string()})).length(1),za=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{me("Running Pockyt Paypal flow...");const o=r.anyCdeConnection,a=await Se(o);me("Verifying CPM...");const c=Za.parse(e);me("├ Validating non-CDE form fields");const u=s==null?void 0:s.settings,l=We(t,n.get.onValidationError,u==null?void 0:u.defaultFieldValues),d=na(l);me(`Starting payment flow... Mode: ${a.mode}`);const m=a.mode!=="setup",w=await Nt(o,{payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:m,pay_first_flow_cart_info:m?{line_items:a.line_items,displayed_total_amount_atom:a.amount_total_atom}:void 0,...d});if(me("Start payment flow response",w),!w.checkout_attempt_id)throw Sn("Checkout attempt ID not found in response:",w),new Error("An error occurred during checkout, please try again with another payment method.");const h=Va.parse(w.required_user_actions)[0];me("Opening paypal iframe...");const g=await _a("PayPal",o,h.verify_token,h.paypal_iframe_url);me("Paypal flow result",g);const E=bn(g.href);me(`Confirming payment flow using vault ID ${E}`);const P=await Ce(o,{secure_token:a.token,their_pm_id:E,checkout_attempt_id:m?w.checkout_attempt_id:void 0});if(me("Confirm payment flow result",P),a.mode==="setup")return{mode:"setup",result:{payment_method_id:P.payment_methods[0].id}};if(!P.pay_first_success_response)throw Sn("Checkout failed, no pay-first success response:",P),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:P.pay_first_success_response}}),hr=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:s,overridePaymentRequest:o})=>{var l;const a=o!=null&&o.amount?Math.max(o.amount.amountAtom/100,0):Math.max((s==null?void 0:s.amountAtom)??0,0),c=(((l=o==null?void 0:o.amount)==null?void 0:l.currency)??(s==null?void 0:s.currency)??"USD").toUpperCase(),u={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:r,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:t},transactionInfo:{countryCode:"US",currencyCode:c,totalPriceStatus:o!=null&&o.pending?"ESTIMATED":"FINAL",totalPrice:a.toFixed(2)}};return o!=null&&o.googlePayPaymentRequest?{...u,...o.googlePayPaymentRequest}:u},Ba=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://pay.google.com/gp/p/js/pay.js",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Google Pay SDK")),document.body.appendChild(t)}),qa=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?zr.parse(e):null},Ga=(r,e)=>{var s,o,a,c;const t={...r},n=(o=(s=e.paymentMethodData)==null?void 0:s.info)==null?void 0:o.billingAddress;if(n){const[u,...l]=((c=(a=n.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],d=l.join(" ")||void 0;t[f.EMAIL]=t[f.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[f.COUNTRY]=t[f.COUNTRY]||n.countryCode||"US",t[f.ADDRESS]=t[f.ADDRESS]||n.address1||"",t[f.CITY]=t[f.CITY]||n.locality||"",t[f.ZIP_CODE]=t[f.ZIP_CODE]||n.postalCode||"00000",t[f.STATE]=t[f.STATE]||n.administrativeArea||"",t[f.FIRST_NAME]=t[f.FIRST_NAME]||u||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:J,err__:vt}=$("gpay");let mr=null;const Cn=r=>{const e=r===je?"PRODUCTION":"TEST";return mr===null&&(mr=new window.google.payments.api.PaymentsClient({environment:e,merchantInfo:hr({gateway:"airwallex",gatewayMerchantId:"",merchantName:""}).merchantInfo})),mr},xn=i.object({provider:i.literal("google_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string(),google_pay_merchant_id:i.string().nullish()})}),Ya=$t(async({context:r,formCallbacks:e})=>{var o,a;const t=Ye(r.checkoutPaymentMethods,xn);if(!t)return{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};J("Google Pay CPM",t);const n=t.metadata;if(!n.processor_account_id)return vt("No gateway merchant ID found in processor account"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(J("Loading Google Pay SDK..."),await Ba(),!((a=(o=window.google)==null?void 0:o.payments)!=null&&a.api))return vt("Google Pay SDK not loaded properly"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};J("Google Pay SDK loaded",window.google.payments);try{const{result:c}=await Cn(r.baseUrl).isReadyToPay(hr({gateway:"airwallex",gatewayMerchantId:n.processor_account_id,merchantName:n.processor_account_name,merchantId:n.google_pay_merchant_id??"",initialPreview:void 0}));if(!c)return J("Google Pay is not available for this user"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}catch(c){return vt("Error checking Google Pay availability",c),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}return{isAvailable:!0,isLoading:!1,startFlow:async c=>{try{ne.airwallexGooglePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,initResult:void 0,customParams:c??{}})}catch(u){vt("Google Pay payment error",u),e.get.onCheckoutError((u==null?void 0:u.message)??"Unknown error")}}}}),Wa=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var m,w,h,g,E,P,T;J("Starting Google Pay flow...");const o=Ye(r.checkoutPaymentMethods,xn),a=Cn(r.baseUrl),c=r.anyCdeConnection,u=await Se(c),l=o.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const d=hr({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:"",initialPreview:await Mt(c,u.token,u.mode==="setup",void 0),overridePaymentRequest:s==null?void 0:s.overridePaymentRequest});try{const A=await a.loadPaymentData(d);J("Google Pay Payment data",A);const I=Ga(t,A),D=We(I,n.get.onValidationError),L=(w=(m=A.paymentMethodData)==null?void 0:m.tokenizationData)==null?void 0:w.token;if(!L)throw new Error("No payment token received from Google Pay");const V=await Nt(c,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:D[f.EMAIL],new_customer_first_name:D[f.FIRST_NAME],new_customer_last_name:D[f.LAST_NAME],new_customer_address:{postal_code:D[f.ZIP_CODE],country_code:D[f.COUNTRY]}}),Ae=qa(V);J("Start flow next actions",Ae);const xr=await Ce(c,{secure_token:u.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Ae==null?void 0:Ae.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:L}}}});J("[1st] Confirm payment flow response",xr);let bt=(g=(h=xr.payment_methods)==null?void 0:h[0])==null?void 0:g.id;const Me=(E=xr.required_user_actions)==null?void 0:E.find(de=>de.type==="airwallex_payment_consent");if(Me&&Me.redirect_url){J("3DS Required, starting verification...",Me);const{status:de}=await Ut({url:Me.redirect_url,baseUrl:r.baseUrl});if(J(`╰ 3DS verification completed [Status: ${de}]`),de===re.CANCELLED)throw new Error("3DS verification cancelled");if(de===re.FAILURE)throw new Error("3DS verification failed")}if(Me&&!bt){const de=await Ce(c,{secure_token:u.token,their_pm_id:Me.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Me.consent_id}});J("[2nd] Confirm payment flow response",de),bt=(T=(P=de.payment_methods)==null?void 0:P[0])==null?void 0:T.id}if(!bt)throw new Error("No PM ID found");if(u.mode==="setup")return{mode:"setup",result:{payment_method_id:bt}};{J("Starting one-time payment flow...");const de={secure_token:u.token,payment_input:{provider_type:e.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:bt,line_items:u.line_items,total_amount_atom:u.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e,customer_email:D[f.EMAIL],customer_zip_code:D[f.ZIP_CODE],customer_country:D[f.COUNTRY],promotion_code:D[f.PROMOTION_CODE],customer_first_name:D[f.FIRST_NAME],customer_last_name:D[f.LAST_NAME]};return{mode:"checkout",result:await jt(c,de)}}}catch(A){throw vt("Google Pay payment error",A),new Error((A==null?void 0:A.message)??"Unknown error")}}),Ha=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Apple Pay SDK")),document.body.appendChild(t)}),Ka=(r,e)=>{var n;const t={...r};return e&&(t[f.EMAIL]=t[f.EMAIL]||e.emailAddress||"op_unfilled@getopenpay.com",t[f.COUNTRY]=t[f.COUNTRY]||e.countryCode||"US",t[f.ADDRESS]=t[f.ADDRESS]||((n=e.addressLines)==null?void 0:n[0])||"",t[f.CITY]=t[f.CITY]||e.locality||"",t[f.ZIP_CODE]=t[f.ZIP_CODE]||e.postalCode||"00000",t[f.STATE]=t[f.STATE]||e.administrativeArea||"",t[f.FIRST_NAME]=t[f.FIRST_NAME]||e.givenName||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||e.familyName||"_OP_UNKNOWN"),t},{log__:Zt}=$("applepay-session");async function Ja(r,e){try{const n=(await Nt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:e.nonCdeFormInputs[f.EMAIL],new_customer_first_name:e.nonCdeFormInputs[f.FIRST_NAME],new_customer_last_name:e.nonCdeFormInputs[f.LAST_NAME],processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).required_user_actions[0],s=n.payment_session,o=n.consent_id;if(!s)throw new Error("No session data received from payment flow");if(!o)throw new Error("No consent ID received from payment flow");return e.session.completeMerchantValidation(s),o}catch(t){throw e.session.abort(),t}}async function Xa(r,e){var s,o;if(!r.redirect_url)throw new Error("No redirect URL found");Zt("3DS Required, starting verification...",r);const{status:t}=await Ut({url:r.redirect_url,baseUrl:e.baseUrl});if(Zt(`╰ 3DS verification completed [Status: ${t}]`),t===re.CANCELLED)throw new Error("3DS verification cancelled");if(t===re.FAILURE)throw new Error("3DS verification failed");const n=await Ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:r.their_pm_id,airwallex_consent_id:r.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return Zt("[2nd] Confirm payment flow response",n),(o=(s=n.payment_methods)==null?void 0:s[0])==null?void 0:o.id}async function Qa(r,e,t){return{mode:"checkout",result:await jt(t.connection,{secure_token:t.prefill.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:r,line_items:t.prefill.line_items,total_amount_atom:t.prefill.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,customer_email:e[f.EMAIL],customer_zip_code:e[f.ZIP_CODE],customer_country:e[f.COUNTRY],promotion_code:e[f.PROMOTION_CODE]})}}async function ec(r,e,t){var n,s,o;try{const a=r.payment,c=Ka(e.nonCdeFormInputs,a.billingContact),u=We(c,e.formCallbacks.get.onValidationError),l=await Ce(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:t,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(a.token)}}}});Zt("[1st] Confirm payment flow response",l);let d=(s=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:s.id;const m=(o=l.required_user_actions)==null?void 0:o.find(h=>h.type==="airwallex_payment_consent");if(m!=null&&m.redirect_url&&m.consent_id&&m.their_pm_id&&(d=await Xa(m,e)),!d)throw new Error("No PM ID found");const w={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(w),e.isSetupMode?{mode:"setup",result:{payment_method_id:d}}:await Qa(d,u,e)}catch(a){const c={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(c),a}}const{log__:H,err__:yr}=$("applepay"),Pn=i.object({provider:i.literal("apple_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string()})}),tc=$t(async({context:r,formCallbacks:e})=>{const t=Ye(r.checkoutPaymentMethods,Pn);if(!t)return{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};H("Loading Apple Pay SDK...");try{await Ha(),H("Apple Pay SDK loaded successfully")}catch(d){return yr("Failed to load Apple Pay SDK",d),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}}}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return H("Apple Pay is not available on this device/browser"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};if(H("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return H("No active cards available for Apple Pay"),{isAvailable:!1,isLoading:!1,startFlow:async()=>{}};const s=r.anyCdeConnection,o=await Se(s),a=o.mode==="setup",c=await Mt(s,o.token,a,void 0),u=t.metadata;if(H("processorAccount",u),!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");return{isAvailable:!0,isLoading:!1,startFlow:async d=>{var m;try{await ne.airwallexApplePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,customParams:{isSetupMode:a,prefill:o,initialPreview:((m=d==null?void 0:d.overridePaymentRequest)==null?void 0:m.amount)??c,overridePaymentRequest:d==null?void 0:d.overridePaymentRequest},initResult:void 0})}catch(w){yr("Apple Pay payment error",w),e.get.onCheckoutError((w==null?void 0:w.message)??"Unknown error")}}}}),rc=Ge(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:s})=>{var T,A;const o=Ye(r.checkoutPaymentMethods,Pn),{initialPreview:a,isSetupMode:c,prefill:u,overridePaymentRequest:l}=n,d=(((T=l==null?void 0:l.amount)==null?void 0:T.currency)??a.currency??"USD").toUpperCase(),m=(A=l==null?void 0:l.amount)!=null&&A.amountAtom?(l.amount.amountAtom/100).toFixed(2):Math.max(a.amountAtom/100,0).toFixed(2),w={label:(l==null?void 0:l.label)??(c?"Setup Payment":"Payment Total"),type:l!=null&&l.pending?"pending":"final",amount:m},h={countryCode:"US",currencyCode:d,supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:w,...(l==null?void 0:l.applePayPaymentRequest)??{}};H("Payment Request",h);const g=new ApplePaySession(3,h);H("ApplePaySession",g);const E={session:g,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:o.metadata,prefill:u,isSetupMode:c,baseUrl:r.baseUrl,formCallbacks:s};let P;return new Promise((I,D)=>{g.oncancel=()=>{H("Payment cancelled by user"),D(new Error("Payment cancelled by user"))},g.onvalidatemerchant=async L=>{try{P=await Ja(L,E)}catch(V){D(V)}},g.onshippingmethodselected=L=>{H("Shipping method selected",L.shippingMethod)},g.onshippingmethodselected=L=>{H("Shipping method selected",L.shippingMethod);const V={};g.completeShippingMethodSelection(V)},g.onshippingcontactselected=L=>{H("Shipping contact selected",L.shippingContact);const V={};g.completeShippingContactSelection(V)},g.onpaymentmethodselected=L=>{H("Payment method selected",L.paymentMethod);const V={newTotal:{...w}};g.completePaymentMethodSelection(V)},g.onpaymentauthorized=async L=>{try{const V=await ec(L,E,P);I(V)}catch(V){D(V)}},g.begin()}).catch(I=>{throw yr("Apple Pay payment error",I),I})}),_r=(r,e,t)=>{const n=r.filter(s=>{const o=t===void 0?!0:s.processor_name===t,a=s.provider===e;return o&&a});if(n.length===0)throw console.error("CPMs list",r),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(n.length!==1)throw console.error("CPMs list",r),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return n[0]},ne={commonCC:{init:async()=>{},run:Ta},stripePR:{init:Da,run:La},stripeLink:{init:ca,run:la},pockytPaypal:{run:za},airwallexGooglePay:{init:Ya,run:Wa},airwallexApplePay:{init:tc,run:rc}};var gr=function(r,e){return gr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])},gr(r,e)};function xe(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");gr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function nc(r,e,t,n){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function c(d){try{l(n.next(d))}catch(m){a(m)}}function u(d){try{l(n.throw(d))}catch(m){a(m)}}function l(d){d.done?o(d.value):s(d.value).then(c,u)}l((n=n.apply(r,e||[])).next())})}function An(r,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,s,o,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(l){return function(d){return u([l,d])}}function u(l){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(n=1,s&&(o=l[0]&2?s.return:l[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,l[1])).done)return o;switch(s=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,s=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){t.label=l[1];break}if(l[0]===6&&t.label<o[1]){t.label=o[1],o=l;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(l);break}o[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(d){l=[6,d],s=0}finally{n=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function He(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){a={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o}function zt(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))}function Ke(r){return this instanceof Ke?(this.v=r,this):new Ke(r)}function sc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(h){return function(g){return Promise.resolve(g).then(h,m)}}function c(h,g){n[h]&&(s[h]=function(E){return new Promise(function(P,T){o.push([h,E,P,T])>1||u(h,E)})},g&&(s[h]=g(s[h])))}function u(h,g){try{l(n[h](g))}catch(E){w(o[0][3],E)}}function l(h){h.value instanceof Ke?Promise.resolve(h.value.v).then(d,m):w(o[0][2],h)}function d(h){u("next",h)}function m(h){u("throw",h)}function w(h,g){h(g),o.shift(),o.length&&u(o[0][0],o[0][1])}}function oc(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof He=="function"?He(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(a){return new Promise(function(c,u){a=r[o](a),s(c,u,a.done,a.value)})}}function s(o,a,c,u){Promise.resolve(u).then(function(l){o({value:l,done:c})},a)}}typeof SuppressedError=="function"&&SuppressedError;function Z(r){return typeof r=="function"}function Bt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var vr=Bt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
24
24
  `+t.map(function(n,s){return s+1+") "+n.toString()}).join(`
25
- `):"",this.name="UnsubscriptionError",this.errors=t}});function qt(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var wt=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,s,o;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=He(a),u=c.next();!u.done;u=c.next()){var l=u.value;l.remove(this)}}catch(E){e={error:E}}finally{try{u&&!u.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else a.remove(this);var d=this.initialTeardown;if($(d))try{d()}catch(E){o=E instanceof vr?E.errors:[E]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var b=He(h),m=b.next();!m.done;m=b.next()){var g=m.value;try{Tn(g)}catch(E){o=o??[],E instanceof vr?o=zt(zt([],Vt(o)),Vt(E.errors)):o.push(E)}}}catch(E){n={error:E}}finally{try{m&&!m.done&&(s=b.return)&&s.call(b)}finally{if(n)throw n.error}}}if(o)throw new vr(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Tn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&qt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&qt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Pn=wt.EMPTY;function An(r){return r instanceof wt||r&&"closed"in r&&$(r.remove)&&$(r.add)&&$(r.unsubscribe)}function Tn(r){$(r)?r():r.unsubscribe()}var In={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Rn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,zt([r,e],Vt(t)))},clearTimeout:function(r){var e=Rn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function On(r){Rn.setTimeout(function(){throw r})}function Nn(){}function Gt(r){r()}var wr=function(r){Se(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,An(t)&&t.add(n)):n.destination=cc,n}return e.create=function(t,n,s){return new kr(t,n,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(wt),oc=Function.prototype.bind;function br(r,e){return oc.call(r,e)}var ic=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){Yt(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Yt(n)}else Yt(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Yt(t)}},r}(),kr=function(r){Se(e,r);function e(t,n,s){var o=r.call(this)||this,a;if($(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&In.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&br(t.next,c),error:t.error&&br(t.error,c),complete:t.complete&&br(t.complete,c)}):a=t}return o.destination=new ic(a),o}return e}(wr);function Yt(r){On(r)}function ac(r){throw r}var cc={closed:!0,next:Nn,error:ac,complete:Nn},Er=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function lc(r){return r}function uc(r){return r.length===0?lc:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var fe=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var s=this,o=pc(e)?e:new kr(e,t,n);return Gt(function(){var a=s,c=a.operator,u=a.source;o.add(c?c.call(o,u):u?s._subscribe(o):s._trySubscribe(o))}),o},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=Mn(t),new t(function(s,o){var a=new kr({next:function(c){try{e(c)}catch(u){o(u),a.unsubscribe()}},error:o,complete:s});n.subscribe(a)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Er]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return uc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Mn(e),new e(function(n,s){var o;t.subscribe(function(a){return o=a},function(a){return s(a)},function(){return n(o)})})},r.create=function(e){return new r(e)},r}();function Mn(r){var e;return(e=r??In.Promise)!==null&&e!==void 0?e:Promise}function dc(r){return r&&$(r.next)&&$(r.error)&&$(r.complete)}function pc(r){return r&&r instanceof wr||dc(r)&&An(r)}function fc(r){return $(r==null?void 0:r.lift)}function hc(r){return function(e){if(fc(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function mc(r,e,t,n,s){return new yc(r,e,t,n,s)}var yc=function(r){Se(e,r);function e(t,n,s,o,a,c){var u=r.call(this,t)||this;return u.onFinalize=a,u.shouldUnsubscribe=c,u._next=n?function(l){try{n(l)}catch(d){t.error(d)}}:r.prototype._next,u._error=o?function(l){try{o(l)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,u._complete=s?function(){try{s()}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._complete,u}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(wr),_c=Bt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),jn=function(r){Se(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new Dn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new _c},e.prototype.next=function(t){var n=this;Gt(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=He(n.currentObservers),c=a.next();!c.done;c=a.next()){var u=c.value;u.next(t)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var n=this;Gt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var s=n.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Gt(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,s=this,o=s.hasError,a=s.isStopped,c=s.observers;return o||a?Pn:(this.currentObservers=null,c.push(t),new wt(function(){n.currentObservers=null,qt(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,s=n.hasError,o=n.thrownError,a=n.isStopped;s?t.error(o):a&&t.complete()},e.prototype.asObservable=function(){var t=new fe;return t.source=this,t},e.create=function(t,n){return new Dn(t,n)},e}(fe),Dn=function(r){Se(e,r);function e(t,n){var s=r.call(this)||this;return s.destination=t,s.source=n,s}return e.prototype.next=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,t)},e.prototype.error=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&s!==void 0?s:Pn},e}(jn),gc={now:function(){return Date.now()},delegate:void 0},vc=function(r){Se(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(wt),Ln={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,zt([r,e],Vt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},wc=function(r){Se(e,r);function e(t,n){var s=r.call(this,t,n)||this;return s.scheduler=t,s.work=n,s.pending=!1,s}return e.prototype.schedule=function(t,n){var s;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var o=this.id,a=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(a,o,n)),this.pending=!0,this.delay=n,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(a,this.id,n),this},e.prototype.requestAsyncId=function(t,n,s){return s===void 0&&(s=0),Ln.setInterval(t.flush.bind(t,this),s)},e.prototype.recycleAsyncId=function(t,n,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return n;n!=null&&Ln.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(t,n);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var s=!1,o;try{this.work(t)}catch(a){s=!0,o=a||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,s=t.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,qt(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(vc),Un=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=gc.now,r}(),bc=function(r){Se(e,r);function e(t,n){n===void 0&&(n=Un.now);var s=r.call(this,t,n)||this;return s.actions=[],s._active=!1,s}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var s;this._active=!0;do if(s=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,s){for(;t=n.shift();)t.unsubscribe();throw s}},e}(Un),kc=new bc(wc),Ec=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Sc(r){return $(r==null?void 0:r.then)}function Cc(r){return $(r[Er])}function xc(r){return Symbol.asyncIterator&&$(r==null?void 0:r[Symbol.asyncIterator])}function Pc(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ac(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Tc=Ac();function Ic(r){return $(r==null?void 0:r[Tc])}function Rc(r){return nc(this,arguments,function(){var t,n,s,o;return xn(this,function(a){switch(a.label){case 0:t=r.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Ke(t.read())];case 3:return n=a.sent(),s=n.value,o=n.done,o?[4,Ke(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Ke(s)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Oc(r){return $(r==null?void 0:r.getReader)}function Nc(r){if(r instanceof fe)return r;if(r!=null){if(Cc(r))return Mc(r);if(Ec(r))return jc(r);if(Sc(r))return Dc(r);if(xc(r))return $n(r);if(Ic(r))return Lc(r);if(Oc(r))return Uc(r)}throw Pc(r)}function Mc(r){return new fe(function(e){var t=r[Er]();if($(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function jc(r){return new fe(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Dc(r){return new fe(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,On)})}function Lc(r){return new fe(function(e){var t,n;try{for(var s=He(r),o=s.next();!o.done;o=s.next()){var a=o.value;if(e.next(a),e.closed)return}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}e.complete()})}function $n(r){return new fe(function(e){$c(r,e).catch(function(t){return e.error(t)})})}function Uc(r){return $n(Rc(r))}function $c(r,e){var t,n,s,o;return rc(this,void 0,void 0,function(){var a,c;return xn(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),t=sc(r),u.label=1;case 1:return[4,t.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=u.sent(),s={error:c},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Fc(r,e,t,n,s){n===void 0&&(n=0),s===void 0&&(s=!1);var o=e.schedule(function(){t(),s?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(o),!s)return o}function Zc(r,e){var t=$(r)?r:function(){return r},n=function(s){return s.error(t())};return new fe(n)}var Vc=Bt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function zc(r,e){return new Promise(function(t,n){var s=!1,o;r.subscribe({next:function(a){o=a,s=!0},error:n,complete:function(){s?t(o):n(new Vc)}})})}function Bc(r){return r instanceof Date&&!isNaN(r)}var qc=Bt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Gc(r,e){var t=Bc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?Yc:o,c=t.scheduler,u=c===void 0?kc:c,l=t.meta,d=l===void 0?null:l;if(n==null&&s==null)throw new TypeError("No timeout provided.");return hc(function(h,b){var m,g,E=null,I=0,C=function(A){g=Fc(b,u,function(){try{m.unsubscribe(),Nc(a({meta:d,lastValue:E,seen:I})).subscribe(b)}catch(T){b.error(T)}},A)};m=h.subscribe(mc(b,function(A){g==null||g.unsubscribe(),I++,b.next(E=A),s>0&&C(s)},void 0,void 0,function(){g!=null&&g.closed||g==null||g.unsubscribe(),E=null})),!I&&C(n!=null?typeof n=="number"?n:+n-u.now():s)})}function Yc(r){throw new qc(r)}class Wt{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&ar(this._current);const t={first:e.timeoutSec*1e3,with:()=>Zc(()=>new Error(e.timeoutErrMsg))};return zc(this._subject.pipe(Gc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new jn}get current(){return this._current}}const{log__:Wc,err__:Hc}=L("init-flows"),Ht=(r,e)=>{const t=new Wt;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const s=await e(n);Wc(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){Hc(`𝙭 ${r} flow initialization failed. Error:`,de(s),"Details:",s),t.throw(s,de(s))}}}},Kc=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Jc=()=>({stripePR:Ht("Stripe PR",ee.stripePR.init),stripeLink:Ht("Stripe Link",ee.stripeLink.init),airwallexGooglePay:Ht("Airwallex GPay",ee.airwallexGooglePay.init),airwallexApplePay:Ht("Airwallex ApplePay",ee.airwallexApplePay.init)}),{err__:Xc}=L("form-callbacks"),te=i.function().optional(),Fn=i.object({onFocus:te,onBlur:te,onChange:te,onLoad:te,onLoadError:te,onValidationError:te,onCheckoutStarted:te,onCheckoutSuccess:te,onSetupPaymentMethodSuccess:te,onCheckoutError:te,onPaymentRequestLoad:te}),ae=class ae{constructor(){this.setCallbacks=e=>{this._callbacks=ae.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const s=Hs(t,n??ae.NOOP,Xc);this._callbacks[t]=s})},this._callbacks=ae.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ae.NOOP=()=>{},ae.createEmptyCallbacks=()=>{const e={};return Object.keys(Fn.keyof().enum).forEach(t=>{e[t]=ae.NOOP}),e},ae.fromObject=e=>{const t=new ae;return t.setCallbacks(Fn.parse(e)),t};let Sr=ae;class Qc{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if(Zn(o.origin)!==Zn(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;const a=Zo(JSON.parse(o.data));if(!this.validateEvent(a))return;const{elementId:u,payload:l}=a,d=l.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(l.height?`${l.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(u,l.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(u,l.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(u,l.elementType,l.errors);break;case"LOADED":this.eventTargets[u]=o.source,this.internalCallbacks.onCdeLoaded(l);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(l.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(l.elementType,l.errors,u);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=o=>o.formId!==this.formId||!o.elementId?(console.log("[OJS] formId",this.formId,o.formId),console.warn("[form] Ignoring unknown event:",o),!1):this.nonces.has(o.nonce)?(console.warn("[form] Ignoring duplicate event:",o),!1):(this.nonces.add(o.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=s}}const Zn=r=>new URL(r).origin;async function el(r,e){const n=await Hr({iframe:r,debug:!1,childOrigin:e}).promise,s=await li(n);if(!ui(n,s))throw new Error("Got invalid CDE connection object");return n}class tl{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const rl=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(s=>{if(s.isSuccess){const o=s.loadedValue,a=o.isAvailable&&o.availableProviders.applePay,c=o.isAvailable&&o.availableProviders.googlePay,u={apple_pay:{isLoading:!1,isAvailable:a,startFlow:async l=>{a&&Vn("apple_pay",o,e,t,l)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async l=>{c&&Vn("google_pay",o,e,t,l)}}};t.get.onPaymentRequestLoad(u)}})},Vn=(r,e,t,n,s)=>ee.stripePR.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,r),nonCdeFormInputs:ze(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),zn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ce,err__:Kt}=L("op-form"),he=class he{constructor(e){this.cdeLoadEvent=new Wt,this.anyCdeConn=new Wt,this.context=new Wt,this.initFlows=Jc(),this.startFormInit=async()=>{try{Ce("Initializing OpenPay form:"),Ce("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:zn});Ce("├ CDE load event received"),Ce("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:zn});Ce("├ CDE connection received"),Ce("├ Creating OJS context, setting up handlers...");const s=he.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(s),rl(this.initFlows,s,this.formCallbacks),Ce("├ Starting OJS init flows..."),await Kc(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Ce("╰ Done initializing OJS flows.")}catch(t){const n=de(t);Kt("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const s=Ks.parse(t),o=document.createElement("iframe"),a=this.buildQueryString(n);o.name=`${s}-element`;const c=new URL(`/app/v1/${o.name}/`,this.config.baseUrl);return c.search=a.toString(),o.src=c.href,o.style.border="none",o.style.width="100%",this.registerIframe(s,o)},this.registerIframe=(t,n)=>{const s={type:t,node:n,mount:o=>{var a;return(a=document.querySelector(o))==null?void 0:a.appendChild(n)}};return this.connectToElement({type:s.type,node:s.node}),this.registeredElements||(this.registeredElements={[Ve.CARD]:void 0,[Ve.CARD_NUMBER]:void 0,[Ve.CARD_EXPIRY]:void 0,[Ve.CARD_CVC]:void 0}),this.registeredElements[t]=s,s},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",jo(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{el(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Kt("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Kt("Please wait for the form to finish loading before submitting.");return}ee.commonCC.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ze(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.generalSubmit=t=>{const n=this.context.getValueIfLoadedElse(null);if(!n){Kt("Please wait for the form to finish loading before submitting.");return}switch(t){case"pockyt-paypal":return ee.pockytPaypal.run({context:n,checkoutPaymentMethod:_r(n.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ze(n.formDiv),formCallbacks:this.formCallbacks,customParams:void 0,initResult:void 0});case"airwallex-google-pay":return this.initFlows.airwallexGooglePay.publisher.subscribe(s=>{s.isSuccess&&s.loadedValue.isAvailable&&s.loadedValue.startFlow()});case"airwallex-apple-pay":return this.initFlows.airwallexApplePay.publisher.subscribe(s=>{s.isSuccess&&s.loadedValue.isAvailable&&s.loadedValue.startFlow()});default:ar(t)}},this.submit=this.submitCard,this.destroy=()=>{for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},he.assignAsSingleton(this),this.ojsVersion="0.2.3",this.ojsReleaseVersion="0.2.3",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Sr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Fo()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new tl,this.eventHandler=new Qc(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}};he.ojsFlows=ee,he.assignAsSingleton=e=>{if(he.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},he.getInstance=()=>window.ojs??null,he.buildOjsFlowContext=(e,t,n,s)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??je).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Cr=he;Ae.FieldName=f,Ae.OpenPayForm=Cr,Object.defineProperty(Ae,Symbol.toStringTag,{value:"Module"})});
25
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function qt(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var wt=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,s,o;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=He(a),u=c.next();!u.done;u=c.next()){var l=u.value;l.remove(this)}}catch(E){e={error:E}}finally{try{u&&!u.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else a.remove(this);var d=this.initialTeardown;if(Z(d))try{d()}catch(E){o=E instanceof vr?E.errors:[E]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var w=He(m),h=w.next();!h.done;h=w.next()){var g=h.value;try{On(g)}catch(E){o=o??[],E instanceof vr?o=zt(zt([],Vt(o)),Vt(E.errors)):o.push(E)}}}catch(E){n={error:E}}finally{try{h&&!h.done&&(s=w.return)&&s.call(w)}finally{if(n)throw n.error}}}if(o)throw new vr(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)On(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&qt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&qt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Tn=wt.EMPTY;function In(r){return r instanceof wt||r&&"closed"in r&&Z(r.remove)&&Z(r.add)&&Z(r.unsubscribe)}function On(r){Z(r)?r():r.unsubscribe()}var Rn={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Nn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,zt([r,e],Vt(t)))},clearTimeout:function(r){var e=Nn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function Mn(r){Nn.setTimeout(function(){throw r})}function jn(){}function Gt(r){r()}var wr=function(r){xe(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,In(t)&&t.add(n)):n.destination=lc,n}return e.create=function(t,n,s){return new kr(t,n,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(wt),ic=Function.prototype.bind;function br(r,e){return ic.call(r,e)}var ac=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){Yt(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Yt(n)}else Yt(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Yt(t)}},r}(),kr=function(r){xe(e,r);function e(t,n,s){var o=r.call(this)||this,a;if(Z(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&Rn.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&br(t.next,c),error:t.error&&br(t.error,c),complete:t.complete&&br(t.complete,c)}):a=t}return o.destination=new ac(a),o}return e}(wr);function Yt(r){Mn(r)}function cc(r){throw r}var lc={closed:!0,next:jn,error:cc,complete:jn},Er=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function uc(r){return r}function dc(r){return r.length===0?uc:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var ye=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var s=this,o=fc(e)?e:new kr(e,t,n);return Gt(function(){var a=s,c=a.operator,u=a.source;o.add(c?c.call(o,u):u?s._subscribe(o):s._trySubscribe(o))}),o},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=Dn(t),new t(function(s,o){var a=new kr({next:function(c){try{e(c)}catch(u){o(u),a.unsubscribe()}},error:o,complete:s});n.subscribe(a)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Er]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Dn(e),new e(function(n,s){var o;t.subscribe(function(a){return o=a},function(a){return s(a)},function(){return n(o)})})},r.create=function(e){return new r(e)},r}();function Dn(r){var e;return(e=r??Rn.Promise)!==null&&e!==void 0?e:Promise}function pc(r){return r&&Z(r.next)&&Z(r.error)&&Z(r.complete)}function fc(r){return r&&r instanceof wr||pc(r)&&In(r)}function hc(r){return Z(r==null?void 0:r.lift)}function mc(r){return function(e){if(hc(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function yc(r,e,t,n,s){return new _c(r,e,t,n,s)}var _c=function(r){xe(e,r);function e(t,n,s,o,a,c){var u=r.call(this,t)||this;return u.onFinalize=a,u.shouldUnsubscribe=c,u._next=n?function(l){try{n(l)}catch(d){t.error(d)}}:r.prototype._next,u._error=o?function(l){try{o(l)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,u._complete=s?function(){try{s()}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._complete,u}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(wr),gc=Bt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ln=function(r){xe(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new Fn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new gc},e.prototype.next=function(t){var n=this;Gt(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=He(n.currentObservers),c=a.next();!c.done;c=a.next()){var u=c.value;u.next(t)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var n=this;Gt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var s=n.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Gt(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,s=this,o=s.hasError,a=s.isStopped,c=s.observers;return o||a?Tn:(this.currentObservers=null,c.push(t),new wt(function(){n.currentObservers=null,qt(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,s=n.hasError,o=n.thrownError,a=n.isStopped;s?t.error(o):a&&t.complete()},e.prototype.asObservable=function(){var t=new ye;return t.source=this,t},e.create=function(t,n){return new Fn(t,n)},e}(ye),Fn=function(r){xe(e,r);function e(t,n){var s=r.call(this)||this;return s.destination=t,s.source=n,s}return e.prototype.next=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,t)},e.prototype.error=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&s!==void 0?s:Tn},e}(Ln),vc={now:function(){return Date.now()},delegate:void 0},wc=function(r){xe(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(wt),$n={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,zt([r,e],Vt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},bc=function(r){xe(e,r);function e(t,n){var s=r.call(this,t,n)||this;return s.scheduler=t,s.work=n,s.pending=!1,s}return e.prototype.schedule=function(t,n){var s;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var o=this.id,a=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(a,o,n)),this.pending=!0,this.delay=n,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(a,this.id,n),this},e.prototype.requestAsyncId=function(t,n,s){return s===void 0&&(s=0),$n.setInterval(t.flush.bind(t,this),s)},e.prototype.recycleAsyncId=function(t,n,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return n;n!=null&&$n.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(t,n);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var s=!1,o;try{this.work(t)}catch(a){s=!0,o=a||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,s=t.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,qt(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(wc),Un=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=vc.now,r}(),kc=function(r){xe(e,r);function e(t,n){n===void 0&&(n=Un.now);var s=r.call(this,t,n)||this;return s.actions=[],s._active=!1,s}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var s;this._active=!0;do if(s=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,s){for(;t=n.shift();)t.unsubscribe();throw s}},e}(Un),Ec=new kc(bc),Sc=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Cc(r){return Z(r==null?void 0:r.then)}function xc(r){return Z(r[Er])}function Pc(r){return Symbol.asyncIterator&&Z(r==null?void 0:r[Symbol.asyncIterator])}function Ac(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Tc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ic=Tc();function Oc(r){return Z(r==null?void 0:r[Ic])}function Rc(r){return sc(this,arguments,function(){var t,n,s,o;return An(this,function(a){switch(a.label){case 0:t=r.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Ke(t.read())];case 3:return n=a.sent(),s=n.value,o=n.done,o?[4,Ke(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Ke(s)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Nc(r){return Z(r==null?void 0:r.getReader)}function Mc(r){if(r instanceof ye)return r;if(r!=null){if(xc(r))return jc(r);if(Sc(r))return Dc(r);if(Cc(r))return Lc(r);if(Pc(r))return Zn(r);if(Oc(r))return Fc(r);if(Nc(r))return $c(r)}throw Ac(r)}function jc(r){return new ye(function(e){var t=r[Er]();if(Z(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Dc(r){return new ye(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Lc(r){return new ye(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Mn)})}function Fc(r){return new ye(function(e){var t,n;try{for(var s=He(r),o=s.next();!o.done;o=s.next()){var a=o.value;if(e.next(a),e.closed)return}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}e.complete()})}function Zn(r){return new ye(function(e){Uc(r,e).catch(function(t){return e.error(t)})})}function $c(r){return Zn(Rc(r))}function Uc(r,e){var t,n,s,o;return nc(this,void 0,void 0,function(){var a,c;return An(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),t=oc(r),u.label=1;case 1:return[4,t.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=u.sent(),s={error:c},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Zc(r,e,t,n,s){n===void 0&&(n=0),s===void 0&&(s=!1);var o=e.schedule(function(){t(),s?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(o),!s)return o}function Vc(r,e){var t=Z(r)?r:function(){return r},n=function(s){return s.error(t())};return new ye(n)}var zc=Bt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function Bc(r,e){return new Promise(function(t,n){var s=!1,o;r.subscribe({next:function(a){o=a,s=!0},error:n,complete:function(){s?t(o):n(new zc)}})})}function qc(r){return r instanceof Date&&!isNaN(r)}var Gc=Bt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Yc(r,e){var t=qc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?Wc:o,c=t.scheduler,u=c===void 0?Ec:c,l=t.meta,d=l===void 0?null:l;if(n==null&&s==null)throw new TypeError("No timeout provided.");return mc(function(m,w){var h,g,E=null,P=0,T=function(A){g=Zc(w,u,function(){try{h.unsubscribe(),Mc(a({meta:d,lastValue:E,seen:P})).subscribe(w)}catch(I){w.error(I)}},A)};h=m.subscribe(yc(w,function(A){g==null||g.unsubscribe(),P++,w.next(E=A),s>0&&T(s)},void 0,void 0,function(){g!=null&&g.closed||g==null||g.unsubscribe(),E=null})),!P&&T(n!=null?typeof n=="number"?n:+n-u.now():s)})}function Wc(r){throw new Gc(r)}class Wt{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&ar(this._current);const t={first:e.timeoutSec*1e3,with:()=>Vc(()=>new Error(e.timeoutErrMsg))};return Bc(this._subject.pipe(Yc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new Ln}get current(){return this._current}}const{log__:Hc,err__:Kc}=$("init-flows"),Ht=(r,e)=>{const t=new Wt;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const s=await e(n);Hc(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){Kc(`𝙭 ${r} flow initialization failed. Error:`,he(s),"Details:",s),t.throw(s,he(s))}}}},Jc=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Xc=()=>({stripePR:Ht("Stripe PR",ne.stripePR.init),stripeLink:Ht("Stripe Link",ne.stripeLink.init),airwallexGooglePay:Ht("Airwallex GPay",ne.airwallexGooglePay.init),airwallexApplePay:Ht("Airwallex ApplePay",ne.airwallexApplePay.init)}),{err__:Qc}=$("form-callbacks"),se=i.function().optional(),Vn=i.object({onFocus:se,onBlur:se,onChange:se,onLoad:se,onLoadError:se,onValidationError:se,onCheckoutStarted:se,onCheckoutSuccess:se,onSetupPaymentMethodSuccess:se,onCheckoutError:se,onPaymentRequestLoad:se}),ue=class ue{constructor(){this.setCallbacks=e=>{this._callbacks=ue.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const s=Js(t,n??ue.NOOP,Qc);this._callbacks[t]=s})},this._callbacks=ue.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ue.NOOP=()=>{},ue.createEmptyCallbacks=()=>{const e={};return Object.keys(Vn.keyof().enum).forEach(t=>{e[t]=ue.NOOP}),e},ue.fromObject=e=>{const t=new ue;return t.setCallbacks(Vn.parse(e)),t};let Sr=ue;class el{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if(zn(o.origin)!==zn(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;const a=zo(JSON.parse(o.data));if(!this.validateEvent(a))return;const{elementId:u,payload:l}=a,d=l.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(l.height?`${l.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(u,l.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(u,l.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(u,l.elementType,l.errors);break;case"LOADED":this.eventTargets[u]=o.source,this.internalCallbacks.onCdeLoaded(l);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(l.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(l.elementType,l.errors,u);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=o=>o.formId!==this.formId||!o.elementId?(console.log("[OJS] formId",this.formId,o.formId),console.warn("[form] Ignoring unknown event:",o),!1):this.nonces.has(o.nonce)?(console.warn("[form] Ignoring duplicate event:",o),!1):(this.nonces.add(o.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=s}}const zn=r=>new URL(r).origin;async function tl(r,e){const n=await Kr({iframe:r,debug:!1,childOrigin:e}).promise,s=await di(n);if(!pi(n,s))throw new Error("Got invalid CDE connection object");return n}class rl{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const nl=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(s=>{if(s.isSuccess){const o=s.loadedValue,a=o.isAvailable&&o.availableProviders.applePay,c=o.isAvailable&&o.availableProviders.googlePay,u={apple_pay:{isLoading:!1,isAvailable:a,startFlow:async l=>{a&&Bn("apple_pay",o,e,t,l)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async l=>{c&&Bn("google_pay",o,e,t,l)}}};t.get.onPaymentRequestLoad(u)}})},Bn=(r,e,t,n,s)=>ne.stripePR.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,r),nonCdeFormInputs:ze(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),qn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Pe,err__:Kt}=$("op-form"),_e=class _e{constructor(e){this.cdeLoadEvent=new Wt,this.anyCdeConn=new Wt,this.context=new Wt,this.initFlows=Xc(),this.startFormInit=async()=>{try{Pe("Initializing OpenPay form:"),Pe("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:qn});Pe("├ CDE load event received"),Pe("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:qn});Pe("├ CDE connection received"),Pe("├ Creating OJS context, setting up handlers...");const s=_e.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(s),nl(this.initFlows,s,this.formCallbacks),Pe("├ Starting OJS init flows..."),await Jc(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Pe("╰ Done initializing OJS flows.")}catch(t){const n=he(t);Kt("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const s=Xs.parse(t),o=document.createElement("iframe"),a=this.buildQueryString(n);o.name=`${s}-element`;const c=new URL(`/app/v1/${o.name}/`,this.config.baseUrl);return c.search=a.toString(),o.src=c.href,o.style.border="none",o.style.width="100%",this.registerIframe(s,o)},this.registerIframe=(t,n)=>{const s={type:t,node:n,mount:o=>{var a;return(a=document.querySelector(o))==null?void 0:a.appendChild(n)}};return this.connectToElement({type:s.type,node:s.node}),this.registeredElements||(this.registeredElements={[Ve.CARD]:void 0,[Ve.CARD_NUMBER]:void 0,[Ve.CARD_EXPIRY]:void 0,[Ve.CARD_CVC]:void 0}),this.registeredElements[t]=s,s},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",Lo(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{tl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Kt("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Kt("Please wait for the form to finish loading before submitting.");return}ne.commonCC.run({context:t,checkoutPaymentMethod:_r(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ze(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.generalSubmit=(t,n)=>{const s=this.context.getValueIfLoadedElse(null);if(!s){Kt("Please wait for the form to finish loading before submitting.");return}switch(t){case"pockyt-paypal":return ne.pockytPaypal.run({context:s,checkoutPaymentMethod:_r(s.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ze(s.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case"airwallex-google-pay":return this.initFlows.airwallexGooglePay.publisher.subscribe(o=>{o.isSuccess&&o.loadedValue.isAvailable&&o.loadedValue.startFlow()});case"airwallex-apple-pay":return this.initFlows.airwallexApplePay.publisher.subscribe(o=>{o.isSuccess&&o.loadedValue.isAvailable&&o.loadedValue.startFlow()});default:ar(t)}},this.submit=this.submitCard,this.destroy=()=>{for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},_e.assignAsSingleton(this),this.ojsVersion="0.2.4",this.ojsReleaseVersion="0.2.4",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Sr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Vo()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new rl,this.eventHandler=new el(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}};_e.ojsFlows=ne,_e.assignAsSingleton=e=>{if(_e.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},_e.getInstance=()=>window.ojs??null,_e.buildOjsFlowContext=(e,t,n,s)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??je).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Cr=_e;Te.FieldName=f,Te.OpenPayForm=Cr,Object.defineProperty(Te,Symbol.toStringTag,{value:"Module"})});