@getopenpay/openpay-js 0.1.21 → 0.2.0-alpha.ff4f99c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +50 -1
- package/dist/index.es.js +1417 -899
- package/dist/index.umd.js +12 -12
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
(function(_e,$e){typeof exports=="object"&&typeof module<"u"?$e(exports):typeof define=="function"&&define.amd?define(["exports"],$e):(_e=typeof globalThis<"u"?globalThis:_e||self,$e(_e.OpenPay={}))})(this,function(_e){"use strict";const $e="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 Lt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Lt||(Lt={}));const p=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ce=r=>{switch(typeof r){case"undefined":return p.undefined;case"string":return p.string;case"number":return isNaN(r)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(r)?p.array:r===null?p.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?p.promise:typeof Map<"u"&&r instanceof Map?p.map:typeof Set<"u"&&r instanceof Set?p.set:typeof Date<"u"&&r instanceof Date?p.date:p.object;default:return p.unknown}},f=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"]),Pn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class V 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,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(a))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return s(this),n}static assert(e){if(!(e instanceof V))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()}}V.create=r=>new V(r);const Ce=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===p.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.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 f.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 f.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 f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}};let cr=Ce;function On(r){cr=r}function ut(){return cr}const lt=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 l=n.filter(u=>!!u).slice().reverse();for(const u of l)c=u(a,{data:e,defaultError:c}).message;return{...s,path:o,message:c}},Rn=[];function h(r,e){const t=ut(),n=lt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ce?void 0:Ce].filter(s=>!!s)});r.common.issues.push(n)}class D{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 b;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 D.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 b;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 b=Object.freeze({status:"aborted"}),xe=r=>({status:"dirty",value:r}),Z=r=>({status:"valid",value:r}),Dt=r=>r.status==="aborted",$t=r=>r.status==="dirty",Ze=r=>r.status==="valid",Ue=r=>typeof Promise<"u"&&r instanceof Promise;function dt(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 ur(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 _;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(_||(_={}));var Fe,Ve;class J{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 lr=(r,e)=>{if(Ze(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 V(r.common.issues);return this._error=t,this._error}}};function k(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 l,u;const{message:d}=r;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??t)!==null&&u!==void 0?u:c.defaultError}},description:s}}class S{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 ce(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new D,ctx:{common:e.parent.common,data:e.data,parsedType:ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ue(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:ce(e)},o=this._parseSync({data:e,path:s.path,parent:s});return lr(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:ce(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Ue(s)?s:Promise.resolve(s));return lr(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:f.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!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 H({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Q.create(this,this._def)}nullable(){return fe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Y.create(this,this._def)}promise(){return Re.create(this,this._def)}or(e){return We.create([this,e],this._def)}and(e){return Ye.create(this,e,this._def)}transform(e){return new H({...k(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Xe({...k(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new Ft({typeName:v.ZodBranded,type:this,...k(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Qe({...k(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return et.create(this,e)}readonly(){return tt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const In=/^c[^\s-]{8,}$/i,An=/^[0-9a-z]+$/,jn=/^[0-9A-HJKMNP-TV-Z]{26}$/,Nn=/^[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,Mn=/^[a-z0-9_-]{21}$/i,Ln=/^[-+]?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)?)??$/,Dn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$n="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Zt;const Zn=/^(?:(?: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])$/,Un=/^(([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})))$/,Fn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dr="((\\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])))",Vn=new RegExp(`^${dr}$`);function fr(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 zn(r){return new RegExp(`^${fr(r)}$`)}function hr(r){let e=`${dr}T${fr(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 Bn(r,e){return!!((e==="v4"||!e)&&Zn.test(r)||(e==="v6"||!e)&&Un.test(r))}class W extends S{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:p.string,received:o.parsedType}),b}const n=new D;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.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),h(s,{code:f.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?h(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&h(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Dn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"email",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Zt||(Zt=new RegExp($n,"u")),Zt.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"emoji",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Nn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"uuid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Mn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"nanoid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")In.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"cuid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")An.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"cuid2",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")jn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"ulid",code:f.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),h(s,{validation:"url",code:f.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),h(s,{validation:"regex",code:f.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),h(s,{code:f.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),h(s,{code:f.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?hr(o).test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Vn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?zn(o).test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{code:f.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Ln.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"duration",code:f.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Bn(e.data,o.version)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"ip",code:f.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Fn.test(e.data)||(s=this._getOrReturnCtx(e,s),h(s,{validation:"base64",code:f.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:f.invalid_string,..._.errToObj(n)})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",..._.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",..._.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",..._.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",..._.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",..._.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",..._.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,..._.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,..._.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",..._.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,..._.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,..._.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,..._.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,..._.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,..._.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,..._.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,..._.errToObj(t)})}nonempty(e){return this.min(1,_.errToObj(e))}trim(){return new W({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new W({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new W({...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}}W.create=r=>{var e;return new W({checks:[],typeName:v.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...k(r)})};function qn(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 ue extends S{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)!==p.number){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:p.number,received:o.parsedType}),b}let n;const s=new D;for(const o of this._def.checks)o.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.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),h(n,{code:f.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),h(n,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?qn(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.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,_.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_.toString(t))}setLimit(e,t,n,s){return new ue({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:_.toString(s)}]})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:_.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_.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)}}ue.create=r=>new ue({checks:[],typeName:v.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...k(r)});class le extends S{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)!==p.bigint){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:p.bigint,received:o.parsedType}),b}let n;const s=new D;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),h(n,{code:f.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),h(n,{code:f.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),h(n,{code:f.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,_.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_.toString(t))}setLimit(e,t,n,s){return new le({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:_.toString(s)}]})}_addCheck(e){return new le({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_.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}}le.create=r=>{var e;return new le({checks:[],typeName:v.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...k(r)})};class ze extends S{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:p.boolean,received:n.parsedType}),b}return Z(e.data)}}ze.create=r=>new ze({typeName:v.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...k(r)});class ge extends S{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:p.date,received:o.parsedType}),b}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_date}),b}const n=new D;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),h(s,{code:f.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),h(s,{code:f.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 ge({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:_.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:_.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}}ge.create=r=>new ge({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:v.ZodDate,...k(r)});class ft extends S{_parse(e){if(this._getType(e)!==p.symbol){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:p.symbol,received:n.parsedType}),b}return Z(e.data)}}ft.create=r=>new ft({typeName:v.ZodSymbol,...k(r)});class Be extends S{_parse(e){if(this._getType(e)!==p.undefined){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:p.undefined,received:n.parsedType}),b}return Z(e.data)}}Be.create=r=>new Be({typeName:v.ZodUndefined,...k(r)});class qe extends S{_parse(e){if(this._getType(e)!==p.null){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:p.null,received:n.parsedType}),b}return Z(e.data)}}qe.create=r=>new qe({typeName:v.ZodNull,...k(r)});class Te extends S{constructor(){super(...arguments),this._any=!0}_parse(e){return Z(e.data)}}Te.create=r=>new Te({typeName:v.ZodAny,...k(r)});class ve extends S{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Z(e.data)}}ve.create=r=>new ve({typeName:v.ZodUnknown,...k(r)});class ne extends S{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:p.never,received:t.parsedType}),b}}ne.create=r=>new ne({typeName:v.ZodNever,...k(r)});class ht extends S{_parse(e){if(this._getType(e)!==p.undefined){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:p.void,received:n.parsedType}),b}return Z(e.data)}}ht.create=r=>new ht({typeName:v.ZodVoid,...k(r)});class Y extends S{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==p.array)return h(t,{code:f.invalid_type,expected:p.array,received:t.parsedType}),b;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(a||c)&&(h(t,{code:a?f.too_big:f.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&&(h(t,{code:f.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&&(h(t,{code:f.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 J(t,a,t.path,c)))).then(a=>D.mergeArray(n,a));const o=[...t.data].map((a,c)=>s.type._parseSync(new J(t,a,t.path,c)));return D.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new Y({...this._def,minLength:{value:e,message:_.toString(t)}})}max(e,t){return new Y({...this._def,maxLength:{value:e,message:_.toString(t)}})}length(e,t){return new Y({...this._def,exactLength:{value:e,message:_.toString(t)}})}nonempty(e){return this.min(1,e)}}Y.create=(r,e)=>new Y({type:r,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...k(e)});function Pe(r){if(r instanceof P){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=Q.create(Pe(n))}return new P({...r._def,shape:()=>e})}else return r instanceof Y?new Y({...r._def,type:Pe(r.element)}):r instanceof Q?Q.create(Pe(r.unwrap())):r instanceof fe?fe.create(Pe(r.unwrap())):r instanceof X?X.create(r.items.map(e=>Pe(e))):r}class P extends S{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)!==p.object){const u=this._getOrReturnCtx(e);return h(u,{code:f.invalid_type,expected:p.object,received:u.parsedType}),b}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof ne&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||c.push(u);const l=[];for(const u of a){const d=o[u],y=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new J(s,y,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof ne){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")c.length>0&&(h(s,{code:f.unrecognized_keys,keys:c}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of c){const y=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new J(s,y,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const y=await d.key,w=await d.value;u.push({key:y,value:w,alwaysSet:d.alwaysSet})}return u}).then(u=>D.mergeObjectSync(n,u)):D.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return _.errToObj,new P({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,o,a,c;const l=(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=_.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new P({...this._def,unknownKeys:"strip"})}passthrough(){return new P({...this._def,unknownKeys:"passthrough"})}extend(e){return new P({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new P({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new P({...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 P({...this._def,shape:()=>t})}omit(e){const t={};return x.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new P({...this._def,shape:()=>t})}deepPartial(){return Pe(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 P({...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 Q;)o=o._def.innerType;t[n]=o}}),new P({...this._def,shape:()=>t})}keyof(){return pr(x.objectKeys(this.shape))}}P.create=(r,e)=>new P({shape:()=>r,unknownKeys:"strip",catchall:ne.create(),typeName:v.ZodObject,...k(e)}),P.strictCreate=(r,e)=>new P({shape:()=>r,unknownKeys:"strict",catchall:ne.create(),typeName:v.ZodObject,...k(e)}),P.lazycreate=(r,e)=>new P({shape:r,unknownKeys:"strip",catchall:ne.create(),typeName:v.ZodObject,...k(e)});class We extends S{_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 V(c.ctx.common.issues));return h(t,{code:f.invalid_union,unionErrors:a}),b}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 l of n){const u={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(l=>new V(l));return h(t,{code:f.invalid_union,unionErrors:c}),b}}get options(){return this._def.options}}We.create=(r,e)=>new We({options:r,typeName:v.ZodUnion,...k(e)});const se=r=>r instanceof Ge?se(r.schema):r instanceof H?se(r.innerType()):r instanceof Ke?[r.value]:r instanceof de?r.options:r instanceof Je?x.objectValues(r.enum):r instanceof Xe?se(r._def.innerType):r instanceof Be?[void 0]:r instanceof qe?[null]:r instanceof Q?[void 0,...se(r.unwrap())]:r instanceof fe?[null,...se(r.unwrap())]:r instanceof Ft||r instanceof tt?se(r.unwrap()):r instanceof Qe?se(r._def.innerType):[];class pt extends S{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.object)return h(t,{code:f.invalid_type,expected:p.object,received:t.parsedType}),b;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}):(h(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),b)}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=se(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:v.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...k(n)})}}function Ut(r,e){const t=ce(r),n=ce(e);if(r===e)return{valid:!0,data:r};if(t===p.object&&n===p.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 l=Ut(r[c],e[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(t===p.array&&n===p.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],l=Ut(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===p.date&&n===p.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class Ye extends S{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Dt(o)||Dt(a))return b;const c=Ut(o.value,a.value);return c.valid?(($t(o)||$t(a))&&t.dirty(),{status:t.value,value:c.data}):(h(n,{code:f.invalid_intersection_types}),b)};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}))}}Ye.create=(r,e,t)=>new Ye({left:r,right:e,typeName:v.ZodIntersection,...k(t)});class X extends S{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return h(n,{code:f.invalid_type,expected:p.array,received:n.parsedType}),b;if(n.data.length<this._def.items.length)return h(n,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&n.data.length>this._def.items.length&&(h(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...n.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new J(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>D.mergeArray(t,a)):D.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new X({...this._def,rest:e})}}X.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new X({items:r,typeName:v.ZodTuple,rest:null,...k(e)})};class He extends S{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!==p.object)return h(n,{code:f.invalid_type,expected:p.object,received:n.parsedType}),b;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in n.data)s.push({key:o._parse(new J(n,c,n.path,c)),value:a._parse(new J(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?D.mergeObjectAsync(t,s):D.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof S?new He({keyType:e,valueType:t,typeName:v.ZodRecord,...k(n)}):new He({keyType:W.create(),valueType:e,typeName:v.ZodRecord,...k(t)})}}class mt extends S{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!==p.map)return h(n,{code:f.invalid_type,expected:p.map,received:n.parsedType}),b;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([c,l],u)=>({key:s._parse(new J(n,c,n.path,[u,"key"])),value:o._parse(new J(n,l,n.path,[u,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return b;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}})}else{const c=new Map;for(const l of a){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return b;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}}}}mt.create=(r,e,t)=>new mt({valueType:e,keyType:r,typeName:v.ZodMap,...k(t)});class be extends S{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return h(n,{code:f.invalid_type,expected:p.set,received:n.parsedType}),b;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(h(n,{code:f.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&&(h(n,{code:f.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(l){const u=new Set;for(const d of l){if(d.status==="aborted")return b;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}const c=[...n.data.values()].map((l,u)=>o._parse(new J(n,l,n.path,u)));return n.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(e,t){return new be({...this._def,minSize:{value:e,message:_.toString(t)}})}max(e,t){return new be({...this._def,maxSize:{value:e,message:_.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}be.create=(r,e)=>new be({valueType:r,minSize:null,maxSize:null,typeName:v.ZodSet,...k(e)});class Oe extends S{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.function)return h(t,{code:f.invalid_type,expected:p.function,received:t.parsedType}),b;function n(c,l){return lt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Ce].filter(u=>!!u),issueData:{code:f.invalid_arguments,argumentsError:l}})}function s(c,l){return lt({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Ce].filter(u=>!!u),issueData:{code:f.invalid_return_type,returnTypeError:l}})}const o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Re){const c=this;return Z(async function(...l){const u=new V([]),d=await c._def.args.parseAsync(l,o).catch(m=>{throw u.addIssue(n(l,m)),u}),y=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(y,o).catch(m=>{throw u.addIssue(s(y,m)),u})})}else{const c=this;return Z(function(...l){const u=c._def.args.safeParse(l,o);if(!u.success)throw new V([n(l,u.error)]);const d=Reflect.apply(a,this,u.data),y=c._def.returns.safeParse(d,o);if(!y.success)throw new V([s(d,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Oe({...this._def,args:X.create(e).rest(ve.create())})}returns(e){return new Oe({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Oe({args:e||X.create([]).rest(ve.create()),returns:t||ve.create(),typeName:v.ZodFunction,...k(n)})}}class Ge extends S{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})}}Ge.create=(r,e)=>new Ge({getter:r,typeName:v.ZodLazy,...k(e)});class Ke extends S{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ke.create=(r,e)=>new Ke({value:r,typeName:v.ZodLiteral,...k(e)});function pr(r,e){return new de({values:r,typeName:v.ZodEnum,...k(e)})}class de extends S{constructor(){super(...arguments),Fe.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{expected:x.joinValues(n),received:t.parsedType,code:f.invalid_type}),b}if(dt(this,Fe)||ur(this,Fe,new Set(this._def.values)),!dt(this,Fe).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{received:t.data,code:f.invalid_enum_value,options:n}),b}return Z(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 de.create(e,{...this._def,...t})}exclude(e,t=this._def){return de.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}Fe=new WeakMap,de.create=pr;class Je extends S{constructor(){super(...arguments),Ve.set(this,void 0)}_parse(e){const t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){const s=x.objectValues(t);return h(n,{expected:x.joinValues(s),received:n.parsedType,code:f.invalid_type}),b}if(dt(this,Ve)||ur(this,Ve,new Set(x.getValidEnumValues(this._def.values))),!dt(this,Ve).has(e.data)){const s=x.objectValues(t);return h(n,{received:n.data,code:f.invalid_enum_value,options:s}),b}return Z(e.data)}get enum(){return this._def.values}}Ve=new WeakMap,Je.create=(r,e)=>new Je({values:r,typeName:v.ZodNativeEnum,...k(e)});class Re extends S{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.promise&&t.common.async===!1)return h(t,{code:f.invalid_type,expected:p.promise,received:t.parsedType}),b;const n=t.parsedType===p.promise?t.data:Promise.resolve(t.data);return Z(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Re.create=(r,e)=>new Re({type:r,typeName:v.ZodPromise,...k(e)});class H extends S{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.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=>{h(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 b;const l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?b:l.status==="dirty"||t.value==="dirty"?xe(l.value):l});{if(t.value==="aborted")return b;const c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?b:c.status==="dirty"||t.value==="dirty"?xe(c.value):c}}if(s.type==="refinement"){const a=c=>{const l=s.refinement(c,o);if(n.common.async)return Promise.resolve(l);if(l 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"?b:(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"?b:(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(!Ze(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=>Ze(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:t.value,value:c})):a);x.assertNever(s)}}H.create=(r,e,t)=>new H({schema:r,typeName:v.ZodEffects,effect:e,...k(t)}),H.createWithPreprocess=(r,e,t)=>new H({schema:e,effect:{type:"preprocess",transform:r},typeName:v.ZodEffects,...k(t)});class Q extends S{_parse(e){return this._getType(e)===p.undefined?Z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Q.create=(r,e)=>new Q({innerType:r,typeName:v.ZodOptional,...k(e)});class fe extends S{_parse(e){return this._getType(e)===p.null?Z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fe.create=(r,e)=>new fe({innerType:r,typeName:v.ZodNullable,...k(e)});class Xe extends S{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Xe.create=(r,e)=>new Xe({innerType:r,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...k(e)});class Qe extends S{_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 Ue(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Qe.create=(r,e)=>new Qe({innerType:r,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...k(e)});class yt extends S{_parse(e){if(this._getType(e)!==p.nan){const n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:p.nan,received:n.parsedType}),b}return{status:"valid",value:e.data}}}yt.create=r=>new yt({typeName:v.ZodNaN,...k(r)});const Wn=Symbol("zod_brand");class Ft extends S{_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 et extends S{_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"?b:o.status==="dirty"?(t.dirty(),xe(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"?b: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 et({in:e,out:t,typeName:v.ZodPipeline})}}class tt extends S{_parse(e){const t=this._def.innerType._parse(e),n=s=>(Ze(s)&&(s.value=Object.freeze(s.value)),s);return Ue(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}tt.create=(r,e)=>new tt({innerType:r,typeName:v.ZodReadonly,...k(e)});function mr(r,e={},t){return r?Te.create().superRefine((n,s)=>{var o,a;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(a=(o=c.fatal)!==null&&o!==void 0?o:t)!==null&&a!==void 0?a:!0,u=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...u,fatal:l})}}):Te.create()}const Yn={object:P.lazycreate};var v;(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"})(v||(v={}));const Hn=(r,e={message:`Input not instance of ${r.name}`})=>mr(t=>t instanceof r,e),yr=W.create,_r=ue.create,Gn=yt.create,Kn=le.create,gr=ze.create,Jn=ge.create,Xn=ft.create,Qn=Be.create,es=qe.create,ts=Te.create,rs=ve.create,ns=ne.create,ss=ht.create,os=Y.create,is=P.create,as=P.strictCreate,cs=We.create,us=pt.create,ls=Ye.create,ds=X.create,fs=He.create,hs=mt.create,ps=be.create,ms=Oe.create,ys=Ge.create,_s=Ke.create,gs=de.create,vs=Je.create,bs=Re.create,vr=H.create,ws=Q.create,ks=fe.create,Es=H.createWithPreprocess,Ss=et.create;var i=Object.freeze({__proto__:null,defaultErrorMap:Ce,setErrorMap:On,getErrorMap:ut,makeIssue:lt,EMPTY_PATH:Rn,addIssueToContext:h,ParseStatus:D,INVALID:b,DIRTY:xe,OK:Z,isAborted:Dt,isDirty:$t,isValid:Ze,isAsync:Ue,get util(){return x},get objectUtil(){return Lt},ZodParsedType:p,getParsedType:ce,ZodType:S,datetimeRegex:hr,ZodString:W,ZodNumber:ue,ZodBigInt:le,ZodBoolean:ze,ZodDate:ge,ZodSymbol:ft,ZodUndefined:Be,ZodNull:qe,ZodAny:Te,ZodUnknown:ve,ZodNever:ne,ZodVoid:ht,ZodArray:Y,ZodObject:P,ZodUnion:We,ZodDiscriminatedUnion:pt,ZodIntersection:Ye,ZodTuple:X,ZodRecord:He,ZodMap:mt,ZodSet:be,ZodFunction:Oe,ZodLazy:Ge,ZodLiteral:Ke,ZodEnum:de,ZodNativeEnum:Je,ZodPromise:Re,ZodEffects:H,ZodTransformer:H,ZodOptional:Q,ZodNullable:fe,ZodDefault:Xe,ZodCatch:Qe,ZodNaN:yt,BRAND:Wn,ZodBranded:Ft,ZodPipeline:et,ZodReadonly:tt,custom:mr,Schema:S,ZodSchema:S,late:Yn,get ZodFirstPartyTypeKind(){return v},coerce:{string:r=>W.create({...r,coerce:!0}),number:r=>ue.create({...r,coerce:!0}),boolean:r=>ze.create({...r,coerce:!0}),bigint:r=>le.create({...r,coerce:!0}),date:r=>ge.create({...r,coerce:!0})},any:ts,array:os,bigint:Kn,boolean:gr,date:Jn,discriminatedUnion:us,effect:vr,enum:gs,function:ms,instanceof:Hn,intersection:ls,lazy:ys,literal:_s,map:hs,nan:Gn,nativeEnum:vs,never:ns,null:es,nullable:ks,number:_r,object:is,oboolean:()=>gr().optional(),onumber:()=>_r().optional(),optional:ws,ostring:()=>yr().optional(),pipeline:Ss,preprocess:Es,promise:bs,record:fs,set:ps,strictObject:as,string:yr,symbol:Xn,transformer:vr,tuple:ds,undefined:Qn,union:cs,unknown:rs,void:ss,NEVER:b,ZodIssueCode:f,quotelessJson:Pn,ZodError:V});const Cs=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()}),xs=i.array(Cs),Ts=i.object({code:i.string(),message:i.string(),path:i.array(i.string())}),Ps=i.array(Ts),Os={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},Vt=r=>{const e=r.toLowerCase().trim();return Os[e]??r},Rs=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},Is=r=>r.length===1?Vt(r[0].msg):`Please fix the following errors:
|
|
2
|
-
${r.map(t=>`• ${
|
|
3
|
-
`)}`,
|
|
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 Xt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Xt||(Xt={}));const _=x.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=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"]),Vn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class B 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 B))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()}}B.create=r=>new B(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 Sr=De;function zn(r){Sr=r}function Et(){return Sr}const St=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}},Bn=[];function m(r,e){const t=Et(),n=St({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 ${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 $.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}),Z=r=>({status:"valid",value:r}),Qt=r=>r.status==="aborted",er=r=>r.status==="dirty",Je=r=>r.status==="valid",Xe=r=>typeof Promise<"u"&&r instanceof Promise;function Ct(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 Cr(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 Pr=(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 B(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 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 $,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 Pr(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 Pr(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 be.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 nr({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 qn=/^c[^\s-]{8,}$/i,Yn=/^[0-9a-z]+$/,Gn=/^[0-9A-HJKMNP-TV-Z]{26}$/,Wn=/^[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,Hn=/^[a-z0-9_-]{21}$/i,Kn=/^[-+]?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)?)??$/,Jn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let tr;const Qn=/^(?:(?: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])$/,es=/^(([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})))$/,ts=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xr="((\\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])))",rs=new RegExp(`^${xr}$`);function Tr(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 ns(r){return new RegExp(`^${Tr(r)}$`)}function Ar(r){let e=`${xr}T${Tr(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 ss(r,e){return!!((e==="v4"||!e)&&Qn.test(r)||(e==="v6"||!e)&&es.test(r))}class H extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_.string){const o=this._getOrReturnCtx(e);return m(o,{code:p.invalid_type,expected:_.string,received:o.parsedType}),k}const n=new $;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),m(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),m(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?m(s,{code:p.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&m(s,{code:p.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")Jn.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")tr||(tr=new RegExp(Xn,"u")),tr.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Wn.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Hn.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"nanoid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")qn.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Yn.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:p.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Gn.test(e.data)||(s=this._getOrReturnCtx(e,s),m(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),m(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),m(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),m(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),m(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),m(s,{code:p.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Ar(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:p.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?rs.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:p.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?ns(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:p.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Kn.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"duration",code:p.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?ss(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:p.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?ts.test(e.data)||(s=this._getOrReturnCtx(e,s),m(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 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 os(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 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 m(o,{code:p.invalid_type,expected:_.number,received:o.parsedType}),k}let n;const s=new $;for(const o of this._def.checks)o.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(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),m(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),m(n,{code:p.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?os(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),m(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),m(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 _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"&&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)}}_e.create=r=>new _e({checks:[],typeName:w.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class ge 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 m(o,{code:p.invalid_type,expected:_.bigint,received:o.parsedType}),k}let n;const s=new $;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),m(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),m(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),m(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 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 C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_.boolean){const n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:_.boolean,received:n.parsedType}),k}return Z(e.data)}}tt.create=r=>new tt({typeName:w.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Ae extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_.date){const o=this._getOrReturnCtx(e);return m(o,{code:p.invalid_type,expected:_.date,received:o.parsedType}),k}if(isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return m(o,{code:p.invalid_date}),k}const n=new $;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),m(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),m(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 Ae({...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}}Ae.create=r=>new Ae({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:w.ZodDate,...S(r)});class Pt extends C{_parse(e){if(this._getType(e)!==_.symbol){const n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:_.symbol,received:n.parsedType}),k}return Z(e.data)}}Pt.create=r=>new Pt({typeName:w.ZodSymbol,...S(r)});class rt extends C{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:_.undefined,received:n.parsedType}),k}return Z(e.data)}}rt.create=r=>new rt({typeName:w.ZodUndefined,...S(r)});class nt extends C{_parse(e){if(this._getType(e)!==_.null){const n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:_.null,received:n.parsedType}),k}return Z(e.data)}}nt.create=r=>new nt({typeName:w.ZodNull,...S(r)});class Ue extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return Z(e.data)}}Ue.create=r=>new Ue({typeName:w.ZodAny,...S(r)});class Ie extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Z(e.data)}}Ie.create=r=>new Ie({typeName:w.ZodUnknown,...S(r)});class le extends C{_parse(e){const t=this._getOrReturnCtx(e);return m(t,{code:p.invalid_type,expected:_.never,received:t.parsedType}),k}}le.create=r=>new le({typeName:w.ZodNever,...S(r)});class xt extends C{_parse(e){if(this._getType(e)!==_.undefined){const n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:_.void,received:n.parsedType}),k}return Z(e.data)}}xt.create=r=>new xt({typeName:w.ZodVoid,...S(r)});class K extends C{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==_.array)return m(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)&&(m(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&&(m(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&&(m(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=>$.mergeArray(n,a));const o=[...t.data].map((a,c)=>s.type._parseSync(new re(t,a,t.path,c)));return $.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 R){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=se.create($e(n))}return new R({...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 be?be.create($e(r.unwrap())):r instanceof ne?ne.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 m(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],y=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new re(s,y,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&&(m(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 y=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new re(s,y,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of u){const y=await d.key,b=await d.value;l.push({key:y,value:b,alwaysSet:d.alwaysSet})}return l}).then(l=>$.mergeObjectSync(n,l)):$.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:w.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 se;)o=o._def.innerType;t[n]=o}}),new R({...this._def,shape:()=>t})}keyof(){return Ir(x.objectKeys(this.shape))}}R.create=(r,e)=>new R({shape:()=>r,unknownKeys:"strip",catchall:le.create(),typeName:w.ZodObject,...S(e)}),R.strictCreate=(r,e)=>new R({shape:()=>r,unknownKeys:"strict",catchall:le.create(),typeName:w.ZodObject,...S(e)}),R.lazycreate=(r,e)=>new R({shape:r,unknownKeys:"strip",catchall:le.create(),typeName:w.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 B(c.ctx.common.issues));return m(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 B(u));return m(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?x.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 be?[null,...ue(r.unwrap())]:r instanceof nr||r instanceof ft?ue(r.unwrap()):r instanceof dt?ue(r._def.innerType):[];class Tt extends C{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.object)return m(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}):(m(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 Tt({typeName:w.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...S(n)})}}function rr(r,e){const t=ye(r),n=ye(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=rr(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=rr(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(Qt(o)||Qt(a))return k;const c=rr(o.value,a.value);return c.valid?((er(o)||er(a))&&t.dirty(),{status:t.value,value:c.data}):(m(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 C{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.array)return m(n,{code:p.invalid_type,expected:_.array,received:n.parsedType}),k;if(n.data.length<this._def.items.length)return m(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&&(m(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=>$.mergeArray(t,a)):$.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 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 m(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?$.mergeObjectAsync(t,s):$.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:w.ZodRecord,...S(n)}):new it({keyType:H.create(),valueType:e,typeName:w.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 m(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 C{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==_.set)return m(n,{code:p.invalid_type,expected:_.set,received:n.parsedType}),k;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(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&&(m(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 C{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.function)return m(t,{code:p.invalid_type,expected:_.function,received:t.parsedType}),k;function n(c,u){return St({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Et(),De].filter(l=>!!l),issueData:{code:p.invalid_arguments,argumentsError:u}})}function s(c,u){return St({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Et(),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 Z(async function(...u){const l=new B([]),d=await c._def.args.parseAsync(u,o).catch(h=>{throw l.addIssue(n(u,h)),l}),y=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(y,o).catch(h=>{throw l.addIssue(s(y,h)),l})})}else{const c=this;return Z(function(...u){const l=c._def.args.safeParse(u,o);if(!l.success)throw new B([n(u,l.error)]);const d=Reflect.apply(a,this,l.data),y=c._def.returns.safeParse(d,o);if(!y.success)throw new B([s(d,y.error)]);return y.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 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:w.ZodLazy,...S(e)});class ct extends C{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return m(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 Ir(r,e){return new ve({values:r,typeName:w.ZodEnum,...S(e)})}class ve 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 m(t,{expected:x.joinValues(n),received:t.parsedType,code:p.invalid_type}),k}if(Ct(this,Qe)||Cr(this,Qe,new Set(this._def.values)),!Ct(this,Qe).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return m(t,{received:t.data,code:p.invalid_enum_value,options:n}),k}return Z(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=Ir;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 m(n,{expected:x.joinValues(s),received:n.parsedType,code:p.invalid_type}),k}if(Ct(this,et)||Cr(this,et,new Set(x.getValidEnumValues(this._def.values))),!Ct(this,et).has(e.data)){const s=x.objectValues(t);return m(n,{received:n.data,code:p.invalid_enum_value,options:s}),k}return Z(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 C{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==_.promise&&t.common.async===!1)return m(t,{code:p.invalid_type,expected:_.promise,received:t.parsedType}),k;const n=t.parsedType===_.promise?t.data:Promise.resolve(t.data);return Z(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 C{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=>{m(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)}}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 C{_parse(e){return this._getType(e)===_.undefined?Z(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 be extends C{_parse(e){return this._getType(e)===_.null?Z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}be.create=(r,e)=>new be({innerType:r,typeName:w.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:w.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 B(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new B(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 It extends C{_parse(e){if(this._getType(e)!==_.nan){const n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:_.nan,received:n.parsedType}),k}return{status:"valid",value:e.data}}}It.create=r=>new It({typeName:w.ZodNaN,...S(r)});const is=Symbol("zod_brand");class nr 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:w.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:w.ZodReadonly,...S(e)});function Rr(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 as={object:R.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 cs=(r,e={message:`Input not instance of ${r.name}`})=>Rr(t=>t instanceof r,e),Or=H.create,Nr=_e.create,ls=It.create,us=ge.create,Mr=tt.create,ds=Ae.create,ps=Pt.create,fs=rt.create,hs=nt.create,ms=Ue.create,ys=Ie.create,_s=le.create,gs=xt.create,vs=K.create,bs=R.create,ws=R.strictCreate,ks=st.create,Es=Tt.create,Ss=ot.create,Cs=ne.create,Ps=it.create,xs=At.create,Ts=Re.create,As=Fe.create,Is=at.create,Rs=ct.create,Os=ve.create,Ns=lt.create,Ms=Ze.create,jr=J.create,js=se.create,Ds=be.create,Ls=J.createWithPreprocess,Us=pt.create;var i=Object.freeze({__proto__:null,defaultErrorMap:De,setErrorMap:zn,getErrorMap:Et,makeIssue:St,EMPTY_PATH:Bn,addIssueToContext:m,ParseStatus:$,INVALID:k,DIRTY:Le,OK:Z,isAborted:Qt,isDirty:er,isValid:Je,isAsync:Xe,get util(){return x},get objectUtil(){return Xt},ZodParsedType:_,getParsedType:ye,ZodType:C,datetimeRegex:Ar,ZodString:H,ZodNumber:_e,ZodBigInt:ge,ZodBoolean:tt,ZodDate:Ae,ZodSymbol:Pt,ZodUndefined:rt,ZodNull:nt,ZodAny:Ue,ZodUnknown:Ie,ZodNever:le,ZodVoid:xt,ZodArray:K,ZodObject:R,ZodUnion:st,ZodDiscriminatedUnion:Tt,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:be,ZodDefault:ut,ZodCatch:dt,ZodNaN:It,BRAND:is,ZodBranded:nr,ZodPipeline:pt,ZodReadonly:ft,custom:Rr,Schema:C,ZodSchema:C,late:as,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=>Ae.create({...r,coerce:!0})},any:ms,array:vs,bigint:us,boolean:Mr,date:ds,discriminatedUnion:Es,effect:jr,enum:Os,function:As,instanceof:cs,intersection:Ss,lazy:Is,literal:Rs,map:xs,nan:ls,nativeEnum:Ns,never:_s,null:hs,nullable:Ds,number:Nr,object:bs,oboolean:()=>Mr().optional(),onumber:()=>Nr().optional(),optional:js,ostring:()=>Or().optional(),pipeline:Us,preprocess:Ls,promise:Ms,record:Ps,set:Ts,strictObject:ws,string:Or,symbol:ps,transformer:jr,tuple:Cs,undefined:fs,union:ks,unknown:ys,void:gs,NEVER:k,ZodIssueCode:p,quotelessJson:Vn,ZodError:B});const $s=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()}),Fs=i.array($s),Zs=i.object({code:i.string(),message:i.string(),path:i.array(i.string())}),Vs=i.array(Zs),zs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},sr=r=>{const e=r.toLowerCase().trim();return zs[e]??r},Bs=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},qs=r=>r.length===1?sr(r[0].msg):`Please fix the following errors:
|
|
2
|
+
${r.map(t=>`• ${sr(t.msg)}`).join(`
|
|
3
|
+
`)}`,Ys=r=>`Encountered the following errors:
|
|
4
4
|
${r.map(t=>`- ${t.path.join("/")}: ${t.message}`).join(`
|
|
5
|
-
`)}`,
|
|
6
|
-
${r.message}`),r.message)}else return Vt(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}},$=i.string().trim().min(1,{message:"Cannot be blank"}),A=i.string().trim().optional(),rt=r=>i.nullable(r.optional());var E=(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))(E||{});const br=i.nativeEnum(E);var wr=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(wr||{});const kr=i.nativeEnum(wr),Er=i.union([br,kr]);var Ie=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(Ie||{});const Ns=i.nativeEnum(Ie),_t=i.object({provider:i.string(),processor_name:rt(i.string()),metadata:rt(i.record(i.string(),i.any()))}),Ms=i.object({id:i.string()});i.object({cardNumber:A,expiry:A,cvc:A}),i.object({backgroundColor:A,color:A,fontFamily:A,fontSize:A,fontWeight:A,margin:A,padding:A,letterSpacing:A,lineHeight:A,hideIcon:A});const G=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"]),Ls=G.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Ds=i.object({type:Ls}),$s=G.extract(["BLUR","FOCUS","CHANGE"]),Zs=i.object({type:$s,elementType:kr,errors:i.array(i.string()).optional()}),Us=G.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),Fs=i.object({type:Us,message:$,headers:i.record(i.string(),i.string()).optional()}),Vs=G.extract(["VALIDATION_ERROR"]),zs=i.object({type:Vs,elementType:Er,errors:i.array(i.string())}),Bs=i.object({type:i.literal(G.enum.LAYOUT),height:$}),qs=i.object({type:i.literal(G.enum.LOADED),sessionId:$,totalAmountAtoms:i.number(),currency:A,checkoutPaymentMethods:i.array(_t)}),Ws=i.object({type:i.literal(G.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:i.record(i.string(),i.any()),paymentFlowMetadata:i.any().optional(),startPFMetadata:i.optional(i.record(i.string(),i.any()))}),Ys=i.object({type:i.literal(G.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:i.string()}),nt=i.object({firstName:$,lastName:$,email:$,zipCode:$,country:$,promotionCode:A}),Hs=i.object({firstName:A,lastName:A,email:$,zipCode:$,country:$,promotionCode:A}),Gs=G.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),Ks=i.object({type:Gs,sessionId:$,checkoutPaymentMethod:_t,paymentFlowMetadata:i.any().optional(),doNotUseLegacyCCFlow:i.boolean().optional(),existingCCPMId:A}).extend(nt.shape),Js=i.object({type:i.literal(G.enum.TOKENIZE_SUCCESS),isReadyForCheckout:i.boolean()}),Xs=i.object({type:i.literal(G.enum.CHECKOUT_SUCCESS),invoiceUrls:i.array(i.string()),subscriptionIds:i.array(i.string()),customerId:i.string()}),Qs=i.discriminatedUnion("type",[Ds,Zs,Fs,zs,Bs,qs,Ks,Js,Xs,Ws,Ys]),eo=i.object({payload:Qs,nonce:$,formId:$,elementId:$});i.object({amountAtom:i.number(),currency:$}),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:rt(i.string()),their_pm_id:rt(i.string())});const to=i.object({payment_methods:i.array(Ms)}),ro=i.object({elementType:i.string(),errors:i.array(i.string())});i.object({session_id:i.string()});const no=i.object({success:i.literal(!1),error_type:i.literal("validation_error"),errors:i.array(ro)}),so=i.discriminatedUnion("success",[i.object({success:i.literal(!0)}),no]);i.object({session_id:i.string(),checkout_payment_method:_t,non_cde_form_fields:nt,do_not_use_legacy_cc_flow:i.boolean().optional(),existing_cc_pm_id:rt(i.string())}),i.object({session_id:i.string(),checkout_payment_method:_t,non_cde_form_fields:nt,extra_metadata:i.record(i.string(),i.any()).optional()});var we=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))(we||{});const oo=i.object({status:i.enum(["success","failure","cancelled"]),href:i.string().optional().nullable()});i.object({href:i.string().optional().nullable()});const io=i.object({type:i.string(),redirect_url:i.string(),initial_intent_id:i.string(),consent_id:i.string()}),ao=i.discriminatedUnion("present",[i.object({present:i.literal(!0),href:i.string()}),i.object({present:i.literal(!1)})]),co=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const s=br.parse(t);Array.isArray(n)?e[s]=n:Array.isArray(n._errors)&&(e[s]=n._errors)}catch{return}}),e},uo=i.object({stripe_pk:i.string(),client_secret:i.string(),stripe_pm_id:i.string()}),lo=i.object({type:i.string(),client_secret:i.string(),stripe_pk:i.string()}),fo={usd:"usd",brl:"brl"},gt=async r=>{for(let t=0;t<10;t++)Sr()||await mo(500);if(!Sr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},ho=async(r,e)=>{const t=await gt(r);return{elements:t.elements(e),stripe:t}},po=async(r,e,t,n,s)=>{const o=await gt(r),a=fo[t.toLowerCase().trim()];return o.paymentRequest({country:"US",currency:a,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},mo=r=>new Promise(e=>{setTimeout(e,r)}),Sr=()=>"Stripe"in window,yo=async r=>new Promise((e,t)=>{try{r.on("paymentmethod",async n=>{e(n)}),r.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){t(n)}}),_o=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 gt(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},go=async r=>{var s,o,a,c;const t=await(await gt(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."}`)},vo=r=>JSON.stringify(r);for(var N=[],zt=0;zt<256;++zt)N.push((zt+256).toString(16).slice(1));function bo(r,e=0){return(N[r[e+0]]+N[r[e+1]]+N[r[e+2]]+N[r[e+3]]+"-"+N[r[e+4]]+N[r[e+5]]+"-"+N[r[e+6]]+N[r[e+7]]+"-"+N[r[e+8]]+N[r[e+9]]+"-"+N[r[e+10]]+N[r[e+11]]+N[r[e+12]]+N[r[e+13]]+N[r[e+14]]+N[r[e+15]]).toLowerCase()}var vt,wo=new Uint8Array(16);function ko(){if(!vt&&(vt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!vt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vt(wo)}var Eo=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Cr={randomUUID:Eo};function So(r,e,t){if(Cr.randomUUID&&!e&&!r)return Cr.randomUUID();r=r||{};var n=r.random||(r.rng||ko)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,bo(n)}const bt=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((s,o)=>{const a=o.getAttribute("data-opid");return a?{...s,[a]:o.value}:s},{}),Co=r=>{try{return eo.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var ee;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(ee||(ee={}));var ke;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(ke||(ke={}));var st;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(st||(st={}));var Bt;(function(r){r.DataCloneError="DataCloneError"})(Bt||(Bt={}));var pe;(function(r){r.Message="message"})(pe||(pe={}));const xo=(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)}}},To=r=>(...e)=>{r&&console.log("[Penpal]",...e)},Po={"http:":"80","https:":"443"},Oo=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ro=["file:","data:"],Io=r=>{if(r&&Ro.find(c=>r.startsWith(c)))return"null";const e=document.location,t=Oo.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!==Po[n]?`:${o}`:"";return`${n}//${s}${a}`},xr=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Ao=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 l=!1;const u=d=>{if(d.source!==o||d.data.penpal!==ee.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const y=d.data,{methodName:w,args:m,id:g}=y;t(`${n}: Received ${w}() call`);const C=R=>q=>{if(t(`${n}: Sending ${w}() reply`),l){t(`${n}: Unable to send ${w}() reply due to destroyed connection`);return}const B={penpal:ee.Reply,id:g,resolution:R,returnValue:q};R===ke.Rejected&&q instanceof Error&&(B.returnValue=xr(q),B.returnValueIsError=!0);try{o.postMessage(B,a)}catch(j){if(j.name===Bt.DataCloneError){const Le={penpal:ee.Reply,id:g,resolution:ke.Rejected,returnValue:xr(j),returnValueIsError:!0};o.postMessage(Le,a)}throw j}};new Promise(R=>R(e[w].apply(e,m))).then(C(ke.Fulfilled),C(ke.Rejected))};return s.addEventListener(pe.Message,u),()=>{l=!0,s.removeEventListener(pe.Message,u)}};let No=0;const Mo=()=>++No,Tr=".",Pr=r=>r?r.split(Tr):[],Lo=r=>r.join(Tr),Do=(r,e)=>{const t=Pr(e||"");return t.push(r),Lo(t)},$o=(r,e,t)=>{const n=Pr(e);return n.reduce((s,o,a)=>(typeof s[o]>"u"&&(s[o]={}),a===n.length-1&&(s[o]=t),s[o]),r),r},Or=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const s=r[n],o=Do(n,e);typeof s=="object"&&Object.assign(t,Or(s,o)),typeof s=="function"&&(t[o]=s)}),t},Zo=r=>{const e={};for(const t in r)$o(e,t,r[t]);return e},Uo=(r,e,t,n,s)=>{const{localName:o,local:a,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;s(`${o}: Connecting call sender`);const y=m=>(...g)=>{s(`${o}: Sending ${m}() call`);let C;try{c.closed&&(C=!0)}catch{C=!0}if(C&&n(),d){const R=new Error(`Unable to send ${m}() call due to destroyed connection`);throw R.code=st.ConnectionDestroyed,R}return new Promise((R,q)=>{const B=Mo(),j=De=>{if(De.source!==c||De.data.penpal!==ee.Reply||De.data.id!==B)return;if(u!=="*"&&De.origin!==u){s(`${o} received message from origin ${De.origin} which did not match expected origin ${u}`);return}const ir=De.data;s(`${o}: Received ${m}() reply`),a.removeEventListener(pe.Message,j);let ar=ir.returnValue;ir.returnValueIsError&&(ar=Ao(ar)),(ir.resolution===ke.Fulfilled?R:q)(ar)};a.addEventListener(pe.Message,j);const Le={penpal:ee.Call,id:B,methodName:m,args:g};c.postMessage(Le,l)})},w=t.reduce((m,g)=>(m[g]=y(g),m),{});return Object.assign(r,Zo(w)),()=>{d=!0}},Fo=(r,e,t,n,s)=>{const{destroy:o,onDestroy:a}=n;let c,l;const u={};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 y={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=jo(y,r,s),a(c),l&&l.forEach(m=>{delete u[m]}),l=d.data.methodNames;const w=Uo(u,y,l,o,s);return a(w),u}},Vo=(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:ee.SynAck,methodNames:Object.keys(e)};s.source.postMessage(o,n)},zo=6e4,Bo=(r,e)=>{const{destroy:t,onDestroy:n}=e,s=setInterval(()=>{r.isConnected||(clearInterval(s),t())},zo);n(()=>{clearInterval(s)})},qo=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=st.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},Wo=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=st.NoIframeSrc,e}},Rr=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:s,debug:o=!1}=r;const a=To(o),c=xo("Parent",a),{onDestroy:l,destroy:u}=c;n||(Wo(e),n=Io(e.src));const d=n==="null"?"*":n,y=Or(t),w=Vo(a,y,n,d),m=Fo(y,n,d,c,a);return{promise:new Promise((C,R)=>{const q=qo(s,u),B=j=>{if(!(j.source!==e.contentWindow||!j.data)){if(j.data.penpal===ee.Syn){w(j);return}if(j.data.penpal===ee.Ack){const Le=m(j);Le&&(q(),C(Le));return}}};window.addEventListener(pe.Message,B),a("Parent: Awaiting handshake"),Bo(e,c),l(j=>{window.removeEventListener(pe.Message,B),j&&R(j)})}),destroy(){u()}}},Yo=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}},Ho=(r,e)=>!!r&&e,I=r=>i.nullable(r.optional());i.string().trim().min(1,{message:"Cannot be blank"});const Go=i.object({cde_response_type:i.literal("error"),message:i.string(),headers:i.record(i.string(),i.string()).optional()});i.enum(["usd","brl"]);const Ir=i.object({name:i.string(),amount_atom_off:I(i.number()),percent_off:I(i.number()),currency:I(i.string()),duration:i.string(),duration_in_months:I(i.number())}),Ar=i.object({amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),currency:i.string(),description:I(i.string()),price_id:i.string(),billing_interval:I(i.string()),billing_interval_count:I(i.number().int()),quantity:i.number().int()}),Ko=i.record(i.string(),i.any()),Jo=i.object({name:i.string(),settings:I(Ko)}),ot=i.object({provider:i.string(),processor_name:I(i.string()),metadata:I(i.record(i.string(),i.any()))}),Xo=i.object({quantity:i.number()}),Qo=i.object({id:I(i.string()),billing_interval:I(i.string()),billing_interval_count:I(i.number().int()),subscription_items:i.array(Xo),trial_start:I(i.string()),trial_end:I(i.string())}),jr=i.object({amount_atom:i.number()}),ei=i.object({amount_atom:i.number(),amount_atom_considering_discount_applied:i.number(),currency:i.string(),discount_amount_atoms:i.array(jr),subscription_item_id:i.string()}),ti=i.object({coupon:Ir}),ri=i.object({currency:i.string(),discounts:i.array(ti),hosted_invoice_url:I(i.string()),lines:i.array(ei),remaining_amount_atom:i.number(),tax_amount_atom:i.number(),total_amount_atom:i.number(),total_discount_amount_atoms:i.array(jr)}),Nr=i.object({created:i.array(Qo),invoices:i.array(ri)}),Mr=i.object({preview:Nr,preview_post_trial:I(Nr),coupons:i.array(Ir)}),Lr=i.object({status:i.literal("open"),token:i.string(),email:I(i.string()),line_items:i.array(Ar),amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),brand:Jo,subs_preview:I(Mr),methods_available:i.array(ot)}),Dr=i.discriminatedUnion("mode",[i.object({mode:i.literal("setup"),currency:i.nullable(i.undefined())}).extend(Lr.shape),i.object({mode:i.enum(["payment","subscription"]),currency:i.string()}).extend(Lr.shape)]),ni=i.object({status:i.literal("complete")}),si=i.object({status:i.literal("expired")});i.union([Dr,ni,si]),i.object({logo:i.string(),icon:i.string(),primary_color:i.string(),secondary_color:i.string()});const $r=i.object({invoice_urls:i.array(i.string()),subscription_ids:i.array(i.string()),customer_id: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(Ar),total_amount_atom:i.number().int(),cancel_at_end:i.boolean(),checkout_payment_method:ot,promotion_code:i.string().optional(),do_not_use_legacy_cc_flow:i.boolean().optional(),use_confirmed_pm_id:I(i.string())});const Zr=i.object({payment_method_id:i.string()});i.object({id:i.string(),return_url:i.string()});const oi=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()});i.array(oi);const ii=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()});i.object({payment_provider:i.string(),checkout_payment_method:ot,existing_cc_pm_id:i.string().optional(),their_existing_pm_id:i.string().optional()}).extend(ii.shape);const Ur=i.object({required_user_actions:i.array(i.record(i.string(),i.any()))});i.object({fields:Hs,checkoutPaymentMethod:ot}),i.object({session_id:i.string(),non_cde_form_fields:nt,checkout_payment_method:ot,extra_metadata:i.record(i.string(),i.any())});const ai=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),cc_pm_id:i.string()});i.record(i.any());const ci=r=>r.reduce((e,t)=>e+t,0);function ui(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function li(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var di=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)}}(),fi=function(r){di(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}),ui(o,s.prototype),li(o),o}return e}(Error);class Fr extends fi{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const z=async(r,e,t)=>{const n=await r.send(e);if(pi(n))throw new Fr(n);if(!hi(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},hi=(r,e)=>e.safeParse(r).success,pi=r=>Go.safeParse(r).success,mi=async(r,e)=>await z(r,{type:"get_checkout_preview",payload:e},Mr),Ee=async r=>await z(r,{type:"get_prefill",payload:{}},Dr),Vr=async(r,e)=>await z(r,{type:"v2_start_payment_flow",payload:e},Ur),yi=async(r,e)=>await z(r,{type:"start_payment_flow_for_cc",payload:e},ai),_i=async(r,e)=>await z(r,{type:"start_payment_flow_for_pr",payload:e},Ur),wt=async(r,e)=>await z(r,{type:"confirm_payment_flow",payload:e},to),gi=async(r,e)=>await z(r,{type:"finalize_setup_payment_method",payload:e},Zr),vi=async(r,e)=>await z(r,{type:"check_if_popup_window_verified",payload:e},ao),bi=async(r,e,t)=>{const n=await mi(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=ci(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:o,amountAtom:a}},zr=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const s=await bi(r,e,n);return{amountAtom:s.amountAtom,currency:s.currency}}},wi=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>z(n,{type:"tokenize_card",payload:e},so)))},Br=async(r,e)=>{try{return await z(r,{type:"checkout_card_elements",payload:e},$r)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},ki=async(r,e)=>await z(r,{type:"setup_payment_method",payload:e},Zr),qt=async(r,e)=>await z(r,{type:"checkout",payload:e},$r),qr=1e3,Ei=async(r,e)=>{console.log(e);const n=await Rr({iframe:r,debug:!0,timeout:qr,childOrigin:"*"}).promise,s=await z(n,{type:"ping-3ds-status"},oo);return console.log("🟢 CDE connection successful! Stopping polling... Result:",s),s};function Wt(r){throw new Error(`Unhandled case: ${r}`)}const Yt=10,Wr=(r=0)=>e=>`\x1B[${e+r}m`,Yr=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Hr=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,T={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(T.modifier);const Si=Object.keys(T.color),Ci=Object.keys(T.bgColor);[...Si,...Ci];function xi(){const r=new Map;for(const[e,t]of Object.entries(T)){for(const[n,s]of Object.entries(t))T[n]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[n]=T[n],r.set(s[0],s[1]);Object.defineProperty(T,e,{value:t,enumerable:!1})}return Object.defineProperty(T,"codes",{value:r,enumerable:!1}),T.color.close="\x1B[39m",T.bgColor.close="\x1B[49m",T.color.ansi=Wr(),T.color.ansi256=Yr(),T.color.ansi16m=Hr(),T.bgColor.ansi=Wr(Yt),T.bgColor.ansi256=Yr(Yt),T.bgColor.ansi16m=Hr(Yt),Object.defineProperties(T,{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=>T.rgbToAnsi256(...T.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)=>T.ansi256ToAnsi(T.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>T.ansi256ToAnsi(T.hexToAnsi256(e)),enumerable:!1}}),T}const te=xi(),kt=(()=>{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})(),Gr=kt!==0&&{level:kt,hasBasic:!0,has256:kt>=2,has16m:kt>=3},Ti={stdout:Gr,stderr:Gr};function Pi(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 Oi(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
|
+
`)}`,we=r=>{if(r instanceof Error)if(Bs(r.message)){const e=JSON.parse(r.message);return Fs.safeParse(e).success?qs(e):Vs.safeParse(e).success?Ys(e):(console.warn(`Encountered unknown stringified JSON object:
|
|
6
|
+
${r.message}`),r.message)}else return sr(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},Gs=(r,e,t)=>(...n)=>{try{return e(...n)}catch(s){t(`[form] Error running callback (${r}):`,s);return}},F=i.string().trim().min(1,{message:"Cannot be blank"}),O=i.string().trim().optional(),G=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 Dr=i.nativeEnum(f);var Lr=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(Lr||{});const Ur=i.nativeEnum(Lr),$r=i.union([Dr,Ur]);var Ve=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r))(Ve||{});const Ws=i.nativeEnum(Ve),Rt=i.object({provider:i.string(),processor_name:G(i.string()),metadata:G(i.record(i.string(),i.any()))}),Hs=i.object({id:i.string()});i.object({cardNumber:O,expiry:O,cvc:O}),i.object({backgroundColor:O,color:O,fontFamily:O,fontSize:O,fontWeight:O,margin:O,padding:O,letterSpacing:O,lineHeight:O,hideIcon:O});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"]),Ks=X.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Js=i.object({type:Ks}),Xs=X.extract(["BLUR","FOCUS","CHANGE"]),Qs=i.object({type:Xs,elementType:Ur,errors:i.array(i.string()).optional()}),eo=X.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),to=i.object({type:eo,message:F,headers:i.record(i.string(),i.string()).optional()}),ro=X.extract(["VALIDATION_ERROR"]),no=i.object({type:ro,elementType:$r,errors:i.array(i.string())}),so=i.object({type:i.literal(X.enum.LAYOUT),height:F}),oo=i.object({type:i.literal(X.enum.LOADED),sessionId:F,totalAmountAtoms:i.number(),currency:O,checkoutPaymentMethods:i.array(Rt)}),io=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()))}),ao=i.object({type:i.literal(X.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:i.string()}),ht=i.object({firstName:F,lastName:F,email:F,zipCode:F,country:F,promotionCode:O}),co=i.object({firstName:O,lastName:O,email:F,zipCode:F,country:F,promotionCode:O,address:O,city:O,state:O}),lo=X.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),uo=i.object({type:lo,sessionId:F,checkoutPaymentMethod:Rt,paymentFlowMetadata:i.any().optional(),doNotUseLegacyCCFlow:i.boolean().optional(),existingCCPMId:O}).extend(ht.shape),po=i.object({type:i.literal(X.enum.TOKENIZE_SUCCESS),isReadyForCheckout:i.boolean()}),fo=i.object({type:i.literal(X.enum.CHECKOUT_SUCCESS),invoiceUrls:i.array(i.string()),subscriptionIds:i.array(i.string()),customerId:i.string()}),ho=i.discriminatedUnion("type",[Js,Qs,to,no,so,oo,uo,po,fo,io,ao]),mo=i.object({payload:ho,nonce:F,formId:F,elementId:F});i.object({amountAtom:i.number(),currency:F}),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:G(i.string()),their_pm_id:G(i.string()),processor_specific_metadata:G(i.record(i.string(),i.any()))});const yo=i.object({elementType:i.string(),errors:i.array(i.string())});i.object({session_id:i.string()});const _o=i.object({success:i.literal(!1),error_type:i.literal("validation_error"),errors:i.array(yo)}),go=i.discriminatedUnion("success",[i.object({success:i.literal(!0)}),_o]);i.object({session_id:i.string(),checkout_payment_method:Rt,non_cde_form_fields:ht,do_not_use_legacy_cc_flow:i.boolean().optional(),existing_cc_pm_id:G(i.string())}),i.object({session_id:i.string(),checkout_payment_method:Rt,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 vo=i.object({status:i.enum(["success","failure","cancelled"]),href:i.string().optional().nullable()});i.object({href:i.string().optional().nullable()});const bo=i.object({type:i.string(),redirect_url:i.string(),initial_intent_id:i.string(),consent_id:i.string(),their_pm_id:i.string().optional()}),Fr=i.object({type:i.string(),redirect_url:G(i.string()),initial_intent_id:G(i.string()),consent_id:G(i.string()),their_pm_id:G(i.string()),payment_session:G(i.record(i.string(),i.any()))}),wo=i.discriminatedUnion("present",[i.object({present:i.literal(!0),href:i.string()}),i.object({present:i.literal(!1)})]),ko=i.object({payment_methods:i.array(Hs),required_user_actions:G(i.array(Fr))}),Eo=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const s=Dr.parse(t);Array.isArray(n)?e[s]=n:Array.isArray(n._errors)&&(e[s]=n._errors)}catch{return}}),e},So=i.object({stripe_pk:i.string(),client_secret:i.string(),stripe_pm_id:i.string()}),Co=i.object({type:i.string(),client_secret:i.string(),stripe_pk:i.string()}),Po={usd:"usd",brl:"brl"},Ot=async r=>{for(let t=0;t<10;t++)Zr()||await Ao(500);if(!Zr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},xo=async(r,e)=>{const t=await Ot(r);return{elements:t.elements(e),stripe:t}},To=async(r,e,t,n,s)=>{const o=await Ot(r),a=Po[t.toLowerCase().trim()];return o.paymentRequest({country:"US",currency:a,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},Ao=r=>new Promise(e=>{setTimeout(e,r)}),Zr=()=>"Stripe"in window,Io=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)}}),Ro=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},Oo=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."}`)},No=r=>JSON.stringify(r);for(var j=[],or=0;or<256;++or)j.push((or+256).toString(16).slice(1));function Mo(r,e=0){return(j[r[e+0]]+j[r[e+1]]+j[r[e+2]]+j[r[e+3]]+"-"+j[r[e+4]]+j[r[e+5]]+"-"+j[r[e+6]]+j[r[e+7]]+"-"+j[r[e+8]]+j[r[e+9]]+"-"+j[r[e+10]]+j[r[e+11]]+j[r[e+12]]+j[r[e+13]]+j[r[e+14]]+j[r[e+15]]).toLowerCase()}var Nt,jo=new Uint8Array(16);function Do(){if(!Nt&&(Nt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Nt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Nt(jo)}var Lo=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Vr={randomUUID:Lo};function Uo(r,e,t){if(Vr.randomUUID&&!e&&!r)return Vr.randomUUID();r=r||{};var n=r.random||(r.rng||Do)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Mo(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},{}),$o=r=>{try{return mo.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 ke;(function(r){r.Message="message"})(ke||(ke={}));const Fo=(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)},Vo={"http:":"80","https:":"443"},zo=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Bo=["file:","data:"],qo=r=>{if(r&&Bo.find(c=>r.startsWith(c)))return"null";const e=document.location,t=zo.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!==Vo[n]?`:${o}`:"";return`${n}//${s}${a}`},zr=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Yo=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Go=(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 y=d.data,{methodName:b,args:h,id:g}=y;t(`${n}: Received ${b}() call`);const E=P=>T=>{if(t(`${n}: Sending ${b}() reply`),u){t(`${n}: Unable to send ${b}() reply due to destroyed connection`);return}const z={penpal:oe.Reply,id:g,resolution:P,returnValue:T};P===Oe.Rejected&&T instanceof Error&&(z.returnValue=zr(T),z.returnValueIsError=!0);try{o.postMessage(z,a)}catch(A){if(A.name===ir.DataCloneError){const me={penpal:oe.Reply,id:g,resolution:Oe.Rejected,returnValue:zr(A),returnValueIsError:!0};o.postMessage(me,a)}throw A}};new Promise(P=>P(e[b].apply(e,h))).then(E(Oe.Fulfilled),E(Oe.Rejected))};return s.addEventListener(ke.Message,l),()=>{u=!0,s.removeEventListener(ke.Message,l)}};let Wo=0;const Ho=()=>++Wo,Br=".",qr=r=>r?r.split(Br):[],Ko=r=>r.join(Br),Jo=(r,e)=>{const t=qr(e||"");return t.push(r),Ko(t)},Xo=(r,e,t)=>{const n=qr(e);return n.reduce((s,o,a)=>(typeof s[o]>"u"&&(s[o]={}),a===n.length-1&&(s[o]=t),s[o]),r),r},Yr=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const s=r[n],o=Jo(n,e);typeof s=="object"&&Object.assign(t,Yr(s,o)),typeof s=="function"&&(t[o]=s)}),t},Qo=r=>{const e={};for(const t in r)Xo(e,t,r[t]);return e},ei=(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 y=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 z=Ho(),A=Pe=>{if(Pe.source!==c||Pe.data.penpal!==oe.Reply||Pe.data.id!==z)return;if(l!=="*"&&Pe.origin!==l){s(`${o} received message from origin ${Pe.origin} which did not match expected origin ${l}`);return}const xe=Pe.data;s(`${o}: Received ${h}() reply`),a.removeEventListener(ke.Message,A);let Ne=xe.returnValue;xe.returnValueIsError&&(Ne=Yo(Ne)),(xe.resolution===Oe.Fulfilled?P:T)(Ne)};a.addEventListener(ke.Message,A);const me={penpal:oe.Call,id:z,methodName:h,args:g};c.postMessage(me,u)})},b=t.reduce((h,g)=>(h[g]=y(g),h),{});return Object.assign(r,Qo(b)),()=>{d=!0}},ti=(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 y={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=Go(y,r,s),a(c),u&&u.forEach(h=>{delete l[h]}),u=d.data.methodNames;const b=ei(l,y,u,o,s);return a(b),l}},ri=(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)},ni=6e4,si=(r,e)=>{const{destroy:t,onDestroy:n}=e,s=setInterval(()=>{r.isConnected||(clearInterval(s),t())},ni);n(()=>{clearInterval(s)})},oi=(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)}},ii=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=mt.NoIframeSrc,e}},Gr=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:s,debug:o=!1}=r;const a=Zo(o),c=Fo("Parent",a),{onDestroy:u,destroy:l}=c;n||(ii(e),n=qo(e.src));const d=n==="null"?"*":n,y=Yr(t),b=ri(a,y,n,d),h=ti(y,n,d,c,a);return{promise:new Promise((E,P)=>{const T=oi(s,l),z=A=>{if(!(A.source!==e.contentWindow||!A.data)){if(A.data.penpal===oe.Syn){b(A);return}if(A.data.penpal===oe.Ack){const me=h(A);me&&(T(),E(me));return}}};window.addEventListener(ke.Message,z),a("Parent: Awaiting handshake"),si(e,c),u(A=>{window.removeEventListener(ke.Message,z),A&&P(A)})}),destroy(){l()}}},ai=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}},ci=(r,e)=>!!r&&e,N=r=>i.nullable(r.optional());i.string().trim().min(1,{message:"Cannot be blank"});const li=i.object({cde_response_type:i.literal("error"),message:i.string(),headers:i.record(i.string(),i.string()).optional()});i.enum(["usd","brl"]);const Wr=i.object({name:i.string(),amount_atom_off:N(i.number()),percent_off:N(i.number()),currency:N(i.string()),duration:i.string(),duration_in_months:N(i.number())}),Hr=i.object({amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),currency:i.string(),description:N(i.string()),price_id:i.string(),billing_interval:N(i.string()),billing_interval_count:N(i.number().int()),quantity:i.number().int()}),ui=i.record(i.string(),i.any()),di=i.object({name:i.string(),settings:N(ui)}),yt=i.object({provider:i.string(),processor_name:N(i.string()),metadata:N(i.record(i.string(),i.any()))}),pi=i.object({quantity:i.number()}),fi=i.object({id:N(i.string()),billing_interval:N(i.string()),billing_interval_count:N(i.number().int()),subscription_items:i.array(pi),trial_start:N(i.string()),trial_end:N(i.string())}),Kr=i.object({amount_atom:i.number()}),hi=i.object({amount_atom:i.number(),amount_atom_considering_discount_applied:i.number(),currency:i.string(),discount_amount_atoms:i.array(Kr),subscription_item_id:i.string()}),mi=i.object({coupon:Wr}),yi=i.object({currency:i.string(),discounts:i.array(mi),hosted_invoice_url:N(i.string()),lines:i.array(hi),remaining_amount_atom:i.number(),tax_amount_atom:i.number(),total_amount_atom:i.number(),total_discount_amount_atoms:i.array(Kr)}),Jr=i.object({created:i.array(fi),invoices:i.array(yi)}),Xr=i.object({preview:Jr,preview_post_trial:N(Jr),coupons:i.array(Wr)}),Qr=i.object({status:i.literal("open"),token:i.string(),email:N(i.string()),line_items:i.array(Hr),amount_subtotal_atom:i.number().int(),amount_total_atom:i.number().int(),brand:di,subs_preview:N(Xr),methods_available:i.array(yt)}),en=i.discriminatedUnion("mode",[i.object({mode:i.literal("setup"),currency:i.nullable(i.undefined())}).extend(Qr.shape),i.object({mode:i.enum(["payment","subscription"]),currency:i.string()}).extend(Qr.shape)]),_i=i.object({status:i.literal("complete")}),gi=i.object({status:i.literal("expired")});i.union([en,_i,gi]),i.object({logo:i.string(),icon:i.string(),primary_color:i.string(),secondary_color:i.string()});const tn=i.object({invoice_urls:i.array(i.string()),subscription_ids:i.array(i.string()),customer_id: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(Hr),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:N(i.string())});const rn=i.object({payment_method_id:i.string()});i.object({id:i.string(),return_url:i.string()});const vi=i.object({type:i.string(),loc:i.array(i.string()),msg:i.string(),url:i.string()});i.array(vi);const bi=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()}),wi=i.object({processor_specific_metadata:N(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()}).extend(bi.shape).extend(wi.shape);const nn=i.object({required_user_actions:i.array(i.record(i.string(),i.any()))});i.object({fields:co,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 ki=i.object({required_user_actions:i.array(i.record(i.string(),i.any())),cc_pm_id:i.string()});i.record(i.any());const Ei=r=>r.reduce((e,t)=>e+t,0);function Si(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function Ci(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var Pi=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)}}(),xi=function(r){Pi(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}),Si(o,s.prototype),Ci(o),o}return e}(Error);class sn extends xi{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const q=async(r,e,t)=>{const n=await r.send(e);if(Ai(n))throw new sn(n);if(!Ti(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},Ti=(r,e)=>e.safeParse(r).success,Ai=r=>li.safeParse(r).success,Ii=async(r,e)=>await q(r,{type:"get_checkout_preview",payload:e},Xr),de=async r=>await q(r,{type:"get_prefill",payload:{}},en),Mt=async(r,e)=>await q(r,{type:"v2_start_payment_flow",payload:e},nn),Ri=async(r,e)=>await q(r,{type:"start_payment_flow_for_cc",payload:e},ki),Oi=async(r,e)=>await q(r,{type:"start_payment_flow_for_pr",payload:e},nn),Ee=async(r,e)=>await q(r,{type:"confirm_payment_flow",payload:e},ko),Ni=async(r,e)=>await q(r,{type:"finalize_setup_payment_method",payload:e},rn),Mi=async(r,e)=>await q(r,{type:"check_if_popup_window_verified",payload:e},wo),ji=async(r,e,t)=>{const n=await Ii(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=Ei(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:o,amountAtom:a}},jt=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const s=await ji(r,e,n);return{amountAtom:s.amountAtom,currency:s.currency}}},Di=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>q(n,{type:"tokenize_card",payload:e},go)))},on=async(r,e)=>{try{return await q(r,{type:"checkout_card_elements",payload:e},tn)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},Li=async(r,e)=>await q(r,{type:"setup_payment_method",payload:e},rn),_t=async(r,e)=>await q(r,{type:"checkout",payload:e},tn),an=1e3,Ui=async(r,e)=>{console.log(e);const n=await Gr({iframe:r,debug:!0,timeout:an,childOrigin:"*"}).promise,s=await q(n,{type:"ping-3ds-status"},vo);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`,I={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(I.modifier);const $i=Object.keys(I.color),Fi=Object.keys(I.bgColor);[...$i,...Fi];function Zi(){const r=new Map;for(const[e,t]of Object.entries(I)){for(const[n,s]of Object.entries(t))I[n]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},t[n]=I[n],r.set(s[0],s[1]);Object.defineProperty(I,e,{value:t,enumerable:!1})}return Object.defineProperty(I,"codes",{value:r,enumerable:!1}),I.color.close="\x1B[39m",I.bgColor.close="\x1B[49m",I.color.ansi=cn(),I.color.ansi256=ln(),I.color.ansi16m=un(),I.bgColor.ansi=cn(cr),I.bgColor.ansi256=ln(cr),I.bgColor.ansi16m=un(cr),Object.defineProperties(I,{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=>I.rgbToAnsi256(...I.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)=>I.ansi256ToAnsi(I.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>I.ansi256ToAnsi(I.hexToAnsi256(e)),enumerable:!1}}),I}const ie=Zi(),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},Vi={stdout:dn,stderr:dn};function zi(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 Bi(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:
|
|
10
|
-
`);return o!==-1&&(e=
|
|
9
|
+
`,s)}while(n!==-1);return o+=r.slice(s),o}const{stdout:pn,stderr:fn}=Vi,lr=Symbol("GENERATOR"),Be=Symbol("STYLER"),gt=Symbol("IS_EMPTY"),hn=["ansi","ansi","ansi256","ansi16m"],qe=Object.create(null),qi=(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},Yi=r=>{const e=(...t)=>t.join(" ");return qi(e,r),Object.setPrototypeOf(e,vt.prototype),e};function vt(r){return Yi(r)}Object.setPrototypeOf(vt.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[gt]);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),Gi=["rgb","hex","ansi256"];for(const r of Gi){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[gt])}}};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[gt])}}}}const Wi=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)=>Hi(n,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(n,Wi),n[lr]=r,n[Be]=e,n[gt]=t,n},Hi=(r,e)=>{if(r.level<=0||!e)return r[gt]?"":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=zi(e,t.close,t.open),t=t.parent;const o=e.indexOf(`
|
|
10
|
+
`);return o!==-1&&(e=Bi(e,s,n,o)),n+e+s};Object.defineProperties(vt.prototype,qe);const Ut=vt();vt({level:fn?fn.level:0});const Ye=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(we(s))}},$t=r=>async e=>{try{return await r(e)}catch(t){const{err__:n}=D("init-error-catcher");return n(t),{isAvailable:!1,reason:we(t)}}},D=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__:el,err__:Ki}=D("common"),Ft=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}},Ge=(r,e)=>{const t=r.find(n=>e.safeParse(n).success);if(!t)throw Ki("No CPMs found for model. All models:",r),new Error("No CPMs found for model");return e.parse(t)},Ji=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}),Xi=async(r,e,t,n,s)=>{const{log__:o}=D(r),a=await de(e),c=Ft(s);if(a.mode==="setup")return o("Setting up payment method..."),{mode:"setup",result:await Ni(e,{secure_token:a.token,pm_id:c.payment_method_id})};{o("Doing checkout...");const u={secure_token:a.token,payment_input:{provider_type:t.provider},customer_email:n[f.EMAIL],customer_zip_code:n[f.ZIP_CODE],customer_country:n[f.COUNTRY],promotion_code:n[f.PROMOTION_CODE],line_items:a.line_items,total_amount_atom:a.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t,use_confirmed_pm_id:c.payment_method_id};return{mode:"checkout",result:await _t(e,u)}}},{log__:Qi,err__:mn}=D("common-cc"),We=(r,e)=>{const t=ht.safeParse(r);if(!t.success){const n=t.error.format(),s=Eo(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},ea=(r,e)=>{for(const t of r)if(t.success===!1)throw t.errors.forEach(n=>{const s=$r.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)}}),Qi(`Error tokenizing card: got validation errors: ${JSON.stringify(t.errors)}`),new Error("Got validation errors while tokenizing card")},yn="ojs-stripe-link-btn",{log__:L,err__:ta}=D("stripe-link"),ra=i.object({provider:i.literal("stripe_link"),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),na=i.array(i.object({our_existing_pm_id:i.string()})).length(1),sa=$t(async({context:r,formCallbacks:e})=>{const t=r.customInitParams.stripeLink;L("Checking if there are any CPMs for Stripe Link...");const n=Ge(r.checkoutPaymentMethods,ra);L("Starting stripe link flow...");const s=r.anyCdeConnection,o=await de(s),a=o.mode==="setup";L("Creating stripe elements...");const c=await jt(s,o.token,a,void 0),{elements:u,stripe:l}=await xo(n.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});L("Creating express checkout...");const d=u.create("expressCheckout",{buttonHeight:t==null?void 0:t.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),y=()=>{d.mount(`#${yn}`)},b=()=>{d.unmount()};return t!=null&&t.doNotMountOnInit?L("NOT mounting stripe link button (doNotMountOnInit is true)"):(L("Mounting stripe link button..."),y()),d.on("click",async h=>{if(L("Stripe Link button clicked"),t!=null&&t.overrideLinkSubmit&&!await t.overrideLinkSubmit()){L("Stripe Link submit aborted by overrideLinkSubmit");return}h.resolve()}),d.on("confirm",async h=>{L("Stripe Link window confirmed",h);const g=await l.createPaymentMethod({elements:u,params:{billing_details:h.billingDetails}});g.error?(ta("error",g.error),e.get.onCheckoutError(g.error.message??"Stripe Link unknown error")):(L("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:y,dismountButton:b,waitForButtonToMount:async()=>await aa(yn)}}}),oa=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{L("Running Stripe Link flow...");const o=r.anyCdeConnection;L("Merging PM fields with form fields...");const a=ia(t,s.stripePM),c=We(a,n.get.onValidationError);L("Starting payment flow...");const u=await Mt(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]}});L("Start payment flow response",u);const d=na.parse(u.required_user_actions)[0].our_existing_pm_id,y=await de(o);if(y.mode==="setup"){L("Doing payment setup...");const b=await Ee(o,{secure_token:y.token,existing_cc_pm_id:d});return{mode:"setup",result:Ft(b)}}else{L("Doing checkout...");const b={secure_token:y.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:y.line_items,total_amount_atom:y.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await _t(o,b)}}}),ia=(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",L("Final form inputs:",t),t},aa=r=>new Promise(e=>{const t=()=>{const n=document.getElementById(r);n?e(n):requestAnimationFrame(t)};t()}),ca="@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}",la=r=>{const e=document.createElement("template");e.innerHTML=`
|
|
11
11
|
<style>
|
|
12
|
-
${
|
|
12
|
+
${ca}
|
|
13
13
|
</style>
|
|
14
14
|
<div class="overlay">
|
|
15
15
|
<div class="container">
|
|
@@ -17,8 +17,8 @@ ${r.message}`),r.message)}else return Vt(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
|
|
21
|
-
Error: ${
|
|
22
|
-
Details: got ${r.required_user_actions.length} required user actions`);return lo.parse(r.required_user_actions[0])},{log__:oe}=F("pockyt-paypal"),_a=i.object({processor_name:i.literal("pockyt"),provider:i.literal("paypal")}),ga=i.array(i.object({paypal_iframe_url:i.string(),verify_token:i.string()})).length(1),va=Ct(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n})=>{oe("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,o=await Ee(s);oe("Verifying CPM...");const a=_a.parse(e);oe("├ Validating non-CDE form fields");const c=Tt(t,n.get.onValidationError),l=Li(c);oe("Starting payment flow...");const u=await Vr(s,{payment_provider:a.provider,checkout_payment_method:a,...l});oe("Start payment flow response",u);const d=ga.parse(u.required_user_actions)[0];oe("Opening paypal iframe...");const y=await Qi("PayPal",s,d.verify_token,d.paypal_iframe_url);oe("Paypal flow result",y);const w=on(y.href);oe(`Confirming payment flow using vault ID ${w}`);const m=await wt(s,{secure_token:o.token,their_pm_id:w});return oe("Confirm payment flow result",m),await Di("pockyt-paypal",s,a,c,m)}),Jt=(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]},Se={commonCC:{init:async()=>{},run:oa},stripePR:{init:fa,run:ha},stripeLink:{init:zi,run:Bi},pockytPaypal:{run:va}};var Xt=function(r,e){return Xt=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])},Xt(r,e)};function me(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Xt(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function ba(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{u(n.next(d))}catch(y){a(y)}}function l(d){try{u(n.throw(d))}catch(y){a(y)}}function u(d){d.done?o(d.value):s(d.value).then(c,l)}u((n=n.apply(r,e||[])).next())})}function un(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(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(t=0)),t;)try{if(n=1,s&&(o=u[0]&2?s.return:u[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,u[1])).done)return o;switch(s=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,s=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){t.label=u[1];break}if(u[0]===6&&t.label<o[1]){t.label=o[1],o=u;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(u);break}o[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(d){u=[6,d],s=0}finally{n=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Ne(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 Pt(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 Ot(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 Me(r){return this instanceof Me?(this.v=r,this):new Me(r)}function wa(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,y)}}function c(m,g){n[m]&&(s[m]=function(C){return new Promise(function(R,q){o.push([m,C,R,q])>1||l(m,C)})},g&&(s[m]=g(s[m])))}function l(m,g){try{u(n[m](g))}catch(C){w(o[0][3],C)}}function u(m){m.value instanceof Me?Promise.resolve(m.value.v).then(d,y):w(o[0][2],m)}function d(m){l("next",m)}function y(m){l("throw",m)}function w(m,g){m(g),o.shift(),o.length&&l(o[0][0],o[0][1])}}function ka(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 Ne=="function"?Ne(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,l){a=r[o](a),s(c,l,a.done,a.value)})}}function s(o,a,c,l){Promise.resolve(l).then(function(u){o({value:u,done:c})},a)}}typeof SuppressedError=="function"&&SuppressedError;function L(r){return typeof r=="function"}function Rt(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 Qt=Rt(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 ua(r,e,t){const n=async()=>{try{const o=await Ui(r,t);o&&(clearInterval(s),e(o))}catch{}};n();const s=setInterval(n,an);return s}function da({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 Zt(r){const{url:e,baseUrl:t}=r,n=la(e);return new Promise(s=>{const o=u=>{setTimeout(()=>{n.host.remove()},1e3),s(u),c==null||c()},a=ua(n.iframe,o,new URL(t).origin),c=da({elements:n,pollingInterval:a,resolve:s})})}const pa=async r=>{const e=await Zt(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}},fa=(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},ha=async(r,e,t,n)=>{const{err__:s}=D("popup-verify");return new Promise((o,a)=>{const c=fa(r,n),u=setInterval(async()=>{try{const l=await Mi(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(we(l)),clearInterval(u),a(we(l))}},1e3)})},{log__:ma,err__:_n}=D("pockyt-cc"),ya=i.object({"op-pockyt-3ds-url":i.string(),"op-pockyt-txn-no":i.string(),"op-pockyt-ref-no":i.string()}),_a=r=>{const e=ya.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 _n(n),new Error(t)}return e.data},gn=r=>{try{const e=new URL(r??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return ma(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const t="Error verifying 3DS verification result.";throw _n(t,`Resulting URL: ${r}.
|
|
21
|
+
Error: ${we(e)}`),new Error(t)}},ga=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!==void 0,va=async(r,e)=>{const t=_a(e),n=await pa({url:t["op-pockyt-3ds-url"],baseUrl:r});return{existing_cc:{vault_id:gn(n.href??""),transaction_no:t["op-pockyt-txn-no"],reference_no:t["op-pockyt-ref-no"]}}},{log__:M,err__:vn}=D("common-cc"),{log__:bn}=D("stripe-cc");i.array(i.object({our_existing_pm_id:i.string()})).length(1);const ba=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var l;M("├ Running common CC flow...",{checkoutPaymentMethod:e});const o=r.anyCdeConnection,a=await de(o);M(`├ 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{M(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await Di(s.currentCdeConnections,{session_id:r.elementsSessionId});if(ea(d,n.get.onValidationError),a.mode==="setup"){M(`├ Setting up payment method in CDE [Token: ${a.token}]`);const y=await Li(o,u);return M(`╰ Setup completed successfully [PM ID: ${y.payment_method_id}]`),{mode:"setup",result:y}}else{M(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const y=await on(o,u);return M("╰ Checkout completed successfully."),{mode:"checkout",result:y}}}catch(d){if(d instanceof sn&&d.originalErrorMessage.includes("3DS_REQUIRED")){M("├ Card requires 3DS, starting non-legacy payment flow"),M("Received 3DS error response headers:",d.response.headers);const y=ga(d.response.headers);if(y){M("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const E=await va(r.baseUrl,d.response.headers);u.extra_metadata.pockyt=E}const b=await Ri(o,u);M("├ Payment flow result:",b);const h=((l=d.response.headers)==null?void 0:l["op-should-use-new-flow"])!=="true";y?M("├ Pockyt 3DS is successful, other 3DS flows will be skipped."):h?(M("├ Using stripe 3DS flow"),await Sa(b)):(M("├ Using common 3DS flow"),await Ea(b,r.baseUrl));const g=b.cc_pm_id;if(a.mode==="setup"){M(`├ Confirming payment flow [cc_pm_id: ${g}]`);const E=await Ee(o,{secure_token:a.token,existing_cc_pm_id:g});M("├ Confirm payment flow result received Result:",E);const P=Ft(E);return M(`╰ Setup completed successfully [PM ID: ${P.payment_method_id}]`),{mode:"setup",result:P}}else{M(`├ Checking out after 3DS flow [Flow: ${h?"legacy":"new"}]`);const E=await on(o,{...u,existing_cc_pm_id:g,do_not_use_legacy_cc_flow:h});return M("╰ Checkout completed successfully."),{mode:"checkout",result:E}}}throw vn("╰ Error checking out card info in CDE"),vn(d),d}}),wa=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return So.parse(e)},ka=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 bo.parse(e)},Ea=async(r,e)=>{const t=ka(r);M(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Zt({url:t.redirect_url,baseUrl:e});if(M(`╰ 3DS verification completed [Status: ${n}]`),n===Q.CANCELLED)throw new Error("3DS verification cancelled");if(n===Q.FAILURE)throw new Error("3DS verification failed")},Sa=async r=>{const e=wa(r);bn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Oo(e),bn("╰ Stripe 3DS flow completed successfully")},{log__:V,err__:Ca}=D("stripe-pr"),Pa=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()})}),xa=$t(async({context:r})=>{V("Checking if there are any CPMs for Stripe PR...");const e=Ge(r.checkoutPaymentMethods,Pa);V("Initializing Stripe PR flow...");const t=r.anyCdeConnection,n=await de(t),s=n.mode==="setup";V("Getting initial preview amount");const o=await jt(t,n.token,s,void 0),a=await To(e.metadata.stripe_pk,o.amountAtom,o.currency,s);V("Checking if can make payment");const c=await a.canMakePayment();return c===null?(Ca("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(V("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:a,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),Ta=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s,initResult:o})=>{if(V("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;V("Overriding PR amount with",g),Ia(c,g.amount,g.pending,g.stripeApplePay)}V("Showing PR dialog..."),c.show();const u=await Io(c);V("Stripe PM added event:",u),V("Merging PM fields with form fields...");const l=Aa(t,u),d=We(l,n.get.onValidationError);V("PR dialog finished. Starting payment flow...",d);const y=await Oi(a,{fields:d,checkoutPaymentMethod:e}),b=Ra(y);V("Confirming PR with Stripe..."),await Ro(b,u);const h=await de(a);if(h.mode==="setup"){V("Confirming payment flow for setup...");const g=await Ee(a,{secure_token:h.token});return{mode:"setup",result:Ft(g)}}else{V("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 _t(a,g)}}}),Aa=(r,e)=>{var u,l,d,y;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=(y=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:y.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",V("Final form inputs:",t),t},Ia=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Ra=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
|
|
22
|
+
Details: got ${r.required_user_actions.length} required user actions`);return Co.parse(r.required_user_actions[0])},{log__:pe}=D("pockyt-paypal"),Oa=i.object({processor_name:i.literal("pockyt"),provider:i.literal("paypal")}),Na=i.array(i.object({paypal_iframe_url:i.string(),verify_token:i.string()})).length(1),Ma=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n})=>{pe("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,o=await de(s);pe("Verifying CPM...");const a=Oa.parse(e);pe("├ Validating non-CDE form fields");const c=We(t,n.get.onValidationError),u=Ji(c);pe("Starting payment flow...");const l=await Mt(s,{payment_provider:a.provider,checkout_payment_method:a,...u});pe("Start payment flow response",l);const d=Na.parse(l.required_user_actions)[0];pe("Opening paypal iframe...");const y=await ha("PayPal",s,d.verify_token,d.paypal_iframe_url);pe("Paypal flow result",y);const b=gn(y.href);pe(`Confirming payment flow using vault ID ${b}`);const h=await Ee(s,{secure_token:o.token,their_pm_id:b});return pe("Confirm payment flow result",h),await Xi("pockyt-paypal",s,a,c,h)}),pr=({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)}}},ja=()=>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)}),Da=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?Fr.parse(e):null},La=(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__:bt}=D("gpay");let fr=null;const wn=r=>{const e=r===je?"PRODUCTION":"TEST";return fr===null&&(fr=new window.google.payments.api.PaymentsClient({environment:e,merchantInfo:pr({gateway:"airwallex",gatewayMerchantId:"",merchantName:""}).merchantInfo})),fr},kn=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()})}),Ua=$t(async({context:r,formCallbacks:e})=>{var o,a;const t=Ge(r.checkoutPaymentMethods,kn);if(!t)return{isAvailable:!1};W("Google Pay CPM",t);const n=t.metadata;if(!n.processor_account_id)return bt("No gateway merchant ID found in processor account"),{isAvailable:!1};if(W("Loading Google Pay SDK..."),await ja(),!((a=(o=window.google)==null?void 0:o.payments)!=null&&a.api))return bt("Google Pay SDK not loaded properly"),{isAvailable:!1};W("Google Pay SDK loaded",window.google.payments);try{const{result:c}=await wn(r.baseUrl).isReadyToPay(pr({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 bt("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){bt("Google Pay payment error",c),e.get.onCheckoutError((c==null?void 0:c.message)??"Unknown error")}}}}),$a=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n})=>{var d,y,b,h,g,E,P;W("Starting Google Pay flow...");const s=Ge(r.checkoutPaymentMethods,kn),o=wn(r.baseUrl),a=r.anyCdeConnection,c=await de(a),u=s.metadata;if(!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const l=pr({gateway:"airwallex",gatewayMerchantId:u.processor_account_id,merchantName:u.processor_account_name,merchantId:"",initialPreview:await jt(a,c.token,c.mode==="setup",void 0)});try{const T=await o.loadPaymentData(l);W("Google Pay Payment data",T);const z=La(t,T),A=We(z,n.get.onValidationError),me=(y=(d=T.paymentMethodData)==null?void 0:d.tokenizationData)==null?void 0:y.token;if(!me)throw new Error("No payment token received from Google Pay");const Pe=await Mt(a,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:A[f.EMAIL],new_customer_first_name:A[f.FIRST_NAME],new_customer_last_name:A[f.LAST_NAME],new_customer_address:{postal_code:A[f.ZIP_CODE],country_code:A[f.COUNTRY]}}),xe=Da(Pe);W("Start flow next actions",xe);const Ne=await Ee(a,{secure_token:c.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:xe==null?void 0:xe.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 kt=(h=(b=Ne.payment_methods)==null?void 0:b[0])==null?void 0:h.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 Zt({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&&!kt){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),kt=(P=(E=ce.payment_methods)==null?void 0:E[0])==null?void 0:P.id}if(!kt)throw new Error("No PM ID found");if(c.mode==="setup")return{mode:"setup",result:{payment_method_id:kt}};{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:kt,line_items:c.line_items,total_amount_atom:c.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e,customer_email:A[f.EMAIL],customer_zip_code:A[f.ZIP_CODE],customer_country:A[f.COUNTRY],promotion_code:A[f.PROMOTION_CODE],customer_first_name:A[f.FIRST_NAME],customer_last_name:A[f.LAST_NAME]};return{mode:"checkout",result:await _t(a,ce)}}}catch(T){throw bt("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Fa=()=>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)}),Za=(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__:Vt}=D("applepay-session");async function Va(r,e){try{const n=(await Mt(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.payment_session),o}catch(t){throw e.session.abort(),t}}async function za(r,e){var s,o;if(!r.redirect_url)throw new Error("No redirect URL found");Vt("3DS Required, starting verification...",r);const{status:t}=await Zt({url:r.redirect_url,baseUrl:e.baseUrl});if(Vt(`╰ 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 Vt("[2nd] Confirm payment flow response",n),(o=(s=n.payment_methods)==null?void 0:s[0])==null?void 0:o.id}async function Ba(r,e,t){return{mode:"checkout",result:await _t(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=Za(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:a.token}}}});Vt("[1st] Confirm payment flow response",l);let d=(s=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:s.id;const y=(o=l.required_user_actions)==null?void 0:o.find(h=>h.type==="airwallex_payment_consent");if(y!=null&&y.redirect_url&&y.consent_id&&y.their_pm_id&&(d=await za(y,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 Ba(d,u,e)}catch(a){const c={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(c),a}}const{log__:Y,err__:hr}=D("applepay"),En=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()})}),Ya=$t(async({context:r,formCallbacks:e})=>{const t=Ge(r.checkoutPaymentMethods,En);if(!t)return{isAvailable:!1};Y("Loading Apple Pay SDK...");try{await Fa(),Y("Apple Pay SDK loaded successfully")}catch(d){return hr("Failed to load Apple Pay SDK",d),{isAvailable:!1}}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return Y("Apple Pay is not available on this device/browser"),{isAvailable:!1};if(Y("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Y("No active cards available for Apple Pay"),{isAvailable:!1};const s=r.anyCdeConnection,o=await de(s),a=o.mode==="setup",c=await jt(s,o.token,a,void 0),u=t.metadata;if(Y("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){hr("Apple Pay payment error",d),e.get.onCheckoutError((d==null?void 0:d.message)??"Unknown error")}}}}),Ga=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:s})=>{var h;const o=Ge(r.checkoutPaymentMethods,En),{initialPreview:a,isSetupMode:c,prefill:u}=n,l={countryCode:"US",currencyCode:((h=a.currency)==null?void 0:h.toUpperCase())??"USD",supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:{label:c?"Setup Payment":"Payment Total",amount:c?"0.00":(a.amountAtom/100).toFixed(2),type:"final"}};Y("Payment Request",l);const d=new ApplePaySession(3,l);Y("ApplePaySession",d);const y={session:d,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:o.metadata,prefill:u,isSetupMode:c,baseUrl:r.baseUrl,formCallbacks:s};let b;return new Promise((g,E)=>{d.oncancel=()=>{Y("Payment cancelled by user"),d.abort(),E(new Error("Payment cancelled by user"))},d.onvalidatemerchant=async P=>{try{b=await Va(P,y)}catch(T){E(T)}},d.onshippingmethodselected=P=>{Y("Shipping method selected",P.shippingMethod)},d.onshippingmethodselected=P=>{Y("Shipping method selected",P.shippingMethod);const T={};d.completeShippingMethodSelection(T)},d.onshippingcontactselected=P=>{Y("Shipping contact selected",P.shippingContact);const T={};d.completeShippingContactSelection(T)},d.onpaymentmethodselected=P=>{Y("Payment method selected",P.paymentMethod);const T={};d.completePaymentMethodSelection(T)},d.onpaymentauthorized=async P=>{try{const T=await qa(P,y,b);g(T)}catch(T){E(T)}},d.begin()}).catch(g=>{throw d.abort(),hr("Apple Pay payment error",g),g})}),mr=(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:ba},stripePR:{init:xa,run:Ta},stripeLink:{init:sa,run:oa},pockytPaypal:{run:Ma},airwallexGooglePay:{init:Ua,run:$a},airwallexApplePay:{init:Ya,run:Ga}};var yr=function(r,e){return yr=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])},yr(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");yr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Wa(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(y){a(y)}}function u(d){try{l(n.throw(d))}catch(y){a(y)}}function l(d){d.done?o(d.value):s(d.value).then(c,u)}l((n=n.apply(r,e||[])).next())})}function Sn(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 zt(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 Bt(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 Ha(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,y)}}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){b(o[0][3],E)}}function l(h){h.value instanceof Ke?Promise.resolve(h.value.v).then(d,y):b(o[0][2],h)}function d(h){u("next",h)}function y(h){u("throw",h)}function b(h,g){h(g),o.shift(),o.length&&u(o[0][0],o[0][1])}}function Ka(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 U(r){return typeof r=="function"}function qt(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 _r=qt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
23
23
|
`+t.map(function(n,s){return s+1+") "+n.toString()}).join(`
|
|
24
|
-
`):"",this.name="UnsubscriptionError",this.errors=t}});function It(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var ct=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=Ne(a),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(C){e={error:C}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else a.remove(this);var d=this.initialTeardown;if(L(d))try{d()}catch(C){o=C instanceof Qt?C.errors:[C]}var y=this._finalizers;if(y){this._finalizers=null;try{for(var w=Ne(y),m=w.next();!m.done;m=w.next()){var g=m.value;try{fn(g)}catch(C){o=o??[],C instanceof Qt?o=Ot(Ot([],Pt(o)),Pt(C.errors)):o.push(C)}}}catch(C){n={error:C}}finally{try{m&&!m.done&&(s=w.return)&&s.call(w)}finally{if(n)throw n.error}}}if(o)throw new Qt(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)fn(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)&&It(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&It(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),ln=ct.EMPTY;function dn(r){return r instanceof ct||r&&"closed"in r&&L(r.remove)&&L(r.add)&&L(r.unsubscribe)}function fn(r){L(r)?r():r.unsubscribe()}var hn={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},pn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,Ot([r,e],Pt(t)))},clearTimeout:function(r){var e=pn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function mn(r){pn.setTimeout(function(){throw r})}function yn(){}function At(r){r()}var er=function(r){me(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,dn(t)&&t.add(n)):n.destination=xa,n}return e.create=function(t,n,s){return new rr(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}(ct),Ea=Function.prototype.bind;function tr(r,e){return Ea.call(r,e)}var Sa=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){jt(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){jt(n)}else jt(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){jt(t)}},r}(),rr=function(r){me(e,r);function e(t,n,s){var o=r.call(this)||this,a;if(L(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&hn.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&tr(t.next,c),error:t.error&&tr(t.error,c),complete:t.complete&&tr(t.complete,c)}):a=t}return o.destination=new Sa(a),o}return e}(er);function jt(r){mn(r)}function Ca(r){throw r}var xa={closed:!0,next:yn,error:Ca,complete:yn},nr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Ta(r){return r}function Pa(r){return r.length===0?Ta:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var ie=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=Ra(e)?e:new rr(e,t,n);return At(function(){var a=s,c=a.operator,l=a.source;o.add(c?c.call(o,l):l?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=_n(t),new t(function(s,o){var a=new rr({next:function(c){try{e(c)}catch(l){o(l),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[nr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=_n(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 _n(r){var e;return(e=r??hn.Promise)!==null&&e!==void 0?e:Promise}function Oa(r){return r&&L(r.next)&&L(r.error)&&L(r.complete)}function Ra(r){return r&&r instanceof er||Oa(r)&&dn(r)}function Ia(r){return L(r==null?void 0:r.lift)}function Aa(r){return function(e){if(Ia(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 ja(r,e,t,n,s){return new Na(r,e,t,n,s)}var Na=function(r){me(e,r);function e(t,n,s,o,a,c){var l=r.call(this,t)||this;return l.onFinalize=a,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){t.error(d)}}:r.prototype._next,l._error=o?function(u){try{o(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,l._complete=s?function(){try{s()}catch(u){t.error(u)}finally{this.unsubscribe()}}:r.prototype._complete,l}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}(er),Ma=Rt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),gn=function(r){me(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 vn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Ma},e.prototype.next=function(t){var n=this;At(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=Ne(n.currentObservers),c=a.next();!c.done;c=a.next()){var l=c.value;l.next(t)}}catch(u){s={error:u}}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;At(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;At(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?ln:(this.currentObservers=null,c.push(t),new ct(function(){n.currentObservers=null,It(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 ie;return t.source=this,t},e.create=function(t,n){return new vn(t,n)},e}(ie),vn=function(r){me(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:ln},e}(gn),La={now:function(){return Date.now()},delegate:void 0},Da=function(r){me(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(ct),bn={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,Ot([r,e],Pt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},$a=function(r){me(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),bn.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&&bn.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,It(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(Da),wn=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=La.now,r}(),Za=function(r){me(e,r);function e(t,n){n===void 0&&(n=wn.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}(wn),Ua=new Za($a),Fa=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Va(r){return L(r==null?void 0:r.then)}function za(r){return L(r[nr])}function Ba(r){return Symbol.asyncIterator&&L(r==null?void 0:r[Symbol.asyncIterator])}function qa(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 Wa(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ya=Wa();function Ha(r){return L(r==null?void 0:r[Ya])}function Ga(r){return wa(this,arguments,function(){var t,n,s,o;return un(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,Me(t.read())];case 3:return n=a.sent(),s=n.value,o=n.done,o?[4,Me(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Me(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 Ka(r){return L(r==null?void 0:r.getReader)}function Ja(r){if(r instanceof ie)return r;if(r!=null){if(za(r))return Xa(r);if(Fa(r))return Qa(r);if(Va(r))return ec(r);if(Ba(r))return kn(r);if(Ha(r))return tc(r);if(Ka(r))return rc(r)}throw qa(r)}function Xa(r){return new ie(function(e){var t=r[nr]();if(L(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Qa(r){return new ie(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function ec(r){return new ie(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,mn)})}function tc(r){return new ie(function(e){var t,n;try{for(var s=Ne(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 kn(r){return new ie(function(e){nc(r,e).catch(function(t){return e.error(t)})})}function rc(r){return kn(Ga(r))}function nc(r,e){var t,n,s,o;return ba(this,void 0,void 0,function(){var a,c;return un(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=ka(r),l.label=1;case 1:return[4,t.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),s={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:l.sent(),l.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 sc(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 oc(r,e){var t=L(r)?r:function(){return r},n=function(s){return s.error(t())};return new ie(n)}var ic=Rt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function ac(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 ic)}})})}function cc(r){return r instanceof Date&&!isNaN(r)}var uc=Rt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function lc(r,e){var t=cc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?dc:o,c=t.scheduler,l=c===void 0?Ua:c,u=t.meta,d=u===void 0?null:u;if(n==null&&s==null)throw new TypeError("No timeout provided.");return Aa(function(y,w){var m,g,C=null,R=0,q=function(B){g=sc(w,l,function(){try{m.unsubscribe(),Ja(a({meta:d,lastValue:C,seen:R})).subscribe(w)}catch(j){w.error(j)}},B)};m=y.subscribe(ja(w,function(B){g==null||g.unsubscribe(),R++,w.next(C=B),s>0&&q(s)},void 0,void 0,function(){g!=null&&g.closed||g==null||g.unsubscribe(),C=null})),!R&&q(n!=null?typeof n=="number"?n:+n-l.now():s)})}function dc(r){throw new uc(r)}class Nt{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,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"&&Wt(this._current);const t={first:e.timeoutSec*1e3,with:()=>oc(()=>new Error(e.timeoutErrMsg))};return ac(this._subject.pipe(lc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new gn}get current(){return this._current}}const{log__:fc,err__:hc}=F("init-flows"),En=(r,e)=>{const t=new Nt;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);fc(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){hc(`𝙭 ${r} flow initialization failed. Error:`,he(s),"Details:",s),t.throw(s,he(s))}}}},pc=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},mc=()=>({stripePR:En("Stripe PR",Se.stripePR.init),stripeLink:En("Stripe Link",Se.stripeLink.init)}),{err__:yc}=F("form-callbacks"),K=i.function().optional(),Sn=i.object({onFocus:K,onBlur:K,onChange:K,onLoad:K,onLoadError:K,onValidationError:K,onCheckoutStarted:K,onCheckoutSuccess:K,onSetupPaymentMethodSuccess:K,onCheckoutError:K,onPaymentRequestLoad:K}),re=class re{constructor(){this.setCallbacks=e=>{this._callbacks=re.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const s=js(t,n??re.NOOP,yc);this._callbacks[t]=s})},this._callbacks=re.createEmptyCallbacks()}get get(){return{...this._callbacks}}};re.NOOP=()=>{},re.createEmptyCallbacks=()=>{const e={};return Object.keys(Sn.keyof().enum).forEach(t=>{e[t]=re.NOOP}),e},re.fromObject=e=>{const t=new re;return t.setCallbacks(Sn.parse(e)),t};let sr=re;class _c{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if(Cn(o.origin)!==Cn(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;const a=Co(JSON.parse(o.data));if(!this.validateEvent(a))return;const{elementId:l,payload:u}=a,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=o.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=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 Cn=r=>new URL(r).origin;async function gc(r,e){const n=await Rr({iframe:r,debug:!1,childOrigin:e}).promise,s=await Yo(n);if(!Ho(n,s))throw new Error("Got invalid CDE connection object");return n}class vc{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 bc=(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,l={apple_pay:{isLoading:!1,isAvailable:a,startFlow:async u=>{a&&xn("apple_pay",o,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&xn("google_pay",o,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},xn=(r,e,t,n,s)=>Se.stripePR.run({context:t,checkoutPaymentMethod:Jt(t.checkoutPaymentMethods,r),nonCdeFormInputs:bt(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),Tn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:ye,err__:Mt}=F("op-form"),ae=class ae{constructor(e){this.cdeLoadEvent=new Nt,this.anyCdeConn=new Nt,this.context=new Nt,this.initFlows=mc(),this.startFormInit=async()=>{try{ye("Initializing OpenPay form:"),ye("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Tn});ye("├ CDE load event received"),ye("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Tn});ye("├ CDE connection received"),ye("├ Creating OJS context, setting up handlers...");const s=ae.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(s),bc(this.initFlows,s,this.formCallbacks),ye("├ Starting OJS init flows..."),await pc(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),ye("╰ Done initializing OJS flows.")}catch(t){const n=he(t);Mt("╰ 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=Ns.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={[Ie.CARD]:void 0,[Ie.CARD_NUMBER]:void 0,[Ie.CARD_EXPIRY]:void 0,[Ie.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",vo(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{gc(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Mt("[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){Mt("Please wait for the form to finish loading before submitting.");return}Se.commonCC.run({context:t,checkoutPaymentMethod:Jt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:bt(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.generalSubmit=t=>{const n=this.context.getValueIfLoadedElse(null);if(!n){Mt("Please wait for the form to finish loading before submitting.");return}t==="pockyt-paypal"?Se.pockytPaypal.run({context:n,checkoutPaymentMethod:Jt(n.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:bt(n.formDiv),formCallbacks:this.formCallbacks,customParams:void 0,initResult:void 0}):Wt(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)},ae.assignAsSingleton(this),this.ojsVersion="0.1.21",this.ojsReleaseVersion="0.1.21",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-${So()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new vc,this.eventHandler=new _c(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}};ae.ojsFlows=Se,ae.assignAsSingleton=e=>{if(ae.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},ae.getInstance=()=>window.ojs??null,ae.buildOjsFlowContext=(e,t,n,s)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??$e).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let or=ae;_e.FieldName=E,_e.OpenPayForm=or,Object.defineProperty(_e,Symbol.toStringTag,{value:"Module"})});
|
|
24
|
+
`):"",this.name="UnsubscriptionError",this.errors=t}});function Yt(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(U(d))try{d()}catch(E){o=E instanceof _r?E.errors:[E]}var y=this._finalizers;if(y){this._finalizers=null;try{for(var b=He(y),h=b.next();!h.done;h=b.next()){var g=h.value;try{xn(g)}catch(E){o=o??[],E instanceof _r?o=Bt(Bt([],zt(o)),zt(E.errors)):o.push(E)}}}catch(E){n={error:E}}finally{try{h&&!h.done&&(s=b.return)&&s.call(b)}finally{if(n)throw n.error}}}if(o)throw new _r(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)xn(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)&&Yt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&Yt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Cn=wt.EMPTY;function Pn(r){return r instanceof wt||r&&"closed"in r&&U(r.remove)&&U(r.add)&&U(r.unsubscribe)}function xn(r){U(r)?r():r.unsubscribe()}var Tn={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},An={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,Bt([r,e],zt(t)))},clearTimeout:function(r){var e=An.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function In(r){An.setTimeout(function(){throw r})}function Rn(){}function Gt(r){r()}var gr=function(r){Se(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Pn(t)&&t.add(n)):n.destination=ec,n}return e.create=function(t,n,s){return new br(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),Ja=Function.prototype.bind;function vr(r,e){return Ja.call(r,e)}var Xa=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){Wt(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Wt(n)}else Wt(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Wt(t)}},r}(),br=function(r){Se(e,r);function e(t,n,s){var o=r.call(this)||this,a;if(U(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&Tn.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&vr(t.next,c),error:t.error&&vr(t.error,c),complete:t.complete&&vr(t.complete,c)}):a=t}return o.destination=new Xa(a),o}return e}(gr);function Wt(r){In(r)}function Qa(r){throw r}var ec={closed:!0,next:Rn,error:Qa,complete:Rn},wr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function tc(r){return r}function rc(r){return r.length===0?tc: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=sc(e)?e:new br(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=On(t),new t(function(s,o){var a=new br({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[wr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return rc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=On(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 On(r){var e;return(e=r??Tn.Promise)!==null&&e!==void 0?e:Promise}function nc(r){return r&&U(r.next)&&U(r.error)&&U(r.complete)}function sc(r){return r&&r instanceof gr||nc(r)&&Pn(r)}function oc(r){return U(r==null?void 0:r.lift)}function ic(r){return function(e){if(oc(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 ac(r,e,t,n,s){return new cc(r,e,t,n,s)}var cc=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}(gr),lc=qt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Nn=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 Mn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new lc},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?Cn:(this.currentObservers=null,c.push(t),new wt(function(){n.currentObservers=null,Yt(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 Mn(t,n)},e}(fe),Mn=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:Cn},e}(Nn),uc={now:function(){return Date.now()},delegate:void 0},dc=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),jn={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,Bt([r,e],zt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},pc=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),jn.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&&jn.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,Yt(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(dc),Dn=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=uc.now,r}(),fc=function(r){Se(e,r);function e(t,n){n===void 0&&(n=Dn.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}(Dn),hc=new fc(pc),mc=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function yc(r){return U(r==null?void 0:r.then)}function _c(r){return U(r[wr])}function gc(r){return Symbol.asyncIterator&&U(r==null?void 0:r[Symbol.asyncIterator])}function vc(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 bc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var wc=bc();function kc(r){return U(r==null?void 0:r[wc])}function Ec(r){return Ha(this,arguments,function(){var t,n,s,o;return Sn(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 Sc(r){return U(r==null?void 0:r.getReader)}function Cc(r){if(r instanceof fe)return r;if(r!=null){if(_c(r))return Pc(r);if(mc(r))return xc(r);if(yc(r))return Tc(r);if(gc(r))return Ln(r);if(kc(r))return Ac(r);if(Sc(r))return Ic(r)}throw vc(r)}function Pc(r){return new fe(function(e){var t=r[wr]();if(U(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function xc(r){return new fe(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Tc(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,In)})}function Ac(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 Ln(r){return new fe(function(e){Rc(r,e).catch(function(t){return e.error(t)})})}function Ic(r){return Ln(Ec(r))}function Rc(r,e){var t,n,s,o;return Wa(this,void 0,void 0,function(){var a,c;return Sn(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),t=Ka(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 Oc(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 Nc(r,e){var t=U(r)?r:function(){return r},n=function(s){return s.error(t())};return new fe(n)}var Mc=qt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function jc(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 Mc)}})})}function Dc(r){return r instanceof Date&&!isNaN(r)}var Lc=qt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function Uc(r,e){var t=Dc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?$c:o,c=t.scheduler,u=c===void 0?hc:c,l=t.meta,d=l===void 0?null:l;if(n==null&&s==null)throw new TypeError("No timeout provided.");return ic(function(y,b){var h,g,E=null,P=0,T=function(z){g=Oc(b,u,function(){try{h.unsubscribe(),Cc(a({meta:d,lastValue:E,seen:P})).subscribe(b)}catch(A){b.error(A)}},z)};h=y.subscribe(ac(b,function(z){g==null||g.unsubscribe(),P++,b.next(E=z),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 $c(r){throw new Lc(r)}class Ht{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:()=>Nc(()=>new Error(e.timeoutErrMsg))};return jc(this._subject.pipe(Uc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new Nn}get current(){return this._current}}const{log__:Fc,err__:Zc}=D("init-flows"),Kt=(r,e)=>{const t=new Ht;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);Fc(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){Zc(`𝙭 ${r} flow initialization failed. Error:`,we(s),"Details:",s),t.throw(s,we(s))}}}},Vc=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},zc=()=>({stripePR:Kt("Stripe PR",ee.stripePR.init),stripeLink:Kt("Stripe Link",ee.stripeLink.init),airwallexGooglePay:Kt("Airwallex GPay",ee.airwallexGooglePay.init),airwallexApplePay:Kt("Airwallex ApplePay",ee.airwallexApplePay.init)}),{err__:Bc}=D("form-callbacks"),te=i.function().optional(),Un=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=Gs(t,n??ae.NOOP,Bc);this._callbacks[t]=s})},this._callbacks=ae.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ae.NOOP=()=>{},ae.createEmptyCallbacks=()=>{const e={};return Object.keys(Un.keyof().enum).forEach(t=>{e[t]=ae.NOOP}),e},ae.fromObject=e=>{const t=new ae;return t.setCallbacks(Un.parse(e)),t};let kr=ae;class qc{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if($n(o.origin)!==$n(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;const a=$o(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 $n=r=>new URL(r).origin;async function Yc(r,e){const n=await Gr({iframe:r,debug:!1,childOrigin:e}).promise,s=await ai(n);if(!ci(n,s))throw new Error("Got invalid CDE connection object");return n}class Gc{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 Wc=(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&&Fn("apple_pay",o,e,t,l)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async l=>{c&&Fn("google_pay",o,e,t,l)}}};t.get.onPaymentRequestLoad(u)}})},Fn=(r,e,t,n,s)=>ee.stripePR.run({context:t,checkoutPaymentMethod:mr(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__:Jt}=D("op-form"),he=class he{constructor(e){this.cdeLoadEvent=new Ht,this.anyCdeConn=new Ht,this.context=new Ht,this.initFlows=zc(),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),Wc(this.initFlows,s,this.formCallbacks),Ce("├ Starting OJS init flows..."),await Vc(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Ce("╰ Done initializing OJS flows.")}catch(t){const n=we(t);Jt("╰ 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=Ws.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",No(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{Yc(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Jt("[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){Jt("Please wait for the form to finish loading before submitting.");return}ee.commonCC.run({context:t,checkoutPaymentMethod:mr(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){Jt("Please wait for the form to finish loading before submitting.");return}switch(t){case"pockyt-paypal":return ee.pockytPaypal.run({context:n,checkoutPaymentMethod:mr(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.0",this.ojsReleaseVersion="0.2.0-alpha.ff4f99c",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=kr.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Uo()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Gc,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 Er=he;Te.FieldName=f,Te.OpenPayForm=Er,Object.defineProperty(Te,Symbol.toStringTag,{value:"Module"})});
|