#
tokens: 80861/50000 1/29 files (page 3/3)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 3 of 3. Use http://codebase.md/zabaglione/mcp-server-unity?lines=true&page={x} to view the full context.

# Directory Structure

```
├── .claude
│   └── settings.local.json
├── .gitignore
├── build-bundle.js
├── build-final-dxt.sh
├── BUILD.md
├── CHANGELOG.md
├── CLAUDE.md
├── CONTRIBUTING.md
├── create-bundled-dxt.sh
├── docs
│   ├── API.md
│   └── ARCHITECTURE.md
├── generate-embedded-scripts.cjs
├── LICENSE
├── manifest.json
├── package-lock.json
├── package.json
├── README-ja.md
├── README.md
├── src
│   ├── adapters
│   │   └── unity-http-adapter.ts
│   ├── embedded-scripts.ts
│   ├── services
│   │   └── unity-bridge-deploy-service.ts
│   ├── simple-index.ts
│   ├── tools
│   │   └── unity-mcp-tools.ts
│   └── unity-scripts
│       ├── UnityHttpServer.cs
│       └── UnityMCPServerWindow.cs
├── TECHNICAL.md
├── tests
│   ├── integration
│   │   └── simple-integration.test.ts
│   ├── unit
│   │   ├── adapters
│   │   │   └── unity-http-adapter.test.ts
│   │   ├── templates
│   │   │   └── shaders
│   │   │       └── shader-templates.test.ts
│   │   └── tools
│   │       └── unity-mcp-tools.test.ts
│   └── unity
│       └── UnityHttpServerTests.cs
├── tsconfig.json
├── tsconfig.test.json
├── unity-mcp-server.bundle.js
└── vitest.config.ts
```

# Files

--------------------------------------------------------------------------------
/unity-mcp-server.bundle.js:
--------------------------------------------------------------------------------

