@getopenpay/openpay-js 0.2.22 → 0.2.24
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 +2 -0
- package/dist/index.es.js +3729 -3300
- package/dist/index.umd.js +17 -17
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
(function(be,Le){typeof exports=="object"&&typeof module<"u"?Le(exports):typeof define=="function"&&define.amd?define(["exports"],Le):(be=typeof globalThis<"u"?globalThis:be||self,Le(be.OpenPay={}))})(this,function(be){"use strict";const Le="https://cde.getopenpay.com";var R;(function(r){r.assertEqual=o=>o;function e(o){}r.assertIs=e;function t(o){throw new Error}r.assertNever=t,r.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},r.getValidEnumValues=o=>{const s=r.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return r.objectValues(i)},r.objectValues=o=>r.objectKeys(o).map(function(s){return o[s]}),r.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},r.find=(o,s)=>{for(const i of o)if(s(i))return i},r.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}r.joinValues=n,r.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(R||(R={}));var dr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(dr||(dr={}));const v=R.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 v.undefined;case"string":return v.string;case"number":return isNaN(r)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(r)?v.array:r===null?v.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?v.promise:typeof Map<"u"&&r instanceof Map?v.map:typeof Set<"u"&&r instanceof Set?v.set:typeof Date<"u"&&r instanceof Date?v.date:v.object;default:return v.unknown}},y=R.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"]),ko=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class Q extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(s){return s.message},n={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let c=n,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),n}static assert(e){if(!(e instanceof Q))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const o of this.issues)o.path.length>0?(t[o.path[0]]=t[o.path[0]]||[],t[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Q.create=r=>new Q(r);const Ye=(r,e)=>{let t;switch(r.code){case y.invalid_type:r.received===v.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case y.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,R.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:t=`Unrecognized key(s) in object: ${R.joinValues(r.keys,", ")}`;break;case y.invalid_union:t="Invalid input";break;case y.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${R.joinValues(r.options)}`;break;case y.invalid_enum_value:t=`Invalid enum value. Expected ${R.joinValues(r.options)}, received '${r.received}'`;break;case y.invalid_arguments:t="Invalid function arguments";break;case y.invalid_return_type:t="Invalid function return type";break;case y.invalid_date:t="Invalid date";break;case y.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}"`:R.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case y.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 y.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 y.custom:t="Invalid input";break;case y.invalid_intersection_types:t="Intersection results could not be merged";break;case y.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case y.not_finite:t="Number must be finite";break;default:t=e.defaultError,R.assertNever(r)}return{message:t}};let Vr=Ye;function Co(r){Vr=r}function Lt(){return Vr}const Ft=r=>{const{data:e,path:t,errorMaps:n,issueData:o}=r,s=[...t,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},So=[];function g(r,e){const t=Lt(),n=Ft({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ye?void 0:Ye].filter(o=>!!o)});r.common.issues.push(n)}class q{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 o of t){if(o.status==="aborted")return k;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const o of t){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return q.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const o of t){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return k;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const k=Object.freeze({status:"aborted"}),We=r=>({status:"dirty",value:r}),W=r=>({status:"valid",value:r}),pr=r=>r.status==="aborted",fr=r=>r.status==="dirty",lt=r=>r.status==="valid",ut=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 zr(r,e,t,n,o){if(typeof e=="function"?r!==e||!o:!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 b;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));var dt,pt;class ue{constructor(e,t,n,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=o}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 Gr=(r,e)=>{if(lt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Q(r.common.issues);return this._error=t,this._error}}};function P(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:o}=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:o}:{errorMap:(i,c)=>{var l,u;const{message:d}=r;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??t)!==null&&u!==void 0?u:c.defaultError}},description:o}}class I{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 q,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(ut(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 o={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)},s=this._parseSync({data:e,path:o.path,parent:o});return Gr(o,s)}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)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ut(o)?o:Promise.resolve(o));return Gr(n,s)}refine(e,t){const n=o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:y.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof t=="function"?t(n,o):t),!1))}_refinement(e){return new ne({schema:this,typeName:E.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return pe.create(this,this._def)}nullable(){return Ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this,this._def)}promise(){return Xe.create(this,this._def)}or(e){return yt.create([this,e],this._def)}and(e){return _t.create(this,e,this._def)}transform(e){return new ne({...P(this._def),schema:this,typeName:E.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Et({...P(this._def),innerType:this,defaultValue:t,typeName:E.ZodDefault})}brand(){return new yr({typeName:E.ZodBranded,type:this,...P(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new kt({...P(this._def),innerType:this,catchValue:t,typeName:E.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ct.create(this,e)}readonly(){return St.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Po=/^c[^\s-]{8,}$/i,Ao=/^[0-9a-z]+$/,xo=/^[0-9A-HJKMNP-TV-Z]{26}$/,Io=/^[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,To=/^[a-z0-9_-]{21}$/i,Ro=/^[-+]?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)?)??$/,Oo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,No="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let mr;const Mo=/^(?:(?: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])$/,Do=/^(([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})))$/,jo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Br="((\\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])))",Lo=new RegExp(`^${Br}$`);function qr(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 Fo(r){return new RegExp(`^${qr(r)}$`)}function Yr(r){let e=`${Br}T${qr(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 Uo(r,e){return!!((e==="v4"||!e)&&Mo.test(r)||(e==="v6"||!e)&&Do.test(r))}class te extends I{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.string,received:s.parsedType}),k}const n=new q;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,c=e.data.length<s.value;(i||c)&&(o=this._getOrReturnCtx(e,o),i?g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Oo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")mr||(mr=new RegExp(No,"u")),mr.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Io.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")To.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Po.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Ao.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:y.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:y.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Yr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Lo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Fo(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Ro.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Uo(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?jo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:y.invalid_string,message:s.message}),n.dirty()):R.assertNever(s);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(o=>e.test(o),{validation:t,code:y.invalid_string,...b.errToObj(n)})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.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,...b.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,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...b.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...b.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...b.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...b.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...b.errToObj(t)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new te({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new te({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new te({...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}}te.create=r=>{var e;return new te({checks:[],typeName:E.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...P(r)})};function $o(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=t>n?t:n,s=parseInt(r.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Te extends I{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)!==v.number){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.number,received:s.parsedType}),k}let n;const o=new q;for(const s of this._def.checks)s.kind==="int"?R.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?$o(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_finite,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,n,o){return new Te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Te({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.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"&&R.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)}}Te.create=r=>new Te({checks:[],typeName:E.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...P(r)});class Re extends I{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)!==v.bigint){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.bigint,received:s.parsedType}),k}let n;const o=new q;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),g(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,n,o){return new Re({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:b.toString(o)}]})}_addCheck(e){return new Re({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.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}}Re.create=r=>{var e;return new Re({checks:[],typeName:E.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...P(r)})};class ft extends I{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.boolean,received:n.parsedType}),k}return W(e.data)}}ft.create=r=>new ft({typeName:E.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...P(r)});class Fe extends I{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.date,received:s.parsedType}),k}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_date}),k}const n=new q;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):R.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Fe({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:b.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}}Fe.create=r=>new Fe({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:E.ZodDate,...P(r)});class $t extends I{_parse(e){if(this._getType(e)!==v.symbol){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.symbol,received:n.parsedType}),k}return W(e.data)}}$t.create=r=>new $t({typeName:E.ZodSymbol,...P(r)});class mt extends I{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.undefined,received:n.parsedType}),k}return W(e.data)}}mt.create=r=>new mt({typeName:E.ZodUndefined,...P(r)});class ht extends I{_parse(e){if(this._getType(e)!==v.null){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.null,received:n.parsedType}),k}return W(e.data)}}ht.create=r=>new ht({typeName:E.ZodNull,...P(r)});class Ke extends I{constructor(){super(...arguments),this._any=!0}_parse(e){return W(e.data)}}Ke.create=r=>new Ke({typeName:E.ZodAny,...P(r)});class Ue extends I{constructor(){super(...arguments),this._unknown=!0}_parse(e){return W(e.data)}}Ue.create=r=>new Ue({typeName:E.ZodUnknown,...P(r)});class Ee extends I{_parse(e){const t=this._getOrReturnCtx(e);return g(t,{code:y.invalid_type,expected:v.never,received:t.parsedType}),k}}Ee.create=r=>new Ee({typeName:E.ZodNever,...P(r)});class Zt extends I{_parse(e){if(this._getType(e)!==v.undefined){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.void,received:n.parsedType}),k}return W(e.data)}}Zt.create=r=>new Zt({typeName:E.ZodVoid,...P(r)});class re extends I{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),o=this._def;if(t.parsedType!==v.array)return g(t,{code:y.invalid_type,expected:v.array,received:t.parsedType}),k;if(o.exactLength!==null){const i=t.data.length>o.exactLength.value,c=t.data.length<o.exactLength.value;(i||c)&&(g(t,{code:i?y.too_big:y.too_small,minimum:c?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(g(t,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(g(t,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,c)=>o.type._parseAsync(new ue(t,i,t.path,c)))).then(i=>q.mergeArray(n,i));const s=[...t.data].map((i,c)=>o.type._parseSync(new ue(t,i,t.path,c)));return q.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new re({...this._def,minLength:{value:e,message:b.toString(t)}})}max(e,t){return new re({...this._def,maxLength:{value:e,message:b.toString(t)}})}length(e,t){return new re({...this._def,exactLength:{value:e,message:b.toString(t)}})}nonempty(e){return this.min(1,e)}}re.create=(r,e)=>new re({type:r,minLength:null,maxLength:null,exactLength:null,typeName:E.ZodArray,...P(e)});function He(r){if(r instanceof D){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=pe.create(He(n))}return new D({...r._def,shape:()=>e})}else return r instanceof re?new re({...r._def,type:He(r.element)}):r instanceof pe?pe.create(He(r.unwrap())):r instanceof Ne?Ne.create(He(r.unwrap())):r instanceof de?de.create(r.items.map(e=>He(e))):r}class D extends I{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=R.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:y.invalid_type,expected:v.object,received:u.parsedType}),k}const{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Ee&&this._def.unknownKeys==="strip"))for(const u in o.data)i.includes(u)||c.push(u);const l=[];for(const u of i){const d=s[u],p=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ue(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Ee){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")c.length>0&&(g(o,{code:y.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 p=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ue(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const p=await d.key,_=await d.value;u.push({key:p,value:_,alwaysSet:d.alwaysSet})}return u}).then(u=>q.mergeObjectSync(n,u)):q.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new D({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,t,n).message)!==null&&i!==void 0?i:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=b.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new D({...this._def,unknownKeys:"strip"})}passthrough(){return new D({...this._def,unknownKeys:"passthrough"})}extend(e){return new D({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new D({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:E.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new D({...this._def,catchall:e})}pick(e){const t={};return R.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new D({...this._def,shape:()=>t})}omit(e){const t={};return R.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new D({...this._def,shape:()=>t})}deepPartial(){return He(this)}partial(e){const t={};return R.objectKeys(this.shape).forEach(n=>{const o=this.shape[n];e&&!e[n]?t[n]=o:t[n]=o.optional()}),new D({...this._def,shape:()=>t})}required(e){const t={};return R.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof pe;)s=s._def.innerType;t[n]=s}}),new D({...this._def,shape:()=>t})}keyof(){return Wr(R.objectKeys(this.shape))}}D.create=(r,e)=>new D({shape:()=>r,unknownKeys:"strip",catchall:Ee.create(),typeName:E.ZodObject,...P(e)}),D.strictCreate=(r,e)=>new D({shape:()=>r,unknownKeys:"strict",catchall:Ee.create(),typeName:E.ZodObject,...P(e)}),D.lazycreate=(r,e)=>new D({shape:r,unknownKeys:"strip",catchall:Ee.create(),typeName:E.ZodObject,...P(e)});class yt extends I{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new Q(c.ctx.common.issues));return g(t,{code:y.invalid_union,unionErrors:i}),k}if(t.common.async)return Promise.all(n.map(async s=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];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"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new Q(l));return g(t,{code:y.invalid_union,unionErrors:c}),k}}get options(){return this._def.options}}yt.create=(r,e)=>new yt({options:r,typeName:E.ZodUnion,...P(e)});const ke=r=>r instanceof vt?ke(r.schema):r instanceof ne?ke(r.innerType()):r instanceof wt?[r.value]:r instanceof Oe?r.options:r instanceof bt?R.objectValues(r.enum):r instanceof Et?ke(r._def.innerType):r instanceof mt?[void 0]:r instanceof ht?[null]:r instanceof pe?[void 0,...ke(r.unwrap())]:r instanceof Ne?[null,...ke(r.unwrap())]:r instanceof yr||r instanceof St?ke(r.unwrap()):r instanceof kt?ke(r._def.innerType):[];class Vt extends I{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.object)return g(t,{code:y.invalid_type,expected:v.object,received:t.parsedType}),k;const n=this.discriminator,o=t.data[n],s=this.optionsMap.get(o);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),k)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const o=new Map;for(const s of t){const i=ke(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of i){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new Vt({typeName:E.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...P(n)})}}function hr(r,e){const t=Ie(r),n=Ie(e);if(r===e)return{valid:!0,data:r};if(t===v.object&&n===v.object){const o=R.objectKeys(e),s=R.objectKeys(r).filter(c=>o.indexOf(c)!==-1),i={...r,...e};for(const c of s){const l=hr(r[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(t===v.array&&n===v.array){if(r.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<r.length;s++){const i=r[s],c=e[s],l=hr(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return t===v.date&&n===v.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class _t extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(pr(s)||pr(i))return k;const c=hr(s.value,i.value);return c.valid?((fr(s)||fr(i))&&t.dirty(),{status:t.value,value:c.data}):(g(n,{code:y.invalid_intersection_types}),k)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}_t.create=(r,e,t)=>new _t({left:r,right:e,typeName:E.ZodIntersection,...P(t)});class de extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.array)return g(n,{code:y.invalid_type,expected:v.array,received:n.parsedType}),k;if(n.data.length<this._def.items.length)return g(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),k;!this._def.rest&&n.data.length>this._def.items.length&&(g(n,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...n.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new ue(n,i,n.path,c)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>q.mergeArray(t,i)):q.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new de({...this._def,rest:e})}}de.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new de({items:r,typeName:E.ZodTuple,rest:null,...P(e)})};class gt extends I{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!==v.object)return g(n,{code:y.invalid_type,expected:v.object,received:n.parsedType}),k;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in n.data)o.push({key:s._parse(new ue(n,c,n.path,c)),value:i._parse(new ue(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?q.mergeObjectAsync(t,o):q.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof I?new gt({keyType:e,valueType:t,typeName:E.ZodRecord,...P(n)}):new gt({keyType:te.create(),valueType:e,typeName:E.ZodRecord,...P(t)})}}class zt extends I{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!==v.map)return g(n,{code:y.invalid_type,expected:v.map,received:n.parsedType}),k;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([c,l],u)=>({key:o._parse(new ue(n,c,n.path,[u,"key"])),value:s._parse(new ue(n,l,n.path,[u,"value"]))}));if(n.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return k;(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 i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return k;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(u.value,d.value)}return{status:t.value,value:c}}}}zt.create=(r,e,t)=>new zt({valueType:e,keyType:r,typeName:E.ZodMap,...P(t)});class $e extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==v.set)return g(n,{code:y.invalid_type,expected:v.set,received:n.parsedType}),k;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(g(n,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(g(n,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return k;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}const c=[...n.data.values()].map((l,u)=>s._parse(new ue(n,l,n.path,u)));return n.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,t){return new $e({...this._def,minSize:{value:e,message:b.toString(t)}})}max(e,t){return new $e({...this._def,maxSize:{value:e,message:b.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:E.ZodSet,...P(e)});class Je extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.function)return g(t,{code:y.invalid_type,expected:v.function,received:t.parsedType}),k;function n(c,l){return Ft({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Lt(),Ye].filter(u=>!!u),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(c,l){return Ft({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Lt(),Ye].filter(u=>!!u),issueData:{code:y.invalid_return_type,returnTypeError:l}})}const s={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Xe){const c=this;return W(async function(...l){const u=new Q([]),d=await c._def.args.parseAsync(l,s).catch(f=>{throw u.addIssue(n(l,f)),u}),p=await Reflect.apply(i,this,d);return await c._def.returns._def.type.parseAsync(p,s).catch(f=>{throw u.addIssue(o(p,f)),u})})}else{const c=this;return W(function(...l){const u=c._def.args.safeParse(l,s);if(!u.success)throw new Q([n(l,u.error)]);const d=Reflect.apply(i,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new Q([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Je({...this._def,args:de.create(e).rest(Ue.create())})}returns(e){return new Je({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Je({args:e||de.create([]).rest(Ue.create()),returns:t||Ue.create(),typeName:E.ZodFunction,...P(n)})}}class vt extends I{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})}}vt.create=(r,e)=>new vt({getter:r,typeName:E.ZodLazy,...P(e)});class wt extends I{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:y.invalid_literal,expected:this._def.value}),k}return{status:"valid",value:e.data}}get value(){return this._def.value}}wt.create=(r,e)=>new wt({value:r,typeName:E.ZodLiteral,...P(e)});function Wr(r,e){return new Oe({values:r,typeName:E.ZodEnum,...P(e)})}class Oe extends I{constructor(){super(...arguments),dt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return g(t,{expected:R.joinValues(n),received:t.parsedType,code:y.invalid_type}),k}if(Ut(this,dt)||zr(this,dt,new Set(this._def.values)),!Ut(this,dt).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return g(t,{received:t.data,code:y.invalid_enum_value,options:n}),k}return W(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 Oe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Oe.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}dt=new WeakMap,Oe.create=Wr;class bt extends I{constructor(){super(...arguments),pt.set(this,void 0)}_parse(e){const t=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==v.string&&n.parsedType!==v.number){const o=R.objectValues(t);return g(n,{expected:R.joinValues(o),received:n.parsedType,code:y.invalid_type}),k}if(Ut(this,pt)||zr(this,pt,new Set(R.getValidEnumValues(this._def.values))),!Ut(this,pt).has(e.data)){const o=R.objectValues(t);return g(n,{received:n.data,code:y.invalid_enum_value,options:o}),k}return W(e.data)}get enum(){return this._def.values}}pt=new WeakMap,bt.create=(r,e)=>new bt({values:r,typeName:E.ZodNativeEnum,...P(e)});class Xe extends I{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==v.promise&&t.common.async===!1)return g(t,{code:y.invalid_type,expected:v.promise,received:t.parsedType}),k;const n=t.parsedType===v.promise?t.data:Promise.resolve(t.data);return W(n.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Xe.create=(r,e)=>new Xe({type:r,typeName:E.ZodPromise,...P(e)});class ne extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===E.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async c=>{if(t.value==="aborted")return k;const l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?k:l.status==="dirty"||t.value==="dirty"?We(l.value):l});{if(t.value==="aborted")return k;const c=this._def.schema._parseSync({data:i,path:n.path,parent:n});return c.status==="aborted"?k:c.status==="dirty"||t.value==="dirty"?We(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);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"?k:(c.status==="dirty"&&t.dirty(),i(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?k:(c.status==="dirty"&&t.dirty(),i(c.value).then(()=>({status:t.value,value:c.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!lt(i))return i;const c=o.transform(i.value,s);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(i=>lt(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:t.value,value:c})):i);R.assertNever(o)}}ne.create=(r,e,t)=>new ne({schema:r,typeName:E.ZodEffects,effect:e,...P(t)}),ne.createWithPreprocess=(r,e,t)=>new ne({schema:e,effect:{type:"preprocess",transform:r},typeName:E.ZodEffects,...P(t)});class pe extends I{_parse(e){return this._getType(e)===v.undefined?W(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pe.create=(r,e)=>new pe({innerType:r,typeName:E.ZodOptional,...P(e)});class Ne extends I{_parse(e){return this._getType(e)===v.null?W(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ne.create=(r,e)=>new Ne({innerType:r,typeName:E.ZodNullable,...P(e)});class Et extends I{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Et.create=(r,e)=>new Et({innerType:r,typeName:E.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...P(e)});class kt extends I{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ut(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Q(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Q(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}kt.create=(r,e)=>new kt({innerType:r,typeName:E.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...P(e)});class Gt extends I{_parse(e){if(this._getType(e)!==v.nan){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.nan,received:n.parsedType}),k}return{status:"valid",value:e.data}}}Gt.create=r=>new Gt({typeName:E.ZodNaN,...P(r)});const Zo=Symbol("zod_brand");class yr extends I{_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 Ct extends I{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?k:s.status==="dirty"?(t.dirty(),We(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?k:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,t){return new Ct({in:e,out:t,typeName:E.ZodPipeline})}}class St extends I{_parse(e){const t=this._def.innerType._parse(e),n=o=>(lt(o)&&(o.value=Object.freeze(o.value)),o);return ut(t)?t.then(o=>n(o)):n(t)}unwrap(){return this._def.innerType}}St.create=(r,e)=>new St({innerType:r,typeName:E.ZodReadonly,...P(e)});function Kr(r,e={},t){return r?Ke.create().superRefine((n,o)=>{var s,i;if(!r(n)){const c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:t)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):Ke.create()}const Vo={object:D.lazycreate};var E;(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"})(E||(E={}));const zo=(r,e={message:`Input not instance of ${r.name}`})=>Kr(t=>t instanceof r,e),Hr=te.create,Jr=Te.create,Go=Gt.create,Bo=Re.create,Xr=ft.create,qo=Fe.create,Yo=$t.create,Wo=mt.create,Ko=ht.create,Ho=Ke.create,Jo=Ue.create,Xo=Ee.create,Qo=Zt.create,es=re.create,ts=D.create,rs=D.strictCreate,ns=yt.create,os=Vt.create,ss=_t.create,as=de.create,is=gt.create,cs=zt.create,ls=$e.create,us=Je.create,ds=vt.create,ps=wt.create,fs=Oe.create,ms=bt.create,hs=Xe.create,Qr=ne.create,ys=pe.create,_s=Ne.create,gs=ne.createWithPreprocess,vs=Ct.create;var a=Object.freeze({__proto__:null,defaultErrorMap:Ye,setErrorMap:Co,getErrorMap:Lt,makeIssue:Ft,EMPTY_PATH:So,addIssueToContext:g,ParseStatus:q,INVALID:k,DIRTY:We,OK:W,isAborted:pr,isDirty:fr,isValid:lt,isAsync:ut,get util(){return R},get objectUtil(){return dr},ZodParsedType:v,getParsedType:Ie,ZodType:I,datetimeRegex:Yr,ZodString:te,ZodNumber:Te,ZodBigInt:Re,ZodBoolean:ft,ZodDate:Fe,ZodSymbol:$t,ZodUndefined:mt,ZodNull:ht,ZodAny:Ke,ZodUnknown:Ue,ZodNever:Ee,ZodVoid:Zt,ZodArray:re,ZodObject:D,ZodUnion:yt,ZodDiscriminatedUnion:Vt,ZodIntersection:_t,ZodTuple:de,ZodRecord:gt,ZodMap:zt,ZodSet:$e,ZodFunction:Je,ZodLazy:vt,ZodLiteral:wt,ZodEnum:Oe,ZodNativeEnum:bt,ZodPromise:Xe,ZodEffects:ne,ZodTransformer:ne,ZodOptional:pe,ZodNullable:Ne,ZodDefault:Et,ZodCatch:kt,ZodNaN:Gt,BRAND:Zo,ZodBranded:yr,ZodPipeline:Ct,ZodReadonly:St,custom:Kr,Schema:I,ZodSchema:I,late:Vo,get ZodFirstPartyTypeKind(){return E},coerce:{string:r=>te.create({...r,coerce:!0}),number:r=>Te.create({...r,coerce:!0}),boolean:r=>ft.create({...r,coerce:!0}),bigint:r=>Re.create({...r,coerce:!0}),date:r=>Fe.create({...r,coerce:!0})},any:Ho,array:es,bigint:Bo,boolean:Xr,date:qo,discriminatedUnion:os,effect:Qr,enum:fs,function:us,instanceof:zo,intersection:ss,lazy:ds,literal:ps,map:cs,nan:Go,nativeEnum:ms,never:Xo,null:Ko,nullable:_s,number:Jr,object:ts,oboolean:()=>Xr().optional(),onumber:()=>Jr().optional(),optional:ys,ostring:()=>Hr().optional(),pipeline:vs,preprocess:gs,promise:hs,record:is,set:ls,strictObject:rs,string:Hr,symbol:Yo,transformer:Qr,tuple:as,undefined:Wo,union:ns,unknown:Jo,void:Qo,NEVER:k,ZodIssueCode:y,quotelessJson:ko,ZodError:Q});const ws=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),bs=a.array(ws),Es=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),ks=a.array(Es),Cs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},_r=r=>{const e=r.toLowerCase().trim();return Cs[e]??r},Ss=r=>{try{return typeof JSON.parse(r)=="object"}catch{return!1}},Ps=r=>r.length===1?_r(r[0].msg):`Please fix the following errors:
|
|
2
|
-
${
|
|
3
|
-
`)}`,
|
|
4
|
-
${
|
|
5
|
-
`)}`,
|
|
6
|
-
${r.message}`),r.message)}else return _r(r.message);if(typeof r=="object")try{return JSON.stringify(r)}catch(e){return e+""}else return r+""},xs=(r,e,t)=>(...n)=>{try{return e(...n)}catch(o){t(`[form] Error running callback (${r}):`,o);return}};var ee=(r=>(r.pockytPaypal="pockyt-paypal",r.airwallexGooglePay="airwallex-google-pay",r.airwallexApplePay="airwallex-apple-pay",r.authorizenetGooglePay="authorizenet-google-pay",r.authorizenetApplePay="authorizenet-apple-pay",r.loopCrypto="loop-crypto",r))(ee||{});const Is=a.nativeEnum(ee),U=a.string().trim().min(1,{message:"Cannot be blank"}),j=a.string().trim().optional(),K=r=>a.nullable(r.optional());var m=(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))(m||{});const en=a.nativeEnum(m);var tn=(r=>(r.CARD_NUMBER="cardNumber",r.CARD_EXPIRY="cardExpiry",r.CARD_CVC="cardCvc",r))(tn||{});const rn=a.nativeEnum(tn),nn=a.union([en,rn]);var Ce=(r=>(r.CARD="card",r.CARD_NUMBER="card-number",r.CARD_EXPIRY="card-expiry",r.CARD_CVC="card-cvc",r.CDE_BRIDGE="cde-bridge",r))(Ce||{});const Ts=a.nativeEnum(Ce),Bt=a.object({provider:a.string(),processor_name:K(a.string()),metadata:K(a.record(a.string(),a.any()))}),Rs=a.object({id:a.string()});a.object({cardNumber:j,expiry:j,cvc:j}),a.object({backgroundColor:j,color:j,fontFamily:j,fontSize:j,fontWeight:j,margin:j,padding:j,letterSpacing:j,lineHeight:j,hideIcon:j});const oe=a.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=oe.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Ns=a.object({type:Os}),Ms=oe.extract(["BLUR","FOCUS","CHANGE"]),Ds=a.object({type:Ms,elementType:rn,errors:a.array(a.string()).optional()}),js=oe.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),Ls=a.object({type:js,message:U,headers:a.record(a.string(),a.string()).optional()}),Fs=oe.extract(["VALIDATION_ERROR"]),Us=a.object({type:Fs,elementType:nn,errors:a.array(a.string())}),$s=a.object({type:a.literal(oe.enum.LAYOUT),height:U}),Zs=a.object({type:a.literal(oe.enum.LOADED),sessionId:U,totalAmountAtoms:a.number(),currency:j,checkoutPaymentMethods:a.array(Bt)}),Vs=a.object({type:a.literal(oe.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),zs=a.object({type:a.literal(oe.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),Pt=a.object({firstName:U,lastName:U,email:U,zipCode:U,country:U,promotionCode:j}),Gs=a.object({firstName:j,lastName:j,email:U,zipCode:U,country:U,promotionCode:j,address:j,city:j,state:j}),Bs=oe.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),qs=a.object({type:Bs,sessionId:U,checkoutPaymentMethod:Bt,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:j}).extend(Pt.shape),Ys=a.object({type:a.literal(oe.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),Ws=a.object({type:a.literal(oe.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),Ks=a.discriminatedUnion("type",[Ns,Ds,Ls,Us,$s,Zs,qs,Ys,Ws,Vs,zs]),Hs=a.object({payload:Ks,nonce:U,formId:U,elementId:U});a.object({amountAtom:a.number(),currency:U}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:K(a.string()),their_pm_id:K(a.string()),checkout_attempt_id:K(a.string()),processor_specific_metadata:K(a.record(a.string(),a.any()))});const gr=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:K(a.array(a.string()))}),Js=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const Xs=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(Js)}),Qs=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),Xs]);a.object({session_id:a.string(),checkout_payment_method:Bt,non_cde_form_fields:Pt,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:K(a.string()),extra_metadata:a.record(a.string(),a.any())}),a.object({session_id:a.string(),checkout_payment_method:Bt,non_cde_form_fields:Pt,extra_metadata:a.record(a.string(),a.any()).optional()});var $=(r=>(r.SUCCESS="success",r.FAILURE="failure",r.CANCELLED="cancelled",r))($||{});const ea=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const ta=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),on=a.object({type:a.string(),redirect_url:K(a.string()),initial_intent_id:K(a.string()),consent_id:K(a.string()),their_pm_id:K(a.string()),payment_session:K(a.record(a.string(),a.any()))}),ra=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),na=a.object({payment_methods:a.array(Rs),pay_first_success_response:K(gr),required_user_actions:K(a.array(on))}),sn=r=>{const e={};return Object.entries(r).forEach(([t,n])=>{try{const o=en.parse(t);Array.isArray(n)?e[o]=n:Array.isArray(n._errors)&&(e[o]=n._errors)}catch{return}}),e},oa=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),sa=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),aa={usd:"usd",brl:"brl"},qt=async r=>{for(let t=0;t<10;t++)an()||await vr(500);if(!an())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(r)},ia=async(r,e)=>{const t=await qt(r);return{elements:t.elements(e),stripe:t}},ca=async(r,e,t,n,o)=>{const s=await qt(r),i=aa[t.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:n},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},vr=r=>new Promise(e=>{setTimeout(e,r)}),an=()=>"Stripe"in window,la=async r=>new Promise((e,t)=>{try{r.on("paymentmethod",async n=>{console.log("paymentmethod EVT:: ",n),e(n)}),r.on("token",async n=>{console.log("token EVT:: ",n)}),r.on("cancel",()=>{t(new Error("Payment cancelled, please click Submit again to pay"))})}catch(n){t(n)}}),ua=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 qt(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},da=async r=>{var o,s,i,c;const t=await(await qt(r.stripe_pk)).confirmCardSetup(r.client_secret,{payment_method:r.stripe_pm_id}),n=(o=t.setupIntent)==null?void 0:o.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(`${((s=t.error)==null?void 0:s.message)??((c=(i=t.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},pa=r=>JSON.stringify(r);for(var V=[],wr=0;wr<256;++wr)V.push((wr+256).toString(16).slice(1));function fa(r,e=0){return(V[r[e+0]]+V[r[e+1]]+V[r[e+2]]+V[r[e+3]]+"-"+V[r[e+4]]+V[r[e+5]]+"-"+V[r[e+6]]+V[r[e+7]]+"-"+V[r[e+8]]+V[r[e+9]]+"-"+V[r[e+10]]+V[r[e+11]]+V[r[e+12]]+V[r[e+13]]+V[r[e+14]]+V[r[e+15]]).toLowerCase()}var Yt,ma=new Uint8Array(16);function ha(){if(!Yt&&(Yt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Yt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Yt(ma)}var ya=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const cn={randomUUID:ya};function br(r,e,t){if(cn.randomUUID&&!e&&!r)return cn.randomUUID();r=r||{};var n=r.random||(r.rng||ha)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,fa(n)}const me=(r,e)=>Array.from(r.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),_a=r=>{try{return Hs.parse(r)}catch(e){throw console.error("Error parsing event payload:",r,e),e}};var he;(function(r){r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack"})(he||(he={}));var Ze;(function(r){r.Fulfilled="fulfilled",r.Rejected="rejected"})(Ze||(Ze={}));var At;(function(r){r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc"})(At||(At={}));var Er;(function(r){r.DataCloneError="DataCloneError"})(Er||(Er={}));var Me;(function(r){r.Message="message"})(Me||(Me={}));const ga=(r,e)=>{const t=[];let n=!1;return{destroy(o){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(s=>{s(o)}))},onDestroy(o){n?o():t.push(o)}}},va=r=>(...e)=>{r&&console.log("[Penpal]",...e)},wa={"http:":"80","https:":"443"},ba=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ea=["file:","data:"],ka=r=>{if(r&&Ea.find(c=>r.startsWith(c)))return"null";const e=document.location,t=ba.exec(r);let n,o,s;t?(n=t[1]?t[1]:e.protocol,o=t[2],s=t[4]):(n=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==wa[n]?`:${s}`:"";return`${n}//${o}${i}`},ln=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Ca=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Sa=(r,e,t)=>{const{localName:n,local:o,remote:s,originForSending:i,originForReceiving:c}=r;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==he.Call)return;if(c!=="*"&&d.origin!==c){t(`${n} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const p=d.data,{methodName:_,args:f,id:h}=p;t(`${n}: Received ${_}() call`);const w=x=>S=>{if(t(`${n}: Sending ${_}() reply`),l){t(`${n}: Unable to send ${_}() reply due to destroyed connection`);return}const T={penpal:he.Reply,id:h,resolution:x,returnValue:S};x===Ze.Rejected&&S instanceof Error&&(T.returnValue=ln(S),T.returnValueIsError=!0);try{s.postMessage(T,i)}catch(A){if(A.name===Er.DataCloneError){const O={penpal:he.Reply,id:h,resolution:Ze.Rejected,returnValue:ln(A),returnValueIsError:!0};s.postMessage(O,i)}throw A}};new Promise(x=>x(e[_].apply(e,f))).then(w(Ze.Fulfilled),w(Ze.Rejected))};return o.addEventListener(Me.Message,u),()=>{l=!0,o.removeEventListener(Me.Message,u)}};let Pa=0;const Aa=()=>++Pa,un=".",dn=r=>r?r.split(un):[],xa=r=>r.join(un),Ia=(r,e)=>{const t=dn(e||"");return t.push(r),xa(t)},Ta=(r,e,t)=>{const n=dn(e);return n.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===n.length-1&&(o[s]=t),o[s]),r),r},pn=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const o=r[n],s=Ia(n,e);typeof o=="object"&&Object.assign(t,pn(o,s)),typeof o=="function"&&(t[s]=o)}),t},Ra=r=>{const e={};for(const t in r)Ta(e,t,r[t]);return e},Oa=(r,e,t,n,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const p=f=>(...h)=>{o(`${s}: Sending ${f}() call`);let w;try{c.closed&&(w=!0)}catch{w=!0}if(w&&n(),d){const x=new Error(`Unable to send ${f}() call due to destroyed connection`);throw x.code=At.ConnectionDestroyed,x}return new Promise((x,S)=>{const T=Aa(),A=F=>{if(F.source!==c||F.data.penpal!==he.Reply||F.data.id!==T)return;if(u!=="*"&&F.origin!==u){o(`${s} received message from origin ${F.origin} which did not match expected origin ${u}`);return}const Y=F.data;o(`${s}: Received ${f}() reply`),i.removeEventListener(Me.Message,A);let we=Y.returnValue;Y.returnValueIsError&&(we=Ca(we)),(Y.resolution===Ze.Fulfilled?x:S)(we)};i.addEventListener(Me.Message,A);const O={penpal:he.Call,id:T,methodName:f,args:h};c.postMessage(O,l)})},_=t.reduce((f,h)=>(f[h]=p(h),f),{});return Object.assign(r,Ra(_)),()=>{d=!0}},Na=(r,e,t,n,o)=>{const{destroy:s,onDestroy:i}=n;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const p={localName:"Parent",local:window,remote:d.source,originForSending:t,originForReceiving:e};c&&c(),c=Sa(p,r,o),i(c),l&&l.forEach(f=>{delete u[f]}),l=d.data.methodNames;const _=Oa(u,p,l,s,o);return i(_),u}},Ma=(r,e,t,n)=>o=>{if(!o.source)return;if(t!=="*"&&o.origin!==t){r(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${t}`);return}r("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:he.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,n)},Da=6e4,ja=(r,e)=>{const{destroy:t,onDestroy:n}=e,o=setInterval(()=>{r.isConnected||(clearInterval(o),t())},Da);n(()=>{clearInterval(o)})},La=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=At.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},Fa=r=>{if(!r.src&&!r.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=At.NoIframeSrc,e}},fn=r=>{let{iframe:e,methods:t={},childOrigin:n,timeout:o,debug:s=!1}=r;const i=va(s),c=ga("Parent",i),{onDestroy:l,destroy:u}=c;n||(Fa(e),n=ka(e.src));const d=n==="null"?"*":n,p=pn(t),_=Ma(i,p,n,d),f=Na(p,n,d,c,i);return{promise:new Promise((w,x)=>{const S=La(o,u),T=A=>{if(!(A.source!==e.contentWindow||!A.data)){if(A.data.penpal===he.Syn){_(A);return}if(A.data.penpal===he.Ack){const O=f(A);O&&(S(),w(O));return}}};window.addEventListener(Me.Message,T),i("Parent: Awaiting handshake"),ja(e,c),l(A=>{window.removeEventListener(Me.Message,T),A&&x(A)})}),destroy(){u()}}},Ua=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}},$a=(r,e)=>!!r&&e,C=r=>a.nullable(r.optional());a.string().trim().min(1,{message:"Cannot be blank"});const Za=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const mn=a.object({name:a.string(),amount_atom_off:C(a.number()),percent_off:C(a.number()),currency:C(a.string()),duration:a.string(),duration_in_months:C(a.number())}),hn=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:C(a.string()),price_id:a.string(),billing_interval:C(a.string()),billing_interval_count:C(a.number().int()),quantity:a.number().int()}),Va=a.record(a.string(),a.any()),za=a.object({name:a.string(),settings:C(Va)}),Qe=a.object({provider:a.string(),processor_name:C(a.string()),metadata:C(a.record(a.string(),a.any()))}),Ga=a.object({quantity:a.number()}),Ba=a.object({id:C(a.string()),billing_interval:C(a.string()),billing_interval_count:C(a.number().int()),subscription_items:a.array(Ga),trial_start:C(a.string()),trial_end:C(a.string())}),yn=a.object({amount_atom:a.number()}),qa=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(yn),subscription_item_id:a.string()}),Ya=a.object({coupon:mn}),Wa=a.object({currency:a.string(),discounts:a.array(Ya),hosted_invoice_url:C(a.string()),lines:a.array(qa),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(yn)}),_n=a.object({created:a.array(Ba),invoices:a.array(Wa),processors_used:C(a.array(a.string()))}),gn=a.object({preview:_n,preview_post_trial:C(_n),coupons:a.array(mn)}),vn=a.object({status:a.literal("open"),locale:C(a.string()),token:a.string(),email:C(a.string()),line_items:a.array(hn),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:za,subs_preview:C(gn),methods_available:a.array(Qe)}),wn=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(vn.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(vn.shape)]),Ka=a.object({status:a.literal("complete")}),Ha=a.object({status:a.literal("expired")});a.union([wn,Ka,Ha]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(hn),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:Qe,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:C(a.string())});const bn=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const Ja=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(Ja);const Xa=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),Qa=a.object({price_id:a.string(),quantity:a.number().int()}),ei=a.object({line_items:a.array(Qa),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),ti=a.object({processor_specific_metadata:C(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:Qe,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:ei.optional()}).extend(Xa.shape).extend(ti.shape);const En=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:C(a.string())});a.object({fields:Gs,checkoutPaymentMethod:Qe}),a.object({session_id:a.string(),non_cde_form_fields:Pt,checkout_payment_method:Qe,extra_metadata:a.record(a.string(),a.any())});const ri=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:C(a.string()),last_name:C(a.string()),line1:C(a.string()),line2:C(a.string()),line3:C(a.string()),city:C(a.string()),state:C(a.string()),country:C(a.string()),zip_code:C(a.string()),email:C(a.string()),billing_email:C(a.string()),phone_number:C(a.string()),update_processor_customer:C(a.boolean())}),a.object({id:a.string(),email:C(a.string()),first_name:C(a.string()),last_name:C(a.string()),phone_number:C(a.string()),billing_email:C(a.string()),address:C(a.record(a.string(),a.any()))}),a.object({message:a.string()});const ni=a.object({error_code:a.string()});a.object({checkout_payment_method:Qe,processor_specific_metadata:a.record(a.any()).optional()});const oi=a.object({next_action_metadata:C(a.record(a.any()))}),si=r=>r.reduce((e,t)=>e+t,0);function ai(r,e){var t=Object.setPrototypeOf;t?t(r,e):r.__proto__=e}function ii(r,e){e===void 0&&(e=r.constructor);var t=Error.captureStackTrace;t&&t(r,e)}var ci=function(){var r=function(t,n){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},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)}}(),li=function(r){ci(e,r);function e(t,n){var o=this.constructor,s=r.call(this,t,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),ai(s,o.prototype),ii(s),s}return e}(Error);class kn extends li{constructor(e){const t=`${e.message}`;super(t),this.response=e}get originalErrorMessage(){return this.response.message}}const H=async(r,e,t)=>{const n=await r.send(e);if(di(n))throw new kn(n);if(!ui(n,t)){const o=t.safeParse(n);throw o.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",t,"Actual:",n),o.error)}return n},ui=(r,e)=>e.safeParse(r).success,di=r=>Za.safeParse(r).success,pi=async(r,e)=>await H(r,{type:"get_checkout_preview",payload:e},gn),z=async r=>await H(r,{type:"get_prefill",payload:{}},wn),et=async(r,e)=>await H(r,{type:"v2_start_payment_flow",payload:e},En),fi=async(r,e)=>await H(r,{type:"start_payment_flow_for_cc",payload:e},ri),mi=async(r,e)=>await H(r,{type:"start_payment_flow_for_pr",payload:e},En),se=async(r,e)=>await H(r,{type:"confirm_payment_flow",payload:e},na),hi=async(r,e)=>await H(r,{type:"finalize_setup_payment_method",payload:e},bn),yi=async(r,e)=>await H(r,{type:"check_if_popup_window_verified",payload:e},ra),_i=async(r,e,t)=>{const n=await pi(r,{secure_token:e,promotion_code:t}),o=new Set(n.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=si(n.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},tt=async(r,e,t,n)=>{if(t)return{amountAtom:0,currency:"usd"};{n=n||void 0;const o=await _i(r,e,n);return{amountAtom:o.amountAtom,currency:o.currency}}},gi=async(r,e)=>{if(r.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(r.values()).map(n=>H(n,{type:"tokenize_card",payload:e},Qs)))},Cn=async(r,e)=>{try{return await H(r,{type:"checkout_card_elements",payload:e},gr)}catch(t){throw console.error("[cde-client] Error during checkoutCardElements:",t,JSON.stringify(t)),t}},vi=async(r,e)=>await H(r,{type:"setup_payment_method",payload:e},bn),kr=async(r,e)=>await H(r,{type:"checkout",payload:e},gr),Sn=1e3,wi=async(r,e)=>{console.log(e);const n=await fn({iframe:r,debug:!0,timeout:Sn,childOrigin:"*"}).promise,o=await H(n,{type:"ping-3ds-status"},ea);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Cr=async(r,e)=>await H(r,{type:"prepare_payment_flow",payload:e},oi),Pn=async(r,e)=>{try{return(await H(r,{type:"get_standardized_error_code",payload:{message:e}},ni)).error_code}catch(t){return console.error("[cde-client] Error during getStandardizedErrorCode:",fe(t)),"PAYMENT_FAILED_GENERIC"}};function Wt(r){throw new Error(`Unhandled case: ${r}`)}const Sr=10,An=(r=0)=>e=>`\x1B[${e+r}m`,xn=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,In=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,N={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(N.modifier);const bi=Object.keys(N.color),Ei=Object.keys(N.bgColor);[...bi,...Ei];function ki(){const r=new Map;for(const[e,t]of Object.entries(N)){for(const[n,o]of Object.entries(t))N[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},t[n]=N[n],r.set(o[0],o[1]);Object.defineProperty(N,e,{value:t,enumerable:!1})}return Object.defineProperty(N,"codes",{value:r,enumerable:!1}),N.color.close="\x1B[39m",N.bgColor.close="\x1B[49m",N.color.ansi=An(),N.color.ansi256=xn(),N.color.ansi16m=In(),N.bgColor.ansi=An(Sr),N.bgColor.ansi256=xn(Sr),N.bgColor.ansi16m=In(Sr),Object.defineProperties(N,{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(s=>s+s).join(""));const o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>N.rgbToAnsi256(...N.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,o;if(e>=232)t=((e-232)*10+8)/255,n=t,o=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,n=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(t,n,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(t));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>N.ansi256ToAnsi(N.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>N.ansi256ToAnsi(N.hexToAnsi256(e)),enumerable:!1}}),N}const ye=ki(),Kt=(()=>{if(navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Tn=Kt!==0&&{level:Kt,hasBasic:!0,has256:Kt>=2,has16m:Kt>=3},Ci={stdout:Tn,stderr:Tn};function Si(r,e,t){let n=r.indexOf(e);if(n===-1)return r;const o=e.length;let s=0,i="";do i+=r.slice(s,n)+e+t,s=n+o,n=r.indexOf(e,s);while(n!==-1);return i+=r.slice(s),i}function Pi(r,e,t,n){let o=0,s="";do{const i=r[n-1]==="\r";s+=r.slice(o,i?n-1:n)+e+(i?`\r
|
|
1
|
+
(function(ke,Fe){typeof exports=="object"&&typeof module<"u"?Fe(exports):typeof define=="function"&&define.amd?define(["exports"],Fe):(ke=typeof globalThis<"u"?globalThis:ke||self,Fe(ke.OpenPay={}))})(this,function(ke){"use strict";const Fe="https://cde.getopenpay.com";var R;(function(t){t.assertEqual=o=>o;function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},t.getValidEnumValues=o=>{const s=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(const c of s)i[c]=o[c];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(const i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(R||(R={}));var gn;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(gn||(gn={}));const v=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ie=t=>{switch(typeof t){case"undefined":return v.undefined;case"string":return v.string;case"number":return isNaN(t)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(t)?v.array:t===null?v.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?v.promise:typeof Map<"u"&&t instanceof Map?v.map:typeof Set<"u"&&t instanceof Set?v.set:typeof Date<"u"&&t instanceof Date?v.date:v.object;default:return v.unknown}},y=R.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"]),$o=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class ee extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let c=r,l=0;for(;l<i.path.length;){const u=i.path[l];l===i.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(i))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}};return o(this),r}static assert(e){if(!(e instanceof ee))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}ee.create=t=>new ee(t);const He=(t,e)=>{let n;switch(t.code){case y.invalid_type:t.received===v.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,R.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:n=`Unrecognized key(s) in object: ${R.joinValues(t.keys,", ")}`;break;case y.invalid_union:n="Invalid input";break;case y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${R.joinValues(t.options)}`;break;case y.invalid_enum_value:n=`Invalid enum value. Expected ${R.joinValues(t.options)}, received '${t.received}'`;break;case y.invalid_arguments:n="Invalid function arguments";break;case y.invalid_return_type:n="Invalid function return type";break;case y.invalid_date:n="Invalid date";break;case y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:R.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case y.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case y.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case y.custom:n="Invalid input";break;case y.invalid_intersection_types:n="Intersection results could not be merged";break;case y.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case y.not_finite:n="Number must be finite";break;default:n=e.defaultError,R.assertNever(t)}return{message:n}};let Yn=He;function Zo(t){Yn=t}function Zt(){return Yn}const Vt=t=>{const{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)c=u(i,{data:e,defaultError:c}).message;return{...o,path:s,message:c}},Vo=[];function g(t,e){const n=Zt(),r=Vt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===He?void 0:He].filter(o=>!!o)});t.common.issues.push(r)}class W{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const o of n){if(o.status==="aborted")return S;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const o of n){const s=await o.key,i=await o.value;r.push({key:s,value:i})}return W.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const o of n){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return S;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}}const S=Object.freeze({status:"aborted"}),Ke=t=>({status:"dirty",value:t}),K=t=>({status:"valid",value:t}),vn=t=>t.status==="aborted",wn=t=>t.status==="dirty",ut=t=>t.status==="valid",dt=t=>typeof Promise<"u"&&t instanceof Promise;function zt(t,e,n,r){if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function Wn(t,e,n,r,o){if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}typeof SuppressedError=="function"&&SuppressedError;var w;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(w||(w={}));var pt,ft;class pe{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}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 Hn=(t,e)=>{if(ut(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new ee(t.common.issues);return this._error=n,this._error}}};function A(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,c)=>{var l,u;const{message:d}=t;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(l=d??r)!==null&&l!==void 0?l:c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:(u=d??n)!==null&&u!==void 0?u:c.defaultError}},description:o}}class T{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,n){return n||{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 W,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 n=this._parse(e);if(dt(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ie(e)},s=this._parseSync({data:e,path:o.path,parent:o});return Hn(o,s)}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ie(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(dt(o)?o:Promise.resolve(o));return Hn(r,s)}refine(e,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const i=e(o),c=()=>s.addIssue({code:y.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new se({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return me.create(this,this._def)}nullable(){return Me.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this,this._def)}promise(){return et.create(this,this._def)}or(e){return _t.create([this,e],this._def)}and(e){return gt.create(this,e,this._def)}transform(e){return new se({...A(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new kt({...A(this._def),innerType:this,defaultValue:n,typeName:k.ZodDefault})}brand(){return new kn({typeName:k.ZodBranded,type:this,...A(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Ct({...A(this._def),innerType:this,catchValue:n,typeName:k.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return St.create(this,e)}readonly(){return Pt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const zo=/^c[^\s-]{8,}$/i,Go=/^[0-9a-z]+$/,Bo=/^[0-9A-HJKMNP-TV-Z]{26}$/,qo=/^[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,Yo=/^[a-z0-9_-]{21}$/i,Wo=/^[-+]?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)?)??$/,Ho=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ko="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let bn;const Jo=/^(?:(?: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])$/,Qo=/^(([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})))$/,Xo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Kn="((\\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])))",es=new RegExp(`^${Kn}$`);function Jn(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function ts(t){return new RegExp(`^${Jn(t)}$`)}function Qn(t){let e=`${Kn}T${Jn(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function ns(t,e){return!!((e==="v4"||!e)&&Jo.test(t)||(e==="v6"||!e)&&Qo.test(t))}class re extends T{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==v.string){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.string,received:s.parsedType}),S}const r=new W;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,c=e.data.length<s.value;(i||c)&&(o=this._getOrReturnCtx(e,o),i?g(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&g(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Ho.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"email",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")bn||(bn=new RegExp(Ko,"u")),bn.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"emoji",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")qo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"uuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Yo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")zo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Go.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Bo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ulid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),g(o,{validation:"url",code:y.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"regex",code:y.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Qn(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?es.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?ts(s).test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{code:y.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Wo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"duration",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?ns(e.data,s.version)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"ip",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Xo.test(e.data)||(o=this._getOrReturnCtx(e,o),g(o,{validation:"base64",code:y.invalid_string,message:s.message}),r.dirty()):R.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:y.invalid_string,...w.errToObj(r)})}_addCheck(e){return new re({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...w.errToObj(e)})}url(e){return this._addCheck({kind:"url",...w.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...w.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...w.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...w.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...w.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...w.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...w.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...w.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...w.errToObj(e)})}datetime(e){var n,r;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:(n=e==null?void 0:e.offset)!==null&&n!==void 0?n:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...w.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,...w.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...w.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...w.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...w.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...w.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...w.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...w.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...w.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...w.errToObj(n)})}nonempty(e){return this.min(1,w.errToObj(e))}trim(){return new re({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new re({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new re({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}re.create=t=>{var e;return new re({checks:[],typeName:k.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...A(t)})};function rs(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(t.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Re extends T{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)!==v.number){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.number,received:s.parsedType}),S}let r;const o=new W;for(const s of this._def.checks)s.kind==="int"?R.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?rs(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_finite,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,w.toString(n))}gt(e,n){return this.setLimit("min",e,!1,w.toString(n))}lte(e,n){return this.setLimit("max",e,!0,w.toString(n))}lt(e,n){return this.setLimit("max",e,!1,w.toString(n))}setLimit(e,n,r,o){return new Re({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:w.toString(o)}]})}_addCheck(e){return new Re({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:w.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:w.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Re.create=t=>new Re({checks:[],typeName:k.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...A(t)});class Ne extends T{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)!==v.bigint){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.bigint,received:s.parsedType}),S}let r;const o=new W;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),g(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):R.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,w.toString(n))}gt(e,n){return this.setLimit("min",e,!1,w.toString(n))}lte(e,n){return this.setLimit("max",e,!0,w.toString(n))}lt(e,n){return this.setLimit("max",e,!1,w.toString(n))}setLimit(e,n,r,o){return new Ne({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:w.toString(o)}]})}_addCheck(e){return new Ne({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Ne.create=t=>{var e;return new Ne({checks:[],typeName:k.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...A(t)})};class mt extends T{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==v.boolean){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.boolean,received:r.parsedType}),S}return K(e.data)}}mt.create=t=>new mt({typeName:k.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...A(t)});class Ue extends T{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==v.date){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_type,expected:v.date,received:s.parsedType}),S}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return g(s,{code:y.invalid_date}),S}const r=new W;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),g(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):R.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ue({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:w.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:w.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Ue.create=t=>new Ue({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:k.ZodDate,...A(t)});class Gt extends T{_parse(e){if(this._getType(e)!==v.symbol){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.symbol,received:r.parsedType}),S}return K(e.data)}}Gt.create=t=>new Gt({typeName:k.ZodSymbol,...A(t)});class ht extends T{_parse(e){if(this._getType(e)!==v.undefined){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.undefined,received:r.parsedType}),S}return K(e.data)}}ht.create=t=>new ht({typeName:k.ZodUndefined,...A(t)});class yt extends T{_parse(e){if(this._getType(e)!==v.null){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.null,received:r.parsedType}),S}return K(e.data)}}yt.create=t=>new yt({typeName:k.ZodNull,...A(t)});class Je extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return K(e.data)}}Je.create=t=>new Je({typeName:k.ZodAny,...A(t)});class $e extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return K(e.data)}}$e.create=t=>new $e({typeName:k.ZodUnknown,...A(t)});class Ce extends T{_parse(e){const n=this._getOrReturnCtx(e);return g(n,{code:y.invalid_type,expected:v.never,received:n.parsedType}),S}}Ce.create=t=>new Ce({typeName:k.ZodNever,...A(t)});class Bt extends T{_parse(e){if(this._getType(e)!==v.undefined){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.void,received:r.parsedType}),S}return K(e.data)}}Bt.create=t=>new Bt({typeName:k.ZodVoid,...A(t)});class oe extends T{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==v.array)return g(n,{code:y.invalid_type,expected:v.array,received:n.parsedType}),S;if(o.exactLength!==null){const i=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(i||c)&&(g(n,{code:i?y.too_big:y.too_small,minimum:c?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(g(n,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(g(n,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,c)=>o.type._parseAsync(new pe(n,i,n.path,c)))).then(i=>W.mergeArray(r,i));const s=[...n.data].map((i,c)=>o.type._parseSync(new pe(n,i,n.path,c)));return W.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new oe({...this._def,minLength:{value:e,message:w.toString(n)}})}max(e,n){return new oe({...this._def,maxLength:{value:e,message:w.toString(n)}})}length(e,n){return new oe({...this._def,exactLength:{value:e,message:w.toString(n)}})}nonempty(e){return this.min(1,e)}}oe.create=(t,e)=>new oe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...A(e)});function Qe(t){if(t instanceof L){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=me.create(Qe(r))}return new L({...t._def,shape:()=>e})}else return t instanceof oe?new oe({...t._def,type:Qe(t.element)}):t instanceof me?me.create(Qe(t.unwrap())):t instanceof Me?Me.create(Qe(t.unwrap())):t instanceof fe?fe.create(t.items.map(e=>Qe(e))):t}class L extends T{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(),n=R.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==v.object){const u=this._getOrReturnCtx(e);return g(u,{code:y.invalid_type,expected:v.object,received:u.parsedType}),S}const{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Ce&&this._def.unknownKeys==="strip"))for(const u in o.data)i.includes(u)||c.push(u);const l=[];for(const u of i){const d=s[u],p=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new pe(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Ce){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")c.length>0&&(g(o,{code:y.unrecognized_keys,keys:c}),r.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 p=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new pe(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const p=await d.key,_=await d.value;u.push({key:p,value:_,alwaysSet:d.alwaysSet})}return u}).then(u=>W.mergeObjectSync(r,u)):W.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return w.errToObj,new L({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var o,s,i,c;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=w.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new L({...this._def,unknownKeys:"strip"})}passthrough(){return new L({...this._def,unknownKeys:"passthrough"})}extend(e){return new L({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new L({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new L({...this._def,catchall:e})}pick(e){const n={};return R.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new L({...this._def,shape:()=>n})}omit(e){const n={};return R.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new L({...this._def,shape:()=>n})}deepPartial(){return Qe(this)}partial(e){const n={};return R.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}),new L({...this._def,shape:()=>n})}required(e){const n={};return R.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof me;)s=s._def.innerType;n[r]=s}}),new L({...this._def,shape:()=>n})}keyof(){return Xn(R.objectKeys(this.shape))}}L.create=(t,e)=>new L({shape:()=>t,unknownKeys:"strip",catchall:Ce.create(),typeName:k.ZodObject,...A(e)}),L.strictCreate=(t,e)=>new L({shape:()=>t,unknownKeys:"strict",catchall:Ce.create(),typeName:k.ZodObject,...A(e)}),L.lazycreate=(t,e)=>new L({shape:t,unknownKeys:"strip",catchall:Ce.create(),typeName:k.ZodObject,...A(e)});class _t extends T{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const i=s.map(c=>new ee(c.ctx.common.issues));return g(n,{code:y.invalid_union,unionErrors:i}),S}if(n.common.async)return Promise.all(r.map(async s=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of r){const u={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=i.map(l=>new ee(l));return g(n,{code:y.invalid_union,unionErrors:c}),S}}get options(){return this._def.options}}_t.create=(t,e)=>new _t({options:t,typeName:k.ZodUnion,...A(e)});const Se=t=>t instanceof wt?Se(t.schema):t instanceof se?Se(t.innerType()):t instanceof bt?[t.value]:t instanceof Oe?t.options:t instanceof Et?R.objectValues(t.enum):t instanceof kt?Se(t._def.innerType):t instanceof ht?[void 0]:t instanceof yt?[null]:t instanceof me?[void 0,...Se(t.unwrap())]:t instanceof Me?[null,...Se(t.unwrap())]:t instanceof kn||t instanceof Pt?Se(t.unwrap()):t instanceof Ct?Se(t._def.innerType):[];class qt extends T{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==v.object)return g(n,{code:y.invalid_type,expected:v.object,received:n.parsedType}),S;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(g(n,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const o=new Map;for(const s of n){const i=Se(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of i){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,s)}}return new qt({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...A(r)})}}function En(t,e){const n=Ie(t),r=Ie(e);if(t===e)return{valid:!0,data:t};if(n===v.object&&r===v.object){const o=R.objectKeys(e),s=R.objectKeys(t).filter(c=>o.indexOf(c)!==-1),i={...t,...e};for(const c of s){const l=En(t[c],e[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}else if(n===v.array&&r===v.array){if(t.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<t.length;s++){const i=t[s],c=e[s],l=En(i,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===v.date&&r===v.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class gt extends T{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(vn(s)||vn(i))return S;const c=En(s.value,i.value);return c.valid?((wn(s)||wn(i))&&n.dirty(),{status:n.value,value:c.data}):(g(r,{code:y.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}gt.create=(t,e,n)=>new gt({left:t,right:e,typeName:k.ZodIntersection,...A(n)});class fe extends T{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.array)return g(r,{code:y.invalid_type,expected:v.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return g(r,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(g(r,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new pe(r,i,r.path,c)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>W.mergeArray(n,i)):W.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new fe({...this._def,rest:e})}}fe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fe({items:t,typeName:k.ZodTuple,rest:null,...A(e)})};class vt extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.object)return g(r,{code:y.invalid_type,expected:v.object,received:r.parsedType}),S;const o=[],s=this._def.keyType,i=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new pe(r,c,r.path,c)),value:i._parse(new pe(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?W.mergeObjectAsync(n,o):W.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof T?new vt({keyType:e,valueType:n,typeName:k.ZodRecord,...A(r)}):new vt({keyType:re.create(),valueType:e,typeName:k.ZodRecord,...A(n)})}}class Yt extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.map)return g(r,{code:y.invalid_type,expected:v.map,received:r.parsedType}),S;const o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([c,l],u)=>({key:o._parse(new pe(r,c,r.path,[u,"key"])),value:s._parse(new pe(r,l,r.path,[u,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of i){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return S;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}}}}Yt.create=(t,e,n)=>new Yt({valueType:e,keyType:t,typeName:k.ZodMap,...A(n)});class Ze extends T{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==v.set)return g(r,{code:y.invalid_type,expected:v.set,received:r.parsedType}),S;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(g(r,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(g(r,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function i(l){const u=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&n.dirty(),u.add(d.value)}return{status:n.value,value:u}}const c=[...r.data.values()].map((l,u)=>s._parse(new pe(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(e,n){return new Ze({...this._def,minSize:{value:e,message:w.toString(n)}})}max(e,n){return new Ze({...this._def,maxSize:{value:e,message:w.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Ze.create=(t,e)=>new Ze({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...A(e)});class Xe extends T{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==v.function)return g(n,{code:y.invalid_type,expected:v.function,received:n.parsedType}),S;function r(c,l){return Vt({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zt(),He].filter(u=>!!u),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(c,l){return Vt({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zt(),He].filter(u=>!!u),issueData:{code:y.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof et){const c=this;return K(async function(...l){const u=new ee([]),d=await c._def.args.parseAsync(l,s).catch(f=>{throw u.addIssue(r(l,f)),u}),p=await Reflect.apply(i,this,d);return await c._def.returns._def.type.parseAsync(p,s).catch(f=>{throw u.addIssue(o(p,f)),u})})}else{const c=this;return K(function(...l){const u=c._def.args.safeParse(l,s);if(!u.success)throw new ee([r(l,u.error)]);const d=Reflect.apply(i,this,u.data),p=c._def.returns.safeParse(d,s);if(!p.success)throw new ee([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Xe({...this._def,args:fe.create(e).rest($e.create())})}returns(e){return new Xe({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new Xe({args:e||fe.create([]).rest($e.create()),returns:n||$e.create(),typeName:k.ZodFunction,...A(r)})}}class wt extends T{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}wt.create=(t,e)=>new wt({getter:t,typeName:k.ZodLazy,...A(e)});class bt extends T{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return g(n,{received:n.data,code:y.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}bt.create=(t,e)=>new bt({value:t,typeName:k.ZodLiteral,...A(e)});function Xn(t,e){return new Oe({values:t,typeName:k.ZodEnum,...A(e)})}class Oe extends T{constructor(){super(...arguments),pt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return g(n,{expected:R.joinValues(r),received:n.parsedType,code:y.invalid_type}),S}if(zt(this,pt)||Wn(this,pt,new Set(this._def.values)),!zt(this,pt).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return g(n,{received:n.data,code:y.invalid_enum_value,options:r}),S}return K(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Oe.create(e,{...this._def,...n})}exclude(e,n=this._def){return Oe.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}pt=new WeakMap,Oe.create=Xn;class Et extends T{constructor(){super(...arguments),ft.set(this,void 0)}_parse(e){const n=R.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==v.string&&r.parsedType!==v.number){const o=R.objectValues(n);return g(r,{expected:R.joinValues(o),received:r.parsedType,code:y.invalid_type}),S}if(zt(this,ft)||Wn(this,ft,new Set(R.getValidEnumValues(this._def.values))),!zt(this,ft).has(e.data)){const o=R.objectValues(n);return g(r,{received:r.data,code:y.invalid_enum_value,options:o}),S}return K(e.data)}get enum(){return this._def.values}}ft=new WeakMap,Et.create=(t,e)=>new Et({values:t,typeName:k.ZodNativeEnum,...A(e)});class et extends T{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==v.promise&&n.common.async===!1)return g(n,{code:y.invalid_type,expected:v.promise,received:n.parsedType}),S;const r=n.parsedType===v.promise?n.data:Promise.resolve(n.data);return K(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}et.create=(t,e)=>new et({type:t,typeName:k.ZodPromise,...A(e)});class se extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{g(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async c=>{if(n.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?S:l.status==="dirty"||n.value==="dirty"?Ke(l.value):l});{if(n.value==="aborted")return S;const c=this._def.schema._parseSync({data:i,path:r.path,parent:r});return c.status==="aborted"?S:c.status==="dirty"||n.value==="dirty"?Ke(c.value):c}}if(o.type==="refinement"){const i=c=>{const l=o.refinement(c,s);if(r.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(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?S:(c.status==="dirty"&&n.dirty(),i(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?S:(c.status==="dirty"&&n.dirty(),i(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ut(i))return i;const c=o.transform(i.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ut(i)?Promise.resolve(o.transform(i.value,s)).then(c=>({status:n.value,value:c})):i);R.assertNever(o)}}se.create=(t,e,n)=>new se({schema:t,typeName:k.ZodEffects,effect:e,...A(n)}),se.createWithPreprocess=(t,e,n)=>new se({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...A(n)});class me extends T{_parse(e){return this._getType(e)===v.undefined?K(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}me.create=(t,e)=>new me({innerType:t,typeName:k.ZodOptional,...A(e)});class Me extends T{_parse(e){return this._getType(e)===v.null?K(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Me.create=(t,e)=>new Me({innerType:t,typeName:k.ZodNullable,...A(e)});class kt extends T{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===v.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}kt.create=(t,e)=>new kt({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...A(e)});class Ct extends T{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return dt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ee(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ee(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ct.create=(t,e)=>new Ct({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...A(e)});class Wt extends T{_parse(e){if(this._getType(e)!==v.nan){const r=this._getOrReturnCtx(e);return g(r,{code:y.invalid_type,expected:v.nan,received:r.parsedType}),S}return{status:"valid",value:e.data}}}Wt.create=t=>new Wt({typeName:k.ZodNaN,...A(t)});const os=Symbol("zod_brand");class kn extends T{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class St extends T{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S:s.status==="dirty"?(n.dirty(),Ke(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?S:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new St({in:e,out:n,typeName:k.ZodPipeline})}}class Pt extends T{_parse(e){const n=this._def.innerType._parse(e),r=o=>(ut(o)&&(o.value=Object.freeze(o.value)),o);return dt(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Pt.create=(t,e)=>new Pt({innerType:t,typeName:k.ZodReadonly,...A(e)});function er(t,e={},n){return t?Je.create().superRefine((r,o)=>{var s,i;if(!t(r)){const c=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,l=(i=(s=c.fatal)!==null&&s!==void 0?s:n)!==null&&i!==void 0?i:!0,u=typeof c=="string"?{message:c}:c;o.addIssue({code:"custom",...u,fatal:l})}}):Je.create()}const ss={object:L.lazycreate};var k;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(k||(k={}));const as=(t,e={message:`Input not instance of ${t.name}`})=>er(n=>n instanceof t,e),tr=re.create,nr=Re.create,is=Wt.create,cs=Ne.create,rr=mt.create,ls=Ue.create,us=Gt.create,ds=ht.create,ps=yt.create,fs=Je.create,ms=$e.create,hs=Ce.create,ys=Bt.create,_s=oe.create,gs=L.create,vs=L.strictCreate,ws=_t.create,bs=qt.create,Es=gt.create,ks=fe.create,Cs=vt.create,Ss=Yt.create,Ps=Ze.create,As=Xe.create,Ts=wt.create,xs=bt.create,Is=Oe.create,Rs=Et.create,Ns=et.create,or=se.create,Os=me.create,Ms=Me.create,Ds=se.createWithPreprocess,Ls=St.create;var a=Object.freeze({__proto__:null,defaultErrorMap:He,setErrorMap:Zo,getErrorMap:Zt,makeIssue:Vt,EMPTY_PATH:Vo,addIssueToContext:g,ParseStatus:W,INVALID:S,DIRTY:Ke,OK:K,isAborted:vn,isDirty:wn,isValid:ut,isAsync:dt,get util(){return R},get objectUtil(){return gn},ZodParsedType:v,getParsedType:Ie,ZodType:T,datetimeRegex:Qn,ZodString:re,ZodNumber:Re,ZodBigInt:Ne,ZodBoolean:mt,ZodDate:Ue,ZodSymbol:Gt,ZodUndefined:ht,ZodNull:yt,ZodAny:Je,ZodUnknown:$e,ZodNever:Ce,ZodVoid:Bt,ZodArray:oe,ZodObject:L,ZodUnion:_t,ZodDiscriminatedUnion:qt,ZodIntersection:gt,ZodTuple:fe,ZodRecord:vt,ZodMap:Yt,ZodSet:Ze,ZodFunction:Xe,ZodLazy:wt,ZodLiteral:bt,ZodEnum:Oe,ZodNativeEnum:Et,ZodPromise:et,ZodEffects:se,ZodTransformer:se,ZodOptional:me,ZodNullable:Me,ZodDefault:kt,ZodCatch:Ct,ZodNaN:Wt,BRAND:os,ZodBranded:kn,ZodPipeline:St,ZodReadonly:Pt,custom:er,Schema:T,ZodSchema:T,late:ss,get ZodFirstPartyTypeKind(){return k},coerce:{string:t=>re.create({...t,coerce:!0}),number:t=>Re.create({...t,coerce:!0}),boolean:t=>mt.create({...t,coerce:!0}),bigint:t=>Ne.create({...t,coerce:!0}),date:t=>Ue.create({...t,coerce:!0})},any:fs,array:_s,bigint:cs,boolean:rr,date:ls,discriminatedUnion:bs,effect:or,enum:Is,function:As,instanceof:as,intersection:Es,lazy:Ts,literal:xs,map:Ss,nan:is,nativeEnum:Rs,never:hs,null:ps,nullable:Ms,number:nr,object:gs,oboolean:()=>rr().optional(),onumber:()=>nr().optional(),optional:Os,ostring:()=>tr().optional(),pipeline:Ls,preprocess:Ds,promise:Ns,record:Cs,set:Ps,strictObject:vs,string:tr,symbol:us,transformer:or,tuple:ks,undefined:ds,union:ws,unknown:ms,void:ys,NEVER:S,ZodIssueCode:y,quotelessJson:$o,ZodError:ee});const js=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()}),Fs=a.array(js),Us=a.object({code:a.string(),message:a.string(),path:a.array(a.string())}),$s=a.array(Us),Zs={"failed to fetch":"Connection error: please double check if you are connected to the internet, then try again"},Cn=t=>{const e=t.toLowerCase().trim();return Zs[e]??t},Vs=t=>{try{return typeof JSON.parse(t)=="object"}catch{return!1}},zs=t=>t.length===1?Cn(t[0].msg):`Please fix the following errors:
|
|
2
|
+
${t.map(n=>`• ${Cn(n.msg)}`).join(`
|
|
3
|
+
`)}`,Gs=t=>`Encountered the following errors:
|
|
4
|
+
${t.map(n=>`- ${n.path.join("/")}: ${n.message}`).join(`
|
|
5
|
+
`)}`,ne=t=>{if(t instanceof Error)if(Vs(t.message)){const e=JSON.parse(t.message);return Fs.safeParse(e).success?zs(e):$s.safeParse(e).success?Gs(e):(console.warn(`Encountered unknown stringified JSON object:
|
|
6
|
+
${t.message}`),t.message)}else return Cn(t.message);if(typeof t=="object")try{return JSON.stringify(t)}catch(e){return e+""}else return t+""},Bs=(t,e,n)=>(...r)=>{try{return e(...r)}catch(o){n(`[form] Error running callback (${t}):`,o);return}};var te=(t=>(t.pockytPaypal="pockyt-paypal",t.airwallexGooglePay="airwallex-google-pay",t.airwallexApplePay="airwallex-apple-pay",t.authorizenetGooglePay="authorizenet-google-pay",t.authorizenetApplePay="authorizenet-apple-pay",t.loopCrypto="loop-crypto",t))(te||{});const qs=a.nativeEnum(te),$=a.string().trim().min(1,{message:"Cannot be blank"}),j=a.string().trim().optional(),J=t=>a.nullable(t.optional());var m=(t=>(t.FIRST_NAME="firstName",t.LAST_NAME="lastName",t.EMAIL="email",t.ZIP_CODE="zipCode",t.CITY="city",t.STATE="state",t.COUNTRY="country",t.ADDRESS="address",t.PHONE="phone",t.PROMOTION_CODE="promotionCode",t))(m||{});const sr=a.nativeEnum(m);var ar=(t=>(t.CARD_NUMBER="cardNumber",t.CARD_EXPIRY="cardExpiry",t.CARD_CVC="cardCvc",t))(ar||{});const ir=a.nativeEnum(ar),cr=a.union([sr,ir]);var he=(t=>(t.CARD="card",t.CARD_NUMBER="card-number",t.CARD_EXPIRY="card-expiry",t.CARD_CVC="card-cvc",t.CDE_BRIDGE="cde-bridge",t))(he||{});const Ys=a.nativeEnum(he),Ht=a.object({provider:a.string(),processor_name:J(a.string()),metadata:J(a.record(a.string(),a.any()))}),Ws=a.object({id:a.string()});a.object({cardNumber:j,expiry:j,cvc:j}),a.object({backgroundColor:j,color:j,fontFamily:j,fontSize:j,fontWeight:j,margin:j,padding:j,letterSpacing:j,lineHeight:j,hideIcon:j});const ae=a.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"]),Hs=ae.extract(["TOKENIZE_STARTED","CHECKOUT_STARTED"]),Ks=a.object({type:Hs}),Js=ae.extract(["BLUR","FOCUS","CHANGE"]),Qs=a.object({type:Js,elementType:ir,errors:a.array(a.string()).optional()}),Xs=ae.extract(["LOAD_ERROR","TOKENIZE_ERROR","CHECKOUT_ERROR"]),ea=a.object({type:Xs,message:$,headers:a.record(a.string(),a.string()).optional()}),ta=ae.extract(["VALIDATION_ERROR"]),na=a.object({type:ta,elementType:cr,errors:a.array(a.string())}),ra=a.object({type:a.literal(ae.enum.LAYOUT),height:$}),oa=a.object({type:a.literal(ae.enum.LOADED),sessionId:$,totalAmountAtoms:a.number(),currency:j,checkoutPaymentMethods:a.array(Ht)}),sa=a.object({type:a.literal(ae.enum.PAYMENT_FLOW_STARTED),nextActionMetadata:a.record(a.string(),a.any()),paymentFlowMetadata:a.any().optional(),startPFMetadata:a.optional(a.record(a.string(),a.any()))}),aa=a.object({type:a.literal(ae.enum.SETUP_PAYMENT_METHOD_SUCCESS),paymentMethodId:a.string()}),At=a.object({firstName:$,lastName:$,email:$,zipCode:$,country:$,promotionCode:j}),ia=a.object({firstName:j,lastName:j,email:$,zipCode:$,country:$,promotionCode:j,address:j,city:j,state:j}),ca=ae.extract(["TOKENIZE","CHECKOUT","START_PAYMENT_FLOW"]),la=a.object({type:ca,sessionId:$,checkoutPaymentMethod:Ht,paymentFlowMetadata:a.any().optional(),doNotUseLegacyCCFlow:a.boolean().optional(),existingCCPMId:j}).extend(At.shape),ua=a.object({type:a.literal(ae.enum.TOKENIZE_SUCCESS),isReadyForCheckout:a.boolean()}),da=a.object({type:a.literal(ae.enum.CHECKOUT_SUCCESS),invoiceUrls:a.array(a.string()),subscriptionIds:a.array(a.string()),customerId:a.string()}),pa=a.discriminatedUnion("type",[Ks,Qs,ea,na,ra,oa,la,ua,da,sa,aa]),fa=a.object({payload:pa,nonce:$,formId:$,elementId:$});a.object({amountAtom:a.number(),currency:$}),a.enum(["apple_pay","google_pay"]),a.object({secure_token:a.string(),promotion_code:a.string().optional()}),a.object({secure_token:a.string(),existing_cc_pm_id:J(a.string()),their_pm_id:J(a.string()),checkout_attempt_id:J(a.string()),processor_specific_metadata:J(a.record(a.string(),a.any()))});const Sn=a.object({invoice_urls:a.array(a.string()),subscription_ids:a.array(a.string()),customer_id:a.string(),processors_used:J(a.array(a.string()))}),ma=a.object({elementType:a.string(),errors:a.array(a.string())});a.object({session_id:a.string()});const ha=a.object({success:a.literal(!1),error_type:a.literal("validation_error"),errors:a.array(ma)}),ya=a.discriminatedUnion("success",[a.object({success:a.literal(!0)}),ha]);a.object({session_id:a.string(),checkout_payment_method:Ht,non_cde_form_fields:At,do_not_use_legacy_cc_flow:a.boolean().optional(),existing_cc_pm_id:J(a.string()),extra_metadata:a.record(a.string(),a.any())}),a.object({session_id:a.string(),checkout_payment_method:Ht,non_cde_form_fields:At,extra_metadata:a.record(a.string(),a.any()).optional()});var Z=(t=>(t.SUCCESS="success",t.FAILURE="failure",t.CANCELLED="cancelled",t))(Z||{});const _a=a.object({status:a.enum(["success","failure","cancelled"]),href:a.string().optional().nullable()});a.object({href:a.string().optional().nullable()});const ga=a.object({type:a.string(),redirect_url:a.string(),initial_intent_id:a.string(),consent_id:a.string(),their_pm_id:a.string().optional()}),lr=a.object({type:a.string(),redirect_url:J(a.string()),initial_intent_id:J(a.string()),consent_id:J(a.string()),their_pm_id:J(a.string()),payment_session:J(a.record(a.string(),a.any()))}),va=a.discriminatedUnion("present",[a.object({present:a.literal(!0),href:a.string()}),a.object({present:a.literal(!1)})]),wa=a.object({payment_methods:a.array(Ws),pay_first_success_response:J(Sn),required_user_actions:J(a.array(lr))}),ur=t=>{const e={};return Object.entries(t).forEach(([n,r])=>{try{const o=sr.parse(n);Array.isArray(r)?e[o]=r:Array.isArray(r._errors)&&(e[o]=r._errors)}catch{return}}),e},ba=a.object({stripe_pk:a.string(),client_secret:a.string(),stripe_pm_id:a.string()}),Ea=a.object({type:a.string(),client_secret:a.string(),stripe_pk:a.string()}),ka={usd:"usd",brl:"brl"},Kt=async t=>{for(let n=0;n<10;n++)dr()||await Pn(500);if(!dr())throw console.log("Stripe JS not found."),new Error("Stripe JS not found.");return new Stripe(t)},Ca=async(t,e)=>{const n=await Kt(t);return{elements:n.elements(e),stripe:n}},Sa=async(t,e,n,r,o)=>{const s=await Kt(t),i=ka[n.toLowerCase().trim()];return s.paymentRequest({country:"US",currency:i,total:{label:"Total",amount:e,pending:r},requestPayerName:!0,requestPayerEmail:!0,disableWallets:[]})},Pn=t=>new Promise(e=>{setTimeout(e,t)}),dr=()=>"Stripe"in window,Pa=async t=>new Promise((e,n)=>{try{t.on("paymentmethod",async r=>{console.log("paymentmethod EVT:: ",r),e(r)}),t.on("token",async r=>{console.log("token EVT:: ",r)}),t.on("cancel",()=>{n(new Error("Payment cancelled, please click Submit again to pay"))})}catch(r){n(r)}}),Aa=async(t,e)=>{if(!t.stripe_pk||!t.client_secret)throw new Error(`Invalid next action metadata format: ${JSON.stringify(t)}`);const r=await(await Kt(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:e.paymentMethod.id});if(r.error)throw e.complete("fail"),new Error(`Payment failed: ${r.error.message??"unknown"}`);return e.complete("success"),r},Ta=async t=>{var o,s,i,c;const n=await(await Kt(t.stripe_pk)).confirmCardSetup(t.client_secret,{payment_method:t.stripe_pm_id}),r=(o=n.setupIntent)==null?void 0:o.status;if(r==="succeeded")console.log("[3DS] CONFIRMING PM:",t.stripe_pm_id),console.log("[3DS] Setup intent created:",n.setupIntent);else throw r==="canceled"?new Error("Payment cancelled, please click Submit again to pay"):new Error(`${((s=n.error)==null?void 0:s.message)??((c=(i=n.setupIntent)==null?void 0:i.last_setup_error)==null?void 0:c.message)??"Payment failed, please click submit again to pay."}`)},xa=t=>JSON.stringify(t);for(var z=[],An=0;An<256;++An)z.push((An+256).toString(16).slice(1));function Ia(t,e=0){return(z[t[e+0]]+z[t[e+1]]+z[t[e+2]]+z[t[e+3]]+"-"+z[t[e+4]]+z[t[e+5]]+"-"+z[t[e+6]]+z[t[e+7]]+"-"+z[t[e+8]]+z[t[e+9]]+"-"+z[t[e+10]]+z[t[e+11]]+z[t[e+12]]+z[t[e+13]]+z[t[e+14]]+z[t[e+15]]).toLowerCase()}var Jt,Ra=new Uint8Array(16);function Na(){if(!Jt&&(Jt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Jt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Jt(Ra)}var Oa=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const pr={randomUUID:Oa};function Qt(t,e,n){if(pr.randomUUID&&!e&&!t)return pr.randomUUID();t=t||{};var r=t.random||(t.rng||Na)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Ia(r)}const ye=(t,e)=>Array.from(t.querySelectorAll("[data-opid]")??[]).reduce((o,s)=>{const i=s.getAttribute("data-opid");return i?{...o,[i]:s.value}:o},{}),Ma=t=>{try{return fa.parse(t)}catch(e){throw console.error("Error parsing event payload:",t,e),e}};var _e;(function(t){t.Call="call",t.Reply="reply",t.Syn="syn",t.SynAck="synAck",t.Ack="ack"})(_e||(_e={}));var Ve;(function(t){t.Fulfilled="fulfilled",t.Rejected="rejected"})(Ve||(Ve={}));var Tt;(function(t){t.ConnectionDestroyed="ConnectionDestroyed",t.ConnectionTimeout="ConnectionTimeout",t.NoIframeSrc="NoIframeSrc"})(Tt||(Tt={}));var Tn;(function(t){t.DataCloneError="DataCloneError"})(Tn||(Tn={}));var De;(function(t){t.Message="message"})(De||(De={}));const Da=(t,e)=>{const n=[];let r=!1;return{destroy(o){r||(r=!0,e(`${t}: Destroying connection`),n.forEach(s=>{s(o)}))},onDestroy(o){r?o():n.push(o)}}},La=t=>(...e)=>{t&&console.log("[Penpal]",...e)},ja={"http:":"80","https:":"443"},Fa=/^(https?:)?\/\/([^/:]+)?(:(\d+))?/,Ua=["file:","data:"],$a=t=>{if(t&&Ua.find(c=>t.startsWith(c)))return"null";const e=document.location,n=Fa.exec(t);let r,o,s;n?(r=n[1]?n[1]:e.protocol,o=n[2],s=n[4]):(r=e.protocol,o=e.hostname,s=e.port);const i=s&&s!==ja[r]?`:${s}`:"";return`${r}//${o}${i}`},fr=({name:t,message:e,stack:n})=>({name:t,message:e,stack:n}),Za=t=>{const e=new Error;return Object.keys(t).forEach(n=>e[n]=t[n]),e},Va=(t,e,n)=>{const{localName:r,local:o,remote:s,originForSending:i,originForReceiving:c}=t;let l=!1;const u=d=>{if(d.source!==s||d.data.penpal!==_e.Call)return;if(c!=="*"&&d.origin!==c){n(`${r} received message from origin ${d.origin} which did not match expected origin ${c}`);return}const p=d.data,{methodName:_,args:f,id:h}=p;n(`${r}: Received ${_}() call`);const b=I=>E=>{if(n(`${r}: Sending ${_}() reply`),l){n(`${r}: Unable to send ${_}() reply due to destroyed connection`);return}const N={penpal:_e.Reply,id:h,resolution:I,returnValue:E};I===Ve.Rejected&&E instanceof Error&&(N.returnValue=fr(E),N.returnValueIsError=!0);try{s.postMessage(N,i)}catch(x){if(x.name===Tn.DataCloneError){const O={penpal:_e.Reply,id:h,resolution:Ve.Rejected,returnValue:fr(x),returnValueIsError:!0};s.postMessage(O,i)}throw x}};new Promise(I=>I(e[_].apply(e,f))).then(b(Ve.Fulfilled),b(Ve.Rejected))};return o.addEventListener(De.Message,u),()=>{l=!0,o.removeEventListener(De.Message,u)}};let za=0;const Ga=()=>++za,mr=".",hr=t=>t?t.split(mr):[],Ba=t=>t.join(mr),qa=(t,e)=>{const n=hr(e||"");return n.push(t),Ba(n)},Ya=(t,e,n)=>{const r=hr(e);return r.reduce((o,s,i)=>(typeof o[s]>"u"&&(o[s]={}),i===r.length-1&&(o[s]=n),o[s]),t),t},yr=(t,e)=>{const n={};return Object.keys(t).forEach(r=>{const o=t[r],s=qa(r,e);typeof o=="object"&&Object.assign(n,yr(o,s)),typeof o=="function"&&(n[s]=o)}),n},Wa=t=>{const e={};for(const n in t)Ya(e,n,t[n]);return e},Ha=(t,e,n,r,o)=>{const{localName:s,local:i,remote:c,originForSending:l,originForReceiving:u}=e;let d=!1;o(`${s}: Connecting call sender`);const p=f=>(...h)=>{o(`${s}: Sending ${f}() call`);let b;try{c.closed&&(b=!0)}catch{b=!0}if(b&&r(),d){const I=new Error(`Unable to send ${f}() call due to destroyed connection`);throw I.code=Tt.ConnectionDestroyed,I}return new Promise((I,E)=>{const N=Ga(),x=U=>{if(U.source!==c||U.data.penpal!==_e.Reply||U.data.id!==N)return;if(u!=="*"&&U.origin!==u){o(`${s} received message from origin ${U.origin} which did not match expected origin ${u}`);return}const Y=U.data;o(`${s}: Received ${f}() reply`),i.removeEventListener(De.Message,x);let Ee=Y.returnValue;Y.returnValueIsError&&(Ee=Za(Ee)),(Y.resolution===Ve.Fulfilled?I:E)(Ee)};i.addEventListener(De.Message,x);const O={penpal:_e.Call,id:N,methodName:f,args:h};c.postMessage(O,l)})},_=n.reduce((f,h)=>(f[h]=p(h),f),{});return Object.assign(t,Wa(_)),()=>{d=!0}},Ka=(t,e,n,r,o)=>{const{destroy:s,onDestroy:i}=r;let c,l;const u={};return d=>{if(e!=="*"&&d.origin!==e){o(`Parent: Handshake - Received ACK message from origin ${d.origin} which did not match expected origin ${e}`);return}o("Parent: Handshake - Received ACK");const p={localName:"Parent",local:window,remote:d.source,originForSending:n,originForReceiving:e};c&&c(),c=Va(p,t,o),i(c),l&&l.forEach(f=>{delete u[f]}),l=d.data.methodNames;const _=Ha(u,p,l,s,o);return i(_),u}},Ja=(t,e,n,r)=>o=>{if(!o.source)return;if(n!=="*"&&o.origin!==n){t(`Parent: Handshake - Received SYN message from origin ${o.origin} which did not match expected origin ${n}`);return}t("Parent: Handshake - Received SYN, responding with SYN-ACK");const s={penpal:_e.SynAck,methodNames:Object.keys(e)};o.source.postMessage(s,r)},Qa=6e4,Xa=(t,e)=>{const{destroy:n,onDestroy:r}=e,o=setInterval(()=>{t.isConnected||(clearInterval(o),n())},Qa);r(()=>{clearInterval(o)})},ei=(t,e)=>{let n;return t!==void 0&&(n=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${t}ms`);r.code=Tt.ConnectionTimeout,e(r)},t)),()=>{clearTimeout(n)}},ti=t=>{if(!t.src&&!t.srcdoc){const e=new Error("Iframe must have src or srcdoc property defined.");throw e.code=Tt.NoIframeSrc,e}},_r=t=>{let{iframe:e,methods:n={},childOrigin:r,timeout:o,debug:s=!1}=t;const i=La(s),c=Da("Parent",i),{onDestroy:l,destroy:u}=c;r||(ti(e),r=$a(e.src));const d=r==="null"?"*":r,p=yr(n),_=Ja(i,p,r,d),f=Ka(p,r,d,c,i);return{promise:new Promise((b,I)=>{const E=ei(o,u),N=x=>{if(!(x.source!==e.contentWindow||!x.data)){if(x.data.penpal===_e.Syn){_(x);return}if(x.data.penpal===_e.Ack){const O=f(x);O&&(E(),b(O));return}}};window.addEventListener(De.Message,N),i("Parent: Awaiting handshake"),Xa(e,c),l(x=>{window.removeEventListener(De.Message,N),x&&I(x)})}),destroy(){u()}}},ni=async t=>{if(typeof t!="object"||!t)return!1;try{const e={type:"ping"},n=await t.send(e);if(n!==!0)throw new Error(`Expected 'true' after ping, got ${JSON.stringify(n)}`);return!0}catch(e){return console.error("Invalid CDE connection check:",e),!1}},ri=(t,e)=>!!t&&e,P=t=>a.nullable(t.optional());a.string().trim().min(1,{message:"Cannot be blank"});const oi=a.object({cde_response_type:a.literal("error"),message:a.string(),headers:a.record(a.string(),a.string()).optional()});a.enum(["usd","brl"]);const gr=a.object({name:a.string(),amount_atom_off:P(a.number()),percent_off:P(a.number()),currency:P(a.string()),duration:a.string(),duration_in_months:P(a.number())}),vr=a.object({amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),currency:a.string(),description:P(a.string()),price_id:a.string(),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),quantity:a.number().int()}),si=a.record(a.string(),a.any()),ai=a.object({name:a.string(),settings:P(si)}),tt=a.object({provider:a.string(),processor_name:P(a.string()),metadata:P(a.record(a.string(),a.any()))}),ii=a.object({quantity:a.number()}),ci=a.object({id:P(a.string()),billing_interval:P(a.string()),billing_interval_count:P(a.number().int()),subscription_items:a.array(ii),trial_start:P(a.string()),trial_end:P(a.string())}),wr=a.object({amount_atom:a.number()}),li=a.object({amount_atom:a.number(),amount_atom_considering_discount_applied:a.number(),currency:a.string(),discount_amount_atoms:a.array(wr),subscription_item_id:a.string()}),ui=a.object({coupon:gr}),di=a.object({currency:a.string(),discounts:a.array(ui),hosted_invoice_url:P(a.string()),lines:a.array(li),remaining_amount_atom:a.number(),tax_amount_atom:a.number(),total_amount_atom:a.number(),total_discount_amount_atoms:a.array(wr)}),br=a.object({created:a.array(ci),invoices:a.array(di),processors_used:P(a.array(a.string()))}),Er=a.object({preview:br,preview_post_trial:P(br),coupons:a.array(gr)}),kr=a.object({status:a.literal("open"),locale:P(a.string()),token:a.string(),email:P(a.string()),line_items:a.array(vr),amount_subtotal_atom:a.number().int(),amount_total_atom:a.number().int(),brand:ai,subs_preview:P(Er),methods_available:a.array(tt)}),Cr=a.discriminatedUnion("mode",[a.object({mode:a.literal("setup"),currency:a.nullable(a.undefined())}).extend(kr.shape),a.object({mode:a.enum(["payment","subscription"]),currency:a.string()}).extend(kr.shape)]),pi=a.object({status:a.literal("complete")}),fi=a.object({status:a.literal("expired")});a.union([Cr,pi,fi]),a.object({logo:a.string(),icon:a.string(),primary_color:a.string(),secondary_color:a.string()}),a.object({secure_token:a.string(),pm_id:a.string()}),a.object({secure_token:a.string(),payment_input:a.any(),customer_first_name:a.string().optional(),customer_last_name:a.string().optional(),customer_email:a.string(),customer_zip_code:a.string(),customer_country:a.string(),line_items:a.array(vr),total_amount_atom:a.number().int(),cancel_at_end:a.boolean(),checkout_payment_method:tt,promotion_code:a.string().optional(),do_not_use_legacy_cc_flow:a.boolean().optional(),use_confirmed_pm_id:P(a.string())});const Sr=a.object({payment_method_id:a.string()});a.object({id:a.string(),return_url:a.string()});const mi=a.object({type:a.string(),loc:a.array(a.string()),msg:a.string(),url:a.string()});a.array(mi);const hi=a.object({new_customer_email:a.string().optional(),new_customer_address:a.record(a.string(),a.any()).optional(),new_customer_first_name:a.string().optional(),new_customer_last_name:a.string().optional()}),yi=a.object({price_id:a.string(),quantity:a.number().int()}),_i=a.object({line_items:a.array(yi),promotion_code:a.string().optional(),displayed_total_amount_atom:a.number().int()}),gi=a.object({processor_specific_metadata:P(a.record(a.string(),a.any()))});a.object({payment_provider:a.string(),checkout_payment_method:tt,existing_cc_pm_id:a.string().optional(),their_existing_pm_id:a.string().optional(),use_pay_first_flow:a.boolean().optional(),pay_first_flow_cart_info:_i.optional()}).extend(hi.shape).extend(gi.shape);const Pr=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),checkout_attempt_id:P(a.string())});a.object({fields:ia,checkoutPaymentMethod:tt}),a.object({session_id:a.string(),non_cde_form_fields:At,checkout_payment_method:tt,extra_metadata:a.record(a.string(),a.any())});const vi=a.object({required_user_actions:a.array(a.record(a.string(),a.any())),cc_pm_id:a.string()});a.record(a.any()),a.object({first_name:P(a.string()),last_name:P(a.string()),line1:P(a.string()),line2:P(a.string()),line3:P(a.string()),city:P(a.string()),state:P(a.string()),country:P(a.string()),zip_code:P(a.string()),email:P(a.string()),billing_email:P(a.string()),phone_number:P(a.string()),update_processor_customer:P(a.boolean())}),a.object({id:a.string(),email:P(a.string()),first_name:P(a.string()),last_name:P(a.string()),phone_number:P(a.string()),billing_email:P(a.string()),address:P(a.record(a.string(),a.any()))}),a.object({message:a.string()});const wi=a.object({error_code:a.string()});a.object({checkout_payment_method:tt,processor_specific_metadata:a.record(a.any()).optional()});const bi=a.object({next_action_metadata:P(a.record(a.any()))});a.object({events:a.array(a.object({event_name:a.string(),device_token:a.string(),properties:a.record(a.any()).optional(),context_properties:a.record(a.any()).optional()}))}),a.any().optional(),a.object({device_token:a.string()});const Ei=a.object({}),ki=t=>t.reduce((e,n)=>e+n,0);function Ci(t,e){var n=Object.setPrototypeOf;n?n(t,e):t.__proto__=e}function Si(t,e){e===void 0&&(e=t.constructor);var n=Error.captureStackTrace;n&&n(t,e)}var Pi=function(){var t=function(n,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(o[i]=s[i])},t(n,r)};return function(e,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ai=function(t){Pi(e,t);function e(n,r){var o=this.constructor,s=t.call(this,n,r)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1,configurable:!0}),Ci(s,o.prototype),Si(s),s}return e}(Error);const xn=10,Ar=(t=0)=>e=>`\x1B[${e+t}m`,Tr=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,xr=(t=0)=>(e,n,r)=>`\x1B[${38+t};2;${e};${n};${r}m`,M={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(M.modifier);const Ti=Object.keys(M.color),xi=Object.keys(M.bgColor);[...Ti,...xi];function Ii(){const t=new Map;for(const[e,n]of Object.entries(M)){for(const[r,o]of Object.entries(n))M[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=M[r],t.set(o[0],o[1]);Object.defineProperty(M,e,{value:n,enumerable:!1})}return Object.defineProperty(M,"codes",{value:t,enumerable:!1}),M.color.close="\x1B[39m",M.bgColor.close="\x1B[49m",M.color.ansi=Ar(),M.color.ansi256=Tr(),M.color.ansi16m=xr(),M.bgColor.ansi=Ar(xn),M.bgColor.ansi256=Tr(xn),M.bgColor.ansi16m=xr(xn),Object.defineProperties(M,{rgbToAnsi256:{value(e,n,r){return e===n&&n===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>M.rgbToAnsi256(...M.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let n,r,o;if(e>=232)n=((e-232)*10+8)/255,r=n,o=n;else{e-=16;const c=e%36;n=Math.floor(e/36)/5,r=Math.floor(c/6)/5,o=c%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,n,r)=>M.ansi256ToAnsi(M.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>M.ansi256ToAnsi(M.hexToAnsi256(e)),enumerable:!1}}),M}const ge=Ii(),Xt=(()=>{if(navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(navigator.userAgent)?1:0})(),Ir=Xt!==0&&{level:Xt,hasBasic:!0,has256:Xt>=2,has16m:Xt>=3},Ri={stdout:Ir,stderr:Ir};function Ni(t,e,n){let r=t.indexOf(e);if(r===-1)return t;const o=e.length;let s=0,i="";do i+=t.slice(s,r)+e+n,s=r+o,r=t.indexOf(e,s);while(r!==-1);return i+=t.slice(s),i}function Oi(t,e,n,r){let o=0,s="";do{const i=t[r-1]==="\r";s+=t.slice(o,i?r-1:r)+e+(i?`\r
|
|
7
7
|
`:`
|
|
8
|
-
`)+
|
|
9
|
-
`,o)}while(
|
|
10
|
-
`);return s!==-1&&(e=
|
|
8
|
+
`)+n,o=r+1,r=t.indexOf(`
|
|
9
|
+
`,o)}while(r!==-1);return s+=t.slice(o),s}const{stdout:Rr,stderr:Nr}=Ri,In=Symbol("GENERATOR"),nt=Symbol("STYLER"),xt=Symbol("IS_EMPTY"),Or=["ansi","ansi","ansi256","ansi16m"],rt=Object.create(null),Mi=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=Rr?Rr.level:0;t.level=e.level===void 0?n:e.level},Di=t=>{const e=(...n)=>n.join(" ");return Mi(e,t),Object.setPrototypeOf(e,It.prototype),e};function It(t){return Di(t)}Object.setPrototypeOf(It.prototype,Function.prototype);for(const[t,e]of Object.entries(ge))rt[t]={get(){const n=en(this,Nn(e.open,e.close,this[nt]),this[xt]);return Object.defineProperty(this,t,{value:n}),n}};rt.visible={get(){const t=en(this,this[nt],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const Rn=(t,e,n,...r)=>t==="rgb"?e==="ansi16m"?ge[n].ansi16m(...r):e==="ansi256"?ge[n].ansi256(ge.rgbToAnsi256(...r)):ge[n].ansi(ge.rgbToAnsi(...r)):t==="hex"?Rn("rgb",e,n,...ge.hexToRgb(...r)):ge[n][t](...r),Li=["rgb","hex","ansi256"];for(const t of Li){rt[t]={get(){const{level:n}=this;return function(...r){const o=Nn(Rn(t,Or[n],"color",...r),ge.color.close,this[nt]);return en(this,o,this[xt])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);rt[e]={get(){const{level:n}=this;return function(...r){const o=Nn(Rn(t,Or[n],"bgColor",...r),ge.bgColor.close,this[nt]);return en(this,o,this[xt])}}}}const ji=Object.defineProperties(()=>{},{...rt,level:{enumerable:!0,get(){return this[In].level},set(t){this[In].level=t}}}),Nn=(t,e,n)=>{let r,o;return n===void 0?(r=t,o=e):(r=n.openAll+t,o=e+n.closeAll),{open:t,close:e,openAll:r,closeAll:o,parent:n}},en=(t,e,n)=>{const r=(...o)=>Fi(r,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(r,ji),r[In]=t,r[nt]=e,r[xt]=n,r},Fi=(t,e)=>{if(t.level<=0||!e)return t[xt]?"":e;let n=t[nt];if(n===void 0)return e;const{openAll:r,closeAll:o}=n;if(e.includes("\x1B"))for(;n!==void 0;)e=Ni(e,n.close,n.open),n=n.parent;const s=e.indexOf(`
|
|
10
|
+
`);return s!==-1&&(e=Oi(e,o,r,s)),r+e+o};Object.defineProperties(It.prototype,rt);const tn=It();It({level:Nr?Nr.level:0});const Pe=t=>async e=>{var n,r;try{(r=(n=e.formCallbacks.get).onCheckoutStarted)==null||r.call(n),C("checkout_started");const o=await t(e);if(C("checkout_success",{...o}),o.mode==="setup")e.formCallbacks.get.onSetupPaymentMethodSuccess(o.result.payment_method_id);else if(o.mode==="checkout")e.formCallbacks.get.onCheckoutSuccess(o.result.invoice_urls,o.result.subscription_ids,o.result.customer_id,o.result.processors_used??[]);else throw new Error(`Unhandled mode: ${o}`)}catch(o){const s=ne(o),i=await to(e.context.anyCdeConnection,s);e.formCallbacks.get.onCheckoutError(s,i),C("checkout_error",{errorMessage:s,errorCode:i})}},ze=t=>async e=>{try{return await t(e)}catch(n){const{err__:r}=F("init-error-catcher"),o=ne(n),s=await to(e.context.anyCdeConnection,o);return r(s,o,n),C("init_flow_error",{errorMessage:o,errorCode:s}),{isAvailable:!1,reason:o,errorCode:s}}},F=t=>{const e=(...r)=>{window.console.log(`${tn.green.bold("ojs/")}${tn.bold.gray(`${t}`)} `,...r)},n=(...r)=>{window.console.warn(`${tn.red.bold("ojs/")}${tn.bold.gray(`${t}`)} `,...r)};return{log:e,err:n,log__:e,err__:n}};var On=function(t,e){return On=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},On(t,e)};function Le(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");On(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Ui(t,e,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function c(d){try{u(r.next(d))}catch(p){i(p)}}function l(d){try{u(r.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((r=r.apply(t,e||[])).next())})}function Mr(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(n=0)),n;)try{if(r=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,o=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(d){u=[6,d],o=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function ot(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function nn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s}function rn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}function st(t){return this instanceof st?(this.v=t,this):new st(t)}function $i(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(f){return function(h){return Promise.resolve(h).then(f,p)}}function c(f,h){r[f]&&(o[f]=function(b){return new Promise(function(I,E){s.push([f,b,I,E])>1||l(f,b)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(r[f](h))}catch(b){_(s[0][3],b)}}function u(f){f.value instanceof st?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Zi(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof ot=="function"?ot(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(i){return new Promise(function(c,l){i=t[s](i),o(c,l,i.done,i.value)})}}function o(s,i,c,l){Promise.resolve(l).then(function(u){s({value:u,done:c})},i)}}typeof SuppressedError=="function"&&SuppressedError;function G(t){return typeof t=="function"}function on(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Mn=on(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
11
|
+
`+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
12
|
+
`):"",this.name="UnsubscriptionError",this.errors=n}});function sn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var Rt=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=ot(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(b){e={error:b}}finally{try{l&&!l.done&&(n=c.return)&&n.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(G(d))try{d()}catch(b){s=b instanceof Mn?b.errors:[b]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=ot(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{jr(h)}catch(b){s=s??[],b instanceof Mn?s=rn(rn([],nn(s)),nn(b.errors)):s.push(b)}}}catch(b){r={error:b}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(r)throw r.error}}}if(s)throw new Mn(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)jr(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&sn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&sn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),Dr=Rt.EMPTY;function Lr(t){return t instanceof Rt||t&&"closed"in t&&G(t.remove)&&G(t.add)&&G(t.unsubscribe)}function jr(t){G(t)?t():t.unsubscribe()}var Fr={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Ur={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,rn([t,e],nn(n)))},clearTimeout:function(t){var e=Ur.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function $r(t){Ur.setTimeout(function(){throw t})}function Zr(){}function an(t){t()}var Dn=function(t){Le(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Lr(n)&&n.add(r)):r.destination=Bi,r}return e.create=function(n,r,o){return new jn(n,r,o)},e.prototype.next=function(n){this.isStopped||this._next(n)},e.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Rt),Vi=Function.prototype.bind;function Ln(t,e){return Vi.call(t,e)}var zi=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){cn(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){cn(r)}else cn(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){cn(n)}},t}(),jn=function(t){Le(e,t);function e(n,r,o){var s=t.call(this)||this,i;if(G(n)||!n)i={next:n??void 0,error:r??void 0,complete:o??void 0};else{var c;s&&Fr.useDeprecatedNextContext?(c=Object.create(n),c.unsubscribe=function(){return s.unsubscribe()},i={next:n.next&&Ln(n.next,c),error:n.error&&Ln(n.error,c),complete:n.complete&&Ln(n.complete,c)}):i=n}return s.destination=new zi(i),s}return e}(Dn);function cn(t){$r(t)}function Gi(t){throw t}var Bi={closed:!0,next:Zr,error:Gi,complete:Zr},Fn=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function qi(t){return t}function Yi(t){return t.length===0?qi:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var Ae=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,s=Hi(e)?e:new jn(e,n,r);return an(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=Vr(n),new n(function(o,s){var i=new jn({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[Fn]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Yi(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=Vr(e),new e(function(r,o){var s;n.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},t.create=function(e){return new t(e)},t}();function Vr(t){var e;return(e=t??Fr.Promise)!==null&&e!==void 0?e:Promise}function Wi(t){return t&&G(t.next)&&G(t.error)&&G(t.complete)}function Hi(t){return t&&t instanceof Dn||Wi(t)&&Lr(t)}function Ki(t){return G(t==null?void 0:t.lift)}function Ji(t){return function(e){if(Ki(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Qi(t,e,n,r,o){return new Xi(t,e,n,r,o)}var Xi=function(t){Le(e,t);function e(n,r,o,s,i,c){var l=t.call(this,n)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=r?function(u){try{r(u)}catch(d){n.error(d)}}:t.prototype._next,l._error=s?function(u){try{s(u)}catch(d){n.error(d)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){n.error(u)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e}(Dn),ec=on(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),zr=function(t){Le(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new Gr(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new ec},e.prototype.next=function(n){var r=this;an(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=ot(r.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(n)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;an(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;an(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?Dr:(this.currentObservers=null,c.push(n),new Rt(function(){r.currentObservers=null,sn(c,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?n.error(s):i&&n.complete()},e.prototype.asObservable=function(){var n=new Ae;return n.source=this,n},e.create=function(n,r){return new Gr(n,r)},e}(Ae),Gr=function(t){Le(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:Dr},e}(zr),tc={now:function(){return Date.now()},delegate:void 0},nc=function(t){Le(e,t);function e(n,r){return t.call(this)||this}return e.prototype.schedule=function(n,r){return this},e}(Rt),Br={setInterval:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,rn([t,e],nn(n)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},rc=function(t){Le(e,t);function e(n,r){var o=t.call(this,n,r)||this;return o.scheduler=n,o.work=r,o.pending=!1,o}return e.prototype.schedule=function(n,r){var o;if(r===void 0&&(r=0),this.closed)return this;this.state=n;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,r)),this.pending=!0,this.delay=r,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,r),this},e.prototype.requestAsyncId=function(n,r,o){return o===void 0&&(o=0),Br.setInterval(n.flush.bind(n,this),o)},e.prototype.recycleAsyncId=function(n,r,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return r;r!=null&&Br.clearInterval(r)},e.prototype.execute=function(n,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(n,r);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(n,r){var o=!1,s;try{this.work(n)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var n=this,r=n.id,o=n.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,sn(s,this),r!=null&&(this.id=this.recycleAsyncId(o,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(nc),qr=function(){function t(e,n){n===void 0&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(e,n,r){return n===void 0&&(n=0),new this.schedulerActionCtor(this,e).schedule(r,n)},t.now=tc.now,t}(),oc=function(t){Le(e,t);function e(n,r){r===void 0&&(r=qr.now);var o=t.call(this,n,r)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(n){var r=this.actions;if(this._active){r.push(n);return}var o;this._active=!0;do if(o=n.execute(n.state,n.delay))break;while(n=r.shift());if(this._active=!1,o){for(;n=r.shift();)n.unsubscribe();throw o}},e}(qr),sc=new oc(rc),ac=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function ic(t){return G(t==null?void 0:t.then)}function cc(t){return G(t[Fn])}function lc(t){return Symbol.asyncIterator&&G(t==null?void 0:t[Symbol.asyncIterator])}function uc(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function dc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var pc=dc();function fc(t){return G(t==null?void 0:t[pc])}function mc(t){return $i(this,arguments,function(){var n,r,o,s;return Mr(this,function(i){switch(i.label){case 0:n=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,st(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,st(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,st(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function hc(t){return G(t==null?void 0:t.getReader)}function yc(t){if(t instanceof Ae)return t;if(t!=null){if(cc(t))return _c(t);if(ac(t))return gc(t);if(ic(t))return vc(t);if(lc(t))return Yr(t);if(fc(t))return wc(t);if(hc(t))return bc(t)}throw uc(t)}function _c(t){return new Ae(function(e){var n=t[Fn]();if(G(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function gc(t){return new Ae(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function vc(t){return new Ae(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,$r)})}function wc(t){return new Ae(function(e){var n,r;try{for(var o=ot(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){n={error:c}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function Yr(t){return new Ae(function(e){Ec(t,e).catch(function(n){return e.error(n)})})}function bc(t){return Yr(mc(t))}function Ec(t,e){var n,r,o,s;return Ui(this,void 0,void 0,function(){var i,c;return Mr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Zi(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function kc(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!o)return s}function Cc(t,e){var n=G(t)?t:function(){return t},r=function(o){return o.error(n())};return new Ae(r)}var Sc=on(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function Pc(t,e){return new Promise(function(n,r){var o=!1,s;t.subscribe({next:function(i){s=i,o=!0},error:r,complete:function(){o?n(s):r(new Sc)}})})}function Ac(t){return t instanceof Date&&!isNaN(t)}var Tc=on(function(t){return function(n){n===void 0&&(n=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=n}});function xc(t,e){var n=Ac(t)?{first:t}:typeof t=="number"?{each:t}:t,r=n.first,o=n.each,s=n.with,i=s===void 0?Ic:s,c=n.scheduler,l=c===void 0?sc:c,u=n.meta,d=u===void 0?null:u;if(r==null&&o==null)throw new TypeError("No timeout provided.");return Ji(function(p,_){var f,h,b=null,I=0,E=function(N){h=kc(_,l,function(){try{f.unsubscribe(),yc(i({meta:d,lastValue:b,seen:I})).subscribe(_)}catch(x){_.error(x)}},N)};f=p.subscribe(Qi(_,function(N){h==null||h.unsubscribe(),I++,_.next(b=N),o>0&&E(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),b=null})),!I&&E(r!=null?typeof r=="number"?r:+r-l.now():o)})}function Ic(t){throw new Tc(t)}class Nt{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,n)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:n},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const n=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),n.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&un(this._current);const n={first:e.timeoutSec*1e3,with:()=>Cc(()=>new Error(e.timeoutErrMsg))};return Pc(this._subject.pipe(xc(n)))},this._current={status:"initial",isSuccess:!1},this._subject=new zr}get current(){return this._current}}const Un=new Nt,Wr="op_metrics_queue",Rc=3,Nc=3,Oc=1e3,{log__:ln}=F("op-metrics");class Mc{constructor(){this.queue=[],this.processingQueue=!1,this.batchTimeout=null,this.lastEventTimestamp=0,this.offlineListener=()=>{ln("Network offline, metrics will be queued"),this.cancelBatchProcessing()},this.onlineListener=()=>{ln("Network online, processing metrics queue"),this.processQueue()},!(typeof window>"u")&&(this.loadQueueFromStorage(),window.addEventListener("offline",this.offlineListener),window.addEventListener("online",this.onlineListener))}addEvent(e,n,r){const o={eventName:e,properties:n||{},contextProperties:r||{},nonce:Qt(),timestamp:performance.now(),datetime:new Date().toISOString(),attemptCount:0,timeDiffFromPreviousEvent:this.lastEventTimestamp?performance.now()-this.lastEventTimestamp:0};this.lastEventTimestamp=o.timestamp,this.queue.push(o),this.saveQueueToStorage(),this.scheduleBatchProcessing()}loadQueueFromStorage(){try{const e=window.localStorage.getItem(Wr);e&&(this.queue=JSON.parse(e))}catch{this.queue=[],this.saveQueueToStorage()}}saveQueueToStorage(){window.localStorage.setItem(Wr,JSON.stringify(this.queue))}scheduleBatchProcessing(){navigator.onLine&&!this.processingQueue&&this.queue.length>0&&!this.batchTimeout&&(this.batchTimeout=window.setTimeout(()=>{this.batchTimeout=null,this.processQueue()},Oc))}cancelBatchProcessing(){this.batchTimeout&&(window.clearTimeout(this.batchTimeout),this.batchTimeout=null),this.processingQueue=!1}processQueue(){!navigator.onLine||this.processingQueue||this.queue.length===0||(this.processingQueue=!0,this.sendBatch().finally(()=>{this.processingQueue=!1,this.queue.length>0&&this.scheduleBatchProcessing()}))}async sendBatch(){if(this.queue.length===0)return;const e=Un.getValueIfLoadedElse(void 0);if(!e){ln("Metrics context not available, will retry later");return}const n=this.queue.slice(0,Nc);try{const r={events:n.map(i=>({event_name:i.eventName,device_token:e.deviceToken,context_properties:{...e,...i.contextProperties},properties:{nonce:i.nonce,datetime:i.datetime,timestamp:i.timestamp,time_diff_from_previous_event:i.timeDiffFromPreviousEvent,checkout_secure_token:e.checkoutSecureToken,...i.properties}}))},o=new URL("/metrics/public/capture",e.metricsBaseUrl);(await fetch(o.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).ok?(this.queue=this.queue.slice(n.length),this.saveQueueToStorage()):this.handleFailedBatch(n)}catch(r){ln("Error sending metrics batch:",r),this.handleFailedBatch(n)}}handleFailedBatch(e){e.forEach(r=>{r.attemptCount++});const n=e.filter(r=>r.attemptCount<Rc);this.queue=this.queue.slice(e.length),this.queue=[...n,...this.queue],this.saveQueueToStorage()}cleanup(){window.removeEventListener("offline",this.offlineListener),window.removeEventListener("online",this.onlineListener),this.cancelBatchProcessing()}}const Hr=new Mc,C=(t,e,n)=>{Hr.addEvent(t,e,n)},Kr=t=>{const e=ne(t.reason);C("unhandled_rejection_error",{error_message:e,error_name:t.reason})},Jr=t=>{var n,r;const e=ne(t.error);C("uncaught_error",{error_message:e,error_name:(n=t.error)==null?void 0:n.name,error_stack:(r=t.error)==null?void 0:r.stack,file_name:t.filename,line_number:t.lineno,column_number:t.colno})},Dc=()=>{window.addEventListener("error",Jr),window.addEventListener("unhandledrejection",Kr)},Lc=()=>{window.removeEventListener("error",Jr),window.removeEventListener("unhandledrejection",Kr)};typeof window<"u"&&window.addEventListener("beforeunload",()=>{Hr.processQueue()});class Qr extends Ai{constructor(e){const n=`${e.message}`;super(n),this.response=e}get originalErrorMessage(){return this.response.message}}const H=async(t,e,n,r)=>{r&&C(r,{...e});const o=await t.send(e);if(Fc(o))throw new Qr(o);if(!jc(o,n)){const s=n.safeParse(o);throw s.success?new Error("Invalid state"):(console.error("OJS queryApi got a schema error. Expected schema:",n,"Actual:",o),s.error)}return r&&C(r,{...o}),o},jc=(t,e)=>e.safeParse(t).success,Fc=t=>oi.safeParse(t).success,Uc=async(t,e)=>await H(t,{type:"get_checkout_preview",payload:e},Er),B=async t=>await H(t,{type:"get_prefill",payload:{}},Cr),at=async(t,e)=>await H(t,{type:"v2_start_payment_flow",payload:e},Pr,"start_payment_flow"),$c=async(t,e)=>await H(t,{type:"start_payment_flow_for_cc",payload:e},vi,"start_payment_flow_for_cc"),Zc=async(t,e)=>{C("start_payment_flow_for_pr",{...e});const n=await H(t,{type:"start_payment_flow_for_pr",payload:e},Pr);return C("start_payment_flow_for_pr_result",{...n}),n},ie=async(t,e)=>await H(t,{type:"confirm_payment_flow",payload:e},wa,"confirm_payment_flow"),Vc=async(t,e)=>await H(t,{type:"finalize_setup_payment_method",payload:e},Sr,"finalize_setup_payment_method"),zc=async(t,e)=>await H(t,{type:"check_if_popup_window_verified",payload:e},va,"check_if_popup_window_verified"),Gc=async(t,e,n)=>{const r=await Uc(t,{secure_token:e,promotion_code:n}),o=new Set(r.preview.invoices.map(c=>c.currency));if(o.size!==1)throw new Error(`Expected exactly one currency, got ${o.size}`);const s=o.values().next().value??"usd",i=ki(r.preview.invoices.map(c=>c.remaining_amount_atom));return{currency:s,amountAtom:i}},it=async(t,e,n,r)=>{if(n)return{amountAtom:0,currency:"usd"};{r=r||void 0;const o=await Gc(t,e,r);return{amountAtom:o.amountAtom,currency:o.currency}}},Bc=async(t,e)=>{if(t.size===0)throw new Error("No CDE connections found");return await Promise.all(Array.from(t.values()).map(r=>H(r,{type:"tokenize_card",payload:e},ya)))},Xr=async(t,e)=>await H(t,{type:"checkout_card_elements",payload:e},Sn,"checkout_card_elements"),qc=async(t,e)=>await H(t,{type:"setup_payment_method",payload:e},Sr,"setup_checkout"),$n=async(t,e)=>await H(t,{type:"checkout",payload:e},Sn,"perform_checkout"),eo=1e3,Yc=async(t,e)=>{console.log(e);const r=await _r({iframe:t,debug:!0,timeout:eo,childOrigin:"*"}).promise,o=await H(r,{type:"ping-3ds-status"},_a);return console.log("🟢 CDE connection successful! Stopping polling... Result:",o),o},Zn=async(t,e)=>await H(t,{type:"prepare_payment_flow",payload:e},bi,"prepare_payment_flow"),to=async(t,e)=>{try{return(await H(t,{type:"get_standardized_error_code",payload:{message:e}},wi)).error_code}catch(n){return console.error("[cde-client] Error during getStandardizedErrorCode:",ne(n)),"PAYMENT_FAILED_GENERIC"}},Wc=async(t,e)=>await H(t,{type:"set_user_device_token",payload:{device_token:e}},Ei);function un(t){throw new Error(`Unhandled case: ${t}`)}const no=(t,e)=>Object.fromEntries(Object.entries(t).filter(([n])=>!e.includes(n))),{log__:Wu,err__:Hc}=F("common"),Ot=t=>{if(t.payment_methods.length!==1)throw new Error(`Expected exactly one payment method, got ${t.payment_methods.length}`);return{payment_method_id:t.payment_methods[0].id}},ce=(t,e)=>{const n=t.find(r=>e.safeParse(r).success);if(!n)throw Hc("No CPMs found for model. All models:",t),new Error("No CPMs found for model");return e.parse(n)},Kc=t=>({new_customer_email:t.email,new_customer_address:{zip_code:t.zipCode,country:t.country},new_customer_first_name:t.firstName,new_customer_last_name:t.lastName}),dn=async t=>{const{log__:e}=F(t.logPrefix),n=await B(t.anyCdeConnection),r=Ot(t.confirmResult);if(n.mode==="setup")return e("Setting up payment method..."),{mode:"setup",result:await Vc(t.anyCdeConnection,{secure_token:n.token,pm_id:r.payment_method_id})};{e("Doing checkout...");const o={secure_token:n.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},customer_email:t.requiredFormFields[m.EMAIL],customer_zip_code:t.requiredFormFields[m.ZIP_CODE],customer_country:t.requiredFormFields[m.COUNTRY],promotion_code:t.requiredFormFields[m.PROMOTION_CODE],line_items:n.line_items,total_amount_atom:n.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,use_confirmed_pm_id:r.payment_method_id};return{mode:"checkout",result:await $n(t.anyCdeConnection,o)}}},{log__:ro,err__:oo}=F("common-cc"),je=(t,e,n)=>{if(n){ro(`Received default field values: ${JSON.stringify(n)}`);for(const[o,s]of Object.entries(n))t[o]||(t[o]=s)}const r=At.safeParse(t);if(!r.success){const o=r.error.format(),s=ur(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw oo("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},Jc=(t,e)=>{for(const n of t)if(n.success===!1)throw n.errors.forEach(r=>{const o=cr.safeParse(r.elementType);if(!o.success)oo(`Unknown field name in onValidationError: ${r.elementType}. Error object:`,r);else{const s=o.data;e(s,r.errors)}}),ro(`Error tokenizing card: got validation errors: ${JSON.stringify(n.errors)}`),new Error("Got validation errors while tokenizing card")},so="ojs-stripe-link-btn",{log__:q,err__:Qc}=F("stripe-link"),Xc=a.object({provider:a.literal("stripe_link"),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),el=a.array(a.object({our_existing_pm_id:a.string()})).length(1),tl=ze(async({context:t,formCallbacks:e})=>{const n=t.customInitParams.stripeLink;q("Checking if there are any CPMs for Stripe Link...");const r=ce(t.checkoutPaymentMethods,Xc);q("Starting stripe link flow...");const o=t.anyCdeConnection,s=await B(o),i=s.mode==="setup";q("Creating stripe elements...");const c=await it(o,s.token,i,void 0),{elements:l,stripe:u}=await Ca(r.metadata.stripe_pk,{mode:"setup",currency:c.currency,setup_future_usage:"off_session",paymentMethodCreation:"manual"});q("Creating express checkout...");const d=l.create("expressCheckout",{buttonHeight:n==null?void 0:n.buttonHeight,paymentMethods:{amazonPay:"never",applePay:"never",googlePay:"never",paypal:"never"}}),p=()=>{d.mount(`#${so}`)},_=()=>{d.unmount()};return n!=null&&n.doNotMountOnInit?q("NOT mounting stripe link button (doNotMountOnInit is true)"):(q("Mounting stripe link button..."),p()),d.on("click",async f=>{if(q("Stripe Link button clicked"),n!=null&&n.overrideLinkSubmit&&!await n.overrideLinkSubmit()){q("Stripe Link submit aborted by overrideLinkSubmit");return}f.resolve()}),d.on("confirm",async f=>{q("Stripe Link window confirmed",f);const h=await u.createPaymentMethod({elements:l,params:{billing_details:f.billingDetails}});h.error?(Qc("error",h.error),e.get.onCheckoutError(h.error.message??"Stripe Link unknown error")):(q("paymentMethod",h.paymentMethod),V.stripeLink.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{stripePM:h.paymentMethod},initResult:{isAvailable:!0}}))}),{isAvailable:!0,controller:{mountButton:p,dismountButton:_,waitForButtonToMount:async()=>await ol(so)}}}),nl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{q("Running Stripe Link flow...");const s=t.anyCdeConnection;q("Merging PM fields with form fields...");const i=rl(n,o.stripePM),c=je(i,r.get.onValidationError);C("billing_details_received",{...c}),q("Starting payment flow...");const l=await at(s,{payment_provider:e.provider,checkout_payment_method:e,their_existing_pm_id:o.stripePM.id,new_customer_email:c[m.EMAIL],new_customer_first_name:c[m.FIRST_NAME],new_customer_last_name:c[m.LAST_NAME],new_customer_address:{zip_code:c[m.ZIP_CODE],country:c[m.COUNTRY]}});q("Start payment flow response",l);const d=el.parse(l.required_user_actions)[0].our_existing_pm_id,p=await B(s);if(p.mode==="setup"){q("Doing payment setup...");const _=await ie(s,{secure_token:p.token,existing_cc_pm_id:d});return{mode:"setup",result:Ot(_)}}else{q("Doing checkout...");const _={secure_token:p.token,payment_input:{provider_type:e.provider},customer_email:c[m.EMAIL],customer_zip_code:c[m.ZIP_CODE],customer_country:c[m.COUNTRY],promotion_code:c[m.PROMOTION_CODE],line_items:p.line_items,total_amount_atom:p.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await $n(s,_)}}}),rl=(t,e)=>{var l,u,d,p,_;const n={...t},[r,...o]=((u=(l=e.billing_details.name)==null?void 0:l.trim())==null?void 0:u.split(/\s+/))??[],s=o.join(" ")||void 0;n[m.EMAIL]=n[m.EMAIL]||((d=e.link)==null?void 0:d.email)||e.billing_details.email||"op_unfilled@getopenpay.com",n[m.ZIP_CODE]=n[m.ZIP_CODE]||((p=e.billing_details.address)==null?void 0:p.postal_code)||"00000",n[m.COUNTRY]=n[m.COUNTRY]||((_=e.billing_details.address)==null?void 0:_.country)||"US";const i=n[m.FIRST_NAME]||r||"",c=n[m.LAST_NAME]||s||"";return i||c?(n[m.FIRST_NAME]=i,n[m.LAST_NAME]=c):(n[m.FIRST_NAME]="_OP_UNKNOWN",n[m.LAST_NAME]=""),q("Final form inputs:",n),n},ol=t=>new Promise(e=>{const n=()=>{const r=document.getElementById(t);r?e(r):requestAnimationFrame(n)};n()}),sl="@keyframes fadeIn{0%{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483648!important;display:flex;justify-content:center;align-items:center;background-color:#00000080}.container{max-width:500px;max-height:600px;width:100%;height:100%;background-color:#fff;position:relative;animation:fadeIn .3s ease-out}.frame,#adyen-container,#adyen-container>*{max-width:500px;max-height:600px;width:100%;height:100%;border:none}.cancel-button{position:absolute;background:transparent;border:none;font-size:1rem;color:#fff;cursor:pointer;top:-1.5rem;padding:0;right:0}",ao=t=>{const e=document.createElement("template");e.innerHTML=`
|
|
11
13
|
<style>
|
|
12
|
-
${
|
|
14
|
+
${sl}
|
|
13
15
|
</style>
|
|
14
16
|
<div class="overlay">
|
|
15
17
|
<div class="container">
|
|
16
18
|
<button class="cancel-button">Cancel</button>
|
|
17
|
-
<iframe src="${
|
|
19
|
+
<iframe src="${t}" class="frame" id="three-ds-iframe" title="3D Secure verification" allow="payment"></iframe>
|
|
18
20
|
</div>
|
|
19
21
|
</div>
|
|
20
|
-
`;const
|
|
21
|
-
Error: ${
|
|
22
|
-
Error: ${fe(e)}`),new Error(t)}},oc=async(r,e)=>{const t=tc(e),n=await Fn({url:t["op-airwallex-3ds-url"],baseUrl:r}),o=nc(n.href??""),s=t["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Ir(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:t["op-airwallex-consent-id"]}}},Zn=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),Vn=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),sc=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),ac=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:ot,err__:Rt}=L("adyen-cc"),ic=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":sc,"op-adyen-action":a.string()}),zn="Unable to process your credit card. Please contact support for assistance.",cc=r=>{const e=ic.safeParse(r);if(!e.success)throw Rt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(r)}`),new Error(zn);return e.data},lc=r=>JSON.parse(r),Gn=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,uc=async()=>{ot("Waiting for Adyen SDK to load...");for(let r=0;r<10;r++)Gn()||await vr(500);if(!Gn())throw Rt("Adyen SDK not loaded properly"),new Error(zn);return ot("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},dc=r=>{const{headers:e,locale:t,countryCode:n,component:o,host:s,cancelButton:i}=r,c=lc(e["op-adyen-action"]);return ot(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{ot("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Rt("Authentication failed. Result:",h),l({status:$.FAILURE,cleanup:u})},p=h=>{Rt("Adyen error:",h),l({status:$.FAILURE,cleanup:u})},_=()=>{l({status:$.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,w,x)=>{s.remove(),l({status:$.SUCCESS,additionalDetails:h,cleanup:u})};uc().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:t,countryCode:n,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},pc=r=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,t=r??e,n=ac.safeParse(t);return n.success?(ot(`Resolved locale: ${n.data}`),n.data):(Rt(`Resolved invalid locale: ${t}. Defaulting to en-US.`),"en-US")},fc=r=>(r==null?void 0:r["op-adyen-action"])!==void 0,mc=async(r,e,t)=>{const n=cc(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=Ln("http://example.com");i.replaceWith(o);const l=await dc({headers:n,locale:pc(t),countryCode:r,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===$.FAILURE)throw new Error("3DS verification failed");if(l.status===$.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===$.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return ot("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else Wt(l.status)},{log__:M,err__:Bn}=L("common-cc"),{log__:qn}=L("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const hc=Se(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var u;M("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=r.anyCdeConnection,i=await z(s);M(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=De(t,n.get.onValidationError),l={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{M(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await gi(o.currentCdeConnections,{session_id:r.elementsSessionId});if(Mi(d,n.get.onValidationError),i.mode==="setup"){M(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await vi(s,l);return M(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{M(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const p=await Cn(s,l);return M("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof kn&&d.originalErrorMessage.includes("3DS_REQUIRED")){M("├ Card requires 3DS, starting non-legacy payment flow"),M("Received 3DS error response headers:",d.response.headers);const p=Ji(d.response.headers);if(p){M("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const S=await Xi(r.baseUrl,d.response.headers);l.extra_metadata.pockyt=S}if(rc(d.response.headers)){M("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const S=await oc(r.baseUrl,d.response.headers);l.extra_metadata.airwallex=S}if(fc(d.response.headers)){M("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const S=await mc(t[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=S}const h=await fi(s,l);M("├ Payment flow result:",h);const w=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?M("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):w?(M("├ Using stripe 3DS flow"),await wc(h)):(M("├ Using common 3DS flow"),await vc(h,r.baseUrl));const x=h.cc_pm_id;if(i.mode==="setup"){M(`├ Confirming payment flow [cc_pm_id: ${x}]`);const S=await se(s,{secure_token:i.token,existing_cc_pm_id:x});M("├ Confirm payment flow result received Result:",S);const T=Tt(S);return M(`╰ Setup completed successfully [PM ID: ${T.payment_method_id}]`),{mode:"setup",result:T}}else{M(`├ Checking out after 3DS flow [Flow: ${w?"legacy":"new"}]`);const S=await Cn(s,{...l,existing_cc_pm_id:x,do_not_use_legacy_cc_flow:w});return M("╰ Checkout completed successfully."),{mode:"checkout",result:S}}}throw Bn("╰ Error checking out card info in CDE"),Bn(d),d}}),yc=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return oa.parse(e)},_c=["airwallex_payment_consent","adyen"],gc=r=>{const e=r.required_user_actions.find(t=>_c.includes(t.type));if(!e)throw new Error("No common 3DS action found");return ta.parse(e)},vc=async(r,e)=>{const t=gc(r);if(t.redirect_url==="3DS_COMPLETE"){M("├ 3DS flow completed successfully");return}M(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Qt({url:t.redirect_url,baseUrl:e});if(M(`╰ 3DS verification completed [Status: ${n}]`),n===$.CANCELLED)throw new Error("3DS verification cancelled");if(n===$.FAILURE)throw new Error("3DS verification failed")},wc=async r=>{const e=yc(r);qn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await da(e),qn("╰ Stripe 3DS flow completed successfully")},ie=a.enum(["stripe","airwallex","authorize_net"]);ie.Enum.stripe;const{log__:J,err__:bc}=L("stripe-pr"),Ec=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),kc=Ve(async({context:r,formCallbacks:e})=>{J("Checking if there are any CPMs for Stripe PR...");const t=ae(r.checkoutPaymentMethods,Ec);J("Initializing Stripe PR flow...");const n=r.anyCdeConnection,o=await z(n),s=o.mode==="setup";J("Getting initial preview amount");const i=await tt(n,o.token,s,void 0),c=await ca(t.metadata.stripe_pk,i.amountAtom,i.currency,s);J("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return bc("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};J("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>Z.stripePR.run({context:r,checkoutPaymentMethod:Mt(r.checkoutPaymentMethods,d),nonCdeFormInputs:me(r.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:ie.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:ie.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),Cc=Se(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o,initResult:s})=>{if(J("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=r.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const h=o.overridePaymentRequest;J("Overriding PR amount with",h),Pc(c,h.amount,h.pending,h.applePayPaymentRequest)}J("Showing PR dialog..."),c.show();const l=await la(c);J("Stripe PM added event:",l),J("Merging PM fields with form fields...");const u=Sc(t,l),d=De(u,n.get.onValidationError);J("PR dialog finished. Starting payment flow...",d);const p=await mi(i,{fields:d,checkoutPaymentMethod:e}),_=Ac(p);J("Confirming PR with Stripe..."),await ua(_,l);const f=await z(i);if(f.mode==="setup"){J("Confirming payment flow for setup...");const h=await se(i,{secure_token:f.token});return{mode:"setup",result:Tt(h)}}else{J("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await kr(i,h)}}}),Sc=(r,e)=>{var d,p,_,f;const t={...r},[n,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(_=e.paymentMethod)==null?void 0:_.billing_details)==null?void 0:f.address,c=e.shippingAddress;t[m.EMAIL]=t[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[m.ZIP_CODE]=t[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[m.COUNTRY]=t[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=t[m.FIRST_NAME]||n||"",u=t[m.LAST_NAME]||s||"";return l||u?(t[m.FIRST_NAME]=l,t[m.LAST_NAME]=u):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]=""),J("Final form inputs:",t),t},Pc=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Ac=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
|
|
23
|
-
Details: got ${r.required_user_actions.length} required user actions`);return sa.parse(r.required_user_actions[0])},{log__:_e,err__:Yn}=L("pockyt-paypal"),xc=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const Ic=Se(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var Y,we;_e("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,i=await z(s);_e("Verifying CPM...");const c=xc.parse(e);_e("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=De(t,n.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Ni(u);_e(`Starting payment flow... Mode: ${i.mode}`);const p=br(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((Y=o==null?void 0:o.settings)!=null&&Y.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",r.baseUrl).toString(),w=btoa(JSON.stringify(f)),x=new URLSearchParams({st:i.token,r:w}),S=`${h}?${x.toString()}`;if((we=o==null?void 0:o.settings)!=null&&we.useRedirectFlow)throw _e("Starting redirect mode for PayPal..."),window.location.href=S,await vr(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");_e("Starting popup mode for PayPal..."),_e("Opening paypal iframe...");const T=await qi("PayPal",s,p,S);_e("Paypal flow result",T);const A=$n(T.href),O=Hi(T.href,"catt");if(!O)throw Yn("Checkout attempt ID not found in redirect URL:",T.href),new Error("Checkout attempt ID not found in redirect URL");_e(`Confirming payment flow using vault ID ${A}`);const F=await se(s,{secure_token:i.token,their_pm_id:A,checkout_attempt_id:_?O:void 0});if(_e("Confirm payment flow result",F),i.mode==="setup")return{mode:"setup",result:{payment_method_id:F.payment_methods[0].id}};if(!F.pay_first_success_response)throw Yn("Checkout failed, no pay-first success response:",F),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:F.pay_first_success_response}}),er=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:r,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n??"",merchantName:t},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},Wn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://pay.google.com/gp/p/js/pay.js",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Google Pay SDK")),document.body.appendChild(t)});let Tr=null;const Kn=r=>r===Le||r===window.location.origin?"PRODUCTION":"TEST",tr=(r,e)=>{const t=Kn(r);return Tr===null&&(Tr=new window.google.payments.api.PaymentsClient({environment:t,merchantInfo:e.merchantInfo})),Tr},Tc=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?on.parse(e):null},Hn=(r,e)=>{var o,s,i,c;const t={...r},n=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(n){const[l,...u]=((c=(i=n.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;t[m.EMAIL]=t[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[m.COUNTRY]=t[m.COUNTRY]||n.countryCode||"US",t[m.ADDRESS]=t[m.ADDRESS]||n.address1||"",t[m.CITY]=t[m.CITY]||n.locality||"",t[m.ZIP_CODE]=t[m.ZIP_CODE]||n.postalCode||"00000",t[m.STATE]=t[m.STATE]||n.administrativeArea||"";const p=t[m.FIRST_NAME]||l||"",_=t[m.LAST_NAME]||d||"";p||_?(t[m.FIRST_NAME]=p,t[m.LAST_NAME]=_):(t[m.FIRST_NAME]="_OP_UNKNOWN",t[m.LAST_NAME]="")}return t},{log__:ce,err__:st}=L("awx-google-pay"),Rc=Ve(async({context:r,formCallbacks:e})=>{var p,_;const t={processor:ie.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,Vn);if(!n)return t;ce("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return st("No gateway merchant ID found in processor account"),t;if(ce("Loading Google Pay SDK..."),await Wn(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return st("Google Pay SDK not loaded properly"),t;if(Kn(r.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return st("Google Pay merchant ID is required for production environment"),t;ce("Google Pay SDK loaded",window.google.payments);try{const f=er({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await tr(r.baseUrl,f).isReadyToPay(f);if(!h)return ce("Google Pay is not available for this user"),t}catch(f){return st("Error checking Google Pay availability",f),t}const i=r.anyCdeConnection,c=await z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async f=>{try{Z.airwallexGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:me(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){st("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:ie.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Oc=Se(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{var p,_,f,h,w,x,S;ce("Starting Google Pay flow...");const s=ae(r.checkoutPaymentMethods,Vn),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=er({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=tr(r.baseUrl,u);try{const T=await d.loadPaymentData(u);ce("Google Pay Payment data",T);const A=r.anyCdeConnection,O=await z(A),F=Hn(t,T),Y=De(F,n.get.onValidationError,o==null?void 0:o.defaultFieldValues),we=(_=(p=T.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!we)throw new Error("No payment token received from Google Pay");const Jl=await et(A,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:Y[m.EMAIL],new_customer_first_name:Y[m.FIRST_NAME],new_customer_last_name:Y[m.LAST_NAME],new_customer_address:{zip_code:Y[m.ZIP_CODE],country:Y[m.COUNTRY]}}),ur=Tc(Jl);ce("Start flow next actions",ur);let Be=await se(A,{secure_token:O.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:ur==null?void 0:ur.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:we}}}});ce("[1st] Confirm payment flow response",Be);let Zr=(h=(f=Be.payment_methods)==null?void 0:f[0])==null?void 0:h.id;const qe=(w=Be.required_user_actions)==null?void 0:w.find(jt=>jt.type==="airwallex_payment_consent");if(qe&&qe.redirect_url){ce("3DS Required, starting verification...",qe);const{status:jt}=await Qt({url:qe.redirect_url,baseUrl:r.baseUrl});if(ce(`╰ 3DS verification completed [Status: ${jt}]`),jt===$.CANCELLED)throw new Error("3DS verification cancelled");if(jt===$.FAILURE)throw new Error("3DS verification failed")}if(qe&&!Zr&&(Be=await se(A,{secure_token:O.token,their_pm_id:qe.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:qe.consent_id}}),ce("[2nd] Confirm payment flow response",Be),Zr=(S=(x=Be.payment_methods)==null?void 0:x[0])==null?void 0:S.id),!Zr)throw new Error("No PM ID found");return Xt({logPrefix:"awx-googlepay",anyCdeConnection:A,checkoutPaymentMethod:e,requiredFormFields:Y,confirmResult:Be,usePayFirstFlow:!1})}catch(T){throw st("Google Pay payment error",T),new Error((T==null?void 0:T.message)??"Unknown error")}}),Jn=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Apple Pay SDK")),document.body.appendChild(t)}),Xn=(r,e)=>{const t=e.token.paymentMethod.billingContact,n=e.billingContact,o=e.shippingContact,s={...r};if(t||n||o){s[m.EMAIL]=s[m.EMAIL]||(t==null?void 0:t.emailAddress)||(n==null?void 0:n.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(t==null?void 0:t.countryCode)||(n==null?void 0:n.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(t==null?void 0:t.postalCode)||(n==null?void 0:n.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(t==null?void 0:t.givenName)||(n==null?void 0:n.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(t==null?void 0:t.familyName)||(n==null?void 0:n.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const Qn=({total:r,prefill:e})=>{var n;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:r.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Le).toString()};const t=(n=e.line_items)==null?void 0:n[0];if(t)return{paymentDescription:(t==null?void 0:t.description)??"",regularBilling:{amount:r.amount,label:(t==null?void 0:t.description)??"",recurringPaymentIntervalUnit:t==null?void 0:t.billing_interval,recurringPaymentIntervalCount:(t==null?void 0:t.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},eo=({overridePaymentRequest:r,initialPreview:e,prefill:t,defaultLabel:n="Total"})=>{var c,l;const o=(((c=r==null?void 0:r.amount)==null?void 0:c.currency)??(t==null?void 0:t.currency)??e.currency).toUpperCase(),i=((((l=r==null?void 0:r.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(r==null?void 0:r.label)??n??"Total",type:r!=null&&r.pending?"pending":"final",amount:i}}},{log__:rr}=L("awx-apple-pay");async function Nc(r,e){try{const n=(await Cr(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function Mc(r,e){if(!r.redirect_url)throw new Error("No redirect URL found");rr("3DS Required, starting verification...",r);const{status:t}=await Qt({url:r.redirect_url,baseUrl:e.baseUrl});if(rr(`╰ 3DS verification completed [Status: ${t}]`),t===$.CANCELLED)throw new Error("3DS verification cancelled");if(t===$.FAILURE)throw new Error("3DS verification failed");const n=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:r.their_pm_id,airwallex_consent_id:r.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return rr("[2nd] Confirm payment flow response",n),n}async function Dc(r,e){var t,n,o,s,i;try{const c=r.payment,l=Xn(e.nonCdeFormInputs,c),u=De(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues),_=(await et(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});rr("[1st] Confirm payment flow response",f);let h=(n=(t=f.payment_methods)==null?void 0:t[0])==null?void 0:n.id;const w=(o=f.required_user_actions)==null?void 0:o.find(S=>S.type==="airwallex_payment_consent");if(w!=null&&w.redirect_url&&w.consent_id&&w.their_pm_id&&(f=await Mc(w,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const x={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(x),Xt({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:at,err__:Rr}=L("awx-apple-pay"),jc=Ve(async({context:r,formCallbacks:e})=>{const t={processor:ie.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,Zn);if(!n)return t;at("Loading Apple Pay SDK...");try{await Jn(),at("Apple Pay SDK loaded successfully")}catch(p){return Rr("Failed to load Apple Pay SDK",p),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return at("Apple Pay is not available on this device/browser"),t;if(at("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return at("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async p=>{try{await Z.airwallexApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:me(r.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Rr("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ie.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Lc=Se(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var x;const s=ae(r.checkoutPaymentMethods,Zn),{overridePaymentRequest:i,initialPreview:c}=n,l=r.anyCdeConnection,u=await z(l),d=u.mode==="setup",{currencyCode:p,total:_}=eo({overridePaymentRequest:i,initialPreview:c,defaultLabel:(x=s==null?void 0:s.metadata)==null?void 0:x.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Qn({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:r.baseUrl,formCallbacks:o,defaultFieldValues:n==null?void 0:n.defaultFieldValues};return new Promise((S,T)=>{const A=()=>{at("Payment cancelled by user"),T(new Error("Payment cancelled by user"))};h.oncancel=A,h.onvalidatemerchant=async O=>{try{await Nc(O,w)}catch(F){T(F)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{try{const F=await Dc(O,w);S(F)}catch(F){T(F)}},h.begin()}).catch(S=>{throw Rr("Apple Pay payment error",S),S})}),Fc=1,Uc=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:X,err__:to}=L("loop-crypto"),$c=a.object({loopFirstName:U,loopLastName:U,loopEmail:U,[m.PROMOTION_CODE]:j}),Zc=(r,e,t)=>{const n=$c.safeParse(r);if(!n.success){const o=n.error.format(),s=sn(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw to("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return n.data},Vc=Ve(async({context:r})=>{X("Checking if there are any CPMs for Loop Crypto...");const e=ae(r.checkoutPaymentMethods,Uc);X(`checkoutPaymentMethod: ${JSON.stringify(e)}`),X("Starting Loop Crypto flow...");const t=await z(r.anyCdeConnection),n=await Cr(r.anyCdeConnection,{checkout_payment_method:e});if(t.mode!=="setup"&&!e.metadata.supported_currencies.includes(t.currency))throw Error(`Currency ${t.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!n||!n.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=n.next_action_metadata;let s;t.mode==="setup"?s=Fc:s=t.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=br(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),zc=Se(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:o})=>{X("Running Loop flow..."),X("context",r),X("checkoutPaymentMethod",e),X("nonCdeFormInputs",t),X("flowCallbacks",n),X("customParams",o);const s=Zc(t,n.get.onValidationError),i=r.anyCdeConnection,c=await z(r.anyCdeConnection),l=c.mode!=="setup",u=await et(r.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await se(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_success:o.success}});if(X(`Confirm result: ${d}`),c.mode==="setup"){X("Doing payment setup..."),X("├ Confirm payment flow result received Result:",d);const p=Tt(d);return X(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(X("Doing checkout..."),!d.pay_first_success_response)throw to("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}});async function Gc(r,e){try{const n=(await Cr(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=n==null?void 0:n.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o)}catch(t){throw e.session.abort(),t}}async function Bc(r,e){var t,n;try{const o=r.payment,s=Xn(e.nonCdeFormInputs,o),i=De(s,e.formCallbacks.get.onValidationError);await et(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await se(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((n=(t=l.payment_methods)==null?void 0:t[0])==null?void 0:n.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),Xt({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const ro=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),no=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:Ot,err__:Or}=L("authnet-applepay"),qc=Ve(async({context:r,formCallbacks:e})=>{const t={processor:ie.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,ro);if(!n)return t;Ot("Loading Apple Pay SDK...");try{await Jn(),Ot("Apple Pay SDK loaded successfully")}catch(p){return Or("Failed to load Apple Pay SDK",p),t}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return Ot("Apple Pay is not available on this device/browser"),t;if(!await ApplePaySession.canMakePayments())return Ot("No active cards available for Apple Pay"),t;if(!n.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=r.anyCdeConnection,c=await z(i),l=c.mode==="setup",u=await tt(i,c.token,l,void 0),d=async p=>{try{await Z.authorizeNetApplePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:me(r.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Or("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:ie.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),Yc=Se(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:o})=>{var x;const{initialPreview:s,overridePaymentRequest:i}=n,c=ae(r.checkoutPaymentMethods,ro),{currencyCode:l,total:u}=eo({overridePaymentRequest:i,initialPreview:s,defaultLabel:(x=c==null?void 0:c.metadata)==null?void 0:x.processor_account_name}),d=r.anyCdeConnection,p=await z(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Qn({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),w={session:h,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:r.baseUrl,formCallbacks:o};return new Promise((S,T)=>{h.oncancel=()=>{Ot("Payment cancelled by user"),T(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async A=>{try{await Gc(A,w)}catch(O){T(O)}},h.onpaymentmethodselected=()=>{const A={newTotal:f.total};h.completePaymentMethodSelection(A)},h.onpaymentauthorized=async A=>{try{const O=await Bc(A,w);S(O)}catch(O){T(O)}},h.begin()}).catch(S=>{throw Or("Apple Pay payment error",S),S})}),{log__:ze,err__:Nt}=L("authnet-googlepay"),Wc=Ve(async({context:r,formCallbacks:e})=>{var d,p;ze("Initializing Authnet GooglePay flow");const t={processor:ie.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},n=ae(r.checkoutPaymentMethods,no);if(!n)return t;ze("Google Pay CPM",n);const o=n.metadata;if(!o.processor_account_id)return Nt("No gateway merchant ID found in processor account"),t;if(ze("Loading Google Pay SDK..."),await Wn(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Nt("Google Pay SDK not loaded properly"),t;ze("Google Pay SDK loaded",window.google.payments);try{const _=er({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await tr(r.baseUrl,_).isReadyToPay(_);if(!f)return ze("Google Pay is not available for this user"),t}catch(_){return Nt("Error checking Google Pay availability",_),t}const s=r.anyCdeConnection,i=await z(s),c=i.mode==="setup",l=await tt(s,i.token,c,void 0),u=async _=>{try{Z.authorizeNetGooglePay.run({context:r,checkoutPaymentMethod:n,nonCdeFormInputs:me(r.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Nt("Google Pay payment error",f),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:ie.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),Kc=Se(async({context:r,nonCdeFormInputs:e,checkoutPaymentMethod:t,formCallbacks:n,customParams:o})=>{var p,_,f,h;const{initialPreview:s,overridePaymentRequest:i}=o,l=ae(r.checkoutPaymentMethods,no).metadata,u=er({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=tr(r.baseUrl,u);try{const w=await d.loadPaymentData(u);ze("Google Pay Payment data",w);const x=r.anyCdeConnection,S=await z(x),T=Hn(e,w),A=De(T,n.get.onValidationError),O=(_=(p=w.paymentMethodData)==null?void 0:p.tokenizationData)==null?void 0:_.token;if(!O)throw new Error("No payment token received from Google Pay");const F=await et(x,{payment_provider:t.provider,checkout_payment_method:t,new_customer_email:A[m.EMAIL],new_customer_first_name:A[m.FIRST_NAME],new_customer_last_name:A[m.LAST_NAME],new_customer_address:{zip_code:A[m.ZIP_CODE],country:A[m.COUNTRY]}});ze("Start payment flow response",F);const Y=await se(x,{secure_token:S.token,processor_specific_metadata:{payment_provider:t.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((h=(f=Y.payment_methods)==null?void 0:f[0])==null?void 0:h.id))throw new Error("No PM ID found");return Xt({logPrefix:"authnet-googlepay",anyCdeConnection:x,checkoutPaymentMethod:t,requiredFormFields:A,confirmResult:Y,usePayFirstFlow:!1})}catch(w){throw Nt("Google Pay payment error",w),new Error((w==null?void 0:w.message)??"Unknown error")}}),Mt=(r,e,t)=>{const n=r.filter(o=>{const s=t===void 0?!0:o.processor_name===t,i=o.provider===e;return s&&i});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]},Z={commonCC:{init:async()=>{},run:hc},stripePR:{init:kc,run:Cc},stripeLink:{init:Fi,run:Ui},pockytPaypal:{run:Ic},airwallexGooglePay:{init:Rc,run:Oc},airwallexApplePay:{init:jc,run:Lc},loopCrypto:{init:Vc,run:zc},authorizeNetApplePay:{init:qc,run:Yc},authorizeNetGooglePay:{init:Wc,run:Kc}};var Nr=function(r,e){return Nr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},Nr(r,e)};function je(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Nr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Hc(r,e,t,n){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function c(d){try{u(n.next(d))}catch(p){i(p)}}function l(d){try{u(n.throw(d))}catch(p){i(p)}}function u(d){d.done?s(d.value):o(d.value).then(c,l)}u((n=n.apply(r,e||[])).next())})}function oo(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=c(0),i.throw=c(1),i.return=c(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function c(u){return function(d){return l([u,d])}}function l(u){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(t=0)),t;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,o=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){t.label=u[1];break}if(u[0]===6&&t.label<s[1]){t.label=s[1],s=u;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(u);break}s[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function it(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 nr(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(c){i={error:c}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return s}function or(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))}function ct(r){return this instanceof ct?(this.v=r,this):new ct(r)}function Jc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(f){return function(h){return Promise.resolve(h).then(f,p)}}function c(f,h){n[f]&&(o[f]=function(w){return new Promise(function(x,S){s.push([f,w,x,S])>1||l(f,w)})},h&&(o[f]=h(o[f])))}function l(f,h){try{u(n[f](h))}catch(w){_(s[0][3],w)}}function u(f){f.value instanceof ct?Promise.resolve(f.value.v).then(d,p):_(s[0][2],f)}function d(f){l("next",f)}function p(f){l("throw",f)}function _(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Xc(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 it=="function"?it(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(i){return new Promise(function(c,l){i=r[s](i),o(c,l,i.done,i.value)})}}function o(s,i,c,l){Promise.resolve(l).then(function(u){s({value:u,done:c})},i)}}typeof SuppressedError=="function"&&SuppressedError;function B(r){return typeof r=="function"}function sr(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 Mr=sr(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
24
|
-
`+t.map(function(n,o){return o+1+") "+n.toString()}).join(`
|
|
25
|
-
`):"",this.name="UnsubscriptionError",this.errors=t}});function ar(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Dt=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,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var c=it(i),l=c.next();!l.done;l=c.next()){var u=l.value;u.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(B(d))try{d()}catch(w){s=w instanceof Mr?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var _=it(p),f=_.next();!f.done;f=_.next()){var h=f.value;try{io(h)}catch(w){s=s??[],w instanceof Mr?s=or(or([],nr(s)),nr(w.errors)):s.push(w)}}}catch(w){n={error:w}}finally{try{f&&!f.done&&(o=_.return)&&o.call(_)}finally{if(n)throw n.error}}}if(s)throw new Mr(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)io(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)&&ar(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ar(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),so=Dt.EMPTY;function ao(r){return r instanceof Dt||r&&"closed"in r&&B(r.remove)&&B(r.add)&&B(r.unsubscribe)}function io(r){B(r)?r():r.unsubscribe()}var co={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},lo={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,or([r,e],nr(t)))},clearTimeout:function(r){var e=lo.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function uo(r){lo.setTimeout(function(){throw r})}function po(){}function ir(r){r()}var Dr=function(r){je(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,ao(t)&&t.add(n)):n.destination=rl,n}return e.create=function(t,n,o){return new Lr(t,n,o)},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}(Dt),Qc=Function.prototype.bind;function jr(r,e){return Qc.call(r,e)}var el=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){cr(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){cr(n)}else cr(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){cr(t)}},r}(),Lr=function(r){je(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(B(t)||!t)i={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;s&&co.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&jr(t.next,c),error:t.error&&jr(t.error,c),complete:t.complete&&jr(t.complete,c)}):i=t}return s.destination=new el(i),s}return e}(Dr);function cr(r){uo(r)}function tl(r){throw r}var rl={closed:!0,next:po,error:tl,complete:po},Fr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function nl(r){return r}function ol(r){return r.length===0?nl:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var Pe=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 o=this,s=al(e)?e:new Lr(e,t,n);return ir(function(){var i=o,c=i.operator,l=i.source;s.add(c?c.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},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=fo(t),new t(function(o,s){var i=new Lr({next:function(c){try{e(c)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Fr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ol(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=fo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r}();function fo(r){var e;return(e=r??co.Promise)!==null&&e!==void 0?e:Promise}function sl(r){return r&&B(r.next)&&B(r.error)&&B(r.complete)}function al(r){return r&&r instanceof Dr||sl(r)&&ao(r)}function il(r){return B(r==null?void 0:r.lift)}function cl(r){return function(e){if(il(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 ll(r,e,t,n,o){return new ul(r,e,t,n,o)}var ul=function(r){je(e,r);function e(t,n,o,s,i,c){var l=r.call(this,t)||this;return l.onFinalize=i,l.shouldUnsubscribe=c,l._next=n?function(u){try{n(u)}catch(d){t.error(d)}}:r.prototype._next,l._error=s?function(u){try{s(u)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,l._complete=o?function(){try{o()}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}(Dr),dl=sr(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),mo=function(r){je(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 ho(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new dl},e.prototype.next=function(t){var n=this;ir(function(){var o,s;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=it(n.currentObservers),c=i.next();!c.done;c=i.next()){var l=c.value;l.next(t)}}catch(u){o={error:u}}finally{try{c&&!c.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(t){var n=this;ir(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var o=n.observers;o.length;)o.shift().error(t)}})},e.prototype.complete=function(){var t=this;ir(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,o=this,s=o.hasError,i=o.isStopped,c=o.observers;return s||i?so:(this.currentObservers=null,c.push(t),new Dt(function(){n.currentObservers=null,ar(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,o=n.hasError,s=n.thrownError,i=n.isStopped;o?t.error(s):i&&t.complete()},e.prototype.asObservable=function(){var t=new Pe;return t.source=this,t},e.create=function(t,n){return new ho(t,n)},e}(Pe),ho=function(r){je(e,r);function e(t,n){var o=r.call(this)||this;return o.destination=t,o.source=n,o}return e.prototype.next=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,t)},e.prototype.error=function(t){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.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,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&o!==void 0?o:so},e}(mo),pl={now:function(){return Date.now()},delegate:void 0},fl=function(r){je(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(Dt),yo={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,or([r,e],nr(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},ml=function(r){je(e,r);function e(t,n){var o=r.call(this,t,n)||this;return o.scheduler=t,o.work=n,o.pending=!1,o}return e.prototype.schedule=function(t,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var s=this.id,i=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(i,s,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(i,this.id,n),this},e.prototype.requestAsyncId=function(t,n,o){return o===void 0&&(o=0),yo.setInterval(t.flush.bind(t,this),o)},e.prototype.recycleAsyncId=function(t,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&yo.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(t,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var o=!1,s;try{this.work(t)}catch(i){o=!0,s=i||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,o=t.scheduler,s=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ar(s,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(fl),_o=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=pl.now,r}(),hl=function(r){je(e,r);function e(t,n){n===void 0&&(n=_o.now);var o=r.call(this,t,n)||this;return o.actions=[],o._active=!1,o}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var o;this._active=!0;do if(o=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,o){for(;t=n.shift();)t.unsubscribe();throw o}},e}(_o),yl=new hl(ml),_l=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function gl(r){return B(r==null?void 0:r.then)}function vl(r){return B(r[Fr])}function wl(r){return Symbol.asyncIterator&&B(r==null?void 0:r[Symbol.asyncIterator])}function bl(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 El(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var kl=El();function Cl(r){return B(r==null?void 0:r[kl])}function Sl(r){return Jc(this,arguments,function(){var t,n,o,s;return oo(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,ct(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,ct(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,ct(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Pl(r){return B(r==null?void 0:r.getReader)}function Al(r){if(r instanceof Pe)return r;if(r!=null){if(vl(r))return xl(r);if(_l(r))return Il(r);if(gl(r))return Tl(r);if(wl(r))return go(r);if(Cl(r))return Rl(r);if(Pl(r))return Ol(r)}throw bl(r)}function xl(r){return new Pe(function(e){var t=r[Fr]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Il(r){return new Pe(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function Tl(r){return new Pe(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,uo)})}function Rl(r){return new Pe(function(e){var t,n;try{for(var o=it(r),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function go(r){return new Pe(function(e){Nl(r,e).catch(function(t){return e.error(t)})})}function Ol(r){return go(Sl(r))}function Nl(r,e){var t,n,o,s;return Hc(this,void 0,void 0,function(){var i,c;return oo(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),t=Xc(r),l.label=1;case 1:return[4,t.next()];case 2:if(n=l.sent(),!!n.done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),o={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Ml(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function Dl(r,e){var t=B(r)?r:function(){return r},n=function(o){return o.error(t())};return new Pe(n)}var jl=sr(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function Ll(r,e){return new Promise(function(t,n){var o=!1,s;r.subscribe({next:function(i){s=i,o=!0},error:n,complete:function(){o?t(s):n(new jl)}})})}function Fl(r){return r instanceof Date&&!isNaN(r)}var Ul=sr(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function $l(r,e){var t=Fl(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,o=t.each,s=t.with,i=s===void 0?Zl:s,c=t.scheduler,l=c===void 0?yl:c,u=t.meta,d=u===void 0?null:u;if(n==null&&o==null)throw new TypeError("No timeout provided.");return cl(function(p,_){var f,h,w=null,x=0,S=function(T){h=Ml(_,l,function(){try{f.unsubscribe(),Al(i({meta:d,lastValue:w,seen:x})).subscribe(_)}catch(A){_.error(A)}},T)};f=p.subscribe(ll(_,function(T){h==null||h.unsubscribe(),x++,_.next(w=T),o>0&&S(o)},void 0,void 0,function(){h!=null&&h.closed||h==null||h.unsubscribe(),w=null})),!x&&S(n!=null?typeof n=="number"?n:+n-l.now():o)})}function Zl(r){throw new Ul(r)}class lr{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&Wt(this._current);const t={first:e.timeoutSec*1e3,with:()=>Dl(()=>new Error(e.timeoutErrMsg))};return Ll(this._subject.pipe($l(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new mo}get current(){return this._current}}const{log__:Vl,err__:zl}=L("init-flows"),Ge=(r,e)=>{const t=new lr;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(n);Vl(`✔ ${r} flow initialized successfully. Result:`,o),t.set(o)}catch(o){zl(`𝙭 ${r} flow initialization failed. Error:`,fe(o),"Details:",o),t.throw(o,fe(o))}}}},Gl=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Bl=()=>({stripePR:Ge("Stripe PR",Z.stripePR.init),stripeLink:Ge("Stripe Link",Z.stripeLink.init),airwallexGooglePay:Ge("Airwallex GooglePay",Z.airwallexGooglePay.init),airwallexApplePay:Ge("Airwallex ApplePay",Z.airwallexApplePay.init),loop:Ge("Loop",Z.loopCrypto.init),authorizeNetGooglePay:Ge("Authnet GooglePay",Z.authorizeNetGooglePay.init),authorizeNetApplePay:Ge("Authnet ApplePay",Z.authorizeNetApplePay.init)}),{err__:ql}=L("form-callbacks"),le=a.function().optional(),vo=a.object({onFocus:le,onBlur:le,onChange:le,onLoad:le,onLoadError:le,onValidationError:le,onCheckoutStarted:le,onCheckoutSuccess:le,onSetupPaymentMethodSuccess:le,onCheckoutError:le,onPaymentRequestLoad:le}),ve=class ve{constructor(){this.setCallbacks=e=>{this._callbacks=ve.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const o=xs(t,n??ve.NOOP,ql);this._callbacks[t]=o})},this._callbacks=ve.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ve.NOOP=()=>{},ve.createEmptyCallbacks=()=>{const e={};return Object.keys(vo.keyof().enum).forEach(t=>{e[t]=ve.NOOP}),e},ve.fromObject=e=>{const t=new ve;return t.setCallbacks(vo.parse(e)),t};let Ur=ve;class Yl{constructor(e,t,n,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(wo(s.origin)!==wo(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=_a(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=o}}const wo=r=>new URL(r).origin;async function Wl(r,e){const n=await fn({iframe:r,debug:!1,childOrigin:e}).promise,o=await Ua(n);if(!$a(n,o))throw new Error("Got invalid CDE connection object");return n}class Kl{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 Hl=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&bo("apple_pay",s,e,t,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&bo("google_pay",s,e,t,u)}}};t.get.onPaymentRequestLoad(l)}})},bo=(r,e,t,n,o)=>Z.stripePR.run({context:t,checkoutPaymentMethod:Mt(t.checkoutPaymentMethods,r),nonCdeFormInputs:me(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Eo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:ge,err__:Ae}=L("op-form"),xe=class xe{constructor(e){this.cdeLoadEvent=new lr,this.anyCdeConn=new lr,this.context=new lr,this.initFlows=Bl(),this.startFormInit=async()=>{try{const t=this.createElement(Ce.CDE_BRIDGE);t.node.id="__op_internal_cde_bridge",t.node.ariaHidden="true",Object.assign(t.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),t.mount("body"),ge("CDE bridge element mounted"),this.connectToElement(t),ge("Initializing OpenPay form:"),ge("├ Waiting for CDE load event...");const n=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Eo});ge("├ CDE load event received"),ge("├ Waiting for CDE connection...");const o=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Eo});ge("├ CDE connection received"),ge("├ Creating OJS context, setting up handlers...");const s=xe.buildOjsFlowContext(this.config,n,o,this.getFormDiv());this.context.set(s),Hl(this.initFlows,s,this.formCallbacks),ge("├ Starting OJS init flows..."),await Gl(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(n.totalAmountAtoms,n.currency),ge("╰ Done initializing OJS flows.")}catch(t){const n=fe(t);Ae("╰ 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.type===Ce.CDE_BRIDGE||(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 o=Ts.parse(t),s=document.createElement("iframe"),i=this.buildQueryString(n);s.name=`${o}-element`;const c=new URL(`/app/v1/${s.name}/`,this.config.baseUrl);return c.search=i.toString(),s.src=c.href,s.style.border="none",s.style.width="100%",this.registerIframe(o,s)},this.registerIframe=(t,n)=>{const o={type:t,node:n,mount:s=>{var i;return(i=document.querySelector(s))==null?void 0:i.appendChild(n)}};return this.registeredElements||(this.registeredElements={[Ce.CARD]:void 0,[Ce.CARD_NUMBER]:void 0,[Ce.CARD_EXPIRY]:void 0,[Ce.CARD_CVC]:void 0,[Ce.CDE_BRIDGE]:void 0}),this.registeredElements[t]=o,o},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",pa(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{Wl(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Ae("[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){Ae("Please wait for the form to finish loading before submitting.");return}Z.commonCC.run({context:t,checkoutPaymentMethod:Mt(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:me(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Ae("Please wait for the form to finish loading before getting available payment methods.");return}const n={airwallexGooglePay:ee.airwallexGooglePay,airwallexApplePay:ee.airwallexApplePay,authorizeNetGooglePay:ee.authorizenetGooglePay,authorizeNetApplePay:ee.authorizenetApplePay};return Object.entries(this.initFlows).map(([o,s])=>({name:n[o]??o,...s.publisher.getValueIfLoadedElse(null)}))},this.generalSubmit=(t,n)=>{const o=this.context.getValueIfLoadedElse(null);if(!o){Ae("Please wait for the form to finish loading before submitting.");return}switch(t){case ee.pockytPaypal:return Z.pockytPaypal.run({context:o,checkoutPaymentMethod:Mt(o.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:me(o.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:n},initResult:void 0});case ee.airwallexGooglePay:{const s=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ae("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.airwallexApplePay:{const s=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ae("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetGooglePay:{const s=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!s){Ae("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.authorizenetApplePay:{const s=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!s){Ae("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return s.startFlow(n)}case ee.loopCrypto:return Z.loopCrypto.run({context:o,checkoutPaymentMethod:Mt(o.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:me(o.formDiv),formCallbacks:this.formCallbacks,customParams:n,initResult:void 0});default:Wt(t)}},this.submit=this.submitCard,this.destroy=()=>{ge("Destroying OpenPay form...");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)},xe.assignAsSingleton(this),this.ojsVersion="0.2.22",this.ojsReleaseVersion="0.2.22",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Ur.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${br()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new Kl,this.eventHandler=new Yl(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};xe.ojsFlows=Z,xe.assignAsSingleton=e=>{if(xe.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},xe.getInstance=()=>window.ojs??null,xe.buildOjsFlowContext=(e,t,n,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Le).origin,formDiv:o,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let $r=xe;be.FieldName=m,be.OpenPayForm=$r,be.SubmitMethod=Is,be.SubmitMethods=ee,Object.defineProperty(be,Symbol.toStringTag,{value:"Module"})});
|
|
22
|
+
`;const n=document.createElement("div"),r=n.attachShadow({mode:"open"});r.appendChild(e.content.cloneNode(!0));const o=r.querySelector("#three-ds-iframe"),s=r.querySelector(".cancel-button");return document.body.appendChild(n),{host:n,iframe:o,cancelButton:s}};function al(t,e,n){const r=async()=>{try{const s=await Yc(t,n);s&&(clearInterval(o),e(s))}catch{}};r();const o=setInterval(r,eo);return o}function il({elements:t,pollingInterval:e,resolve:n}){const r=()=>{clearInterval(e),t.host.remove(),n({status:Z.CANCELLED})};return t.cancelButton.addEventListener("click",r),()=>{t.cancelButton.removeEventListener("click",r)}}async function pn(t){const{url:e,baseUrl:n}=t,r=ao(e);return new Promise(o=>{const s=l=>{setTimeout(()=>{r.host.remove()},1e3),o(l),c==null||c()},i=al(r.iframe,s,new URL(n).origin),c=il({elements:r,pollingInterval:i,resolve:o})})}const io=async t=>{const e=await pn(t);if(e.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(e.status===Z.FAILURE)throw new Error("3DS verification failed");return e.status!==Z.SUCCESS&&un(e.status),{href:e.href}},cl=(t,e)=>{const n=window.open(e,"_blank");if(!n)throw new Error(`${t} popup window blocked. Please allow popups for this site.`);return n},ll=async(t,e,n,r)=>{const{err__:o}=F("popup-verify");return new Promise((s,i)=>{const c=cl(t,r),l=setInterval(async()=>{try{const u=await zc(e,n);if(u.present)clearInterval(l),c.close(),s({href:u.href});else if(c.closed)throw new Error(`${t} payment cancelled`)}catch(u){o(ne(u)),clearInterval(l),i(ne(u))}},1e3)})},{log__:ul,err__:co}=F("pockyt-cc"),dl=a.object({"op-pockyt-3ds-url":a.string(),"op-pockyt-txn-no":a.string(),"op-pockyt-ref-no":a.string()}),pl=t=>{const e=dl.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Pockyt 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw co(r),new Error(n)}return e.data},lo=t=>{try{const e=new URL(t??"").searchParams.get("vaultId");if(!e)throw new Error("No vault ID found in 3DS verification result");return ul(`3DS verification success. [Vault ID: ${e}]`),e}catch(e){const n="Error verifying 3DS verification result.";throw co(n,`Resulting URL: ${t}.
|
|
23
|
+
Error: ${ne(e)}`),new Error(n)}},fl=(t,e)=>new URL(t).searchParams.get(e),ml=t=>(t==null?void 0:t["op-pockyt-3ds-url"])!==void 0,hl=async(t,e)=>{const n=pl(e),r=await io({url:n["op-pockyt-3ds-url"],baseUrl:t});return{existing_cc:{vault_id:lo(r.href??""),transaction_no:n["op-pockyt-txn-no"],reference_no:n["op-pockyt-ref-no"]}}},{log__:yl,err__:Vn}=F("airwallex-cc"),_l=a.object({"op-airwallex-3ds-url":a.string(),"op-airwallex-initial-intent-id":a.string(),"op-airwallex-consent-id":a.string()}),gl=t=>{const e=_l.safeParse(t);if(!e.success){const n="Unable to process your credit card. Please contact support for assistance.",r=`Airwallex 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`;throw Vn(r),new Error(n)}return e.data},vl=t=>(t==null?void 0:t["op-airwallex-3ds-url"])!==void 0,wl=t=>{try{const e=new URL(t??"").searchParams.get("payment_intent_id");if(!e)throw new Error("No intent ID found in Airwallex 3DS verification result");return yl(`Airwallex 3DS verification success. [Intent ID: ${e}]`),e}catch(e){const n="Error verifying Airwallex 3DS verification result.";throw Vn(n,`Resulting URL: ${t}.
|
|
24
|
+
Error: ${ne(e)}`),new Error(n)}},bl=async(t,e)=>{const n=gl(e),r=await io({url:n["op-airwallex-3ds-url"],baseUrl:t}),o=wl(r.href??""),s=n["op-airwallex-initial-intent-id"];if(s!==o){const c="Unable to process your credit card. Please contact support for assistance.",l=`Intent ID from callback (${o}) does not match the initial intent ID (${s}).`;throw Vn(l),new Error(c)}return{existing_cc:{initial_intent_id:o,consent_id:n["op-airwallex-consent-id"]}}},uo=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),po=a.object({provider:a.literal("google_pay"),processor_name:a.literal("airwallex"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),El=a.enum(["test","live","live-us","live-in","live-apse","live-au"]),kl=a.enum(["ar","bg-BG","ca-ES","cs-CZ","da-DK","de-DE","el-GR","en-US","es-ES","et-EE","fi-FI","fr-FR","hr-HR","hu-HU","is-IS","it-IT","ja-JP","ko-KR","lt-LT","lv-LV","nl-NL","no-NO","pl-PL","pt-BR","pt-PT","ro-RO","ru-RU","sk-SK","sl-SI","sv-SE","zh-CN","zh-TW"]),{log__:ct,err__:Mt}=F("adyen-cc"),Cl=a.object({"op-account-id":a.string(),"op-adyen-client-key":a.string(),"op-adyen-environment":El,"op-adyen-action":a.string()}),fo="Unable to process your credit card. Please contact support for assistance.",Sl=t=>{const e=Cl.safeParse(t);if(!e.success)throw Mt(`Adyen 3DS is required but headers are malformed. Got: ${JSON.stringify(t)}`),new Error(fo);return e.data},Pl=t=>JSON.parse(t),mo=()=>"AdyenWeb"in window&&"AdyenCheckout"in window.AdyenWeb,Al=async()=>{ct("Waiting for Adyen SDK to load...");for(let t=0;t<10;t++)mo()||await Pn(500);if(!mo())throw Mt("Adyen SDK not loaded properly"),new Error(fo);return ct("Adyen SDK loaded successfully"),window.AdyenWeb.AdyenCheckout},Tl=t=>{const{headers:e,locale:n,countryCode:r,component:o,host:s,cancelButton:i}=t,c=Pl(e["op-adyen-action"]);return ct(`Running Adyen 3DS flow for action type: ${c.type}`),new Promise(l=>{const u=()=>{ct("Cleaning up Adyen 3DS flow"),i.removeEventListener("click",_),s.remove()},d=h=>{Mt("Authentication failed. Result:",h),l({status:Z.FAILURE,cleanup:u})},p=h=>{Mt("Adyen error:",h),l({status:Z.FAILURE,cleanup:u})},_=()=>{l({status:Z.CANCELLED,cleanup:u})};i.addEventListener("click",_);const f=(h,b,I)=>{s.remove(),l({status:Z.SUCCESS,additionalDetails:h,cleanup:u})};Al().then(h=>h({clientKey:e["op-adyen-client-key"],environment:e["op-adyen-environment"],locale:n,countryCode:r,onAdditionalDetails:f,onPaymentFailed:d,onError:p})).then(h=>{h.createFromAction(c,{challengeWindowSize:"03"}).mount(o)})})},xl=t=>{const e=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language,n=t??e,r=kl.safeParse(n);return r.success?(ct(`Resolved locale: ${r.data}`),r.data):(Mt(`Resolved invalid locale: ${n}. Defaulting to en-US.`),"en-US")},Il=t=>(t==null?void 0:t["op-adyen-action"])!==void 0,Rl=async(t,e,n)=>{const r=Sl(e),o=document.createElement("div");o.id="adyen-container";const{host:s,iframe:i,cancelButton:c}=ao("http://example.com");i.replaceWith(o);const l=await Tl({headers:r,locale:xl(n),countryCode:t,component:o,host:s,cancelButton:c});if(l.cleanup(),l.status===Z.FAILURE)throw new Error("3DS verification failed");if(l.status===Z.CANCELLED)throw new Error("3DS verification cancelled");if(l.status===Z.SUCCESS){if(!l.additionalDetails)throw new Error("3DS verification succeeded but no additional details were returned");return ct("3DS verification succeeded"),{existing_cc:{additional_details:l.additionalDetails.data}}}else un(l.status)},{log__:D,err__:ho}=F("common-cc"),{log__:yo}=F("stripe-cc");a.array(a.object({our_existing_pm_id:a.string()})).length(1);const Nl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var u;D("├ Running common CC flow...",{checkoutPaymentMethod:e});const s=t.anyCdeConnection,i=await B(s);C("common_cc_flow_started",{...e,prefill:i}),D(`├ Validating non-CDE form fields [Mode: ${i.mode}]`);const c=je(n,r.get.onValidationError);C("billing_details_received",{...c});const l={session_id:t.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{origin:window.location.origin}};try{D(`├ Tokenizing card info in CDE [Session: ${t.elementsSessionId}]`);const d=await Bc(o.currentCdeConnections,{session_id:t.elementsSessionId});if(Jc(d,r.get.onValidationError),i.mode==="setup"){D(`├ Setting up payment method in CDE [Token: ${i.token}]`);const p=await qc(s,l);return D(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{D(`├ Initial checkout flow. Checking out card info in CDE [Session: ${t.elementsSessionId}]`);const p=await Xr(s,l);return D("╰ Checkout completed successfully."),{mode:"checkout",result:p}}}catch(d){if(d instanceof Qr&&d.originalErrorMessage.includes("3DS_REQUIRED")){D("├ Card requires 3DS, starting non-legacy payment flow"),D("Received 3DS error response headers:",d.response.headers),C("3ds_required",{...e,...d.response.headers});const p=ml(d.response.headers);if(p){D("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const E=await hl(t.baseUrl,d.response.headers);l.extra_metadata.pockyt=E}if(vl(d.response.headers)){D("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const E=await bl(t.baseUrl,d.response.headers);l.extra_metadata.airwallex=E}if(Il(d.response.headers)){D("├ Adyen 3DS case detected. Going through Adyen 3DS flow.");const E=await Rl(n[m.COUNTRY],d.response.headers,i.locale);l.extra_metadata.adyen=E}const h=await $c(s,l);D("├ Payment flow result:",h);const b=((u=d.response.headers)==null?void 0:u["op-should-use-new-flow"])!=="true";p?D("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):b?(D("├ Using stripe 3DS flow"),await jl(h)):(D("├ Using common 3DS flow"),await Ll(h,t.baseUrl));const I=h.cc_pm_id;if(i.mode==="setup"){D(`├ Confirming payment flow [cc_pm_id: ${I}]`);const E=await ie(s,{secure_token:i.token,existing_cc_pm_id:I});D("├ Confirm payment flow result received Result:",E);const N=Ot(E);return D(`╰ Setup completed successfully [PM ID: ${N.payment_method_id}]`),{mode:"setup",result:N}}else{D(`├ Checking out after 3DS flow [Flow: ${b?"legacy":"new"}]`);const E=await Xr(s,{...l,existing_cc_pm_id:I,do_not_use_legacy_cc_flow:b});return D("╰ Checkout completed successfully."),{mode:"checkout",result:E}}}throw ho("╰ Error checking out card info in CDE"),ho(d),d}}),Ol=t=>{const e=t.required_user_actions.find(n=>n.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return ba.parse(e)},Ml=["airwallex_payment_consent","adyen"],Dl=t=>{const e=t.required_user_actions.find(n=>Ml.includes(n.type));if(!e)throw new Error("No common 3DS action found");return ga.parse(e)},Ll=async(t,e)=>{const n=Dl(t);if(n.redirect_url==="3DS_COMPLETE"){D("├ 3DS flow completed successfully"),C("3ds_complete");return}D(`├ Using common 3DS flow [URL: ${n.redirect_url}]`),C("3ds_redirect",{...n});const{status:r}=await pn({url:n.redirect_url,baseUrl:e});if(D(`╰ 3DS verification completed [Status: ${r}]`),r===Z.CANCELLED)throw C("3ds_cancelled"),new Error("3DS verification cancelled");if(r===Z.FAILURE)throw C("3ds_failure"),new Error("3DS verification failed")},jl=async t=>{const e=Ol(t);C("3ds_stripe_redirect",{...e}),yo(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Ta(e),C("3ds_stripe_complete"),yo("╰ Stripe 3DS flow completed successfully")},le=a.enum(["stripe","airwallex","authorize_net"]);le.Enum.stripe;const _o=({scriptId:t,src:e,checkLoadedFn:n})=>{const r=new AbortController;return new Promise((o,s)=>{let i=document.createElement("script");i.src=e,i.id=t,i.async=!0;const c=document.getElementById(t);n()?o():c?i=c:document.body.appendChild(i),i.addEventListener("load",()=>{r.abort(),o()},{signal:r.signal}),i.addEventListener("error",()=>{r.abort(),s("Failed to load the script")},{signal:r.signal})})},{log__:Q,err__:Fl}=F("stripe-pr"),Ul=a.object({provider:a.union([a.literal("apple_pay"),a.literal("google_pay")]),processor_name:a.literal("stripe"),metadata:a.object({stripe_pk:a.string()})}),$l=ze(async({context:t,formCallbacks:e})=>{Q("Checking if there are any CPMs for Stripe PR...");const n=ce(t.checkoutPaymentMethods,Ul);Q("Initializing Stripe PR flow...");const r=t.anyCdeConnection,o=await B(r),s=o.mode==="setup";Q("Getting initial preview amount");const i=await it(r,o.token,s,void 0),c=await Sa(n.metadata.stripe_pk,i.amountAtom,i.currency,s);Q("Checking if can make payment");const l=await c.canMakePayment();if(l===null)return Fl("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"};Q("Stripe PR flow initialized successfully. Can make payment",l);const u=(d,p)=>V.stripePR.run({context:t,checkoutPaymentMethod:jt(t.checkoutPaymentMethods,d),nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{provider:d,overridePaymentRequest:p==null?void 0:p.overridePaymentRequest},initResult:{processor:le.Enum.stripe,pr:c,isAvailable:!0,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}});return{processor:le.Enum.stripe,isAvailable:!0,pr:c,availableProviders:{applePay:l.applePay,googlePay:l.googlePay},startFlow:u}}),Zl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o,initResult:s})=>{if(Q("Running Stripe PR flow..."),o.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${o.provider}, got ${e.provider}`);const i=t.anyCdeConnection,c=s.pr;if(o!=null&&o.overridePaymentRequest){const h=o.overridePaymentRequest;Q("Overriding PR amount with",h),zl(c,h.amount,h.pending,h.applePayPaymentRequest,h.label)}Q("Showing PR dialog..."),c.show();const l=await Pa(c);Q("Stripe PM added event:",l),Q("Merging PM fields with form fields...");const u=Vl(n,l),d=je(u,r.get.onValidationError);C("billing_details_received",{...d}),Q("PR dialog finished. Starting payment flow...",d);const p=await Zc(i,{fields:d,checkoutPaymentMethod:e}),_=Gl(p);Q("Confirming PR with Stripe..."),await Aa(_,l);const f=await B(i);if(f.mode==="setup"){Q("Confirming payment flow for setup...");const h=await ie(i,{secure_token:f.token});return{mode:"setup",result:Ot(h)}}else{Q("Performing checkout...");const h={secure_token:f.token,payment_input:{provider_type:e.provider},customer_first_name:d[m.FIRST_NAME],customer_last_name:d[m.LAST_NAME],customer_email:d[m.EMAIL],customer_zip_code:d[m.ZIP_CODE],customer_country:d[m.COUNTRY],promotion_code:d[m.PROMOTION_CODE],line_items:f.line_items,total_amount_atom:f.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await $n(i,h)}}}),Vl=(t,e)=>{var d,p,_,f;const n={...t},[r,...o]=((p=(d=e.payerName)==null?void 0:d.trim())==null?void 0:p.split(/\s+/))??[],s=o.join(" ")||void 0,i=(f=(_=e.paymentMethod)==null?void 0:_.billing_details)==null?void 0:f.address,c=e.shippingAddress;n[m.EMAIL]=n[m.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",n[m.ZIP_CODE]=n[m.ZIP_CODE]||(i==null?void 0:i.postal_code)||(c==null?void 0:c.postalCode)||"00000",n[m.COUNTRY]=n[m.COUNTRY]||(i==null?void 0:i.country)||(c==null?void 0:c.country)||"US";const l=n[m.FIRST_NAME]||r||"",u=n[m.LAST_NAME]||s||"";return l||u?(n[m.FIRST_NAME]=l,n[m.LAST_NAME]=u):(n[m.FIRST_NAME]="_OP_UNKNOWN",n[m.LAST_NAME]=""),Q("Final form inputs:",n),n},zl=(t,e,n,r,o)=>{t.update({total:{amount:e.amountAtom,label:o??"Total",pending:n},currency:e.currency,applePay:r})},Gl=t=>{if(t.required_user_actions.length!==1)throw new Error(`Error occurred.
|
|
25
|
+
Details: got ${t.required_user_actions.length} required user actions`);return Ea.parse(t.required_user_actions[0])},{log__:ve,err__:go}=F("pockyt-paypal"),Bl=a.object({processor_name:a.literal("pockyt"),provider:a.literal("paypal")});a.array(a.object({paypal_iframe_url:a.string(),verify_token:a.string()})).length(1);const ql=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var Y,Ee;ve("Running Pockyt Paypal flow...");const s=t.anyCdeConnection,i=await B(s);ve("Verifying CPM...");const c=Bl.parse(e);ve("├ Validating non-CDE form fields");const l=o==null?void 0:o.settings,u=je(n,r.get.onValidationError,l==null?void 0:l.defaultFieldValues),d=Kc(u);ve(`Starting payment flow... Mode: ${i.mode}`);const p=Qt(),_=i.mode!=="setup",f={payment_provider:c.provider,checkout_payment_method:c,use_pay_first_flow:_,pay_first_flow_cart_info:_?{line_items:i.line_items,displayed_total_amount_atom:i.amount_total_atom}:void 0,processor_specific_metadata:{use_paypal_redirect_flow:!!((Y=o==null?void 0:o.settings)!=null&&Y.useRedirectFlow),frontend_token_for_redirect_flow:p},...d},h=new URL("/app/pre-action/start/",t.baseUrl).toString(),b=btoa(JSON.stringify(f)),I=new URLSearchParams({st:i.token,r:b}),E=`${h}?${I.toString()}`;if((Ee=o==null?void 0:o.settings)!=null&&Ee.useRedirectFlow)throw ve("Starting redirect mode for PayPal..."),window.location.href=E,await Pn(20*1e3),new Error("Paypal flow timed out, please try again with another payment method.");ve("Starting popup mode for PayPal..."),ve("Opening paypal iframe...");const N=await ll("PayPal",s,p,E);ve("Paypal flow result",N);const x=lo(N.href),O=fl(N.href,"catt");if(!O)throw go("Checkout attempt ID not found in redirect URL:",N.href),new Error("Checkout attempt ID not found in redirect URL");ve(`Confirming payment flow using vault ID ${x}`);const U=await ie(s,{secure_token:i.token,their_pm_id:x,checkout_attempt_id:_?O:void 0});if(ve("Confirm payment flow result",U),i.mode==="setup")return{mode:"setup",result:{payment_method_id:U.payment_methods[0].id}};if(!U.pay_first_success_response)throw go("Checkout failed, no pay-first success response:",U),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:U.pay_first_success_response}}),fn=({gateway:t,gatewayMerchantId:e,merchantName:n,merchantId:r,initialPreview:o,overridePaymentRequest:s,prefill:i})=>{var p,_;const c=((p=s==null?void 0:s.amount)==null?void 0:p.amountAtom)??(o==null?void 0:o.amountAtom)??0,l=Math.max(c/100,0),u=(((_=s==null?void 0:s.amount)==null?void 0:_.currency)??(i==null?void 0:i.currency)??o.currency).toUpperCase(),d={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:t,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:r??"",merchantName:n},transactionInfo:{countryCode:"US",currencyCode:u,totalPriceStatus:s!=null&&s.pending?"ESTIMATED":"FINAL",totalPrice:l.toFixed(2)}};return s!=null&&s.googlePayPaymentRequest?{...d,...s.googlePayPaymentRequest}:d},vo=()=>_o({scriptId:"__op_internal_google_pay_sdk",src:"https://pay.google.com/gp/p/js/pay.js",checkLoadedFn:()=>{var t,e;return!!((e=(t=window.google)==null?void 0:t.payments)!=null&&e.api)}});let zn=null;const wo=t=>t===Fe||t===window.location.origin?"PRODUCTION":"TEST",mn=(t,e)=>{const n=wo(t);return zn===null&&(zn=new window.google.payments.api.PaymentsClient({environment:n,merchantInfo:e.merchantInfo})),zn},Yl=t=>{const e=t.required_user_actions.find(n=>n.type==="airwallex_payment_consent");return e?lr.parse(e):null},bo=(t,e)=>{var o,s,i,c;const n={...t},r=(s=(o=e.paymentMethodData)==null?void 0:o.info)==null?void 0:s.billingAddress;if(r){const[l,...u]=((c=(i=r.name)==null?void 0:i.trim())==null?void 0:c.split(/\s+/))??[],d=u.join(" ")||void 0;n[m.EMAIL]=n[m.EMAIL]||e.email||"op_unfilled@getopenpay.com",n[m.COUNTRY]=n[m.COUNTRY]||r.countryCode||"US",n[m.ADDRESS]=n[m.ADDRESS]||r.address1||"",n[m.CITY]=n[m.CITY]||r.locality||"",n[m.ZIP_CODE]=n[m.ZIP_CODE]||r.postalCode||"00000",n[m.STATE]=n[m.STATE]||r.administrativeArea||"";const p=n[m.FIRST_NAME]||l||"",_=n[m.LAST_NAME]||d||"";p||_?(n[m.FIRST_NAME]=p,n[m.LAST_NAME]=_):(n[m.FIRST_NAME]="_OP_UNKNOWN",n[m.LAST_NAME]="")}return n},{log__:ue,err__:lt}=F("awx-google-pay"),Wl=ze(async({context:t,formCallbacks:e})=>{var p,_;const n={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,po);if(!r)return n;ue("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return lt("No gateway merchant ID found in processor account"),n;if(ue("Loading Google Pay script"),await vo(),!((_=(p=window.google)==null?void 0:p.payments)!=null&&_.api))return lt("Google Pay SDK not loaded properly"),n;if(wo(t.baseUrl)==="PRODUCTION"&&!o.google_pay_merchant_id)return lt("Google Pay merchant ID is required for production environment"),n;ue("Google Pay SDK loaded",window.google.payments);try{const f=fn({gateway:"airwallex",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:h}=await mn(t.baseUrl,f).isReadyToPay(f);if(!h)return ue("Google Pay is not available for this user"),n}catch(f){return lt("Error checking Google Pay availability",f),n}const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async f=>{try{V.airwallexGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{...f,initialPreview:u}})}catch(h){lt("Google Pay payment error",h),e.get.onCheckoutError((h==null?void 0:h.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),Hl=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{var f,h,b,I,E,N,x;ue("Starting Google Pay flow...");const s=ce(t.checkoutPaymentMethods,po),{initialPreview:i,overridePaymentRequest:c}=o,l=s.metadata;if(!l.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const u=fn({gateway:"airwallex",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:i,overridePaymentRequest:c}),d=t.anyCdeConnection,p=await B(d);C("google_pay_flow_started",{processor_name:s.processor_name,prefill:no(p,["brand"]),overridePaymentRequest:c});const _=mn(t.baseUrl,u);try{const O=await _.loadPaymentData(u);ue("Google Pay Payment data",O);const U=bo(n,O),Y=je(U,r.get.onValidationError,o==null?void 0:o.defaultFieldValues);C("billing_details_received",{...Y});const Ee=(h=(f=O.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!Ee)throw new Error("No payment token received from Google Pay");const Vu=await at(d,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:Y[m.EMAIL],new_customer_first_name:Y[m.FIRST_NAME],new_customer_last_name:Y[m.LAST_NAME],new_customer_address:{zip_code:Y[m.ZIP_CODE],country:Y[m.COUNTRY]}}),_n=Yl(Vu);ue("Start flow next actions",_n);let Ye=await ie(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:_n==null?void 0:_n.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:Ee}}}});ue("[1st] Confirm payment flow response",Ye);let qn=(I=(b=Ye.payment_methods)==null?void 0:b[0])==null?void 0:I.id;const We=(E=Ye.required_user_actions)==null?void 0:E.find($t=>$t.type==="airwallex_payment_consent");if(We&&We.redirect_url){ue("3DS Required, starting verification...",We);const{status:$t}=await pn({url:We.redirect_url,baseUrl:t.baseUrl});if(ue(`╰ 3DS verification completed [Status: ${$t}]`),$t===Z.CANCELLED)throw new Error("3DS verification cancelled");if($t===Z.FAILURE)throw new Error("3DS verification failed")}if(We&&!qn&&(Ye=await ie(d,{secure_token:p.token,their_pm_id:We.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:We.consent_id}}),ue("[2nd] Confirm payment flow response",Ye),qn=(x=(N=Ye.payment_methods)==null?void 0:N[0])==null?void 0:x.id),!qn)throw new Error("No PM ID found");return dn({logPrefix:"awx-googlepay",anyCdeConnection:d,checkoutPaymentMethod:e,requiredFormFields:Y,confirmResult:Ye,usePayFirstFlow:!1})}catch(O){throw lt("Google Pay payment error",O),C("google_pay_payment_error",{error:O}),new Error((O==null?void 0:O.message)??"Unknown error")}}),Eo=()=>_o({scriptId:"__op_internal_apple_pay_sdk",src:"https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",checkLoadedFn:()=>!!window.ApplePaySession||!!window.ApplePaySDK}),ko=(t,e)=>{const n=e.token.paymentMethod.billingContact,r=e.billingContact,o=e.shippingContact,s={...t};if(n||r||o){s[m.EMAIL]=s[m.EMAIL]||(n==null?void 0:n.emailAddress)||(r==null?void 0:r.emailAddress)||(o==null?void 0:o.emailAddress)||"op_unfilled@email.com",s[m.COUNTRY]=s[m.COUNTRY]||(n==null?void 0:n.countryCode)||(r==null?void 0:r.countryCode)||(o==null?void 0:o.countryCode)||"US",s[m.ZIP_CODE]=s[m.ZIP_CODE]||(n==null?void 0:n.postalCode)||(r==null?void 0:r.postalCode)||(o==null?void 0:o.postalCode)||"00000";const i=s[m.FIRST_NAME]||(n==null?void 0:n.givenName)||(r==null?void 0:r.givenName)||(o==null?void 0:o.givenName)||"",c=s[m.LAST_NAME]||(n==null?void 0:n.familyName)||(r==null?void 0:r.familyName)||(o==null?void 0:o.familyName)||"";i||c?(s[m.FIRST_NAME]=i,s[m.LAST_NAME]=c):(s[m.FIRST_NAME]="_OP_UNKNOWN",s[m.LAST_NAME]="")}return s};a.object({data:a.object({messageHeaders:a.record(a.string(),a.any()),errors:a.array(a.any()),messageType:a.string(),messageBody:a.record(a.string(),a.any())}),origin:a.literal("https://applepay.cdn-apple.com")});const Co=({total:t,prefill:e})=>{var r;if(e.mode==="setup")return{paymentDescription:"Setup recurring payment",regularBilling:{amount:t.amount,label:"Setup recurring payment",paymentTiming:"recurring",type:"final"},managementURL:new URL(`/pay/${e.token}`,Fe).toString()};const n=(r=e.line_items)==null?void 0:r[0];if(n)return{paymentDescription:(n==null?void 0:n.description)??"",regularBilling:{amount:t.amount,label:(n==null?void 0:n.description)??"",recurringPaymentIntervalUnit:n==null?void 0:n.billing_interval,recurringPaymentIntervalCount:(n==null?void 0:n.billing_interval_count)??void 0,paymentTiming:"recurring",type:"final"},managementURL:`https://cde.getopenpay.com/pay/${e.token}`}},So=({overridePaymentRequest:t,initialPreview:e,prefill:n,defaultLabel:r="Total"})=>{var c,l;const o=(((c=t==null?void 0:t.amount)==null?void 0:c.currency)??(n==null?void 0:n.currency)??e.currency).toUpperCase(),i=((((l=t==null?void 0:t.amount)==null?void 0:l.amountAtom)??(e==null?void 0:e.amountAtom)??0)/100).toFixed(2);return{currencyCode:o,total:{label:(t==null?void 0:t.label)??r??"Total",type:t!=null&&t.pending?"pending":"final",amount:i}}},{log__:hn}=F("awx-apple-pay");async function Kl(t,e){try{const r=(await Zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{airwallex_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function Jl(t,e){if(!t.redirect_url)throw new Error("No redirect URL found");hn("3DS Required, starting verification...",t);const{status:n}=await pn({url:t.redirect_url,baseUrl:e.baseUrl});if(hn(`╰ 3DS verification completed [Status: ${n}]`),n===Z.CANCELLED)throw new Error("3DS verification cancelled");if(n===Z.FAILURE)throw new Error("3DS verification failed");const r=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:t.their_pm_id,airwallex_consent_id:t.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return hn("[2nd] Confirm payment flow response",r),r}async function Ql(t,e){var n,r,o,s,i;try{const c=t.payment,l=ko(e.nonCdeFormInputs,c),u=je(l,e.formCallbacks.get.onValidationError,e.defaultFieldValues);C("billing_details_received",{...u});const _=(await at(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:u[m.EMAIL],new_customer_first_name:u[m.FIRST_NAME],new_customer_last_name:u[m.LAST_NAME],new_customer_address:{zip_code:u[m.ZIP_CODE],country:u[m.COUNTRY]}})).required_user_actions[0].consent_id;if(!_)throw new Error("No consent ID received from payment flow");let f=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:_,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(c.token)}}}});hn("[1st] Confirm payment flow response",f);let h=(r=(n=f.payment_methods)==null?void 0:n[0])==null?void 0:r.id;const b=(o=f.required_user_actions)==null?void 0:o.find(E=>E.type==="airwallex_payment_consent");if(b!=null&&b.redirect_url&&b.consent_id&&b.their_pm_id&&(f=await Jl(b,e),h=(i=(s=f.payment_methods)==null?void 0:s[0])==null?void 0:i.id),!h)throw new Error("No PM ID found");const I={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(I),dn({logPrefix:"awx-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:u,confirmResult:f,usePayFirstFlow:!1})}catch(c){const l={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(l),c}}const{log__:Dt,err__:Po}=F("awx-apple-pay"),Xl=ze(async({context:t,formCallbacks:e})=>{const n={processor:le.Enum.airwallex,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,uo);if(!r)return n;if(Dt("Loading Apple Pay script"),await Eo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return Dt("Apple Pay is not available on this device/browser"),n;if(Dt("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Dt("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async p=>{try{await V.airwallexApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Po("Apple Pay payment error",_),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.airwallex,isAvailable:!0,isLoading:!1,startFlow:d}}),eu=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var I;const s=ce(t.checkoutPaymentMethods,uo),{overridePaymentRequest:i,initialPreview:c}=r,l=t.anyCdeConnection,u=await B(l),d=u.mode==="setup",{currencyCode:p,total:_}=So({overridePaymentRequest:i,initialPreview:c,defaultLabel:(I=s==null?void 0:s.metadata)==null?void 0:I.processor_account_name}),f={countryCode:"US",currencyCode:p,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:_,recurringPaymentRequest:Co({total:_,prefill:u}),...(i==null?void 0:i.applePayPaymentRequest)??{}},h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:s.metadata,prefill:u,isSetupMode:d,baseUrl:t.baseUrl,formCallbacks:o,defaultFieldValues:r==null?void 0:r.defaultFieldValues};return C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:no(u,["brand"]),overridePaymentRequest:i}),new Promise((E,N)=>{const x=()=>{Dt("Payment cancelled by user"),N(new Error("Payment cancelled by user"))};h.oncancel=x,h.onvalidatemerchant=async O=>{try{await Kl(O,b)}catch(U){N(U)}},h.onpaymentmethodselected=()=>{const O={newTotal:{..._}};h.completePaymentMethodSelection(O)},h.onpaymentauthorized=async O=>{C("apple_pay_payment_authorized");try{const U=await Ql(O,b);E(U)}catch(U){N(U)}},h.begin()}).catch(E=>{throw Po("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),tu=1,nu=a.object({processor_name:a.literal("loop"),provider:a.literal("crypto"),metadata:a.object({merchant_id:a.string(),entity_id:a.string(),api_token:a.string(),supported_currencies:a.array(a.string()),environment:a.string()})}),{log__:X,err__:Ao}=F("loop-crypto"),ru=a.object({loopFirstName:$,loopLastName:$,loopEmail:$,[m.PROMOTION_CODE]:j}),ou=(t,e,n)=>{const r=ru.safeParse(t);if(!r.success){const o=r.error.format(),s=ur(o);for(const[i,c]of Object.entries(s))e(i,c,i);throw Ao("Got validation errors in non-CDE form fields",s),new Error("Got validation errors in non-CDE form fields")}return r.data},su=ze(async({context:t})=>{X("Checking if there are any CPMs for Loop Crypto...");const e=ce(t.checkoutPaymentMethods,nu);X(`checkoutPaymentMethod: ${JSON.stringify(e)}`),X("Starting Loop Crypto flow...");const n=await B(t.anyCdeConnection),r=await Zn(t.anyCdeConnection,{checkout_payment_method:e});if(n.mode!=="setup"&&!e.metadata.supported_currencies.includes(n.currency))throw Error(`Currency ${n.currency} not enabled for Loop. Enabled currencies: ${e.metadata.supported_currencies}`);if(!r||!r.next_action_metadata)throw Error("Failed to fetch necessary setup data for Loop");const o=r.next_action_metadata;let s;n.mode==="setup"?s=tu:s=n.amount_total_atom*o.token_price;const i=s,c=o.authorization_amount,l=Qt(),u={paymentUsdAmount:i,suggestedAuthorizationUsdAmount:c,customerRefId:l},d={apiKey:e.metadata.api_token,entityId:e.metadata.entity_id,merchantId:e.metadata.merchant_id,environment:e.metadata.environment};return{isAvailable:!0,widgetProps:u,initLoopConnectProps:d}}),au=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,formCallbacks:r,customParams:o})=>{X("Running Loop flow..."),X("context",t),X("checkoutPaymentMethod",e),X("nonCdeFormInputs",n),X("flowCallbacks",r),X("customParams",o);const s=ou(n,r.get.onValidationError),i=t.anyCdeConnection,c=await B(t.anyCdeConnection),l=c.mode!=="setup",u=await at(t.anyCdeConnection,{checkout_payment_method:e,payment_provider:e.provider,new_customer_email:s.loopEmail,new_customer_first_name:s.loopFirstName,new_customer_last_name:s.loopLastName,use_pay_first_flow:l,pay_first_flow_cart_info:l?{line_items:c.line_items,displayed_total_amount_atom:c.amount_total_atom}:void 0});if(!o)throw Error("Checkout failed. Failed to properly submit form data.");const d=await ie(i,{secure_token:c.token,their_pm_id:o.success?o.payin.paymentMethod.paymentMethodId:void 0,checkout_attempt_id:c.mode!=="setup"?u.checkout_attempt_id:void 0,processor_specific_metadata:{loop_customer:o.success?o.customer:void 0,loop_payin:o.success?o.payin:void 0,loop_failure_details:o.success?void 0:o.failureDetails,loop_success:o.success}});if(X(`Confirm result: ${d}`),c.mode==="setup"){X("Doing payment setup..."),X("├ Confirm payment flow result received Result:",d);const p=Ot(d);return X(`╰ Setup completed successfully [PM ID: ${p.payment_method_id}]`),{mode:"setup",result:p}}else{if(X("Doing checkout..."),!d.pay_first_success_response)throw Ao("Checkout failed, no pay-first success response:",d),new Error("Checkout failed, please try again with another payment method.");return{mode:"checkout",result:d.pay_first_success_response}}});async function iu(t,e){try{const r=(await Zn(e.connection,{checkout_payment_method:e.checkoutPaymentMethod,processor_specific_metadata:{apple_payment_session:{validation_url:t.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).next_action_metadata,o=r==null?void 0:r.apple_pay_session;if(!o)throw new Error("No session data received from payment flow");e.session.completeMerchantValidation(o),C("apple_pay_complete_merchant_validation",{...o})}catch(n){throw e.session.abort(),n}}async function cu(t,e){var n,r;try{const o=t.payment,s=ko(e.nonCdeFormInputs,o),i=je(s,e.formCallbacks.get.onValidationError);C("billing_details_received",{...i}),await at(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:i[m.EMAIL],new_customer_first_name:i[m.FIRST_NAME],new_customer_last_name:i[m.LAST_NAME],new_customer_address:{zip_code:i[m.ZIP_CODE],country:i[m.COUNTRY]}});const c={dataDescriptor:"COMMON.APPLE.INAPP.PAYMENT",dataValue:window.btoa(JSON.stringify(o.token.paymentData))},l=await ie(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,mobile_wallet_payment_data:c}});if(!((r=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:r.id))throw new Error("No PM ID found");const d={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(d),dn({logPrefix:"authnet-applepay",anyCdeConnection:e.connection,checkoutPaymentMethod:e.checkoutPaymentMethod,requiredFormFields:i,confirmResult:l,usePayFirstFlow:!1})}catch(o){const s={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(s),o}}const To=a.object({provider:a.literal("apple_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string()})}),xo=a.object({provider:a.literal("google_pay"),processor_name:a.literal("authorize_net"),metadata:a.object({processor_account_id:a.string(),processor_account_name:a.string(),google_pay_merchant_id:a.string().nullish()})}),{log__:yn,err__:Io}=F("authnet-applepay"),lu=ze(async({context:t,formCallbacks:e})=>{const n={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,To);if(!r)return n;if(yn("Loading Apple Pay script"),await Eo(),!window.ApplePaySession||!ApplePaySession.canMakePayments())return yn("Apple Pay is not available on this device/browser"),n;if(!await ApplePaySession.canMakePayments())return yn("No active cards available for Apple Pay"),n;if(!r.metadata.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const i=t.anyCdeConnection,c=await B(i),l=c.mode==="setup",u=await it(i,c.token,l,void 0),d=async p=>{try{await V.authorizeNetApplePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,customParams:{...p,initialPreview:u},initResult:void 0})}catch(_){Io("Apple Pay payment error",_),C("apple_pay_payment_error",{error:_}),e.get.onCheckoutError((_==null?void 0:_.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:d}}),uu=Pe(async({context:t,checkoutPaymentMethod:e,nonCdeFormInputs:n,customParams:r,formCallbacks:o})=>{var I;const{initialPreview:s,overridePaymentRequest:i}=r,c=ce(t.checkoutPaymentMethods,To),{currencyCode:l,total:u}=So({overridePaymentRequest:i,initialPreview:s,defaultLabel:(I=c==null?void 0:c.metadata)==null?void 0:I.processor_account_name}),d=t.anyCdeConnection,p=await B(d),_=p.mode==="setup",f={countryCode:"US",currencyCode:l,total:u,requiredBillingContactFields:["email","postalAddress","name"],requiredShippingContactFields:["email"],supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],recurringPaymentRequest:Co({total:u,prefill:p}),...(i==null?void 0:i.applePayPaymentRequest)??{}};C("apple_pay_flow_started",{processor_name:e.processor_name,prefill:p,overridePaymentRequest:i});const h=new ApplePaySession(3,f),b={session:h,connection:t.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:n,processorAccount:e.metadata,prefill:p,isSetupMode:_,baseUrl:t.baseUrl,formCallbacks:o};return new Promise((E,N)=>{h.oncancel=()=>{yn("Payment cancelled by user"),N(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async x=>{try{await iu(x,b)}catch(O){N(O)}},h.onpaymentmethodselected=()=>{const x={newTotal:f.total};h.completePaymentMethodSelection(x)},h.onpaymentauthorized=async x=>{C("apple_pay_payment_authorized");try{const O=await cu(x,b);E(O)}catch(O){N(O)}},h.begin()}).catch(E=>{throw Io("Apple Pay payment error",E),C("apple_pay_payment_error",{error:E}),E})}),{log__:Ge,err__:Lt}=F("authnet-googlepay"),du=ze(async({context:t,formCallbacks:e})=>{var d,p;Ge("Initializing Authnet GooglePay flow");const n={processor:le.Enum.authorize_net,isAvailable:!1,isLoading:!1,startFlow:async()=>{}},r=ce(t.checkoutPaymentMethods,xo);if(!r)return n;Ge("Google Pay CPM",r);const o=r.metadata;if(!o.processor_account_id)return Lt("No gateway merchant ID found in processor account"),n;if(Ge("Loading Google Pay script"),await vo(),!((p=(d=window.google)==null?void 0:d.payments)!=null&&p.api))return Lt("Google Pay SDK not loaded properly"),n;Ge("Google Pay SDK loaded",window.google.payments);try{const _=fn({gateway:"authorizenet",gatewayMerchantId:o.processor_account_id,merchantName:o.processor_account_name,merchantId:o.google_pay_merchant_id??"",initialPreview:{amountAtom:0,currency:"USD"}}),{result:f}=await mn(t.baseUrl,_).isReadyToPay(_);if(!f)return Ge("Google Pay is not available for this user"),n}catch(_){return Lt("Error checking Google Pay availability",_),n}const s=t.anyCdeConnection,i=await B(s),c=i.mode==="setup",l=await it(s,i.token,c,void 0),u=async _=>{try{V.authorizeNetGooglePay.run({context:t,checkoutPaymentMethod:r,nonCdeFormInputs:ye(t.formDiv),formCallbacks:e,initResult:void 0,customParams:{..._,initialPreview:l}})}catch(f){Lt("Google Pay payment error",f),C("google_pay_payment_error",{error:f}),e.get.onCheckoutError((f==null?void 0:f.message)??"Unknown error")}};return{processor:le.Enum.authorize_net,isAvailable:!0,isLoading:!1,startFlow:u}}),pu=Pe(async({context:t,nonCdeFormInputs:e,checkoutPaymentMethod:n,formCallbacks:r,customParams:o})=>{var f,h,b,I;const{initialPreview:s,overridePaymentRequest:i}=o,l=ce(t.checkoutPaymentMethods,xo).metadata,u=fn({gateway:"authorizenet",gatewayMerchantId:l.processor_account_id,merchantName:l.processor_account_name,merchantId:l.google_pay_merchant_id??"",initialPreview:s,overridePaymentRequest:i}),d=t.anyCdeConnection,p=await B(d);C("google_pay_flow_started",{processor_name:n.processor_name,prefill:p,overridePaymentRequest:i});const _=mn(t.baseUrl,u);try{const E=await _.loadPaymentData(u);Ge("Google Pay Payment data",E);const N=bo(e,E),x=je(N,r.get.onValidationError);C("billing_details_received",{...x});const O=(h=(f=E.paymentMethodData)==null?void 0:f.tokenizationData)==null?void 0:h.token;if(!O)throw new Error("No payment token received from Google Pay");const U=await at(d,{payment_provider:n.provider,checkout_payment_method:n,new_customer_email:x[m.EMAIL],new_customer_first_name:x[m.FIRST_NAME],new_customer_last_name:x[m.LAST_NAME],new_customer_address:{zip_code:x[m.ZIP_CODE],country:x[m.COUNTRY]}});Ge("Start payment flow response",U);const Y=await ie(d,{secure_token:p.token,processor_specific_metadata:{payment_provider:n.provider,mobile_wallet_payment_data:{dataDescriptor:"COMMON.GOOGLE.INAPP.PAYMENT",dataValue:window.btoa(O)}}});if(!((I=(b=Y.payment_methods)==null?void 0:b[0])==null?void 0:I.id))throw new Error("No PM ID found");return dn({logPrefix:"authnet-googlepay",anyCdeConnection:d,checkoutPaymentMethod:n,requiredFormFields:x,confirmResult:Y,usePayFirstFlow:!1})}catch(E){throw Lt("Google Pay payment error",E),C("google_pay_payment_error",{error:E}),new Error((E==null?void 0:E.message)??"Unknown error")}}),jt=(t,e,n)=>{const r=t.filter(o=>{const s=n===void 0?!0:o.processor_name===n,i=o.provider===e;return s&&i});if(r.length===0)throw console.error("CPMs list",t),new Error(`No CPMs found with provider '${e}' and processor '${n}'`);if(r.length!==1)throw console.error("CPMs list",t),new Error(`More than one CPM found with provider '${e}' and processor '${n}'`);return r[0]},V={commonCC:{init:async()=>{},run:Nl},stripePR:{init:$l,run:Zl},stripeLink:{init:tl,run:nl},pockytPaypal:{run:ql},airwallexGooglePay:{init:Wl,run:Hl},airwallexApplePay:{init:Xl,run:eu},loopCrypto:{init:su,run:au},authorizeNetApplePay:{init:lu,run:uu},authorizeNetGooglePay:{init:du,run:pu}},{log__:fu,err__:mu}=F("init-flows"),Be=(t,e)=>{const n=new Nt;return{publisher:n,initialize:async r=>{try{if(n.current.isSuccess)throw new Error("This flow has already been initialized.");const o=await e(r);fu(`✔ ${t} flow initialized successfully. Result:`,o),n.set(o)}catch(o){mu(`𝙭 ${t} flow initialization failed. Error:`,ne(o),"Details:",o),n.throw(o,ne(o))}}}},hu=async(t,e,n)=>{await Promise.all(Object.values(t).map(r=>r.initialize({context:e,formCallbacks:n})))},yu=()=>({stripePR:Be("Stripe PR",V.stripePR.init),stripeLink:Be("Stripe Link",V.stripeLink.init),airwallexGooglePay:Be("Airwallex GooglePay",V.airwallexGooglePay.init),airwallexApplePay:Be("Airwallex ApplePay",V.airwallexApplePay.init),loop:Be("Loop",V.loopCrypto.init),authorizeNetGooglePay:Be("Authnet GooglePay",V.authorizeNetGooglePay.init),authorizeNetApplePay:Be("Authnet ApplePay",V.authorizeNetApplePay.init)}),{err__:_u}=F("form-callbacks"),de=a.function().optional(),Ro=a.object({onFocus:de,onBlur:de,onChange:de,onLoad:de,onLoadError:de,onValidationError:de,onCheckoutStarted:de,onCheckoutSuccess:de,onSetupPaymentMethodSuccess:de,onCheckoutError:de,onPaymentRequestLoad:de}),be=class be{constructor(){this.setCallbacks=e=>{this._callbacks=be.createEmptyCallbacks(),Object.entries(e).forEach(([n,r])=>{const o=Bs(n,r??be.NOOP,_u);this._callbacks[n]=o})},this._callbacks=be.createEmptyCallbacks()}get get(){return{...this._callbacks}}};be.NOOP=()=>{},be.createEmptyCallbacks=()=>{const e={};return Object.keys(Ro.keyof().enum).forEach(n=>{e[n]=be.NOOP}),e},be.fromObject=e=>{const n=new be;return n.setCallbacks(Ro.parse(e)),n};let Gn=be;const gu="error",vu="debug",wu=console.error,bu=console.debug;typeof window<"u"&&(window._ojs_console_callbacks=[]),console.error=function(...t){wu.call(console,...t),window._ojs_console_callbacks.forEach(e=>e(gu,...t))},console.debug=function(...t){bu.call(console,...t),window._ojs_console_callbacks.forEach(e=>e(vu,...t))};const No="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ft=32,Eu=16,Oo=10,Mo=0xffffffffffff;var qe;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(qe||(qe={}));class Ut extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e}}function ku(t){let e=Math.floor(t()*Ft);return e===Ft&&(e=Ft-1),No.charAt(e)}function Cu(t){const e=Su(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return()=>n.randomBytes(1).readUInt8()/255;throw new Ut(qe.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Su(){return Tu()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Pu(t,e){let n="";for(;t>0;t--)n=ku(e)+n;return n}function Au(t,e=Oo){if(isNaN(t))throw new Ut(qe.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Mo)throw new Ut(qe.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Mo}: ${t}`);if(t<0)throw new Ut(qe.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new Ut(qe.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,r="";for(let o=e;o>0;o--)n=t%Ft,r=No.charAt(n)+r,t=(t-n)/Ft;return r}function Tu(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function xu(t,e){const n=Cu(),r=Date.now();return Au(r,Oo)+Pu(Eu,n)}const Do="op_analytics_device_token",Iu=()=>{const t=document.cookie.split(";").find(n=>n.includes(Do));if(t)return t.split("=")[1];const e=xu();return Ru(e),e},Ru=t=>{const e=new Date;e.setFullYear(e.getFullYear()+1),document.cookie=`${Do}=${t}; path=/; expires=${e.toUTCString()}`};function Nu(){if(typeof window>"u")return"unknown";try{const t=window;if(t.next||t.__NEXT_DATA__||document.querySelector("#__next"))return"nextjs";if(window.__NUXT__||document.querySelector("#__nuxt"))return"nuxt";if(Object.keys(document).find(r=>r.includes("react"))||Array.from(document.body.querySelectorAll("body > *")).find(r=>r._reactRootContainer))return"react";const n=window;return n.Vue||n.__VUE__?"vue":document.querySelector("[ng-version]")?"angular":"vanilla"}catch{return"unknown"}}function Ou(t){var e,n;if(typeof window>"u")return null;try{switch(t){case"react":return null;case"nextjs":{const r=window;return((e=r.next)==null?void 0:e.version)||((n=r.__NEXT_DATA__)==null?void 0:n.buildId)||null}case"nuxt":return null;case"vue":return null;case"angular":{const r=document.querySelector("[ng-version]");return r?r.getAttribute("ng-version"):null}default:return null}}catch{return null}}function Mu(){const t=Nu(),e=Ou(t);return{framework:t,version:e}}const Lo={prod:"https://cde.getopenpay.com",stg:"https://cde.openpaystaging.com",dev:"http://localhost:8001"},Du={prod:"https://connto.getopenpay.com",stg:"https://connto.openpaystaging.com",dev:"http://localhost:8000"},Lu=t=>{const e=new URL(t);return Object.keys(Lo).find(r=>e.toString().startsWith(Lo[r]))??"dev"},ju=t=>Du[t];class Fu{constructor(e,n,r,o){this.handleMessage=s=>{if(!s.source){console.warn("[OJS] No source found");return}if(jo(s.origin)!==jo(this.baseUrl)||typeof s.data=="object"&&s.data.penpal||typeof s.data=="object"&&s.data.source&&s.data.source==="react-devtools-bridge")return;let i=null;try{i=Ma(JSON.parse(s.data))}catch{return}if(!this.validateEvent(i))return;const{elementId:l,payload:u}=i,d=u.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(u.height?`${u.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(l,u.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(l,u.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(l,u.elementType,u.errors);break;case"LOADED":this.eventTargets[l]=s.source,this.internalCallbacks.onCdeLoaded(u);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(u.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(u.elementType,u.errors,l);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=s=>s.formId!==this.formId||!s.elementId?(console.log("[OJS] formId",this.formId,s.formId),console.warn("[form] Ignoring unknown event:",s),!1):this.nonces.has(s.nonce)?(console.warn("[form] Ignoring duplicate event:",s),!1):(this.nonces.add(s.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=n,this.formCallbacks=r,this.internalCallbacks=o}}const jo=t=>new URL(t).origin;async function Uu(t,e){const r=await _r({iframe:t,debug:!1,childOrigin:e}).promise,o=await ni(r);if(!ri(r,o))throw new Error("Got invalid CDE connection object");return r}class $u{constructor(){this.connections=new Map}addConnection(e,n){this.connections.set(e,n)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const Zu=(t,e,n)=>{const{stripePR:r}=t;r.publisher.subscribe(o=>{if(o.isSuccess){const s=o.loadedValue,i=s.isAvailable&&s.availableProviders.applePay,c=s.isAvailable&&s.availableProviders.googlePay,l={apple_pay:{isLoading:!1,isAvailable:i,startFlow:async u=>{i&&Fo("apple_pay",s,e,n,u)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async u=>{c&&Fo("google_pay",s,e,n,u)}}};n.get.onPaymentRequestLoad(l)}})},Fo=(t,e,n,r,o)=>V.stripePR.run({context:n,checkoutPaymentMethod:jt(n.checkoutPaymentMethods,t),nonCdeFormInputs:ye(n.formDiv),formCallbacks:r,customParams:{provider:t,overridePaymentRequest:o==null?void 0:o.overridePaymentRequest},initResult:e}),Uo="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:we,err__:Te}=F("op-form"),xe=class xe{constructor(e){this.cdeLoadEvent=new Nt,this.anyCdeConn=new Nt,this.context=new Nt,this.initFlows=yu(),this.startFormInit=async()=>{try{const o=this.createElement(he.CDE_BRIDGE);o.node.id="__op_internal_cde_bridge",o.node.ariaHidden="true",Object.assign(o.node.style,{border:"none",margin:"0px",padding:"0px",width:"1px",height:"1px",overflow:"hidden",visibility:"hidden",position:"fixed",pointerEvents:"none",userSelect:"none"}),o.mount("body"),we("CDE bridge element mounted"),we("Initializing OpenPay form:"),we("├ Waiting for CDE load event...");const s=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:Uo});we("├ CDE load event received"),we("├ Waiting for CDE connection...");const i=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:Uo});we("├ CDE connection received"),await Wc(i,this.deviceToken),we("├ Creating OJS context, setting up handlers...");const c=xe.buildOjsFlowContext(this.config,s,i,this.getFormDiv());this.context.set(c),Zu(this.initFlows,c,this.formCallbacks),we("├ Starting OJS init flows..."),await hu(this.initFlows,c,this.formCallbacks),this.formCallbacks.get.onLoad(s.totalAmountAtoms,s.currency),we("╰ Done initializing OJS flows."),C("form_loaded")}catch(o){const s=ne(o);Te("╰ Error initializing OP form:",s),C("form_init_error",{error:s}),this.formCallbacks.get.onLoadError(s)}},this.setFormHeight=o=>{this.formProperties.height=o,this.registeredElements&&Object.values(this.registeredElements).forEach(s=>{!s||s.type===he.CDE_BRIDGE||(s.node.style.height=o)})},this.onCdeLoaded=o=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.set(o),C("cde_loaded"))},this.onCdeLoadError=o=>{this.cdeLoadEvent.current.isSuccess||(this.cdeLoadEvent.throw(new Error(o),o),C("cde_load_error",{error:o}))},this.createElement=(o,s={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const i=Ys.parse(o),c=document.createElement("iframe"),l=this.buildQueryString(s);c.name=`${i}-element`;const u=new URL(`/app/v1/${c.name}/`,this.config.baseUrl);return u.search=l.toString(),c.src=u.href,c.style.border="none",c.style.width="100%",this.registerIframe(i,c)},this.registerIframe=(o,s)=>{const i={type:o,node:s,mount:c=>{var l;(l=document.querySelector(c))==null||l.appendChild(s),C("element_mounted",{element_type:o})}};return this.connectToElement({type:i.type,node:i.node}),this.registeredElements||(this.registeredElements={[he.CARD]:void 0,[he.CARD_NUMBER]:void 0,[he.CARD_EXPIRY]:void 0,[he.CARD_CVC]:void 0,[he.CDE_BRIDGE]:void 0}),this.registeredElements[o]=i,i},this.buildQueryString=o=>{const s=new URLSearchParams;return s.append("referer",this.referrer),s.append("formId",this.formId),o.styles&&s.append("styles",xa(o.styles)),s.append("secureToken",this.config.checkoutSecureToken),s},this.connectToElement=o=>{Uu(o.node).then(s=>{this.connectionManager.addConnection(o.type,s),!this.anyCdeConn.current.isSuccess&&o.type===he.CDE_BRIDGE&&this.anyCdeConn.set(s)}).catch(s=>Te("[FORM] Error connecting to CDE iframe",s))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{C("submit_card");const o=this.context.getValueIfLoadedElse(null);if(!o){Te("Please wait for the form to finish loading before submitting.");return}V.commonCC.run({context:o,checkoutPaymentMethod:jt(o.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ye(o.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.getAvailablePaymentMethods=()=>{if(!this.context.getValueIfLoadedElse(null)){Te("Please wait for the form to finish loading before getting available payment methods.");return}const s={airwallexGooglePay:te.airwallexGooglePay,airwallexApplePay:te.airwallexApplePay,authorizeNetGooglePay:te.authorizenetGooglePay,authorizeNetApplePay:te.authorizenetApplePay},i=Object.entries(this.initFlows).map(([c,l])=>({name:s[c]??c,...l.publisher.getValueIfLoadedElse(null)}));return C("get_available_payment_methods",{available_payment_methods:i}),i},this.generalSubmit=(o,s)=>{C("general_form_submit",{method:o,settings:s});const i=this.context.getValueIfLoadedElse(null);if(!i){Te("Please wait for the form to finish loading before submitting.");return}switch(o){case te.pockytPaypal:return V.pockytPaypal.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ye(i.formDiv),formCallbacks:this.formCallbacks,customParams:{settings:s},initResult:void 0});case te.airwallexGooglePay:{const c=this.initFlows.airwallexGooglePay.publisher.getValueIfLoadedElse(null);if(!c){Te("airwallex-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.airwallexApplePay:{const c=this.initFlows.airwallexApplePay.publisher.getValueIfLoadedElse(null);if(!c){Te("airwallex-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.authorizenetGooglePay:{const c=this.initFlows.authorizeNetGooglePay.publisher.getValueIfLoadedElse(null);if(!c){Te("authorize-net-google-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.authorizenetApplePay:{const c=this.initFlows.authorizeNetApplePay.publisher.getValueIfLoadedElse(null);if(!c){Te("authorize-net-apple-pay is not available. Please check the availability using 'getAvailablePaymentMethods()'");return}return c.startFlow(s)}case te.loopCrypto:return V.loopCrypto.run({context:i,checkoutPaymentMethod:jt(i.checkoutPaymentMethods,"crypto","loop"),nonCdeFormInputs:ye(i.formDiv),formCallbacks:this.formCallbacks,customParams:s,initResult:void 0});default:un(o)}},this.submit=this.submitCard,this.destroy=()=>{we("Destroying OpenPay form...");for(const o of Object.values(this.registeredElements??{}))o&&o.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),Lc(),this.registeredElements=null,delete window.ojs,C("form_destroyed")},this.updateCallbacks=o=>{this.formCallbacks.setCallbacks(o)},xe.assignAsSingleton(this),this.ojsVersion="0.2.24",this.ojsReleaseVersion="0.2.24",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Gn.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Qt()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new $u,this.deviceToken=Iu(),Dc();const{framework:n,version:r}=Mu();Un.current.isSuccess||Un.set({checkoutSecureToken:this.config.checkoutSecureToken,deviceToken:this.deviceToken,metricsBaseUrl:ju(Lu(this.baseUrl)),framework:n,frameworkVersion:r,ojsVersion:this.ojsVersion,ojsReleaseVersion:this.ojsReleaseVersion,referrer:this.referrer,baseUrl:this.baseUrl}),C("form_init"),this.eventHandler=new Fu(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};xe.ojsFlows=V,xe.assignAsSingleton=e=>{if(xe.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},xe.getInstance=()=>window.ojs??null,xe.buildOjsFlowContext=(e,n,r,o)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??Fe).origin,formDiv:o,elementsSessionId:n.sessionId,checkoutPaymentMethods:n.checkoutPaymentMethods,anyCdeConnection:r,customInitParams:e.customInitParams??{}});let Bn=xe;ke.FieldName=m,ke.OpenPayForm=Bn,ke.SubmitMethod=qs,ke.SubmitMethods=te,Object.defineProperty(ke,Symbol.toStringTag,{value:"Module"})});
|