mapper.js 85 KB

1234567891011121314151617181920
  1. !function(){"use strict";function e(e){return(...t)=>{if(globalThis.document?.documentElement){console.log(e,...t);const n=function(e){const t=e+"_log",n=document.getElementById(t);if(n)return n;const s=document.createElement("div");return s.id=t,s.innerHTML=`<h3>${e}:</h3>`,document.body.appendChild(s),s}(e),s=document.createElement("pre");s.textContent=t.join(", "),n.appendChild(s)}}}class t{method;params;constructor(e,t){this.method=e,this.params=t}}var n;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),s={};for(const e of n)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)}}(n||(n={}));const s=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),r=e=>{switch(typeof e){case"undefined":return s.undefined;case"string":return s.string;case"number":return isNaN(e)?s.nan:s.number;case"boolean":return s.boolean;case"function":return s.function;case"bigint":return s.bigint;case"object":return Array.isArray(e)?s.array:null===e?s.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?s.promise:"undefined"!=typeof Map&&e instanceof Map?s.map:"undefined"!=typeof Set&&e instanceof Set?s.set:"undefined"!=typeof Date&&e instanceof Date?s.date:s.object;default:return s.unknown}},a=n.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"]);class i extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};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(e){return e.message},n={_errors:[]},s=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(s);else if("invalid_return_type"===r.code)s(r.returnTypeError);else if("invalid_arguments"===r.code)s(r.argumentsError);else if(0===r.path.length)n._errors.push(t(r));else{let e=n,s=0;for(;s<r.path.length;){const n=r.path[s];s===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],s++}}};return s(this),n}toString(){return this.message}get message(){return JSON.stringify(this.issues,b,2)}get isEmpty(){return 0===this.issues.length}flatten(e=(e=>e.message)){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}i.create=e=>new i(e);const o=(e,t)=>{let r;switch(e.code){case a.invalid_type:r=e.received===s.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case a.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,b)}`;break;case a.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case a.invalid_union:r="Invalid input";break;case a.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case a.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case a.invalid_arguments:r="Invalid function arguments";break;case a.invalid_return_type:r="Invalid function return type";break;case a.invalid_date:r="Invalid date";break;case a.invalid_string:"object"==typeof e.validation?"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case a.too_small:r="array"===e.type?`Array must contain ${e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be greater than ${e.inclusive?"or equal to ":""}${e.minimum}`:"date"===e.type?`Date must be greater than ${e.inclusive?"or equal to ":""}${new Date(e.minimum)}`:"Invalid input";break;case a.too_big:r="array"===e.type?`Array must contain ${e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be less than ${e.inclusive?"or equal to ":""}${e.maximum}`:"date"===e.type?`Date must be smaller than ${e.inclusive?"or equal to ":""}${new Date(e.maximum)}`:"Invalid input";break;case a.custom:r="Invalid input";break;case a.invalid_intersection_types:r="Intersection results could not be merged";break;case a.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};let c=o;function d(){return c}const l=e=>{const{data:t,path:n,errorMaps:s,issueData:r}=e,a=[...n,...r.path||[]],i={...r,path:a};let o="";const c=s.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...r,path:a,message:r.message||o}};function u(e,t){const n=l({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,d(),o].filter((e=>!!e))});e.common.issues.push(n)}class h{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if("aborted"===s.status)return p;"dirty"===s.status&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t)n.push({key:await e.key,value:await e.value});return h.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:t,value:r}=s;if("aborted"===t.status)return p;if("aborted"===r.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),(void 0!==r.value||s.alwaysSet)&&(n[t.value]=r.value)}return{status:e.value,value:n}}}const p=Object.freeze({status:"aborted"}),m=e=>({status:"valid",value:e}),g=e=>"aborted"===e.status,f=e=>"dirty"===e.status,v=e=>"valid"===e.status,y=e=>void 0!==typeof Promise&&e instanceof Promise,b=(e,t)=>"bigint"==typeof t?t.toString():t;var _;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(_||(_={}));class w{constructor(e,t,n,s){this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._path.concat(this._key)}}const x=(e,t)=>{if(v(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,error:new i(e.common.issues)}};function C(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:r}=e;if(t&&(n||s))throw new Error('Can\'t use "invalid" or "required" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=s?s:t.defaultError}:{message:null!=n?n:t.defaultError},description:r}}class T{constructor(e){this.spa=this.safeParseAsync,this.superRefine=this._refinement,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.default=this.default.bind(this),this.describe=this.describe.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return r(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(y(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:null!==(n=null==t?void 0:t.async)&&void 0!==n&&n,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},a=this._parseSync({data:e,path:s.path,parent:s});return x(s,a)}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:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},s=this._parse({data:e,path:[],parent:n}),a=await(y(s)?s:Promise.resolve(s));return x(n,a)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const r=e(t),i=()=>s.addIssue({code:a.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then((e=>!!e||(i(),!1))):!!r||(i(),!1)}))}refinement(e,t){return this._refinement(((n,s)=>!!e(n)||(s.addIssue("function"==typeof t?t(n,s):t),!1)))}_refinement(e){return new ie({schema:this,typeName:ge.ZodEffects,effect:{type:"refinement",refinement:e}})}optional(){return oe.create(this)}nullable(){return ce.create(this)}nullish(){return this.optional().nullable()}array(){return B.create(this)}promise(){return ae.create(this)}or(e){return W.create([this,e])}and(e){return q.create(this,e)}transform(e){return new ie({schema:this,typeName:ge.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new de({innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:ge.ZodDefault})}brand(){return new he({typeName:ge.ZodBranded,type:this,...C(void 0)})}describe(e){return new(0,this.constructor)({...this._def,description:e})}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const S=/^c[^\s-]{8,}$/i,k=/^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,O=/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;class E extends T{constructor(){super(...arguments),this._regex=(e,t,n)=>this.refinement((t=>e.test(t)),{validation:t,code:a.invalid_string,..._.errToObj(n)}),this.nonempty=e=>this.min(1,_.errToObj(e)),this.trim=()=>new E({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}_parse(e){if(this._getType(e)!==s.string){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.string,received:t.parsedType}),p}const t=new h;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:a.too_small,minimum:s.value,type:"string",inclusive:!0,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:a.too_big,maximum:s.value,type:"string",inclusive:!0,message:s.message}),t.dirty());else if("email"===s.kind)O.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"email",code:a.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)k.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"uuid",code:a.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)S.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"cuid",code:a.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch(n){r=this._getOrReturnCtx(e,r),u(r,{validation:"url",code:a.invalid_string,message:s.message}),t.dirty()}else if("regex"===s.kind){s.regex.lastIndex=0;s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{validation:"regex",code:a.invalid_string,message:s.message}),t.dirty())}else"trim"===s.kind?e.data=e.data.trim():"startsWith"===s.kind?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),u(r,{code:a.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),u(r,{code:a.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):n.assertNever(s);return{status:t.value,value:e.data}}_addCheck(e){return new E({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,..._.errToObj(t)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,..._.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,..._.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,..._.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,..._.errToObj(t)})}length(e,t){return this.min(e,t).max(e,t)}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function I(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=n>s?n:s;return parseInt(e.toFixed(r).replace(".",""))%parseInt(t.toFixed(r).replace(".",""))/Math.pow(10,r)}E.create=e=>new E({checks:[],typeName:ge.ZodString,...C(e)});class D extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._getType(e)!==s.number){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.number,received:t.parsedType}),p}let t;const r=new h;for(const s of this._def.checks)if("int"===s.kind)n.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),u(t,{code:a.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),u(t,{code:a.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,message:s.message}),r.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),u(t,{code:a.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,message:s.message}),r.dirty())}else"multipleOf"===s.kind?0!==I(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),u(t,{code:a.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,_.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_.toString(t))}setLimit(e,t,n,s){return new D({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:_.toString(s)}]})}_addCheck(e){return new D({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind))}}D.create=e=>new D({checks:[],typeName:ge.ZodNumber,...C(e)});class P extends T{_parse(e){if(this._getType(e)!==s.bigint){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.bigint,received:t.parsedType}),p}return m(e.data)}}P.create=e=>new P({typeName:ge.ZodBigInt,...C(e)});class N extends T{_parse(e){if(this._getType(e)!==s.boolean){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.boolean,received:t.parsedType}),p}return m(e.data)}}N.create=e=>new N({typeName:ge.ZodBoolean,...C(e)});class j extends T{_parse(e){if(this._getType(e)!==s.date){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.date,received:t.parsedType}),p}if(isNaN(e.data.getTime())){return u(this._getOrReturnCtx(e),{code:a.invalid_date}),p}const t=new h;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:a.too_small,message:s.message,inclusive:!0,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),u(r,{code:a.too_big,message:s.message,inclusive:!0,maximum:s.value,type:"date"}),t.dirty()):n.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new j({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:_.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:_.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}j.create=e=>new j({checks:[],typeName:ge.ZodDate,...C(e)});class M extends T{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.undefined,received:t.parsedType}),p}return m(e.data)}}M.create=e=>new M({typeName:ge.ZodUndefined,...C(e)});class R extends T{_parse(e){if(this._getType(e)!==s.null){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.null,received:t.parsedType}),p}return m(e.data)}}R.create=e=>new R({typeName:ge.ZodNull,...C(e)});class A extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}A.create=e=>new A({typeName:ge.ZodAny,...C(e)});class L extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}L.create=e=>new L({typeName:ge.ZodUnknown,...C(e)});class Z extends T{_parse(e){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.never,received:t.parsedType}),p}}Z.create=e=>new Z({typeName:ge.ZodNever,...C(e)});class F extends T{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.void,received:t.parsedType}),p}return m(e.data)}}F.create=e=>new F({typeName:ge.ZodVoid,...C(e)});class B extends T{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==s.array)return u(t,{code:a.invalid_type,expected:s.array,received:t.parsedType}),p;if(null!==r.minLength&&t.data.length<r.minLength.value&&(u(t,{code:a.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(u(t,{code:a.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all(t.data.map(((e,n)=>r.type._parseAsync(new w(t,e,t.path,n))))).then((e=>h.mergeArray(n,e)));const i=t.data.map(((e,n)=>r.type._parseSync(new w(t,e,t.path,n))));return h.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new B({...this._def,minLength:{value:e,message:_.toString(t)}})}max(e,t){return new B({...this._def,maxLength:{value:e,message:_.toString(t)}})}length(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}var z;B.create=(e,t)=>new B({type:e,minLength:null,maxLength:null,typeName:ge.ZodArray,...C(t)}),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(z||(z={}));const V=e=>t=>new $({...e,shape:()=>({...e.shape(),...t})});function U(e){if(e instanceof $){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=oe.create(U(s))}return new $({...e._def,shape:()=>t})}return e instanceof B?B.create(U(e.element)):e instanceof oe?oe.create(U(e.unwrap())):e instanceof ce?ce.create(U(e.unwrap())):e instanceof J?J.create(e.items.map((e=>U(e)))):e}class $ extends T{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=V(this._def),this.extend=V(this._def)}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==s.object){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.object,received:t.parsedType}),p}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),o=[];for(const e in n.data)i.includes(e)||o.push(e);const c=[];for(const e of i){const t=r[e],s=n.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new w(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Z){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)c.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)o.length>0&&(u(n,{code:a.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const s=n.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new w(n,s,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of c){const n=await t.key;e.push({key:n,value:await t.value,alwaysSet:t.alwaysSet})}return e})).then((e=>h.mergeObjectSync(t,e))):h.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return _.errToObj,new $({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{var s,r,a,i;const o=null!==(a=null===(r=(s=this._def).errorMap)||void 0===r?void 0:r.call(s,t,n).message)&&void 0!==a?a:n.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=_.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new $({...this._def,unknownKeys:"strip"})}passthrough(){return new $({...this._def,unknownKeys:"passthrough"})}setKey(e,t){return this.augment({[e]:t})}merge(e){return new $({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>z.mergeShapes(this._def.shape(),e._def.shape()),typeName:ge.ZodObject})}catchall(e){return new $({...this._def,catchall:e})}pick(e){const t={};return n.objectKeys(e).map((e=>{this.shape[e]&&(t[e]=this.shape[e])})),new $({...this._def,shape:()=>t})}omit(e){const t={};return n.objectKeys(this.shape).map((s=>{-1===n.objectKeys(e).indexOf(s)&&(t[s]=this.shape[s])})),new $({...this._def,shape:()=>t})}deepPartial(){return U(this)}partial(e){const t={};if(e)return n.objectKeys(this.shape).map((s=>{-1===n.objectKeys(e).indexOf(s)?t[s]=this.shape[s]:t[s]=this.shape[s].optional()})),new $({...this._def,shape:()=>t});for(const e in this.shape){const n=this.shape[e];t[e]=n.optional()}return new $({...this._def,shape:()=>t})}required(){const e={};for(const t in this.shape){let n=this.shape[t];for(;n instanceof oe;)n=n._def.innerType;e[t]=n}return new $({...this._def,shape:()=>e})}keyof(){return ne(n.objectKeys(this.shape))}}$.create=(e,t)=>new $({shape:()=>e,unknownKeys:"strip",catchall:Z.create(),typeName:ge.ZodObject,...C(t)}),$.strictCreate=(e,t)=>new $({shape:()=>e,unknownKeys:"strict",catchall:Z.create(),typeName:ge.ZodObject,...C(t)}),$.lazycreate=(e,t)=>new $({shape:e,unknownKeys:"strip",catchall:Z.create(),typeName:ge.ZodObject,...C(t)});class W extends T{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map((async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map((e=>new i(e.ctx.common.issues)));return u(t,{code:a.invalid_union,unionErrors:n}),p}));{let e;const s=[];for(const r of n){const n={...t,common:{...t.common,issues:[]},parent:null},a=r._parseSync({data:t.data,path:t.path,parent:n});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:n}),n.common.issues.length&&s.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=s.map((e=>new i(e)));return u(t,{code:a.invalid_union,unionErrors:r}),p}}get options(){return this._def.options}}W.create=(e,t)=>new W({options:e,typeName:ge.ZodUnion,...C(t)});class K extends T{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return u(t,{code:a.invalid_type,expected:s.object,received:t.parsedType}),p;const n=this.discriminator,r=t.data[n],i=this.options.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:a.invalid_union_discriminator,options:this.validDiscriminatorValues,path:[n]}),p)}get discriminator(){return this._def.discriminator}get validDiscriminatorValues(){return Array.from(this.options.keys())}get options(){return this._def.options}static create(e,t,n){const s=new Map;try{t.forEach((t=>{const n=t.shape[e].value;s.set(n,t)}))}catch(e){throw new Error("The discriminator value could not be extracted from all the provided schemas")}if(s.size!==t.length)throw new Error("Some of the discriminator values are not unique");return new K({typeName:ge.ZodDiscriminatedUnion,discriminator:e,options:s,...C(n)})}}function H(e,t){const a=r(e),i=r(t);if(e===t)return{valid:!0,data:e};if(a===s.object&&i===s.object){const s=n.objectKeys(t),r=n.objectKeys(e).filter((e=>-1!==s.indexOf(e))),a={...e,...t};for(const n of r){const s=H(e[n],t[n]);if(!s.valid)return{valid:!1};a[n]=s.data}return{valid:!0,data:a}}if(a===s.array&&i===s.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let s=0;s<e.length;s++){const r=H(e[s],t[s]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return a===s.date&&i===s.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class q extends T{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(e,s)=>{if(g(e)||g(s))return p;const r=H(e.value,s.value);return r.valid?((f(e)||f(s))&&t.dirty(),{status:t.value,value:r.data}):(u(n,{code:a.invalid_intersection_types}),p)};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((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}q.create=(e,t,n)=>new q({left:e,right:t,typeName:ge.ZodIntersection,...C(n)});class J extends T{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.array)return u(n,{code:a.invalid_type,expected:s.array,received:n.parsedType}),p;if(n.data.length<this._def.items.length)return u(n,{code:a.too_small,minimum:this._def.items.length,inclusive:!0,type:"array"}),p;!this._def.rest&&n.data.length>this._def.items.length&&(u(n,{code:a.too_big,maximum:this._def.items.length,inclusive:!0,type:"array"}),t.dirty());const r=n.data.map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new w(n,e,n.path,t)):null})).filter((e=>!!e));return n.common.async?Promise.all(r).then((e=>h.mergeArray(t,e))):h.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new J({...this._def,rest:e})}}J.create=(e,t)=>new J({items:e,typeName:ge.ZodTuple,rest:null,...C(t)});class G extends T{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!==s.object)return u(n,{code:a.invalid_type,expected:s.object,received:n.parsedType}),p;const r=[],i=this._def.keyType,o=this._def.valueType;for(const e in n.data)r.push({key:i._parse(new w(n,e,n.path,e)),value:o._parse(new w(n,n.data[e],n.path,e))});return n.common.async?h.mergeObjectAsync(t,r):h.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new G(t instanceof T?{keyType:e,valueType:t,typeName:ge.ZodRecord,...C(n)}:{keyType:E.create(),valueType:e,typeName:ge.ZodRecord,...C(t)})}}class X extends T{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.map)return u(n,{code:a.invalid_type,expected:s.map,received:n.parsedType}),p;const r=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map((([e,t],s)=>({key:r._parse(new w(n,e,n.path,[s,"key"])),value:i._parse(new w(n,t,n.path,[s,"value"]))})));if(n.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const n of o){const s=await n.key,r=await n.value;if("aborted"===s.status||"aborted"===r.status)return p;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const n of o){const s=n.key,r=n.value;if("aborted"===s.status||"aborted"===r.status)return p;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}}}X.create=(e,t,n)=>new X({valueType:t,keyType:e,typeName:ge.ZodMap,...C(n)});class Q extends T{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.set)return u(n,{code:a.invalid_type,expected:s.set,received:n.parsedType}),p;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(u(n,{code:a.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(u(n,{code:a.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const n=new Set;for(const s of e){if("aborted"===s.status)return p;"dirty"===s.status&&t.dirty(),n.add(s.value)}return{status:t.value,value:n}}const c=[...n.data.values()].map(((e,t)=>i._parse(new w(n,e,n.path,t))));return n.common.async?Promise.all(c).then((e=>o(e))):o(c)}min(e,t){return new Q({...this._def,minSize:{value:e,message:_.toString(t)}})}max(e,t){return new Q({...this._def,maxSize:{value:e,message:_.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Q.create=(e,t)=>new Q({valueType:e,minSize:null,maxSize:null,typeName:ge.ZodSet,...C(t)});class Y extends T{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.function)return u(t,{code:a.invalid_type,expected:s.function,received:t.parsedType}),p;function n(e,n){return l({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),o].filter((e=>!!e)),issueData:{code:a.invalid_arguments,argumentsError:n}})}function r(e,n){return l({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,d(),o].filter((e=>!!e)),issueData:{code:a.invalid_return_type,returnTypeError:n}})}const c={errorMap:t.common.contextualErrorMap},h=t.data;return this._def.returns instanceof ae?m((async(...e)=>{const t=new i([]),s=await this._def.args.parseAsync(e,c).catch((s=>{throw t.addIssue(n(e,s)),t})),a=await h(...s);return await this._def.returns._def.type.parseAsync(a,c).catch((e=>{throw t.addIssue(r(a,e)),t}))})):m(((...e)=>{const t=this._def.args.safeParse(e,c);if(!t.success)throw new i([n(e,t.error)]);const s=h(...t.data),a=this._def.returns.safeParse(s,c);if(!a.success)throw new i([r(s,a.error)]);return a.data}))}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Y({...this._def,args:J.create(e).rest(L.create())})}returns(e){return new Y({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}}Y.create=(e,t,n)=>new Y({args:e?e.rest(L.create()):J.create([]).rest(L.create()),returns:t||L.create(),typeName:ge.ZodFunction,...C(n)});class ee extends T{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})}}ee.create=(e,t)=>new ee({getter:e,typeName:ge.ZodLazy,...C(t)});class te extends T{_parse(e){if(e.data!==this._def.value){return u(this._getOrReturnCtx(e),{code:a.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ne(e,t){return new se({values:e,typeName:ge.ZodEnum,...C(t)})}te.create=(e,t)=>new te({value:e,typeName:ge.ZodLiteral,...C(t)});class se extends T{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{expected:n.joinValues(s),received:t.parsedType,code:a.invalid_type}),p}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return u(t,{received:t.data,code:a.invalid_enum_value,options:n}),p}return m(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}}se.create=ne;class re extends T{_parse(e){const t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==s.string&&r.parsedType!==s.number){const e=n.objectValues(t);return u(r,{expected:n.joinValues(e),received:r.parsedType,code:a.invalid_type}),p}if(-1===t.indexOf(e.data)){const e=n.objectValues(t);return u(r,{received:r.data,code:a.invalid_enum_value,options:e}),p}return m(e.data)}get enum(){return this._def.values}}re.create=(e,t)=>new re({values:e,typeName:ge.ZodNativeEnum,...C(t)});class ae extends T{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.promise&&!1===t.common.async)return u(t,{code:a.invalid_type,expected:s.promise,received:t.parsedType}),p;const n=t.parsedType===s.promise?t.data:Promise.resolve(t.data);return m(n.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}ae.create=(e,t)=>new ae({type:e,typeName:ge.ZodPromise,...C(t)});class ie extends T{innerType(){return this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null;if("preprocess"===r.type){const e=r.transform(s.data);return s.common.async?Promise.resolve(e).then((e=>this._def.schema._parseAsync({data:e,path:s.path,parent:s}))):this._def.schema._parseSync({data:e,path:s.path,parent:s})}const a={addIssue:e=>{u(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),"refinement"===r.type){const e=e=>{const t=r.refinement(e,a);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const n=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===n.status?p:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((n=>"aborted"===n.status?p:("dirty"===n.status&&t.dirty(),e(n.value).then((()=>({status:t.value,value:n.value}))))))}if("transform"===r.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!v(e))return e;const n=r.transform(e.value,a);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e=>v(e)?Promise.resolve(r.transform(e.value,a)).then((e=>({status:t.value,value:e}))):e))}n.assertNever(r)}}ie.create=(e,t,n)=>new ie({schema:e,typeName:ge.ZodEffects,effect:t,...C(n)}),ie.createWithPreprocess=(e,t,n)=>new ie({schema:t,effect:{type:"preprocess",transform:e},typeName:ge.ZodEffects,...C(n)});class oe extends T{_parse(e){return this._getType(e)===s.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}oe.create=(e,t)=>new oe({innerType:e,typeName:ge.ZodOptional,...C(t)});class ce extends T{_parse(e){return this._getType(e)===s.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ce.create=(e,t)=>new ce({innerType:e,typeName:ge.ZodNullable,...C(t)});class de extends T{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===s.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}de.create=(e,t)=>new oe({innerType:e,typeName:ge.ZodOptional,...C(t)});class le extends T{_parse(e){if(this._getType(e)!==s.nan){const t=this._getOrReturnCtx(e);return u(t,{code:a.invalid_type,expected:s.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}le.create=e=>new le({typeName:ge.ZodNaN,...C(e)});const ue=Symbol("zod_brand");class he extends T{_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}}const pe=(e,t={},n)=>e?A.create().superRefine(((s,r)=>{if(!e(s)){const e="function"==typeof t?t(s):t,a="string"==typeof e?{message:e}:e;r.addIssue({code:"custom",...a,fatal:n})}})):A.create(),me={object:$.lazycreate};var ge;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded"}(ge||(ge={}));const fe=E.create,ve=D.create,ye=le.create,be=P.create,_e=N.create,we=j.create,xe=M.create,Ce=R.create,Te=A.create,Se=L.create,ke=Z.create,Oe=F.create,Ee=B.create,Ie=$.create,De=$.strictCreate,Pe=W.create,Ne=K.create,je=q.create,Me=J.create,Re=G.create,Ae=X.create,Le=Q.create,Ze=Y.create,Fe=ee.create,Be=te.create,ze=se.create,Ve=re.create,Ue=ae.create,$e=ie.create,We=oe.create,Ke=ce.create,He=ie.createWithPreprocess;var qe=Object.freeze({__proto__:null,getParsedType:r,ZodParsedType:s,makeIssue:l,EMPTY_PATH:[],addIssueToContext:u,ParseStatus:h,INVALID:p,DIRTY:e=>({status:"dirty",value:e}),OK:m,isAborted:g,isDirty:f,isValid:v,isAsync:y,jsonStringifyReplacer:b,ZodType:T,ZodString:E,ZodNumber:D,ZodBigInt:P,ZodBoolean:N,ZodDate:j,ZodUndefined:M,ZodNull:R,ZodAny:A,ZodUnknown:L,ZodNever:Z,ZodVoid:F,ZodArray:B,get objectUtil(){return z},ZodObject:$,ZodUnion:W,ZodDiscriminatedUnion:K,ZodIntersection:q,ZodTuple:J,ZodRecord:G,ZodMap:X,ZodSet:Q,ZodFunction:Y,ZodLazy:ee,ZodLiteral:te,ZodEnum:se,ZodNativeEnum:re,ZodPromise:ae,ZodEffects:ie,ZodTransformer:ie,ZodOptional:oe,ZodNullable:ce,ZodDefault:de,ZodNaN:le,BRAND:ue,ZodBranded:he,custom:pe,Schema:T,ZodSchema:T,late:me,get ZodFirstPartyTypeKind(){return ge},any:Te,array:Ee,bigint:be,boolean:_e,date:we,discriminatedUnion:Ne,effect:$e,enum:ze,function:Ze,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>pe((t=>t instanceof e),t,!0),intersection:je,lazy:Fe,literal:Be,map:Ae,nan:ye,nativeEnum:Ve,never:ke,null:Ce,nullable:Ke,number:ve,object:Ie,oboolean:()=>_e().optional(),onumber:()=>ve().optional(),optional:We,ostring:()=>fe().optional(),preprocess:He,promise:Ue,record:Re,set:Le,strictObject:De,string:fe,transformer:$e,tuple:Me,undefined:xe,union:Pe,unknown:Se,void:Oe,ZodIssueCode:a,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:i,defaultErrorMap:o,setErrorMap:function(e){c=e},getErrorMap:d});class Je{constructor(e,t,n){this.error=e,this.message=t,this.stacktrace=n}error;message;stacktrace;toErrorResponse(e){return{id:e,error:this.error,message:this.message,stacktrace:this.stacktrace}}}class Ge extends Je{constructor(e,t){super("unknown error",e,t)}}class Xe extends Je{constructor(e,t){super("unknown command",e,t)}}class Qe extends Je{constructor(e,t){super("invalid argument",e,t)}}class Ye extends Je{constructor(e){super("no such frame",e)}}const et=e("command parser");function tt(e,t){const n=t.safeParse(e);if(n.success)return n.data;et(`Command ${JSON.stringify(e)} parse failed: ${JSON.stringify(n)}.`);const s=n.error.errors.map((e=>`${e.message} in ${e.path.map((e=>JSON.stringify(e))).join("/")}.`)).join(" ");throw new Qe(s)}var nt,st,rt,at,it,ot;!function(e){e.RemoteReferenceSchema=qe.object({handle:qe.string().min(1)});const t=qe.object({type:qe.literal("undefined")}),n=qe.object({type:qe.literal("null")}),s=qe.object({type:qe.literal("string"),value:qe.string()}),r=qe.enum(["NaN","-0","Infinity","+Infinity","-Infinity"]),a=qe.object({type:qe.literal("number"),value:qe.union([r,qe.number()])}),i=qe.object({type:qe.literal("boolean"),value:qe.boolean()}),o=qe.object({type:qe.literal("bigint"),value:qe.string()}),c=qe.union([t,n,s,a,i,o]);e.LocalValueSchema=qe.lazy((()=>qe.union([c,l,u,p,m,g,f])));const d=qe.array(e.LocalValueSchema),l=qe.lazy((()=>qe.object({type:qe.literal("array"),value:d}))),u=qe.object({type:qe.literal("date"),value:qe.string().min(1)}),h=qe.lazy((()=>qe.tuple([qe.union([qe.string(),e.LocalValueSchema]),e.LocalValueSchema]))),p=qe.object({type:qe.literal("map"),value:qe.array(h)}),m=qe.object({type:qe.literal("object"),value:qe.array(h)}),g=qe.lazy((()=>qe.object({type:qe.literal("regexp"),value:qe.object({pattern:qe.string(),flags:qe.string().optional()})}))),f=qe.lazy((()=>qe.object({type:qe.literal("set"),value:d})));e.BrowsingContextSchema=qe.string()}(nt||(nt={})),function(e){const t=qe.object({context:nt.BrowsingContextSchema,sandbox:qe.string().optional()}),n=qe.object({realm:qe.string().min(1)}),s=qe.union([t,n]),r=qe.enum(["root","none"]),a=qe.object({expression:qe.string(),awaitPromise:qe.boolean(),target:s,resultOwnership:r.optional()});e.parseEvaluateParams=function(e){return tt(e,a)};const i=qe.union([nt.RemoteReferenceSchema,nt.LocalValueSchema]),o=qe.object({functionDeclaration:qe.string(),target:s,arguments:qe.array(i).optional(),this:i.optional(),awaitPromise:qe.boolean(),resultOwnership:r.optional()});e.parseCallFunctionParams=function(e){return tt(e,o)}}(st||(st={})),function(e){const n=qe.object({maxDepth:qe.number().int().nonnegative().max(9007199254740991).optional(),root:nt.BrowsingContextSchema.optional()});e.parseGetTreeParams=function(e){return tt(e,n)};const s=qe.enum(["none","interactive","complete"]),r=qe.object({context:nt.BrowsingContextSchema,url:qe.string().url(),wait:s.optional()});e.parseNavigateParams=function(e){return tt(e,r)};const a=qe.object({type:qe.enum(["tab","window"])});e.parseCreateParams=function(e){return tt(e,a)};const i=qe.object({context:nt.BrowsingContextSchema});e.parseCloseParams=function(e){return tt(e,i)};class o extends t{static method="browsingContext.load";constructor(e){super(o.method,e)}}e.LoadEvent=o;class c extends t{static method="browsingContext.domContentLoaded";constructor(e){super(c.method,e)}}e.DomContentLoadedEvent=c;class d extends t{static method="browsingContext.contextCreated";constructor(e){super(d.method,e)}}e.ContextCreatedEvent=d;class l extends t{static method="browsingContext.contextDestroyed";constructor(e){super(l.method,e)}}e.ContextDestroyedEvent=l,function(e){const t=qe.object({context:nt.BrowsingContextSchema,selector:qe.string()});e.parseFindElementParams=function(e){return tt(e,t)}}(e.PROTO||(e.PROTO={})),e.EventNames=[o.method,c.method,d.method,l.method]}(rt||(rt={})),function(e){class n extends t{static method="log.entryAdded";constructor(e){super(n.method,e)}}e.LogEntryAddedEvent=n,e.EventNames=[n.method]}(at||(at={})),function(e){let n;!function(e){const n=qe.object({cdpMethod:qe.string(),cdpParams:qe.object({}).passthrough(),cdpSession:qe.string().optional()});e.parseSendCommandParams=function(e){return tt(e,n)};const s=qe.object({context:nt.BrowsingContextSchema});e.parseGetSessionParams=function(e){return tt(e,s)};class r extends t{static method="PROTO.cdp.eventReceived";constructor(e){super(r.method,e)}}e.EventReceivedEvent=r}(n=e.PROTO||(e.PROTO={})),e.EventNames=[n.EventReceivedEvent.method]}(it||(it={})),function(e){const t=qe.enum([...rt.EventNames,...at.EventNames,...it.EventNames]),n=qe.object({events:qe.array(t),contexts:qe.array(nt.BrowsingContextSchema).optional()});e.parseSubscribeParams=function(e){return tt(e,n)}}(ot||(ot={}));class ct{#e=()=>{};#t=()=>{};#n;#s=!1;get isFinished(){return this.#s}constructor(){this.#n=new Promise(((e,t)=>{this.#e=e,this.#t=t}))}then(e,t){return this.#n.then(e,t)}catch(e){return this.#n.catch(e)}resolve(e){this.#s=!0,this.#e(e)}reject(e){this.#s=!0,this.#t(e)}finally(e){return this.#n.finally(e)}[Symbol.toStringTag]="Promise"}const dt=["%s","%d","%i","%f","%o","%O","%c"];function lt(e){return dt.some((t=>e.includes(t)))}function ut(e){if(!["number","string","object"].includes(e.type))throw Error("Invalid value type: "+e.toString());if("number"===e.type&&(e.value,1))return e.value.toString();if("string"===e.type&&(e.value,1))return'"'+e.value.toString()+'"';if("object"===e.type&&(e.value,1))return'{"'+e.value[0][0]+'": '+ut(e.value[0][1])+"}";throw Error("Invalid value type: "+e.toString())}function ht(e,t){return 0==e.length?"":"string"===e[0].type&&lt(e[0].value.toString())&&t?function(e){let t="";const n=e[0].value.toString(),s=e.slice(1,void 0),r=n.split(new RegExp(dt.map((e=>"("+e+")")).join("|"),"g"));for(const n of r)if(void 0!==n&&""!=n)if(lt(n)){const r=s.shift();if(void 0===r)throw new Error('Less value is provided: "'+ht(e,!1)+'"');t+="%s"===n?r.value.toString():"%d"===n||"%i"===n?parseInt(r.value.toString(),10):"%f"===n?parseFloat(r.value.toString()):ut(r)}else t+=n;if(s.length>0)throw new Error('More value is provided: "'+ht(e,!1)+'"');return t}(e):e.map((e=>e.hasOwnProperty("value")?e.value.toString():e.type)).join(" ")}class pt{#r;#a;#i;#o;constructor(e,t,n,s){this.#o=s,this.#i=n,this.#a=t,this.#r=e}static create(e,t,n,s){const r=new pt(e,t,n,s);return r.#c(),r}#c(){this.#d()}#d(){this.#l()}#l(){this.#a.Runtime.on("consoleAPICalled",(async e=>{const t=await Promise.all(e.args.map((async t=>this.#o?.serializeCdpObject(t,"none",e.executionContextId))));await this.#i.sendMessage(new at.LogEntryAddedEvent({level:pt.#u(e.type),text:ht(t,!0),timestamp:e.timestamp,stackTrace:pt.#h(e.stackTrace),type:"console",method:e.type,realm:this.#r,args:t}))})),this.#a.Runtime.on("exceptionThrown",(async e=>{let t=e.exceptionDetails.text;if(e.exceptionDetails.exception)if(void 0===e.exceptionDetails.executionContextId)t=JSON.stringify(e.exceptionDetails.exception);else{const n=await this.#o.stringifyObject(e.exceptionDetails.exception,e.exceptionDetails.executionContextId);n&&(t=n)}await this.#i.sendMessage(new at.LogEntryAddedEvent({level:"error",text:t,timestamp:e.timestamp,stackTrace:pt.#h(e.exceptionDetails.stackTrace),type:"javascript",realm:this.#r}))}))}static#u(e){return e in["error","assert"]?"error":e in["debug","trace"]?"debug":e in["warning","warn"]?"warning":"info"}static#h(e){const t=e?.callFrames.map((e=>({columnNumber:e.columnNumber,functionName:e.functionName,lineNumber:e.lineNumber,url:e.url})));return t?{callFrames:t}:void 0}}class mt{#a;#p=0;#m=1;constructor(e){this.#a=e}static create(e){return new mt(e)}async serializeCdpObject(e,t,n){const s=await this.#a.Runtime.callFunctionOn({functionDeclaration:String((e=>e)),awaitPromise:!1,arguments:[e],generateWebDriverValue:!0,objectId:await this.#g(n)});return await this.#f(s,t)}async stringifyObject(e,t){return(await this.#a.Runtime.callFunctionOn({functionDeclaration:String((function(e){return String(e)})),awaitPromise:!1,arguments:[e],returnByValue:!0,objectId:await this.#g(t)})).result.value}async#g(e){return(await this.#a.Runtime.evaluate({expression:"(()=>{return {}})()",contextId:e})).result.objectId}async callFunction(e,t,n,s,r,a){const i=`(...args)=>{ return _callFunction((\n${t}\n), args);\n function _callFunction(f, args) {\n const deserializedThis = args.shift();\n const deserializedArgs = args;\n return f.apply(deserializedThis, deserializedArgs);\n }}`,o=[await this.#v(n,e)];o.push(...await Promise.all(s.map((async t=>await this.#v(t,e)))));const c=await this.#a.Runtime.callFunctionOn({functionDeclaration:i,awaitPromise:r,arguments:o,generateWebDriverValue:!0,objectId:await this.#g(e)});return c.exceptionDetails?{exceptionDetails:await this.#y(c.exceptionDetails,this.#m,a,e),realm:"TODO: ADD"}:{result:await this.#f(c,a),realm:"TODO: ADD"}}async#y(e,t,n,s){const r=e.stackTrace?.callFrames.map((e=>({url:e.url,functionName:e.functionName,lineNumber:e.lineNumber-t,columnNumber:e.columnNumber}))),a=await this.serializeCdpObject(e.exception,n,s),i=await this.stringifyObject(e.exception,s);return{exception:a,columnNumber:e.columnNumber,lineNumber:e.lineNumber-t,stackTrace:{callFrames:r||[]},text:i||e.text}}async#f(e,t){const n=e.result.webDriverValue;if(!e.result.objectId)return n;const s=e.result.objectId,r=n;return"root"===t?r.handle=s:await this.#a.Runtime.releaseObject({objectId:s}),r}async scriptEvaluate(e,t,n,s){let r=await this.#a.Runtime.evaluate({contextId:e,expression:t,awaitPromise:n,generateWebDriverValue:!0});return r.exceptionDetails?{result:{exceptionDetails:await this.#y(r.exceptionDetails,this.#p,s,e),realm:"TODO: ADD"}}:{result:{result:await this.#f(r,s),realm:"TODO: ADD"}}}async#v(e,t){if("handle"in e)return{objectId:e.handle};switch(e.type){case"undefined":return{unserializableValue:"undefined"};case"null":return{unserializableValue:"null"};case"string":return{value:e.value};case"number":return"NaN"===e.value?{unserializableValue:"NaN"}:"-0"===e.value?{unserializableValue:"-0"}:"+Infinity"===e.value?{unserializableValue:"+Infinity"}:"Infinity"===e.value?{unserializableValue:"Infinity"}:"-Infinity"===e.value?{unserializableValue:"-Infinity"}:{value:e.value};case"boolean":return{value:!!e.value};case"bigint":return{unserializableValue:`BigInt(${JSON.stringify(e.value)})`};case"date":return{unserializableValue:`new Date(Date.parse(${JSON.stringify(e.value)}))`};case"regexp":return{unserializableValue:`new RegExp(${JSON.stringify(e.value.pattern)}, ${JSON.stringify(e.value.flags)})`};case"map":{const n=await this.#b(e.value,t);return{objectId:(await this.#a.Runtime.callFunctionOn({functionDeclaration:String((function(...e){const t=new Map;for(let n=0;n<e.length;n+=2)t.set(e[n],e[n+1]);return t})),awaitPromise:!1,arguments:n,returnByValue:!1,objectId:await this.#g(t)})).result.objectId}}case"object":{const n=await this.#b(e.value,t);return{objectId:(await this.#a.Runtime.callFunctionOn({functionDeclaration:String((function(...e){const t={};for(let n=0;n<e.length;n+=2){t[e[n]]=e[n+1]}return t})),awaitPromise:!1,arguments:n,returnByValue:!1,objectId:await this.#g(t)})).result.objectId}}case"array":{const n=await this.#_(e.value,t);return{objectId:(await this.#a.Runtime.callFunctionOn({functionDeclaration:String((function(...e){return e})),awaitPromise:!1,arguments:n,returnByValue:!1,objectId:await this.#g(t)})).result.objectId}}case"set":{const n=await this.#_(e.value,t);return{objectId:(await this.#a.Runtime.callFunctionOn({functionDeclaration:String((function(...e){return new Set(e)})),awaitPromise:!1,arguments:n,returnByValue:!1,objectId:await this.#g(t)})).result.objectId}}default:throw new Error(`Value ${JSON.stringify(e)} is not deserializable.`)}}async#b(e,t){const n=[];for(let s of e){const e=s[0],r=s[1];let a,i;a="string"==typeof e?{value:e}:await this.#v(e,t),i=await this.#v(r,t),n.push(a),n.push(i)}return n}async#_(e,t){const n=[];for(let s of e)n.push(await this.#v(s,t));return n}}var gt=rt.LoadEvent;class ft{#w={documentInitialized:new ct,targetUnblocked:new ct,Page:{navigatedWithinDocument:new ct,lifecycleEvent:{DOMContentLoaded:new ct,load:new ct}}};#r;#x;#C="about:blank";#T=null;#S;#a;#i;#k;#O=[];#E;#I=null;constructor(e,t,n,s,r,a){this.#r=e,this.#x=t,this.#a=n,this.#k=a,this.#S=r,this.#i=s,this.#E=mt.create(n),this.#D()}static createFrameContext(e,t,n,s,r,a){const i=new ft(e,t,n,s,r,a);return i.#w.targetUnblocked.resolve(),i}static createTargetContext(e,t,n,s,r,a){const i=new ft(e,t,n,s,r,a);return i.#P(),i}static convertFrameToTargetContext(e,t,n){return e.#N(t,n),e.#P(),e}#N(e,t){this.#w.targetUnblocked.isFinished||this.#w.targetUnblocked.reject("OOPiF"),this.#w.targetUnblocked=new ct,this.#a=e,this.#S=t,this.#E=mt.create(e),this.#D()}async#P(){pt.create(this.#r,this.#a,this.#i,this.#E),await this.#a.Runtime.enable(),await this.#a.Page.enable(),await this.#a.Page.setLifecycleEventsEnabled({enabled:!0}),await this.#a.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),await this.#a.Runtime.runIfWaitingForDebugger(),this.#w.targetUnblocked.resolve()}get contextId(){return this.#r}get parentId(){return this.#x}get cdpSessionId(){return this.#S}get children(){return this.#O}get url(){return this.#C}addChild(e){this.#O.push(e)}serializeToBidiValue(e,t){return{context:this.#r,url:this.url,children:e>0?this.children.map((t=>t.serializeToBidiValue(e-1,!1))):null,...t?{parent:this.#x}:{}}}#D(){this.#a.Target.on("targetInfoChanged",(e=>{this.contextId===e.targetInfo.targetId&&(this.#C=e.targetInfo.url)})),this.#a.Page.on("frameNavigated",(e=>{this.contextId===e.frame.id&&(this.#C=e.frame.url+(e.frame.urlFragment??""))})),this.#a.Page.on("navigatedWithinDocument",(e=>{this.contextId===e.frameId&&(this.#C=e.url,this.#w.Page.navigatedWithinDocument.resolve(e))})),this.#a.Page.on("lifecycleEvent",(async e=>{if(this.contextId===e.frameId&&("init"===e.name&&(this.#j(e.loaderId),this.#w.documentInitialized.resolve()),e.loaderId===this.#T))switch(e.name){case"DOMContentLoaded":this.#w.Page.lifecycleEvent.DOMContentLoaded.resolve(e),await this.#k.sendEvent(new rt.DomContentLoadedEvent({context:this.contextId,navigation:this.#T}),this.contextId);break;case"load":this.#w.Page.lifecycleEvent.load.resolve(e),await this.#k.sendEvent(new gt({context:this.contextId,navigation:this.#T}),this.contextId)}})),this.#a.Runtime.on("executionContextCreated",(e=>{e.context.auxData.frameId===this.contextId&&e.context.auxData.isDefault&&(this.#I=e.context.id)}))}#j(e){this.#T!==e&&(this.#w.documentInitialized.isFinished||this.#w.documentInitialized.reject("Document changed"),this.#w.documentInitialized=new ct,this.#w.Page.navigatedWithinDocument.isFinished||this.#w.Page.navigatedWithinDocument.reject("Document changed"),this.#w.Page.navigatedWithinDocument=new ct,this.#w.Page.lifecycleEvent.DOMContentLoaded.isFinished||this.#w.Page.lifecycleEvent.DOMContentLoaded.reject("Document changed"),this.#w.Page.lifecycleEvent.DOMContentLoaded=new ct,this.#w.Page.lifecycleEvent.load.isFinished||this.#w.Page.lifecycleEvent.load.reject("Document changed"),this.#w.Page.lifecycleEvent.load=new ct,this.#T=e)}async navigate(e,t){await this.#w.targetUnblocked;const n=await this.#a.Page.navigate({url:e,frameId:this.contextId});if(n.errorText)throw new Ge(n.errorText);switch(void 0!==n.loaderId&&n.loaderId!==this.#T&&this.#j(n.loaderId),t){case"none":break;case"interactive":void 0===n.loaderId?await this.#w.Page.navigatedWithinDocument:await this.#w.Page.lifecycleEvent.DOMContentLoaded;break;case"complete":void 0===n.loaderId?await this.#w.Page.navigatedWithinDocument:await this.#w.Page.lifecycleEvent.load;break;default:throw new Error(`Not implemented wait '${t}'`)}return{result:{navigation:n.loaderId||null,url:e}}}async callFunction(e,t,n,s,r){if(await this.#w.targetUnblocked,null===this.#I)throw Error("No execution context");return{result:await this.#E.callFunction(this.#I,e,t,n,s,r)}}async scriptEvaluate(e,t,n){if(await this.#w.targetUnblocked,null===this.#I)throw Error("No execution context");return this.#E.scriptEvaluate(this.#I,e,t,n)}async findElement(e){await this.#w.targetUnblocked;const t=String((e=>document.querySelector(e))),n=[{type:"string",value:e}];return await this.callFunction(t,{type:"undefined"},n,!0,"root")}}const vt=e("context");class yt{static#M=new Map;static#R(){return Array.from(yt.#M.values()).filter((e=>null===e.parentId))}static#A(e){yt.#M.delete(e)}static#L(e){yt.#M.set(e.contextId,e),null!==e.parentId&&yt.#Z(e.parentId).addChild(e)}static#F(e){return yt.#M.has(e)}static#Z(e){if(!yt.#F(e))throw new Ye(`Context ${e} not found`);return yt.#M.get(e)}sessions=new Set;#B;#z;#i;#k;constructor(e,t,n,s){this.#B=e,this.#z=t,this.#i=n,this.#k=s,this.#V(this.#B.browserClient())}#V(e){this.#U(e)}#U(e){e.Target.on("attachedToTarget",(async t=>{await this.#$(t,e)})),e.Target.on("detachedFromTarget",(async e=>{await this.#W(e)}))}#K(e){if(this.sessions.has(e))return;this.sessions.add(e);const t=this.#B.getCdpClient(e);this.#U(t),t.on("event",(async(t,n)=>{await this.#k.sendEvent({method:"PROTO.cdp.eventReceived",params:{cdpMethod:t,cdpParams:n,session:e}},null)})),t.Page.on("frameAttached",(async n=>{const s=ft.createFrameContext(n.frameId,n.parentFrameId,t,this.#i,e,this.#k);yt.#L(s),await this.#k.sendEvent(new rt.ContextCreatedEvent(s.serializeToBidiValue(0,!0)),s.contextId)}))}async#$(e,t){vt("AttachedToTarget event received: "+JSON.stringify(e));const{sessionId:n,targetInfo:s}=e;let r=this.#B.getCdpClient(n);if(!this.#H(s))return await r.Runtime.runIfWaitingForDebugger(),void await t.Target.detachFromTarget(e);if(this.#K(n),yt.#F(s.targetId))ft.convertFrameToTargetContext(yt.#Z(s.targetId),r,n);else{const e=ft.createTargetContext(s.targetId,null,r,this.#i,n,this.#k);yt.#L(e),await this.#k.sendEvent(new rt.ContextCreatedEvent(e.serializeToBidiValue(0,!0)),e.contextId)}}async#W(e){vt("detachedFromTarget event received: "+JSON.stringify(e));const t=e.targetId;if(!yt.#F(t))return;const n=yt.#Z(t);yt.#A(t),await this.#k.sendEvent(new rt.ContextDestroyedEvent(n.serializeToBidiValue(0,!0)),t)}async process_browsingContext_getTree(e){return{result:{contexts:(void 0===e.root?yt.#R():[yt.#Z(e.root)]).map((t=>t.serializeToBidiValue(e.maxDepth??Number.MAX_VALUE,!0)))}}}async process_browsingContext_create(e){const t=this.#B.browserClient();return{result:{context:(await t.Target.createTarget({url:"about:blank",newWindow:"window"===e.type})).targetId,parent:null,url:"about:blank",children:[]}}}async process_browsingContext_navigate(e){const t=yt.#Z(e.context);return await t.navigate(e.url,void 0!==e.wait?e.wait:"none")}async process_script_evaluate(e){const t=yt.#Z(e.target.context);return await t.scriptEvaluate(e.expression,e.awaitPromise,e.resultOwnership??"none")}async process_script_callFunction(e){const t=yt.#Z(e.target.context);return await t.callFunction(e.functionDeclaration,e.this||{type:"undefined"},e.arguments||[],e.awaitPromise,e.resultOwnership??"none")}async process_PROTO_browsingContext_findElement(e){const t=yt.#Z(e.context);return await t.findElement(e.selector)}async process_browsingContext_close(e){const t=this.#B.browserClient();if(null!==yt.#Z(e.context).parentId)throw new Qe("Not a top-level browsing context cannot be closed.");const n=new Promise((async n=>{const s=r=>{r.targetId===e.context&&(t.Target.removeListener("detachedFromTarget",s),n())};t.Target.on("detachedFromTarget",s)}));return await this.#B.browserClient().Target.closeTarget({targetId:e.context}),await n,{result:{}}}#H(e){return e.targetId!==this.#z&&["page","iframe"].includes(e.type)}async process_PROTO_cdp_sendCommand(e){return{result:await this.#B.sendCommand(e.cdpMethod,e.cdpParams,e.cdpSession??null)}}async process_PROTO_cdp_getSession(e){const t=e.context,n=yt.#Z(t).cdpSessionId;return void 0===n?{result:{session:null}}:{result:{session:n}}}}class bt{#q;#i;#k;static run(e,t,n,s){new bt(e,t,n,s).#J()}constructor(e,t,n,s){this.#k=n,this.#i=t,this.#q=new yt(e,s,t,n)}#J(){this.#i.on("message",(e=>this.#G(e)))}async#X(){return{result:{ready:!0,message:"ready"}}}async#Q(e){return await this.#k.subscribe(e.events,e.contexts??null),{result:{}}}async#Y(e){return await this.#k.unsubscribe(e.events,e.contexts??null),{result:{}}}async#ee(e){switch(e.method){case"session.status":return await this.#X();case"session.subscribe":return await this.#Q(ot.parseSubscribeParams(e.params));case"session.unsubscribe":return await this.#Y(ot.parseSubscribeParams(e.params));case"browsingContext.create":return await this.#q.process_browsingContext_create(rt.parseCreateParams(e.params));case"browsingContext.close":return await this.#q.process_browsingContext_close(rt.parseCloseParams(e.params));case"browsingContext.getTree":return await this.#q.process_browsingContext_getTree(rt.parseGetTreeParams(e.params));case"browsingContext.navigate":return await this.#q.process_browsingContext_navigate(rt.parseNavigateParams(e.params));case"script.callFunction":return await this.#q.process_script_callFunction(st.parseCallFunctionParams(e.params));case"script.evaluate":return await this.#q.process_script_evaluate(st.parseEvaluateParams(e.params));case"PROTO.browsingContext.findElement":return await this.#q.process_PROTO_browsingContext_findElement(rt.PROTO.parseFindElementParams(e.params));case"PROTO.cdp.sendCommand":return await this.#q.process_PROTO_cdp_sendCommand(it.PROTO.parseSendCommandParams(e.params));case"PROTO.cdp.getSession":return await this.#q.process_PROTO_cdp_getSession(it.PROTO.parseGetSessionParams(e.params));default:throw new Xe(`Unknown command '${e.method}'.`)}}#G=async e=>{try{const t=await this.#ee(e),n={id:e.id,...t};await this.#i.sendMessage(n)}catch(t){if(t instanceof Je){const n=t;await this.#i.sendMessage(n.toErrorResponse(e.id))}else{const n=t;console.error(n),await this.#i.sendMessage(new Ge(n.message).toErrorResponse(e.id))}}}}function _t(){}function wt(){wt.init.call(this)}function xt(e){return void 0===e._maxListeners?wt.defaultMaxListeners:e._maxListeners}function Ct(e,t,n){if(t)e.call(n);else for(var s=e.length,r=Pt(e,s),a=0;a<s;++a)r[a].call(n)}function Tt(e,t,n,s){if(t)e.call(n,s);else for(var r=e.length,a=Pt(e,r),i=0;i<r;++i)a[i].call(n,s)}function St(e,t,n,s,r){if(t)e.call(n,s,r);else for(var a=e.length,i=Pt(e,a),o=0;o<a;++o)i[o].call(n,s,r)}function kt(e,t,n,s,r,a){if(t)e.call(n,s,r,a);else for(var i=e.length,o=Pt(e,i),c=0;c<i;++c)o[c].call(n,s,r,a)}function Ot(e,t,n,s){if(t)e.apply(n,s);else for(var r=e.length,a=Pt(e,r),i=0;i<r;++i)a[i].apply(n,s)}function Et(e,t,n,s){var r,a,i,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),i=a[t]):(a=e._events=new _t,e._eventsCount=0),i){if("function"==typeof i?i=a[t]=s?[n,i]:[i,n]:s?i.unshift(n):i.push(n),!i.warned&&(r=xt(e))&&r>0&&i.length>r){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,o=c,"function"==typeof console.warn?console.warn(o):console.log(o)}}else i=a[t]=n,++e._eventsCount;return e}function It(e,t,n){var s=!1;function r(){e.removeListener(t,r),s||(s=!0,n.apply(e,arguments))}return r.listener=n,r}function Dt(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function Pt(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}_t.prototype=Object.create(null),wt.EventEmitter=wt,wt.usingDomains=!1,wt.prototype.domain=void 0,wt.prototype._events=void 0,wt.prototype._maxListeners=void 0,wt.defaultMaxListeners=10,wt.init=function(){this.domain=null,wt.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new _t,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},wt.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},wt.prototype.getMaxListeners=function(){return xt(this)},wt.prototype.emit=function(e){var t,n,s,r,a,i,o,c="error"===e;if(i=this._events)c=c&&null==i.error;else if(!c)return!1;if(o=this.domain,c){if(t=arguments[1],!o){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=i[e]))return!1;var l="function"==typeof n;switch(s=arguments.length){case 1:Ct(n,l,this);break;case 2:Tt(n,l,this,arguments[1]);break;case 3:St(n,l,this,arguments[1],arguments[2]);break;case 4:kt(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(r=new Array(s-1),a=1;a<s;a++)r[a-1]=arguments[a];Ot(n,l,this,r)}return!0},wt.prototype.addListener=function(e,t){return Et(this,e,t,!1)},wt.prototype.on=wt.prototype.addListener,wt.prototype.prependListener=function(e,t){return Et(this,e,t,!0)},wt.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,It(this,e,t)),this},wt.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,It(this,e,t)),this},wt.prototype.removeListener=function(e,t){var n,s,r,a,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new _t:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,a=n.length;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){i=n[a].listener,r=a;break}if(r<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new _t,this;delete s[e]}else!function(e,t){for(var n=t,s=n+1,r=e.length;s<r;n+=1,s+=1)e[n]=e[s];e.pop()}(n,r);s.removeListener&&this.emit("removeListener",e,i||t)}return this},wt.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new _t,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new _t:delete n[e]),this;if(0===arguments.length){for(var s,r=Object.keys(n),a=0;a<r.length;++a)"removeListener"!==(s=r[a])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new _t,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},wt.prototype.listeners=function(e){var t,n=this._events;return n&&(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]},wt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Dt.call(e,t)},wt.prototype.listenerCount=Dt,wt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const Nt=[{domain:"Accessibility",commands:["disable","enable","getPartialAXTree","getFullAXTree","getRootAXNode","getAXNodeAndAncestors","getChildAXNodes","queryAXTree"]},{domain:"Animation",commands:["disable","enable","getCurrentTime","getPlaybackRate","releaseAnimations","resolveAnimation","seekAnimations","setPaused","setPlaybackRate","setTiming"]},{domain:"Audits",commands:["getEncodedResponse","disable","enable","checkContrast"]},{domain:"BackgroundService",commands:["startObserving","stopObserving","setRecording","clearEvents"]},{domain:"Browser",commands:["setPermission","grantPermissions","resetPermissions","setDownloadBehavior","cancelDownload","close","crash","crashGpuProcess","getVersion","getBrowserCommandLine","getHistograms","getHistogram","getWindowBounds","getWindowForTarget","setWindowBounds","setDockTile","executeBrowserCommand"]},{domain:"CSS",commands:["addRule","collectClassNames","createStyleSheet","disable","enable","forcePseudoState","getBackgroundColors","getComputedStyleForNode","getInlineStylesForNode","getMatchedStylesForNode","getMediaQueries","getPlatformFontsForNode","getStyleSheetText","getLayersForNode","trackComputedStyleUpdates","takeComputedStyleUpdates","setEffectivePropertyValueForNode","setKeyframeKey","setMediaText","setContainerQueryText","setSupportsText","setRuleSelector","setStyleSheetText","setStyleTexts","startRuleUsageTracking","stopRuleUsageTracking","takeCoverageDelta","setLocalFontsEnabled"]},{domain:"CacheStorage",commands:["deleteCache","deleteEntry","requestCacheNames","requestCachedResponse","requestEntries"]},{domain:"Cast",commands:["enable","disable","setSinkToUse","startDesktopMirroring","startTabMirroring","stopCasting"]},{domain:"DOM",commands:["collectClassNamesFromSubtree","copyTo","describeNode","scrollIntoViewIfNeeded","disable","discardSearchResults","enable","focus","getAttributes","getBoxModel","getContentQuads","getDocument","getFlattenedDocument","getNodesForSubtreeByStyle","getNodeForLocation","getOuterHTML","getRelayoutBoundary","getSearchResults","hideHighlight","highlightNode","highlightRect","markUndoableState","moveTo","performSearch","pushNodeByPathToFrontend","pushNodesByBackendIdsToFrontend","querySelector","querySelectorAll","redo","removeAttribute","removeNode","requestChildNodes","requestNode","resolveNode","setAttributeValue","setAttributesAsText","setFileInputFiles","setNodeStackTracesEnabled","getNodeStackTraces","getFileInfo","setInspectedNode","setNodeName","setNodeValue","setOuterHTML","undo","getFrameOwner","getContainerForNode","getQueryingDescendantsForContainer"]},{domain:"DOMDebugger",commands:["getEventListeners","removeDOMBreakpoint","removeEventListenerBreakpoint","removeInstrumentationBreakpoint","removeXHRBreakpoint","setBreakOnCSPViolation","setDOMBreakpoint","setEventListenerBreakpoint","setInstrumentationBreakpoint","setXHRBreakpoint"]},{domain:"EventBreakpoints",commands:["setInstrumentationBreakpoint","removeInstrumentationBreakpoint"]},{domain:"DOMSnapshot",commands:["disable","enable","getSnapshot","captureSnapshot"]},{domain:"DOMStorage",commands:["clear","disable","enable","getDOMStorageItems","removeDOMStorageItem","setDOMStorageItem"]},{domain:"Database",commands:["disable","enable","executeSQL","getDatabaseTableNames"]},{domain:"DeviceOrientation",commands:["clearDeviceOrientationOverride","setDeviceOrientationOverride"]},{domain:"Emulation",commands:["canEmulate","clearDeviceMetricsOverride","clearGeolocationOverride","resetPageScaleFactor","setFocusEmulationEnabled","setAutoDarkModeOverride","setCPUThrottlingRate","setDefaultBackgroundColorOverride","setDeviceMetricsOverride","setScrollbarsHidden","setDocumentCookieDisabled","setEmitTouchEventsForMouse","setEmulatedMedia","setEmulatedVisionDeficiency","setGeolocationOverride","setIdleOverride","clearIdleOverride","setNavigatorOverrides","setPageScaleFactor","setScriptExecutionDisabled","setTouchEmulationEnabled","setVirtualTimePolicy","setLocaleOverride","setTimezoneOverride","setVisibleSize","setDisabledImageTypes","setHardwareConcurrencyOverride","setUserAgentOverride","setAutomationOverride"]},{domain:"HeadlessExperimental",commands:["beginFrame","disable","enable"]},{domain:"IO",commands:["close","read","resolveBlob"]},{domain:"IndexedDB",commands:["clearObjectStore","deleteDatabase","deleteObjectStoreEntries","disable","enable","requestData","getMetadata","requestDatabase","requestDatabaseNames"]},{domain:"Input",commands:["dispatchDragEvent","dispatchKeyEvent","insertText","imeSetComposition","dispatchMouseEvent","dispatchTouchEvent","emulateTouchFromMouseEvent","setIgnoreInputEvents","setInterceptDrags","synthesizePinchGesture","synthesizeScrollGesture","synthesizeTapGesture"]},{domain:"Inspector",commands:["disable","enable"]},{domain:"LayerTree",commands:["compositingReasons","disable","enable","loadSnapshot","makeSnapshot","profileSnapshot","releaseSnapshot","replaySnapshot","snapshotCommandLog"]},{domain:"Log",commands:["clear","disable","enable","startViolationsReport","stopViolationsReport"]},{domain:"Memory",commands:["getDOMCounters","prepareForLeakDetection","forciblyPurgeJavaScriptMemory","setPressureNotificationsSuppressed","simulatePressureNotification","startSampling","stopSampling","getAllTimeSamplingProfile","getBrowserSamplingProfile","getSamplingProfile"]},{domain:"Network",commands:["setAcceptedEncodings","clearAcceptedEncodingsOverride","canClearBrowserCache","canClearBrowserCookies","canEmulateNetworkConditions","clearBrowserCache","clearBrowserCookies","continueInterceptedRequest","deleteCookies","disable","emulateNetworkConditions","enable","getAllCookies","getCertificate","getCookies","getResponseBody","getRequestPostData","getResponseBodyForInterception","takeResponseBodyForInterceptionAsStream","replayXHR","searchInResponseBody","setBlockedURLs","setBypassServiceWorker","setCacheDisabled","setCookie","setCookies","setExtraHTTPHeaders","setAttachDebugStack","setRequestInterception","setUserAgentOverride","getSecurityIsolationStatus","enableReportingApi","loadNetworkResource"]},{domain:"Overlay",commands:["disable","enable","getHighlightObjectForTest","getGridHighlightObjectsForTest","getSourceOrderHighlightObjectForTest","hideHighlight","highlightFrame","highlightNode","highlightQuad","highlightRect","highlightSourceOrder","setInspectMode","setShowAdHighlights","setPausedInDebuggerMessage","setShowDebugBorders","setShowFPSCounter","setShowGridOverlays","setShowFlexOverlays","setShowScrollSnapOverlays","setShowContainerQueryOverlays","setShowPaintRects","setShowLayoutShiftRegions","setShowScrollBottleneckRects","setShowHitTestBorders","setShowWebVitals","setShowViewportSizeOnResize","setShowHinge","setShowIsolatedElements"]},{domain:"Page",commands:["addScriptToEvaluateOnLoad","addScriptToEvaluateOnNewDocument","bringToFront","captureScreenshot","captureSnapshot","clearDeviceMetricsOverride","clearDeviceOrientationOverride","clearGeolocationOverride","createIsolatedWorld","deleteCookie","disable","enable","getAppManifest","getInstallabilityErrors","getManifestIcons","getAppId","getCookies","getFrameTree","getLayoutMetrics","getNavigationHistory","resetNavigationHistory","getResourceContent","getResourceTree","handleJavaScriptDialog","navigate","navigateToHistoryEntry","printToPDF","reload","removeScriptToEvaluateOnLoad","removeScriptToEvaluateOnNewDocument","screencastFrameAck","searchInResource","setAdBlockingEnabled","setBypassCSP","getPermissionsPolicyState","getOriginTrials","setDeviceMetricsOverride","setDeviceOrientationOverride","setFontFamilies","setFontSizes","setDocumentContent","setDownloadBehavior","setGeolocationOverride","setLifecycleEventsEnabled","setTouchEmulationEnabled","startScreencast","stopLoading","crash","close","setWebLifecycleState","stopScreencast","produceCompilationCache","addCompilationCache","clearCompilationCache","setSPCTransactionMode","generateTestReport","waitForDebugger","setInterceptFileChooserDialog"]},{domain:"Performance",commands:["disable","enable","setTimeDomain","getMetrics"]},{domain:"PerformanceTimeline",commands:["enable"]},{domain:"Security",commands:["disable","enable","setIgnoreCertificateErrors","handleCertificateError","setOverrideCertificateErrors"]},{domain:"ServiceWorker",commands:["deliverPushMessage","disable","dispatchSyncEvent","dispatchPeriodicSyncEvent","enable","inspectWorker","setForceUpdateOnPageLoad","skipWaiting","startWorker","stopAllWorkers","stopWorker","unregister","updateRegistration"]},{domain:"Storage",commands:["getStorageKeyForFrame","clearDataForOrigin","getCookies","setCookies","clearCookies","getUsageAndQuota","overrideQuotaForOrigin","trackCacheStorageForOrigin","trackIndexedDBForOrigin","untrackCacheStorageForOrigin","untrackIndexedDBForOrigin","getTrustTokens","clearTrustTokens","getInterestGroupDetails","setInterestGroupTracking"]},{domain:"SystemInfo",commands:["getInfo","getProcessInfo"]},{domain:"Target",commands:["activateTarget","attachToTarget","attachToBrowserTarget","closeTarget","exposeDevToolsProtocol","createBrowserContext","getBrowserContexts","createTarget","detachFromTarget","disposeBrowserContext","getTargetInfo","getTargets","sendMessageToTarget","setAutoAttach","autoAttachRelated","setDiscoverTargets","setRemoteLocations"]},{domain:"Tethering",commands:["bind","unbind"]},{domain:"Tracing",commands:["end","getCategories","recordClockSyncMarker","requestMemoryDump","start"]},{domain:"Fetch",commands:["disable","enable","failRequest","fulfillRequest","continueRequest","continueWithAuth","continueResponse","getResponseBody","takeResponseBodyAsStream"]},{domain:"WebAudio",commands:["enable","disable","getRealtimeData"]},{domain:"WebAuthn",commands:["enable","disable","addVirtualAuthenticator","removeVirtualAuthenticator","addCredential","getCredential","getCredentials","removeCredential","clearCredentials","setUserVerified","setAutomaticPresenceSimulation"]},{domain:"Media",commands:["enable","disable"]},{domain:"Console",commands:["clearMessages","disable","enable"]},{domain:"Debugger",commands:["continueToLocation","disable","enable","evaluateOnCallFrame","getPossibleBreakpoints","getScriptSource","getWasmBytecode","getStackTrace","pause","pauseOnAsyncCall","removeBreakpoint","restartFrame","resume","searchInContent","setAsyncCallStackDepth","setBlackboxPatterns","setBlackboxedRanges","setBreakpoint","setInstrumentationBreakpoint","setBreakpointByUrl","setBreakpointOnFunctionCall","setBreakpointsActive","setPauseOnExceptions","setReturnValue","setScriptSource","setSkipAllPauses","setVariableValue","stepInto","stepOut","stepOver"]},{domain:"HeapProfiler",commands:["addInspectedHeapObject","collectGarbage","disable","enable","getHeapObjectId","getObjectByHeapObjectId","getSamplingProfile","startSampling","startTrackingHeapObjects","stopSampling","stopTrackingHeapObjects","takeHeapSnapshot"]},{domain:"Profiler",commands:["disable","enable","getBestEffortCoverage","setSamplingInterval","start","startPreciseCoverage","startTypeProfile","stop","stopPreciseCoverage","stopTypeProfile","takePreciseCoverage","takeTypeProfile"]},{domain:"Runtime",commands:["awaitPromise","callFunctionOn","compileScript","disable","discardConsoleEntries","enable","evaluate","getIsolateId","getHeapUsage","getProperties","globalLexicalScopeNames","queryObjects","releaseObject","releaseObjectGroup","runIfWaitingForDebugger","runScript","setAsyncCallStackDepth","setCustomObjectFormatterEnabled","setMaxCallStackSizeToCapture","terminateExecution","addBinding","removeBinding","getExceptionDetails"]},{domain:"Schema",commands:["getDomains"]}],jt=new Map;class Mt extends wt{_client;constructor(e){super(),this._client=e}}for(let e of Nt){class t extends Mt{constructor(e){super(e)}}for(let n of e.commands)Object.defineProperty(t.prototype,n,{value:async function(t){return await this._client.sendCommand(`${e.domain}.${n}`,t)}});jt.set(e.domain,t)}class Rt extends wt{_cdpConnection;_sessionId;_domains;constructor(e,t){super(),this._cdpConnection=e,this._sessionId=t,this._domains=new Map;for(const[e,t]of jt.entries())this._domains.set(e,new t(this)),Object.defineProperty(this,e,{get(){return this._domains.get(e)}})}sendCommand(e,t){return this._cdpConnection.sendCommand(e,t,this._sessionId)}_onCdpEvent(e,t){this.emit("event",e,t);const[n,s]=e.split("."),r=this._domains.get(n);r&&r.emit(s,t)}}function At(e,t){return new Rt(e,t)}const Lt=e("cdp");class Zt{_transport;_browserCdpClient;_sessionCdpClients=new Map;_commandCallbacks=new Map;_nextId;constructor(e){this._transport=e,this._nextId=0,this._transport.setOnMessage(this._onMessage),this._browserCdpClient=At(this,null)}close(){this._transport.close();for(const[e,{reject:t}]of this._commandCallbacks)t(new Error("Disconnected"));this._commandCallbacks.clear(),this._sessionCdpClients.clear()}browserClient(){return this._browserCdpClient}getCdpClient(e){const t=this._sessionCdpClients.get(e);if(!t)throw new Error("Unknown CDP session ID");return t}sendCommand(e,t,n){return new Promise(((s,r)=>{const a=this._nextId++;this._commandCallbacks.set(a,{resolve:s,reject:r});let i={id:a,method:e,params:t};n&&(i.sessionId=n);const o=JSON.stringify(i);this._transport.sendMessage(o),Lt("sent > "+o)}))}_onMessage=async e=>{Lt("received < "+e);const t=JSON.parse(e);if("Target.attachedToTarget"===t.method){const{sessionId:e}=t.params;this._sessionCdpClients.set(e,At(this,e))}else if("Target.detachedFromTarget"===t.method){const{sessionId:e}=t.params;this._sessionCdpClients.get(e)&&this._sessionCdpClients.delete(e)}if(void 0!==t.id){const e=this._commandCallbacks.get(t.id);e&&(t.result?e.resolve(t.result):t.error&&e.reject(t.error))}else if(t.method){const e=t.sessionId?this._sessionCdpClients.get(t.sessionId):this._browserCdpClient;e&&e._onCdpEvent(t.method,t.params||{})}}}const Ft=e("bidi");class Bt extends wt{_transport;constructor(e){super(),this._transport=e,this._transport.setOnMessage(this._onBidiMessage)}async sendMessage(e){const t=JSON.stringify(e);Ft("sent > "+t),this._transport.sendMessage(t)}close(){this._transport.close()}_onBidiMessage=async e=>{let t;Ft("received < "+e);try{t=this._parseBidiMessage(e)}catch(t){return void this._respondWithError(e,"invalid argument",t.message)}this.emit("message",t)};_respondWithError(e,t,n){const s=this._getErrorResponse(e,t,n);this.sendMessage(s)}_getJsonType(e){return null===e?"null":Array.isArray(e)?"array":typeof e}_getErrorResponse(e,t,n){let s;try{const t=JSON.parse(e);"object"===this._getJsonType(t)&&"id"in t&&(s=t.id)}catch{}return{id:s,error:t,message:n}}_parseBidiMessage(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Cannot parse data as JSON")}const n=this._getJsonType(t);if("object"!==n)throw new Error(`Expected JSON object but got ${n}`);const{id:s,method:r,params:a}=t,i=this._getJsonType(s);if("number"!==i||!Number.isInteger(s)||s<0)throw new Error(`Expected unsigned integer but got ${i}`);const o=this._getJsonType(r);if("string"!==o)throw new Error(`Expected string method but got ${o}`);const c=this._getJsonType(a);if("object"!==c)throw new Error(`Expected object params but got ${c}`);return{id:s,method:r,params:a}}}class zt{#te=new Map;#i;constructor(e){this.#i=e}async sendEvent(e,t){(this.#ne(e.method,null)||null!==t&&this.#ne(e.method,t))&&await this.#i.sendMessage(e)}#ne(e,t){return this.#te.has(t)&&this.#te.get(t).has(e)}async subscribe(e,t){for(let n of e)if(null===t)this.#se(n,null);else for(let e of t)this.#se(n,e)}#se(e,t){this.#te.has(t)||this.#te.set(t,new Set),this.#te.get(t).add(e)}async unsubscribe(e,t){for(let n of e)if(null===t)this.#re(n,null);else for(let e of t)this.#re(n,e)}#re(e,t){const n=this.#te.get(t);n?.delete(e),0===n?.size&&this.#te.delete(t)}}
  2. /**
  3. * Copyright 2021 Google LLC.
  4. * Copyright (c) Microsoft Corporation.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * @license
  19. */const Vt=e("system"),Ut=async function(){return await new Promise((e=>{window.setSelfTargetId=function(t){Vt("current target ID: "+t),e(t)}}))}();(async()=>{window.document.documentElement.innerHTML="<h1>Bidi mapper runs here!</h1><h2>Don't close.</h2>",window.document.title="BiDi Mapper";const e=function(){class e{_onMessage=null;constructor(){window.cdp.onmessage=e=>{this._onMessage&&this._onMessage.call(null,e)}}setOnMessage(e){this._onMessage=e}async sendMessage(e){window.cdp.send(e)}close(){this._onMessage=null,window.cdp.onmessage=null}}return new Zt(new e)}(),t=e.browserClient(),n=function(){class e{_onMessage=null;constructor(){window.onBidiMessage=e=>{this._onMessage&&this._onMessage.call(null,e)}}setOnMessage(e){this._onMessage=e}async sendMessage(e){window.sendBidiResponse(e)}close(){this._onMessage=null,window.onBidiMessage=null}}return new Bt(new e)}(),s=new zt(n),r=await Ut;bt.run(e,n,s,r),await async function(e){await e.Target.setDiscoverTargets({discover:!0}),await e.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0})}(t),Vt("launched"),n.sendMessage({launched:!0})})()}();
  20. //# sourceMappingURL=mapper.js.map