@kelceyp/chrome-control-mcp 0.2.0 → 0.2.1

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.
Files changed (3) hide show
  1. package/dist/index.js +143 -0
  2. package/package.json +21 -11
  3. package/server/index.js +0 -576
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ var SW=Object.defineProperty;var FW=($,W)=>{for(var G in W)SW($,G,{get:W[G],enumerable:!0,configurable:!0,set:(H)=>W[G]=()=>H})};var J={};FW(J,{void:()=>w3,util:()=>b,unknown:()=>M3,union:()=>V3,undefined:()=>Q3,tuple:()=>U3,transformer:()=>f3,symbol:()=>J3,string:()=>MW,strictObject:()=>O3,setErrorMap:()=>kW,set:()=>N3,record:()=>b3,quotelessJson:()=>fW,promise:()=>F3,preprocess:()=>C3,pipeline:()=>I3,ostring:()=>P3,optional:()=>K3,onumber:()=>g3,oboolean:()=>T3,objectUtil:()=>m$,object:()=>j3,number:()=>qW,nullable:()=>k3,null:()=>Y3,never:()=>q3,nativeEnum:()=>S3,nan:()=>G3,map:()=>D3,makeIssue:()=>A$,literal:()=>L3,lazy:()=>v3,late:()=>$3,isValid:()=>u,isDirty:()=>F$,isAsync:()=>G$,isAborted:()=>S$,intersection:()=>A3,instanceof:()=>W3,getParsedType:()=>T,getErrorMap:()=>W$,function:()=>R3,enum:()=>E3,effect:()=>f3,discriminatedUnion:()=>_3,defaultErrorMap:()=>y,datetimeRegex:()=>QW,date:()=>H3,custom:()=>BW,coerce:()=>h3,boolean:()=>wW,bigint:()=>X3,array:()=>z3,any:()=>B3,addIssueToContext:()=>z,ZodVoid:()=>b$,ZodUnknown:()=>c,ZodUnion:()=>B$,ZodUndefined:()=>Q$,ZodType:()=>U,ZodTuple:()=>x,ZodTransformer:()=>C,ZodSymbol:()=>U$,ZodString:()=>F,ZodSet:()=>s,ZodSchema:()=>U,ZodRecord:()=>D$,ZodReadonly:()=>V$,ZodPromise:()=>t,ZodPipeline:()=>v$,ZodParsedType:()=>q,ZodOptional:()=>K,ZodObject:()=>D,ZodNumber:()=>n,ZodNullable:()=>Z,ZodNull:()=>Y$,ZodNever:()=>h,ZodNativeEnum:()=>z$,ZodNaN:()=>R$,ZodMap:()=>N$,ZodLiteral:()=>w$,ZodLazy:()=>q$,ZodIssueCode:()=>B,ZodIntersection:()=>M$,ZodFunction:()=>H$,ZodFirstPartyTypeKind:()=>_,ZodError:()=>L,ZodEnum:()=>i,ZodEffects:()=>C,ZodDiscriminatedUnion:()=>f$,ZodDefault:()=>j$,ZodDate:()=>o,ZodCatch:()=>O$,ZodBranded:()=>K$,ZodBoolean:()=>J$,ZodBigInt:()=>p,ZodArray:()=>f,ZodAny:()=>a,Schema:()=>U,ParseStatus:()=>N,OK:()=>R,NEVER:()=>x3,INVALID:()=>O,EMPTY_PATH:()=>CW,DIRTY:()=>r,BRAND:()=>eW});var b;(function($){$.assertEqual=(X)=>{};function W(X){}$.assertIs=W;function G(X){throw new Error}$.assertNever=G,$.arrayToEnum=(X)=>{let Q={};for(let Y of X)Q[Y]=Y;return Q},$.getValidEnumValues=(X)=>{let Q=$.objectKeys(X).filter((M)=>typeof X[X[M]]!=="number"),Y={};for(let M of Q)Y[M]=X[M];return $.objectValues(Y)},$.objectValues=(X)=>{return $.objectKeys(X).map(function(Q){return X[Q]})},$.objectKeys=typeof Object.keys==="function"?(X)=>Object.keys(X):(X)=>{let Q=[];for(let Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))Q.push(Y);return Q},$.find=(X,Q)=>{for(let Y of X)if(Q(Y))return Y;return},$.isInteger=typeof Number.isInteger==="function"?(X)=>Number.isInteger(X):(X)=>typeof X==="number"&&Number.isFinite(X)&&Math.floor(X)===X;function H(X,Q=" | "){return X.map((Y)=>typeof Y==="string"?`'${Y}'`:Y).join(Q)}$.joinValues=H,$.jsonStringifyReplacer=(X,Q)=>{if(typeof Q==="bigint")return Q.toString();return Q}})(b||(b={}));var m$;(function($){$.mergeShapes=(W,G)=>{return{...W,...G}}})(m$||(m$={}));var q=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T=($)=>{switch(typeof $){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN($)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":if(Array.isArray($))return q.array;if($===null)return q.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return q.promise;if(typeof Map!=="undefined"&&$ instanceof Map)return q.map;if(typeof Set!=="undefined"&&$ instanceof Set)return q.set;if(typeof Date!=="undefined"&&$ instanceof Date)return q.date;return q.object;default:return q.unknown}};var B=b.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"]),fW=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class L extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(G)=>{this.issues=[...this.issues,G]},this.addIssues=(G=[])=>{this.issues=[...this.issues,...G]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(X){return X.message},G={_errors:[]},H=(X)=>{for(let Q of X.issues)if(Q.code==="invalid_union")Q.unionErrors.map(H);else if(Q.code==="invalid_return_type")H(Q.returnTypeError);else if(Q.code==="invalid_arguments")H(Q.argumentsError);else if(Q.path.length===0)G._errors.push(W(Q));else{let Y=G,M=0;while(M<Q.path.length){let w=Q.path[M];if(M!==Q.path.length-1)Y[w]=Y[w]||{_errors:[]};else Y[w]=Y[w]||{_errors:[]},Y[w]._errors.push(W(Q));Y=Y[w],M++}}};return H(this),G}static assert($){if(!($ instanceof L))throw new Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},G=[];for(let H of this.issues)if(H.path.length>0){let X=H.path[0];W[X]=W[X]||[],W[X].push($(H))}else G.push($(H));return{formErrors:G,fieldErrors:W}}get formErrors(){return this.flatten()}}L.create=($)=>{return new L($)};var KW=($,W)=>{let G;switch($.code){case B.invalid_type:if($.received===q.undefined)G="Required";else G=`Expected ${$.expected}, received ${$.received}`;break;case B.invalid_literal:G=`Invalid literal value, expected ${JSON.stringify($.expected,b.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:G=`Unrecognized key(s) in object: ${b.joinValues($.keys,", ")}`;break;case B.invalid_union:G="Invalid input";break;case B.invalid_union_discriminator:G=`Invalid discriminator value. Expected ${b.joinValues($.options)}`;break;case B.invalid_enum_value:G=`Invalid enum value. Expected ${b.joinValues($.options)}, received '${$.received}'`;break;case B.invalid_arguments:G="Invalid function arguments";break;case B.invalid_return_type:G="Invalid function return type";break;case B.invalid_date:G="Invalid date";break;case B.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(G=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")G=`${G} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)G=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)G=`Invalid input: must end with "${$.validation.endsWith}"`;else b.assertNever($.validation);else if($.validation!=="regex")G=`Invalid ${$.validation}`;else G="Invalid";break;case B.too_small:if($.type==="array")G=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")G=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")G=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")G=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")G=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else G="Invalid input";break;case B.too_big:if($.type==="array")G=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")G=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")G=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")G=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")G=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else G="Invalid input";break;case B.custom:G="Invalid input";break;case B.invalid_intersection_types:G="Intersection results could not be merged";break;case B.not_multiple_of:G=`Number must be a multiple of ${$.multipleOf}`;break;case B.not_finite:G="Number must be finite";break;default:G=W.defaultError,b.assertNever($)}return{message:G}},y=KW;var WW=y;function kW($){WW=$}function W$(){return WW}var A$=($)=>{let{data:W,path:G,errorMaps:H,issueData:X}=$,Q=[...G,...X.path||[]],Y={...X,path:Q};if(X.message!==void 0)return{...X,path:Q,message:X.message};let M="",w=H.filter((V)=>!!V).slice().reverse();for(let V of w)M=V(Y,{data:W,defaultError:M}).message;return{...X,path:Q,message:M}},CW=[];function z($,W){let G=W$(),H=A$({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,G,G===y?void 0:y].filter((X)=>!!X)});$.common.issues.push(H)}class N{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let G=[];for(let H of W){if(H.status==="aborted")return O;if(H.status==="dirty")$.dirty();G.push(H.value)}return{status:$.value,value:G}}static async mergeObjectAsync($,W){let G=[];for(let H of W){let X=await H.key,Q=await H.value;G.push({key:X,value:Q})}return N.mergeObjectSync($,G)}static mergeObjectSync($,W){let G={};for(let H of W){let{key:X,value:Q}=H;if(X.status==="aborted")return O;if(Q.status==="aborted")return O;if(X.status==="dirty")$.dirty();if(Q.status==="dirty")$.dirty();if(X.value!=="__proto__"&&(typeof Q.value!=="undefined"||H.alwaysSet))G[X.value]=Q.value}return{status:$.value,value:G}}}var O=Object.freeze({status:"aborted"}),r=($)=>({status:"dirty",value:$}),R=($)=>({status:"valid",value:$}),S$=($)=>$.status==="aborted",F$=($)=>$.status==="dirty",u=($)=>$.status==="valid",G$=($)=>typeof Promise!=="undefined"&&$ instanceof Promise;var j;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W?.message})(j||(j={}));class k{constructor($,W,G,H){this._cachedPath=[],this.parent=$,this.data=W,this._path=G,this._key=H}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var GW=($,W)=>{if(u(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let G=new L($.common.issues);return this._error=G,this._error}}}};function A($){if(!$)return{};let{errorMap:W,invalid_type_error:G,required_error:H,description:X}=$;if(W&&(G||H))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:X};return{errorMap:(Y,M)=>{let{message:w}=$;if(Y.code==="invalid_enum_value")return{message:w??M.defaultError};if(typeof M.data==="undefined")return{message:w??H??M.defaultError};if(Y.code!=="invalid_type")return{message:M.defaultError};return{message:w??G??M.defaultError}},description:X}}class U{get description(){return this._def.description}_getType($){return T($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:T($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new N,ctx:{common:$.parent.common,data:$.data,parsedType:T($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(G$(W))throw new Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let G=this.safeParse($,W);if(G.success)return G.data;throw G.error}safeParse($,W){let G={common:{issues:[],async:W?.async??!1,contextualErrorMap:W?.errorMap},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T($)},H=this._parseSync({data:$,path:G.path,parent:G});return GW(G,H)}"~validate"($){let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T($)};if(!this["~standard"].async)try{let G=this._parseSync({data:$,path:[],parent:W});return u(G)?{value:G.value}:{issues:W.common.issues}}catch(G){if(G?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((G)=>u(G)?{value:G.value}:{issues:W.common.issues})}async parseAsync($,W){let G=await this.safeParseAsync($,W);if(G.success)return G.data;throw G.error}async safeParseAsync($,W){let G={common:{issues:[],contextualErrorMap:W?.errorMap,async:!0},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T($)},H=this._parse({data:$,path:G.path,parent:G}),X=await(G$(H)?H:Promise.resolve(H));return GW(G,X)}refine($,W){let G=(H)=>{if(typeof W==="string"||typeof W==="undefined")return{message:W};else if(typeof W==="function")return W(H);else return W};return this._refinement((H,X)=>{let Q=$(H),Y=()=>X.addIssue({code:B.custom,...G(H)});if(typeof Promise!=="undefined"&&Q instanceof Promise)return Q.then((M)=>{if(!M)return Y(),!1;else return!0});if(!Q)return Y(),!1;else return!0})}refinement($,W){return this._refinement((G,H)=>{if(!$(G))return H.addIssue(typeof W==="function"?W(G,H):W),!1;else return!0})}_refinement($){return new C({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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),this["~standard"]={version:1,vendor:"zod",validate:(W)=>this["~validate"](W)}}optional(){return K.create(this,this._def)}nullable(){return Z.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return f.create(this)}promise(){return t.create(this,this._def)}or($){return B$.create([this,$],this._def)}and($){return M$.create(this,$,this._def)}transform($){return new C({...A(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new j$({...A(this._def),innerType:this,defaultValue:W,typeName:_.ZodDefault})}brand(){return new K$({typeName:_.ZodBranded,type:this,...A(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new O$({...A(this._def),innerType:this,catchValue:W,typeName:_.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return v$.create(this,$)}readonly(){return V$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var IW=/^c[^\s-]{8,}$/i,PW=/^[0-9a-z]+$/,gW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,TW=/^[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,hW=/^[a-z0-9_-]{21}$/i,xW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lW=/^[-+]?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)?)??$/,yW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,mW="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Z$,ZW=/^(?:(?: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])$/,uW=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,cW=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nW=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pW=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,iW=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,HW="((\\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])))",dW=new RegExp(`^${HW}$`);function JW($){let W="[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;let G=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${W})${G}`}function rW($){return new RegExp(`^${JW($)}$`)}function QW($){let W=`${HW}T${JW($)}`,G=[];if(G.push($.local?"Z?":"Z"),$.offset)G.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${G.join("|")})`,new RegExp(`^${W}$`)}function oW($,W){if((W==="v4"||!W)&&ZW.test($))return!0;if((W==="v6"||!W)&&cW.test($))return!0;return!1}function aW($,W){if(!xW.test($))return!1;try{let[G]=$.split(".");if(!G)return!1;let H=G.replace(/-/g,"+").replace(/_/g,"/").padEnd(G.length+(4-G.length%4)%4,"="),X=JSON.parse(atob(H));if(typeof X!=="object"||X===null)return!1;if("typ"in X&&X?.typ!=="JWT")return!1;if(!X.alg)return!1;if(W&&X.alg!==W)return!1;return!0}catch{return!1}}function sW($,W){if((W==="v4"||!W)&&uW.test($))return!0;if((W==="v6"||!W)&&nW.test($))return!0;return!1}class F extends U{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==q.string){let X=this._getOrReturnCtx($);return z(X,{code:B.invalid_type,expected:q.string,received:X.parsedType}),O}let G=new N,H=void 0;for(let X of this._def.checks)if(X.kind==="min"){if($.data.length<X.value)H=this._getOrReturnCtx($,H),z(H,{code:B.too_small,minimum:X.value,type:"string",inclusive:!0,exact:!1,message:X.message}),G.dirty()}else if(X.kind==="max"){if($.data.length>X.value)H=this._getOrReturnCtx($,H),z(H,{code:B.too_big,maximum:X.value,type:"string",inclusive:!0,exact:!1,message:X.message}),G.dirty()}else if(X.kind==="length"){let Q=$.data.length>X.value,Y=$.data.length<X.value;if(Q||Y){if(H=this._getOrReturnCtx($,H),Q)z(H,{code:B.too_big,maximum:X.value,type:"string",inclusive:!0,exact:!0,message:X.message});else if(Y)z(H,{code:B.too_small,minimum:X.value,type:"string",inclusive:!0,exact:!0,message:X.message});G.dirty()}}else if(X.kind==="email"){if(!yW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"email",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="emoji"){if(!Z$)Z$=new RegExp(mW,"u");if(!Z$.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"emoji",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="uuid"){if(!TW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"uuid",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="nanoid"){if(!hW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"nanoid",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="cuid"){if(!IW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"cuid",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="cuid2"){if(!PW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"cuid2",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="ulid"){if(!gW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"ulid",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="url")try{new URL($.data)}catch{H=this._getOrReturnCtx($,H),z(H,{validation:"url",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="regex"){if(X.regex.lastIndex=0,!X.regex.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"regex",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="trim")$.data=$.data.trim();else if(X.kind==="includes"){if(!$.data.includes(X.value,X.position))H=this._getOrReturnCtx($,H),z(H,{code:B.invalid_string,validation:{includes:X.value,position:X.position},message:X.message}),G.dirty()}else if(X.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(X.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(X.kind==="startsWith"){if(!$.data.startsWith(X.value))H=this._getOrReturnCtx($,H),z(H,{code:B.invalid_string,validation:{startsWith:X.value},message:X.message}),G.dirty()}else if(X.kind==="endsWith"){if(!$.data.endsWith(X.value))H=this._getOrReturnCtx($,H),z(H,{code:B.invalid_string,validation:{endsWith:X.value},message:X.message}),G.dirty()}else if(X.kind==="datetime"){if(!QW(X).test($.data))H=this._getOrReturnCtx($,H),z(H,{code:B.invalid_string,validation:"datetime",message:X.message}),G.dirty()}else if(X.kind==="date"){if(!dW.test($.data))H=this._getOrReturnCtx($,H),z(H,{code:B.invalid_string,validation:"date",message:X.message}),G.dirty()}else if(X.kind==="time"){if(!rW(X).test($.data))H=this._getOrReturnCtx($,H),z(H,{code:B.invalid_string,validation:"time",message:X.message}),G.dirty()}else if(X.kind==="duration"){if(!lW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"duration",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="ip"){if(!oW($.data,X.version))H=this._getOrReturnCtx($,H),z(H,{validation:"ip",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="jwt"){if(!aW($.data,X.alg))H=this._getOrReturnCtx($,H),z(H,{validation:"jwt",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="cidr"){if(!sW($.data,X.version))H=this._getOrReturnCtx($,H),z(H,{validation:"cidr",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="base64"){if(!pW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"base64",code:B.invalid_string,message:X.message}),G.dirty()}else if(X.kind==="base64url"){if(!iW.test($.data))H=this._getOrReturnCtx($,H),z(H,{validation:"base64url",code:B.invalid_string,message:X.message}),G.dirty()}else b.assertNever(X);return{status:G.value,value:$.data}}_regex($,W,G){return this.refinement((H)=>$.test(H),{validation:W,code:B.invalid_string,...j.errToObj(G)})}_addCheck($){return new F({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...j.errToObj($)})}url($){return this._addCheck({kind:"url",...j.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...j.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...j.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...j.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...j.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...j.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...j.errToObj($)})}base64($){return this._addCheck({kind:"base64",...j.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...j.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...j.errToObj($)})}ip($){return this._addCheck({kind:"ip",...j.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...j.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision==="undefined"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...j.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision==="undefined"?null:$?.precision,...j.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...j.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...j.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W?.position,...j.errToObj(W?.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...j.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...j.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...j.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...j.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...j.errToObj(W)})}nonempty($){return this.min(1,j.errToObj($))}trim(){return new F({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new F({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new F({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}F.create=($)=>{return new F({checks:[],typeName:_.ZodString,coerce:$?.coerce??!1,...A($)})};function tW($,W){let G=($.toString().split(".")[1]||"").length,H=(W.toString().split(".")[1]||"").length,X=G>H?G:H,Q=Number.parseInt($.toFixed(X).replace(".","")),Y=Number.parseInt(W.toFixed(X).replace(".",""));return Q%Y/10**X}class n extends U{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==q.number){let X=this._getOrReturnCtx($);return z(X,{code:B.invalid_type,expected:q.number,received:X.parsedType}),O}let G=void 0,H=new N;for(let X of this._def.checks)if(X.kind==="int"){if(!b.isInteger($.data))G=this._getOrReturnCtx($,G),z(G,{code:B.invalid_type,expected:"integer",received:"float",message:X.message}),H.dirty()}else if(X.kind==="min"){if(X.inclusive?$.data<X.value:$.data<=X.value)G=this._getOrReturnCtx($,G),z(G,{code:B.too_small,minimum:X.value,type:"number",inclusive:X.inclusive,exact:!1,message:X.message}),H.dirty()}else if(X.kind==="max"){if(X.inclusive?$.data>X.value:$.data>=X.value)G=this._getOrReturnCtx($,G),z(G,{code:B.too_big,maximum:X.value,type:"number",inclusive:X.inclusive,exact:!1,message:X.message}),H.dirty()}else if(X.kind==="multipleOf"){if(tW($.data,X.value)!==0)G=this._getOrReturnCtx($,G),z(G,{code:B.not_multiple_of,multipleOf:X.value,message:X.message}),H.dirty()}else if(X.kind==="finite"){if(!Number.isFinite($.data))G=this._getOrReturnCtx($,G),z(G,{code:B.not_finite,message:X.message}),H.dirty()}else b.assertNever(X);return{status:H.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,j.toString(W))}gt($,W){return this.setLimit("min",$,!1,j.toString(W))}lte($,W){return this.setLimit("max",$,!0,j.toString(W))}lt($,W){return this.setLimit("max",$,!1,j.toString(W))}setLimit($,W,G,H){return new n({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:G,message:j.toString(H)}]})}_addCheck($){return new n({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:j.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:j.toString(W)})}finite($){return this._addCheck({kind:"finite",message:j.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&b.isInteger($.value))}get isFinite(){let $=null,W=null;for(let G of this._def.checks)if(G.kind==="finite"||G.kind==="int"||G.kind==="multipleOf")return!0;else if(G.kind==="min"){if(W===null||G.value>W)W=G.value}else if(G.kind==="max"){if($===null||G.value<$)$=G.value}return Number.isFinite(W)&&Number.isFinite($)}}n.create=($)=>{return new n({checks:[],typeName:_.ZodNumber,coerce:$?.coerce||!1,...A($)})};class p extends U{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==q.bigint)return this._getInvalidInput($);let G=void 0,H=new N;for(let X of this._def.checks)if(X.kind==="min"){if(X.inclusive?$.data<X.value:$.data<=X.value)G=this._getOrReturnCtx($,G),z(G,{code:B.too_small,type:"bigint",minimum:X.value,inclusive:X.inclusive,message:X.message}),H.dirty()}else if(X.kind==="max"){if(X.inclusive?$.data>X.value:$.data>=X.value)G=this._getOrReturnCtx($,G),z(G,{code:B.too_big,type:"bigint",maximum:X.value,inclusive:X.inclusive,message:X.message}),H.dirty()}else if(X.kind==="multipleOf"){if($.data%X.value!==BigInt(0))G=this._getOrReturnCtx($,G),z(G,{code:B.not_multiple_of,multipleOf:X.value,message:X.message}),H.dirty()}else b.assertNever(X);return{status:H.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return z(W,{code:B.invalid_type,expected:q.bigint,received:W.parsedType}),O}gte($,W){return this.setLimit("min",$,!0,j.toString(W))}gt($,W){return this.setLimit("min",$,!1,j.toString(W))}lte($,W){return this.setLimit("max",$,!0,j.toString(W))}lt($,W){return this.setLimit("max",$,!1,j.toString(W))}setLimit($,W,G,H){return new p({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:G,message:j.toString(H)}]})}_addCheck($){return new p({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:j.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}p.create=($)=>{return new p({checks:[],typeName:_.ZodBigInt,coerce:$?.coerce??!1,...A($)})};class J$ extends U{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==q.boolean){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:q.boolean,received:G.parsedType}),O}return R($.data)}}J$.create=($)=>{return new J$({typeName:_.ZodBoolean,coerce:$?.coerce||!1,...A($)})};class o extends U{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==q.date){let X=this._getOrReturnCtx($);return z(X,{code:B.invalid_type,expected:q.date,received:X.parsedType}),O}if(Number.isNaN($.data.getTime())){let X=this._getOrReturnCtx($);return z(X,{code:B.invalid_date}),O}let G=new N,H=void 0;for(let X of this._def.checks)if(X.kind==="min"){if($.data.getTime()<X.value)H=this._getOrReturnCtx($,H),z(H,{code:B.too_small,message:X.message,inclusive:!0,exact:!1,minimum:X.value,type:"date"}),G.dirty()}else if(X.kind==="max"){if($.data.getTime()>X.value)H=this._getOrReturnCtx($,H),z(H,{code:B.too_big,message:X.message,inclusive:!0,exact:!1,maximum:X.value,type:"date"}),G.dirty()}else b.assertNever(X);return{status:G.value,value:new Date($.data.getTime())}}_addCheck($){return new o({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:j.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:j.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}o.create=($)=>{return new o({checks:[],coerce:$?.coerce||!1,typeName:_.ZodDate,...A($)})};class U$ extends U{_parse($){if(this._getType($)!==q.symbol){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:q.symbol,received:G.parsedType}),O}return R($.data)}}U$.create=($)=>{return new U$({typeName:_.ZodSymbol,...A($)})};class Q$ extends U{_parse($){if(this._getType($)!==q.undefined){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:q.undefined,received:G.parsedType}),O}return R($.data)}}Q$.create=($)=>{return new Q$({typeName:_.ZodUndefined,...A($)})};class Y$ extends U{_parse($){if(this._getType($)!==q.null){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:q.null,received:G.parsedType}),O}return R($.data)}}Y$.create=($)=>{return new Y$({typeName:_.ZodNull,...A($)})};class a extends U{constructor(){super(...arguments);this._any=!0}_parse($){return R($.data)}}a.create=($)=>{return new a({typeName:_.ZodAny,...A($)})};class c extends U{constructor(){super(...arguments);this._unknown=!0}_parse($){return R($.data)}}c.create=($)=>{return new c({typeName:_.ZodUnknown,...A($)})};class h extends U{_parse($){let W=this._getOrReturnCtx($);return z(W,{code:B.invalid_type,expected:q.never,received:W.parsedType}),O}}h.create=($)=>{return new h({typeName:_.ZodNever,...A($)})};class b$ extends U{_parse($){if(this._getType($)!==q.undefined){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:q.void,received:G.parsedType}),O}return R($.data)}}b$.create=($)=>{return new b$({typeName:_.ZodVoid,...A($)})};class f extends U{_parse($){let{ctx:W,status:G}=this._processInputParams($),H=this._def;if(W.parsedType!==q.array)return z(W,{code:B.invalid_type,expected:q.array,received:W.parsedType}),O;if(H.exactLength!==null){let Q=W.data.length>H.exactLength.value,Y=W.data.length<H.exactLength.value;if(Q||Y)z(W,{code:Q?B.too_big:B.too_small,minimum:Y?H.exactLength.value:void 0,maximum:Q?H.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:H.exactLength.message}),G.dirty()}if(H.minLength!==null){if(W.data.length<H.minLength.value)z(W,{code:B.too_small,minimum:H.minLength.value,type:"array",inclusive:!0,exact:!1,message:H.minLength.message}),G.dirty()}if(H.maxLength!==null){if(W.data.length>H.maxLength.value)z(W,{code:B.too_big,maximum:H.maxLength.value,type:"array",inclusive:!0,exact:!1,message:H.maxLength.message}),G.dirty()}if(W.common.async)return Promise.all([...W.data].map((Q,Y)=>{return H.type._parseAsync(new k(W,Q,W.path,Y))})).then((Q)=>{return N.mergeArray(G,Q)});let X=[...W.data].map((Q,Y)=>{return H.type._parseSync(new k(W,Q,W.path,Y))});return N.mergeArray(G,X)}get element(){return this._def.type}min($,W){return new f({...this._def,minLength:{value:$,message:j.toString(W)}})}max($,W){return new f({...this._def,maxLength:{value:$,message:j.toString(W)}})}length($,W){return new f({...this._def,exactLength:{value:$,message:j.toString(W)}})}nonempty($){return this.min(1,$)}}f.create=($,W)=>{return new f({type:$,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...A(W)})};function X$($){if($ instanceof D){let W={};for(let G in $.shape){let H=$.shape[G];W[G]=K.create(X$(H))}return new D({...$._def,shape:()=>W})}else if($ instanceof f)return new f({...$._def,type:X$($.element)});else if($ instanceof K)return K.create(X$($.unwrap()));else if($ instanceof Z)return Z.create(X$($.unwrap()));else if($ instanceof x)return x.create($.items.map((W)=>X$(W)));else return $}class D extends U{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),W=b.objectKeys($);return this._cached={shape:$,keys:W},this._cached}_parse($){if(this._getType($)!==q.object){let w=this._getOrReturnCtx($);return z(w,{code:B.invalid_type,expected:q.object,received:w.parsedType}),O}let{status:G,ctx:H}=this._processInputParams($),{shape:X,keys:Q}=this._getCached(),Y=[];if(!(this._def.catchall instanceof h&&this._def.unknownKeys==="strip")){for(let w in H.data)if(!Q.includes(w))Y.push(w)}let M=[];for(let w of Q){let V=X[w],v=H.data[w];M.push({key:{status:"valid",value:w},value:V._parse(new k(H,v,H.path,w)),alwaysSet:w in H.data})}if(this._def.catchall instanceof h){let w=this._def.unknownKeys;if(w==="passthrough")for(let V of Y)M.push({key:{status:"valid",value:V},value:{status:"valid",value:H.data[V]}});else if(w==="strict"){if(Y.length>0)z(H,{code:B.unrecognized_keys,keys:Y}),G.dirty()}else if(w==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let w=this._def.catchall;for(let V of Y){let v=H.data[V];M.push({key:{status:"valid",value:V},value:w._parse(new k(H,v,H.path,V)),alwaysSet:V in H.data})}}if(H.common.async)return Promise.resolve().then(async()=>{let w=[];for(let V of M){let v=await V.key,g=await V.value;w.push({key:v,value:g,alwaysSet:V.alwaysSet})}return w}).then((w)=>{return N.mergeObjectSync(G,w)});else return N.mergeObjectSync(G,M)}get shape(){return this._def.shape()}strict($){return j.errToObj,new D({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,G)=>{let H=this._def.errorMap?.(W,G).message??G.defaultError;if(W.code==="unrecognized_keys")return{message:j.errToObj($).message??H};return{message:H}}}:{}})}strip(){return new D({...this._def,unknownKeys:"strip"})}passthrough(){return new D({...this._def,unknownKeys:"passthrough"})}extend($){return new D({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new D({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:_.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new D({...this._def,catchall:$})}pick($){let W={};for(let G of b.objectKeys($))if($[G]&&this.shape[G])W[G]=this.shape[G];return new D({...this._def,shape:()=>W})}omit($){let W={};for(let G of b.objectKeys(this.shape))if(!$[G])W[G]=this.shape[G];return new D({...this._def,shape:()=>W})}deepPartial(){return X$(this)}partial($){let W={};for(let G of b.objectKeys(this.shape)){let H=this.shape[G];if($&&!$[G])W[G]=H;else W[G]=H.optional()}return new D({...this._def,shape:()=>W})}required($){let W={};for(let G of b.objectKeys(this.shape))if($&&!$[G])W[G]=this.shape[G];else{let X=this.shape[G];while(X instanceof K)X=X._def.innerType;W[G]=X}return new D({...this._def,shape:()=>W})}keyof(){return YW(b.objectKeys(this.shape))}}D.create=($,W)=>{return new D({shape:()=>$,unknownKeys:"strip",catchall:h.create(),typeName:_.ZodObject,...A(W)})};D.strictCreate=($,W)=>{return new D({shape:()=>$,unknownKeys:"strict",catchall:h.create(),typeName:_.ZodObject,...A(W)})};D.lazycreate=($,W)=>{return new D({shape:$,unknownKeys:"strip",catchall:h.create(),typeName:_.ZodObject,...A(W)})};class B$ extends U{_parse($){let{ctx:W}=this._processInputParams($),G=this._def.options;function H(X){for(let Y of X)if(Y.result.status==="valid")return Y.result;for(let Y of X)if(Y.result.status==="dirty")return W.common.issues.push(...Y.ctx.common.issues),Y.result;let Q=X.map((Y)=>new L(Y.ctx.common.issues));return z(W,{code:B.invalid_union,unionErrors:Q}),O}if(W.common.async)return Promise.all(G.map(async(X)=>{let Q={...W,common:{...W.common,issues:[]},parent:null};return{result:await X._parseAsync({data:W.data,path:W.path,parent:Q}),ctx:Q}})).then(H);else{let X=void 0,Q=[];for(let M of G){let w={...W,common:{...W.common,issues:[]},parent:null},V=M._parseSync({data:W.data,path:W.path,parent:w});if(V.status==="valid")return V;else if(V.status==="dirty"&&!X)X={result:V,ctx:w};if(w.common.issues.length)Q.push(w.common.issues)}if(X)return W.common.issues.push(...X.ctx.common.issues),X.result;let Y=Q.map((M)=>new L(M));return z(W,{code:B.invalid_union,unionErrors:Y}),O}}get options(){return this._def.options}}B$.create=($,W)=>{return new B$({options:$,typeName:_.ZodUnion,...A(W)})};var m=($)=>{if($ instanceof q$)return m($.schema);else if($ instanceof C)return m($.innerType());else if($ instanceof w$)return[$.value];else if($ instanceof i)return $.options;else if($ instanceof z$)return b.objectValues($.enum);else if($ instanceof j$)return m($._def.innerType);else if($ instanceof Q$)return[void 0];else if($ instanceof Y$)return[null];else if($ instanceof K)return[void 0,...m($.unwrap())];else if($ instanceof Z)return[null,...m($.unwrap())];else if($ instanceof K$)return m($.unwrap());else if($ instanceof V$)return m($.unwrap());else if($ instanceof O$)return m($._def.innerType);else return[]};class f$ extends U{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==q.object)return z(W,{code:B.invalid_type,expected:q.object,received:W.parsedType}),O;let G=this.discriminator,H=W.data[G],X=this.optionsMap.get(H);if(!X)return z(W,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[G]}),O;if(W.common.async)return X._parseAsync({data:W.data,path:W.path,parent:W});else return X._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,G){let H=new Map;for(let X of W){let Q=m(X.shape[$]);if(!Q.length)throw new Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Y of Q){if(H.has(Y))throw new Error(`Discriminator property ${String($)} has duplicate value ${String(Y)}`);H.set(Y,X)}}return new f$({typeName:_.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:H,...A(G)})}}function u$($,W){let G=T($),H=T(W);if($===W)return{valid:!0,data:$};else if(G===q.object&&H===q.object){let X=b.objectKeys(W),Q=b.objectKeys($).filter((M)=>X.indexOf(M)!==-1),Y={...$,...W};for(let M of Q){let w=u$($[M],W[M]);if(!w.valid)return{valid:!1};Y[M]=w.data}return{valid:!0,data:Y}}else if(G===q.array&&H===q.array){if($.length!==W.length)return{valid:!1};let X=[];for(let Q=0;Q<$.length;Q++){let Y=$[Q],M=W[Q],w=u$(Y,M);if(!w.valid)return{valid:!1};X.push(w.data)}return{valid:!0,data:X}}else if(G===q.date&&H===q.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class M$ extends U{_parse($){let{status:W,ctx:G}=this._processInputParams($),H=(X,Q)=>{if(S$(X)||S$(Q))return O;let Y=u$(X.value,Q.value);if(!Y.valid)return z(G,{code:B.invalid_intersection_types}),O;if(F$(X)||F$(Q))W.dirty();return{status:W.value,value:Y.data}};if(G.common.async)return Promise.all([this._def.left._parseAsync({data:G.data,path:G.path,parent:G}),this._def.right._parseAsync({data:G.data,path:G.path,parent:G})]).then(([X,Q])=>H(X,Q));else return H(this._def.left._parseSync({data:G.data,path:G.path,parent:G}),this._def.right._parseSync({data:G.data,path:G.path,parent:G}))}}M$.create=($,W,G)=>{return new M$({left:$,right:W,typeName:_.ZodIntersection,...A(G)})};class x extends U{_parse($){let{status:W,ctx:G}=this._processInputParams($);if(G.parsedType!==q.array)return z(G,{code:B.invalid_type,expected:q.array,received:G.parsedType}),O;if(G.data.length<this._def.items.length)return z(G,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;if(!this._def.rest&&G.data.length>this._def.items.length)z(G,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let X=[...G.data].map((Q,Y)=>{let M=this._def.items[Y]||this._def.rest;if(!M)return null;return M._parse(new k(G,Q,G.path,Y))}).filter((Q)=>!!Q);if(G.common.async)return Promise.all(X).then((Q)=>{return N.mergeArray(W,Q)});else return N.mergeArray(W,X)}get items(){return this._def.items}rest($){return new x({...this._def,rest:$})}}x.create=($,W)=>{if(!Array.isArray($))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new x({items:$,typeName:_.ZodTuple,rest:null,...A(W)})};class D$ extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:G}=this._processInputParams($);if(G.parsedType!==q.object)return z(G,{code:B.invalid_type,expected:q.object,received:G.parsedType}),O;let H=[],X=this._def.keyType,Q=this._def.valueType;for(let Y in G.data)H.push({key:X._parse(new k(G,Y,G.path,Y)),value:Q._parse(new k(G,G.data[Y],G.path,Y)),alwaysSet:Y in G.data});if(G.common.async)return N.mergeObjectAsync(W,H);else return N.mergeObjectSync(W,H)}get element(){return this._def.valueType}static create($,W,G){if(W instanceof U)return new D$({keyType:$,valueType:W,typeName:_.ZodRecord,...A(G)});return new D$({keyType:F.create(),valueType:$,typeName:_.ZodRecord,...A(W)})}}class N$ extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:G}=this._processInputParams($);if(G.parsedType!==q.map)return z(G,{code:B.invalid_type,expected:q.map,received:G.parsedType}),O;let H=this._def.keyType,X=this._def.valueType,Q=[...G.data.entries()].map(([Y,M],w)=>{return{key:H._parse(new k(G,Y,G.path,[w,"key"])),value:X._parse(new k(G,M,G.path,[w,"value"]))}});if(G.common.async){let Y=new Map;return Promise.resolve().then(async()=>{for(let M of Q){let w=await M.key,V=await M.value;if(w.status==="aborted"||V.status==="aborted")return O;if(w.status==="dirty"||V.status==="dirty")W.dirty();Y.set(w.value,V.value)}return{status:W.value,value:Y}})}else{let Y=new Map;for(let M of Q){let{key:w,value:V}=M;if(w.status==="aborted"||V.status==="aborted")return O;if(w.status==="dirty"||V.status==="dirty")W.dirty();Y.set(w.value,V.value)}return{status:W.value,value:Y}}}}N$.create=($,W,G)=>{return new N$({valueType:W,keyType:$,typeName:_.ZodMap,...A(G)})};class s extends U{_parse($){let{status:W,ctx:G}=this._processInputParams($);if(G.parsedType!==q.set)return z(G,{code:B.invalid_type,expected:q.set,received:G.parsedType}),O;let H=this._def;if(H.minSize!==null){if(G.data.size<H.minSize.value)z(G,{code:B.too_small,minimum:H.minSize.value,type:"set",inclusive:!0,exact:!1,message:H.minSize.message}),W.dirty()}if(H.maxSize!==null){if(G.data.size>H.maxSize.value)z(G,{code:B.too_big,maximum:H.maxSize.value,type:"set",inclusive:!0,exact:!1,message:H.maxSize.message}),W.dirty()}let X=this._def.valueType;function Q(M){let w=new Set;for(let V of M){if(V.status==="aborted")return O;if(V.status==="dirty")W.dirty();w.add(V.value)}return{status:W.value,value:w}}let Y=[...G.data.values()].map((M,w)=>X._parse(new k(G,M,G.path,w)));if(G.common.async)return Promise.all(Y).then((M)=>Q(M));else return Q(Y)}min($,W){return new s({...this._def,minSize:{value:$,message:j.toString(W)}})}max($,W){return new s({...this._def,maxSize:{value:$,message:j.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}s.create=($,W)=>{return new s({valueType:$,minSize:null,maxSize:null,typeName:_.ZodSet,...A(W)})};class H$ extends U{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==q.function)return z(W,{code:B.invalid_type,expected:q.function,received:W.parsedType}),O;function G(Y,M){return A$({data:Y,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,W$(),y].filter((w)=>!!w),issueData:{code:B.invalid_arguments,argumentsError:M}})}function H(Y,M){return A$({data:Y,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,W$(),y].filter((w)=>!!w),issueData:{code:B.invalid_return_type,returnTypeError:M}})}let X={errorMap:W.common.contextualErrorMap},Q=W.data;if(this._def.returns instanceof t){let Y=this;return R(async function(...M){let w=new L([]),V=await Y._def.args.parseAsync(M,X).catch(($$)=>{throw w.addIssue(G(M,$$)),w}),v=await Reflect.apply(Q,this,V);return await Y._def.returns._def.type.parseAsync(v,X).catch(($$)=>{throw w.addIssue(H(v,$$)),w})})}else{let Y=this;return R(function(...M){let w=Y._def.args.safeParse(M,X);if(!w.success)throw new L([G(M,w.error)]);let V=Reflect.apply(Q,this,w.data),v=Y._def.returns.safeParse(V,X);if(!v.success)throw new L([H(V,v.error)]);return v.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new H$({...this._def,args:x.create($).rest(c.create())})}returns($){return new H$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,G){return new H$({args:$?$:x.create([]).rest(c.create()),returns:W||c.create(),typeName:_.ZodFunction,...A(G)})}}class q$ extends U{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}q$.create=($,W)=>{return new q$({getter:$,typeName:_.ZodLazy,...A(W)})};class w$ extends U{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return z(W,{received:W.data,code:B.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:$.data}}get value(){return this._def.value}}w$.create=($,W)=>{return new w$({value:$,typeName:_.ZodLiteral,...A(W)})};function YW($,W){return new i({values:$,typeName:_.ZodEnum,...A(W)})}class i extends U{_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),G=this._def.values;return z(W,{expected:b.joinValues(G),received:W.parsedType,code:B.invalid_type}),O}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let W=this._getOrReturnCtx($),G=this._def.values;return z(W,{received:W.data,code:B.invalid_enum_value,options:G}),O}return R($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return i.create($,{...this._def,...W})}exclude($,W=this._def){return i.create(this.options.filter((G)=>!$.includes(G)),{...this._def,...W})}}i.create=YW;class z$ extends U{_parse($){let W=b.getValidEnumValues(this._def.values),G=this._getOrReturnCtx($);if(G.parsedType!==q.string&&G.parsedType!==q.number){let H=b.objectValues(W);return z(G,{expected:b.joinValues(H),received:G.parsedType,code:B.invalid_type}),O}if(!this._cache)this._cache=new Set(b.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let H=b.objectValues(W);return z(G,{received:G.data,code:B.invalid_enum_value,options:H}),O}return R($.data)}get enum(){return this._def.values}}z$.create=($,W)=>{return new z$({values:$,typeName:_.ZodNativeEnum,...A(W)})};class t extends U{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==q.promise&&W.common.async===!1)return z(W,{code:B.invalid_type,expected:q.promise,received:W.parsedType}),O;let G=W.parsedType===q.promise?W.data:Promise.resolve(W.data);return R(G.then((H)=>{return this._def.type.parseAsync(H,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}t.create=($,W)=>{return new t({type:$,typeName:_.ZodPromise,...A(W)})};class C extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:G}=this._processInputParams($),H=this._def.effect||null,X={addIssue:(Q)=>{if(z(G,Q),Q.fatal)W.abort();else W.dirty()},get path(){return G.path}};if(X.addIssue=X.addIssue.bind(X),H.type==="preprocess"){let Q=H.transform(G.data,X);if(G.common.async)return Promise.resolve(Q).then(async(Y)=>{if(W.value==="aborted")return O;let M=await this._def.schema._parseAsync({data:Y,path:G.path,parent:G});if(M.status==="aborted")return O;if(M.status==="dirty")return r(M.value);if(W.value==="dirty")return r(M.value);return M});else{if(W.value==="aborted")return O;let Y=this._def.schema._parseSync({data:Q,path:G.path,parent:G});if(Y.status==="aborted")return O;if(Y.status==="dirty")return r(Y.value);if(W.value==="dirty")return r(Y.value);return Y}}if(H.type==="refinement"){let Q=(Y)=>{let M=H.refinement(Y,X);if(G.common.async)return Promise.resolve(M);if(M instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Y};if(G.common.async===!1){let Y=this._def.schema._parseSync({data:G.data,path:G.path,parent:G});if(Y.status==="aborted")return O;if(Y.status==="dirty")W.dirty();return Q(Y.value),{status:W.value,value:Y.value}}else return this._def.schema._parseAsync({data:G.data,path:G.path,parent:G}).then((Y)=>{if(Y.status==="aborted")return O;if(Y.status==="dirty")W.dirty();return Q(Y.value).then(()=>{return{status:W.value,value:Y.value}})})}if(H.type==="transform")if(G.common.async===!1){let Q=this._def.schema._parseSync({data:G.data,path:G.path,parent:G});if(!u(Q))return O;let Y=H.transform(Q.value,X);if(Y instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:Y}}else return this._def.schema._parseAsync({data:G.data,path:G.path,parent:G}).then((Q)=>{if(!u(Q))return O;return Promise.resolve(H.transform(Q.value,X)).then((Y)=>({status:W.value,value:Y}))});b.assertNever(H)}}C.create=($,W,G)=>{return new C({schema:$,typeName:_.ZodEffects,effect:W,...A(G)})};C.createWithPreprocess=($,W,G)=>{return new C({schema:W,effect:{type:"preprocess",transform:$},typeName:_.ZodEffects,...A(G)})};class K extends U{_parse($){if(this._getType($)===q.undefined)return R(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}K.create=($,W)=>{return new K({innerType:$,typeName:_.ZodOptional,...A(W)})};class Z extends U{_parse($){if(this._getType($)===q.null)return R(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}Z.create=($,W)=>{return new Z({innerType:$,typeName:_.ZodNullable,...A(W)})};class j$ extends U{_parse($){let{ctx:W}=this._processInputParams($),G=W.data;if(W.parsedType===q.undefined)G=this._def.defaultValue();return this._def.innerType._parse({data:G,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}j$.create=($,W)=>{return new j$({innerType:$,typeName:_.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...A(W)})};class O$ extends U{_parse($){let{ctx:W}=this._processInputParams($),G={...W,common:{...W.common,issues:[]}},H=this._def.innerType._parse({data:G.data,path:G.path,parent:{...G}});if(G$(H))return H.then((X)=>{return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new L(G.common.issues)},input:G.data})}});else return{status:"valid",value:H.status==="valid"?H.value:this._def.catchValue({get error(){return new L(G.common.issues)},input:G.data})}}removeCatch(){return this._def.innerType}}O$.create=($,W)=>{return new O$({innerType:$,typeName:_.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...A(W)})};class R$ extends U{_parse($){if(this._getType($)!==q.nan){let G=this._getOrReturnCtx($);return z(G,{code:B.invalid_type,expected:q.nan,received:G.parsedType}),O}return{status:"valid",value:$.data}}}R$.create=($)=>{return new R$({typeName:_.ZodNaN,...A($)})};var eW=Symbol("zod_brand");class K$ extends U{_parse($){let{ctx:W}=this._processInputParams($),G=W.data;return this._def.type._parse({data:G,path:W.path,parent:W})}unwrap(){return this._def.type}}class v$ extends U{_parse($){let{status:W,ctx:G}=this._processInputParams($);if(G.common.async)return(async()=>{let X=await this._def.in._parseAsync({data:G.data,path:G.path,parent:G});if(X.status==="aborted")return O;if(X.status==="dirty")return W.dirty(),r(X.value);else return this._def.out._parseAsync({data:X.value,path:G.path,parent:G})})();else{let H=this._def.in._parseSync({data:G.data,path:G.path,parent:G});if(H.status==="aborted")return O;if(H.status==="dirty")return W.dirty(),{status:"dirty",value:H.value};else return this._def.out._parseSync({data:H.value,path:G.path,parent:G})}}static create($,W){return new v$({in:$,out:W,typeName:_.ZodPipeline})}}class V$ extends U{_parse($){let W=this._def.innerType._parse($),G=(H)=>{if(u(H))H.value=Object.freeze(H.value);return H};return G$(W)?W.then((H)=>G(H)):G(W)}unwrap(){return this._def.innerType}}V$.create=($,W)=>{return new V$({innerType:$,typeName:_.ZodReadonly,...A(W)})};function XW($,W){let G=typeof $==="function"?$(W):typeof $==="string"?{message:$}:$;return typeof G==="string"?{message:G}:G}function BW($,W={},G){if($)return a.create().superRefine((H,X)=>{let Q=$(H);if(Q instanceof Promise)return Q.then((Y)=>{if(!Y){let M=XW(W,H),w=M.fatal??G??!0;X.addIssue({code:"custom",...M,fatal:w})}});if(!Q){let Y=XW(W,H),M=Y.fatal??G??!0;X.addIssue({code:"custom",...Y,fatal:M})}return});return a.create()}var $3={object:D.lazycreate},_;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(_||(_={}));var W3=($,W={message:`Input not instance of ${$.name}`})=>BW((G)=>G instanceof $,W),MW=F.create,qW=n.create,G3=R$.create,X3=p.create,wW=J$.create,H3=o.create,J3=U$.create,Q3=Q$.create,Y3=Y$.create,B3=a.create,M3=c.create,q3=h.create,w3=b$.create,z3=f.create,j3=D.create,O3=D.strictCreate,V3=B$.create,_3=f$.create,A3=M$.create,U3=x.create,b3=D$.create,D3=N$.create,N3=s.create,R3=H$.create,v3=q$.create,L3=w$.create,E3=i.create,S3=z$.create,F3=t.create,f3=C.create,K3=K.create,k3=Z.create,C3=C.createWithPreprocess,I3=v$.create,P3=()=>MW().optional(),g3=()=>qW().optional(),T3=()=>wW().optional(),h3={string:($)=>F.create({...$,coerce:!0}),number:($)=>n.create({...$,coerce:!0}),boolean:($)=>J$.create({...$,coerce:!0}),bigint:($)=>p.create({...$,coerce:!0}),date:($)=>o.create({...$,coerce:!0})};var x3=O;var c$="2024-11-05",zW=[c$,"2024-10-07"],k$="2.0",jW=J.union([J.string(),J.number().int()]),OW=J.string(),I=J.object({_meta:J.optional(J.object({progressToken:J.optional(jW)}).passthrough())}).passthrough(),E=J.object({method:J.string(),params:J.optional(I)}),L$=J.object({_meta:J.optional(J.object({}).passthrough())}).passthrough(),l=J.object({method:J.string(),params:J.optional(L$)}),P=J.object({_meta:J.optional(J.object({}).passthrough())}).passthrough(),C$=J.union([J.string(),J.number().int()]),l3=J.object({jsonrpc:J.literal(k$),id:C$}).merge(E).strict(),y3=J.object({jsonrpc:J.literal(k$)}).merge(l).strict(),m3=J.object({jsonrpc:J.literal(k$),id:C$,result:P}).strict(),e;(function($){$[$.ConnectionClosed=-1]="ConnectionClosed",$[$.RequestTimeout=-2]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError"})(e||(e={}));var Z3=J.object({jsonrpc:J.literal(k$),id:C$,error:J.object({code:J.number().int(),message:J.string(),data:J.optional(J.unknown())})}).strict(),VW=J.union([l3,y3,m3,Z3]),I$=P.strict(),P$=l.extend({method:J.literal("notifications/cancelled"),params:L$.extend({requestId:C$,reason:J.string().optional()})}),_W=J.object({name:J.string(),version:J.string()}).passthrough(),u3=J.object({experimental:J.optional(J.object({}).passthrough()),sampling:J.optional(J.object({}).passthrough()),roots:J.optional(J.object({listChanged:J.optional(J.boolean())}).passthrough())}).passthrough(),n$=E.extend({method:J.literal("initialize"),params:I.extend({protocolVersion:J.string(),capabilities:u3,clientInfo:_W})}),c3=J.object({experimental:J.optional(J.object({}).passthrough()),logging:J.optional(J.object({}).passthrough()),prompts:J.optional(J.object({listChanged:J.optional(J.boolean())}).passthrough()),resources:J.optional(J.object({subscribe:J.optional(J.boolean()),listChanged:J.optional(J.boolean())}).passthrough()),tools:J.optional(J.object({listChanged:J.optional(J.boolean())}).passthrough())}).passthrough(),n3=P.extend({protocolVersion:J.string(),capabilities:c3,serverInfo:_W}),p$=l.extend({method:J.literal("notifications/initialized")}),g$=E.extend({method:J.literal("ping")}),p3=J.object({progress:J.number(),total:J.optional(J.number())}).passthrough(),T$=l.extend({method:J.literal("notifications/progress"),params:L$.merge(p3).extend({progressToken:jW})}),h$=E.extend({params:I.extend({cursor:J.optional(OW)}).optional()}),x$=P.extend({nextCursor:J.optional(OW)}),AW=J.object({uri:J.string(),mimeType:J.optional(J.string())}).passthrough(),UW=AW.extend({text:J.string()}),bW=AW.extend({blob:J.string().base64()}),i3=J.object({uri:J.string(),name:J.string(),description:J.optional(J.string()),mimeType:J.optional(J.string())}).passthrough(),d3=J.object({uriTemplate:J.string(),name:J.string(),description:J.optional(J.string()),mimeType:J.optional(J.string())}).passthrough(),r3=h$.extend({method:J.literal("resources/list")}),o3=x$.extend({resources:J.array(i3)}),a3=h$.extend({method:J.literal("resources/templates/list")}),s3=x$.extend({resourceTemplates:J.array(d3)}),t3=E.extend({method:J.literal("resources/read"),params:I.extend({uri:J.string()})}),e3=P.extend({contents:J.array(J.union([UW,bW]))}),$G=l.extend({method:J.literal("notifications/resources/list_changed")}),WG=E.extend({method:J.literal("resources/subscribe"),params:I.extend({uri:J.string()})}),GG=E.extend({method:J.literal("resources/unsubscribe"),params:I.extend({uri:J.string()})}),XG=l.extend({method:J.literal("notifications/resources/updated"),params:L$.extend({uri:J.string()})}),HG=J.object({name:J.string(),description:J.optional(J.string()),required:J.optional(J.boolean())}).passthrough(),JG=J.object({name:J.string(),description:J.optional(J.string()),arguments:J.optional(J.array(HG))}).passthrough(),QG=h$.extend({method:J.literal("prompts/list")}),YG=x$.extend({prompts:J.array(JG)}),BG=E.extend({method:J.literal("prompts/get"),params:I.extend({name:J.string(),arguments:J.optional(J.record(J.string()))})}),l$=J.object({type:J.literal("text"),text:J.string()}).passthrough(),y$=J.object({type:J.literal("image"),data:J.string().base64(),mimeType:J.string()}).passthrough(),DW=J.object({type:J.literal("resource"),resource:J.union([UW,bW])}).passthrough(),MG=J.object({role:J.enum(["user","assistant"]),content:J.union([l$,y$,DW])}).passthrough(),qG=P.extend({description:J.optional(J.string()),messages:J.array(MG)}),wG=l.extend({method:J.literal("notifications/prompts/list_changed")}),zG=J.object({name:J.string(),description:J.optional(J.string()),inputSchema:J.object({type:J.literal("object"),properties:J.optional(J.object({}).passthrough())}).passthrough()}).passthrough(),i$=h$.extend({method:J.literal("tools/list")}),jG=x$.extend({tools:J.array(zG)}),NW=P.extend({content:J.array(J.union([l$,y$,DW])),isError:J.boolean().default(!1).optional()}),BX=NW.or(P.extend({toolResult:J.unknown()})),d$=E.extend({method:J.literal("tools/call"),params:I.extend({name:J.string(),arguments:J.optional(J.record(J.unknown()))})}),OG=l.extend({method:J.literal("notifications/tools/list_changed")}),RW=J.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),VG=E.extend({method:J.literal("logging/setLevel"),params:I.extend({level:RW})}),_G=l.extend({method:J.literal("notifications/message"),params:L$.extend({level:RW,logger:J.optional(J.string()),data:J.unknown()})}),AG=J.object({name:J.string().optional()}).passthrough(),UG=J.object({hints:J.optional(J.array(AG)),costPriority:J.optional(J.number().min(0).max(1)),speedPriority:J.optional(J.number().min(0).max(1)),intelligencePriority:J.optional(J.number().min(0).max(1))}).passthrough(),bG=J.object({role:J.enum(["user","assistant"]),content:J.union([l$,y$])}).passthrough(),DG=E.extend({method:J.literal("sampling/createMessage"),params:I.extend({messages:J.array(bG),systemPrompt:J.optional(J.string()),includeContext:J.optional(J.enum(["none","thisServer","allServers"])),temperature:J.optional(J.number()),maxTokens:J.number().int(),stopSequences:J.optional(J.array(J.string())),metadata:J.optional(J.object({}).passthrough()),modelPreferences:J.optional(UG)})}),r$=P.extend({model:J.string(),stopReason:J.optional(J.enum(["endTurn","stopSequence","maxTokens"]).or(J.string())),role:J.enum(["user","assistant"]),content:J.discriminatedUnion("type",[l$,y$])}),NG=J.object({type:J.literal("ref/resource"),uri:J.string()}).passthrough(),RG=J.object({type:J.literal("ref/prompt"),name:J.string()}).passthrough(),vG=E.extend({method:J.literal("completion/complete"),params:I.extend({ref:J.union([RG,NG]),argument:J.object({name:J.string(),value:J.string()}).passthrough()})}),LG=P.extend({completion:J.object({values:J.array(J.string()).max(100),total:J.optional(J.number().int()),hasMore:J.optional(J.boolean())}).passthrough()}),EG=J.object({uri:J.string().startsWith("file://"),name:J.optional(J.string())}).passthrough(),SG=E.extend({method:J.literal("roots/list")}),o$=P.extend({roots:J.array(EG)}),FG=l.extend({method:J.literal("notifications/roots/list_changed")}),MX=J.union([g$,n$,vG,VG,BG,QG,r3,a3,t3,WG,GG,d$,i$]),qX=J.union([P$,T$,p$,FG]),wX=J.union([I$,r$,o$]),zX=J.union([g$,DG,SG]),jX=J.union([P$,T$,_G,XG,$G,OG,wG]),OX=J.union([I$,n3,LG,qG,YG,o3,s3,e3,NW,jG]);class E$ extends Error{constructor($,W,G){super(`MCP error ${$}: ${W}`);this.code=$,this.data=G}}var fG=60000;class a${constructor($){this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this.setNotificationHandler(P$,(W)=>{let G=this._requestHandlerAbortControllers.get(W.params.requestId);G===null||G===void 0||G.abort(W.params.reason)}),this.setNotificationHandler(T$,(W)=>{this._onprogress(W)}),this.setRequestHandler(g$,(W)=>({}))}async connect($){this._transport=$,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=(W)=>{this._onerror(W)},this._transport.onmessage=(W)=>{if(!("method"in W))this._onresponse(W);else if("id"in W)this._onrequest(W);else this._onnotification(W)},await this._transport.start()}_onclose(){var $;let W=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,($=this.onclose)===null||$===void 0||$.call(this);let G=new E$(e.ConnectionClosed,"Connection closed");for(let H of W.values())H(G)}_onerror($){var W;(W=this.onerror)===null||W===void 0||W.call(this,$)}_onnotification($){var W;let G=(W=this._notificationHandlers.get($.method))!==null&&W!==void 0?W:this.fallbackNotificationHandler;if(G===void 0)return;Promise.resolve().then(()=>G($)).catch((H)=>this._onerror(new Error(`Uncaught error in notification handler: ${H}`)))}_onrequest($){var W,G;let H=(W=this._requestHandlers.get($.method))!==null&&W!==void 0?W:this.fallbackRequestHandler;if(H===void 0){(G=this._transport)===null||G===void 0||G.send({jsonrpc:"2.0",id:$.id,error:{code:e.MethodNotFound,message:"Method not found"}}).catch((Q)=>this._onerror(new Error(`Failed to send an error response: ${Q}`)));return}let X=new AbortController;this._requestHandlerAbortControllers.set($.id,X),Promise.resolve().then(()=>H($,{signal:X.signal})).then((Q)=>{var Y;if(X.signal.aborted)return;return(Y=this._transport)===null||Y===void 0?void 0:Y.send({result:Q,jsonrpc:"2.0",id:$.id})},(Q)=>{var Y,M;if(X.signal.aborted)return;return(Y=this._transport)===null||Y===void 0?void 0:Y.send({jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(Q.code)?Q.code:e.InternalError,message:(M=Q.message)!==null&&M!==void 0?M:"Internal error"}})}).catch((Q)=>this._onerror(new Error(`Failed to send response: ${Q}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progress:W,total:G,progressToken:H}=$.params,X=this._progressHandlers.get(Number(H));if(X===void 0){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}X({progress:W,total:G})}_onresponse($){let W=$.id,G=this._responseHandlers.get(Number(W));if(G===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}if(this._responseHandlers.delete(Number(W)),this._progressHandlers.delete(Number(W)),"result"in $)G($);else{let H=new E$($.error.code,$.error.message,$.error.data);G(H)}}get transport(){return this._transport}async close(){var $;await(($=this._transport)===null||$===void 0?void 0:$.close())}request($,W,G){return new Promise((H,X)=>{var Q,Y,M,w;if(!this._transport){X(new Error("Not connected"));return}if(((Q=this._options)===null||Q===void 0?void 0:Q.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod($.method);(Y=G===null||G===void 0?void 0:G.signal)===null||Y===void 0||Y.throwIfAborted();let V=this._requestMessageId++,v={...$,jsonrpc:"2.0",id:V};if(G===null||G===void 0?void 0:G.onprogress)this._progressHandlers.set(V,G.onprogress),v.params={...$.params,_meta:{progressToken:V}};let g=void 0;this._responseHandlers.set(V,(S)=>{var d;if(g!==void 0)clearTimeout(g);if((d=G===null||G===void 0?void 0:G.signal)===null||d===void 0?void 0:d.aborted)return;if(S instanceof Error)return X(S);try{let _$=W.parse(S.result);H(_$)}catch(_$){X(_$)}});let $$=(S)=>{var d;this._responseHandlers.delete(V),this._progressHandlers.delete(V),(d=this._transport)===null||d===void 0||d.send({jsonrpc:"2.0",method:"cancelled",params:{requestId:V,reason:String(S)}}).catch((_$)=>this._onerror(new Error(`Failed to send cancellation: ${_$}`))),X(S)};(M=G===null||G===void 0?void 0:G.signal)===null||M===void 0||M.addEventListener("abort",()=>{var S;if(g!==void 0)clearTimeout(g);$$((S=G===null||G===void 0?void 0:G.signal)===null||S===void 0?void 0:S.reason)});let $W=(w=G===null||G===void 0?void 0:G.timeout)!==null&&w!==void 0?w:fG;g=setTimeout(()=>$$(new E$(e.RequestTimeout,"Request timed out",{timeout:$W})),$W),this._transport.send(v).catch((S)=>{if(g!==void 0)clearTimeout(g);X(S)})})}async notification($){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability($.method);let W={...$,jsonrpc:"2.0"};await this._transport.send(W)}setRequestHandler($,W){let G=$.shape.method.value;this.assertRequestHandlerCapability(G),this._requestHandlers.set(G,(H,X)=>Promise.resolve(W($.parse(H),X)))}removeRequestHandler($){this._requestHandlers.delete($)}setNotificationHandler($,W){this._notificationHandlers.set($.shape.method.value,(G)=>Promise.resolve(W($.parse(G))))}removeNotificationHandler($){this._notificationHandlers.delete($)}}class s$ extends a${constructor($,W){super(W);this._serverInfo=$,this._capabilities=W.capabilities,this.setRequestHandler(n$,(G)=>this._oninitialize(G)),this.setNotificationHandler(p$,()=>{var G;return(G=this.oninitialized)===null||G===void 0?void 0:G.call(this)})}assertCapabilityForMethod($){var W,G;switch($){case"sampling/createMessage":if(!((W=this._clientCapabilities)===null||W===void 0?void 0:W.sampling))throw new Error(`Client does not support sampling (required for ${$})`);break;case"roots/list":if(!((G=this._clientCapabilities)===null||G===void 0?void 0:G.roots))throw new Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){switch($){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${$})`);break;case"ping":case"initialize":break}}async _oninitialize($){let W=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:zW.includes(W)?W:c$,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},I$)}async createMessage($,W){return this.request({method:"sampling/createMessage",params:$},r$,W)}async listRoots($,W){return this.request({method:"roots/list",params:$},o$,W)}async sendLoggingMessage($){return this.notification({method:"notifications/message",params:$})}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}import LW from"node:process";class t${append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
3
+ `);if($===-1)return null;let W=this._buffer.toString("utf8",0,$);return this._buffer=this._buffer.subarray($+1),KG(W)}clear(){this._buffer=void 0}}function KG($){return VW.parse(JSON.parse($))}function vW($){return JSON.stringify($)+`
4
+ `}class e${constructor($=LW.stdin,W=LW.stdout){this._stdin=$,this._stdout=W,this._readBuffer=new t$,this._started=!1,this._ondata=(G)=>{this._readBuffer.append(G),this.processReadBuffer()},this._onerror=(G)=>{var H;(H=this.onerror)===null||H===void 0||H.call(this,G)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){var $,W;while(!0)try{let G=this._readBuffer.readMessage();if(G===null)break;($=this.onmessage)===null||$===void 0||$.call(this,G)}catch(G){(W=this.onerror)===null||W===void 0||W.call(this,G)}}async close(){var $;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._readBuffer.clear(),($=this.onclose)===null||$===void 0||$.call(this)}send($){return new Promise((W)=>{let G=vW($);if(this._stdout.write(G))W();else this._stdout.once("drain",W)})}}import{execFile as kG}from"child_process";import{promisify as CG}from"util";var IG=CG(kG);class EW{constructor(){this.server=new s$({name:"chrome-control",version:"0.1.0"},{capabilities:{tools:{}}}),this.setupHandlers()}async executeAppleScript($){try{let{stdout:W,stderr:G}=await IG("osascript",["-e",$]);if(G)console.error("AppleScript stderr:",G);return W.trim()}catch(W){if(console.error("AppleScript execution error:",W),W.message.includes("(-1743)")||W.message.includes("not allowed assistive access")||W.message.includes("not authorized")||W.message.includes("System Events"))throw new Error(`Permission denied: Chrome control requires automation permissions.
5
+
6
+ To grant permission:
7
+ 1. Open System Settings > Privacy & Security > Automation
8
+ 2. Find "Claude" in the list
9
+ 3. Enable "Google Chrome" under Claude
10
+ 4. You may need to restart Claude after granting permission
11
+
12
+ Note: You'll see a permission prompt the first time you use this extension.`);if(W.message.includes("(-600)")||W.message.includes("application isn't running")||W.message.includes("Google Chrome"))throw new Error("Google Chrome is not running. Please launch Chrome and try again.");throw new Error(`AppleScript error: ${W.message}`)}}setupHandlers(){this.server.setRequestHandler(i$,async()=>({tools:[{name:"open_url",description:"Open a URL in Chrome",inputSchema:{type:"object",properties:{url:{type:"string",description:"URL to open"},new_tab:{type:"boolean",description:"Open in a new tab",default:!0}},required:["url"]}},{name:"get_current_tab",description:"Get information about the current active tab",inputSchema:{type:"object",properties:{}}},{name:"list_tabs",description:"List all open tabs in Chrome",inputSchema:{type:"object",properties:{window_id:{type:"number",description:"Specific window ID to list tabs from"}}}},{name:"close_tab",description:"Close a specific tab",inputSchema:{type:"object",properties:{tab_id:{type:"number",description:"ID of the tab to close"}},required:["tab_id"]}},{name:"switch_to_tab",description:"Switch to a specific tab",inputSchema:{type:"object",properties:{tab_id:{type:"number",description:"ID of the tab to switch to"}},required:["tab_id"]}},{name:"reload_tab",description:"Reload a tab",inputSchema:{type:"object",properties:{tab_id:{type:"number",description:"ID of the tab to reload"}}}},{name:"go_back",description:"Navigate back in browser history",inputSchema:{type:"object",properties:{tab_id:{type:"number",description:"ID of the tab"}}}},{name:"go_forward",description:"Navigate forward in browser history",inputSchema:{type:"object",properties:{tab_id:{type:"number",description:"ID of the tab"}}}},{name:"execute_javascript",description:"Execute JavaScript in the current tab",inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript code to execute"},tab_id:{type:"number",description:"ID of the tab"}},required:["code"]}},{name:"get_page_content",description:"Get the text content of the current page",inputSchema:{type:"object",properties:{tab_id:{type:"number",description:"ID of the tab"}}}}]})),this.server.setRequestHandler(d$,async($)=>{let{name:W,arguments:G}=$.params;try{switch(W){case"open_url":{let{url:H,new_tab:X=!0}=G;try{new URL(H)}catch(Y){return{content:[{type:"text",text:`Error: url is not a valid url - ${Y.message}`}],isError:!0}}let Q=X?`tell application "Google Chrome" to open location ${JSON.stringify(H)}`:`tell application "Google Chrome" to set URL of active tab of front window to ${JSON.stringify(H)}`;return await this.executeAppleScript(Q),{content:[{type:"text",text:`Opened ${H} in Chrome`}]}}case"get_current_tab":{let X=await this.executeAppleScript(`
13
+ tell application "Google Chrome"
14
+ set currentTab to active tab of front window
15
+ set tabInfo to {URL of currentTab, title of currentTab, id of currentTab}
16
+ return tabInfo
17
+ end tell
18
+ `),[Q,Y,M]=X.split(", ");return{content:[{type:"text",text:JSON.stringify({url:Q,title:Y,id:parseInt(M)},null,2)}]}}case"list_tabs":{let Q=(await this.executeAppleScript(`
19
+ tell application "Google Chrome"
20
+ set tabsList to {}
21
+ repeat with w in windows
22
+ repeat with t in tabs of w
23
+ set end of tabsList to {id of t as string, URL of t, title of t}
24
+ end repeat
25
+ end repeat
26
+ set AppleScript's text item delimiters to "|"
27
+ set output to ""
28
+ repeat with tabInfo in tabsList
29
+ set output to output & (item 1 of tabInfo) & "," & (item 2 of tabInfo) & "," & (item 3 of tabInfo) & "|"
30
+ end repeat
31
+ return output
32
+ end tell
33
+ `)).split("|").filter((Y)=>Y).map((Y)=>{let[M,w,V]=Y.split(",");return{id:parseInt(M),url:w,title:V}});return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}case"close_tab":{let{tab_id:H}=G,X=`
34
+ tell application "Google Chrome"
35
+ repeat with w in windows
36
+ repeat with t in tabs of w
37
+ if (id of t as string) is "${H}" then
38
+ close t
39
+ return "Tab closed"
40
+ end if
41
+ end repeat
42
+ end repeat
43
+ return "Tab not found"
44
+ end tell
45
+ `;return{content:[{type:"text",text:await this.executeAppleScript(X)}]}}case"switch_to_tab":{let{tab_id:H}=G,X=`
46
+ tell application "Google Chrome"
47
+ repeat with w in windows
48
+ repeat with tabIndex from 1 to count of tabs of w
49
+ set t to tab tabIndex of w
50
+ if (id of t as string) is "${H}" then
51
+ set active tab index of w to tabIndex
52
+ set index of w to 1
53
+ activate
54
+ return "Switched to tab"
55
+ end if
56
+ end repeat
57
+ end repeat
58
+ return "Tab not found"
59
+ end tell
60
+ `;return{content:[{type:"text",text:await this.executeAppleScript(X)}]}}case"reload_tab":{let{tab_id:H}=G,X=H?`
61
+ tell application "Google Chrome"
62
+ repeat with w in windows
63
+ repeat with t in tabs of w
64
+ if (id of t as string) is "${H}" then
65
+ reload t
66
+ return "Tab reloaded"
67
+ end if
68
+ end repeat
69
+ end repeat
70
+ return "Tab not found"
71
+ end tell
72
+ `:`
73
+ tell application "Google Chrome"
74
+ reload active tab of front window
75
+ return "Tab reloaded"
76
+ end tell
77
+ `;return{content:[{type:"text",text:await this.executeAppleScript(X)}]}}case"go_back":{let{tab_id:H}=G,X=H?`
78
+ tell application "Google Chrome"
79
+ repeat with w in windows
80
+ repeat with t in tabs of w
81
+ if (id of t as string) is "${H}" then
82
+ go back t
83
+ return "Navigated back"
84
+ end if
85
+ end repeat
86
+ end repeat
87
+ return "Tab not found"
88
+ end tell
89
+ `:`
90
+ tell application "Google Chrome"
91
+ go back active tab of front window
92
+ return "Navigated back"
93
+ end tell
94
+ `;return{content:[{type:"text",text:await this.executeAppleScript(X)}]}}case"go_forward":{let{tab_id:H}=G,X=H?`
95
+ tell application "Google Chrome"
96
+ repeat with w in windows
97
+ repeat with t in tabs of w
98
+ if (id of t as string) is "${H}" then
99
+ go forward t
100
+ return "Navigated forward"
101
+ end if
102
+ end repeat
103
+ end repeat
104
+ return "Tab not found"
105
+ end tell
106
+ `:`
107
+ tell application "Google Chrome"
108
+ go forward active tab of front window
109
+ return "Navigated forward"
110
+ end tell
111
+ `;return{content:[{type:"text",text:await this.executeAppleScript(X)}]}}case"execute_javascript":{let{code:H,tab_id:X}=G,Q=X?`
112
+ tell application "Google Chrome"
113
+ repeat with w in windows
114
+ repeat with t in tabs of w
115
+ if (id of t as string) is "${X}" then
116
+ set result to execute t javascript ${JSON.stringify(H)}
117
+ return result
118
+ end if
119
+ end repeat
120
+ end repeat
121
+ return "Tab not found"
122
+ end tell
123
+ `:`
124
+ tell application "Google Chrome"
125
+ execute active tab of front window javascript ${JSON.stringify(H)}
126
+ end tell
127
+ `;return{content:[{type:"text",text:await this.executeAppleScript(Q)||"JavaScript executed"}]}}case"get_page_content":{let{tab_id:H}=G,X=H?`
128
+ tell application "Google Chrome"
129
+ repeat with w in windows
130
+ repeat with t in tabs of w
131
+ if (id of t as string) is "${H}" then
132
+ set pageContent to execute t javascript "document.body.innerText"
133
+ return pageContent
134
+ end if
135
+ end repeat
136
+ end repeat
137
+ return "Tab not found"
138
+ end tell
139
+ `:`
140
+ tell application "Google Chrome"
141
+ execute active tab of front window javascript "document.body.innerText"
142
+ end tell
143
+ `;return{content:[{type:"text",text:await this.executeAppleScript(X)}]}}default:throw new Error(`Unknown tool: ${W}`)}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}})}async run(){let $=new e$;await this.server.connect($),console.error("Chrome Control MCP server running on stdio")}}var PG=new EW;PG.run().catch(console.error);
package/package.json CHANGED
@@ -1,16 +1,24 @@
1
1
  {
2
2
  "name": "@kelceyp/chrome-control-mcp",
3
- "version": "0.2.0",
4
- "description": "MCP server for controlling Google Chrome on macOS via AppleScript with async JavaScript support",
5
- "main": "server/index.js",
3
+ "version": "0.2.1",
4
+ "description": "MCP server for controlling Google Chrome on macOS via AppleScript",
6
5
  "type": "module",
6
+ "main": "dist/index.js",
7
7
  "bin": {
8
- "chrome-control-mcp": "server/index.js"
8
+ "chrome-control-mcp": "dist/index.js"
9
9
  },
10
10
  "scripts": {
11
- "start": "node server/index.js",
12
- "test": "echo \"Error: no test specified\" && exit 1"
11
+ "clean": "rm -rf dist",
12
+ "build": "bun run clean && bun build server/index.js --outdir dist --minify --sourcemap=none --target=node --format=esm --banner:js='#!/usr/bin/env node'",
13
+ "prepare": "bun run build",
14
+ "release": "bash scripts/publish.sh"
13
15
  },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE",
20
+ "package.json"
21
+ ],
14
22
  "keywords": [
15
23
  "mcp",
16
24
  "modelcontextprotocol",
@@ -20,24 +28,26 @@
20
28
  "applescript",
21
29
  "macos",
22
30
  "claude",
23
- "ai"
31
+ "ai",
32
+ "server"
24
33
  ],
25
34
  "author": "Paul Kelcey",
26
35
  "license": "MIT",
27
36
  "repository": {
28
37
  "type": "git",
29
- "url": "https://github.com/kelceyp/chrome-control-mcp"
38
+ "url": "git+https://github.com/kelceyp/chrome-control-mcp.git"
30
39
  },
31
40
  "dependencies": {
32
41
  "@modelcontextprotocol/sdk": "^0.6.0"
33
42
  },
34
43
  "engines": {
35
- "node": ">=16.0.0"
44
+ "node": ">=18"
36
45
  },
37
46
  "os": [
38
47
  "darwin"
39
48
  ],
40
49
  "publishConfig": {
41
50
  "access": "restricted"
42
- }
43
- }
51
+ },
52
+ "private": false
53
+ }
package/server/index.js DELETED
@@ -1,576 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
- import {
6
- CallToolRequestSchema,
7
- ListToolsRequestSchema,
8
- } from '@modelcontextprotocol/sdk/types.js';
9
- import { execFile } from 'child_process';
10
- import { promisify } from 'util';
11
-
12
- const execFileAsync = promisify(execFile);
13
-
14
- class ChromeControlServer {
15
- constructor() {
16
- this.server = new Server(
17
- {
18
- name: 'chrome-control',
19
- version: '0.1.0',
20
- },
21
- {
22
- capabilities: {
23
- tools: {},
24
- },
25
- }
26
- );
27
-
28
- this.setupHandlers();
29
- }
30
-
31
- async executeAppleScript(script) {
32
- try {
33
- const { stdout, stderr } = await execFileAsync('osascript', ['-e', script]);
34
- if (stderr) {
35
- console.error('AppleScript stderr:', stderr);
36
- }
37
- return stdout.trim();
38
- } catch (error) {
39
- console.error('AppleScript execution error:', error);
40
-
41
- // Check for common permission-related errors
42
- if (error.message.includes('(-1743)') ||
43
- error.message.includes('not allowed assistive access') ||
44
- error.message.includes('not authorized') ||
45
- error.message.includes('System Events')) {
46
- throw new Error(
47
- 'Permission denied: Chrome control requires automation permissions.\n\n' +
48
- 'To grant permission:\n' +
49
- '1. Open System Settings > Privacy & Security > Automation\n' +
50
- '2. Find "Claude" in the list\n' +
51
- '3. Enable "Google Chrome" under Claude\n' +
52
- '4. You may need to restart Claude after granting permission\n\n' +
53
- 'Note: You\'ll see a permission prompt the first time you use this extension.'
54
- );
55
- }
56
-
57
- // Check for Chrome not running
58
- if (error.message.includes('(-600)') ||
59
- error.message.includes('application isn\'t running') ||
60
- error.message.includes('Google Chrome')) {
61
- throw new Error(
62
- 'Google Chrome is not running. Please launch Chrome and try again.'
63
- );
64
- }
65
-
66
- throw new Error(`AppleScript error: ${error.message}`);
67
- }
68
- }
69
-
70
- setupHandlers() {
71
- this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
72
- tools: [
73
- {
74
- name: 'open_url',
75
- description: 'Open a URL in Chrome',
76
- inputSchema: {
77
- type: 'object',
78
- properties: {
79
- url: { type: 'string', description: 'URL to open' },
80
- new_tab: { type: 'boolean', description: 'Open in a new tab', default: true }
81
- },
82
- required: ['url']
83
- }
84
- },
85
- {
86
- name: 'get_current_tab',
87
- description: 'Get information about the current active tab',
88
- inputSchema: { type: 'object', properties: {} }
89
- },
90
- {
91
- name: 'list_tabs',
92
- description: 'List all open tabs in Chrome',
93
- inputSchema: {
94
- type: 'object',
95
- properties: {
96
- window_id: { type: 'number', description: 'Specific window ID to list tabs from' }
97
- }
98
- }
99
- },
100
- {
101
- name: 'close_tab',
102
- description: 'Close a specific tab',
103
- inputSchema: {
104
- type: 'object',
105
- properties: {
106
- tab_id: { type: 'number', description: 'ID of the tab to close' }
107
- },
108
- required: ['tab_id']
109
- }
110
- },
111
- {
112
- name: 'switch_to_tab',
113
- description: 'Switch to a specific tab',
114
- inputSchema: {
115
- type: 'object',
116
- properties: {
117
- tab_id: { type: 'number', description: 'ID of the tab to switch to' }
118
- },
119
- required: ['tab_id']
120
- }
121
- },
122
- {
123
- name: 'reload_tab',
124
- description: 'Reload a tab',
125
- inputSchema: {
126
- type: 'object',
127
- properties: {
128
- tab_id: { type: 'number', description: 'ID of the tab to reload' }
129
- }
130
- }
131
- },
132
- {
133
- name: 'go_back',
134
- description: 'Navigate back in browser history',
135
- inputSchema: {
136
- type: 'object',
137
- properties: {
138
- tab_id: { type: 'number', description: 'ID of the tab' }
139
- }
140
- }
141
- },
142
- {
143
- name: 'go_forward',
144
- description: 'Navigate forward in browser history',
145
- inputSchema: {
146
- type: 'object',
147
- properties: {
148
- tab_id: { type: 'number', description: 'ID of the tab' }
149
- }
150
- }
151
- },
152
- {
153
- name: 'execute_javascript',
154
- description: 'Execute JavaScript in the current tab',
155
- inputSchema: {
156
- type: 'object',
157
- properties: {
158
- code: { type: 'string', description: 'JavaScript code to execute' },
159
- tab_id: { type: 'number', description: 'ID of the tab' }
160
- },
161
- required: ['code']
162
- }
163
- },
164
- {
165
- name: 'get_page_content',
166
- description: 'Get the text content of the current page',
167
- inputSchema: {
168
- type: 'object',
169
- properties: {
170
- tab_id: { type: 'number', description: 'ID of the tab' }
171
- }
172
- }
173
- },
174
- {
175
- name: 'execute_javascript_async',
176
- description: 'Execute async JavaScript in the current tab and wait for result',
177
- inputSchema: {
178
- type: 'object',
179
- properties: {
180
- code: { type: 'string', description: 'JavaScript code to execute (supports await)' },
181
- tab_id: { type: 'number', description: 'ID of the tab' },
182
- timeout_ms: { type: 'number', description: 'Timeout in milliseconds', default: 60000 },
183
- poll_ms: { type: 'number', description: 'Polling interval in milliseconds', default: 200 },
184
- stringify: { type: 'boolean', description: 'JSON stringify the result', default: true }
185
- },
186
- required: ['code']
187
- }
188
- }
189
- ]
190
- }));
191
-
192
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
193
- const { name, arguments: args } = request.params;
194
-
195
- try {
196
- switch (name) {
197
- case 'open_url': {
198
- const { url, new_tab = true } = args;
199
- try {
200
- new URL(url);
201
- } catch (error) {
202
- return {
203
- content: [{ type: 'text', text: `Error: url is not a valid url - ${error.message}` }],
204
- isError: true
205
- };
206
- }
207
- const script = new_tab
208
- ? `tell application "Google Chrome" to open location ${JSON.stringify(url)}`
209
- : `tell application "Google Chrome" to set URL of active tab of front window to ${JSON.stringify(url)}`;
210
-
211
- await this.executeAppleScript(script);
212
- return { content: [{ type: 'text', text: `Opened ${url} in Chrome` }] };
213
- }
214
-
215
- case 'get_current_tab': {
216
- const script = `
217
- tell application "Google Chrome"
218
- set currentTab to active tab of front window
219
- set tabInfo to {URL of currentTab, title of currentTab, id of currentTab}
220
- return tabInfo
221
- end tell
222
- `;
223
- const result = await this.executeAppleScript(script);
224
- const [url, title, id] = result.split(', ');
225
- return {
226
- content: [{
227
- type: 'text',
228
- text: JSON.stringify({ url, title, id: parseInt(id) }, null, 2)
229
- }]
230
- };
231
- }
232
-
233
- case 'list_tabs': {
234
- const script = `
235
- tell application "Google Chrome"
236
- set tabsList to {}
237
- repeat with w in windows
238
- repeat with t in tabs of w
239
- set end of tabsList to {id of t as string, URL of t, title of t}
240
- end repeat
241
- end repeat
242
- set AppleScript's text item delimiters to "|"
243
- set output to ""
244
- repeat with tabInfo in tabsList
245
- set output to output & (item 1 of tabInfo) & "," & (item 2 of tabInfo) & "," & (item 3 of tabInfo) & "|"
246
- end repeat
247
- return output
248
- end tell
249
- `;
250
- const result = await this.executeAppleScript(script);
251
- const tabs = result.split('|').filter(tab => tab).map(tab => {
252
- const [id, url, title] = tab.split(',');
253
- return { id: parseInt(id), url, title };
254
- });
255
- return {
256
- content: [{
257
- type: 'text',
258
- text: JSON.stringify(tabs, null, 2)
259
- }]
260
- };
261
- }
262
-
263
- case 'close_tab': {
264
- const { tab_id } = args;
265
- const script = `
266
- tell application "Google Chrome"
267
- repeat with w in windows
268
- repeat with t in tabs of w
269
- if (id of t as string) is "${tab_id}" then
270
- close t
271
- return "Tab closed"
272
- end if
273
- end repeat
274
- end repeat
275
- return "Tab not found"
276
- end tell
277
- `;
278
- const result = await this.executeAppleScript(script);
279
- return { content: [{ type: 'text', text: result }] };
280
- }
281
-
282
- case 'switch_to_tab': {
283
- const { tab_id } = args;
284
- const script = `
285
- tell application "Google Chrome"
286
- repeat with w in windows
287
- repeat with tabIndex from 1 to count of tabs of w
288
- set t to tab tabIndex of w
289
- if (id of t as string) is "${tab_id}" then
290
- set active tab index of w to tabIndex
291
- set index of w to 1
292
- activate
293
- return "Switched to tab"
294
- end if
295
- end repeat
296
- end repeat
297
- return "Tab not found"
298
- end tell
299
- `;
300
- const result = await this.executeAppleScript(script);
301
- return { content: [{ type: 'text', text: result }] };
302
- }
303
-
304
- case 'reload_tab': {
305
- const { tab_id } = args;
306
- const script = tab_id ? `
307
- tell application "Google Chrome"
308
- repeat with w in windows
309
- repeat with t in tabs of w
310
- if (id of t as string) is "${tab_id}" then
311
- reload t
312
- return "Tab reloaded"
313
- end if
314
- end repeat
315
- end repeat
316
- return "Tab not found"
317
- end tell
318
- ` : `
319
- tell application "Google Chrome"
320
- reload active tab of front window
321
- return "Tab reloaded"
322
- end tell
323
- `;
324
- const result = await this.executeAppleScript(script);
325
- return { content: [{ type: 'text', text: result }] };
326
- }
327
-
328
- case 'go_back': {
329
- const { tab_id } = args;
330
- const script = tab_id ? `
331
- tell application "Google Chrome"
332
- repeat with w in windows
333
- repeat with t in tabs of w
334
- if (id of t as string) is "${tab_id}" then
335
- go back t
336
- return "Navigated back"
337
- end if
338
- end repeat
339
- end repeat
340
- return "Tab not found"
341
- end tell
342
- ` : `
343
- tell application "Google Chrome"
344
- go back active tab of front window
345
- return "Navigated back"
346
- end tell
347
- `;
348
- const result = await this.executeAppleScript(script);
349
- return { content: [{ type: 'text', text: result }] };
350
- }
351
-
352
- case 'go_forward': {
353
- const { tab_id } = args;
354
- const script = tab_id ? `
355
- tell application "Google Chrome"
356
- repeat with w in windows
357
- repeat with t in tabs of w
358
- if (id of t as string) is "${tab_id}" then
359
- go forward t
360
- return "Navigated forward"
361
- end if
362
- end repeat
363
- end repeat
364
- return "Tab not found"
365
- end tell
366
- ` : `
367
- tell application "Google Chrome"
368
- go forward active tab of front window
369
- return "Navigated forward"
370
- end tell
371
- `;
372
- const result = await this.executeAppleScript(script);
373
- return { content: [{ type: 'text', text: result }] };
374
- }
375
-
376
- case 'execute_javascript': {
377
- const { code, tab_id } = args;
378
- // For AppleScript strings, we need to escape backslashes and double quotes
379
- const script = tab_id ? `
380
- tell application "Google Chrome"
381
- repeat with w in windows
382
- repeat with t in tabs of w
383
- if (id of t as string) is "${tab_id}" then
384
- set result to execute t javascript ${JSON.stringify(code)}
385
- return result
386
- end if
387
- end repeat
388
- end repeat
389
- return "Tab not found"
390
- end tell
391
- ` : `
392
- tell application "Google Chrome"
393
- execute active tab of front window javascript ${JSON.stringify(code)}
394
- end tell
395
- `;
396
- const result = await this.executeAppleScript(script);
397
- return { content: [{ type: 'text', text: result || 'JavaScript executed' }] };
398
- }
399
-
400
- case 'get_page_content': {
401
- const { tab_id } = args;
402
- const script = tab_id ? `
403
- tell application "Google Chrome"
404
- repeat with w in windows
405
- repeat with t in tabs of w
406
- if (id of t as string) is "${tab_id}" then
407
- set pageContent to execute t javascript "document.body.innerText"
408
- return pageContent
409
- end if
410
- end repeat
411
- end repeat
412
- return "Tab not found"
413
- end tell
414
- ` : `
415
- tell application "Google Chrome"
416
- execute active tab of front window javascript "document.body.innerText"
417
- end tell
418
- `;
419
- const result = await this.executeAppleScript(script);
420
- return { content: [{ type: 'text', text: result }] };
421
- }
422
-
423
- case 'execute_javascript_async': {
424
- const {
425
- code,
426
- tab_id,
427
- timeout_ms = 60000,
428
- poll_ms = 200,
429
- stringify = true,
430
- } = args;
431
-
432
- if (typeof code !== 'string' || !code.trim()) {
433
- return { content: [{ type: 'text', text: 'Error: code is required (string)' }] };
434
- }
435
-
436
- // Build the page-side bootstrap that returns a token and completes later
437
- // Note: we embed `code` as-is inside an async IIFE, so it can use `await`.
438
- const bootstrapJs = `
439
- (() => {
440
- try {
441
- window.__MCP_ASYNC_RESULTS = window.__MCP_ASYNC_RESULTS || {};
442
- const token = 'mcp_' + Date.now() + '_' + Math.random().toString(36).slice(2);
443
- (async () => {
444
- try {
445
- const __result__ = await (async () => { ${code} })();
446
- window.__MCP_ASYNC_RESULTS[token] = {
447
- status: 'fulfilled',
448
- value: ${stringify ? 'JSON.stringify(__result__)' : '__result__'}
449
- };
450
- } catch (e) {
451
- window.__MCP_ASYNC_RESULTS[token] = {
452
- status: 'rejected',
453
- error: String(e && e.message || e)
454
- };
455
- }
456
- })();
457
- return token;
458
- } catch (e) {
459
- return 'ERROR_BOOTSTRAP:' + String(e && e.message || e);
460
- }
461
- })();
462
- `.trim();
463
-
464
- // Escape for AppleScript execute javascript "..."
465
- const asQuote = (s) =>
466
- s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
467
-
468
- const jsBootEsc = asQuote(bootstrapJs);
469
- const pollSeconds = (Math.max(50, Number(poll_ms)) / 1000).toFixed(3); // >=50ms, to real
470
- const timeoutMs = Math.max(1000, Number(timeout_ms)); // >=1s
471
-
472
- const script = tab_id ? `
473
- set _timeoutMs to ${timeoutMs}
474
- set _pollSec to ${pollSeconds} as real
475
- tell application "Google Chrome"
476
- set _token to ""
477
- repeat with w in windows
478
- repeat with t in tabs of w
479
- if (id of t as string) is "${tab_id}" then
480
- set _token to execute t javascript "${jsBootEsc}"
481
- exit repeat
482
- end if
483
- end repeat
484
- if _token is not "" then exit repeat
485
- end repeat
486
- if _token is "" then return "Tab not found"
487
-
488
- set _t0 to (current date)
489
- repeat
490
- set _status to execute active tab of front window javascript "(() => { var r = window.__MCP_ASYNC_RESULTS && window.__MCP_ASYNC_RESULTS['\" & _token & \"']; return r ? r.status : 'pending'; })()"
491
- if _status is "fulfilled" then
492
- set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
493
- execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
494
- return _val
495
- else if _status is "rejected" then
496
- set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
497
- execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
498
- return "ERROR:" & _err
499
- end if
500
-
501
- set _elapsedMs to ((current date) - _t0) * 1000
502
- if _elapsedMs > _timeoutMs then
503
- execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
504
- return "TIMEOUT"
505
- end if
506
- delay _pollSec
507
- end repeat
508
- end tell
509
- ` : `
510
- set _timeoutMs to ${timeoutMs}
511
- set _pollSec to ${pollSeconds} as real
512
- tell application "Google Chrome"
513
- set _token to execute active tab of front window javascript "${jsBootEsc}"
514
- if _token starts with "ERROR_BOOTSTRAP:" then return _token
515
- set _t0 to (current date)
516
- repeat
517
- set _status to execute active tab of front window javascript "(() => { var r = window.__MCP_ASYNC_RESULTS && window.__MCP_ASYNC_RESULTS['\" & _token & \"']; return r ? r.status : 'pending'; })()"
518
- if _status is "fulfilled" then
519
- set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
520
- execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
521
- return _val
522
- else if _status is "rejected" then
523
- set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
524
- execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
525
- return "ERROR:" & _err
526
- end if
527
-
528
- set _elapsedMs to ((current date) - _t0) * 1000
529
- if _elapsedMs > _timeoutMs then
530
- execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
531
- return "TIMEOUT"
532
- end if
533
- delay _pollSec
534
- end repeat
535
- end tell
536
- `;
537
-
538
- const result = await this.executeAppleScript(script);
539
-
540
- // Normalize response: if we JSON-stringified in page, parse here.
541
- if (typeof result === 'string' && result.startsWith('ERROR:')) {
542
- return { content: [{ type: 'text', text: result }] };
543
- }
544
- if (stringify && typeof result === 'string') {
545
- try {
546
- const parsed = JSON.parse(result);
547
- return { content: [{ type: 'text', text: typeof parsed === 'string' ? parsed : JSON.stringify(parsed) }] };
548
- } catch {
549
- // Not JSON (e.g., primitive string); return as-is
550
- return { content: [{ type: 'text', text: result }] };
551
- }
552
- }
553
- return { content: [{ type: 'text', text: result ?? '' }] };
554
- }
555
-
556
- default:
557
- throw new Error(`Unknown tool: ${name}`);
558
- }
559
- } catch (error) {
560
- return {
561
- content: [{ type: 'text', text: `Error: ${error.message}` }],
562
- isError: true
563
- };
564
- }
565
- });
566
- }
567
-
568
- async run() {
569
- const transport = new StdioServerTransport();
570
- await this.server.connect(transport);
571
- console.error('Chrome Control MCP server running on stdio');
572
- }
573
- }
574
-
575
- const server = new ChromeControlServer();
576
- server.run().catch(console.error);