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