```javascript
   1 | #!/usr/bin/env node
   2 | var __defProp = Object.defineProperty;
   3 | var __export = (target, all) => {
   4 |   for (var name in all)
   5 |     __defProp(target, name, { get: all[name], enumerable: true });
   6 | };
   7 | 
   8 | // node_modules/zod/dist/esm/v3/external.js
   9 | var external_exports = {};
  10 | __export(external_exports, {
  11 |   BRAND: () => BRAND,
  12 |   DIRTY: () => DIRTY,
  13 |   EMPTY_PATH: () => EMPTY_PATH,
  14 |   INVALID: () => INVALID,
  15 |   NEVER: () => NEVER,
  16 |   OK: () => OK,
  17 |   ParseStatus: () => ParseStatus,
  18 |   Schema: () => ZodType,
  19 |   ZodAny: () => ZodAny,
  20 |   ZodArray: () => ZodArray,
  21 |   ZodBigInt: () => ZodBigInt,
  22 |   ZodBoolean: () => ZodBoolean,
  23 |   ZodBranded: () => ZodBranded,
  24 |   ZodCatch: () => ZodCatch,
  25 |   ZodDate: () => ZodDate,
  26 |   ZodDefault: () => ZodDefault,
  27 |   ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  28 |   ZodEffects: () => ZodEffects,
  29 |   ZodEnum: () => ZodEnum,
  30 |   ZodError: () => ZodError,
  31 |   ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  32 |   ZodFunction: () => ZodFunction,
  33 |   ZodIntersection: () => ZodIntersection,
  34 |   ZodIssueCode: () => ZodIssueCode,
  35 |   ZodLazy: () => ZodLazy,
  36 |   ZodLiteral: () => ZodLiteral,
  37 |   ZodMap: () => ZodMap,
  38 |   ZodNaN: () => ZodNaN,
  39 |   ZodNativeEnum: () => ZodNativeEnum,
  40 |   ZodNever: () => ZodNever,
  41 |   ZodNull: () => ZodNull,
  42 |   ZodNullable: () => ZodNullable,
  43 |   ZodNumber: () => ZodNumber,
  44 |   ZodObject: () => ZodObject,
  45 |   ZodOptional: () => ZodOptional,
  46 |   ZodParsedType: () => ZodParsedType,
  47 |   ZodPipeline: () => ZodPipeline,
  48 |   ZodPromise: () => ZodPromise,
  49 |   ZodReadonly: () => ZodReadonly,
  50 |   ZodRecord: () => ZodRecord,
  51 |   ZodSchema: () => ZodType,
  52 |   ZodSet: () => ZodSet,
  53 |   ZodString: () => ZodString,
  54 |   ZodSymbol: () => ZodSymbol,
  55 |   ZodTransformer: () => ZodEffects,
  56 |   ZodTuple: () => ZodTuple,
  57 |   ZodType: () => ZodType,
  58 |   ZodUndefined: () => ZodUndefined,
  59 |   ZodUnion: () => ZodUnion,
  60 |   ZodUnknown: () => ZodUnknown,
  61 |   ZodVoid: () => ZodVoid,
  62 |   addIssueToContext: () => addIssueToContext,
  63 |   any: () => anyType,
  64 |   array: () => arrayType,
  65 |   bigint: () => bigIntType,
  66 |   boolean: () => booleanType,
  67 |   coerce: () => coerce,
  68 |   custom: () => custom,
  69 |   date: () => dateType,
  70 |   datetimeRegex: () => datetimeRegex,
  71 |   defaultErrorMap: () => en_default,
  72 |   discriminatedUnion: () => discriminatedUnionType,
  73 |   effect: () => effectsType,
  74 |   enum: () => enumType,
  75 |   function: () => functionType,
  76 |   getErrorMap: () => getErrorMap,
  77 |   getParsedType: () => getParsedType,
  78 |   instanceof: () => instanceOfType,
  79 |   intersection: () => intersectionType,
  80 |   isAborted: () => isAborted,
  81 |   isAsync: () => isAsync,
  82 |   isDirty: () => isDirty,
  83 |   isValid: () => isValid,
  84 |   late: () => late,
  85 |   lazy: () => lazyType,
  86 |   literal: () => literalType,
  87 |   makeIssue: () => makeIssue,
  88 |   map: () => mapType,
  89 |   nan: () => nanType,
  90 |   nativeEnum: () => nativeEnumType,
  91 |   never: () => neverType,
  92 |   null: () => nullType,
  93 |   nullable: () => nullableType,
  94 |   number: () => numberType,
  95 |   object: () => objectType,
  96 |   objectUtil: () => objectUtil,
  97 |   oboolean: () => oboolean,
  98 |   onumber: () => onumber,
  99 |   optional: () => optionalType,
 100 |   ostring: () => ostring,
 101 |   pipeline: () => pipelineType,
 102 |   preprocess: () => preprocessType,
 103 |   promise: () => promiseType,
 104 |   quotelessJson: () => quotelessJson,
 105 |   record: () => recordType,
 106 |   set: () => setType,
 107 |   setErrorMap: () => setErrorMap,
 108 |   strictObject: () => strictObjectType,
 109 |   string: () => stringType,
 110 |   symbol: () => symbolType,
 111 |   transformer: () => effectsType,
 112 |   tuple: () => tupleType,
 113 |   undefined: () => undefinedType,
 114 |   union: () => unionType,
 115 |   unknown: () => unknownType,
 116 |   util: () => util,
 117 |   void: () => voidType
 118 | });
 119 | 
 120 | // node_modules/zod/dist/esm/v3/helpers/util.js
 121 | var util;
 122 | (function(util2) {
 123 |   util2.assertEqual = (_) => {
 124 |   };
 125 |   function assertIs(_arg) {
 126 |   }
 127 |   util2.assertIs = assertIs;
 128 |   function assertNever(_x) {
 129 |     throw new Error();
 130 |   }
 131 |   util2.assertNever = assertNever;
 132 |   util2.arrayToEnum = (items) => {
 133 |     const obj = {};
 134 |     for (const item of items) {
 135 |       obj[item] = item;
 136 |     }
 137 |     return obj;
 138 |   };
 139 |   util2.getValidEnumValues = (obj) => {
 140 |     const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
 141 |     const filtered = {};
 142 |     for (const k of validKeys) {
 143 |       filtered[k] = obj[k];
 144 |     }
 145 |     return util2.objectValues(filtered);
 146 |   };
 147 |   util2.objectValues = (obj) => {
 148 |     return util2.objectKeys(obj).map(function(e) {
 149 |       return obj[e];
 150 |     });
 151 |   };
 152 |   util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
 153 |     const keys = [];
 154 |     for (const key in object) {
 155 |       if (Object.prototype.hasOwnProperty.call(object, key)) {
 156 |         keys.push(key);
 157 |       }
 158 |     }
 159 |     return keys;
 160 |   };
 161 |   util2.find = (arr, checker) => {
 162 |     for (const item of arr) {
 163 |       if (checker(item))
 164 |         return item;
 165 |     }
 166 |     return void 0;
 167 |   };
 168 |   util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
 169 |   function joinValues(array, separator = " | ") {
 170 |     return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
 171 |   }
 172 |   util2.joinValues = joinValues;
 173 |   util2.jsonStringifyReplacer = (_, value) => {
 174 |     if (typeof value === "bigint") {
 175 |       return value.toString();
 176 |     }
 177 |     return value;
 178 |   };
 179 | })(util || (util = {}));
 180 | var objectUtil;
 181 | (function(objectUtil2) {
 182 |   objectUtil2.mergeShapes = (first, second) => {
 183 |     return {
 184 |       ...first,
 185 |       ...second
 186 |       // second overwrites first
 187 |     };
 188 |   };
 189 | })(objectUtil || (objectUtil = {}));
 190 | var ZodParsedType = util.arrayToEnum([
 191 |   "string",
 192 |   "nan",
 193 |   "number",
 194 |   "integer",
 195 |   "float",
 196 |   "boolean",
 197 |   "date",
 198 |   "bigint",
 199 |   "symbol",
 200 |   "function",
 201 |   "undefined",
 202 |   "null",
 203 |   "array",
 204 |   "object",
 205 |   "unknown",
 206 |   "promise",
 207 |   "void",
 208 |   "never",
 209 |   "map",
 210 |   "set"
 211 | ]);
 212 | var getParsedType = (data) => {
 213 |   const t = typeof data;
 214 |   switch (t) {
 215 |     case "undefined":
 216 |       return ZodParsedType.undefined;
 217 |     case "string":
 218 |       return ZodParsedType.string;
 219 |     case "number":
 220 |       return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
 221 |     case "boolean":
 222 |       return ZodParsedType.boolean;
 223 |     case "function":
 224 |       return ZodParsedType.function;
 225 |     case "bigint":
 226 |       return ZodParsedType.bigint;
 227 |     case "symbol":
 228 |       return ZodParsedType.symbol;
 229 |     case "object":
 230 |       if (Array.isArray(data)) {
 231 |         return ZodParsedType.array;
 232 |       }
 233 |       if (data === null) {
 234 |         return ZodParsedType.null;
 235 |       }
 236 |       if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
 237 |         return ZodParsedType.promise;
 238 |       }
 239 |       if (typeof Map !== "undefined" && data instanceof Map) {
 240 |         return ZodParsedType.map;
 241 |       }
 242 |       if (typeof Set !== "undefined" && data instanceof Set) {
 243 |         return ZodParsedType.set;
 244 |       }
 245 |       if (typeof Date !== "undefined" && data instanceof Date) {
 246 |         return ZodParsedType.date;
 247 |       }
 248 |       return ZodParsedType.object;
 249 |     default:
 250 |       return ZodParsedType.unknown;
 251 |   }
 252 | };
 253 | 
 254 | // node_modules/zod/dist/esm/v3/ZodError.js
 255 | var ZodIssueCode = util.arrayToEnum([
 256 |   "invalid_type",
 257 |   "invalid_literal",
 258 |   "custom",
 259 |   "invalid_union",
 260 |   "invalid_union_discriminator",
 261 |   "invalid_enum_value",
 262 |   "unrecognized_keys",
 263 |   "invalid_arguments",
 264 |   "invalid_return_type",
 265 |   "invalid_date",
 266 |   "invalid_string",
 267 |   "too_small",
 268 |   "too_big",
 269 |   "invalid_intersection_types",
 270 |   "not_multiple_of",
 271 |   "not_finite"
 272 | ]);
 273 | var quotelessJson = (obj) => {
 274 |   const json = JSON.stringify(obj, null, 2);
 275 |   return json.replace(/"([^"]+)":/g, "$1:");
 276 | };
 277 | var ZodError = class _ZodError extends Error {
 278 |   get errors() {
 279 |     return this.issues;
 280 |   }
 281 |   constructor(issues) {
 282 |     super();
 283 |     this.issues = [];
 284 |     this.addIssue = (sub) => {
 285 |       this.issues = [...this.issues, sub];
 286 |     };
 287 |     this.addIssues = (subs = []) => {
 288 |       this.issues = [...this.issues, ...subs];
 289 |     };
 290 |     const actualProto = new.target.prototype;
 291 |     if (Object.setPrototypeOf) {
 292 |       Object.setPrototypeOf(this, actualProto);
 293 |     } else {
 294 |       this.__proto__ = actualProto;
 295 |     }
 296 |     this.name = "ZodError";
 297 |     this.issues = issues;
 298 |   }
 299 |   format(_mapper) {
 300 |     const mapper = _mapper || function(issue) {
 301 |       return issue.message;
 302 |     };
 303 |     const fieldErrors = { _errors: [] };
 304 |     const processError = (error) => {
 305 |       for (const issue of error.issues) {
 306 |         if (issue.code === "invalid_union") {
 307 |           issue.unionErrors.map(processError);
 308 |         } else if (issue.code === "invalid_return_type") {
 309 |           processError(issue.returnTypeError);
 310 |         } else if (issue.code === "invalid_arguments") {
 311 |           processError(issue.argumentsError);
 312 |         } else if (issue.path.length === 0) {
 313 |           fieldErrors._errors.push(mapper(issue));
 314 |         } else {
 315 |           let curr = fieldErrors;
 316 |           let i = 0;
 317 |           while (i < issue.path.length) {
 318 |             const el = issue.path[i];
 319 |             const terminal = i === issue.path.length - 1;
 320 |             if (!terminal) {
 321 |               curr[el] = curr[el] || { _errors: [] };
 322 |             } else {
 323 |               curr[el] = curr[el] || { _errors: [] };
 324 |               curr[el]._errors.push(mapper(issue));
 325 |             }
 326 |             curr = curr[el];
 327 |             i++;
 328 |           }
 329 |         }
 330 |       }
 331 |     };
 332 |     processError(this);
 333 |     return fieldErrors;
 334 |   }
 335 |   static assert(value) {
 336 |     if (!(value instanceof _ZodError)) {
 337 |       throw new Error(`Not a ZodError: ${value}`);
 338 |     }
 339 |   }
 340 |   toString() {
 341 |     return this.message;
 342 |   }
 343 |   get message() {
 344 |     return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
 345 |   }
 346 |   get isEmpty() {
 347 |     return this.issues.length === 0;
 348 |   }
 349 |   flatten(mapper = (issue) => issue.message) {
 350 |     const fieldErrors = {};
 351 |     const formErrors = [];
 352 |     for (const sub of this.issues) {
 353 |       if (sub.path.length > 0) {
 354 |         fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
 355 |         fieldErrors[sub.path[0]].push(mapper(sub));
 356 |       } else {
 357 |         formErrors.push(mapper(sub));
 358 |       }
 359 |     }
 360 |     return { formErrors, fieldErrors };
 361 |   }
 362 |   get formErrors() {
 363 |     return this.flatten();
 364 |   }
 365 | };
 366 | ZodError.create = (issues) => {
 367 |   const error = new ZodError(issues);
 368 |   return error;
 369 | };
 370 | 
 371 | // node_modules/zod/dist/esm/v3/locales/en.js
 372 | var errorMap = (issue, _ctx) => {
 373 |   let message;
 374 |   switch (issue.code) {
 375 |     case ZodIssueCode.invalid_type:
 376 |       if (issue.received === ZodParsedType.undefined) {
 377 |         message = "Required";
 378 |       } else {
 379 |         message = `Expected ${issue.expected}, received ${issue.received}`;
 380 |       }
 381 |       break;
 382 |     case ZodIssueCode.invalid_literal:
 383 |       message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
 384 |       break;
 385 |     case ZodIssueCode.unrecognized_keys:
 386 |       message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
 387 |       break;
 388 |     case ZodIssueCode.invalid_union:
 389 |       message = `Invalid input`;
 390 |       break;
 391 |     case ZodIssueCode.invalid_union_discriminator:
 392 |       message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
 393 |       break;
 394 |     case ZodIssueCode.invalid_enum_value:
 395 |       message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
 396 |       break;
 397 |     case ZodIssueCode.invalid_arguments:
 398 |       message = `Invalid function arguments`;
 399 |       break;
 400 |     case ZodIssueCode.invalid_return_type:
 401 |       message = `Invalid function return type`;
 402 |       break;
 403 |     case ZodIssueCode.invalid_date:
 404 |       message = `Invalid date`;
 405 |       break;
 406 |     case ZodIssueCode.invalid_string:
 407 |       if (typeof issue.validation === "object") {
 408 |         if ("includes" in issue.validation) {
 409 |           message = `Invalid input: must include "${issue.validation.includes}"`;
 410 |           if (typeof issue.validation.position === "number") {
 411 |             message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
 412 |           }
 413 |         } else if ("startsWith" in issue.validation) {
 414 |           message = `Invalid input: must start with "${issue.validation.startsWith}"`;
 415 |         } else if ("endsWith" in issue.validation) {
 416 |           message = `Invalid input: must end with "${issue.validation.endsWith}"`;
 417 |         } else {
 418 |           util.assertNever(issue.validation);
 419 |         }
 420 |       } else if (issue.validation !== "regex") {
 421 |         message = `Invalid ${issue.validation}`;
 422 |       } else {
 423 |         message = "Invalid";
 424 |       }
 425 |       break;
 426 |     case ZodIssueCode.too_small:
 427 |       if (issue.type === "array")
 428 |         message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
 429 |       else if (issue.type === "string")
 430 |         message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
 431 |       else if (issue.type === "number")
 432 |         message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
 433 |       else if (issue.type === "date")
 434 |         message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
 435 |       else
 436 |         message = "Invalid input";
 437 |       break;
 438 |     case ZodIssueCode.too_big:
 439 |       if (issue.type === "array")
 440 |         message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
 441 |       else if (issue.type === "string")
 442 |         message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
 443 |       else if (issue.type === "number")
 444 |         message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
 445 |       else if (issue.type === "bigint")
 446 |         message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
 447 |       else if (issue.type === "date")
 448 |         message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
 449 |       else
 450 |         message = "Invalid input";
 451 |       break;
 452 |     case ZodIssueCode.custom:
 453 |       message = `Invalid input`;
 454 |       break;
 455 |     case ZodIssueCode.invalid_intersection_types:
 456 |       message = `Intersection results could not be merged`;
 457 |       break;
 458 |     case ZodIssueCode.not_multiple_of:
 459 |       message = `Number must be a multiple of ${issue.multipleOf}`;
 460 |       break;
 461 |     case ZodIssueCode.not_finite:
 462 |       message = "Number must be finite";
 463 |       break;
 464 |     default:
 465 |       message = _ctx.defaultError;
 466 |       util.assertNever(issue);
 467 |   }
 468 |   return { message };
 469 | };
 470 | var en_default = errorMap;
 471 | 
 472 | // node_modules/zod/dist/esm/v3/errors.js
 473 | var overrideErrorMap = en_default;
 474 | function setErrorMap(map) {
 475 |   overrideErrorMap = map;
 476 | }
 477 | function getErrorMap() {
 478 |   return overrideErrorMap;
 479 | }
 480 | 
 481 | // node_modules/zod/dist/esm/v3/helpers/parseUtil.js
 482 | var makeIssue = (params) => {
 483 |   const { data, path: path3, errorMaps, issueData } = params;
 484 |   const fullPath = [...path3, ...issueData.path || []];
 485 |   const fullIssue = {
 486 |     ...issueData,
 487 |     path: fullPath
 488 |   };
 489 |   if (issueData.message !== void 0) {
 490 |     return {
 491 |       ...issueData,
 492 |       path: fullPath,
 493 |       message: issueData.message
 494 |     };
 495 |   }
 496 |   let errorMessage = "";
 497 |   const maps = errorMaps.filter((m) => !!m).slice().reverse();
 498 |   for (const map of maps) {
 499 |     errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
 500 |   }
 501 |   return {
 502 |     ...issueData,
 503 |     path: fullPath,
 504 |     message: errorMessage
 505 |   };
 506 | };
 507 | var EMPTY_PATH = [];
 508 | function addIssueToContext(ctx, issueData) {
 509 |   const overrideMap = getErrorMap();
 510 |   const issue = makeIssue({
 511 |     issueData,
 512 |     data: ctx.data,
 513 |     path: ctx.path,
 514 |     errorMaps: [
 515 |       ctx.common.contextualErrorMap,
 516 |       // contextual error map is first priority
 517 |       ctx.schemaErrorMap,
 518 |       // then schema-bound map if available
 519 |       overrideMap,
 520 |       // then global override map
 521 |       overrideMap === en_default ? void 0 : en_default
 522 |       // then global default map
 523 |     ].filter((x) => !!x)
 524 |   });
 525 |   ctx.common.issues.push(issue);
 526 | }
 527 | var ParseStatus = class _ParseStatus {
 528 |   constructor() {
 529 |     this.value = "valid";
 530 |   }
 531 |   dirty() {
 532 |     if (this.value === "valid")
 533 |       this.value = "dirty";
 534 |   }
 535 |   abort() {
 536 |     if (this.value !== "aborted")
 537 |       this.value = "aborted";
 538 |   }
 539 |   static mergeArray(status, results) {
 540 |     const arrayValue = [];
 541 |     for (const s of results) {
 542 |       if (s.status === "aborted")
 543 |         return INVALID;
 544 |       if (s.status === "dirty")
 545 |         status.dirty();
 546 |       arrayValue.push(s.value);
 547 |     }
 548 |     return { status: status.value, value: arrayValue };
 549 |   }
 550 |   static async mergeObjectAsync(status, pairs) {
 551 |     const syncPairs = [];
 552 |     for (const pair of pairs) {
 553 |       const key = await pair.key;
 554 |       const value = await pair.value;
 555 |       syncPairs.push({
 556 |         key,
 557 |         value
 558 |       });
 559 |     }
 560 |     return _ParseStatus.mergeObjectSync(status, syncPairs);
 561 |   }
 562 |   static mergeObjectSync(status, pairs) {
 563 |     const finalObject = {};
 564 |     for (const pair of pairs) {
 565 |       const { key, value } = pair;
 566 |       if (key.status === "aborted")
 567 |         return INVALID;
 568 |       if (value.status === "aborted")
 569 |         return INVALID;
 570 |       if (key.status === "dirty")
 571 |         status.dirty();
 572 |       if (value.status === "dirty")
 573 |         status.dirty();
 574 |       if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
 575 |         finalObject[key.value] = value.value;
 576 |       }
 577 |     }
 578 |     return { status: status.value, value: finalObject };
 579 |   }
 580 | };
 581 | var INVALID = Object.freeze({
 582 |   status: "aborted"
 583 | });
 584 | var DIRTY = (value) => ({ status: "dirty", value });
 585 | var OK = (value) => ({ status: "valid", value });
 586 | var isAborted = (x) => x.status === "aborted";
 587 | var isDirty = (x) => x.status === "dirty";
 588 | var isValid = (x) => x.status === "valid";
 589 | var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
 590 | 
 591 | // node_modules/zod/dist/esm/v3/helpers/errorUtil.js
 592 | var errorUtil;
 593 | (function(errorUtil2) {
 594 |   errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
 595 |   errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
 596 | })(errorUtil || (errorUtil = {}));
 597 | 
 598 | // node_modules/zod/dist/esm/v3/types.js
 599 | var ParseInputLazyPath = class {
 600 |   constructor(parent, value, path3, key) {
 601 |     this._cachedPath = [];
 602 |     this.parent = parent;
 603 |     this.data = value;
 604 |     this._path = path3;
 605 |     this._key = key;
 606 |   }
 607 |   get path() {
 608 |     if (!this._cachedPath.length) {
 609 |       if (Array.isArray(this._key)) {
 610 |         this._cachedPath.push(...this._path, ...this._key);
 611 |       } else {
 612 |         this._cachedPath.push(...this._path, this._key);
 613 |       }
 614 |     }
 615 |     return this._cachedPath;
 616 |   }
 617 | };
 618 | var handleResult = (ctx, result) => {
 619 |   if (isValid(result)) {
 620 |     return { success: true, data: result.value };
 621 |   } else {
 622 |     if (!ctx.common.issues.length) {
 623 |       throw new Error("Validation failed but no issues detected.");
 624 |     }
 625 |     return {
 626 |       success: false,
 627 |       get error() {
 628 |         if (this._error)
 629 |           return this._error;
 630 |         const error = new ZodError(ctx.common.issues);
 631 |         this._error = error;
 632 |         return this._error;
 633 |       }
 634 |     };
 635 |   }
 636 | };
 637 | function processCreateParams(params) {
 638 |   if (!params)
 639 |     return {};
 640 |   const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
 641 |   if (errorMap2 && (invalid_type_error || required_error)) {
 642 |     throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
 643 |   }
 644 |   if (errorMap2)
 645 |     return { errorMap: errorMap2, description };
 646 |   const customMap = (iss, ctx) => {
 647 |     const { message } = params;
 648 |     if (iss.code === "invalid_enum_value") {
 649 |       return { message: message ?? ctx.defaultError };
 650 |     }
 651 |     if (typeof ctx.data === "undefined") {
 652 |       return { message: message ?? required_error ?? ctx.defaultError };
 653 |     }
 654 |     if (iss.code !== "invalid_type")
 655 |       return { message: ctx.defaultError };
 656 |     return { message: message ?? invalid_type_error ?? ctx.defaultError };
 657 |   };
 658 |   return { errorMap: customMap, description };
 659 | }
 660 | var ZodType = class {
 661 |   get description() {
 662 |     return this._def.description;
 663 |   }
 664 |   _getType(input) {
 665 |     return getParsedType(input.data);
 666 |   }
 667 |   _getOrReturnCtx(input, ctx) {
 668 |     return ctx || {
 669 |       common: input.parent.common,
 670 |       data: input.data,
 671 |       parsedType: getParsedType(input.data),
 672 |       schemaErrorMap: this._def.errorMap,
 673 |       path: input.path,
 674 |       parent: input.parent
 675 |     };
 676 |   }
 677 |   _processInputParams(input) {
 678 |     return {
 679 |       status: new ParseStatus(),
 680 |       ctx: {
 681 |         common: input.parent.common,
 682 |         data: input.data,
 683 |         parsedType: getParsedType(input.data),
 684 |         schemaErrorMap: this._def.errorMap,
 685 |         path: input.path,
 686 |         parent: input.parent
 687 |       }
 688 |     };
 689 |   }
 690 |   _parseSync(input) {
 691 |     const result = this._parse(input);
 692 |     if (isAsync(result)) {
 693 |       throw new Error("Synchronous parse encountered promise.");
 694 |     }
 695 |     return result;
 696 |   }
 697 |   _parseAsync(input) {
 698 |     const result = this._parse(input);
 699 |     return Promise.resolve(result);
 700 |   }
 701 |   parse(data, params) {
 702 |     const result = this.safeParse(data, params);
 703 |     if (result.success)
 704 |       return result.data;
 705 |     throw result.error;
 706 |   }
 707 |   safeParse(data, params) {
 708 |     const ctx = {
 709 |       common: {
 710 |         issues: [],
 711 |         async: params?.async ?? false,
 712 |         contextualErrorMap: params?.errorMap
 713 |       },
 714 |       path: params?.path || [],
 715 |       schemaErrorMap: this._def.errorMap,
 716 |       parent: null,
 717 |       data,
 718 |       parsedType: getParsedType(data)
 719 |     };
 720 |     const result = this._parseSync({ data, path: ctx.path, parent: ctx });
 721 |     return handleResult(ctx, result);
 722 |   }
 723 |   "~validate"(data) {
 724 |     const ctx = {
 725 |       common: {
 726 |         issues: [],
 727 |         async: !!this["~standard"].async
 728 |       },
 729 |       path: [],
 730 |       schemaErrorMap: this._def.errorMap,
 731 |       parent: null,
 732 |       data,
 733 |       parsedType: getParsedType(data)
 734 |     };
 735 |     if (!this["~standard"].async) {
 736 |       try {
 737 |         const result = this._parseSync({ data, path: [], parent: ctx });
 738 |         return isValid(result) ? {
 739 |           value: result.value
 740 |         } : {
 741 |           issues: ctx.common.issues
 742 |         };
 743 |       } catch (err) {
 744 |         if (err?.message?.toLowerCase()?.includes("encountered")) {
 745 |           this["~standard"].async = true;
 746 |         }
 747 |         ctx.common = {
 748 |           issues: [],
 749 |           async: true
 750 |         };
 751 |       }
 752 |     }
 753 |     return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
 754 |       value: result.value
 755 |     } : {
 756 |       issues: ctx.common.issues
 757 |     });
 758 |   }
 759 |   async parseAsync(data, params) {
 760 |     const result = await this.safeParseAsync(data, params);
 761 |     if (result.success)
 762 |       return result.data;
 763 |     throw result.error;
 764 |   }
 765 |   async safeParseAsync(data, params) {
 766 |     const ctx = {
 767 |       common: {
 768 |         issues: [],
 769 |         contextualErrorMap: params?.errorMap,
 770 |         async: true
 771 |       },
 772 |       path: params?.path || [],
 773 |       schemaErrorMap: this._def.errorMap,
 774 |       parent: null,
 775 |       data,
 776 |       parsedType: getParsedType(data)
 777 |     };
 778 |     const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
 779 |     const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
 780 |     return handleResult(ctx, result);
 781 |   }
 782 |   refine(check, message) {
 783 |     const getIssueProperties = (val) => {
 784 |       if (typeof message === "string" || typeof message === "undefined") {
 785 |         return { message };
 786 |       } else if (typeof message === "function") {
 787 |         return message(val);
 788 |       } else {
 789 |         return message;
 790 |       }
 791 |     };
 792 |     return this._refinement((val, ctx) => {
 793 |       const result = check(val);
 794 |       const setError = () => ctx.addIssue({
 795 |         code: ZodIssueCode.custom,
 796 |         ...getIssueProperties(val)
 797 |       });
 798 |       if (typeof Promise !== "undefined" && result instanceof Promise) {
 799 |         return result.then((data) => {
 800 |           if (!data) {
 801 |             setError();
 802 |             return false;
 803 |           } else {
 804 |             return true;
 805 |           }
 806 |         });
 807 |       }
 808 |       if (!result) {
 809 |         setError();
 810 |         return false;
 811 |       } else {
 812 |         return true;
 813 |       }
 814 |     });
 815 |   }
 816 |   refinement(check, refinementData) {
 817 |     return this._refinement((val, ctx) => {
 818 |       if (!check(val)) {
 819 |         ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
 820 |         return false;
 821 |       } else {
 822 |         return true;
 823 |       }
 824 |     });
 825 |   }
 826 |   _refinement(refinement) {
 827 |     return new ZodEffects({
 828 |       schema: this,
 829 |       typeName: ZodFirstPartyTypeKind.ZodEffects,
 830 |       effect: { type: "refinement", refinement }
 831 |     });
 832 |   }
 833 |   superRefine(refinement) {
 834 |     return this._refinement(refinement);
 835 |   }
 836 |   constructor(def) {
 837 |     this.spa = this.safeParseAsync;
 838 |     this._def = def;
 839 |     this.parse = this.parse.bind(this);
 840 |     this.safeParse = this.safeParse.bind(this);
 841 |     this.parseAsync = this.parseAsync.bind(this);
 842 |     this.safeParseAsync = this.safeParseAsync.bind(this);
 843 |     this.spa = this.spa.bind(this);
 844 |     this.refine = this.refine.bind(this);
 845 |     this.refinement = this.refinement.bind(this);
 846 |     this.superRefine = this.superRefine.bind(this);
 847 |     this.optional = this.optional.bind(this);
 848 |     this.nullable = this.nullable.bind(this);
 849 |     this.nullish = this.nullish.bind(this);
 850 |     this.array = this.array.bind(this);
 851 |     this.promise = this.promise.bind(this);
 852 |     this.or = this.or.bind(this);
 853 |     this.and = this.and.bind(this);
 854 |     this.transform = this.transform.bind(this);
 855 |     this.brand = this.brand.bind(this);
 856 |     this.default = this.default.bind(this);
 857 |     this.catch = this.catch.bind(this);
 858 |     this.describe = this.describe.bind(this);
 859 |     this.pipe = this.pipe.bind(this);
 860 |     this.readonly = this.readonly.bind(this);
 861 |     this.isNullable = this.isNullable.bind(this);
 862 |     this.isOptional = this.isOptional.bind(this);
 863 |     this["~standard"] = {
 864 |       version: 1,
 865 |       vendor: "zod",
 866 |       validate: (data) => this["~validate"](data)
 867 |     };
 868 |   }
 869 |   optional() {
 870 |     return ZodOptional.create(this, this._def);
 871 |   }
 872 |   nullable() {
 873 |     return ZodNullable.create(this, this._def);
 874 |   }
 875 |   nullish() {
 876 |     return this.nullable().optional();
 877 |   }
 878 |   array() {
 879 |     return ZodArray.create(this);
 880 |   }
 881 |   promise() {
 882 |     return ZodPromise.create(this, this._def);
 883 |   }
 884 |   or(option) {
 885 |     return ZodUnion.create([this, option], this._def);
 886 |   }
 887 |   and(incoming) {
 888 |     return ZodIntersection.create(this, incoming, this._def);
 889 |   }
 890 |   transform(transform) {
 891 |     return new ZodEffects({
 892 |       ...processCreateParams(this._def),
 893 |       schema: this,
 894 |       typeName: ZodFirstPartyTypeKind.ZodEffects,
 895 |       effect: { type: "transform", transform }
 896 |     });
 897 |   }
 898 |   default(def) {
 899 |     const defaultValueFunc = typeof def === "function" ? def : () => def;
 900 |     return new ZodDefault({
 901 |       ...processCreateParams(this._def),
 902 |       innerType: this,
 903 |       defaultValue: defaultValueFunc,
 904 |       typeName: ZodFirstPartyTypeKind.ZodDefault
 905 |     });
 906 |   }
 907 |   brand() {
 908 |     return new ZodBranded({
 909 |       typeName: ZodFirstPartyTypeKind.ZodBranded,
 910 |       type: this,
 911 |       ...processCreateParams(this._def)
 912 |     });
 913 |   }
 914 |   catch(def) {
 915 |     const catchValueFunc = typeof def === "function" ? def : () => def;
 916 |     return new ZodCatch({
 917 |       ...processCreateParams(this._def),
 918 |       innerType: this,
 919 |       catchValue: catchValueFunc,
 920 |       typeName: ZodFirstPartyTypeKind.ZodCatch
 921 |     });
 922 |   }
 923 |   describe(description) {
 924 |     const This = this.constructor;
 925 |     return new This({
 926 |       ...this._def,
 927 |       description
 928 |     });
 929 |   }
 930 |   pipe(target) {
 931 |     return ZodPipeline.create(this, target);
 932 |   }
 933 |   readonly() {
 934 |     return ZodReadonly.create(this);
 935 |   }
 936 |   isOptional() {
 937 |     return this.safeParse(void 0).success;
 938 |   }
 939 |   isNullable() {
 940 |     return this.safeParse(null).success;
 941 |   }
 942 | };
 943 | var cuidRegex = /^c[^\s-]{8,}$/i;
 944 | var cuid2Regex = /^[0-9a-z]+$/;
 945 | var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
 946 | var uuidRegex = /^[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;
 947 | var nanoidRegex = /^[a-z0-9_-]{21}$/i;
 948 | var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
 949 | var durationRegex = /^[-+]?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)?)??$/;
 950 | var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
 951 | var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
 952 | var emojiRegex;
 953 | var ipv4Regex = /^(?:(?: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])$/;
 954 | var ipv4CidrRegex = /^(?:(?: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])$/;
 955 | var ipv6Regex = /^(([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]))$/;
 956 | var ipv6CidrRegex = /^(([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])$/;
 957 | var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
 958 | var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
 959 | var dateRegexSource = `((\\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])))`;
 960 | var dateRegex = new RegExp(`^${dateRegexSource}$`);
 961 | function timeRegexSource(args) {
 962 |   let secondsRegexSource = `[0-5]\\d`;
 963 |   if (args.precision) {
 964 |     secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
 965 |   } else if (args.precision == null) {
 966 |     secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
 967 |   }
 968 |   const secondsQuantifier = args.precision ? "+" : "?";
 969 |   return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
 970 | }
 971 | function timeRegex(args) {
 972 |   return new RegExp(`^${timeRegexSource(args)}$`);
 973 | }
 974 | function datetimeRegex(args) {
 975 |   let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
 976 |   const opts = [];
 977 |   opts.push(args.local ? `Z?` : `Z`);
 978 |   if (args.offset)
 979 |     opts.push(`([+-]\\d{2}:?\\d{2})`);
 980 |   regex = `${regex}(${opts.join("|")})`;
 981 |   return new RegExp(`^${regex}$`);
 982 | }
 983 | function isValidIP(ip, version) {
 984 |   if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
 985 |     return true;
 986 |   }
 987 |   if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
 988 |     return true;
 989 |   }
 990 |   return false;
 991 | }
 992 | function isValidJWT(jwt, alg) {
 993 |   if (!jwtRegex.test(jwt))
 994 |     return false;
 995 |   try {
 996 |     const [header] = jwt.split(".");
 997 |     const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
 998 |     const decoded = JSON.parse(atob(base64));
 999 |     if (typeof decoded !== "object" || decoded === null)
1000 |       return false;
1001 |     if ("typ" in decoded && decoded?.typ !== "JWT")
1002 |       return false;
1003 |     if (!decoded.alg)
1004 |       return false;
1005 |     if (alg && decoded.alg !== alg)
1006 |       return false;
1007 |     return true;
1008 |   } catch {
1009 |     return false;
1010 |   }
1011 | }
1012 | function isValidCidr(ip, version) {
1013 |   if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1014 |     return true;
1015 |   }
1016 |   if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1017 |     return true;
1018 |   }
1019 |   return false;
1020 | }
1021 | var ZodString = class _ZodString extends ZodType {
1022 |   _parse(input) {
1023 |     if (this._def.coerce) {
1024 |       input.data = String(input.data);
1025 |     }
1026 |     const parsedType = this._getType(input);
1027 |     if (parsedType !== ZodParsedType.string) {
1028 |       const ctx2 = this._getOrReturnCtx(input);
1029 |       addIssueToContext(ctx2, {
1030 |         code: ZodIssueCode.invalid_type,
1031 |         expected: ZodParsedType.string,
1032 |         received: ctx2.parsedType
1033 |       });
1034 |       return INVALID;
1035 |     }
1036 |     const status = new ParseStatus();
1037 |     let ctx = void 0;
1038 |     for (const check of this._def.checks) {
1039 |       if (check.kind === "min") {
1040 |         if (input.data.length < check.value) {
1041 |           ctx = this._getOrReturnCtx(input, ctx);
1042 |           addIssueToContext(ctx, {
1043 |             code: ZodIssueCode.too_small,
1044 |             minimum: check.value,
1045 |             type: "string",
1046 |             inclusive: true,
1047 |             exact: false,
1048 |             message: check.message
1049 |           });
1050 |           status.dirty();
1051 |         }
1052 |       } else if (check.kind === "max") {
1053 |         if (input.data.length > check.value) {
1054 |           ctx = this._getOrReturnCtx(input, ctx);
1055 |           addIssueToContext(ctx, {
1056 |             code: ZodIssueCode.too_big,
1057 |             maximum: check.value,
1058 |             type: "string",
1059 |             inclusive: true,
1060 |             exact: false,
1061 |             message: check.message
1062 |           });
1063 |           status.dirty();
1064 |         }
1065 |       } else if (check.kind === "length") {
1066 |         const tooBig = input.data.length > check.value;
1067 |         const tooSmall = input.data.length < check.value;
1068 |         if (tooBig || tooSmall) {
1069 |           ctx = this._getOrReturnCtx(input, ctx);
1070 |           if (tooBig) {
1071 |             addIssueToContext(ctx, {
1072 |               code: ZodIssueCode.too_big,
1073 |               maximum: check.value,
1074 |               type: "string",
1075 |               inclusive: true,
1076 |               exact: true,
1077 |               message: check.message
1078 |             });
1079 |           } else if (tooSmall) {
1080 |             addIssueToContext(ctx, {
1081 |               code: ZodIssueCode.too_small,
1082 |               minimum: check.value,
1083 |               type: "string",
1084 |               inclusive: true,
1085 |               exact: true,
1086 |               message: check.message
1087 |             });
1088 |           }
1089 |           status.dirty();
1090 |         }
1091 |       } else if (check.kind === "email") {
1092 |         if (!emailRegex.test(input.data)) {
1093 |           ctx = this._getOrReturnCtx(input, ctx);
1094 |           addIssueToContext(ctx, {
1095 |             validation: "email",
1096 |             code: ZodIssueCode.invalid_string,
1097 |             message: check.message
1098 |           });
1099 |           status.dirty();
1100 |         }
1101 |       } else if (check.kind === "emoji") {
1102 |         if (!emojiRegex) {
1103 |           emojiRegex = new RegExp(_emojiRegex, "u");
1104 |         }
1105 |         if (!emojiRegex.test(input.data)) {
1106 |           ctx = this._getOrReturnCtx(input, ctx);
1107 |           addIssueToContext(ctx, {
1108 |             validation: "emoji",
1109 |             code: ZodIssueCode.invalid_string,
1110 |             message: check.message
1111 |           });
1112 |           status.dirty();
1113 |         }
1114 |       } else if (check.kind === "uuid") {
1115 |         if (!uuidRegex.test(input.data)) {
1116 |           ctx = this._getOrReturnCtx(input, ctx);
1117 |           addIssueToContext(ctx, {
1118 |             validation: "uuid",
1119 |             code: ZodIssueCode.invalid_string,
1120 |             message: check.message
1121 |           });
1122 |           status.dirty();
1123 |         }
1124 |       } else if (check.kind === "nanoid") {
1125 |         if (!nanoidRegex.test(input.data)) {
1126 |           ctx = this._getOrReturnCtx(input, ctx);
1127 |           addIssueToContext(ctx, {
1128 |             validation: "nanoid",
1129 |             code: ZodIssueCode.invalid_string,
1130 |             message: check.message
1131 |           });
1132 |           status.dirty();
1133 |         }
1134 |       } else if (check.kind === "cuid") {
1135 |         if (!cuidRegex.test(input.data)) {
1136 |           ctx = this._getOrReturnCtx(input, ctx);
1137 |           addIssueToContext(ctx, {
1138 |             validation: "cuid",
1139 |             code: ZodIssueCode.invalid_string,
1140 |             message: check.message
1141 |           });
1142 |           status.dirty();
1143 |         }
1144 |       } else if (check.kind === "cuid2") {
1145 |         if (!cuid2Regex.test(input.data)) {
1146 |           ctx = this._getOrReturnCtx(input, ctx);
1147 |           addIssueToContext(ctx, {
1148 |             validation: "cuid2",
1149 |             code: ZodIssueCode.invalid_string,
1150 |             message: check.message
1151 |           });
1152 |           status.dirty();
1153 |         }
1154 |       } else if (check.kind === "ulid") {
1155 |         if (!ulidRegex.test(input.data)) {
1156 |           ctx = this._getOrReturnCtx(input, ctx);
1157 |           addIssueToContext(ctx, {
1158 |             validation: "ulid",
1159 |             code: ZodIssueCode.invalid_string,
1160 |             message: check.message
1161 |           });
1162 |           status.dirty();
1163 |         }
1164 |       } else if (check.kind === "url") {
1165 |         try {
1166 |           new URL(input.data);
1167 |         } catch {
1168 |           ctx = this._getOrReturnCtx(input, ctx);
1169 |           addIssueToContext(ctx, {
1170 |             validation: "url",
1171 |             code: ZodIssueCode.invalid_string,
1172 |             message: check.message
1173 |           });
1174 |           status.dirty();
1175 |         }
1176 |       } else if (check.kind === "regex") {
1177 |         check.regex.lastIndex = 0;
1178 |         const testResult = check.regex.test(input.data);
1179 |         if (!testResult) {
1180 |           ctx = this._getOrReturnCtx(input, ctx);
1181 |           addIssueToContext(ctx, {
1182 |             validation: "regex",
1183 |             code: ZodIssueCode.invalid_string,
1184 |             message: check.message
1185 |           });
1186 |           status.dirty();
1187 |         }
1188 |       } else if (check.kind === "trim") {
1189 |         input.data = input.data.trim();
1190 |       } else if (check.kind === "includes") {
1191 |         if (!input.data.includes(check.value, check.position)) {
1192 |           ctx = this._getOrReturnCtx(input, ctx);
1193 |           addIssueToContext(ctx, {
1194 |             code: ZodIssueCode.invalid_string,
1195 |             validation: { includes: check.value, position: check.position },
1196 |             message: check.message
1197 |           });
1198 |           status.dirty();
1199 |         }
1200 |       } else if (check.kind === "toLowerCase") {
1201 |         input.data = input.data.toLowerCase();
1202 |       } else if (check.kind === "toUpperCase") {
1203 |         input.data = input.data.toUpperCase();
1204 |       } else if (check.kind === "startsWith") {
1205 |         if (!input.data.startsWith(check.value)) {
1206 |           ctx = this._getOrReturnCtx(input, ctx);
1207 |           addIssueToContext(ctx, {
1208 |             code: ZodIssueCode.invalid_string,
1209 |             validation: { startsWith: check.value },
1210 |             message: check.message
1211 |           });
1212 |           status.dirty();
1213 |         }
1214 |       } else if (check.kind === "endsWith") {
1215 |         if (!input.data.endsWith(check.value)) {
1216 |           ctx = this._getOrReturnCtx(input, ctx);
1217 |           addIssueToContext(ctx, {
1218 |             code: ZodIssueCode.invalid_string,
1219 |             validation: { endsWith: check.value },
1220 |             message: check.message
1221 |           });
1222 |           status.dirty();
1223 |         }
1224 |       } else if (check.kind === "datetime") {
1225 |         const regex = datetimeRegex(check);
1226 |         if (!regex.test(input.data)) {
1227 |           ctx = this._getOrReturnCtx(input, ctx);
1228 |           addIssueToContext(ctx, {
1229 |             code: ZodIssueCode.invalid_string,
1230 |             validation: "datetime",
1231 |             message: check.message
1232 |           });
1233 |           status.dirty();
1234 |         }
1235 |       } else if (check.kind === "date") {
1236 |         const regex = dateRegex;
1237 |         if (!regex.test(input.data)) {
1238 |           ctx = this._getOrReturnCtx(input, ctx);
1239 |           addIssueToContext(ctx, {
1240 |             code: ZodIssueCode.invalid_string,
1241 |             validation: "date",
1242 |             message: check.message
1243 |           });
1244 |           status.dirty();
1245 |         }
1246 |       } else if (check.kind === "time") {
1247 |         const regex = timeRegex(check);
1248 |         if (!regex.test(input.data)) {
1249 |           ctx = this._getOrReturnCtx(input, ctx);
1250 |           addIssueToContext(ctx, {
1251 |             code: ZodIssueCode.invalid_string,
1252 |             validation: "time",
1253 |             message: check.message
1254 |           });
1255 |           status.dirty();
1256 |         }
1257 |       } else if (check.kind === "duration") {
1258 |         if (!durationRegex.test(input.data)) {
1259 |           ctx = this._getOrReturnCtx(input, ctx);
1260 |           addIssueToContext(ctx, {
1261 |             validation: "duration",
1262 |             code: ZodIssueCode.invalid_string,
1263 |             message: check.message
1264 |           });
1265 |           status.dirty();
1266 |         }
1267 |       } else if (check.kind === "ip") {
1268 |         if (!isValidIP(input.data, check.version)) {
1269 |           ctx = this._getOrReturnCtx(input, ctx);
1270 |           addIssueToContext(ctx, {
1271 |             validation: "ip",
1272 |             code: ZodIssueCode.invalid_string,
1273 |             message: check.message
1274 |           });
1275 |           status.dirty();
1276 |         }
1277 |       } else if (check.kind === "jwt") {
1278 |         if (!isValidJWT(input.data, check.alg)) {
1279 |           ctx = this._getOrReturnCtx(input, ctx);
1280 |           addIssueToContext(ctx, {
1281 |             validation: "jwt",
1282 |             code: ZodIssueCode.invalid_string,
1283 |             message: check.message
1284 |           });
1285 |           status.dirty();
1286 |         }
1287 |       } else if (check.kind === "cidr") {
1288 |         if (!isValidCidr(input.data, check.version)) {
1289 |           ctx = this._getOrReturnCtx(input, ctx);
1290 |           addIssueToContext(ctx, {
1291 |             validation: "cidr",
1292 |             code: ZodIssueCode.invalid_string,
1293 |             message: check.message
1294 |           });
1295 |           status.dirty();
1296 |         }
1297 |       } else if (check.kind === "base64") {
1298 |         if (!base64Regex.test(input.data)) {
1299 |           ctx = this._getOrReturnCtx(input, ctx);
1300 |           addIssueToContext(ctx, {
1301 |             validation: "base64",
1302 |             code: ZodIssueCode.invalid_string,
1303 |             message: check.message
1304 |           });
1305 |           status.dirty();
1306 |         }
1307 |       } else if (check.kind === "base64url") {
1308 |         if (!base64urlRegex.test(input.data)) {
1309 |           ctx = this._getOrReturnCtx(input, ctx);
1310 |           addIssueToContext(ctx, {
1311 |             validation: "base64url",
1312 |             code: ZodIssueCode.invalid_string,
1313 |             message: check.message
1314 |           });
1315 |           status.dirty();
1316 |         }
1317 |       } else {
1318 |         util.assertNever(check);
1319 |       }
1320 |     }
1321 |     return { status: status.value, value: input.data };
1322 |   }
1323 |   _regex(regex, validation, message) {
1324 |     return this.refinement((data) => regex.test(data), {
1325 |       validation,
1326 |       code: ZodIssueCode.invalid_string,
1327 |       ...errorUtil.errToObj(message)
1328 |     });
1329 |   }
1330 |   _addCheck(check) {
1331 |     return new _ZodString({
1332 |       ...this._def,
1333 |       checks: [...this._def.checks, check]
1334 |     });
1335 |   }
1336 |   email(message) {
1337 |     return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1338 |   }
1339 |   url(message) {
1340 |     return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1341 |   }
1342 |   emoji(message) {
1343 |     return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1344 |   }
1345 |   uuid(message) {
1346 |     return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1347 |   }
1348 |   nanoid(message) {
1349 |     return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1350 |   }
1351 |   cuid(message) {
1352 |     return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1353 |   }
1354 |   cuid2(message) {
1355 |     return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1356 |   }
1357 |   ulid(message) {
1358 |     return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1359 |   }
1360 |   base64(message) {
1361 |     return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1362 |   }
1363 |   base64url(message) {
1364 |     return this._addCheck({
1365 |       kind: "base64url",
1366 |       ...errorUtil.errToObj(message)
1367 |     });
1368 |   }
1369 |   jwt(options) {
1370 |     return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1371 |   }
1372 |   ip(options) {
1373 |     return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1374 |   }
1375 |   cidr(options) {
1376 |     return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1377 |   }
1378 |   datetime(options) {
1379 |     if (typeof options === "string") {
1380 |       return this._addCheck({
1381 |         kind: "datetime",
1382 |         precision: null,
1383 |         offset: false,
1384 |         local: false,
1385 |         message: options
1386 |       });
1387 |     }
1388 |     return this._addCheck({
1389 |       kind: "datetime",
1390 |       precision: typeof options?.precision === "undefined" ? null : options?.precision,
1391 |       offset: options?.offset ?? false,
1392 |       local: options?.local ?? false,
1393 |       ...errorUtil.errToObj(options?.message)
1394 |     });
1395 |   }
1396 |   date(message) {
1397 |     return this._addCheck({ kind: "date", message });
1398 |   }
1399 |   time(options) {
1400 |     if (typeof options === "string") {
1401 |       return this._addCheck({
1402 |         kind: "time",
1403 |         precision: null,
1404 |         message: options
1405 |       });
1406 |     }
1407 |     return this._addCheck({
1408 |       kind: "time",
1409 |       precision: typeof options?.precision === "undefined" ? null : options?.precision,
1410 |       ...errorUtil.errToObj(options?.message)
1411 |     });
1412 |   }
1413 |   duration(message) {
1414 |     return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1415 |   }
1416 |   regex(regex, message) {
1417 |     return this._addCheck({
1418 |       kind: "regex",
1419 |       regex,
1420 |       ...errorUtil.errToObj(message)
1421 |     });
1422 |   }
1423 |   includes(value, options) {
1424 |     return this._addCheck({
1425 |       kind: "includes",
1426 |       value,
1427 |       position: options?.position,
1428 |       ...errorUtil.errToObj(options?.message)
1429 |     });
1430 |   }
1431 |   startsWith(value, message) {
1432 |     return this._addCheck({
1433 |       kind: "startsWith",
1434 |       value,
1435 |       ...errorUtil.errToObj(message)
1436 |     });
1437 |   }
1438 |   endsWith(value, message) {
1439 |     return this._addCheck({
1440 |       kind: "endsWith",
1441 |       value,
1442 |       ...errorUtil.errToObj(message)
1443 |     });
1444 |   }
1445 |   min(minLength, message) {
1446 |     return this._addCheck({
1447 |       kind: "min",
1448 |       value: minLength,
1449 |       ...errorUtil.errToObj(message)
1450 |     });
1451 |   }
1452 |   max(maxLength, message) {
1453 |     return this._addCheck({
1454 |       kind: "max",
1455 |       value: maxLength,
1456 |       ...errorUtil.errToObj(message)
1457 |     });
1458 |   }
1459 |   length(len, message) {
1460 |     return this._addCheck({
1461 |       kind: "length",
1462 |       value: len,
1463 |       ...errorUtil.errToObj(message)
1464 |     });
1465 |   }
1466 |   /**
1467 |    * Equivalent to `.min(1)`
1468 |    */
1469 |   nonempty(message) {
1470 |     return this.min(1, errorUtil.errToObj(message));
1471 |   }
1472 |   trim() {
1473 |     return new _ZodString({
1474 |       ...this._def,
1475 |       checks: [...this._def.checks, { kind: "trim" }]
1476 |     });
1477 |   }
1478 |   toLowerCase() {
1479 |     return new _ZodString({
1480 |       ...this._def,
1481 |       checks: [...this._def.checks, { kind: "toLowerCase" }]
1482 |     });
1483 |   }
1484 |   toUpperCase() {
1485 |     return new _ZodString({
1486 |       ...this._def,
1487 |       checks: [...this._def.checks, { kind: "toUpperCase" }]
1488 |     });
1489 |   }
1490 |   get isDatetime() {
1491 |     return !!this._def.checks.find((ch) => ch.kind === "datetime");
1492 |   }
1493 |   get isDate() {
1494 |     return !!this._def.checks.find((ch) => ch.kind === "date");
1495 |   }
1496 |   get isTime() {
1497 |     return !!this._def.checks.find((ch) => ch.kind === "time");
1498 |   }
1499 |   get isDuration() {
1500 |     return !!this._def.checks.find((ch) => ch.kind === "duration");
1501 |   }
1502 |   get isEmail() {
1503 |     return !!this._def.checks.find((ch) => ch.kind === "email");
1504 |   }
1505 |   get isURL() {
1506 |     return !!this._def.checks.find((ch) => ch.kind === "url");
1507 |   }
1508 |   get isEmoji() {
1509 |     return !!this._def.checks.find((ch) => ch.kind === "emoji");
1510 |   }
1511 |   get isUUID() {
1512 |     return !!this._def.checks.find((ch) => ch.kind === "uuid");
1513 |   }
1514 |   get isNANOID() {
1515 |     return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1516 |   }
1517 |   get isCUID() {
1518 |     return !!this._def.checks.find((ch) => ch.kind === "cuid");
1519 |   }
1520 |   get isCUID2() {
1521 |     return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1522 |   }
1523 |   get isULID() {
1524 |     return !!this._def.checks.find((ch) => ch.kind === "ulid");
1525 |   }
1526 |   get isIP() {
1527 |     return !!this._def.checks.find((ch) => ch.kind === "ip");
1528 |   }
1529 |   get isCIDR() {
1530 |     return !!this._def.checks.find((ch) => ch.kind === "cidr");
1531 |   }
1532 |   get isBase64() {
1533 |     return !!this._def.checks.find((ch) => ch.kind === "base64");
1534 |   }
1535 |   get isBase64url() {
1536 |     return !!this._def.checks.find((ch) => ch.kind === "base64url");
1537 |   }
1538 |   get minLength() {
1539 |     let min = null;
1540 |     for (const ch of this._def.checks) {
1541 |       if (ch.kind === "min") {
1542 |         if (min === null || ch.value > min)
1543 |           min = ch.value;
1544 |       }
1545 |     }
1546 |     return min;
1547 |   }
1548 |   get maxLength() {
1549 |     let max = null;
1550 |     for (const ch of this._def.checks) {
1551 |       if (ch.kind === "max") {
1552 |         if (max === null || ch.value < max)
1553 |           max = ch.value;
1554 |       }
1555 |     }
1556 |     return max;
1557 |   }
1558 | };
1559 | ZodString.create = (params) => {
1560 |   return new ZodString({
1561 |     checks: [],
1562 |     typeName: ZodFirstPartyTypeKind.ZodString,
1563 |     coerce: params?.coerce ?? false,
1564 |     ...processCreateParams(params)
1565 |   });
1566 | };
1567 | function floatSafeRemainder(val, step) {
1568 |   const valDecCount = (val.toString().split(".")[1] || "").length;
1569 |   const stepDecCount = (step.toString().split(".")[1] || "").length;
1570 |   const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1571 |   const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1572 |   const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1573 |   return valInt % stepInt / 10 ** decCount;
1574 | }
1575 | var ZodNumber = class _ZodNumber extends ZodType {
1576 |   constructor() {
1577 |     super(...arguments);
1578 |     this.min = this.gte;
1579 |     this.max = this.lte;
1580 |     this.step = this.multipleOf;
1581 |   }
1582 |   _parse(input) {
1583 |     if (this._def.coerce) {
1584 |       input.data = Number(input.data);
1585 |     }
1586 |     const parsedType = this._getType(input);
1587 |     if (parsedType !== ZodParsedType.number) {
1588 |       const ctx2 = this._getOrReturnCtx(input);
1589 |       addIssueToContext(ctx2, {
1590 |         code: ZodIssueCode.invalid_type,
1591 |         expected: ZodParsedType.number,
1592 |         received: ctx2.parsedType
1593 |       });
1594 |       return INVALID;
1595 |     }
1596 |     let ctx = void 0;
1597 |     const status = new ParseStatus();
1598 |     for (const check of this._def.checks) {
1599 |       if (check.kind === "int") {
1600 |         if (!util.isInteger(input.data)) {
1601 |           ctx = this._getOrReturnCtx(input, ctx);
1602 |           addIssueToContext(ctx, {
1603 |             code: ZodIssueCode.invalid_type,
1604 |             expected: "integer",
1605 |             received: "float",
1606 |             message: check.message
1607 |           });
1608 |           status.dirty();
1609 |         }
1610 |       } else if (check.kind === "min") {
1611 |         const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1612 |         if (tooSmall) {
1613 |           ctx = this._getOrReturnCtx(input, ctx);
1614 |           addIssueToContext(ctx, {
1615 |             code: ZodIssueCode.too_small,
1616 |             minimum: check.value,
1617 |             type: "number",
1618 |             inclusive: check.inclusive,
1619 |             exact: false,
1620 |             message: check.message
1621 |           });
1622 |           status.dirty();
1623 |         }
1624 |       } else if (check.kind === "max") {
1625 |         const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1626 |         if (tooBig) {
1627 |           ctx = this._getOrReturnCtx(input, ctx);
1628 |           addIssueToContext(ctx, {
1629 |             code: ZodIssueCode.too_big,
1630 |             maximum: check.value,
1631 |             type: "number",
1632 |             inclusive: check.inclusive,
1633 |             exact: false,
1634 |             message: check.message
1635 |           });
1636 |           status.dirty();
1637 |         }
1638 |       } else if (check.kind === "multipleOf") {
1639 |         if (floatSafeRemainder(input.data, check.value) !== 0) {
1640 |           ctx = this._getOrReturnCtx(input, ctx);
1641 |           addIssueToContext(ctx, {
1642 |             code: ZodIssueCode.not_multiple_of,
1643 |             multipleOf: check.value,
1644 |             message: check.message
1645 |           });
1646 |           status.dirty();
1647 |         }
1648 |       } else if (check.kind === "finite") {
1649 |         if (!Number.isFinite(input.data)) {
1650 |           ctx = this._getOrReturnCtx(input, ctx);
1651 |           addIssueToContext(ctx, {
1652 |             code: ZodIssueCode.not_finite,
1653 |             message: check.message
1654 |           });
1655 |           status.dirty();
1656 |         }
1657 |       } else {
1658 |         util.assertNever(check);
1659 |       }
1660 |     }
1661 |     return { status: status.value, value: input.data };
1662 |   }
1663 |   gte(value, message) {
1664 |     return this.setLimit("min", value, true, errorUtil.toString(message));
1665 |   }
1666 |   gt(value, message) {
1667 |     return this.setLimit("min", value, false, errorUtil.toString(message));
1668 |   }
1669 |   lte(value, message) {
1670 |     return this.setLimit("max", value, true, errorUtil.toString(message));
1671 |   }
1672 |   lt(value, message) {
1673 |     return this.setLimit("max", value, false, errorUtil.toString(message));
1674 |   }
1675 |   setLimit(kind, value, inclusive, message) {
1676 |     return new _ZodNumber({
1677 |       ...this._def,
1678 |       checks: [
1679 |         ...this._def.checks,
1680 |         {
1681 |           kind,
1682 |           value,
1683 |           inclusive,
1684 |           message: errorUtil.toString(message)
1685 |         }
1686 |       ]
1687 |     });
1688 |   }
1689 |   _addCheck(check) {
1690 |     return new _ZodNumber({
1691 |       ...this._def,
1692 |       checks: [...this._def.checks, check]
1693 |     });
1694 |   }
1695 |   int(message) {
1696 |     return this._addCheck({
1697 |       kind: "int",
1698 |       message: errorUtil.toString(message)
1699 |     });
1700 |   }
1701 |   positive(message) {
1702 |     return this._addCheck({
1703 |       kind: "min",
1704 |       value: 0,
1705 |       inclusive: false,
1706 |       message: errorUtil.toString(message)
1707 |     });
1708 |   }
1709 |   negative(message) {
1710 |     return this._addCheck({
1711 |       kind: "max",
1712 |       value: 0,
1713 |       inclusive: false,
1714 |       message: errorUtil.toString(message)
1715 |     });
1716 |   }
1717 |   nonpositive(message) {
1718 |     return this._addCheck({
1719 |       kind: "max",
1720 |       value: 0,
1721 |       inclusive: true,
1722 |       message: errorUtil.toString(message)
1723 |     });
1724 |   }
1725 |   nonnegative(message) {
1726 |     return this._addCheck({
1727 |       kind: "min",
1728 |       value: 0,
1729 |       inclusive: true,
1730 |       message: errorUtil.toString(message)
1731 |     });
1732 |   }
1733 |   multipleOf(value, message) {
1734 |     return this._addCheck({
1735 |       kind: "multipleOf",
1736 |       value,
1737 |       message: errorUtil.toString(message)
1738 |     });
1739 |   }
1740 |   finite(message) {
1741 |     return this._addCheck({
1742 |       kind: "finite",
1743 |       message: errorUtil.toString(message)
1744 |     });
1745 |   }
1746 |   safe(message) {
1747 |     return this._addCheck({
1748 |       kind: "min",
1749 |       inclusive: true,
1750 |       value: Number.MIN_SAFE_INTEGER,
1751 |       message: errorUtil.toString(message)
1752 |     })._addCheck({
1753 |       kind: "max",
1754 |       inclusive: true,
1755 |       value: Number.MAX_SAFE_INTEGER,
1756 |       message: errorUtil.toString(message)
1757 |     });
1758 |   }
1759 |   get minValue() {
1760 |     let min = null;
1761 |     for (const ch of this._def.checks) {
1762 |       if (ch.kind === "min") {
1763 |         if (min === null || ch.value > min)
1764 |           min = ch.value;
1765 |       }
1766 |     }
1767 |     return min;
1768 |   }
1769 |   get maxValue() {
1770 |     let max = null;
1771 |     for (const ch of this._def.checks) {
1772 |       if (ch.kind === "max") {
1773 |         if (max === null || ch.value < max)
1774 |           max = ch.value;
1775 |       }
1776 |     }
1777 |     return max;
1778 |   }
1779 |   get isInt() {
1780 |     return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1781 |   }
1782 |   get isFinite() {
1783 |     let max = null;
1784 |     let min = null;
1785 |     for (const ch of this._def.checks) {
1786 |       if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1787 |         return true;
1788 |       } else if (ch.kind === "min") {
1789 |         if (min === null || ch.value > min)
1790 |           min = ch.value;
1791 |       } else if (ch.kind === "max") {
1792 |         if (max === null || ch.value < max)
1793 |           max = ch.value;
1794 |       }
1795 |     }
1796 |     return Number.isFinite(min) && Number.isFinite(max);
1797 |   }
1798 | };
1799 | ZodNumber.create = (params) => {
1800 |   return new ZodNumber({
1801 |     checks: [],
1802 |     typeName: ZodFirstPartyTypeKind.ZodNumber,
1803 |     coerce: params?.coerce || false,
1804 |     ...processCreateParams(params)
1805 |   });
1806 | };
1807 | var ZodBigInt = class _ZodBigInt extends ZodType {
1808 |   constructor() {
1809 |     super(...arguments);
1810 |     this.min = this.gte;
1811 |     this.max = this.lte;
1812 |   }
1813 |   _parse(input) {
1814 |     if (this._def.coerce) {
1815 |       try {
1816 |         input.data = BigInt(input.data);
1817 |       } catch {
1818 |         return this._getInvalidInput(input);
1819 |       }
1820 |     }
1821 |     const parsedType = this._getType(input);
1822 |     if (parsedType !== ZodParsedType.bigint) {
1823 |       return this._getInvalidInput(input);
1824 |     }
1825 |     let ctx = void 0;
1826 |     const status = new ParseStatus();
1827 |     for (const check of this._def.checks) {
1828 |       if (check.kind === "min") {
1829 |         const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1830 |         if (tooSmall) {
1831 |           ctx = this._getOrReturnCtx(input, ctx);
1832 |           addIssueToContext(ctx, {
1833 |             code: ZodIssueCode.too_small,
1834 |             type: "bigint",
1835 |             minimum: check.value,
1836 |             inclusive: check.inclusive,
1837 |             message: check.message
1838 |           });
1839 |           status.dirty();
1840 |         }
1841 |       } else if (check.kind === "max") {
1842 |         const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1843 |         if (tooBig) {
1844 |           ctx = this._getOrReturnCtx(input, ctx);
1845 |           addIssueToContext(ctx, {
1846 |             code: ZodIssueCode.too_big,
1847 |             type: "bigint",
1848 |             maximum: check.value,
1849 |             inclusive: check.inclusive,
1850 |             message: check.message
1851 |           });
1852 |           status.dirty();
1853 |         }
1854 |       } else if (check.kind === "multipleOf") {
1855 |         if (input.data % check.value !== BigInt(0)) {
1856 |           ctx = this._getOrReturnCtx(input, ctx);
1857 |           addIssueToContext(ctx, {
1858 |             code: ZodIssueCode.not_multiple_of,
1859 |             multipleOf: check.value,
1860 |             message: check.message
1861 |           });
1862 |           status.dirty();
1863 |         }
1864 |       } else {
1865 |         util.assertNever(check);
1866 |       }
1867 |     }
1868 |     return { status: status.value, value: input.data };
1869 |   }
1870 |   _getInvalidInput(input) {
1871 |     const ctx = this._getOrReturnCtx(input);
1872 |     addIssueToContext(ctx, {
1873 |       code: ZodIssueCode.invalid_type,
1874 |       expected: ZodParsedType.bigint,
1875 |       received: ctx.parsedType
1876 |     });
1877 |     return INVALID;
1878 |   }
1879 |   gte(value, message) {
1880 |     return this.setLimit("min", value, true, errorUtil.toString(message));
1881 |   }
1882 |   gt(value, message) {
1883 |     return this.setLimit("min", value, false, errorUtil.toString(message));
1884 |   }
1885 |   lte(value, message) {
1886 |     return this.setLimit("max", value, true, errorUtil.toString(message));
1887 |   }
1888 |   lt(value, message) {
1889 |     return this.setLimit("max", value, false, errorUtil.toString(message));
1890 |   }
1891 |   setLimit(kind, value, inclusive, message) {
1892 |     return new _ZodBigInt({
1893 |       ...this._def,
1894 |       checks: [
1895 |         ...this._def.checks,
1896 |         {
1897 |           kind,
1898 |           value,
1899 |           inclusive,
1900 |           message: errorUtil.toString(message)
1901 |         }
1902 |       ]
1903 |     });
1904 |   }
1905 |   _addCheck(check) {
1906 |     return new _ZodBigInt({
1907 |       ...this._def,
1908 |       checks: [...this._def.checks, check]
1909 |     });
1910 |   }
1911 |   positive(message) {
1912 |     return this._addCheck({
1913 |       kind: "min",
1914 |       value: BigInt(0),
1915 |       inclusive: false,
1916 |       message: errorUtil.toString(message)
1917 |     });
1918 |   }
1919 |   negative(message) {
1920 |     return this._addCheck({
1921 |       kind: "max",
1922 |       value: BigInt(0),
1923 |       inclusive: false,
1924 |       message: errorUtil.toString(message)
1925 |     });
1926 |   }
1927 |   nonpositive(message) {
1928 |     return this._addCheck({
1929 |       kind: "max",
1930 |       value: BigInt(0),
1931 |       inclusive: true,
1932 |       message: errorUtil.toString(message)
1933 |     });
1934 |   }
1935 |   nonnegative(message) {
1936 |     return this._addCheck({
1937 |       kind: "min",
1938 |       value: BigInt(0),
1939 |       inclusive: true,
1940 |       message: errorUtil.toString(message)
1941 |     });
1942 |   }
1943 |   multipleOf(value, message) {
1944 |     return this._addCheck({
1945 |       kind: "multipleOf",
1946 |       value,
1947 |       message: errorUtil.toString(message)
1948 |     });
1949 |   }
1950 |   get minValue() {
1951 |     let min = null;
1952 |     for (const ch of this._def.checks) {
1953 |       if (ch.kind === "min") {
1954 |         if (min === null || ch.value > min)
1955 |           min = ch.value;
1956 |       }
1957 |     }
1958 |     return min;
1959 |   }
1960 |   get maxValue() {
1961 |     let max = null;
1962 |     for (const ch of this._def.checks) {
1963 |       if (ch.kind === "max") {
1964 |         if (max === null || ch.value < max)
1965 |           max = ch.value;
1966 |       }
1967 |     }
1968 |     return max;
1969 |   }
1970 | };
1971 | ZodBigInt.create = (params) => {
1972 |   return new ZodBigInt({
1973 |     checks: [],
1974 |     typeName: ZodFirstPartyTypeKind.ZodBigInt,
1975 |     coerce: params?.coerce ?? false,
1976 |     ...processCreateParams(params)
1977 |   });
1978 | };
1979 | var ZodBoolean = class extends ZodType {
1980 |   _parse(input) {
1981 |     if (this._def.coerce) {
1982 |       input.data = Boolean(input.data);
1983 |     }
1984 |     const parsedType = this._getType(input);
1985 |     if (parsedType !== ZodParsedType.boolean) {
1986 |       const ctx = this._getOrReturnCtx(input);
1987 |       addIssueToContext(ctx, {
1988 |         code: ZodIssueCode.invalid_type,
1989 |         expected: ZodParsedType.boolean,
1990 |         received: ctx.parsedType
1991 |       });
1992 |       return INVALID;
1993 |     }
1994 |     return OK(input.data);
1995 |   }
1996 | };
1997 | ZodBoolean.create = (params) => {
1998 |   return new ZodBoolean({
1999 |     typeName: ZodFirstPartyTypeKind.ZodBoolean,
2000 |     coerce: params?.coerce || false,
2001 |     ...processCreateParams(params)
2002 |   });
2003 | };
2004 | var ZodDate = class _ZodDate extends ZodType {
2005 |   _parse(input) {
2006 |     if (this._def.coerce) {
2007 |       input.data = new Date(input.data);
2008 |     }
2009 |     const parsedType = this._getType(input);
2010 |     if (parsedType !== ZodParsedType.date) {
2011 |       const ctx2 = this._getOrReturnCtx(input);
2012 |       addIssueToContext(ctx2, {
2013 |         code: ZodIssueCode.invalid_type,
2014 |         expected: ZodParsedType.date,
2015 |         received: ctx2.parsedType
2016 |       });
2017 |       return INVALID;
2018 |     }
2019 |     if (Number.isNaN(input.data.getTime())) {
2020 |       const ctx2 = this._getOrReturnCtx(input);
2021 |       addIssueToContext(ctx2, {
2022 |         code: ZodIssueCode.invalid_date
2023 |       });
2024 |       return INVALID;
2025 |     }
2026 |     const status = new ParseStatus();
2027 |     let ctx = void 0;
2028 |     for (const check of this._def.checks) {
2029 |       if (check.kind === "min") {
2030 |         if (input.data.getTime() < check.value) {
2031 |           ctx = this._getOrReturnCtx(input, ctx);
2032 |           addIssueToContext(ctx, {
2033 |             code: ZodIssueCode.too_small,
2034 |             message: check.message,
2035 |             inclusive: true,
2036 |             exact: false,
2037 |             minimum: check.value,
2038 |             type: "date"
2039 |           });
2040 |           status.dirty();
2041 |         }
2042 |       } else if (check.kind === "max") {
2043 |         if (input.data.getTime() > check.value) {
2044 |           ctx = this._getOrReturnCtx(input, ctx);
2045 |           addIssueToContext(ctx, {
2046 |             code: ZodIssueCode.too_big,
2047 |             message: check.message,
2048 |             inclusive: true,
2049 |             exact: false,
2050 |             maximum: check.value,
2051 |             type: "date"
2052 |           });
2053 |           status.dirty();
2054 |         }
2055 |       } else {
2056 |         util.assertNever(check);
2057 |       }
2058 |     }
2059 |     return {
2060 |       status: status.value,
2061 |       value: new Date(input.data.getTime())
2062 |     };
2063 |   }
2064 |   _addCheck(check) {
2065 |     return new _ZodDate({
2066 |       ...this._def,
2067 |       checks: [...this._def.checks, check]
2068 |     });
2069 |   }
2070 |   min(minDate, message) {
2071 |     return this._addCheck({
2072 |       kind: "min",
2073 |       value: minDate.getTime(),
2074 |       message: errorUtil.toString(message)
2075 |     });
2076 |   }
2077 |   max(maxDate, message) {
2078 |     return this._addCheck({
2079 |       kind: "max",
2080 |       value: maxDate.getTime(),
2081 |       message: errorUtil.toString(message)
2082 |     });
2083 |   }
2084 |   get minDate() {
2085 |     let min = null;
2086 |     for (const ch of this._def.checks) {
2087 |       if (ch.kind === "min") {
2088 |         if (min === null || ch.value > min)
2089 |           min = ch.value;
2090 |       }
2091 |     }
2092 |     return min != null ? new Date(min) : null;
2093 |   }
2094 |   get maxDate() {
2095 |     let max = null;
2096 |     for (const ch of this._def.checks) {
2097 |       if (ch.kind === "max") {
2098 |         if (max === null || ch.value < max)
2099 |           max = ch.value;
2100 |       }
2101 |     }
2102 |     return max != null ? new Date(max) : null;
2103 |   }
2104 | };
2105 | ZodDate.create = (params) => {
2106 |   return new ZodDate({
2107 |     checks: [],
2108 |     coerce: params?.coerce || false,
2109 |     typeName: ZodFirstPartyTypeKind.ZodDate,
2110 |     ...processCreateParams(params)
2111 |   });
2112 | };
2113 | var ZodSymbol = class extends ZodType {
2114 |   _parse(input) {
2115 |     const parsedType = this._getType(input);
2116 |     if (parsedType !== ZodParsedType.symbol) {
2117 |       const ctx = this._getOrReturnCtx(input);
2118 |       addIssueToContext(ctx, {
2119 |         code: ZodIssueCode.invalid_type,
2120 |         expected: ZodParsedType.symbol,
2121 |         received: ctx.parsedType
2122 |       });
2123 |       return INVALID;
2124 |     }
2125 |     return OK(input.data);
2126 |   }
2127 | };
2128 | ZodSymbol.create = (params) => {
2129 |   return new ZodSymbol({
2130 |     typeName: ZodFirstPartyTypeKind.ZodSymbol,
2131 |     ...processCreateParams(params)
2132 |   });
2133 | };
2134 | var ZodUndefined = class extends ZodType {
2135 |   _parse(input) {
2136 |     const parsedType = this._getType(input);
2137 |     if (parsedType !== ZodParsedType.undefined) {
2138 |       const ctx = this._getOrReturnCtx(input);
2139 |       addIssueToContext(ctx, {
2140 |         code: ZodIssueCode.invalid_type,
2141 |         expected: ZodParsedType.undefined,
2142 |         received: ctx.parsedType
2143 |       });
2144 |       return INVALID;
2145 |     }
2146 |     return OK(input.data);
2147 |   }
2148 | };
2149 | ZodUndefined.create = (params) => {
2150 |   return new ZodUndefined({
2151 |     typeName: ZodFirstPartyTypeKind.ZodUndefined,
2152 |     ...processCreateParams(params)
2153 |   });
2154 | };
2155 | var ZodNull = class extends ZodType {
2156 |   _parse(input) {
2157 |     const parsedType = this._getType(input);
2158 |     if (parsedType !== ZodParsedType.null) {
2159 |       const ctx = this._getOrReturnCtx(input);
2160 |       addIssueToContext(ctx, {
2161 |         code: ZodIssueCode.invalid_type,
2162 |         expected: ZodParsedType.null,
2163 |         received: ctx.parsedType
2164 |       });
2165 |       return INVALID;
2166 |     }
2167 |     return OK(input.data);
2168 |   }
2169 | };
2170 | ZodNull.create = (params) => {
2171 |   return new ZodNull({
2172 |     typeName: ZodFirstPartyTypeKind.ZodNull,
2173 |     ...processCreateParams(params)
2174 |   });
2175 | };
2176 | var ZodAny = class extends ZodType {
2177 |   constructor() {
2178 |     super(...arguments);
2179 |     this._any = true;
2180 |   }
2181 |   _parse(input) {
2182 |     return OK(input.data);
2183 |   }
2184 | };
2185 | ZodAny.create = (params) => {
2186 |   return new ZodAny({
2187 |     typeName: ZodFirstPartyTypeKind.ZodAny,
2188 |     ...processCreateParams(params)
2189 |   });
2190 | };
2191 | var ZodUnknown = class extends ZodType {
2192 |   constructor() {
2193 |     super(...arguments);
2194 |     this._unknown = true;
2195 |   }
2196 |   _parse(input) {
2197 |     return OK(input.data);
2198 |   }
2199 | };
2200 | ZodUnknown.create = (params) => {
2201 |   return new ZodUnknown({
2202 |     typeName: ZodFirstPartyTypeKind.ZodUnknown,
2203 |     ...processCreateParams(params)
2204 |   });
2205 | };
2206 | var ZodNever = class extends ZodType {
2207 |   _parse(input) {
2208 |     const ctx = this._getOrReturnCtx(input);
2209 |     addIssueToContext(ctx, {
2210 |       code: ZodIssueCode.invalid_type,
2211 |       expected: ZodParsedType.never,
2212 |       received: ctx.parsedType
2213 |     });
2214 |     return INVALID;
2215 |   }
2216 | };
2217 | ZodNever.create = (params) => {
2218 |   return new ZodNever({
2219 |     typeName: ZodFirstPartyTypeKind.ZodNever,
2220 |     ...processCreateParams(params)
2221 |   });
2222 | };
2223 | var ZodVoid = class extends ZodType {
2224 |   _parse(input) {
2225 |     const parsedType = this._getType(input);
2226 |     if (parsedType !== ZodParsedType.undefined) {
2227 |       const ctx = this._getOrReturnCtx(input);
2228 |       addIssueToContext(ctx, {
2229 |         code: ZodIssueCode.invalid_type,
2230 |         expected: ZodParsedType.void,
2231 |         received: ctx.parsedType
2232 |       });
2233 |       return INVALID;
2234 |     }
2235 |     return OK(input.data);
2236 |   }
2237 | };
2238 | ZodVoid.create = (params) => {
2239 |   return new ZodVoid({
2240 |     typeName: ZodFirstPartyTypeKind.ZodVoid,
2241 |     ...processCreateParams(params)
2242 |   });
2243 | };
2244 | var ZodArray = class _ZodArray extends ZodType {
2245 |   _parse(input) {
2246 |     const { ctx, status } = this._processInputParams(input);
2247 |     const def = this._def;
2248 |     if (ctx.parsedType !== ZodParsedType.array) {
2249 |       addIssueToContext(ctx, {
2250 |         code: ZodIssueCode.invalid_type,
2251 |         expected: ZodParsedType.array,
2252 |         received: ctx.parsedType
2253 |       });
2254 |       return INVALID;
2255 |     }
2256 |     if (def.exactLength !== null) {
2257 |       const tooBig = ctx.data.length > def.exactLength.value;
2258 |       const tooSmall = ctx.data.length < def.exactLength.value;
2259 |       if (tooBig || tooSmall) {
2260 |         addIssueToContext(ctx, {
2261 |           code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2262 |           minimum: tooSmall ? def.exactLength.value : void 0,
2263 |           maximum: tooBig ? def.exactLength.value : void 0,
2264 |           type: "array",
2265 |           inclusive: true,
2266 |           exact: true,
2267 |           message: def.exactLength.message
2268 |         });
2269 |         status.dirty();
2270 |       }
2271 |     }
2272 |     if (def.minLength !== null) {
2273 |       if (ctx.data.length < def.minLength.value) {
2274 |         addIssueToContext(ctx, {
2275 |           code: ZodIssueCode.too_small,
2276 |           minimum: def.minLength.value,
2277 |           type: "array",
2278 |           inclusive: true,
2279 |           exact: false,
2280 |           message: def.minLength.message
2281 |         });
2282 |         status.dirty();
2283 |       }
2284 |     }
2285 |     if (def.maxLength !== null) {
2286 |       if (ctx.data.length > def.maxLength.value) {
2287 |         addIssueToContext(ctx, {
2288 |           code: ZodIssueCode.too_big,
2289 |           maximum: def.maxLength.value,
2290 |           type: "array",
2291 |           inclusive: true,
2292 |           exact: false,
2293 |           message: def.maxLength.message
2294 |         });
2295 |         status.dirty();
2296 |       }
2297 |     }
2298 |     if (ctx.common.async) {
2299 |       return Promise.all([...ctx.data].map((item, i) => {
2300 |         return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2301 |       })).then((result2) => {
2302 |         return ParseStatus.mergeArray(status, result2);
2303 |       });
2304 |     }
2305 |     const result = [...ctx.data].map((item, i) => {
2306 |       return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2307 |     });
2308 |     return ParseStatus.mergeArray(status, result);
2309 |   }
2310 |   get element() {
2311 |     return this._def.type;
2312 |   }
2313 |   min(minLength, message) {
2314 |     return new _ZodArray({
2315 |       ...this._def,
2316 |       minLength: { value: minLength, message: errorUtil.toString(message) }
2317 |     });
2318 |   }
2319 |   max(maxLength, message) {
2320 |     return new _ZodArray({
2321 |       ...this._def,
2322 |       maxLength: { value: maxLength, message: errorUtil.toString(message) }
2323 |     });
2324 |   }
2325 |   length(len, message) {
2326 |     return new _ZodArray({
2327 |       ...this._def,
2328 |       exactLength: { value: len, message: errorUtil.toString(message) }
2329 |     });
2330 |   }
2331 |   nonempty(message) {
2332 |     return this.min(1, message);
2333 |   }
2334 | };
2335 | ZodArray.create = (schema, params) => {
2336 |   return new ZodArray({
2337 |     type: schema,
2338 |     minLength: null,
2339 |     maxLength: null,
2340 |     exactLength: null,
2341 |     typeName: ZodFirstPartyTypeKind.ZodArray,
2342 |     ...processCreateParams(params)
2343 |   });
2344 | };
2345 | function deepPartialify(schema) {
2346 |   if (schema instanceof ZodObject) {
2347 |     const newShape = {};
2348 |     for (const key in schema.shape) {
2349 |       const fieldSchema = schema.shape[key];
2350 |       newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2351 |     }
2352 |     return new ZodObject({
2353 |       ...schema._def,
2354 |       shape: () => newShape
2355 |     });
2356 |   } else if (schema instanceof ZodArray) {
2357 |     return new ZodArray({
2358 |       ...schema._def,
2359 |       type: deepPartialify(schema.element)
2360 |     });
2361 |   } else if (schema instanceof ZodOptional) {
2362 |     return ZodOptional.create(deepPartialify(schema.unwrap()));
2363 |   } else if (schema instanceof ZodNullable) {
2364 |     return ZodNullable.create(deepPartialify(schema.unwrap()));
2365 |   } else if (schema instanceof ZodTuple) {
2366 |     return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2367 |   } else {
2368 |     return schema;
2369 |   }
2370 | }
2371 | var ZodObject = class _ZodObject extends ZodType {
2372 |   constructor() {
2373 |     super(...arguments);
2374 |     this._cached = null;
2375 |     this.nonstrict = this.passthrough;
2376 |     this.augment = this.extend;
2377 |   }
2378 |   _getCached() {
2379 |     if (this._cached !== null)
2380 |       return this._cached;
2381 |     const shape = this._def.shape();
2382 |     const keys = util.objectKeys(shape);
2383 |     this._cached = { shape, keys };
2384 |     return this._cached;
2385 |   }
2386 |   _parse(input) {
2387 |     const parsedType = this._getType(input);
2388 |     if (parsedType !== ZodParsedType.object) {
2389 |       const ctx2 = this._getOrReturnCtx(input);
2390 |       addIssueToContext(ctx2, {
2391 |         code: ZodIssueCode.invalid_type,
2392 |         expected: ZodParsedType.object,
2393 |         received: ctx2.parsedType
2394 |       });
2395 |       return INVALID;
2396 |     }
2397 |     const { status, ctx } = this._processInputParams(input);
2398 |     const { shape, keys: shapeKeys } = this._getCached();
2399 |     const extraKeys = [];
2400 |     if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2401 |       for (const key in ctx.data) {
2402 |         if (!shapeKeys.includes(key)) {
2403 |           extraKeys.push(key);
2404 |         }
2405 |       }
2406 |     }
2407 |     const pairs = [];
2408 |     for (const key of shapeKeys) {
2409 |       const keyValidator = shape[key];
2410 |       const value = ctx.data[key];
2411 |       pairs.push({
2412 |         key: { status: "valid", value: key },
2413 |         value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2414 |         alwaysSet: key in ctx.data
2415 |       });
2416 |     }
2417 |     if (this._def.catchall instanceof ZodNever) {
2418 |       const unknownKeys = this._def.unknownKeys;
2419 |       if (unknownKeys === "passthrough") {
2420 |         for (const key of extraKeys) {
2421 |           pairs.push({
2422 |             key: { status: "valid", value: key },
2423 |             value: { status: "valid", value: ctx.data[key] }
2424 |           });
2425 |         }
2426 |       } else if (unknownKeys === "strict") {
2427 |         if (extraKeys.length > 0) {
2428 |           addIssueToContext(ctx, {
2429 |             code: ZodIssueCode.unrecognized_keys,
2430 |             keys: extraKeys
2431 |           });
2432 |           status.dirty();
2433 |         }
2434 |       } else if (unknownKeys === "strip") {
2435 |       } else {
2436 |         throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2437 |       }
2438 |     } else {
2439 |       const catchall = this._def.catchall;
2440 |       for (const key of extraKeys) {
2441 |         const value = ctx.data[key];
2442 |         pairs.push({
2443 |           key: { status: "valid", value: key },
2444 |           value: catchall._parse(
2445 |             new ParseInputLazyPath(ctx, value, ctx.path, key)
2446 |             //, ctx.child(key), value, getParsedType(value)
2447 |           ),
2448 |           alwaysSet: key in ctx.data
2449 |         });
2450 |       }
2451 |     }
2452 |     if (ctx.common.async) {
2453 |       return Promise.resolve().then(async () => {
2454 |         const syncPairs = [];
2455 |         for (const pair of pairs) {
2456 |           const key = await pair.key;
2457 |           const value = await pair.value;
2458 |           syncPairs.push({
2459 |             key,
2460 |             value,
2461 |             alwaysSet: pair.alwaysSet
2462 |           });
2463 |         }
2464 |         return syncPairs;
2465 |       }).then((syncPairs) => {
2466 |         return ParseStatus.mergeObjectSync(status, syncPairs);
2467 |       });
2468 |     } else {
2469 |       return ParseStatus.mergeObjectSync(status, pairs);
2470 |     }
2471 |   }
2472 |   get shape() {
2473 |     return this._def.shape();
2474 |   }
2475 |   strict(message) {
2476 |     errorUtil.errToObj;
2477 |     return new _ZodObject({
2478 |       ...this._def,
2479 |       unknownKeys: "strict",
2480 |       ...message !== void 0 ? {
2481 |         errorMap: (issue, ctx) => {
2482 |           const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2483 |           if (issue.code === "unrecognized_keys")
2484 |             return {
2485 |               message: errorUtil.errToObj(message).message ?? defaultError
2486 |             };
2487 |           return {
2488 |             message: defaultError
2489 |           };
2490 |         }
2491 |       } : {}
2492 |     });
2493 |   }
2494 |   strip() {
2495 |     return new _ZodObject({
2496 |       ...this._def,
2497 |       unknownKeys: "strip"
2498 |     });
2499 |   }
2500 |   passthrough() {
2501 |     return new _ZodObject({
2502 |       ...this._def,
2503 |       unknownKeys: "passthrough"
2504 |     });
2505 |   }
2506 |   // const AugmentFactory =
2507 |   //   <Def extends ZodObjectDef>(def: Def) =>
2508 |   //   <Augmentation extends ZodRawShape>(
2509 |   //     augmentation: Augmentation
2510 |   //   ): ZodObject<
2511 |   //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
2512 |   //     Def["unknownKeys"],
2513 |   //     Def["catchall"]
2514 |   //   > => {
2515 |   //     return new ZodObject({
2516 |   //       ...def,
2517 |   //       shape: () => ({
2518 |   //         ...def.shape(),
2519 |   //         ...augmentation,
2520 |   //       }),
2521 |   //     }) as any;
2522 |   //   };
2523 |   extend(augmentation) {
2524 |     return new _ZodObject({
2525 |       ...this._def,
2526 |       shape: () => ({
2527 |         ...this._def.shape(),
2528 |         ...augmentation
2529 |       })
2530 |     });
2531 |   }
2532 |   /**
2533 |    * Prior to [email protected] there was a bug in the
2534 |    * inferred type of merged objects. Please
2535 |    * upgrade if you are experiencing issues.
2536 |    */
2537 |   merge(merging) {
2538 |     const merged = new _ZodObject({
2539 |       unknownKeys: merging._def.unknownKeys,
2540 |       catchall: merging._def.catchall,
2541 |       shape: () => ({
2542 |         ...this._def.shape(),
2543 |         ...merging._def.shape()
2544 |       }),
2545 |       typeName: ZodFirstPartyTypeKind.ZodObject
2546 |     });
2547 |     return merged;
2548 |   }
2549 |   // merge<
2550 |   //   Incoming extends AnyZodObject,
2551 |   //   Augmentation extends Incoming["shape"],
2552 |   //   NewOutput extends {
2553 |   //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2554 |   //       ? Augmentation[k]["_output"]
2555 |   //       : k extends keyof Output
2556 |   //       ? Output[k]
2557 |   //       : never;
2558 |   //   },
2559 |   //   NewInput extends {
2560 |   //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2561 |   //       ? Augmentation[k]["_input"]
2562 |   //       : k extends keyof Input
2563 |   //       ? Input[k]
2564 |   //       : never;
2565 |   //   }
2566 |   // >(
2567 |   //   merging: Incoming
2568 |   // ): ZodObject<
2569 |   //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2570 |   //   Incoming["_def"]["unknownKeys"],
2571 |   //   Incoming["_def"]["catchall"],
2572 |   //   NewOutput,
2573 |   //   NewInput
2574 |   // > {
2575 |   //   const merged: any = new ZodObject({
2576 |   //     unknownKeys: merging._def.unknownKeys,
2577 |   //     catchall: merging._def.catchall,
2578 |   //     shape: () =>
2579 |   //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2580 |   //     typeName: ZodFirstPartyTypeKind.ZodObject,
2581 |   //   }) as any;
2582 |   //   return merged;
2583 |   // }
2584 |   setKey(key, schema) {
2585 |     return this.augment({ [key]: schema });
2586 |   }
2587 |   // merge<Incoming extends AnyZodObject>(
2588 |   //   merging: Incoming
2589 |   // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2590 |   // ZodObject<
2591 |   //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2592 |   //   Incoming["_def"]["unknownKeys"],
2593 |   //   Incoming["_def"]["catchall"]
2594 |   // > {
2595 |   //   // const mergedShape = objectUtil.mergeShapes(
2596 |   //   //   this._def.shape(),
2597 |   //   //   merging._def.shape()
2598 |   //   // );
2599 |   //   const merged: any = new ZodObject({
2600 |   //     unknownKeys: merging._def.unknownKeys,
2601 |   //     catchall: merging._def.catchall,
2602 |   //     shape: () =>
2603 |   //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2604 |   //     typeName: ZodFirstPartyTypeKind.ZodObject,
2605 |   //   }) as any;
2606 |   //   return merged;
2607 |   // }
2608 |   catchall(index) {
2609 |     return new _ZodObject({
2610 |       ...this._def,
2611 |       catchall: index
2612 |     });
2613 |   }
2614 |   pick(mask) {
2615 |     const shape = {};
2616 |     for (const key of util.objectKeys(mask)) {
2617 |       if (mask[key] && this.shape[key]) {
2618 |         shape[key] = this.shape[key];
2619 |       }
2620 |     }
2621 |     return new _ZodObject({
2622 |       ...this._def,
2623 |       shape: () => shape
2624 |     });
2625 |   }
2626 |   omit(mask) {
2627 |     const shape = {};
2628 |     for (const key of util.objectKeys(this.shape)) {
2629 |       if (!mask[key]) {
2630 |         shape[key] = this.shape[key];
2631 |       }
2632 |     }
2633 |     return new _ZodObject({
2634 |       ...this._def,
2635 |       shape: () => shape
2636 |     });
2637 |   }
2638 |   /**
2639 |    * @deprecated
2640 |    */
2641 |   deepPartial() {
2642 |     return deepPartialify(this);
2643 |   }
2644 |   partial(mask) {
2645 |     const newShape = {};
2646 |     for (const key of util.objectKeys(this.shape)) {
2647 |       const fieldSchema = this.shape[key];
2648 |       if (mask && !mask[key]) {
2649 |         newShape[key] = fieldSchema;
2650 |       } else {
2651 |         newShape[key] = fieldSchema.optional();
2652 |       }
2653 |     }
2654 |     return new _ZodObject({
2655 |       ...this._def,
2656 |       shape: () => newShape
2657 |     });
2658 |   }
2659 |   required(mask) {
2660 |     const newShape = {};
2661 |     for (const key of util.objectKeys(this.shape)) {
2662 |       if (mask && !mask[key]) {
2663 |         newShape[key] = this.shape[key];
2664 |       } else {
2665 |         const fieldSchema = this.shape[key];
2666 |         let newField = fieldSchema;
2667 |         while (newField instanceof ZodOptional) {
2668 |           newField = newField._def.innerType;
2669 |         }
2670 |         newShape[key] = newField;
2671 |       }
2672 |     }
2673 |     return new _ZodObject({
2674 |       ...this._def,
2675 |       shape: () => newShape
2676 |     });
2677 |   }
2678 |   keyof() {
2679 |     return createZodEnum(util.objectKeys(this.shape));
2680 |   }
2681 | };
2682 | ZodObject.create = (shape, params) => {
2683 |   return new ZodObject({
2684 |     shape: () => shape,
2685 |     unknownKeys: "strip",
2686 |     catchall: ZodNever.create(),
2687 |     typeName: ZodFirstPartyTypeKind.ZodObject,
2688 |     ...processCreateParams(params)
2689 |   });
2690 | };
2691 | ZodObject.strictCreate = (shape, params) => {
2692 |   return new ZodObject({
2693 |     shape: () => shape,
2694 |     unknownKeys: "strict",
2695 |     catchall: ZodNever.create(),
2696 |     typeName: ZodFirstPartyTypeKind.ZodObject,
2697 |     ...processCreateParams(params)
2698 |   });
2699 | };
2700 | ZodObject.lazycreate = (shape, params) => {
2701 |   return new ZodObject({
2702 |     shape,
2703 |     unknownKeys: "strip",
2704 |     catchall: ZodNever.create(),
2705 |     typeName: ZodFirstPartyTypeKind.ZodObject,
2706 |     ...processCreateParams(params)
2707 |   });
2708 | };
2709 | var ZodUnion = class extends ZodType {
2710 |   _parse(input) {
2711 |     const { ctx } = this._processInputParams(input);
2712 |     const options = this._def.options;
2713 |     function handleResults(results) {
2714 |       for (const result of results) {
2715 |         if (result.result.status === "valid") {
2716 |           return result.result;
2717 |         }
2718 |       }
2719 |       for (const result of results) {
2720 |         if (result.result.status === "dirty") {
2721 |           ctx.common.issues.push(...result.ctx.common.issues);
2722 |           return result.result;
2723 |         }
2724 |       }
2725 |       const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2726 |       addIssueToContext(ctx, {
2727 |         code: ZodIssueCode.invalid_union,
2728 |         unionErrors
2729 |       });
2730 |       return INVALID;
2731 |     }
2732 |     if (ctx.common.async) {
2733 |       return Promise.all(options.map(async (option) => {
2734 |         const childCtx = {
2735 |           ...ctx,
2736 |           common: {
2737 |             ...ctx.common,
2738 |             issues: []
2739 |           },
2740 |           parent: null
2741 |         };
2742 |         return {
2743 |           result: await option._parseAsync({
2744 |             data: ctx.data,
2745 |             path: ctx.path,
2746 |             parent: childCtx
2747 |           }),
2748 |           ctx: childCtx
2749 |         };
2750 |       })).then(handleResults);
2751 |     } else {
2752 |       let dirty = void 0;
2753 |       const issues = [];
2754 |       for (const option of options) {
2755 |         const childCtx = {
2756 |           ...ctx,
2757 |           common: {
2758 |             ...ctx.common,
2759 |             issues: []
2760 |           },
2761 |           parent: null
2762 |         };
2763 |         const result = option._parseSync({
2764 |           data: ctx.data,
2765 |           path: ctx.path,
2766 |           parent: childCtx
2767 |         });
2768 |         if (result.status === "valid") {
2769 |           return result;
2770 |         } else if (result.status === "dirty" && !dirty) {
2771 |           dirty = { result, ctx: childCtx };
2772 |         }
2773 |         if (childCtx.common.issues.length) {
2774 |           issues.push(childCtx.common.issues);
2775 |         }
2776 |       }
2777 |       if (dirty) {
2778 |         ctx.common.issues.push(...dirty.ctx.common.issues);
2779 |         return dirty.result;
2780 |       }
2781 |       const unionErrors = issues.map((issues2) => new ZodError(issues2));
2782 |       addIssueToContext(ctx, {
2783 |         code: ZodIssueCode.invalid_union,
2784 |         unionErrors
2785 |       });
2786 |       return INVALID;
2787 |     }
2788 |   }
2789 |   get options() {
2790 |     return this._def.options;
2791 |   }
2792 | };
2793 | ZodUnion.create = (types, params) => {
2794 |   return new ZodUnion({
2795 |     options: types,
2796 |     typeName: ZodFirstPartyTypeKind.ZodUnion,
2797 |     ...processCreateParams(params)
2798 |   });
2799 | };
2800 | var getDiscriminator = (type) => {
2801 |   if (type instanceof ZodLazy) {
2802 |     return getDiscriminator(type.schema);
2803 |   } else if (type instanceof ZodEffects) {
2804 |     return getDiscriminator(type.innerType());
2805 |   } else if (type instanceof ZodLiteral) {
2806 |     return [type.value];
2807 |   } else if (type instanceof ZodEnum) {
2808 |     return type.options;
2809 |   } else if (type instanceof ZodNativeEnum) {
2810 |     return util.objectValues(type.enum);
2811 |   } else if (type instanceof ZodDefault) {
2812 |     return getDiscriminator(type._def.innerType);
2813 |   } else if (type instanceof ZodUndefined) {
2814 |     return [void 0];
2815 |   } else if (type instanceof ZodNull) {
2816 |     return [null];
2817 |   } else if (type instanceof ZodOptional) {
2818 |     return [void 0, ...getDiscriminator(type.unwrap())];
2819 |   } else if (type instanceof ZodNullable) {
2820 |     return [null, ...getDiscriminator(type.unwrap())];
2821 |   } else if (type instanceof ZodBranded) {
2822 |     return getDiscriminator(type.unwrap());
2823 |   } else if (type instanceof ZodReadonly) {
2824 |     return getDiscriminator(type.unwrap());
2825 |   } else if (type instanceof ZodCatch) {
2826 |     return getDiscriminator(type._def.innerType);
2827 |   } else {
2828 |     return [];
2829 |   }
2830 | };
2831 | var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2832 |   _parse(input) {
2833 |     const { ctx } = this._processInputParams(input);
2834 |     if (ctx.parsedType !== ZodParsedType.object) {
2835 |       addIssueToContext(ctx, {
2836 |         code: ZodIssueCode.invalid_type,
2837 |         expected: ZodParsedType.object,
2838 |         received: ctx.parsedType
2839 |       });
2840 |       return INVALID;
2841 |     }
2842 |     const discriminator = this.discriminator;
2843 |     const discriminatorValue = ctx.data[discriminator];
2844 |     const option = this.optionsMap.get(discriminatorValue);
2845 |     if (!option) {
2846 |       addIssueToContext(ctx, {
2847 |         code: ZodIssueCode.invalid_union_discriminator,
2848 |         options: Array.from(this.optionsMap.keys()),
2849 |         path: [discriminator]
2850 |       });
2851 |       return INVALID;
2852 |     }
2853 |     if (ctx.common.async) {
2854 |       return option._parseAsync({
2855 |         data: ctx.data,
2856 |         path: ctx.path,
2857 |         parent: ctx
2858 |       });
2859 |     } else {
2860 |       return option._parseSync({
2861 |         data: ctx.data,
2862 |         path: ctx.path,
2863 |         parent: ctx
2864 |       });
2865 |     }
2866 |   }
2867 |   get discriminator() {
2868 |     return this._def.discriminator;
2869 |   }
2870 |   get options() {
2871 |     return this._def.options;
2872 |   }
2873 |   get optionsMap() {
2874 |     return this._def.optionsMap;
2875 |   }
2876 |   /**
2877 |    * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2878 |    * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2879 |    * have a different value for each object in the union.
2880 |    * @param discriminator the name of the discriminator property
2881 |    * @param types an array of object schemas
2882 |    * @param params
2883 |    */
2884 |   static create(discriminator, options, params) {
2885 |     const optionsMap = /* @__PURE__ */ new Map();
2886 |     for (const type of options) {
2887 |       const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2888 |       if (!discriminatorValues.length) {
2889 |         throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2890 |       }
2891 |       for (const value of discriminatorValues) {
2892 |         if (optionsMap.has(value)) {
2893 |           throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2894 |         }
2895 |         optionsMap.set(value, type);
2896 |       }
2897 |     }
2898 |     return new _ZodDiscriminatedUnion({
2899 |       typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2900 |       discriminator,
2901 |       options,
2902 |       optionsMap,
2903 |       ...processCreateParams(params)
2904 |     });
2905 |   }
2906 | };
2907 | function mergeValues(a, b) {
2908 |   const aType = getParsedType(a);
2909 |   const bType = getParsedType(b);
2910 |   if (a === b) {
2911 |     return { valid: true, data: a };
2912 |   } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2913 |     const bKeys = util.objectKeys(b);
2914 |     const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2915 |     const newObj = { ...a, ...b };
2916 |     for (const key of sharedKeys) {
2917 |       const sharedValue = mergeValues(a[key], b[key]);
2918 |       if (!sharedValue.valid) {
2919 |         return { valid: false };
2920 |       }
2921 |       newObj[key] = sharedValue.data;
2922 |     }
2923 |     return { valid: true, data: newObj };
2924 |   } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2925 |     if (a.length !== b.length) {
2926 |       return { valid: false };
2927 |     }
2928 |     const newArray = [];
2929 |     for (let index = 0; index < a.length; index++) {
2930 |       const itemA = a[index];
2931 |       const itemB = b[index];
2932 |       const sharedValue = mergeValues(itemA, itemB);
2933 |       if (!sharedValue.valid) {
2934 |         return { valid: false };
2935 |       }
2936 |       newArray.push(sharedValue.data);
2937 |     }
2938 |     return { valid: true, data: newArray };
2939 |   } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2940 |     return { valid: true, data: a };
2941 |   } else {
2942 |     return { valid: false };
2943 |   }
2944 | }
2945 | var ZodIntersection = class extends ZodType {
2946 |   _parse(input) {
2947 |     const { status, ctx } = this._processInputParams(input);
2948 |     const handleParsed = (parsedLeft, parsedRight) => {
2949 |       if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2950 |         return INVALID;
2951 |       }
2952 |       const merged = mergeValues(parsedLeft.value, parsedRight.value);
2953 |       if (!merged.valid) {
2954 |         addIssueToContext(ctx, {
2955 |           code: ZodIssueCode.invalid_intersection_types
2956 |         });
2957 |         return INVALID;
2958 |       }
2959 |       if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2960 |         status.dirty();
2961 |       }
2962 |       return { status: status.value, value: merged.data };
2963 |     };
2964 |     if (ctx.common.async) {
2965 |       return Promise.all([
2966 |         this._def.left._parseAsync({
2967 |           data: ctx.data,
2968 |           path: ctx.path,
2969 |           parent: ctx
2970 |         }),
2971 |         this._def.right._parseAsync({
2972 |           data: ctx.data,
2973 |           path: ctx.path,
2974 |           parent: ctx
2975 |         })
2976 |       ]).then(([left, right]) => handleParsed(left, right));
2977 |     } else {
2978 |       return handleParsed(this._def.left._parseSync({
2979 |         data: ctx.data,
2980 |         path: ctx.path,
2981 |         parent: ctx
2982 |       }), this._def.right._parseSync({
2983 |         data: ctx.data,
2984 |         path: ctx.path,
2985 |         parent: ctx
2986 |       }));
2987 |     }
2988 |   }
2989 | };
2990 | ZodIntersection.create = (left, right, params) => {
2991 |   return new ZodIntersection({
2992 |     left,
2993 |     right,
2994 |     typeName: ZodFirstPartyTypeKind.ZodIntersection,
2995 |     ...processCreateParams(params)
2996 |   });
2997 | };
2998 | var ZodTuple = class _ZodTuple extends ZodType {
2999 |   _parse(input) {
3000 |     const { status, ctx } = this._processInputParams(input);
3001 |     if (ctx.parsedType !== ZodParsedType.array) {
3002 |       addIssueToContext(ctx, {
3003 |         code: ZodIssueCode.invalid_type,
3004 |         expected: ZodParsedType.array,
3005 |         received: ctx.parsedType
3006 |       });
3007 |       return INVALID;
3008 |     }
3009 |     if (ctx.data.length < this._def.items.length) {
3010 |       addIssueToContext(ctx, {
3011 |         code: ZodIssueCode.too_small,
3012 |         minimum: this._def.items.length,
3013 |         inclusive: true,
3014 |         exact: false,
3015 |         type: "array"
3016 |       });
3017 |       return INVALID;
3018 |     }
3019 |     const rest = this._def.rest;
3020 |     if (!rest && ctx.data.length > this._def.items.length) {
3021 |       addIssueToContext(ctx, {
3022 |         code: ZodIssueCode.too_big,
3023 |         maximum: this._def.items.length,
3024 |         inclusive: true,
3025 |         exact: false,
3026 |         type: "array"
3027 |       });
3028 |       status.dirty();
3029 |     }
3030 |     const items = [...ctx.data].map((item, itemIndex) => {
3031 |       const schema = this._def.items[itemIndex] || this._def.rest;
3032 |       if (!schema)
3033 |         return null;
3034 |       return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3035 |     }).filter((x) => !!x);
3036 |     if (ctx.common.async) {
3037 |       return Promise.all(items).then((results) => {
3038 |         return ParseStatus.mergeArray(status, results);
3039 |       });
3040 |     } else {
3041 |       return ParseStatus.mergeArray(status, items);
3042 |     }
3043 |   }
3044 |   get items() {
3045 |     return this._def.items;
3046 |   }
3047 |   rest(rest) {
3048 |     return new _ZodTuple({
3049 |       ...this._def,
3050 |       rest
3051 |     });
3052 |   }
3053 | };
3054 | ZodTuple.create = (schemas, params) => {
3055 |   if (!Array.isArray(schemas)) {
3056 |     throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3057 |   }
3058 |   return new ZodTuple({
3059 |     items: schemas,
3060 |     typeName: ZodFirstPartyTypeKind.ZodTuple,
3061 |     rest: null,
3062 |     ...processCreateParams(params)
3063 |   });
3064 | };
3065 | var ZodRecord = class _ZodRecord extends ZodType {
3066 |   get keySchema() {
3067 |     return this._def.keyType;
3068 |   }
3069 |   get valueSchema() {
3070 |     return this._def.valueType;
3071 |   }
3072 |   _parse(input) {
3073 |     const { status, ctx } = this._processInputParams(input);
3074 |     if (ctx.parsedType !== ZodParsedType.object) {
3075 |       addIssueToContext(ctx, {
3076 |         code: ZodIssueCode.invalid_type,
3077 |         expected: ZodParsedType.object,
3078 |         received: ctx.parsedType
3079 |       });
3080 |       return INVALID;
3081 |     }
3082 |     const pairs = [];
3083 |     const keyType = this._def.keyType;
3084 |     const valueType = this._def.valueType;
3085 |     for (const key in ctx.data) {
3086 |       pairs.push({
3087 |         key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3088 |         value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3089 |         alwaysSet: key in ctx.data
3090 |       });
3091 |     }
3092 |     if (ctx.common.async) {
3093 |       return ParseStatus.mergeObjectAsync(status, pairs);
3094 |     } else {
3095 |       return ParseStatus.mergeObjectSync(status, pairs);
3096 |     }
3097 |   }
3098 |   get element() {
3099 |     return this._def.valueType;
3100 |   }
3101 |   static create(first, second, third) {
3102 |     if (second instanceof ZodType) {
3103 |       return new _ZodRecord({
3104 |         keyType: first,
3105 |         valueType: second,
3106 |         typeName: ZodFirstPartyTypeKind.ZodRecord,
3107 |         ...processCreateParams(third)
3108 |       });
3109 |     }
3110 |     return new _ZodRecord({
3111 |       keyType: ZodString.create(),
3112 |       valueType: first,
3113 |       typeName: ZodFirstPartyTypeKind.ZodRecord,
3114 |       ...processCreateParams(second)
3115 |     });
3116 |   }
3117 | };
3118 | var ZodMap = class extends ZodType {
3119 |   get keySchema() {
3120 |     return this._def.keyType;
3121 |   }
3122 |   get valueSchema() {
3123 |     return this._def.valueType;
3124 |   }
3125 |   _parse(input) {
3126 |     const { status, ctx } = this._processInputParams(input);
3127 |     if (ctx.parsedType !== ZodParsedType.map) {
3128 |       addIssueToContext(ctx, {
3129 |         code: ZodIssueCode.invalid_type,
3130 |         expected: ZodParsedType.map,
3131 |         received: ctx.parsedType
3132 |       });
3133 |       return INVALID;
3134 |     }
3135 |     const keyType = this._def.keyType;
3136 |     const valueType = this._def.valueType;
3137 |     const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3138 |       return {
3139 |         key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3140 |         value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3141 |       };
3142 |     });
3143 |     if (ctx.common.async) {
3144 |       const finalMap = /* @__PURE__ */ new Map();
3145 |       return Promise.resolve().then(async () => {
3146 |         for (const pair of pairs) {
3147 |           const key = await pair.key;
3148 |           const value = await pair.value;
3149 |           if (key.status === "aborted" || value.status === "aborted") {
3150 |             return INVALID;
3151 |           }
3152 |           if (key.status === "dirty" || value.status === "dirty") {
3153 |             status.dirty();
3154 |           }
3155 |           finalMap.set(key.value, value.value);
3156 |         }
3157 |         return { status: status.value, value: finalMap };
3158 |       });
3159 |     } else {
3160 |       const finalMap = /* @__PURE__ */ new Map();
3161 |       for (const pair of pairs) {
3162 |         const key = pair.key;
3163 |         const value = pair.value;
3164 |         if (key.status === "aborted" || value.status === "aborted") {
3165 |           return INVALID;
3166 |         }
3167 |         if (key.status === "dirty" || value.status === "dirty") {
3168 |           status.dirty();
3169 |         }
3170 |         finalMap.set(key.value, value.value);
3171 |       }
3172 |       return { status: status.value, value: finalMap };
3173 |     }
3174 |   }
3175 | };
3176 | ZodMap.create = (keyType, valueType, params) => {
3177 |   return new ZodMap({
3178 |     valueType,
3179 |     keyType,
3180 |     typeName: ZodFirstPartyTypeKind.ZodMap,
3181 |     ...processCreateParams(params)
3182 |   });
3183 | };
3184 | var ZodSet = class _ZodSet extends ZodType {
3185 |   _parse(input) {
3186 |     const { status, ctx } = this._processInputParams(input);
3187 |     if (ctx.parsedType !== ZodParsedType.set) {
3188 |       addIssueToContext(ctx, {
3189 |         code: ZodIssueCode.invalid_type,
3190 |         expected: ZodParsedType.set,
3191 |         received: ctx.parsedType
3192 |       });
3193 |       return INVALID;
3194 |     }
3195 |     const def = this._def;
3196 |     if (def.minSize !== null) {
3197 |       if (ctx.data.size < def.minSize.value) {
3198 |         addIssueToContext(ctx, {
3199 |           code: ZodIssueCode.too_small,
3200 |           minimum: def.minSize.value,
3201 |           type: "set",
3202 |           inclusive: true,
3203 |           exact: false,
3204 |           message: def.minSize.message
3205 |         });
3206 |         status.dirty();
3207 |       }
3208 |     }
3209 |     if (def.maxSize !== null) {
3210 |       if (ctx.data.size > def.maxSize.value) {
3211 |         addIssueToContext(ctx, {
3212 |           code: ZodIssueCode.too_big,
3213 |           maximum: def.maxSize.value,
3214 |           type: "set",
3215 |           inclusive: true,
3216 |           exact: false,
3217 |           message: def.maxSize.message
3218 |         });
3219 |         status.dirty();
3220 |       }
3221 |     }
3222 |     const valueType = this._def.valueType;
3223 |     function finalizeSet(elements2) {
3224 |       const parsedSet = /* @__PURE__ */ new Set();
3225 |       for (const element of elements2) {
3226 |         if (element.status === "aborted")
3227 |           return INVALID;
3228 |         if (element.status === "dirty")
3229 |           status.dirty();
3230 |         parsedSet.add(element.value);
3231 |       }
3232 |       return { status: status.value, value: parsedSet };
3233 |     }
3234 |     const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3235 |     if (ctx.common.async) {
3236 |       return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3237 |     } else {
3238 |       return finalizeSet(elements);
3239 |     }
3240 |   }
3241 |   min(minSize, message) {
3242 |     return new _ZodSet({
3243 |       ...this._def,
3244 |       minSize: { value: minSize, message: errorUtil.toString(message) }
3245 |     });
3246 |   }
3247 |   max(maxSize, message) {
3248 |     return new _ZodSet({
3249 |       ...this._def,
3250 |       maxSize: { value: maxSize, message: errorUtil.toString(message) }
3251 |     });
3252 |   }
3253 |   size(size, message) {
3254 |     return this.min(size, message).max(size, message);
3255 |   }
3256 |   nonempty(message) {
3257 |     return this.min(1, message);
3258 |   }
3259 | };
3260 | ZodSet.create = (valueType, params) => {
3261 |   return new ZodSet({
3262 |     valueType,
3263 |     minSize: null,
3264 |     maxSize: null,
3265 |     typeName: ZodFirstPartyTypeKind.ZodSet,
3266 |     ...processCreateParams(params)
3267 |   });
3268 | };
3269 | var ZodFunction = class _ZodFunction extends ZodType {
3270 |   constructor() {
3271 |     super(...arguments);
3272 |     this.validate = this.implement;
3273 |   }
3274 |   _parse(input) {
3275 |     const { ctx } = this._processInputParams(input);
3276 |     if (ctx.parsedType !== ZodParsedType.function) {
3277 |       addIssueToContext(ctx, {
3278 |         code: ZodIssueCode.invalid_type,
3279 |         expected: ZodParsedType.function,
3280 |         received: ctx.parsedType
3281 |       });
3282 |       return INVALID;
3283 |     }
3284 |     function makeArgsIssue(args, error) {
3285 |       return makeIssue({
3286 |         data: args,
3287 |         path: ctx.path,
3288 |         errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3289 |         issueData: {
3290 |           code: ZodIssueCode.invalid_arguments,
3291 |           argumentsError: error
3292 |         }
3293 |       });
3294 |     }
3295 |     function makeReturnsIssue(returns, error) {
3296 |       return makeIssue({
3297 |         data: returns,
3298 |         path: ctx.path,
3299 |         errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3300 |         issueData: {
3301 |           code: ZodIssueCode.invalid_return_type,
3302 |           returnTypeError: error
3303 |         }
3304 |       });
3305 |     }
3306 |     const params = { errorMap: ctx.common.contextualErrorMap };
3307 |     const fn = ctx.data;
3308 |     if (this._def.returns instanceof ZodPromise) {
3309 |       const me = this;
3310 |       return OK(async function(...args) {
3311 |         const error = new ZodError([]);
3312 |         const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3313 |           error.addIssue(makeArgsIssue(args, e));
3314 |           throw error;
3315 |         });
3316 |         const result = await Reflect.apply(fn, this, parsedArgs);
3317 |         const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3318 |           error.addIssue(makeReturnsIssue(result, e));
3319 |           throw error;
3320 |         });
3321 |         return parsedReturns;
3322 |       });
3323 |     } else {
3324 |       const me = this;
3325 |       return OK(function(...args) {
3326 |         const parsedArgs = me._def.args.safeParse(args, params);
3327 |         if (!parsedArgs.success) {
3328 |           throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3329 |         }
3330 |         const result = Reflect.apply(fn, this, parsedArgs.data);
3331 |         const parsedReturns = me._def.returns.safeParse(result, params);
3332 |         if (!parsedReturns.success) {
3333 |           throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3334 |         }
3335 |         return parsedReturns.data;
3336 |       });
3337 |     }
3338 |   }
3339 |   parameters() {
3340 |     return this._def.args;
3341 |   }
3342 |   returnType() {
3343 |     return this._def.returns;
3344 |   }
3345 |   args(...items) {
3346 |     return new _ZodFunction({
3347 |       ...this._def,
3348 |       args: ZodTuple.create(items).rest(ZodUnknown.create())
3349 |     });
3350 |   }
3351 |   returns(returnType) {
3352 |     return new _ZodFunction({
3353 |       ...this._def,
3354 |       returns: returnType
3355 |     });
3356 |   }
3357 |   implement(func) {
3358 |     const validatedFunc = this.parse(func);
3359 |     return validatedFunc;
3360 |   }
3361 |   strictImplement(func) {
3362 |     const validatedFunc = this.parse(func);
3363 |     return validatedFunc;
3364 |   }
3365 |   static create(args, returns, params) {
3366 |     return new _ZodFunction({
3367 |       args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3368 |       returns: returns || ZodUnknown.create(),
3369 |       typeName: ZodFirstPartyTypeKind.ZodFunction,
3370 |       ...processCreateParams(params)
3371 |     });
3372 |   }
3373 | };
3374 | var ZodLazy = class extends ZodType {
3375 |   get schema() {
3376 |     return this._def.getter();
3377 |   }
3378 |   _parse(input) {
3379 |     const { ctx } = this._processInputParams(input);
3380 |     const lazySchema = this._def.getter();
3381 |     return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3382 |   }
3383 | };
3384 | ZodLazy.create = (getter, params) => {
3385 |   return new ZodLazy({
3386 |     getter,
3387 |     typeName: ZodFirstPartyTypeKind.ZodLazy,
3388 |     ...processCreateParams(params)
3389 |   });
3390 | };
3391 | var ZodLiteral = class extends ZodType {
3392 |   _parse(input) {
3393 |     if (input.data !== this._def.value) {
3394 |       const ctx = this._getOrReturnCtx(input);
3395 |       addIssueToContext(ctx, {
3396 |         received: ctx.data,
3397 |         code: ZodIssueCode.invalid_literal,
3398 |         expected: this._def.value
3399 |       });
3400 |       return INVALID;
3401 |     }
3402 |     return { status: "valid", value: input.data };
3403 |   }
3404 |   get value() {
3405 |     return this._def.value;
3406 |   }
3407 | };
3408 | ZodLiteral.create = (value, params) => {
3409 |   return new ZodLiteral({
3410 |     value,
3411 |     typeName: ZodFirstPartyTypeKind.ZodLiteral,
3412 |     ...processCreateParams(params)
3413 |   });
3414 | };
3415 | function createZodEnum(values, params) {
3416 |   return new ZodEnum({
3417 |     values,
3418 |     typeName: ZodFirstPartyTypeKind.ZodEnum,
3419 |     ...processCreateParams(params)
3420 |   });
3421 | }
3422 | var ZodEnum = class _ZodEnum extends ZodType {
3423 |   _parse(input) {
3424 |     if (typeof input.data !== "string") {
3425 |       const ctx = this._getOrReturnCtx(input);
3426 |       const expectedValues = this._def.values;
3427 |       addIssueToContext(ctx, {
3428 |         expected: util.joinValues(expectedValues),
3429 |         received: ctx.parsedType,
3430 |         code: ZodIssueCode.invalid_type
3431 |       });
3432 |       return INVALID;
3433 |     }
3434 |     if (!this._cache) {
3435 |       this._cache = new Set(this._def.values);
3436 |     }
3437 |     if (!this._cache.has(input.data)) {
3438 |       const ctx = this._getOrReturnCtx(input);
3439 |       const expectedValues = this._def.values;
3440 |       addIssueToContext(ctx, {
3441 |         received: ctx.data,
3442 |         code: ZodIssueCode.invalid_enum_value,
3443 |         options: expectedValues
3444 |       });
3445 |       return INVALID;
3446 |     }
3447 |     return OK(input.data);
3448 |   }
3449 |   get options() {
3450 |     return this._def.values;
3451 |   }
3452 |   get enum() {
3453 |     const enumValues = {};
3454 |     for (const val of this._def.values) {
3455 |       enumValues[val] = val;
3456 |     }
3457 |     return enumValues;
3458 |   }
3459 |   get Values() {
3460 |     const enumValues = {};
3461 |     for (const val of this._def.values) {
3462 |       enumValues[val] = val;
3463 |     }
3464 |     return enumValues;
3465 |   }
3466 |   get Enum() {
3467 |     const enumValues = {};
3468 |     for (const val of this._def.values) {
3469 |       enumValues[val] = val;
3470 |     }
3471 |     return enumValues;
3472 |   }
3473 |   extract(values, newDef = this._def) {
3474 |     return _ZodEnum.create(values, {
3475 |       ...this._def,
3476 |       ...newDef
3477 |     });
3478 |   }
3479 |   exclude(values, newDef = this._def) {
3480 |     return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3481 |       ...this._def,
3482 |       ...newDef
3483 |     });
3484 |   }
3485 | };
3486 | ZodEnum.create = createZodEnum;
3487 | var ZodNativeEnum = class extends ZodType {
3488 |   _parse(input) {
3489 |     const nativeEnumValues = util.getValidEnumValues(this._def.values);
3490 |     const ctx = this._getOrReturnCtx(input);
3491 |     if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3492 |       const expectedValues = util.objectValues(nativeEnumValues);
3493 |       addIssueToContext(ctx, {
3494 |         expected: util.joinValues(expectedValues),
3495 |         received: ctx.parsedType,
3496 |         code: ZodIssueCode.invalid_type
3497 |       });
3498 |       return INVALID;
3499 |     }
3500 |     if (!this._cache) {
3501 |       this._cache = new Set(util.getValidEnumValues(this._def.values));
3502 |     }
3503 |     if (!this._cache.has(input.data)) {
3504 |       const expectedValues = util.objectValues(nativeEnumValues);
3505 |       addIssueToContext(ctx, {
3506 |         received: ctx.data,
3507 |         code: ZodIssueCode.invalid_enum_value,
3508 |         options: expectedValues
3509 |       });
3510 |       return INVALID;
3511 |     }
3512 |     return OK(input.data);
3513 |   }
3514 |   get enum() {
3515 |     return this._def.values;
3516 |   }
3517 | };
3518 | ZodNativeEnum.create = (values, params) => {
3519 |   return new ZodNativeEnum({
3520 |     values,
3521 |     typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3522 |     ...processCreateParams(params)
3523 |   });
3524 | };
3525 | var ZodPromise = class extends ZodType {
3526 |   unwrap() {
3527 |     return this._def.type;
3528 |   }
3529 |   _parse(input) {
3530 |     const { ctx } = this._processInputParams(input);
3531 |     if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3532 |       addIssueToContext(ctx, {
3533 |         code: ZodIssueCode.invalid_type,
3534 |         expected: ZodParsedType.promise,
3535 |         received: ctx.parsedType
3536 |       });
3537 |       return INVALID;
3538 |     }
3539 |     const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3540 |     return OK(promisified.then((data) => {
3541 |       return this._def.type.parseAsync(data, {
3542 |         path: ctx.path,
3543 |         errorMap: ctx.common.contextualErrorMap
3544 |       });
3545 |     }));
3546 |   }
3547 | };
3548 | ZodPromise.create = (schema, params) => {
3549 |   return new ZodPromise({
3550 |     type: schema,
3551 |     typeName: ZodFirstPartyTypeKind.ZodPromise,
3552 |     ...processCreateParams(params)
3553 |   });
3554 | };
3555 | var ZodEffects = class extends ZodType {
3556 |   innerType() {
3557 |     return this._def.schema;
3558 |   }
3559 |   sourceType() {
3560 |     return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3561 |   }
3562 |   _parse(input) {
3563 |     const { status, ctx } = this._processInputParams(input);
3564 |     const effect = this._def.effect || null;
3565 |     const checkCtx = {
3566 |       addIssue: (arg) => {
3567 |         addIssueToContext(ctx, arg);
3568 |         if (arg.fatal) {
3569 |           status.abort();
3570 |         } else {
3571 |           status.dirty();
3572 |         }
3573 |       },
3574 |       get path() {
3575 |         return ctx.path;
3576 |       }
3577 |     };
3578 |     checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3579 |     if (effect.type === "preprocess") {
3580 |       const processed = effect.transform(ctx.data, checkCtx);
3581 |       if (ctx.common.async) {
3582 |         return Promise.resolve(processed).then(async (processed2) => {
3583 |           if (status.value === "aborted")
3584 |             return INVALID;
3585 |           const result = await this._def.schema._parseAsync({
3586 |             data: processed2,
3587 |             path: ctx.path,
3588 |             parent: ctx
3589 |           });
3590 |           if (result.status === "aborted")
3591 |             return INVALID;
3592 |           if (result.status === "dirty")
3593 |             return DIRTY(result.value);
3594 |           if (status.value === "dirty")
3595 |             return DIRTY(result.value);
3596 |           return result;
3597 |         });
3598 |       } else {
3599 |         if (status.value === "aborted")
3600 |           return INVALID;
3601 |         const result = this._def.schema._parseSync({
3602 |           data: processed,
3603 |           path: ctx.path,
3604 |           parent: ctx
3605 |         });
3606 |         if (result.status === "aborted")
3607 |           return INVALID;
3608 |         if (result.status === "dirty")
3609 |           return DIRTY(result.value);
3610 |         if (status.value === "dirty")
3611 |           return DIRTY(result.value);
3612 |         return result;
3613 |       }
3614 |     }
3615 |     if (effect.type === "refinement") {
3616 |       const executeRefinement = (acc) => {
3617 |         const result = effect.refinement(acc, checkCtx);
3618 |         if (ctx.common.async) {
3619 |           return Promise.resolve(result);
3620 |         }
3621 |         if (result instanceof Promise) {
3622 |           throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3623 |         }
3624 |         return acc;
3625 |       };
3626 |       if (ctx.common.async === false) {
3627 |         const inner = this._def.schema._parseSync({
3628 |           data: ctx.data,
3629 |           path: ctx.path,
3630 |           parent: ctx
3631 |         });
3632 |         if (inner.status === "aborted")
3633 |           return INVALID;
3634 |         if (inner.status === "dirty")
3635 |           status.dirty();
3636 |         executeRefinement(inner.value);
3637 |         return { status: status.value, value: inner.value };
3638 |       } else {
3639 |         return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3640 |           if (inner.status === "aborted")
3641 |             return INVALID;
3642 |           if (inner.status === "dirty")
3643 |             status.dirty();
3644 |           return executeRefinement(inner.value).then(() => {
3645 |             return { status: status.value, value: inner.value };
3646 |           });
3647 |         });
3648 |       }
3649 |     }
3650 |     if (effect.type === "transform") {
3651 |       if (ctx.common.async === false) {
3652 |         const base = this._def.schema._parseSync({
3653 |           data: ctx.data,
3654 |           path: ctx.path,
3655 |           parent: ctx
3656 |         });
3657 |         if (!isValid(base))
3658 |           return INVALID;
3659 |         const result = effect.transform(base.value, checkCtx);
3660 |         if (result instanceof Promise) {
3661 |           throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3662 |         }
3663 |         return { status: status.value, value: result };
3664 |       } else {
3665 |         return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3666 |           if (!isValid(base))
3667 |             return INVALID;
3668 |           return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3669 |             status: status.value,
3670 |             value: result
3671 |           }));
3672 |         });
3673 |       }
3674 |     }
3675 |     util.assertNever(effect);
3676 |   }
3677 | };
3678 | ZodEffects.create = (schema, effect, params) => {
3679 |   return new ZodEffects({
3680 |     schema,
3681 |     typeName: ZodFirstPartyTypeKind.ZodEffects,
3682 |     effect,
3683 |     ...processCreateParams(params)
3684 |   });
3685 | };
3686 | ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3687 |   return new ZodEffects({
3688 |     schema,
3689 |     effect: { type: "preprocess", transform: preprocess },
3690 |     typeName: ZodFirstPartyTypeKind.ZodEffects,
3691 |     ...processCreateParams(params)
3692 |   });
3693 | };
3694 | var ZodOptional = class extends ZodType {
3695 |   _parse(input) {
3696 |     const parsedType = this._getType(input);
3697 |     if (parsedType === ZodParsedType.undefined) {
3698 |       return OK(void 0);
3699 |     }
3700 |     return this._def.innerType._parse(input);
3701 |   }
3702 |   unwrap() {
3703 |     return this._def.innerType;
3704 |   }
3705 | };
3706 | ZodOptional.create = (type, params) => {
3707 |   return new ZodOptional({
3708 |     innerType: type,
3709 |     typeName: ZodFirstPartyTypeKind.ZodOptional,
3710 |     ...processCreateParams(params)
3711 |   });
3712 | };
3713 | var ZodNullable = class extends ZodType {
3714 |   _parse(input) {
3715 |     const parsedType = this._getType(input);
3716 |     if (parsedType === ZodParsedType.null) {
3717 |       return OK(null);
3718 |     }
3719 |     return this._def.innerType._parse(input);
3720 |   }
3721 |   unwrap() {
3722 |     return this._def.innerType;
3723 |   }
3724 | };
3725 | ZodNullable.create = (type, params) => {
3726 |   return new ZodNullable({
3727 |     innerType: type,
3728 |     typeName: ZodFirstPartyTypeKind.ZodNullable,
3729 |     ...processCreateParams(params)
3730 |   });
3731 | };
3732 | var ZodDefault = class extends ZodType {
3733 |   _parse(input) {
3734 |     const { ctx } = this._processInputParams(input);
3735 |     let data = ctx.data;
3736 |     if (ctx.parsedType === ZodParsedType.undefined) {
3737 |       data = this._def.defaultValue();
3738 |     }
3739 |     return this._def.innerType._parse({
3740 |       data,
3741 |       path: ctx.path,
3742 |       parent: ctx
3743 |     });
3744 |   }
3745 |   removeDefault() {
3746 |     return this._def.innerType;
3747 |   }
3748 | };
3749 | ZodDefault.create = (type, params) => {
3750 |   return new ZodDefault({
3751 |     innerType: type,
3752 |     typeName: ZodFirstPartyTypeKind.ZodDefault,
3753 |     defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3754 |     ...processCreateParams(params)
3755 |   });
3756 | };
3757 | var ZodCatch = class extends ZodType {
3758 |   _parse(input) {
3759 |     const { ctx } = this._processInputParams(input);
3760 |     const newCtx = {
3761 |       ...ctx,
3762 |       common: {
3763 |         ...ctx.common,
3764 |         issues: []
3765 |       }
3766 |     };
3767 |     const result = this._def.innerType._parse({
3768 |       data: newCtx.data,
3769 |       path: newCtx.path,
3770 |       parent: {
3771 |         ...newCtx
3772 |       }
3773 |     });
3774 |     if (isAsync(result)) {
3775 |       return result.then((result2) => {
3776 |         return {
3777 |           status: "valid",
3778 |           value: result2.status === "valid" ? result2.value : this._def.catchValue({
3779 |             get error() {
3780 |               return new ZodError(newCtx.common.issues);
3781 |             },
3782 |             input: newCtx.data
3783 |           })
3784 |         };
3785 |       });
3786 |     } else {
3787 |       return {
3788 |         status: "valid",
3789 |         value: result.status === "valid" ? result.value : this._def.catchValue({
3790 |           get error() {
3791 |             return new ZodError(newCtx.common.issues);
3792 |           },
3793 |           input: newCtx.data
3794 |         })
3795 |       };
3796 |     }
3797 |   }
3798 |   removeCatch() {
3799 |     return this._def.innerType;
3800 |   }
3801 | };
3802 | ZodCatch.create = (type, params) => {
3803 |   return new ZodCatch({
3804 |     innerType: type,
3805 |     typeName: ZodFirstPartyTypeKind.ZodCatch,
3806 |     catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3807 |     ...processCreateParams(params)
3808 |   });
3809 | };
3810 | var ZodNaN = class extends ZodType {
3811 |   _parse(input) {
3812 |     const parsedType = this._getType(input);
3813 |     if (parsedType !== ZodParsedType.nan) {
3814 |       const ctx = this._getOrReturnCtx(input);
3815 |       addIssueToContext(ctx, {
3816 |         code: ZodIssueCode.invalid_type,
3817 |         expected: ZodParsedType.nan,
3818 |         received: ctx.parsedType
3819 |       });
3820 |       return INVALID;
3821 |     }
3822 |     return { status: "valid", value: input.data };
3823 |   }
3824 | };
3825 | ZodNaN.create = (params) => {
3826 |   return new ZodNaN({
3827 |     typeName: ZodFirstPartyTypeKind.ZodNaN,
3828 |     ...processCreateParams(params)
3829 |   });
3830 | };
3831 | var BRAND = Symbol("zod_brand");
3832 | var ZodBranded = class extends ZodType {
3833 |   _parse(input) {
3834 |     const { ctx } = this._processInputParams(input);
3835 |     const data = ctx.data;
3836 |     return this._def.type._parse({
3837 |       data,
3838 |       path: ctx.path,
3839 |       parent: ctx
3840 |     });
3841 |   }
3842 |   unwrap() {
3843 |     return this._def.type;
3844 |   }
3845 | };
3846 | var ZodPipeline = class _ZodPipeline extends ZodType {
3847 |   _parse(input) {
3848 |     const { status, ctx } = this._processInputParams(input);
3849 |     if (ctx.common.async) {
3850 |       const handleAsync = async () => {
3851 |         const inResult = await this._def.in._parseAsync({
3852 |           data: ctx.data,
3853 |           path: ctx.path,
3854 |           parent: ctx
3855 |         });
3856 |         if (inResult.status === "aborted")
3857 |           return INVALID;
3858 |         if (inResult.status === "dirty") {
3859 |           status.dirty();
3860 |           return DIRTY(inResult.value);
3861 |         } else {
3862 |           return this._def.out._parseAsync({
3863 |             data: inResult.value,
3864 |             path: ctx.path,
3865 |             parent: ctx
3866 |           });
3867 |         }
3868 |       };
3869 |       return handleAsync();
3870 |     } else {
3871 |       const inResult = this._def.in._parseSync({
3872 |         data: ctx.data,
3873 |         path: ctx.path,
3874 |         parent: ctx
3875 |       });
3876 |       if (inResult.status === "aborted")
3877 |         return INVALID;
3878 |       if (inResult.status === "dirty") {
3879 |         status.dirty();
3880 |         return {
3881 |           status: "dirty",
3882 |           value: inResult.value
3883 |         };
3884 |       } else {
3885 |         return this._def.out._parseSync({
3886 |           data: inResult.value,
3887 |           path: ctx.path,
3888 |           parent: ctx
3889 |         });
3890 |       }
3891 |     }
3892 |   }
3893 |   static create(a, b) {
3894 |     return new _ZodPipeline({
3895 |       in: a,
3896 |       out: b,
3897 |       typeName: ZodFirstPartyTypeKind.ZodPipeline
3898 |     });
3899 |   }
3900 | };
3901 | var ZodReadonly = class extends ZodType {
3902 |   _parse(input) {
3903 |     const result = this._def.innerType._parse(input);
3904 |     const freeze = (data) => {
3905 |       if (isValid(data)) {
3906 |         data.value = Object.freeze(data.value);
3907 |       }
3908 |       return data;
3909 |     };
3910 |     return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3911 |   }
3912 |   unwrap() {
3913 |     return this._def.innerType;
3914 |   }
3915 | };
3916 | ZodReadonly.create = (type, params) => {
3917 |   return new ZodReadonly({
3918 |     innerType: type,
3919 |     typeName: ZodFirstPartyTypeKind.ZodReadonly,
3920 |     ...processCreateParams(params)
3921 |   });
3922 | };
3923 | function cleanParams(params, data) {
3924 |   const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3925 |   const p2 = typeof p === "string" ? { message: p } : p;
3926 |   return p2;
3927 | }
3928 | function custom(check, _params = {}, fatal) {
3929 |   if (check)
3930 |     return ZodAny.create().superRefine((data, ctx) => {
3931 |       const r = check(data);
3932 |       if (r instanceof Promise) {
3933 |         return r.then((r2) => {
3934 |           if (!r2) {
3935 |             const params = cleanParams(_params, data);
3936 |             const _fatal = params.fatal ?? fatal ?? true;
3937 |             ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3938 |           }
3939 |         });
3940 |       }
3941 |       if (!r) {
3942 |         const params = cleanParams(_params, data);
3943 |         const _fatal = params.fatal ?? fatal ?? true;
3944 |         ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3945 |       }
3946 |       return;
3947 |     });
3948 |   return ZodAny.create();
3949 | }
3950 | var late = {
3951 |   object: ZodObject.lazycreate
3952 | };
3953 | var ZodFirstPartyTypeKind;
3954 | (function(ZodFirstPartyTypeKind2) {
3955 |   ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3956 |   ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3957 |   ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3958 |   ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3959 |   ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3960 |   ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3961 |   ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3962 |   ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3963 |   ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3964 |   ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3965 |   ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3966 |   ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3967 |   ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3968 |   ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3969 |   ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3970 |   ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3971 |   ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3972 |   ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3973 |   ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3974 |   ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3975 |   ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3976 |   ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3977 |   ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3978 |   ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3979 |   ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3980 |   ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3981 |   ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3982 |   ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3983 |   ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3984 |   ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3985 |   ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3986 |   ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3987 |   ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3988 |   ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3989 |   ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3990 |   ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
3991 | })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3992 | var instanceOfType = (cls, params = {
3993 |   message: `Input not instance of ${cls.name}`
3994 | }) => custom((data) => data instanceof cls, params);
3995 | var stringType = ZodString.create;
3996 | var numberType = ZodNumber.create;
3997 | var nanType = ZodNaN.create;
3998 | var bigIntType = ZodBigInt.create;
3999 | var booleanType = ZodBoolean.create;
4000 | var dateType = ZodDate.create;
4001 | var symbolType = ZodSymbol.create;
4002 | var undefinedType = ZodUndefined.create;
4003 | var nullType = ZodNull.create;
4004 | var anyType = ZodAny.create;
4005 | var unknownType = ZodUnknown.create;
4006 | var neverType = ZodNever.create;
4007 | var voidType = ZodVoid.create;
4008 | var arrayType = ZodArray.create;
4009 | var objectType = ZodObject.create;
4010 | var strictObjectType = ZodObject.strictCreate;
4011 | var unionType = ZodUnion.create;
4012 | var discriminatedUnionType = ZodDiscriminatedUnion.create;
4013 | var intersectionType = ZodIntersection.create;
4014 | var tupleType = ZodTuple.create;
4015 | var recordType = ZodRecord.create;
4016 | var mapType = ZodMap.create;
4017 | var setType = ZodSet.create;
4018 | var functionType = ZodFunction.create;
4019 | var lazyType = ZodLazy.create;
4020 | var literalType = ZodLiteral.create;
4021 | var enumType = ZodEnum.create;
4022 | var nativeEnumType = ZodNativeEnum.create;
4023 | var promiseType = ZodPromise.create;
4024 | var effectsType = ZodEffects.create;
4025 | var optionalType = ZodOptional.create;
4026 | var nullableType = ZodNullable.create;
4027 | var preprocessType = ZodEffects.createWithPreprocess;
4028 | var pipelineType = ZodPipeline.create;
4029 | var ostring = () => stringType().optional();
4030 | var onumber = () => numberType().optional();
4031 | var oboolean = () => booleanType().optional();
4032 | var coerce = {
4033 |   string: (arg) => ZodString.create({ ...arg, coerce: true }),
4034 |   number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4035 |   boolean: (arg) => ZodBoolean.create({
4036 |     ...arg,
4037 |     coerce: true
4038 |   }),
4039 |   bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4040 |   date: (arg) => ZodDate.create({ ...arg, coerce: true })
4041 | };
4042 | var NEVER = INVALID;
4043 | 
4044 | // node_modules/@modelcontextprotocol/sdk/dist/types.js
4045 | var LATEST_PROTOCOL_VERSION = "2024-11-05";
4046 | var SUPPORTED_PROTOCOL_VERSIONS = [
4047 |   LATEST_PROTOCOL_VERSION,
4048 |   "2024-10-07"
4049 | ];
4050 | var JSONRPC_VERSION = "2.0";
4051 | var ProgressTokenSchema = external_exports.union([external_exports.string(), external_exports.number().int()]);
4052 | var CursorSchema = external_exports.string();
4053 | var BaseRequestParamsSchema = external_exports.object({
4054 |   _meta: external_exports.optional(external_exports.object({
4055 |     /**
4056 |      * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
4057 |      */
4058 |     progressToken: external_exports.optional(ProgressTokenSchema)
4059 |   }).passthrough())
4060 | }).passthrough();
4061 | var RequestSchema = external_exports.object({
4062 |   method: external_exports.string(),
4063 |   params: external_exports.optional(BaseRequestParamsSchema)
4064 | });
4065 | var BaseNotificationParamsSchema = external_exports.object({
4066 |   /**
4067 |    * This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.
4068 |    */
4069 |   _meta: external_exports.optional(external_exports.object({}).passthrough())
4070 | }).passthrough();
4071 | var NotificationSchema = external_exports.object({
4072 |   method: external_exports.string(),
4073 |   params: external_exports.optional(BaseNotificationParamsSchema)
4074 | });
4075 | var ResultSchema = external_exports.object({
4076 |   /**
4077 |    * This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.
4078 |    */
4079 |   _meta: external_exports.optional(external_exports.object({}).passthrough())
4080 | }).passthrough();
4081 | var RequestIdSchema = external_exports.union([external_exports.string(), external_exports.number().int()]);
4082 | var JSONRPCRequestSchema = external_exports.object({
4083 |   jsonrpc: external_exports.literal(JSONRPC_VERSION),
4084 |   id: RequestIdSchema
4085 | }).merge(RequestSchema).strict();
4086 | var JSONRPCNotificationSchema = external_exports.object({
4087 |   jsonrpc: external_exports.literal(JSONRPC_VERSION)
4088 | }).merge(NotificationSchema).strict();
4089 | var JSONRPCResponseSchema = external_exports.object({
4090 |   jsonrpc: external_exports.literal(JSONRPC_VERSION),
4091 |   id: RequestIdSchema,
4092 |   result: ResultSchema
4093 | }).strict();
4094 | var ErrorCode;
4095 | (function(ErrorCode2) {
4096 |   ErrorCode2[ErrorCode2["ConnectionClosed"] = -1] = "ConnectionClosed";
4097 |   ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
4098 |   ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
4099 |   ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
4100 |   ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
4101 |   ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
4102 | })(ErrorCode || (ErrorCode = {}));
4103 | var JSONRPCErrorSchema = external_exports.object({
4104 |   jsonrpc: external_exports.literal(JSONRPC_VERSION),
4105 |   id: RequestIdSchema,
4106 |   error: external_exports.object({
4107 |     /**
4108 |      * The error type that occurred.
4109 |      */
4110 |     code: external_exports.number().int(),
4111 |     /**
4112 |      * A short description of the error. The message SHOULD be limited to a concise single sentence.
4113 |      */
4114 |     message: external_exports.string(),
4115 |     /**
4116 |      * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
4117 |      */
4118 |     data: external_exports.optional(external_exports.unknown())
4119 |   })
4120 | }).strict();
4121 | var JSONRPCMessageSchema = external_exports.union([
4122 |   JSONRPCRequestSchema,
4123 |   JSONRPCNotificationSchema,
4124 |   JSONRPCResponseSchema,
4125 |   JSONRPCErrorSchema
4126 | ]);
4127 | var EmptyResultSchema = ResultSchema.strict();
4128 | var CancelledNotificationSchema = NotificationSchema.extend({
4129 |   method: external_exports.literal("notifications/cancelled"),
4130 |   params: BaseNotificationParamsSchema.extend({
4131 |     /**
4132 |      * The ID of the request to cancel.
4133 |      *
4134 |      * This MUST correspond to the ID of a request previously issued in the same direction.
4135 |      */
4136 |     requestId: RequestIdSchema,
4137 |     /**
4138 |      * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
4139 |      */
4140 |     reason: external_exports.string().optional()
4141 |   })
4142 | });
4143 | var ImplementationSchema = external_exports.object({
4144 |   name: external_exports.string(),
4145 |   version: external_exports.string()
4146 | }).passthrough();
4147 | var ClientCapabilitiesSchema = external_exports.object({
4148 |   /**
4149 |    * Experimental, non-standard capabilities that the client supports.
4150 |    */
4151 |   experimental: external_exports.optional(external_exports.object({}).passthrough()),
4152 |   /**
4153 |    * Present if the client supports sampling from an LLM.
4154 |    */
4155 |   sampling: external_exports.optional(external_exports.object({}).passthrough()),
4156 |   /**
4157 |    * Present if the client supports listing roots.
4158 |    */
4159 |   roots: external_exports.optional(external_exports.object({
4160 |     /**
4161 |      * Whether the client supports issuing notifications for changes to the roots list.
4162 |      */
4163 |     listChanged: external_exports.optional(external_exports.boolean())
4164 |   }).passthrough())
4165 | }).passthrough();
4166 | var InitializeRequestSchema = RequestSchema.extend({
4167 |   method: external_exports.literal("initialize"),
4168 |   params: BaseRequestParamsSchema.extend({
4169 |     /**
4170 |      * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
4171 |      */
4172 |     protocolVersion: external_exports.string(),
4173 |     capabilities: ClientCapabilitiesSchema,
4174 |     clientInfo: ImplementationSchema
4175 |   })
4176 | });
4177 | var ServerCapabilitiesSchema = external_exports.object({
4178 |   /**
4179 |    * Experimental, non-standard capabilities that the server supports.
4180 |    */
4181 |   experimental: external_exports.optional(external_exports.object({}).passthrough()),
4182 |   /**
4183 |    * Present if the server supports sending log messages to the client.
4184 |    */
4185 |   logging: external_exports.optional(external_exports.object({}).passthrough()),
4186 |   /**
4187 |    * Present if the server offers any prompt templates.
4188 |    */
4189 |   prompts: external_exports.optional(external_exports.object({
4190 |     /**
4191 |      * Whether this server supports issuing notifications for changes to the prompt list.
4192 |      */
4193 |     listChanged: external_exports.optional(external_exports.boolean())
4194 |   }).passthrough()),
4195 |   /**
4196 |    * Present if the server offers any resources to read.
4197 |    */
4198 |   resources: external_exports.optional(external_exports.object({
4199 |     /**
4200 |      * Whether this server supports clients subscribing to resource updates.
4201 |      */
4202 |     subscribe: external_exports.optional(external_exports.boolean()),
4203 |     /**
4204 |      * Whether this server supports issuing notifications for changes to the resource list.
4205 |      */
4206 |     listChanged: external_exports.optional(external_exports.boolean())
4207 |   }).passthrough()),
4208 |   /**
4209 |    * Present if the server offers any tools to call.
4210 |    */
4211 |   tools: external_exports.optional(external_exports.object({
4212 |     /**
4213 |      * Whether this server supports issuing notifications for changes to the tool list.
4214 |      */
4215 |     listChanged: external_exports.optional(external_exports.boolean())
4216 |   }).passthrough())
4217 | }).passthrough();
4218 | var InitializeResultSchema = ResultSchema.extend({
4219 |   /**
4220 |    * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
4221 |    */
4222 |   protocolVersion: external_exports.string(),
4223 |   capabilities: ServerCapabilitiesSchema,
4224 |   serverInfo: ImplementationSchema
4225 | });
4226 | var InitializedNotificationSchema = NotificationSchema.extend({
4227 |   method: external_exports.literal("notifications/initialized")
4228 | });
4229 | var PingRequestSchema = RequestSchema.extend({
4230 |   method: external_exports.literal("ping")
4231 | });
4232 | var ProgressSchema = external_exports.object({
4233 |   /**
4234 |    * The progress thus far. This should increase every time progress is made, even if the total is unknown.
4235 |    */
4236 |   progress: external_exports.number(),
4237 |   /**
4238 |    * Total number of items to process (or total progress required), if known.
4239 |    */
4240 |   total: external_exports.optional(external_exports.number())
4241 | }).passthrough();
4242 | var ProgressNotificationSchema = NotificationSchema.extend({
4243 |   method: external_exports.literal("notifications/progress"),
4244 |   params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
4245 |     /**
4246 |      * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
4247 |      */
4248 |     progressToken: ProgressTokenSchema
4249 |   })
4250 | });
4251 | var PaginatedRequestSchema = RequestSchema.extend({
4252 |   params: BaseRequestParamsSchema.extend({
4253 |     /**
4254 |      * An opaque token representing the current pagination position.
4255 |      * If provided, the server should return results starting after this cursor.
4256 |      */
4257 |     cursor: external_exports.optional(CursorSchema)
4258 |   }).optional()
4259 | });
4260 | var PaginatedResultSchema = ResultSchema.extend({
4261 |   /**
4262 |    * An opaque token representing the pagination position after the last returned result.
4263 |    * If present, there may be more results available.
4264 |    */
4265 |   nextCursor: external_exports.optional(CursorSchema)
4266 | });
4267 | var ResourceContentsSchema = external_exports.object({
4268 |   /**
4269 |    * The URI of this resource.
4270 |    */
4271 |   uri: external_exports.string(),
4272 |   /**
4273 |    * The MIME type of this resource, if known.
4274 |    */
4275 |   mimeType: external_exports.optional(external_exports.string())
4276 | }).passthrough();
4277 | var TextResourceContentsSchema = ResourceContentsSchema.extend({
4278 |   /**
4279 |    * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
4280 |    */
4281 |   text: external_exports.string()
4282 | });
4283 | var BlobResourceContentsSchema = ResourceContentsSchema.extend({
4284 |   /**
4285 |    * A base64-encoded string representing the binary data of the item.
4286 |    */
4287 |   blob: external_exports.string().base64()
4288 | });
4289 | var ResourceSchema = external_exports.object({
4290 |   /**
4291 |    * The URI of this resource.
4292 |    */
4293 |   uri: external_exports.string(),
4294 |   /**
4295 |    * A human-readable name for this resource.
4296 |    *
4297 |    * This can be used by clients to populate UI elements.
4298 |    */
4299 |   name: external_exports.string(),
4300 |   /**
4301 |    * A description of what this resource represents.
4302 |    *
4303 |    * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
4304 |    */
4305 |   description: external_exports.optional(external_exports.string()),
4306 |   /**
4307 |    * The MIME type of this resource, if known.
4308 |    */
4309 |   mimeType: external_exports.optional(external_exports.string())
4310 | }).passthrough();
4311 | var ResourceTemplateSchema = external_exports.object({
4312 |   /**
4313 |    * A URI template (according to RFC 6570) that can be used to construct resource URIs.
4314 |    */
4315 |   uriTemplate: external_exports.string(),
4316 |   /**
4317 |    * A human-readable name for the type of resource this template refers to.
4318 |    *
4319 |    * This can be used by clients to populate UI elements.
4320 |    */
4321 |   name: external_exports.string(),
4322 |   /**
4323 |    * A description of what this template is for.
4324 |    *
4325 |    * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
4326 |    */
4327 |   description: external_exports.optional(external_exports.string()),
4328 |   /**
4329 |    * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
4330 |    */
4331 |   mimeType: external_exports.optional(external_exports.string())
4332 | }).passthrough();
4333 | var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
4334 |   method: external_exports.literal("resources/list")
4335 | });
4336 | var ListResourcesResultSchema = PaginatedResultSchema.extend({
4337 |   resources: external_exports.array(ResourceSchema)
4338 | });
4339 | var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
4340 |   method: external_exports.literal("resources/templates/list")
4341 | });
4342 | var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
4343 |   resourceTemplates: external_exports.array(ResourceTemplateSchema)
4344 | });
4345 | var ReadResourceRequestSchema = RequestSchema.extend({
4346 |   method: external_exports.literal("resources/read"),
4347 |   params: BaseRequestParamsSchema.extend({
4348 |     /**
4349 |      * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
4350 |      */
4351 |     uri: external_exports.string()
4352 |   })
4353 | });
4354 | var ReadResourceResultSchema = ResultSchema.extend({
4355 |   contents: external_exports.array(external_exports.union([TextResourceContentsSchema, BlobResourceContentsSchema]))
4356 | });
4357 | var ResourceListChangedNotificationSchema = NotificationSchema.extend({
4358 |   method: external_exports.literal("notifications/resources/list_changed")
4359 | });
4360 | var SubscribeRequestSchema = RequestSchema.extend({
4361 |   method: external_exports.literal("resources/subscribe"),
4362 |   params: BaseRequestParamsSchema.extend({
4363 |     /**
4364 |      * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
4365 |      */
4366 |     uri: external_exports.string()
4367 |   })
4368 | });
4369 | var UnsubscribeRequestSchema = RequestSchema.extend({
4370 |   method: external_exports.literal("resources/unsubscribe"),
4371 |   params: BaseRequestParamsSchema.extend({
4372 |     /**
4373 |      * The URI of the resource to unsubscribe from.
4374 |      */
4375 |     uri: external_exports.string()
4376 |   })
4377 | });
4378 | var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
4379 |   method: external_exports.literal("notifications/resources/updated"),
4380 |   params: BaseNotificationParamsSchema.extend({
4381 |     /**
4382 |      * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
4383 |      */
4384 |     uri: external_exports.string()
4385 |   })
4386 | });
4387 | var PromptArgumentSchema = external_exports.object({
4388 |   /**
4389 |    * The name of the argument.
4390 |    */
4391 |   name: external_exports.string(),
4392 |   /**
4393 |    * A human-readable description of the argument.
4394 |    */
4395 |   description: external_exports.optional(external_exports.string()),
4396 |   /**
4397 |    * Whether this argument must be provided.
4398 |    */
4399 |   required: external_exports.optional(external_exports.boolean())
4400 | }).passthrough();
4401 | var PromptSchema = external_exports.object({
4402 |   /**
4403 |    * The name of the prompt or prompt template.
4404 |    */
4405 |   name: external_exports.string(),
4406 |   /**
4407 |    * An optional description of what this prompt provides
4408 |    */
4409 |   description: external_exports.optional(external_exports.string()),
4410 |   /**
4411 |    * A list of arguments to use for templating the prompt.
4412 |    */
4413 |   arguments: external_exports.optional(external_exports.array(PromptArgumentSchema))
4414 | }).passthrough();
4415 | var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
4416 |   method: external_exports.literal("prompts/list")
4417 | });
4418 | var ListPromptsResultSchema = PaginatedResultSchema.extend({
4419 |   prompts: external_exports.array(PromptSchema)
4420 | });
4421 | var GetPromptRequestSchema = RequestSchema.extend({
4422 |   method: external_exports.literal("prompts/get"),
4423 |   params: BaseRequestParamsSchema.extend({
4424 |     /**
4425 |      * The name of the prompt or prompt template.
4426 |      */
4427 |     name: external_exports.string(),
4428 |     /**
4429 |      * Arguments to use for templating the prompt.
4430 |      */
4431 |     arguments: external_exports.optional(external_exports.record(external_exports.string()))
4432 |   })
4433 | });
4434 | var TextContentSchema = external_exports.object({
4435 |   type: external_exports.literal("text"),
4436 |   /**
4437 |    * The text content of the message.
4438 |    */
4439 |   text: external_exports.string()
4440 | }).passthrough();
4441 | var ImageContentSchema = external_exports.object({
4442 |   type: external_exports.literal("image"),
4443 |   /**
4444 |    * The base64-encoded image data.
4445 |    */
4446 |   data: external_exports.string().base64(),
4447 |   /**
4448 |    * The MIME type of the image. Different providers may support different image types.
4449 |    */
4450 |   mimeType: external_exports.string()
4451 | }).passthrough();
4452 | var EmbeddedResourceSchema = external_exports.object({
4453 |   type: external_exports.literal("resource"),
4454 |   resource: external_exports.union([TextResourceContentsSchema, BlobResourceContentsSchema])
4455 | }).passthrough();
4456 | var PromptMessageSchema = external_exports.object({
4457 |   role: external_exports.enum(["user", "assistant"]),
4458 |   content: external_exports.union([
4459 |     TextContentSchema,
4460 |     ImageContentSchema,
4461 |     EmbeddedResourceSchema
4462 |   ])
4463 | }).passthrough();
4464 | var GetPromptResultSchema = ResultSchema.extend({
4465 |   /**
4466 |    * An optional description for the prompt.
4467 |    */
4468 |   description: external_exports.optional(external_exports.string()),
4469 |   messages: external_exports.array(PromptMessageSchema)
4470 | });
4471 | var PromptListChangedNotificationSchema = NotificationSchema.extend({
4472 |   method: external_exports.literal("notifications/prompts/list_changed")
4473 | });
4474 | var ToolSchema = external_exports.object({
4475 |   /**
4476 |    * The name of the tool.
4477 |    */
4478 |   name: external_exports.string(),
4479 |   /**
4480 |    * A human-readable description of the tool.
4481 |    */
4482 |   description: external_exports.optional(external_exports.string()),
4483 |   /**
4484 |    * A JSON Schema object defining the expected parameters for the tool.
4485 |    */
4486 |   inputSchema: external_exports.object({
4487 |     type: external_exports.literal("object"),
4488 |     properties: external_exports.optional(external_exports.object({}).passthrough())
4489 |   }).passthrough()
4490 | }).passthrough();
4491 | var ListToolsRequestSchema = PaginatedRequestSchema.extend({
4492 |   method: external_exports.literal("tools/list")
4493 | });
4494 | var ListToolsResultSchema = PaginatedResultSchema.extend({
4495 |   tools: external_exports.array(ToolSchema)
4496 | });
4497 | var CallToolResultSchema = ResultSchema.extend({
4498 |   content: external_exports.array(external_exports.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])),
4499 |   isError: external_exports.boolean().default(false).optional()
4500 | });
4501 | var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
4502 |   toolResult: external_exports.unknown()
4503 | }));
4504 | var CallToolRequestSchema = RequestSchema.extend({
4505 |   method: external_exports.literal("tools/call"),
4506 |   params: BaseRequestParamsSchema.extend({
4507 |     name: external_exports.string(),
4508 |     arguments: external_exports.optional(external_exports.record(external_exports.unknown()))
4509 |   })
4510 | });
4511 | var ToolListChangedNotificationSchema = NotificationSchema.extend({
4512 |   method: external_exports.literal("notifications/tools/list_changed")
4513 | });
4514 | var LoggingLevelSchema = external_exports.enum([
4515 |   "debug",
4516 |   "info",
4517 |   "notice",
4518 |   "warning",
4519 |   "error",
4520 |   "critical",
4521 |   "alert",
4522 |   "emergency"
4523 | ]);
4524 | var SetLevelRequestSchema = RequestSchema.extend({
4525 |   method: external_exports.literal("logging/setLevel"),
4526 |   params: BaseRequestParamsSchema.extend({
4527 |     /**
4528 |      * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
4529 |      */
4530 |     level: LoggingLevelSchema
4531 |   })
4532 | });
4533 | var LoggingMessageNotificationSchema = NotificationSchema.extend({
4534 |   method: external_exports.literal("notifications/message"),
4535 |   params: BaseNotificationParamsSchema.extend({
4536 |     /**
4537 |      * The severity of this log message.
4538 |      */
4539 |     level: LoggingLevelSchema,
4540 |     /**
4541 |      * An optional name of the logger issuing this message.
4542 |      */
4543 |     logger: external_exports.optional(external_exports.string()),
4544 |     /**
4545 |      * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
4546 |      */
4547 |     data: external_exports.unknown()
4548 |   })
4549 | });
4550 | var ModelHintSchema = external_exports.object({
4551 |   /**
4552 |    * A hint for a model name.
4553 |    */
4554 |   name: external_exports.string().optional()
4555 | }).passthrough();
4556 | var ModelPreferencesSchema = external_exports.object({
4557 |   /**
4558 |    * Optional hints to use for model selection.
4559 |    */
4560 |   hints: external_exports.optional(external_exports.array(ModelHintSchema)),
4561 |   /**
4562 |    * How much to prioritize cost when selecting a model.
4563 |    */
4564 |   costPriority: external_exports.optional(external_exports.number().min(0).max(1)),
4565 |   /**
4566 |    * How much to prioritize sampling speed (latency) when selecting a model.
4567 |    */
4568 |   speedPriority: external_exports.optional(external_exports.number().min(0).max(1)),
4569 |   /**
4570 |    * How much to prioritize intelligence and capabilities when selecting a model.
4571 |    */
4572 |   intelligencePriority: external_exports.optional(external_exports.number().min(0).max(1))
4573 | }).passthrough();
4574 | var SamplingMessageSchema = external_exports.object({
4575 |   role: external_exports.enum(["user", "assistant"]),
4576 |   content: external_exports.union([TextContentSchema, ImageContentSchema])
4577 | }).passthrough();
4578 | var CreateMessageRequestSchema = RequestSchema.extend({
4579 |   method: external_exports.literal("sampling/createMessage"),
4580 |   params: BaseRequestParamsSchema.extend({
4581 |     messages: external_exports.array(SamplingMessageSchema),
4582 |     /**
4583 |      * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
4584 |      */
4585 |     systemPrompt: external_exports.optional(external_exports.string()),
4586 |     /**
4587 |      * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.
4588 |      */
4589 |     includeContext: external_exports.optional(external_exports.enum(["none", "thisServer", "allServers"])),
4590 |     temperature: external_exports.optional(external_exports.number()),
4591 |     /**
4592 |      * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
4593 |      */
4594 |     maxTokens: external_exports.number().int(),
4595 |     stopSequences: external_exports.optional(external_exports.array(external_exports.string())),
4596 |     /**
4597 |      * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
4598 |      */
4599 |     metadata: external_exports.optional(external_exports.object({}).passthrough()),
4600 |     /**
4601 |      * The server's preferences for which model to select.
4602 |      */
4603 |     modelPreferences: external_exports.optional(ModelPreferencesSchema)
4604 |   })
4605 | });
4606 | var CreateMessageResultSchema = ResultSchema.extend({
4607 |   /**
4608 |    * The name of the model that generated the message.
4609 |    */
4610 |   model: external_exports.string(),
4611 |   /**
4612 |    * The reason why sampling stopped.
4613 |    */
4614 |   stopReason: external_exports.optional(external_exports.enum(["endTurn", "stopSequence", "maxTokens"]).or(external_exports.string())),
4615 |   role: external_exports.enum(["user", "assistant"]),
4616 |   content: external_exports.discriminatedUnion("type", [
4617 |     TextContentSchema,
4618 |     ImageContentSchema
4619 |   ])
4620 | });
4621 | var ResourceReferenceSchema = external_exports.object({
4622 |   type: external_exports.literal("ref/resource"),
4623 |   /**
4624 |    * The URI or URI template of the resource.
4625 |    */
4626 |   uri: external_exports.string()
4627 | }).passthrough();
4628 | var PromptReferenceSchema = external_exports.object({
4629 |   type: external_exports.literal("ref/prompt"),
4630 |   /**
4631 |    * The name of the prompt or prompt template
4632 |    */
4633 |   name: external_exports.string()
4634 | }).passthrough();
4635 | var CompleteRequestSchema = RequestSchema.extend({
4636 |   method: external_exports.literal("completion/complete"),
4637 |   params: BaseRequestParamsSchema.extend({
4638 |     ref: external_exports.union([PromptReferenceSchema, ResourceReferenceSchema]),
4639 |     /**
4640 |      * The argument's information
4641 |      */
4642 |     argument: external_exports.object({
4643 |       /**
4644 |        * The name of the argument
4645 |        */
4646 |       name: external_exports.string(),
4647 |       /**
4648 |        * The value of the argument to use for completion matching.
4649 |        */
4650 |       value: external_exports.string()
4651 |     }).passthrough()
4652 |   })
4653 | });
4654 | var CompleteResultSchema = ResultSchema.extend({
4655 |   completion: external_exports.object({
4656 |     /**
4657 |      * An array of completion values. Must not exceed 100 items.
4658 |      */
4659 |     values: external_exports.array(external_exports.string()).max(100),
4660 |     /**
4661 |      * The total number of completion options available. This can exceed the number of values actually sent in the response.
4662 |      */
4663 |     total: external_exports.optional(external_exports.number().int()),
4664 |     /**
4665 |      * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
4666 |      */
4667 |     hasMore: external_exports.optional(external_exports.boolean())
4668 |   }).passthrough()
4669 | });
4670 | var RootSchema = external_exports.object({
4671 |   /**
4672 |    * The URI identifying the root. This *must* start with file:// for now.
4673 |    */
4674 |   uri: external_exports.string().startsWith("file://"),
4675 |   /**
4676 |    * An optional name for the root.
4677 |    */
4678 |   name: external_exports.optional(external_exports.string())
4679 | }).passthrough();
4680 | var ListRootsRequestSchema = RequestSchema.extend({
4681 |   method: external_exports.literal("roots/list")
4682 | });
4683 | var ListRootsResultSchema = ResultSchema.extend({
4684 |   roots: external_exports.array(RootSchema)
4685 | });
4686 | var RootsListChangedNotificationSchema = NotificationSchema.extend({
4687 |   method: external_exports.literal("notifications/roots/list_changed")
4688 | });
4689 | var ClientRequestSchema = external_exports.union([
4690 |   PingRequestSchema,
4691 |   InitializeRequestSchema,
4692 |   CompleteRequestSchema,
4693 |   SetLevelRequestSchema,
4694 |   GetPromptRequestSchema,
4695 |   ListPromptsRequestSchema,
4696 |   ListResourcesRequestSchema,
4697 |   ListResourceTemplatesRequestSchema,
4698 |   ReadResourceRequestSchema,
4699 |   SubscribeRequestSchema,
4700 |   UnsubscribeRequestSchema,
4701 |   CallToolRequestSchema,
4702 |   ListToolsRequestSchema
4703 | ]);
4704 | var ClientNotificationSchema = external_exports.union([
4705 |   CancelledNotificationSchema,
4706 |   ProgressNotificationSchema,
4707 |   InitializedNotificationSchema,
4708 |   RootsListChangedNotificationSchema
4709 | ]);
4710 | var ClientResultSchema = external_exports.union([
4711 |   EmptyResultSchema,
4712 |   CreateMessageResultSchema,
4713 |   ListRootsResultSchema
4714 | ]);
4715 | var ServerRequestSchema = external_exports.union([
4716 |   PingRequestSchema,
4717 |   CreateMessageRequestSchema,
4718 |   ListRootsRequestSchema
4719 | ]);
4720 | var ServerNotificationSchema = external_exports.union([
4721 |   CancelledNotificationSchema,
4722 |   ProgressNotificationSchema,
4723 |   LoggingMessageNotificationSchema,
4724 |   ResourceUpdatedNotificationSchema,
4725 |   ResourceListChangedNotificationSchema,
4726 |   ToolListChangedNotificationSchema,
4727 |   PromptListChangedNotificationSchema
4728 | ]);
4729 | var ServerResultSchema = external_exports.union([
4730 |   EmptyResultSchema,
4731 |   InitializeResultSchema,
4732 |   CompleteResultSchema,
4733 |   GetPromptResultSchema,
4734 |   ListPromptsResultSchema,
4735 |   ListResourcesResultSchema,
4736 |   ListResourceTemplatesResultSchema,
4737 |   ReadResourceResultSchema,
4738 |   CallToolResultSchema,
4739 |   ListToolsResultSchema
4740 | ]);
4741 | var McpError = class extends Error {
4742 |   constructor(code, message, data) {
4743 |     super(`MCP error ${code}: ${message}`);
4744 |     this.code = code;
4745 |     this.data = data;
4746 |   }
4747 | };
4748 | 
4749 | // node_modules/@modelcontextprotocol/sdk/dist/shared/protocol.js
4750 | var Protocol = class {
4751 |   constructor(_options) {
4752 |     this._options = _options;
4753 |     this._requestMessageId = 0;
4754 |     this._requestHandlers = /* @__PURE__ */ new Map();
4755 |     this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
4756 |     this._notificationHandlers = /* @__PURE__ */ new Map();
4757 |     this._responseHandlers = /* @__PURE__ */ new Map();
4758 |     this._progressHandlers = /* @__PURE__ */ new Map();
4759 |     this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
4760 |       const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
4761 |       controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
4762 |     });
4763 |     this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
4764 |       this._onprogress(notification);
4765 |     });
4766 |     this.setRequestHandler(
4767 |       PingRequestSchema,
4768 |       // Automatic pong by default.
4769 |       (_request) => ({})
4770 |     );
4771 |   }
4772 |   /**
4773 |    * Attaches to the given transport, starts it, and starts listening for messages.
4774 |    *
4775 |    * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
4776 |    */
4777 |   async connect(transport) {
4778 |     this._transport = transport;
4779 |     this._transport.onclose = () => {
4780 |       this._onclose();
4781 |     };
4782 |     this._transport.onerror = (error) => {
4783 |       this._onerror(error);
4784 |     };
4785 |     this._transport.onmessage = (message) => {
4786 |       if (!("method" in message)) {
4787 |         this._onresponse(message);
4788 |       } else if ("id" in message) {
4789 |         this._onrequest(message);
4790 |       } else {
4791 |         this._onnotification(message);
4792 |       }
4793 |     };
4794 |     await this._transport.start();
4795 |   }
4796 |   _onclose() {
4797 |     var _a;
4798 |     const responseHandlers = this._responseHandlers;
4799 |     this._responseHandlers = /* @__PURE__ */ new Map();
4800 |     this._progressHandlers.clear();
4801 |     this._transport = void 0;
4802 |     (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
4803 |     const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed");
4804 |     for (const handler of responseHandlers.values()) {
4805 |       handler(error);
4806 |     }
4807 |   }
4808 |   _onerror(error) {
4809 |     var _a;
4810 |     (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);
4811 |   }
4812 |   _onnotification(notification) {
4813 |     var _a;
4814 |     const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== void 0 ? _a : this.fallbackNotificationHandler;
4815 |     if (handler === void 0) {
4816 |       return;
4817 |     }
4818 |     Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
4819 |   }
4820 |   _onrequest(request) {
4821 |     var _a, _b;
4822 |     const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler;
4823 |     if (handler === void 0) {
4824 |       (_b = this._transport) === null || _b === void 0 ? void 0 : _b.send({
4825 |         jsonrpc: "2.0",
4826 |         id: request.id,
4827 |         error: {
4828 |           code: ErrorCode.MethodNotFound,
4829 |           message: "Method not found"
4830 |         }
4831 |       }).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
4832 |       return;
4833 |     }
4834 |     const abortController = new AbortController();
4835 |     this._requestHandlerAbortControllers.set(request.id, abortController);
4836 |     Promise.resolve().then(() => handler(request, { signal: abortController.signal })).then((result) => {
4837 |       var _a2;
4838 |       if (abortController.signal.aborted) {
4839 |         return;
4840 |       }
4841 |       return (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send({
4842 |         result,
4843 |         jsonrpc: "2.0",
4844 |         id: request.id
4845 |       });
4846 |     }, (error) => {
4847 |       var _a2, _b2;
4848 |       if (abortController.signal.aborted) {
4849 |         return;
4850 |       }
4851 |       return (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send({
4852 |         jsonrpc: "2.0",
4853 |         id: request.id,
4854 |         error: {
4855 |           code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
4856 |           message: (_b2 = error.message) !== null && _b2 !== void 0 ? _b2 : "Internal error"
4857 |         }
4858 |       });
4859 |     }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
4860 |       this._requestHandlerAbortControllers.delete(request.id);
4861 |     });
4862 |   }
4863 |   _onprogress(notification) {
4864 |     const { progress, total, progressToken } = notification.params;
4865 |     const handler = this._progressHandlers.get(Number(progressToken));
4866 |     if (handler === void 0) {
4867 |       this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
4868 |       return;
4869 |     }
4870 |     handler({ progress, total });
4871 |   }
4872 |   _onresponse(response) {
4873 |     const messageId = response.id;
4874 |     const handler = this._responseHandlers.get(Number(messageId));
4875 |     if (handler === void 0) {
4876 |       this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
4877 |       return;
4878 |     }
4879 |     this._responseHandlers.delete(Number(messageId));
4880 |     this._progressHandlers.delete(Number(messageId));
4881 |     if ("result" in response) {
4882 |       handler(response);
4883 |     } else {
4884 |       const error = new McpError(response.error.code, response.error.message, response.error.data);
4885 |       handler(error);
4886 |     }
4887 |   }
4888 |   get transport() {
4889 |     return this._transport;
4890 |   }
4891 |   /**
4892 |    * Closes the connection.
4893 |    */
4894 |   async close() {
4895 |     var _a;
4896 |     await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close());
4897 |   }
4898 |   /**
4899 |    * Sends a request and wait for a response.
4900 |    *
4901 |    * Do not use this method to emit notifications! Use notification() instead.
4902 |    */
4903 |   request(request, resultSchema, options) {
4904 |     return new Promise((resolve, reject) => {
4905 |       var _a, _b, _c;
4906 |       if (!this._transport) {
4907 |         reject(new Error("Not connected"));
4908 |         return;
4909 |       }
4910 |       if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) {
4911 |         this.assertCapabilityForMethod(request.method);
4912 |       }
4913 |       (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted();
4914 |       const messageId = this._requestMessageId++;
4915 |       const jsonrpcRequest = {
4916 |         ...request,
4917 |         jsonrpc: "2.0",
4918 |         id: messageId
4919 |       };
4920 |       if (options === null || options === void 0 ? void 0 : options.onprogress) {
4921 |         this._progressHandlers.set(messageId, options.onprogress);
4922 |         jsonrpcRequest.params = {
4923 |           ...request.params,
4924 |           _meta: { progressToken: messageId }
4925 |         };
4926 |       }
4927 |       this._responseHandlers.set(messageId, (response) => {
4928 |         var _a2;
4929 |         if ((_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.aborted) {
4930 |           return;
4931 |         }
4932 |         if (response instanceof Error) {
4933 |           return reject(response);
4934 |         }
4935 |         try {
4936 |           const result = resultSchema.parse(response.result);
4937 |           resolve(result);
4938 |         } catch (error) {
4939 |           reject(error);
4940 |         }
4941 |       });
4942 |       (_c = options === null || options === void 0 ? void 0 : options.signal) === null || _c === void 0 ? void 0 : _c.addEventListener("abort", () => {
4943 |         var _a2, _b2;
4944 |         const reason = (_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.reason;
4945 |         this._responseHandlers.delete(messageId);
4946 |         this._progressHandlers.delete(messageId);
4947 |         (_b2 = this._transport) === null || _b2 === void 0 ? void 0 : _b2.send({
4948 |           jsonrpc: "2.0",
4949 |           method: "cancelled",
4950 |           params: {
4951 |             requestId: messageId,
4952 |             reason: String(reason)
4953 |           }
4954 |         });
4955 |         reject(reason);
4956 |       });
4957 |       this._transport.send(jsonrpcRequest).catch(reject);
4958 |     });
4959 |   }
4960 |   /**
4961 |    * Emits a notification, which is a one-way message that does not expect a response.
4962 |    */
4963 |   async notification(notification) {
4964 |     if (!this._transport) {
4965 |       throw new Error("Not connected");
4966 |     }
4967 |     this.assertNotificationCapability(notification.method);
4968 |     const jsonrpcNotification = {
4969 |       ...notification,
4970 |       jsonrpc: "2.0"
4971 |     };
4972 |     await this._transport.send(jsonrpcNotification);
4973 |   }
4974 |   /**
4975 |    * Registers a handler to invoke when this protocol object receives a request with the given method.
4976 |    *
4977 |    * Note that this will replace any previous request handler for the same method.
4978 |    */
4979 |   setRequestHandler(requestSchema, handler) {
4980 |     const method = requestSchema.shape.method.value;
4981 |     this.assertRequestHandlerCapability(method);
4982 |     this._requestHandlers.set(method, (request, extra) => Promise.resolve(handler(requestSchema.parse(request), extra)));
4983 |   }
4984 |   /**
4985 |    * Removes the request handler for the given method.
4986 |    */
4987 |   removeRequestHandler(method) {
4988 |     this._requestHandlers.delete(method);
4989 |   }
4990 |   /**
4991 |    * Registers a handler to invoke when this protocol object receives a notification with the given method.
4992 |    *
4993 |    * Note that this will replace any previous notification handler for the same method.
4994 |    */
4995 |   setNotificationHandler(notificationSchema, handler) {
4996 |     this._notificationHandlers.set(notificationSchema.shape.method.value, (notification) => Promise.resolve(handler(notificationSchema.parse(notification))));
4997 |   }
4998 |   /**
4999 |    * Removes the notification handler for the given method.
5000 |    */
5001 |   removeNotificationHandler(method) {
5002 |     this._notificationHandlers.delete(method);
5003 |   }
5004 | };
5005 | 
5006 | // node_modules/@modelcontextprotocol/sdk/dist/server/index.js
5007 | var Server = class extends Protocol {
5008 |   /**
5009 |    * Initializes this server with the given name and version information.
5010 |    */
5011 |   constructor(_serverInfo, options) {
5012 |     super(options);
5013 |     this._serverInfo = _serverInfo;
5014 |     this._capabilities = options.capabilities;
5015 |     this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
5016 |     this.setNotificationHandler(InitializedNotificationSchema, () => {
5017 |       var _a;
5018 |       return (_a = this.oninitialized) === null || _a === void 0 ? void 0 : _a.call(this);
5019 |     });
5020 |   }
5021 |   assertCapabilityForMethod(method) {
5022 |     var _a, _b;
5023 |     switch (method) {
5024 |       case "sampling/createMessage":
5025 |         if (!((_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.sampling)) {
5026 |           throw new Error(`Client does not support sampling (required for ${method})`);
5027 |         }
5028 |         break;
5029 |       case "roots/list":
5030 |         if (!((_b = this._clientCapabilities) === null || _b === void 0 ? void 0 : _b.roots)) {
5031 |           throw new Error(`Client does not support listing roots (required for ${method})`);
5032 |         }
5033 |         break;
5034 |       case "ping":
5035 |         break;
5036 |     }
5037 |   }
5038 |   assertNotificationCapability(method) {
5039 |     switch (method) {
5040 |       case "notifications/message":
5041 |         if (!this._capabilities.logging) {
5042 |           throw new Error(`Server does not support logging (required for ${method})`);
5043 |         }
5044 |         break;
5045 |       case "notifications/resources/updated":
5046 |       case "notifications/resources/list_changed":
5047 |         if (!this._capabilities.resources) {
5048 |           throw new Error(`Server does not support notifying about resources (required for ${method})`);
5049 |         }
5050 |         break;
5051 |       case "notifications/tools/list_changed":
5052 |         if (!this._capabilities.tools) {
5053 |           throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
5054 |         }
5055 |         break;
5056 |       case "notifications/prompts/list_changed":
5057 |         if (!this._capabilities.prompts) {
5058 |           throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
5059 |         }
5060 |         break;
5061 |       case "notifications/cancelled":
5062 |         break;
5063 |       case "notifications/progress":
5064 |         break;
5065 |     }
5066 |   }
5067 |   assertRequestHandlerCapability(method) {
5068 |     switch (method) {
5069 |       case "sampling/createMessage":
5070 |         if (!this._capabilities.sampling) {
5071 |           throw new Error(`Server does not support sampling (required for ${method})`);
5072 |         }
5073 |         break;
5074 |       case "logging/setLevel":
5075 |         if (!this._capabilities.logging) {
5076 |           throw new Error(`Server does not support logging (required for ${method})`);
5077 |         }
5078 |         break;
5079 |       case "prompts/get":
5080 |       case "prompts/list":
5081 |         if (!this._capabilities.prompts) {
5082 |           throw new Error(`Server does not support prompts (required for ${method})`);
5083 |         }
5084 |         break;
5085 |       case "resources/list":
5086 |       case "resources/templates/list":
5087 |       case "resources/read":
5088 |         if (!this._capabilities.resources) {
5089 |           throw new Error(`Server does not support resources (required for ${method})`);
5090 |         }
5091 |         break;
5092 |       case "tools/call":
5093 |       case "tools/list":
5094 |         if (!this._capabilities.tools) {
5095 |           throw new Error(`Server does not support tools (required for ${method})`);
5096 |         }
5097 |         break;
5098 |       case "ping":
5099 |       case "initialize":
5100 |         break;
5101 |     }
5102 |   }
5103 |   async _oninitialize(request) {
5104 |     const requestedVersion = request.params.protocolVersion;
5105 |     this._clientCapabilities = request.params.capabilities;
5106 |     this._clientVersion = request.params.clientInfo;
5107 |     return {
5108 |       protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION,
5109 |       capabilities: this.getCapabilities(),
5110 |       serverInfo: this._serverInfo
5111 |     };
5112 |   }
5113 |   /**
5114 |    * After initialization has completed, this will be populated with the client's reported capabilities.
5115 |    */
5116 |   getClientCapabilities() {
5117 |     return this._clientCapabilities;
5118 |   }
5119 |   /**
5120 |    * After initialization has completed, this will be populated with information about the client's name and version.
5121 |    */
5122 |   getClientVersion() {
5123 |     return this._clientVersion;
5124 |   }
5125 |   getCapabilities() {
5126 |     return this._capabilities;
5127 |   }
5128 |   async ping() {
5129 |     return this.request({ method: "ping" }, EmptyResultSchema);
5130 |   }
5131 |   async createMessage(params, options) {
5132 |     return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);
5133 |   }
5134 |   async listRoots(params, options) {
5135 |     return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);
5136 |   }
5137 |   async sendLoggingMessage(params) {
5138 |     return this.notification({ method: "notifications/message", params });
5139 |   }
5140 |   async sendResourceUpdated(params) {
5141 |     return this.notification({
5142 |       method: "notifications/resources/updated",
5143 |       params
5144 |     });
5145 |   }
5146 |   async sendResourceListChanged() {
5147 |     return this.notification({
5148 |       method: "notifications/resources/list_changed"
5149 |     });
5150 |   }
5151 |   async sendToolListChanged() {
5152 |     return this.notification({ method: "notifications/tools/list_changed" });
5153 |   }
5154 |   async sendPromptListChanged() {
5155 |     return this.notification({ method: "notifications/prompts/list_changed" });
5156 |   }
5157 | };
5158 | 
5159 | // node_modules/@modelcontextprotocol/sdk/dist/server/stdio.js
5160 | import process2 from "node:process";
5161 | 
5162 | // node_modules/@modelcontextprotocol/sdk/dist/shared/stdio.js
5163 | var ReadBuffer = class {
5164 |   append(chunk) {
5165 |     this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
5166 |   }
5167 |   readMessage() {
5168 |     if (!this._buffer) {
5169 |       return null;
5170 |     }
5171 |     const index = this._buffer.indexOf("\n");
5172 |     if (index === -1) {
5173 |       return null;
5174 |     }
5175 |     const line = this._buffer.toString("utf8", 0, index);
5176 |     this._buffer = this._buffer.subarray(index + 1);
5177 |     return deserializeMessage(line);
5178 |   }
5179 |   clear() {
5180 |     this._buffer = void 0;
5181 |   }
5182 | };
5183 | function deserializeMessage(line) {
5184 |   return JSONRPCMessageSchema.parse(JSON.parse(line));
5185 | }
5186 | function serializeMessage(message) {
5187 |   return JSON.stringify(message) + "\n";
5188 | }
5189 | 
5190 | // node_modules/@modelcontextprotocol/sdk/dist/server/stdio.js
5191 | var StdioServerTransport = class {
5192 |   constructor(_stdin = process2.stdin, _stdout = process2.stdout) {
5193 |     this._stdin = _stdin;
5194 |     this._stdout = _stdout;
5195 |     this._readBuffer = new ReadBuffer();
5196 |     this._started = false;
5197 |     this._ondata = (chunk) => {
5198 |       this._readBuffer.append(chunk);
5199 |       this.processReadBuffer();
5200 |     };
5201 |     this._onerror = (error) => {
5202 |       var _a;
5203 |       (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);
5204 |     };
5205 |   }
5206 |   /**
5207 |    * Starts listening for messages on stdin.
5208 |    */
5209 |   async start() {
5210 |     if (this._started) {
5211 |       throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
5212 |     }
5213 |     this._started = true;
5214 |     this._stdin.on("data", this._ondata);
5215 |     this._stdin.on("error", this._onerror);
5216 |   }
5217 |   processReadBuffer() {
5218 |     var _a, _b;
5219 |     while (true) {
5220 |       try {
5221 |         const message = this._readBuffer.readMessage();
5222 |         if (message === null) {
5223 |           break;
5224 |         }
5225 |         (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message);
5226 |       } catch (error) {
5227 |         (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error);
5228 |       }
5229 |     }
5230 |   }
5231 |   async close() {
5232 |     var _a;
5233 |     this._stdin.off("data", this._ondata);
5234 |     this._stdin.off("error", this._onerror);
5235 |     this._readBuffer.clear();
5236 |     (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
5237 |   }
5238 |   send(message) {
5239 |     return new Promise((resolve) => {
5240 |       const json = serializeMessage(message);
5241 |       if (this._stdout.write(json)) {
5242 |         resolve();
5243 |       } else {
5244 |         this._stdout.once("drain", resolve);
5245 |       }
5246 |     });
5247 |   }
5248 | };
5249 | 
5250 | // build/adapters/unity-http-adapter.js
5251 | var UnityHttpAdapter = class {
5252 |   constructor(options = {}) {
5253 |     this.url = options.url || "http://localhost:23457/";
5254 |     this.timeout = options.timeout || 15e3;
5255 |   }
5256 |   /**
5257 |    * Call a method on the Unity server
5258 |    */
5259 |   async call(method, params = {}) {
5260 |     const startTime = Date.now();
5261 |     console.error(`[Unity HTTP] Calling method: ${method}`);
5262 |     const maxRetries = 3;
5263 |     let lastError;
5264 |     for (let retry = 0; retry < maxRetries; retry++) {
5265 |       if (retry > 0) {
5266 |         console.error(`[Unity HTTP] Retry ${retry}/${maxRetries - 1} for method: ${method}`);
5267 |         await new Promise((resolve) => setTimeout(resolve, 1e3 * retry));
5268 |       }
5269 |       try {
5270 |         const controller = new AbortController();
5271 |         const timeoutId = setTimeout(() => {
5272 |           console.error(`[Unity HTTP] Request timeout after ${this.timeout}ms for method: ${method}`);
5273 |           controller.abort();
5274 |         }, this.timeout);
5275 |         const response = await fetch(this.url, {
5276 |           method: "POST",
5277 |           headers: {
5278 |             "Content-Type": "application/json; charset=utf-8",
5279 |             "Accept": "application/json; charset=utf-8"
5280 |           },
5281 |           body: JSON.stringify({ method, ...params }),
5282 |           signal: controller.signal
5283 |         });
5284 |         clearTimeout(timeoutId);
5285 |         const elapsed = Date.now() - startTime;
5286 |         console.error(`[Unity HTTP] Response received in ${elapsed}ms for method: ${method}`);
5287 |         const result = await response.json();
5288 |         if (!result.success) {
5289 |           throw new Error(result.error || "Unknown error");
5290 |         }
5291 |         return result.result;
5292 |       } catch (error) {
5293 |         lastError = error;
5294 |         if (error.name === "AbortError") {
5295 |           lastError = new Error("Request timeout");
5296 |         } else if (error.message?.includes("ECONNREFUSED")) {
5297 |           lastError = new Error("Unity HTTP server is not running");
5298 |         } else if (error.message?.includes("Failed to fetch")) {
5299 |           lastError = new Error("Failed to connect to Unity HTTP server");
5300 |         }
5301 |         console.error(`[Unity HTTP] Error on attempt ${retry + 1}: ${lastError.message}`);
5302 |         if (error.message?.includes("Method not found")) {
5303 |           throw error;
5304 |         }
5305 |       }
5306 |     }
5307 |     throw lastError || new Error("Unknown error after retries");
5308 |   }
5309 |   /**
5310 |    * Check if Unity server is connected
5311 |    */
5312 |   async isConnected() {
5313 |     try {
5314 |       await this.call("ping");
5315 |       return true;
5316 |     } catch {
5317 |       return false;
5318 |     }
5319 |   }
5320 |   // Script operations
5321 |   async createScript(fileName, content, folder) {
5322 |     return this.call("script/create", { fileName, content, folder });
5323 |   }
5324 |   async readScript(path3) {
5325 |     return this.call("script/read", { path: path3 });
5326 |   }
5327 |   async deleteScript(path3) {
5328 |     return this.call("script/delete", { path: path3 });
5329 |   }
5330 |   async applyDiff(path3, diff, options) {
5331 |     return this.call("script/applyDiff", { path: path3, diff, options });
5332 |   }
5333 |   // Shader operations
5334 |   async createShader(name, content, folder) {
5335 |     return this.call("shader/create", { name, content, folder });
5336 |   }
5337 |   async readShader(path3) {
5338 |     return this.call("shader/read", { path: path3 });
5339 |   }
5340 |   async deleteShader(path3) {
5341 |     return this.call("shader/delete", { path: path3 });
5342 |   }
5343 |   // Project operations
5344 |   async getProjectInfo() {
5345 |     return this.call("project/info");
5346 |   }
5347 |   // Folder operations
5348 |   async createFolder(path3) {
5349 |     return this.call("folder/create", { path: path3 });
5350 |   }
5351 |   async renameFolder(oldPath, newName) {
5352 |     return this.call("folder/rename", { oldPath, newName });
5353 |   }
5354 |   async moveFolder(sourcePath, targetPath) {
5355 |     return this.call("folder/move", { sourcePath, targetPath });
5356 |   }
5357 |   async deleteFolder(path3, recursive = true) {
5358 |     return this.call("folder/delete", { path: path3, recursive });
5359 |   }
5360 |   async listFolder(path3, recursive = false) {
5361 |     return this.call("folder/list", { path: path3, recursive });
5362 |   }
5363 | };
5364 | 
5365 | // build/services/unity-bridge-deploy-service.js
5366 | import * as fs2 from "fs/promises";
5367 | import * as path2 from "path";
5368 | 
5369 | // build/embedded-scripts.js
5370 | import * as fs from "fs/promises";
5371 | import * as path from "path";
5372 | var EmbeddedScriptsProvider = class {
5373 |   constructor() {
5374 |     this.scripts = /* @__PURE__ */ new Map();
5375 |     this.initializeScripts();
5376 |   }
5377 |   initializeScripts() {
5378 |     this.scripts.set("UnityHttpServer.cs", {
5379 |       fileName: "UnityHttpServer.cs",
5380 |       version: "1.1.0",
5381 |       content: `using System;
5382 | using System.Collections.Generic;
5383 | using System.IO;
5384 | using System.Linq;
5385 | using System.Net;
5386 | using System.Text;
5387 | using System.Threading;
5388 | using UnityEngine;
5389 | using UnityEditor;
5390 | using Newtonsoft.Json;
5391 | using Newtonsoft.Json.Linq;
5392 | 
5393 | namespace UnityMCP
5394 | {
5395 |     [InitializeOnLoad]
5396 |     public static class UnityMCPInstaller
5397 |     {
5398 |         static UnityMCPInstaller()
5399 |         {
5400 |             CheckAndUpdateScripts();
5401 |         }
5402 |         
5403 |         static void CheckAndUpdateScripts()
5404 |         {
5405 |             var installedVersion = EditorPrefs.GetString(UnityHttpServer.VERSION_META_KEY, "0.0.0");
5406 |             if (installedVersion != UnityHttpServer.SCRIPT_VERSION)
5407 |             {
5408 |                 Debug.Log($"[UnityMCP] Updating Unity MCP scripts from version {installedVersion} to {UnityHttpServer.SCRIPT_VERSION}");
5409 |                 // Version update logic will be handled by the MCP server
5410 |                 EditorPrefs.SetString(UnityHttpServer.VERSION_META_KEY, UnityHttpServer.SCRIPT_VERSION);
5411 |             }
5412 |         }
5413 |     }
5414 |     /// <summary>
5415 |     /// Simple HTTP server for Unity MCP integration
5416 |     /// </summary>
5417 |     public static class UnityHttpServer
5418 |     {
5419 |         // Version information for auto-update
5420 |         public const string SCRIPT_VERSION = "1.1.0";
5421 |         public const string VERSION_META_KEY = "UnityMCP.InstalledVersion";
5422 |         
5423 |         // Configuration constants
5424 |         private const int DEFAULT_PORT = 23457;
5425 |         private const int REQUEST_TIMEOUT_MS = 120000; // 2 minutes
5426 |         private const int THREAD_JOIN_TIMEOUT_MS = 1000; // 1 second
5427 |         private const int ASSET_REFRESH_DELAY_MS = 500; // Wait after asset operations
5428 |         public const string SERVER_LOG_PREFIX = "[UnityMCP]";
5429 |         private const string PREFS_PORT_KEY = "UnityMCP.ServerPort";
5430 |         private const string PREFS_PORT_BEFORE_PLAY_KEY = "UnityMCP.ServerPortBeforePlay";
5431 |         
5432 |         // File path constants
5433 |         private const string ASSETS_PREFIX = "Assets/";
5434 |         private const int ASSETS_PREFIX_LENGTH = 7;
5435 |         private const string DEFAULT_SCRIPTS_FOLDER = "Assets/Scripts";
5436 |         private const string DEFAULT_SHADERS_FOLDER = "Assets/Shaders";
5437 |         private const string CS_EXTENSION = ".cs";
5438 |         private const string SHADER_EXTENSION = ".shader";
5439 |         
5440 |         private static HttpListener httpListener;
5441 |         private static Thread listenerThread;
5442 |         private static bool isRunning = false;
5443 |         
5444 |         // Request queue for serialization
5445 |         private static readonly Queue<Action> requestQueue = new Queue<Action>();
5446 |         private static bool isProcessingRequest = false;
5447 |         private static int currentPort = DEFAULT_PORT;
5448 |         
5449 |         /// <summary>
5450 |         /// Gets whether the server is currently running
5451 |         /// </summary>
5452 |         public static bool IsRunning => isRunning;
5453 |         
5454 |         /// <summary>
5455 |         /// Gets the current port the server is running on
5456 |         /// </summary>
5457 |         public static int CurrentPort => currentPort;
5458 |         
5459 |         [InitializeOnLoad]
5460 |         static class AutoShutdown
5461 |         {
5462 |             static AutoShutdown()
5463 |             {
5464 |                 EditorApplication.playModeStateChanged += OnPlayModeChanged;
5465 |                 EditorApplication.quitting += Shutdown;
5466 |                 
5467 |                 // Handle script recompilation
5468 |                 UnityEditor.Compilation.CompilationPipeline.compilationStarted += OnCompilationStarted;
5469 |                 UnityEditor.Compilation.CompilationPipeline.compilationFinished += OnCompilationFinished;
5470 |                 
5471 |                 // Auto-start server on Unity startup
5472 |                 EditorApplication.delayCall += () => {
5473 |                     if (!isRunning)
5474 |                     {
5475 |                         var savedPort = EditorPrefs.GetInt(PREFS_PORT_KEY, DEFAULT_PORT);
5476 |                         Debug.Log($"{SERVER_LOG_PREFIX} Auto-starting server on port {savedPort}");
5477 |                         Start(savedPort);
5478 |                     }
5479 |                 };
5480 |             }
5481 |             
5482 |             static void OnCompilationStarted(object obj)
5483 |             {
5484 |                 Debug.Log($"{SERVER_LOG_PREFIX} Compilation started - stopping server");
5485 |                 if (isRunning)
5486 |                 {
5487 |                     Shutdown();
5488 |                 }
5489 |             }
5490 |             
5491 |             static void OnCompilationFinished(object obj)
5492 |             {
5493 |                 Debug.Log($"{SERVER_LOG_PREFIX} Compilation finished - auto-restarting server");
5494 |                 // Always auto-restart after compilation
5495 |                 var savedPort = EditorPrefs.GetInt(PREFS_PORT_KEY, DEFAULT_PORT);
5496 |                 EditorApplication.delayCall += () => Start(savedPort);
5497 |             }
5498 |         }
5499 |         
5500 |         /// <summary>
5501 |         /// Start the HTTP server on the specified port
5502 |         /// </summary>
5503 |         /// <param name="port">Port to listen on</param>
5504 |         public static void Start(int port = DEFAULT_PORT)
5505 |         {
5506 |             if (isRunning) 
5507 |             {
5508 |                 Debug.LogWarning($"{SERVER_LOG_PREFIX} Server is already running. Stop it first.");
5509 |                 return;
5510 |             }
5511 |             
5512 |             currentPort = port;
5513 |             
5514 |             try
5515 |             {
5516 |                 httpListener = new HttpListener();
5517 |                 httpListener.Prefixes.Add($"http://localhost:{currentPort}/");
5518 |                 httpListener.Start();
5519 |                 isRunning = true;
5520 |                 
5521 |                 listenerThread = new Thread(ListenLoop) 
5522 |                 { 
5523 |                     IsBackground = true,
5524 |                     Name = "UnityMCPHttpListener"
5525 |                 };
5526 |                 listenerThread.Start();
5527 |                 
5528 |                 Debug.Log($"{SERVER_LOG_PREFIX} HTTP Server started on port {currentPort}");
5529 |             }
5530 |             catch (Exception e)
5531 |             {
5532 |                 isRunning = false;
5533 |                 Debug.LogError($"{SERVER_LOG_PREFIX} Failed to start HTTP server: {e.Message}");
5534 |                 throw;
5535 |             }
5536 |         }
5537 |         
5538 |         /// <summary>
5539 |         /// Stop the HTTP server
5540 |         /// </summary>
5541 |         public static void Shutdown()
5542 |         {
5543 |             if (!isRunning)
5544 |             {
5545 |                 Debug.LogWarning($"{SERVER_LOG_PREFIX} Server is not running.");
5546 |                 return;
5547 |             }
5548 |             
5549 |             isRunning = false;
5550 |             
5551 |             try
5552 |             {
5553 |                 httpListener?.Stop();
5554 |                 httpListener?.Close();
5555 |                 listenerThread?.Join(THREAD_JOIN_TIMEOUT_MS);
5556 |                 Debug.Log($"{SERVER_LOG_PREFIX} HTTP Server stopped");
5557 |             }
5558 |             catch (Exception e)
5559 |             {
5560 |                 Debug.LogError($"{SERVER_LOG_PREFIX} Error during shutdown: {e.Message}");
5561 |             }
5562 |             finally
5563 |             {
5564 |                 httpListener = null;
5565 |                 listenerThread = null;
5566 |             }
5567 |         }
5568 |         
5569 |         static void OnPlayModeChanged(PlayModeStateChange state)
5570 |         {
5571 |             // Stop server when entering play mode to avoid conflicts
5572 |             if (state == PlayModeStateChange.ExitingEditMode)
5573 |             {
5574 |                 if (isRunning)
5575 |                 {
5576 |                     Debug.Log($"{SERVER_LOG_PREFIX} Stopping server due to play mode change");
5577 |                     EditorPrefs.SetInt(PREFS_PORT_BEFORE_PLAY_KEY, currentPort);
5578 |                     Shutdown();
5579 |                 }
5580 |             }
5581 |             // Restart server when returning to edit mode
5582 |             else if (state == PlayModeStateChange.EnteredEditMode)
5583 |             {
5584 |                 var savedPort = EditorPrefs.GetInt(PREFS_PORT_BEFORE_PLAY_KEY, DEFAULT_PORT);
5585 |                 Debug.Log($"{SERVER_LOG_PREFIX} Restarting server after play mode on port {savedPort}");
5586 |                 EditorApplication.delayCall += () => Start(savedPort);
5587 |             }
5588 |         }
5589 |         
5590 |         static void ListenLoop()
5591 |         {
5592 |             while (isRunning)
5593 |             {
5594 |                 try
5595 |                 {
5596 |                     var context = httpListener.GetContext();
5597 |                     ThreadPool.QueueUserWorkItem(_ => HandleRequest(context));
5598 |                 }
5599 |                 catch (Exception e)
5600 |                 {
5601 |                     if (isRunning)
5602 |                         Debug.LogError($"{SERVER_LOG_PREFIX} Listen error: {e.Message}");
5603 |                 }
5604 |             }
5605 |         }
5606 |         
5607 |         static void HandleRequest(HttpListenerContext context)
5608 |         {
5609 |             var request = context.Request;
5610 |             var response = context.Response;
5611 |             response.Headers.Add("Access-Control-Allow-Origin", "*");
5612 |             
5613 |             try
5614 |             {
5615 |                 if (request.HttpMethod != "POST")
5616 |                 {
5617 |                     SendResponse(response, 405, false, null, "Method not allowed");
5618 |                     return;
5619 |                 }
5620 |                 
5621 |                 string requestBody;
5622 |                 // Force UTF-8 encoding for request body
5623 |                 using (var reader = new StreamReader(request.InputStream, Encoding.UTF8))
5624 |                 {
5625 |                     requestBody = reader.ReadToEnd();
5626 |                 }
5627 |                 
5628 |                 var requestData = JObject.Parse(requestBody);
5629 |                 var method = requestData["method"]?.ToString();
5630 |                 
5631 |                 if (string.IsNullOrEmpty(method))
5632 |                 {
5633 |                     SendResponse(response, 400, false, null, "Method is required");
5634 |                     return;
5635 |                 }
5636 |                 
5637 |                 Debug.Log($"{SERVER_LOG_PREFIX} Processing request: {method}");
5638 |                 
5639 |                 // Check if this request requires main thread
5640 |                 bool requiresMainThread = RequiresMainThread(method);
5641 |                 
5642 |                 if (!requiresMainThread)
5643 |                 {
5644 |                     // Process directly on worker thread
5645 |                     try
5646 |                     {
5647 |                         var result = ProcessRequestOnWorkerThread(method, requestData);
5648 |                         SendResponse(response, 200, true, result, null);
5649 |                     }
5650 |                     catch (Exception e)
5651 |                     {
5652 |                         var statusCode = e is ArgumentException ? 400 : 500;
5653 |                         SendResponse(response, statusCode, false, null, e.Message);
5654 |                     }
5655 |                 }
5656 |                 else
5657 |                 {
5658 |                     // Execute on main thread for Unity API calls
5659 |                     object result = null;
5660 |                     Exception error = null;
5661 |                     var resetEvent = new ManualResetEvent(false);
5662 |                     
5663 |                     EditorApplication.delayCall += () =>
5664 |                     {
5665 |                         try
5666 |                         {
5667 |                             Debug.Log($"{SERVER_LOG_PREFIX} Processing on main thread: {method}");
5668 |                             result = ProcessRequest(method, requestData);
5669 |                             Debug.Log($"{SERVER_LOG_PREFIX} Completed processing: {method}");
5670 |                         }
5671 |                         catch (Exception e)
5672 |                         {
5673 |                             error = e;
5674 |                             Debug.LogError($"{SERVER_LOG_PREFIX} Error processing {method}: {e.Message}");
5675 |                         }
5676 |                         finally
5677 |                         {
5678 |                             resetEvent.Set();
5679 |                         }
5680 |                     };
5681 |                     
5682 |                     if (!resetEvent.WaitOne(REQUEST_TIMEOUT_MS))
5683 |                     {
5684 |                         SendResponse(response, 504, false, null, "Request timeout - Unity may be busy or unfocused");
5685 |                         return;
5686 |                     }
5687 |                     
5688 |                     if (error != null)
5689 |                     {
5690 |                         var statusCode = error is ArgumentException ? 400 : 500;
5691 |                         SendResponse(response, statusCode, false, null, error.Message);
5692 |                         return;
5693 |                     }
5694 |                     
5695 |                     SendResponse(response, 200, true, result, null);
5696 |                 }
5697 |             }
5698 |             catch (Exception e)
5699 |             {
5700 |                 SendResponse(response, 400, false, null, $"Bad request: {e.Message}");
5701 |             }
5702 |         }
5703 |         
5704 |         static bool RequiresMainThread(string method)
5705 |         {
5706 |             // These methods can run on worker thread
5707 |             switch (method)
5708 |             {
5709 |                 case "ping":
5710 |                 case "script/read":
5711 |                 case "shader/read":
5712 |                     return false;
5713 |                     
5714 |                 // project/info now requires Unity API for render pipeline detection
5715 |                 // Creating, deleting files require Unity API (AssetDatabase)
5716 |                 default:
5717 |                     return true;
5718 |             }
5719 |         }
5720 |         
5721 |         static object ProcessRequestOnWorkerThread(string method, JObject request)
5722 |         {
5723 |             switch (method)
5724 |             {
5725 |                 case "ping":
5726 |                     return new { status = "ok", time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") };
5727 |                     
5728 |                 case "project/info":
5729 |                     // project/info requires Unity API for render pipeline detection
5730 |                     throw new NotImplementedException("project/info requires main thread for render pipeline detection");
5731 |                     
5732 |                 case "script/read":
5733 |                     return ReadScriptOnWorkerThread(request);
5734 |                     
5735 |                 case "shader/read":
5736 |                     return ReadShaderOnWorkerThread(request);
5737 |                     
5738 |                 // Folder operations (can run on worker thread)
5739 |                 case "folder/create":
5740 |                     return CreateFolderOnWorkerThread(request);
5741 |                 case "folder/rename":
5742 |                     return RenameFolderOnWorkerThread(request);
5743 |                 case "folder/move":
5744 |                     return MoveFolderOnWorkerThread(request);
5745 |                 case "folder/delete":
5746 |                     return DeleteFolderOnWorkerThread(request);
5747 |                 case "folder/list":
5748 |                     return ListFolderOnWorkerThread(request);
5749 |                     
5750 |                 default:
5751 |                     throw new NotImplementedException($"Method not implemented for worker thread: {method}");
5752 |             }
5753 |         }
5754 |         
5755 |         static object ReadScriptOnWorkerThread(JObject request)
5756 |         {
5757 |             var path = request["path"]?.ToString();
5758 |             if (string.IsNullOrEmpty(path))
5759 |                 throw new ArgumentException("path is required");
5760 |             
5761 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
5762 |             if (!File.Exists(fullPath))
5763 |                 throw new FileNotFoundException($"File not found: {path}");
5764 |             
5765 |             return new
5766 |             {
5767 |                 path = path,
5768 |                 content = File.ReadAllText(fullPath, new UTF8Encoding(true)),
5769 |                 guid = "" // GUID requires AssetDatabase, skip in worker thread
5770 |             };
5771 |         }
5772 |         
5773 |         static object ReadShaderOnWorkerThread(JObject request)
5774 |         {
5775 |             var path = request["path"]?.ToString();
5776 |             if (string.IsNullOrEmpty(path))
5777 |                 throw new ArgumentException("path is required");
5778 |             
5779 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
5780 |             if (!File.Exists(fullPath))
5781 |                 throw new FileNotFoundException($"File not found: {path}");
5782 |             
5783 |             return new
5784 |             {
5785 |                 path = path,
5786 |                 content = File.ReadAllText(fullPath, new UTF8Encoding(true)),
5787 |                 guid = "" // GUID requires AssetDatabase, skip in worker thread
5788 |             };
5789 |         }
5790 |         
5791 |         static object ProcessRequest(string method, JObject request)
5792 |         {
5793 |             switch (method)
5794 |             {
5795 |                 case "ping":
5796 |                     return new { status = "ok", time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") };
5797 |                 
5798 |                 // Script operations
5799 |                 case "script/create":
5800 |                     return CreateScript(request);
5801 |                 case "script/read":
5802 |                     return ReadScript(request);
5803 |                 case "script/delete":
5804 |                     return DeleteScript(request);
5805 |                 case "script/applyDiff":
5806 |                     return ApplyDiff(request);
5807 |                 
5808 |                 // Shader operations
5809 |                 case "shader/create":
5810 |                     return CreateShader(request);
5811 |                 case "shader/read":
5812 |                     return ReadShader(request);
5813 |                 case "shader/delete":
5814 |                     return DeleteShader(request);
5815 |                 
5816 |                 // Project operations
5817 |                 case "project/info":
5818 |                     return GetProjectInfo();
5819 |                 
5820 |                 // Folder operations
5821 |                 case "folder/create":
5822 |                     return CreateFolder(request);
5823 |                 case "folder/rename":
5824 |                     return RenameFolder(request);
5825 |                 case "folder/move":
5826 |                     return MoveFolder(request);
5827 |                 case "folder/delete":
5828 |                     return DeleteFolder(request);
5829 |                 case "folder/list":
5830 |                     return ListFolder(request);
5831 |                 
5832 |                 default:
5833 |                     throw new NotImplementedException($"Method not found: {method}");
5834 |             }
5835 |         }
5836 |         
5837 |         static object CreateScript(JObject request)
5838 |         {
5839 |             var fileName = request["fileName"]?.ToString();
5840 |             if (string.IsNullOrEmpty(fileName))
5841 |                 throw new ArgumentException("fileName is required");
5842 |             
5843 |             if (!fileName.EndsWith(CS_EXTENSION))
5844 |                 fileName += CS_EXTENSION;
5845 |             
5846 |             var content = request["content"]?.ToString();
5847 |             var folder = request["folder"]?.ToString() ?? DEFAULT_SCRIPTS_FOLDER;
5848 |             
5849 |             var path = Path.Combine(folder, fileName);
5850 |             var directory = Path.GetDirectoryName(path);
5851 |             
5852 |             // Create directory if needed
5853 |             if (!AssetDatabase.IsValidFolder(directory))
5854 |             {
5855 |                 CreateFolderRecursive(directory);
5856 |             }
5857 |             
5858 |             // Use Unity-safe file creation approach
5859 |             var scriptContent = content ?? GetDefaultScriptContent(fileName);
5860 |             
5861 |             // First, ensure the asset doesn't already exist
5862 |             if (AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path) != null)
5863 |             {
5864 |                 throw new InvalidOperationException($"Asset already exists: {path}");
5865 |             }
5866 |             
5867 |             // Write file using UTF-8 with BOM (Unity standard)
5868 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
5869 |             var utf8WithBom = new UTF8Encoding(true);
5870 |             File.WriteAllText(fullPath, scriptContent, utf8WithBom);
5871 |             
5872 |             // Import the asset immediately and wait for completion
5873 |             AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);
5874 |             
5875 |             // Verify the asset was imported successfully
5876 |             var attempts = 0;
5877 |             const int maxAttempts = 10;
5878 |             while (AssetDatabase.AssetPathToGUID(path) == "" && attempts < maxAttempts)
5879 |             {
5880 |                 System.Threading.Thread.Sleep(100);
5881 |                 AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
5882 |                 attempts++;
5883 |             }
5884 |             
5885 |             if (AssetDatabase.AssetPathToGUID(path) == "")
5886 |             {
5887 |                 throw new InvalidOperationException($"Failed to import asset: {path}");
5888 |             }
5889 |             
5890 |             return new
5891 |             {
5892 |                 path = path,
5893 |                 guid = AssetDatabase.AssetPathToGUID(path)
5894 |             };
5895 |         }
5896 |         
5897 |         static object ReadScript(JObject request)
5898 |         {
5899 |             var path = request["path"]?.ToString();
5900 |             if (string.IsNullOrEmpty(path))
5901 |                 throw new ArgumentException("path is required");
5902 |             
5903 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
5904 |             if (!File.Exists(fullPath))
5905 |                 throw new FileNotFoundException($"File not found: {path}");
5906 |             
5907 |             return new
5908 |             {
5909 |                 path = path,
5910 |                 content = File.ReadAllText(fullPath, new UTF8Encoding(true)),
5911 |                 guid = AssetDatabase.AssetPathToGUID(path)
5912 |             };
5913 |         }
5914 |         
5915 |         static object DeleteScript(JObject request)
5916 |         {
5917 |             var path = request["path"]?.ToString();
5918 |             if (string.IsNullOrEmpty(path))
5919 |                 throw new ArgumentException("path is required");
5920 |             
5921 |             // Verify file exists before deletion
5922 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
5923 |             if (!File.Exists(fullPath))
5924 |                 throw new FileNotFoundException($"File not found: {path}");
5925 |             
5926 |             // Delete using AssetDatabase
5927 |             if (!AssetDatabase.DeleteAsset(path))
5928 |                 throw new InvalidOperationException($"Failed to delete: {path}");
5929 |             
5930 |             // Force immediate refresh
5931 |             AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
5932 |             
5933 |             // Wait for asset database to process deletion
5934 |             System.Threading.Thread.Sleep(ASSET_REFRESH_DELAY_MS);
5935 |             
5936 |             return new { message = "Script deleted successfully" };
5937 |         }
5938 |         
5939 |         static object ApplyDiff(JObject request)
5940 |         {
5941 |             var path = request["path"]?.ToString();
5942 |             var diff = request["diff"]?.ToString();
5943 |             var options = request["options"] as JObject;
5944 |             
5945 |             if (string.IsNullOrEmpty(path))
5946 |                 throw new ArgumentException("path is required");
5947 |             if (string.IsNullOrEmpty(diff))
5948 |                 throw new ArgumentException("diff is required");
5949 |             
5950 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
5951 |             if (!File.Exists(fullPath))
5952 |                 throw new FileNotFoundException($"File not found: {path}");
5953 |             
5954 |             var dryRun = options?["dryRun"]?.Value<bool>() ?? false;
5955 |             
5956 |             // Read current content using UTF-8 with BOM (Unity standard)
5957 |             var utf8WithBom = new UTF8Encoding(true);
5958 |             var originalContent = File.ReadAllText(fullPath, utf8WithBom);
5959 |             var lines = originalContent.Split('\\n').ToList();
5960 |             
5961 |             // Parse and apply unified diff
5962 |             var diffLines = diff.Split('\\n');
5963 |             var linesAdded = 0;
5964 |             var linesRemoved = 0;
5965 |             var currentLine = 0;
5966 |             
5967 |             for (int i = 0; i < diffLines.Length; i++)
5968 |             {
5969 |                 var line = diffLines[i];
5970 |                 if (line.StartsWith("@@"))
5971 |                 {
5972 |                     // Parse hunk header: @@ -l,s +l,s @@
5973 |                     var match = System.Text.RegularExpressions.Regex.Match(line, @"@@ -(\\d+),?\\d* \\+(\\d+),?\\d* @@");
5974 |                     if (match.Success)
5975 |                     {
5976 |                         currentLine = int.Parse(match.Groups[1].Value) - 1;
5977 |                     }
5978 |                 }
5979 |                 else if (line.StartsWith("-") && !line.StartsWith("---"))
5980 |                 {
5981 |                     // Remove line
5982 |                     if (currentLine < lines.Count)
5983 |                     {
5984 |                         lines.RemoveAt(currentLine);
5985 |                         linesRemoved++;
5986 |                     }
5987 |                 }
5988 |                 else if (line.StartsWith("+") && !line.StartsWith("+++"))
5989 |                 {
5990 |                     // Add line
5991 |                     lines.Insert(currentLine, line.Substring(1));
5992 |                     currentLine++;
5993 |                     linesAdded++;
5994 |                 }
5995 |                 else if (line.StartsWith(" "))
5996 |                 {
5997 |                     // Context line
5998 |                     currentLine++;
5999 |                 }
6000 |             }
6001 |             
6002 |             // Write result if not dry run
6003 |             if (!dryRun)
6004 |             {
6005 |                 var updatedContent = string.Join("\\n", lines);
6006 |                 // Write with UTF-8 with BOM (Unity standard)
6007 |                 File.WriteAllText(fullPath, updatedContent, utf8WithBom);
6008 |                 AssetDatabase.Refresh();
6009 |                 
6010 |                 // Wait for asset database to process
6011 |                 System.Threading.Thread.Sleep(ASSET_REFRESH_DELAY_MS);
6012 |             }
6013 |             
6014 |             return new
6015 |             {
6016 |                 path = path,
6017 |                 linesAdded = linesAdded,
6018 |                 linesRemoved = linesRemoved,
6019 |                 dryRun = dryRun,
6020 |                 guid = AssetDatabase.AssetPathToGUID(path)
6021 |             };
6022 |         }
6023 |         
6024 |         static object CreateShader(JObject request)
6025 |         {
6026 |             var name = request["name"]?.ToString();
6027 |             if (string.IsNullOrEmpty(name))
6028 |                 throw new ArgumentException("name is required");
6029 |             
6030 |             if (!name.EndsWith(SHADER_EXTENSION))
6031 |                 name += SHADER_EXTENSION;
6032 |             
6033 |             var content = request["content"]?.ToString();
6034 |             var folder = request["folder"]?.ToString() ?? DEFAULT_SHADERS_FOLDER;
6035 |             
6036 |             var path = Path.Combine(folder, name);
6037 |             var directory = Path.GetDirectoryName(path);
6038 |             
6039 |             if (!AssetDatabase.IsValidFolder(directory))
6040 |             {
6041 |                 CreateFolderRecursive(directory);
6042 |             }
6043 |             
6044 |             // Use Unity-safe file creation approach
6045 |             var shaderContent = content ?? GetDefaultShaderContent(name);
6046 |             
6047 |             // First, ensure the asset doesn't already exist
6048 |             if (AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path) != null)
6049 |             {
6050 |                 throw new InvalidOperationException($"Asset already exists: {path}");
6051 |             }
6052 |             
6053 |             // Write file using UTF-8 with BOM (Unity standard)
6054 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
6055 |             var utf8WithBom = new UTF8Encoding(true);
6056 |             File.WriteAllText(fullPath, shaderContent, utf8WithBom);
6057 |             
6058 |             // Import the asset immediately and wait for completion
6059 |             AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);
6060 |             
6061 |             // Verify the asset was imported successfully
6062 |             var attempts = 0;
6063 |             const int maxAttempts = 10;
6064 |             while (AssetDatabase.AssetPathToGUID(path) == "" && attempts < maxAttempts)
6065 |             {
6066 |                 System.Threading.Thread.Sleep(100);
6067 |                 AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
6068 |                 attempts++;
6069 |             }
6070 |             
6071 |             if (AssetDatabase.AssetPathToGUID(path) == "")
6072 |             {
6073 |                 throw new InvalidOperationException($"Failed to import asset: {path}");
6074 |             }
6075 |             
6076 |             return new
6077 |             {
6078 |                 path = path,
6079 |                 guid = AssetDatabase.AssetPathToGUID(path)
6080 |             };
6081 |         }
6082 |         
6083 |         static object ReadShader(JObject request)
6084 |         {
6085 |             var path = request["path"]?.ToString();
6086 |             if (string.IsNullOrEmpty(path))
6087 |                 throw new ArgumentException("path is required");
6088 |             
6089 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
6090 |             if (!File.Exists(fullPath))
6091 |                 throw new FileNotFoundException($"File not found: {path}");
6092 |             
6093 |             return new
6094 |             {
6095 |                 path = path,
6096 |                 content = File.ReadAllText(fullPath, new UTF8Encoding(true)),
6097 |                 guid = AssetDatabase.AssetPathToGUID(path)
6098 |             };
6099 |         }
6100 |         
6101 |         static object DeleteShader(JObject request)
6102 |         {
6103 |             var path = request["path"]?.ToString();
6104 |             if (string.IsNullOrEmpty(path))
6105 |                 throw new ArgumentException("path is required");
6106 |             
6107 |             if (!AssetDatabase.DeleteAsset(path))
6108 |                 throw new InvalidOperationException($"Failed to delete: {path}");
6109 |             
6110 |             // Wait for asset database to process deletion
6111 |             System.Threading.Thread.Sleep(ASSET_REFRESH_DELAY_MS);
6112 |             
6113 |             return new { message = "Shader deleted successfully" };
6114 |         }
6115 |         
6116 |         static object GetProjectInfo()
6117 |         {
6118 |             // Detect render pipeline with multiple methods
6119 |             string renderPipeline = "Built-in";
6120 |             string renderPipelineVersion = "N/A";
6121 |             string detectionMethod = "Default";
6122 |             
6123 |             try
6124 |             {
6125 |                 // Method 1: Check GraphicsSettings.renderPipelineAsset
6126 |                 var renderPipelineAsset = UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset;
6127 |                 Debug.Log($"{SERVER_LOG_PREFIX} RenderPipelineAsset: {(renderPipelineAsset != null ? renderPipelineAsset.GetType().FullName : "null")}");
6128 |                 
6129 |                 if (renderPipelineAsset != null)
6130 |                 {
6131 |                     var assetType = renderPipelineAsset.GetType();
6132 |                     var typeName = assetType.Name;
6133 |                     var fullTypeName = assetType.FullName;
6134 |                     
6135 |                     Debug.Log($"{SERVER_LOG_PREFIX} Asset type: {typeName}, Full type: {fullTypeName}");
6136 |                     
6137 |                     if (fullTypeName.Contains("Universal") || typeName.Contains("Universal") || 
6138 |                         fullTypeName.Contains("URP") || typeName.Contains("URP"))
6139 |                     {
6140 |                         renderPipeline = "URP";
6141 |                         detectionMethod = "GraphicsSettings.renderPipelineAsset";
6142 |                     }
6143 |                     else if (fullTypeName.Contains("HighDefinition") || typeName.Contains("HighDefinition") || 
6144 |                              fullTypeName.Contains("HDRP") || typeName.Contains("HDRP"))
6145 |                     {
6146 |                         renderPipeline = "HDRP";
6147 |                         detectionMethod = "GraphicsSettings.renderPipelineAsset";
6148 |                     }
6149 |                     else
6150 |                     {
6151 |                         renderPipeline = $"Custom ({typeName})";
6152 |                         detectionMethod = "GraphicsSettings.renderPipelineAsset";
6153 |                     }
6154 |                 }
6155 |                 else
6156 |                 {
6157 |                     // Method 2: Check for installed packages if no render pipeline asset
6158 |                     Debug.Log($"{SERVER_LOG_PREFIX} No render pipeline asset found, checking packages...");
6159 |                     
6160 |                     try
6161 |                     {
6162 |                         var urpPackage = UnityEditor.PackageManager.PackageInfo.FindForPackageName("com.unity.render-pipelines.universal");
6163 |                         var hdrpPackage = UnityEditor.PackageManager.PackageInfo.FindForPackageName("com.unity.render-pipelines.high-definition");
6164 |                         
6165 |                         if (urpPackage != null)
6166 |                         {
6167 |                             renderPipeline = "URP (Package Available)";
6168 |                             renderPipelineVersion = urpPackage.version;
6169 |                             detectionMethod = "Package Detection";
6170 |                         }
6171 |                         else if (hdrpPackage != null)
6172 |                         {
6173 |                             renderPipeline = "HDRP (Package Available)";
6174 |                             renderPipelineVersion = hdrpPackage.version;
6175 |                             detectionMethod = "Package Detection";
6176 |                         }
6177 |                         else
6178 |                         {
6179 |                             renderPipeline = "Built-in";
6180 |                             detectionMethod = "No SRP packages found";
6181 |                         }
6182 |                     }
6183 |                     catch (System.Exception ex)
6184 |                     {
6185 |                         Debug.LogWarning($"{SERVER_LOG_PREFIX} Package detection failed: {ex.Message}");
6186 |                         renderPipeline = "Built-in (Package detection failed)";
6187 |                         detectionMethod = "Package detection error";
6188 |                     }
6189 |                 }
6190 |                 
6191 |                 // Try to get version info if not already obtained
6192 |                 if (renderPipelineVersion == "N/A" && renderPipeline.StartsWith("URP"))
6193 |                 {
6194 |                     try
6195 |                     {
6196 |                         var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForPackageName("com.unity.render-pipelines.universal");
6197 |                         if (packageInfo != null)
6198 |                         {
6199 |                             renderPipelineVersion = packageInfo.version;
6200 |                         }
6201 |                     }
6202 |                     catch (System.Exception ex)
6203 |                     {
6204 |                         Debug.LogWarning($"{SERVER_LOG_PREFIX} URP version detection failed: {ex.Message}");
6205 |                         renderPipelineVersion = "Version unknown";
6206 |                     }
6207 |                 }
6208 |                 else if (renderPipelineVersion == "N/A" && renderPipeline.StartsWith("HDRP"))
6209 |                 {
6210 |                     try
6211 |                     {
6212 |                         var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForPackageName("com.unity.render-pipelines.high-definition");
6213 |                         if (packageInfo != null)
6214 |                         {
6215 |                             renderPipelineVersion = packageInfo.version;
6216 |                         }
6217 |                     }
6218 |                     catch (System.Exception ex)
6219 |                     {
6220 |                         Debug.LogWarning($"{SERVER_LOG_PREFIX} HDRP version detection failed: {ex.Message}");
6221 |                         renderPipelineVersion = "Version unknown";
6222 |                     }
6223 |                 }
6224 |                 
6225 |                 Debug.Log($"{SERVER_LOG_PREFIX} Detected render pipeline: {renderPipeline} (v{renderPipelineVersion}) via {detectionMethod}");
6226 |             }
6227 |             catch (System.Exception ex)
6228 |             {
6229 |                 Debug.LogError($"{SERVER_LOG_PREFIX} Render pipeline detection failed: {ex.Message}");
6230 |                 renderPipeline = "Detection Failed";
6231 |                 detectionMethod = "Exception occurred";
6232 |             }
6233 |             
6234 |             return new
6235 |             {
6236 |                 projectPath = Application.dataPath.Replace("/Assets", ""),
6237 |                 projectName = Application.productName,
6238 |                 unityVersion = Application.unityVersion,
6239 |                 platform = Application.platform.ToString(),
6240 |                 isPlaying = Application.isPlaying,
6241 |                 renderPipeline = renderPipeline,
6242 |                 renderPipelineVersion = renderPipelineVersion,
6243 |                 detectionMethod = detectionMethod
6244 |             };
6245 |         }
6246 |         
6247 |         static void CreateFolderRecursive(string path)
6248 |         {
6249 |             var folders = path.Split('/');
6250 |             var currentPath = folders[0];
6251 |             
6252 |             for (int i = 1; i < folders.Length; i++)
6253 |             {
6254 |                 var newPath = currentPath + "/" + folders[i];
6255 |                 if (!AssetDatabase.IsValidFolder(newPath))
6256 |                 {
6257 |                     AssetDatabase.CreateFolder(currentPath, folders[i]);
6258 |                 }
6259 |                 currentPath = newPath;
6260 |             }
6261 |         }
6262 |         
6263 |         static string GetDefaultScriptContent(string fileName)
6264 |         {
6265 |             var className = Path.GetFileNameWithoutExtension(fileName);
6266 |             return "using UnityEngine;\\n\\n" +
6267 |                    $"public class {className} : MonoBehaviour\\n" +
6268 |                    "{\\n" +
6269 |                    "    void Start()\\n" +
6270 |                    "    {\\n" +
6271 |                    "        \\n" +
6272 |                    "    }\\n" +
6273 |                    "    \\n" +
6274 |                    "    void Update()\\n" +
6275 |                    "    {\\n" +
6276 |                    "        \\n" +
6277 |                    "    }\\n" +
6278 |                    "}";
6279 |         }
6280 |         
6281 |         static string GetDefaultShaderContent(string fileName)
6282 |         {
6283 |             var shaderName = Path.GetFileNameWithoutExtension(fileName);
6284 |             return $"Shader \\"Custom/{shaderName}\\"\\n" +
6285 |                    "{\\n" +
6286 |                    "    Properties\\n" +
6287 |                    "    {\\n" +
6288 |                    "        _MainTex (\\"Texture\\", 2D) = \\"white\\" {}\\n" +
6289 |                    "    }\\n" +
6290 |                    "    SubShader\\n" +
6291 |                    "    {\\n" +
6292 |                    "        Tags { \\"RenderType\\"=\\"Opaque\\" }\\n" +
6293 |                    "        LOD 200\\n" +
6294 |                    "\\n" +
6295 |                    "        CGPROGRAM\\n" +
6296 |                    "        #pragma surface surf Standard fullforwardshadows\\n" +
6297 |                    "\\n" +
6298 |                    "        sampler2D _MainTex;\\n" +
6299 |                    "\\n" +
6300 |                    "        struct Input\\n" +
6301 |                    "        {\\n" +
6302 |                    "            float2 uv_MainTex;\\n" +
6303 |                    "        };\\n" +
6304 |                    "\\n" +
6305 |                    "        void surf (Input IN, inout SurfaceOutputStandard o)\\n" +
6306 |                    "        {\\n" +
6307 |                    "            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);\\n" +
6308 |                    "            o.Albedo = c.rgb;\\n" +
6309 |                    "            o.Alpha = c.a;\\n" +
6310 |                    "        }\\n" +
6311 |                    "        ENDCG\\n" +
6312 |                    "    }\\n" +
6313 |                    "    FallBack \\"Diffuse\\"\\n" +
6314 |                    "}";
6315 |         }
6316 |         
6317 |         // Folder operations
6318 |         static object CreateFolder(JObject request)
6319 |         {
6320 |             var path = request["path"]?.ToString();
6321 |             if (string.IsNullOrEmpty(path))
6322 |                 throw new ArgumentException("path is required");
6323 |             
6324 |             if (!path.StartsWith(ASSETS_PREFIX))
6325 |                 path = Path.Combine(DEFAULT_SCRIPTS_FOLDER, path);
6326 |             
6327 |             // Use Unity-safe folder creation
6328 |             if (AssetDatabase.IsValidFolder(path))
6329 |             {
6330 |                 throw new InvalidOperationException($"Folder already exists: {path}");
6331 |             }
6332 |             
6333 |             // Create directory structure properly
6334 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
6335 |             Directory.CreateDirectory(fullPath);
6336 |             
6337 |             // Import the folder immediately
6338 |             AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
6339 |             
6340 |             // Verify the folder was imported successfully
6341 |             var attempts = 0;
6342 |             const int maxAttempts = 10;
6343 |             while (!AssetDatabase.IsValidFolder(path) && attempts < maxAttempts)
6344 |             {
6345 |                 System.Threading.Thread.Sleep(100);
6346 |                 AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
6347 |                 attempts++;
6348 |             }
6349 |             
6350 |             if (!AssetDatabase.IsValidFolder(path))
6351 |             {
6352 |                 throw new InvalidOperationException($"Failed to import folder: {path}");
6353 |             }
6354 |             
6355 |             return new
6356 |             {
6357 |                 path = path,
6358 |                 guid = AssetDatabase.AssetPathToGUID(path)
6359 |             };
6360 |         }
6361 |         
6362 |         static object CreateFolderOnWorkerThread(JObject request)
6363 |         {
6364 |             var path = request["path"]?.ToString();
6365 |             if (string.IsNullOrEmpty(path))
6366 |                 throw new ArgumentException("path is required");
6367 |             
6368 |             if (!path.StartsWith(ASSETS_PREFIX))
6369 |                 path = Path.Combine(DEFAULT_SCRIPTS_FOLDER, path);
6370 |             
6371 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
6372 |             Directory.CreateDirectory(fullPath);
6373 |             
6374 |             return new
6375 |             {
6376 |                 path = path,
6377 |                 guid = "" // GUID requires AssetDatabase
6378 |             };
6379 |         }
6380 |         
6381 |         static object RenameFolder(JObject request)
6382 |         {
6383 |             var oldPath = request["oldPath"]?.ToString();
6384 |             var newName = request["newName"]?.ToString();
6385 |             
6386 |             if (string.IsNullOrEmpty(oldPath))
6387 |                 throw new ArgumentException("oldPath is required");
6388 |             if (string.IsNullOrEmpty(newName))
6389 |                 throw new ArgumentException("newName is required");
6390 |             
6391 |             var error = AssetDatabase.RenameAsset(oldPath, newName);
6392 |             if (!string.IsNullOrEmpty(error))
6393 |                 throw new InvalidOperationException(error);
6394 |             
6395 |             // Wait for asset database to process
6396 |             System.Threading.Thread.Sleep(ASSET_REFRESH_DELAY_MS);
6397 |             
6398 |             var newPath = Path.Combine(Path.GetDirectoryName(oldPath), newName);
6399 |             return new
6400 |             {
6401 |                 oldPath = oldPath,
6402 |                 newPath = newPath,
6403 |                 guid = AssetDatabase.AssetPathToGUID(newPath)
6404 |             };
6405 |         }
6406 |         
6407 |         static object RenameFolderOnWorkerThread(JObject request)
6408 |         {
6409 |             var oldPath = request["oldPath"]?.ToString();
6410 |             var newName = request["newName"]?.ToString();
6411 |             
6412 |             if (string.IsNullOrEmpty(oldPath))
6413 |                 throw new ArgumentException("oldPath is required");
6414 |             if (string.IsNullOrEmpty(newName))
6415 |                 throw new ArgumentException("newName is required");
6416 |             
6417 |             var oldFullPath = Path.Combine(Application.dataPath, oldPath.Substring(ASSETS_PREFIX_LENGTH));
6418 |             var parentDir = Path.GetDirectoryName(oldFullPath);
6419 |             var newFullPath = Path.Combine(parentDir, newName);
6420 |             
6421 |             if (!Directory.Exists(oldFullPath))
6422 |                 throw new DirectoryNotFoundException($"Directory not found: {oldPath}");
6423 |             
6424 |             Directory.Move(oldFullPath, newFullPath);
6425 |             
6426 |             var newPath = Path.Combine(Path.GetDirectoryName(oldPath), newName);
6427 |             return new
6428 |             {
6429 |                 oldPath = oldPath,
6430 |                 newPath = newPath,
6431 |                 guid = "" // GUID requires AssetDatabase
6432 |             };
6433 |         }
6434 |         
6435 |         static object MoveFolder(JObject request)
6436 |         {
6437 |             var sourcePath = request["sourcePath"]?.ToString();
6438 |             var targetPath = request["targetPath"]?.ToString();
6439 |             
6440 |             if (string.IsNullOrEmpty(sourcePath))
6441 |                 throw new ArgumentException("sourcePath is required");
6442 |             if (string.IsNullOrEmpty(targetPath))
6443 |                 throw new ArgumentException("targetPath is required");
6444 |             
6445 |             var error = AssetDatabase.MoveAsset(sourcePath, targetPath);
6446 |             if (!string.IsNullOrEmpty(error))
6447 |                 throw new InvalidOperationException(error);
6448 |             
6449 |             // Wait for asset database to process
6450 |             System.Threading.Thread.Sleep(ASSET_REFRESH_DELAY_MS);
6451 |             
6452 |             return new
6453 |             {
6454 |                 sourcePath = sourcePath,
6455 |                 targetPath = targetPath,
6456 |                 guid = AssetDatabase.AssetPathToGUID(targetPath)
6457 |             };
6458 |         }
6459 |         
6460 |         static object MoveFolderOnWorkerThread(JObject request)
6461 |         {
6462 |             var sourcePath = request["sourcePath"]?.ToString();
6463 |             var targetPath = request["targetPath"]?.ToString();
6464 |             
6465 |             if (string.IsNullOrEmpty(sourcePath))
6466 |                 throw new ArgumentException("sourcePath is required");
6467 |             if (string.IsNullOrEmpty(targetPath))
6468 |                 throw new ArgumentException("targetPath is required");
6469 |             
6470 |             var sourceFullPath = Path.Combine(Application.dataPath, sourcePath.Substring(ASSETS_PREFIX_LENGTH));
6471 |             var targetFullPath = Path.Combine(Application.dataPath, targetPath.Substring(ASSETS_PREFIX_LENGTH));
6472 |             
6473 |             if (!Directory.Exists(sourceFullPath))
6474 |                 throw new DirectoryNotFoundException($"Directory not found: {sourcePath}");
6475 |             
6476 |             // Ensure target parent directory exists
6477 |             var targetParent = Path.GetDirectoryName(targetFullPath);
6478 |             if (!Directory.Exists(targetParent))
6479 |                 Directory.CreateDirectory(targetParent);
6480 |             
6481 |             Directory.Move(sourceFullPath, targetFullPath);
6482 |             
6483 |             return new
6484 |             {
6485 |                 sourcePath = sourcePath,
6486 |                 targetPath = targetPath,
6487 |                 guid = "" // GUID requires AssetDatabase
6488 |             };
6489 |         }
6490 |         
6491 |         static object DeleteFolder(JObject request)
6492 |         {
6493 |             var path = request["path"]?.ToString();
6494 |             var recursive = request["recursive"]?.Value<bool>() ?? true;
6495 |             
6496 |             if (string.IsNullOrEmpty(path))
6497 |                 throw new ArgumentException("path is required");
6498 |             
6499 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
6500 |             if (!Directory.Exists(fullPath))
6501 |                 throw new DirectoryNotFoundException($"Directory not found: {path}");
6502 |             
6503 |             if (!AssetDatabase.DeleteAsset(path))
6504 |                 throw new InvalidOperationException($"Failed to delete folder: {path}");
6505 |             
6506 |             // Wait for asset database to process deletion
6507 |             System.Threading.Thread.Sleep(ASSET_REFRESH_DELAY_MS);
6508 |             
6509 |             return new { path = path };
6510 |         }
6511 |         
6512 |         static object DeleteFolderOnWorkerThread(JObject request)
6513 |         {
6514 |             var path = request["path"]?.ToString();
6515 |             var recursive = request["recursive"]?.Value<bool>() ?? true;
6516 |             
6517 |             if (string.IsNullOrEmpty(path))
6518 |                 throw new ArgumentException("path is required");
6519 |             
6520 |             var fullPath = Path.Combine(Application.dataPath, path.Substring(ASSETS_PREFIX_LENGTH));
6521 |             if (!Directory.Exists(fullPath))
6522 |                 throw new DirectoryNotFoundException($"Directory not found: {path}");
6523 |             
6524 |             Directory.Delete(fullPath, recursive);
6525 |             
6526 |             // Also delete .meta file
6527 |             var metaPath = fullPath + ".meta";
6528 |             if (File.Exists(metaPath))
6529 |                 File.Delete(metaPath);
6530 |             
6531 |             return new { path = path };
6532 |         }
6533 |         
6534 |         static object ListFolder(JObject request)
6535 |         {
6536 |             var path = request["path"]?.ToString() ?? ASSETS_PREFIX;
6537 |             var recursive = request["recursive"]?.Value<bool>() ?? false;
6538 |             
6539 |             var fullPath = Path.Combine(Application.dataPath, path.StartsWith(ASSETS_PREFIX) ? path.Substring(ASSETS_PREFIX_LENGTH) : path);
6540 |             if (!Directory.Exists(fullPath))
6541 |                 throw new DirectoryNotFoundException($"Directory not found: {path}");
6542 |             
6543 |             var entries = new List<object>();
6544 |             
6545 |             // Get directories
6546 |             var dirs = Directory.GetDirectories(fullPath, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
6547 |             foreach (var dir in dirs)
6548 |             {
6549 |                 var relativePath = ASSETS_PREFIX + GetRelativePath(Application.dataPath, dir);
6550 |                 entries.Add(new
6551 |                 {
6552 |                     path = relativePath,
6553 |                     name = Path.GetFileName(dir),
6554 |                     type = "folder",
6555 |                     guid = AssetDatabase.AssetPathToGUID(relativePath)
6556 |                 });
6557 |             }
6558 |             
6559 |             // Get files
6560 |             var files = Directory.GetFiles(fullPath, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
6561 |                                  .Where(f => !f.EndsWith(".meta"));
6562 |             foreach (var file in files)
6563 |             {
6564 |                 var relativePath = ASSETS_PREFIX + GetRelativePath(Application.dataPath, file);
6565 |                 entries.Add(new
6566 |                 {
6567 |                     path = relativePath,
6568 |                     name = Path.GetFileName(file),
6569 |                     type = "file",
6570 |                     extension = Path.GetExtension(file),
6571 |                     guid = AssetDatabase.AssetPathToGUID(relativePath)
6572 |                 });
6573 |             }
6574 |             
6575 |             return new
6576 |             {
6577 |                 path = path,
6578 |                 entries = entries
6579 |             };
6580 |         }
6581 |         
6582 |         static object ListFolderOnWorkerThread(JObject request)
6583 |         {
6584 |             var path = request["path"]?.ToString() ?? ASSETS_PREFIX;
6585 |             var recursive = request["recursive"]?.Value<bool>() ?? false;
6586 |             
6587 |             var fullPath = Path.Combine(Application.dataPath, path.StartsWith(ASSETS_PREFIX) ? path.Substring(ASSETS_PREFIX_LENGTH) : path);
6588 |             if (!Directory.Exists(fullPath))
6589 |                 throw new DirectoryNotFoundException($"Directory not found: {path}");
6590 |             
6591 |             var entries = new List<object>();
6592 |             
6593 |             // Get directories
6594 |             var dirs = Directory.GetDirectories(fullPath, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
6595 |             foreach (var dir in dirs)
6596 |             {
6597 |                 var relativePath = ASSETS_PREFIX + GetRelativePath(Application.dataPath, dir);
6598 |                 entries.Add(new
6599 |                 {
6600 |                     path = relativePath,
6601 |                     name = Path.GetFileName(dir),
6602 |                     type = "folder",
6603 |                     guid = "" // GUID requires AssetDatabase
6604 |                 });
6605 |             }
6606 |             
6607 |             // Get files
6608 |             var files = Directory.GetFiles(fullPath, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
6609 |                                  .Where(f => !f.EndsWith(".meta"));
6610 |             foreach (var file in files)
6611 |             {
6612 |                 var relativePath = ASSETS_PREFIX + GetRelativePath(Application.dataPath, file);
6613 |                 entries.Add(new
6614 |                 {
6615 |                     path = relativePath,
6616 |                     name = Path.GetFileName(file),
6617 |                     type = "file",
6618 |                     extension = Path.GetExtension(file),
6619 |                     guid = "" // GUID requires AssetDatabase
6620 |                 });
6621 |             }
6622 |             
6623 |             return new
6624 |             {
6625 |                 path = path,
6626 |                 entries = entries
6627 |             };
6628 |         }
6629 |         
6630 |         static string GetRelativePath(string basePath, string fullPath)
6631 |         {
6632 |             if (!fullPath.StartsWith(basePath))
6633 |                 return fullPath;
6634 |             
6635 |             var relativePath = fullPath.Substring(basePath.Length);
6636 |             if (relativePath.StartsWith(Path.DirectorySeparatorChar.ToString()))
6637 |                 relativePath = relativePath.Substring(1);
6638 |             
6639 |             return relativePath.Replace(Path.DirectorySeparatorChar, '/');
6640 |         }
6641 |         
6642 |         static void SendResponse(HttpListenerResponse response, int statusCode, bool success, object result, string error)
6643 |         {
6644 |             response.StatusCode = statusCode;
6645 |             response.ContentType = "application/json; charset=utf-8";
6646 |             response.ContentEncoding = Encoding.UTF8;
6647 |             
6648 |             var responseData = new Dictionary<string, object>
6649 |             {
6650 |                 ["success"] = success
6651 |             };
6652 |             
6653 |             if (result != null)
6654 |                 responseData["result"] = result;
6655 |             
6656 |             if (!string.IsNullOrEmpty(error))
6657 |                 responseData["error"] = error;
6658 |             
6659 |             var json = JsonConvert.SerializeObject(responseData);
6660 |             var buffer = Encoding.UTF8.GetBytes(json);
6661 |             
6662 |             response.ContentLength64 = buffer.Length;
6663 |             response.OutputStream.Write(buffer, 0, buffer.Length);
6664 |             response.Close();
6665 |         }
6666 |     }
6667 | }`
6668 |     });
6669 |     this.scripts.set("UnityMCPServerWindow.cs", {
6670 |       fileName: "UnityMCPServerWindow.cs",
6671 |       version: "1.0.0",
6672 |       content: `using System;
6673 | using UnityEngine;
6674 | using UnityEditor;
6675 | 
6676 | namespace UnityMCP
6677 | {
6678 |     /// <summary>
6679 |     /// Unity MCP Server control window
6680 |     /// </summary>
6681 |     public class UnityMCPServerWindow : EditorWindow
6682 |     {
6683 |         // Version information (should match UnityHttpServer)
6684 |         private const string SCRIPT_VERSION = "1.1.0";
6685 |         
6686 |         private int serverPort = 23457;
6687 |         private bool isServerRunning = false;
6688 |         private string serverStatus = "Stopped";
6689 |         private string lastError = "";
6690 |         
6691 |         [MenuItem("Window/Unity MCP Server")]
6692 |         public static void ShowWindow()
6693 |         {
6694 |             GetWindow<UnityMCPServerWindow>("Unity MCP Server");
6695 |         }
6696 |         
6697 |         void OnEnable()
6698 |         {
6699 |             // Load saved settings
6700 |             serverPort = EditorPrefs.GetInt("UnityMCP.ServerPort", 23457);
6701 |             UpdateStatus();
6702 |         }
6703 |         
6704 |         void OnDisable()
6705 |         {
6706 |             // Save settings
6707 |             EditorPrefs.SetInt("UnityMCP.ServerPort", serverPort);
6708 |         }
6709 |         
6710 |         void OnGUI()
6711 |         {
6712 |             GUILayout.Label("Unity MCP Server Control", EditorStyles.boldLabel);
6713 |             GUILayout.Label($"Version: {SCRIPT_VERSION}", EditorStyles.miniLabel);
6714 |             
6715 |             EditorGUILayout.Space();
6716 |             
6717 |             // Server Status
6718 |             EditorGUILayout.BeginHorizontal();
6719 |             GUILayout.Label("Status:", GUILayout.Width(60));
6720 |             var statusColor = isServerRunning ? Color.green : Color.red;
6721 |             var originalColor = GUI.color;
6722 |             GUI.color = statusColor;
6723 |             GUILayout.Label(serverStatus, EditorStyles.boldLabel);
6724 |             GUI.color = originalColor;
6725 |             EditorGUILayout.EndHorizontal();
6726 |             
6727 |             EditorGUILayout.Space();
6728 |             
6729 |             // Port Configuration
6730 |             EditorGUILayout.BeginHorizontal();
6731 |             GUILayout.Label("Port:", GUILayout.Width(60));
6732 |             var newPort = EditorGUILayout.IntField(serverPort);
6733 |             if (newPort != serverPort && newPort > 0 && newPort <= 65535)
6734 |             {
6735 |                 serverPort = newPort;
6736 |                 EditorPrefs.SetInt("UnityMCP.ServerPort", serverPort);
6737 |             }
6738 |             EditorGUILayout.EndHorizontal();
6739 |             
6740 |             // Port validation
6741 |             if (serverPort < 1024)
6742 |             {
6743 |                 EditorGUILayout.HelpBox("Warning: Ports below 1024 may require administrator privileges.", MessageType.Warning);
6744 |             }
6745 |             
6746 |             EditorGUILayout.Space();
6747 |             
6748 |             // Control Buttons
6749 |             EditorGUILayout.BeginHorizontal();
6750 |             
6751 |             GUI.enabled = !isServerRunning;
6752 |             if (GUILayout.Button("Start Server", GUILayout.Height(30)))
6753 |             {
6754 |                 StartServer();
6755 |             }
6756 |             
6757 |             GUI.enabled = isServerRunning;
6758 |             if (GUILayout.Button("Stop Server", GUILayout.Height(30)))
6759 |             {
6760 |                 StopServer();
6761 |             }
6762 |             
6763 |             GUI.enabled = true;
6764 |             EditorGUILayout.EndHorizontal();
6765 |             
6766 |             EditorGUILayout.Space();
6767 |             
6768 |             // Connection Info
6769 |             if (isServerRunning)
6770 |             {
6771 |                 EditorGUILayout.BeginVertical(EditorStyles.helpBox);
6772 |                 GUILayout.Label("Connection Information", EditorStyles.boldLabel);
6773 |                 EditorGUILayout.SelectableLabel($"http://localhost:{serverPort}/");
6774 |                 EditorGUILayout.EndVertical();
6775 |             }
6776 |             
6777 |             // Error Display
6778 |             if (!string.IsNullOrEmpty(lastError))
6779 |             {
6780 |                 EditorGUILayout.Space();
6781 |                 EditorGUILayout.HelpBox(lastError, MessageType.Error);
6782 |                 if (GUILayout.Button("Clear Error"))
6783 |                 {
6784 |                     lastError = "";
6785 |                 }
6786 |             }
6787 |             
6788 |             EditorGUILayout.Space();
6789 |             
6790 |             // Instructions
6791 |             EditorGUILayout.BeginVertical(EditorStyles.helpBox);
6792 |             GUILayout.Label("Instructions", EditorStyles.boldLabel);
6793 |             GUILayout.Label("1. Configure the port (default: 23457)");
6794 |             GUILayout.Label("2. Click 'Start Server' to begin");
6795 |             GUILayout.Label("3. Use the MCP client to connect");
6796 |             GUILayout.Label("4. Click 'Stop Server' when done");
6797 |             EditorGUILayout.EndVertical();
6798 |         }
6799 |         
6800 |         void StartServer()
6801 |         {
6802 |             try
6803 |             {
6804 |                 UnityHttpServer.Start(serverPort);
6805 |                 UpdateStatus();
6806 |                 lastError = "";
6807 |                 Debug.Log($"[UnityMCP] Server started on port {serverPort}");
6808 |             }
6809 |             catch (Exception e)
6810 |             {
6811 |                 lastError = $"Failed to start server: {e.Message}";
6812 |                 Debug.LogError($"[UnityMCP] {lastError}");
6813 |             }
6814 |         }
6815 |         
6816 |         void StopServer()
6817 |         {
6818 |             try
6819 |             {
6820 |                 UnityHttpServer.Shutdown();
6821 |                 UpdateStatus();
6822 |                 lastError = "";
6823 |                 Debug.Log("[UnityMCP] Server stopped");
6824 |             }
6825 |             catch (Exception e)
6826 |             {
6827 |                 lastError = $"Failed to stop server: {e.Message}";
6828 |                 Debug.LogError($"[UnityMCP] {lastError}");
6829 |             }
6830 |         }
6831 |         
6832 |         void UpdateStatus()
6833 |         {
6834 |             isServerRunning = UnityHttpServer.IsRunning;
6835 |             serverStatus = isServerRunning ? $"Running on port {UnityHttpServer.CurrentPort}" : "Stopped";
6836 |             Repaint();
6837 |         }
6838 |         
6839 |         void Update()
6840 |         {
6841 |             // Update status periodically
6842 |             UpdateStatus();
6843 |         }
6844 |     }
6845 | }`
6846 |     });
6847 |   }
6848 |   /**
6849 |    * Get script by filename
6850 |    */
6851 |   async getScript(fileName) {
6852 |     return this.scripts.get(fileName) || null;
6853 |   }
6854 |   /**
6855 |    * Get script synchronously
6856 |    */
6857 |   getScriptSync(fileName) {
6858 |     return this.scripts.get(fileName) || null;
6859 |   }
6860 |   /**
6861 |    * Write script to file with proper UTF-8 BOM for Unity compatibility
6862 |    */
6863 |   async writeScriptToFile(fileName, targetPath) {
6864 |     const script = await this.getScript(fileName);
6865 |     if (!script) {
6866 |       throw new Error(`Script not found: ${fileName}`);
6867 |     }
6868 |     await fs.mkdir(path.dirname(targetPath), { recursive: true });
6869 |     const utf8BOM = Buffer.from([239, 187, 191]);
6870 |     const contentBuffer = Buffer.from(script.content, "utf8");
6871 |     const finalBuffer = Buffer.concat([utf8BOM, contentBuffer]);
6872 |     await fs.writeFile(targetPath, finalBuffer);
6873 |   }
6874 |   /**
6875 |    * Get all available script names
6876 |    */
6877 |   getAvailableScripts() {
6878 |     return Array.from(this.scripts.keys());
6879 |   }
6880 |   /**
6881 |    * Get script version
6882 |    */
6883 |   getScriptVersion(fileName) {
6884 |     const script = this.scripts.get(fileName);
6885 |     return script?.version || null;
6886 |   }
6887 | };
6888 | 
6889 | // build/services/unity-bridge-deploy-service.js
6890 | var UnityBridgeDeployService = class {
6891 |   constructor() {
6892 |     this.logger = {
6893 |       info: (msg) => console.error(`[Unity MCP Deploy] ${msg}`),
6894 |       debug: (msg) => console.error(`[Unity MCP Deploy] DEBUG: ${msg}`),
6895 |       error: (msg) => console.error(`[Unity MCP Deploy] ERROR: ${msg}`)
6896 |     };
6897 |     this.scriptsProvider = new EmbeddedScriptsProvider();
6898 |     this.SCRIPTS = [
6899 |       {
6900 |         fileName: "UnityHttpServer.cs",
6901 |         targetPath: "Assets/Editor/MCP/UnityHttpServer.cs",
6902 |         version: "1.1.0"
6903 |       },
6904 |       {
6905 |         fileName: "UnityMCPServerWindow.cs",
6906 |         targetPath: "Assets/Editor/MCP/UnityMCPServerWindow.cs",
6907 |         version: "1.1.0"
6908 |       }
6909 |     ];
6910 |   }
6911 |   async deployScripts(options) {
6912 |     const { projectPath, forceUpdate = false } = options;
6913 |     const projectValidation = await this.validateUnityProject(projectPath);
6914 |     if (!projectValidation.isValid) {
6915 |       throw new Error(`Invalid Unity project: ${projectValidation.error}`);
6916 |     }
6917 |     const editorMCPPath = path2.join(projectPath, "Assets", "Editor", "MCP");
6918 |     await fs2.mkdir(editorMCPPath, { recursive: true });
6919 |     for (const script of this.SCRIPTS) {
6920 |       await this.deployScript(projectPath, script, forceUpdate);
6921 |     }
6922 |     this.logger.info("Unity MCP scripts deployed successfully");
6923 |   }
6924 |   async deployScript(projectPath, script, forceUpdate) {
6925 |     const targetPath = path2.join(projectPath, script.targetPath);
6926 |     const needsUpdate = await this.checkNeedsUpdate(targetPath, script.version, forceUpdate);
6927 |     if (needsUpdate) {
6928 |       const embeddedScript = await this.scriptsProvider.getScript(script.fileName);
6929 |       if (!embeddedScript) {
6930 |         throw new Error(`Embedded script not found: ${script.fileName}`);
6931 |       }
6932 |       this.logger.debug(`Using embedded script: ${script.fileName} (loaded from source)`);
6933 |       await this.removeExistingFiles(targetPath);
6934 |       await this.scriptsProvider.writeScriptToFile(script.fileName, targetPath);
6935 |       await this.generateMetaFile(targetPath);
6936 |       this.logger.info(`Deployed ${script.fileName} to ${script.targetPath}`);
6937 |     } else {
6938 |       this.logger.debug(`${script.fileName} is up to date`);
6939 |     }
6940 |   }
6941 |   async checkNeedsUpdate(targetPath, currentVersion, forceUpdate) {
6942 |     if (forceUpdate) {
6943 |       return true;
6944 |     }
6945 |     try {
6946 |       const content = await fs2.readFile(targetPath, "utf8");
6947 |       const versionMatch = content.match(/SCRIPT_VERSION\s*=\s*"([^"]+)"/);
6948 |       if (versionMatch) {
6949 |         const installedVersion = versionMatch[1];
6950 |         return this.compareVersions(currentVersion, installedVersion) > 0;
6951 |       }
6952 |       return true;
6953 |     } catch (error) {
6954 |       return true;
6955 |     }
6956 |   }
6957 |   compareVersions(version1, version2) {
6958 |     const v1Parts = version1.split(".").map(Number);
6959 |     const v2Parts = version2.split(".").map(Number);
6960 |     for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
6961 |       const v1Part = v1Parts[i] || 0;
6962 |       const v2Part = v2Parts[i] || 0;
6963 |       if (v1Part > v2Part)
6964 |         return 1;
6965 |       if (v1Part < v2Part)
6966 |         return -1;
6967 |     }
6968 |     return 0;
6969 |   }
6970 |   async generateMetaFile(filePath) {
6971 |     const metaPath = filePath + ".meta";
6972 |     try {
6973 |       await fs2.access(metaPath);
6974 |       return;
6975 |     } catch {
6976 |     }
6977 |     const guid = this.generateGUID();
6978 |     const metaContent = `fileFormatVersion: 2
6979 | guid: ${guid}
6980 | MonoImporter:
6981 |   externalObjects: {}
6982 |   serializedVersion: 2
6983 |   defaultReferences: []
6984 |   executionOrder: 0
6985 |   icon: {instanceID: 0}
6986 |   userData: 
6987 |   assetBundleName: 
6988 |   assetBundleVariant: 
6989 | `;
6990 |     await fs2.writeFile(metaPath, metaContent, "utf8");
6991 |   }
6992 |   async removeExistingFiles(targetPath) {
6993 |     try {
6994 |       await fs2.unlink(targetPath);
6995 |       this.logger.debug(`Removed existing file: ${targetPath}`);
6996 |     } catch (error) {
6997 |       if (error.code !== "ENOENT") {
6998 |         this.logger.debug(`Failed to remove file ${targetPath}: ${error.message}`);
6999 |       }
7000 |     }
7001 |     try {
7002 |       const metaPath = targetPath + ".meta";
7003 |       await fs2.unlink(metaPath);
7004 |       this.logger.debug(`Removed existing meta file: ${metaPath}`);
7005 |     } catch (error) {
7006 |       if (error.code !== "ENOENT") {
7007 |         this.logger.debug(`Failed to remove meta file ${targetPath}.meta: ${error.message}`);
7008 |       }
7009 |     }
7010 |   }
7011 |   generateGUID() {
7012 |     const hex = "0123456789abcdef";
7013 |     let guid = "";
7014 |     for (let i = 0; i < 32; i++) {
7015 |       guid += hex[Math.floor(Math.random() * 16)];
7016 |     }
7017 |     return guid;
7018 |   }
7019 |   async validateUnityProject(projectPath) {
7020 |     try {
7021 |       const stats = await fs2.stat(projectPath);
7022 |       if (!stats.isDirectory()) {
7023 |         return { isValid: false, error: "Path is not a directory" };
7024 |       }
7025 |       const requiredDirs = ["Assets", "ProjectSettings"];
7026 |       for (const dir of requiredDirs) {
7027 |         try {
7028 |           const dirPath = path2.join(projectPath, dir);
7029 |           const dirStats = await fs2.stat(dirPath);
7030 |           if (!dirStats.isDirectory()) {
7031 |             return { isValid: false, error: `Missing ${dir} directory` };
7032 |           }
7033 |         } catch {
7034 |           return { isValid: false, error: `Missing ${dir} directory` };
7035 |         }
7036 |       }
7037 |       return { isValid: true };
7038 |     } catch (error) {
7039 |       return { isValid: false, error: error.message };
7040 |     }
7041 |   }
7042 | };
7043 | 
7044 | // build/tools/unity-mcp-tools.js
7045 | var UnityMcpTools = class {
7046 |   constructor() {
7047 |     const port = process.env.UNITY_MCP_PORT ? parseInt(process.env.UNITY_MCP_PORT) : 23457;
7048 |     const url = `http://localhost:${port}/`;
7049 |     console.error(`[Unity MCP] Connecting to Unity at ${url}`);
7050 |     this.adapter = new UnityHttpAdapter({
7051 |       url,
7052 |       timeout: parseInt(process.env.UNITY_MCP_TIMEOUT || "120000")
7053 |     });
7054 |     this.deployService = new UnityBridgeDeployService();
7055 |     this.checkConnection();
7056 |   }
7057 |   async checkConnection() {
7058 |     try {
7059 |       const connected = await this.adapter.isConnected();
7060 |       if (connected) {
7061 |         console.error("[Unity MCP] Successfully connected to Unity HTTP server");
7062 |       } else {
7063 |         console.error("[Unity MCP] Unity HTTP server is not responding");
7064 |       }
7065 |     } catch (error) {
7066 |       console.error(`[Unity MCP] Connection check failed: ${error.message}`);
7067 |     }
7068 |   }
7069 |   /**
7070 |    * Auto-deploy Unity MCP scripts if connected
7071 |    */
7072 |   async autoDeployScripts() {
7073 |     try {
7074 |       const result = await this.adapter.getProjectInfo();
7075 |       await this.deployService.deployScripts({
7076 |         projectPath: result.projectPath,
7077 |         forceUpdate: false
7078 |       });
7079 |     } catch (error) {
7080 |       console.error(`[Unity MCP] Failed to auto-deploy scripts: ${error.message}`);
7081 |     }
7082 |   }
7083 |   /**
7084 |    * Get all available tools
7085 |    */
7086 |   getTools() {
7087 |     return [
7088 |       // Script tools
7089 |       {
7090 |         name: "script_create",
7091 |         description: "Create a new C# script in Unity project",
7092 |         inputSchema: {
7093 |           type: "object",
7094 |           properties: {
7095 |             fileName: {
7096 |               type: "string",
7097 |               description: "Name of the script file (without .cs extension)"
7098 |             },
7099 |             content: {
7100 |               type: "string",
7101 |               description: "Script content (optional, will use template if not provided)"
7102 |             },
7103 |             folder: {
7104 |               type: "string",
7105 |               description: "Target folder path (default: Assets/Scripts)"
7106 |             }
7107 |           },
7108 |           required: ["fileName"]
7109 |         }
7110 |       },
7111 |       {
7112 |         name: "script_read",
7113 |         description: "Read a C# script from Unity project",
7114 |         inputSchema: {
7115 |           type: "object",
7116 |           properties: {
7117 |             path: {
7118 |               type: "string",
7119 |               description: "Path to the script file"
7120 |             }
7121 |           },
7122 |           required: ["path"]
7123 |         }
7124 |       },
7125 |       {
7126 |         name: "script_delete",
7127 |         description: "Delete a C# script from Unity project",
7128 |         inputSchema: {
7129 |           type: "object",
7130 |           properties: {
7131 |             path: {
7132 |               type: "string",
7133 |               description: "Path to the script file"
7134 |             }
7135 |           },
7136 |           required: ["path"]
7137 |         }
7138 |       },
7139 |       {
7140 |         name: "script_apply_diff",
7141 |         description: "Apply a unified diff to a C# script",
7142 |         inputSchema: {
7143 |           type: "object",
7144 |           properties: {
7145 |             path: {
7146 |               type: "string",
7147 |               description: "Path to the script file"
7148 |             },
7149 |             diff: {
7150 |               type: "string",
7151 |               description: "Unified diff content to apply"
7152 |             },
7153 |             options: {
7154 |               type: "object",
7155 |               description: "Optional diff application settings",
7156 |               properties: {
7157 |                 dryRun: {
7158 |                   type: "boolean",
7159 |                   description: "Preview changes without applying (default: false)"
7160 |                 }
7161 |               }
7162 |             }
7163 |           },
7164 |           required: ["path", "diff"]
7165 |         }
7166 |       },
7167 |       // Shader tools
7168 |       {
7169 |         name: "shader_create",
7170 |         description: "Create a new shader in Unity project",
7171 |         inputSchema: {
7172 |           type: "object",
7173 |           properties: {
7174 |             name: {
7175 |               type: "string",
7176 |               description: "Name of the shader (without .shader extension)"
7177 |             },
7178 |             content: {
7179 |               type: "string",
7180 |               description: "Shader content (optional, will use template if not provided)"
7181 |             },
7182 |             folder: {
7183 |               type: "string",
7184 |               description: "Target folder path (default: Assets/Shaders)"
7185 |             }
7186 |           },
7187 |           required: ["name"]
7188 |         }
7189 |       },
7190 |       {
7191 |         name: "shader_read",
7192 |         description: "Read a shader from Unity project",
7193 |         inputSchema: {
7194 |           type: "object",
7195 |           properties: {
7196 |             path: {
7197 |               type: "string",
7198 |               description: "Path to the shader file"
7199 |             }
7200 |           },
7201 |           required: ["path"]
7202 |         }
7203 |       },
7204 |       {
7205 |         name: "shader_delete",
7206 |         description: "Delete a shader from Unity project",
7207 |         inputSchema: {
7208 |           type: "object",
7209 |           properties: {
7210 |             path: {
7211 |               type: "string",
7212 |               description: "Path to the shader file"
7213 |             }
7214 |           },
7215 |           required: ["path"]
7216 |         }
7217 |       },
7218 |       // Project tools
7219 |       {
7220 |         name: "project_info",
7221 |         description: "Get comprehensive Unity project information including render pipeline details, project path, Unity version, and platform info",
7222 |         inputSchema: {
7223 |           type: "object",
7224 |           properties: {}
7225 |         }
7226 |       },
7227 |       {
7228 |         name: "project_status",
7229 |         description: "Check Unity MCP server connection status (simple connectivity test only)",
7230 |         inputSchema: {
7231 |           type: "object",
7232 |           properties: {}
7233 |         }
7234 |       },
7235 |       {
7236 |         name: "setup_unity_bridge",
7237 |         description: "Install/update Unity MCP bridge scripts to a Unity project (works even if Unity server is not running)",
7238 |         inputSchema: {
7239 |           type: "object",
7240 |           properties: {
7241 |             projectPath: {
7242 |               type: "string",
7243 |               description: "Path to the Unity project"
7244 |             },
7245 |             forceUpdate: {
7246 |               type: "boolean",
7247 |               description: "Force update even if scripts are up to date",
7248 |               default: false
7249 |             }
7250 |           },
7251 |           required: ["projectPath"]
7252 |         }
7253 |       },
7254 |       // Folder tools
7255 |       {
7256 |         name: "folder_create",
7257 |         description: "Create a new folder in Unity project",
7258 |         inputSchema: {
7259 |           type: "object",
7260 |           properties: {
7261 |             path: {
7262 |               type: "string",
7263 |               description: "Path for the new folder (e.g., Assets/MyFolder)"
7264 |             }
7265 |           },
7266 |           required: ["path"]
7267 |         }
7268 |       },
7269 |       {
7270 |         name: "folder_rename",
7271 |         description: "Rename a folder in Unity project",
7272 |         inputSchema: {
7273 |           type: "object",
7274 |           properties: {
7275 |             oldPath: {
7276 |               type: "string",
7277 |               description: "Current path of the folder"
7278 |             },
7279 |             newName: {
7280 |               type: "string",
7281 |               description: "New name for the folder"
7282 |             }
7283 |           },
7284 |           required: ["oldPath", "newName"]
7285 |         }
7286 |       },
7287 |       {
7288 |         name: "folder_move",
7289 |         description: "Move a folder to a new location in Unity project",
7290 |         inputSchema: {
7291 |           type: "object",
7292 |           properties: {
7293 |             sourcePath: {
7294 |               type: "string",
7295 |               description: "Current path of the folder"
7296 |             },
7297 |             targetPath: {
7298 |               type: "string",
7299 |               description: "Target path for the folder"
7300 |             }
7301 |           },
7302 |           required: ["sourcePath", "targetPath"]
7303 |         }
7304 |       },
7305 |       {
7306 |         name: "folder_delete",
7307 |         description: "Delete a folder from Unity project",
7308 |         inputSchema: {
7309 |           type: "object",
7310 |           properties: {
7311 |             path: {
7312 |               type: "string",
7313 |               description: "Path of the folder to delete"
7314 |             },
7315 |             recursive: {
7316 |               type: "boolean",
7317 |               description: "Delete all contents recursively (default: true)"
7318 |             }
7319 |           },
7320 |           required: ["path"]
7321 |         }
7322 |       },
7323 |       {
7324 |         name: "folder_list",
7325 |         description: "List contents of a folder in Unity project",
7326 |         inputSchema: {
7327 |           type: "object",
7328 |           properties: {
7329 |             path: {
7330 |               type: "string",
7331 |               description: "Path of the folder to list (default: Assets)"
7332 |             },
7333 |             recursive: {
7334 |               type: "boolean",
7335 |               description: "List all subdirectories recursively (default: false)"
7336 |             }
7337 |           }
7338 |         }
7339 |       }
7340 |     ];
7341 |   }
7342 |   /**
7343 |    * Execute a tool
7344 |    */
7345 |   async executeTool(toolName, args) {
7346 |     try {
7347 |       switch (toolName) {
7348 |         // Script operations
7349 |         case "script_create": {
7350 |           if (!args.fileName) {
7351 |             throw new Error("fileName is required");
7352 |           }
7353 |           const result = await this.adapter.createScript(args.fileName, args.content, args.folder);
7354 |           return {
7355 |             content: [{
7356 |               type: "text",
7357 |               text: `Script created successfully:
7358 | Path: ${result.path}
7359 | GUID: ${result.guid}`
7360 |             }]
7361 |           };
7362 |         }
7363 |         case "script_read": {
7364 |           if (!args.path) {
7365 |             throw new Error("path is required");
7366 |           }
7367 |           const result = await this.adapter.readScript(args.path);
7368 |           return {
7369 |             content: [{
7370 |               type: "text",
7371 |               text: `Script content from ${result.path}:
7372 | 
7373 | ${result.content}`
7374 |             }]
7375 |           };
7376 |         }
7377 |         case "script_delete": {
7378 |           if (!args.path) {
7379 |             throw new Error("path is required");
7380 |           }
7381 |           await this.adapter.deleteScript(args.path);
7382 |           return {
7383 |             content: [{
7384 |               type: "text",
7385 |               text: `Script deleted successfully: ${args.path}`
7386 |             }]
7387 |           };
7388 |         }
7389 |         case "script_apply_diff": {
7390 |           if (!args.path || !args.diff) {
7391 |             throw new Error("path and diff are required");
7392 |           }
7393 |           const result = await this.adapter.applyDiff(args.path, args.diff, args.options);
7394 |           return {
7395 |             content: [{
7396 |               type: "text",
7397 |               text: `Diff applied successfully:
7398 | Path: ${result.path}
7399 | Lines added: ${result.linesAdded}
7400 | Lines removed: ${result.linesRemoved}`
7401 |             }]
7402 |           };
7403 |         }
7404 |         // Shader operations
7405 |         case "shader_create": {
7406 |           if (!args.name) {
7407 |             throw new Error("name is required");
7408 |           }
7409 |           const result = await this.adapter.createShader(args.name, args.content, args.folder);
7410 |           return {
7411 |             content: [{
7412 |               type: "text",
7413 |               text: `Shader created successfully:
7414 | Path: ${result.path}
7415 | GUID: ${result.guid}`
7416 |             }]
7417 |           };
7418 |         }
7419 |         case "shader_read": {
7420 |           if (!args.path) {
7421 |             throw new Error("path is required");
7422 |           }
7423 |           const result = await this.adapter.readShader(args.path);
7424 |           return {
7425 |             content: [{
7426 |               type: "text",
7427 |               text: `Shader content from ${result.path}:
7428 | 
7429 | ${result.content}`
7430 |             }]
7431 |           };
7432 |         }
7433 |         case "shader_delete": {
7434 |           if (!args.path) {
7435 |             throw new Error("path is required");
7436 |           }
7437 |           await this.adapter.deleteShader(args.path);
7438 |           return {
7439 |             content: [{
7440 |               type: "text",
7441 |               text: `Shader deleted successfully: ${args.path}`
7442 |             }]
7443 |           };
7444 |         }
7445 |         // Project operations
7446 |         case "project_info": {
7447 |           const result = await this.adapter.getProjectInfo();
7448 |           await this.autoDeployScripts();
7449 |           return {
7450 |             content: [{
7451 |               type: "text",
7452 |               text: `Unity Project Information:
7453 | Project Path: ${result.projectPath}
7454 | Project Name: ${result.projectName || "N/A"}
7455 | Unity Version: ${result.unityVersion}
7456 | Platform: ${result.platform}
7457 | Is Playing: ${result.isPlaying}
7458 | Render Pipeline: ${result.renderPipeline || "Unknown"}
7459 | Render Pipeline Version: ${result.renderPipelineVersion || "N/A"}`
7460 |             }]
7461 |           };
7462 |         }
7463 |         case "project_status": {
7464 |           const connected = await this.adapter.isConnected();
7465 |           const status = connected ? "Unity server is connected and ready" : "Unity server is not connected or not responding";
7466 |           return {
7467 |             content: [{
7468 |               type: "text",
7469 |               text: status
7470 |             }]
7471 |           };
7472 |         }
7473 |         case "setup_unity_bridge": {
7474 |           const { projectPath, forceUpdate } = args;
7475 |           if (!projectPath) {
7476 |             throw new Error("projectPath is required");
7477 |           }
7478 |           try {
7479 |             await this.deployService.deployScripts({ projectPath, forceUpdate });
7480 |             return {
7481 |               content: [{
7482 |                 type: "text",
7483 |                 text: `Unity MCP bridge scripts installed successfully to:
7484 | ${projectPath}/Assets/Editor/MCP/
7485 | 
7486 | Please restart Unity Editor or open Window > Unity MCP Server to start the server.`
7487 |               }]
7488 |             };
7489 |           } catch (error) {
7490 |             throw new Error(`Failed to install scripts: ${error.message}`);
7491 |           }
7492 |         }
7493 |         // Folder operations
7494 |         case "folder_create": {
7495 |           if (!args.path) {
7496 |             throw new Error("path is required");
7497 |           }
7498 |           const result = await this.adapter.createFolder(args.path);
7499 |           return {
7500 |             content: [{
7501 |               type: "text",
7502 |               text: `Folder created successfully:
7503 | Path: ${result.path}
7504 | GUID: ${result.guid}`
7505 |             }]
7506 |           };
7507 |         }
7508 |         case "folder_rename": {
7509 |           if (!args.oldPath || !args.newName) {
7510 |             throw new Error("oldPath and newName are required");
7511 |           }
7512 |           const result = await this.adapter.renameFolder(args.oldPath, args.newName);
7513 |           return {
7514 |             content: [{
7515 |               type: "text",
7516 |               text: `Folder renamed successfully:
7517 | Old Path: ${result.oldPath}
7518 | New Path: ${result.newPath}
7519 | GUID: ${result.guid}`
7520 |             }]
7521 |           };
7522 |         }
7523 |         case "folder_move": {
7524 |           if (!args.sourcePath || !args.targetPath) {
7525 |             throw new Error("sourcePath and targetPath are required");
7526 |           }
7527 |           const result = await this.adapter.moveFolder(args.sourcePath, args.targetPath);
7528 |           return {
7529 |             content: [{
7530 |               type: "text",
7531 |               text: `Folder moved successfully:
7532 | From: ${result.sourcePath}
7533 | To: ${result.targetPath}
7534 | GUID: ${result.guid}`
7535 |             }]
7536 |           };
7537 |         }
7538 |         case "folder_delete": {
7539 |           if (!args.path) {
7540 |             throw new Error("path is required");
7541 |           }
7542 |           await this.adapter.deleteFolder(args.path, args.recursive);
7543 |           return {
7544 |             content: [{
7545 |               type: "text",
7546 |               text: `Folder deleted successfully: ${args.path}`
7547 |             }]
7548 |           };
7549 |         }
7550 |         case "folder_list": {
7551 |           const result = await this.adapter.listFolder(args.path, args.recursive);
7552 |           const entries = result.entries.map((e) => {
7553 |             const prefix = e.type === "folder" ? "\u{1F4C1}" : "\u{1F4C4}";
7554 |             const info = e.type === "file" ? ` (${e.extension})` : "";
7555 |             return `${prefix} ${e.name}${info} - ${e.path}`;
7556 |           }).join("\n");
7557 |           return {
7558 |             content: [{
7559 |               type: "text",
7560 |               text: `Contents of ${result.path}:
7561 | 
7562 | ${entries || "(empty)"}`
7563 |             }]
7564 |           };
7565 |         }
7566 |         default:
7567 |           throw new Error(`Unknown tool: ${toolName}`);
7568 |       }
7569 |     } catch (error) {
7570 |       return {
7571 |         content: [{
7572 |           type: "text",
7573 |           text: `Error: ${error.message}`
7574 |         }]
7575 |       };
7576 |     }
7577 |   }
7578 | };
7579 | 
7580 | // build/simple-index.js
7581 | var UnityMcpServer = class {
7582 |   constructor() {
7583 |     this.tools = new UnityMcpTools();
7584 |     this.server = new Server({
7585 |       name: "unity-mcp-server",
7586 |       version: "1.0.0"
7587 |     }, {
7588 |       capabilities: {
7589 |         tools: {}
7590 |       }
7591 |     });
7592 |     this.setupHandlers();
7593 |   }
7594 |   setupHandlers() {
7595 |     this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
7596 |       tools: this.tools.getTools()
7597 |     }));
7598 |     this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
7599 |       return this.tools.executeTool(request.params.name, request.params.arguments || {});
7600 |     });
7601 |   }
7602 |   async run() {
7603 |     try {
7604 |       console.error("[Unity MCP] Starting server...");
7605 |       const transport = new StdioServerTransport();
7606 |       console.error("[Unity MCP] Connecting to transport...");
7607 |       await this.server.connect(transport);
7608 |       console.error("[Unity MCP] Server connected successfully");
7609 |       process.stdin.resume();
7610 |       process.on("SIGINT", () => {
7611 |         console.error("[Unity MCP] Received SIGINT, shutting down...");
7612 |         process.exit(0);
7613 |       });
7614 |       process.on("SIGTERM", () => {
7615 |         console.error("[Unity MCP] Received SIGTERM, shutting down...");
7616 |         process.exit(0);
7617 |       });
7618 |       console.error("[Unity MCP] Server is ready and listening");
7619 |     } catch (error) {
7620 |       console.error("[Unity MCP] Failed to start server:", error);
7621 |       throw error;
7622 |     }
7623 |   }
7624 | };
7625 | var server = new UnityMcpServer();
7626 | server.run().catch((error) => {
7627 |   console.error("[Unity MCP] Fatal error:", error);
7628 |   process.exit(1);
7629 | });
7630 | process.on("uncaughtException", (error) => {
7631 |   console.error("[Unity MCP] Uncaught exception:", error);
7632 |   process.exit(1);
7633 | });
7634 | process.on("unhandledRejection", (reason, promise) => {
7635 |   console.error("[Unity MCP] Unhandled rejection at:", promise, "reason:", reason);
7636 |   process.exit(1);
7637 | });
7638 | 
```
Page 3/3FirstPrevNextLast